From 076371b026e3288a39e1ed858d315a40895a6ca2 Mon Sep 17 00:00:00 2001 From: zsolleci Date: Thu, 6 May 2021 14:20:07 -0500 Subject: [PATCH 01/47] Removed references to JIRA/TestRail; fixed typos and formatting mistakes --- .../Gem/PythonTests/CMakeLists.txt | 2 +- .../AssetEditor_CreateScriptEventFile.py | 5 -- .../scripting/AssetEditor_NewScriptEvent.py | 11 +--- .../Debugging_TargetMultipleEntities.py | 10 +--- .../Debugging_TargetMultipleGraphs.py | 11 +--- .../Gem/PythonTests/scripting/Docking_Pane.py | 19 ++---- .../scripting/EditMenu_UndoRedo.py | 20 ++----- .../Entity_AddScriptCanvasComponent.py | 9 +-- .../scripting/FileMenu_New_Open.py | 18 ++---- .../scripting/GraphClose_SavePrompt.py | 18 ++---- .../scripting/Graph_ZoomInZoomOut.py | 13 +---- .../PythonTests/scripting/ImportPathHelper.py | 7 ++- .../scripting/NodeInspector_RenameVariable.py | 14 ++--- .../scripting/NodePalette_ClearSelection.py | 14 ++--- .../scripting/NodePalette_SelectNode.py | 16 ++--- ...EntityActivatedDeactivated_PrintMessage.py | 58 +++++++++++-------- .../scripting/Opening_Closing_Pane.py | 10 +--- .../scripting/Pane_RetainOnSCRestart.py | 39 +++++-------- .../PythonTests/scripting/Resizing_Pane.py | 15 ++--- .../scripting/ScriptCanvas_ChangingAssets.py | 7 --- .../scripting/ScriptCanvas_TwoComponents.py | 6 +- .../scripting/ScriptCanvas_TwoEntities.py | 11 ++-- .../ScriptEvents_SendReceiveAcrossMultiple.py | 22 +++---- .../ScriptEvents_SendReceiveSuccessfully.py | 5 -- .../PythonTests/scripting/TestSuite_Active.py | 26 --------- .../scripting/Toggle_ScriptCanvasTools.py | 17 +----- .../scripting/UnDockedPane_CloseSCWindow.py | 11 +--- .../VariableManager_CreateDeleteVars.py | 13 +---- 28 files changed, 124 insertions(+), 303 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 31afab87ed..2423bd5b06 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -68,7 +68,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/scripting/TestSuite_Active.py - TIMEOUT 3000 + TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py index dcbbf47f0c..72144ebc0e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py @@ -7,10 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92569013 -Test Case Title: Script Event file can be created -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569013 """ @@ -118,7 +114,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(CreateScriptEventFile) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py index 1f801d4eeb..acc0880a73 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py @@ -7,12 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - - -Test case ID: T92568942 -Test Case Title: Clicking the "+" button and selecting "New Script Event" opens the -Asset Editor with a new Script Event asset -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568942 """ from PySide2 import QtWidgets @@ -36,11 +30,10 @@ GENERAL_WAIT = 0.5 # seconds class TestAssetEditor_NewScriptEvent: """ Summary: - Clicking the "+" button in Node Palette and creating New Script Event opens Asset Editor + Verifying logic flow of the "+" button on the Script Canvas pane's Node Palette is as expected Expected Behavior: - Clicking the "+" button and selecting "New Script Event" opens the Asset Editor with a - new Script Event asset + Clicking the "+" button and selecting "New Script Event" opens the Asset Editor with a new Script Event asset Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py index a26cb4f923..71e24139f4 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py @@ -7,11 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - - -Test case ID: T92568856 -Test Case Title: Multiple Entities can be targeted in the Debugger tool -URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568856 """ @@ -32,14 +27,14 @@ def Debugging_TargetMultipleEntities(): Multiple Entities can be targeted in the Debugger tool Expected Behavior: - Selected files can be checked for logging. + Multiple selected files can be checked for logging. Upon checking, checkboxes of the parent folders change to either full or partial check. Test Steps: 1) Create temp level 2) Create two entities with scriptcanvas components 3) Set values for scriptcanvas - 4) Open Script Canvas window and get sc opbject + 4) Open Script Canvas window and get sc object 5) Open Debugging(Logging) window 6) Click on Entities tab in logging window 7) Verify if the scriptcanvas exist under entities @@ -54,7 +49,6 @@ def Debugging_TargetMultipleEntities(): :return: None """ - from PySide2 import QtWidgets from PySide2.QtCore import Qt import azlmbr.legacy.general as general diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py index 4aa5c822a7..342f8f3cd4 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py @@ -7,17 +7,12 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - - -Test case ID: T92569137 -Test Case Title: Multiple Graphs can be targeted in the Debugger tool -URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569137 """ # fmt: off class Tests(): - select_multiple_targets = ("Multiple targets are selected", "Multiple targets are not selected") + select_multiple_targets = ("Multiple targets are selected", "Multiple targets are not selected") # fmt: on @@ -30,7 +25,7 @@ def Debugging_TargetMultipleGraphs(): Multiple Graphs can be targeted in the Debugger tool Expected Behavior: - Selected files can be checked for logging. + Multiple elected files can be checked for logging. Upon checking, checkboxes of the parent folders change to either full or partial check. Test Steps: @@ -50,7 +45,6 @@ def Debugging_TargetMultipleGraphs(): :return: None """ - from PySide2 import QtWidgets from PySide2.QtCore import Qt import azlmbr.legacy.general as general @@ -107,7 +101,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(Debugging_TargetMultipleGraphs) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py index 4fa1e1257f..da9dc125bc 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py @@ -7,25 +7,21 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: C1702824 -Test Case Title: Docking -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702824 """ # fmt: off class Tests(): - pane_opened = ("Pane is opened successfully", "Failed to open pane") - dock_pane = ("Pane is docked successfully", "Failed to dock Pane into one or more allowed area") + pane_opened = ("Pane is opened successfully", "Failed to open pane") + dock_pane = ("Pane is docked successfully", "Failed to dock Pane into one or more allowed area") # fmt: on def Docking_Pane(): """ Summary: - The Script Canvas window is opened to verify if Script canvas panes can be docked into - every possible area of Script Canvas main window. + The Script Canvas window is opened to verify if Script canvas panes can be docked into every + possible area of Script Canvas main window. (top, bottom, right and left sides of the window) Expected Behavior: The pane docks successfully. @@ -44,12 +40,6 @@ def Docking_Pane(): :return: None """ - - # Helper imports - import ImportPathHelper as imports - - imports.init() - from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import editor_python_test_tools.pyside_utils as pyside_utils @@ -111,7 +101,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from editor_python_test_tools.utils import Report Report.start_test(Docking_Pane) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py index a87d9e9be9..246a8894ba 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py @@ -7,14 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - - -Test case ID: T92569049 -Test Case Title: Edit > Undo undoes the last action -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569049 -Test case ID: T92569051 -Test Case Title: Edit > Redo redoes the last undone action -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569051 """ @@ -35,8 +27,8 @@ def EditMenu_UndoRedo(): redo it and verify if the variable is created again. Expected Behavior: - The last action is undone. - The last undone action is redone. + The last action is undone upon selecting Undo. + The last undone action is redone upon selecting Redo. Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -46,7 +38,7 @@ def EditMenu_UndoRedo(): 5) Create new variable 6) Verify if the variable is created initially 7) Trigger Undo action and verify if variable is removed in Variable Manager - 8) Trigger Redo action and verify if variable is readded in Variable Manager + 8) Trigger Redo action and verify if variable is re-added in Variable Manager 9) Close SC window Note: @@ -56,13 +48,12 @@ def EditMenu_UndoRedo(): :return: None """ - from PySide2 import QtWidgets, QtCore - import azlmbr.legacy.general as general - import pyside_utils + import azlmbr.legacy.general as general + # 1) Open Script Canvas window general.idle_enable(True) general.open_pane("Script Canvas") @@ -117,7 +108,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(EditMenu_UndoRedo) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py index fd8e9b1173..4e8576d892 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py @@ -7,10 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92562978 -Test Case Title: Script Canvas Component can be added to an entity -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562978 """ @@ -27,10 +23,10 @@ class Tests(): def Entity_AddScriptCanvasComponent(): """ Summary: - verify if Script Canvas component can be added to Entity without any issue + Script Canvas Component can be added to an entity Expected Behavior: - Script Canvas Component is added to the entity successfully without issue. + Script Canvas Component is added to the entity successfully without issue Test Steps: 1) Create temp level @@ -47,7 +43,6 @@ def Entity_AddScriptCanvasComponent(): :return: None """ - from utils import TestHelper as helper from utils import Tracer from editor_entity_utils import EditorEntity diff --git a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py index f72ac8ea01..094598e51d 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py @@ -7,24 +7,15 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - - -Test case ID: T92569037 -Test Case Title: File > New Script creates a new script -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569037 -Test case ID: T92569039 -Test Case Title: File > Open opens the Open... dialog -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569039 """ - -import os -import sys from PySide2 import QtWidgets -import azlmbr.legacy.general as general import editor_python_test_tools.pyside_utils as pyside_utils from editor_python_test_tools.utils import Report +import azlmbr.legacy.general as general + + # fmt: off class Tests(): new_action = "File->New action working as expected" @@ -38,7 +29,8 @@ GENERAL_WAIT = 0.5 # seconds class TestFileMenuNewOpen: """ Summary: - When clicked on File->New, new script opens and File->Open should open the FileBrowser + When clicked on File->New, new script opens + File->Open should open the FileBrowser Expected Behavior: New and Open actions should work as expected. diff --git a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py index ce610b159b..b2a4b22056 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py @@ -7,26 +7,17 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - - -Test case ID: T92563070 -Test Case Title: Graphs can be closed by clicking X on the Graph name tab -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563070 -Test case ID: T92563068 -Test Case Title: Save Prompt: User is prompted to save a graph on close after -creating a new graph -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563068 """ -import os -import sys from PySide2 import QtWidgets -import azlmbr.legacy.general as general import editor_python_test_tools.pyside_utils as pyside_utils from editor_python_test_tools.utils import TestHelper as helper from editor_python_test_tools.utils import Report +import azlmbr.legacy.general as general + + # fmt: off class Tests(): new_graph = "New graph created" @@ -45,7 +36,8 @@ class TestGraphCloseSavePrompt: Save Prompt is opened before closing. Expected Behavior: - New and Open actions should work as expected. + The Graph is closed. + Upon closing the graph, User is prompted whether or not to save changes. Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py index a93b6e61d1..754a0ae686 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py @@ -7,14 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - - -Test case ID: T92569079 -Test Case Title: View > Zoom In zooms the graph in -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569079 -Test case ID: T92569081 -Test Case Title: View > Zoom In zooms the graph out -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569081 """ @@ -93,7 +85,7 @@ def Graph_ZoomInZoomOut(): zin = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_ZoomIn", "type": QtWidgets.QAction}) zin.trigger() result = helper.wait_for_condition( - lambda: curr_m11 < graphics_view.transform().m11() and curr_m22 < graphics_view.transform().m22(), GENERAL_WAIT, + lambda: curr_m11 < graphics_view.transform().m11() and curr_m22 < graphics_view.transform().m22(), GENERAL_WAIT ) Report.result(Tests.zoom_in, result) @@ -102,7 +94,7 @@ def Graph_ZoomInZoomOut(): zout = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_ZoomOut", "type": QtWidgets.QAction}) zout.trigger() result = helper.wait_for_condition( - lambda: curr_m11 > graphics_view.transform().m11() and curr_m22 > graphics_view.transform().m22(), GENERAL_WAIT, + lambda: curr_m11 > graphics_view.transform().m11() and curr_m22 > graphics_view.transform().m22(), GENERAL_WAIT ) Report.result(Tests.zoom_out, result) @@ -114,7 +106,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(Graph_ZoomInZoomOut) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py index a45024cebf..ef794433f0 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py @@ -9,9 +9,10 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ + def init(): import os import sys - sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') - sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../EditorPythonTestTools/editor_python_test_tools') - \ No newline at end of file + + sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../automatedtesting_shared") + sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../EditorPythonTestTools/editor_python_test_tools") diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py index 33d3f4137a..7351e45212 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py @@ -7,10 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92568982 -Test Case Title: Renaming variables in the Node Inspector -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568982 """ @@ -51,16 +47,16 @@ def NodeInspector_RenameVariable(): :return: None """ - - TEST_NAME = "test name" - from PySide2 import QtWidgets, QtCore, QtTest from PySide2.QtCore import Qt - import azlmbr.legacy.general as general import pyside_utils from utils import TestHelper as helper + import azlmbr.legacy.general as general + + TEST_NAME = "test name" + def open_tool(sc, dock_widget_name, pane_name): if sc.findChild(QtWidgets.QDockWidget, dock_widget_name) is None: action = pyside_utils.find_child_by_pattern(sc, {"text": pane_name, "type": QtWidgets.QAction}) @@ -121,12 +117,10 @@ def NodeInspector_RenameVariable(): general.close_pane("Script Canvas") - if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(NodeInspector_RenameVariable) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py index de30e46767..87a08346d0 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py @@ -7,10 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92562993 -Test Case Title: Clicking the X button on the Search Box clears the currently entered string -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562993 """ @@ -24,11 +20,11 @@ class Tests(): def NodePalette_ClearSelection(): """ Summary: - We enter some string in the Node Palette Search box, and click on the X button to verify if the - search string got cleared. + Clicking the X button on the Search Box clears the currently entered string Expected Behavior: - Clicking the X button on the Search Box clears the currently entered string + After entering a string value into the Node Palette's search box and click on + the X button, the search box should be cleared Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -45,15 +41,13 @@ def NodePalette_ClearSelection(): :return: None """ - from PySide2 import QtWidgets + import pyside_utils from utils import TestHelper as helper import azlmbr.legacy.general as general - import pyside_utils - TEST_STRING = "Test String" # 1) Open Script Canvas window (Tools > Script Canvas) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py index 2ab76071a6..dfe1064a92 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py @@ -7,18 +7,13 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - - -Test case ID: T92568940 -Test Case Title: Categories and Nodes can be selected -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568940 """ # fmt: off class Tests(): - category_selected = ("Category can be selected", "Category cannot be selected") - node_selected = ("Node can be selected", "Node cannot be selected") + category_selected = ("Category can be selected", "Category cannot be selected") + node_selected = ("Node can be selected", "Node cannot be selected") # fmt: on @@ -31,7 +26,8 @@ def NodePalette_SelectNode(): Categories and Nodes can be selected Expected Behavior: - When clicked on Node Palette, nodes and categories can be selected. + A category can be selected inside the Node Palette + A Node can be selected inside the Node Palette Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -54,11 +50,12 @@ def NodePalette_SelectNode(): NODE = "Find Path To Entity" from PySide2 import QtWidgets - import azlmbr.legacy.general as general import pyside_utils from utils import TestHelper as helper + import azlmbr.legacy.general as general + # 1) Open Script Canvas window (Tools > Script Canvas) general.idle_enable(True) general.open_pane("Script Canvas") @@ -98,7 +95,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(NodePalette_SelectNode) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py index 51b63c4268..c331157e82 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py @@ -7,30 +7,26 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92569253 // T92569254 -Test Case Title: On Entity Activated // On Entity Deactivated -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569253 // https://testrail.agscollab.com/index.php?/tests/view/92569254 """ # fmt: off class Tests(): - level_created = ("Successfully created temp level", "Failed to create temp level") - controller_exists = ("Successfully found controller entity", "Failed to find controller entity") - activated_exists = ("Successfully found activated entity", "Failed to find activated entity") - deactivated_exists = ("Successfully found deactivated entity","Failed to find deactivated entity") - start_states_correct = ("Start states set up successfully", "Start states set up incorrectly") - game_mode_entered = ("Successfully entered game mode" "Failed to enter game mode") - lines_found = ("Successfully found expected prints", "Failed to find expected prints") - game_mode_exited = ("Successfully exited game mode" "Failed to exit game mode") + level_created = ("Successfully created temp level", "Failed to create temp level") + controller_exists = ("Successfully found controller entity", "Failed to find controller entity") + activated_exists = ("Successfully found activated entity", "Failed to find activated entity") + deactivated_exists = ("Successfully found deactivated entity", "Failed to find deactivated entity") + start_states_correct = ("Start states set up successfully", "Start states set up incorrectly") + game_mode_entered = ("Successfully entered game mode" "Failed to enter game mode") + lines_found = ("Successfully found expected prints", "Failed to find expected prints") + game_mode_exited = ("Successfully exited game mode" "Failed to exit game mode") # fmt: on def OnEntityActivatedDeactivated_PrintMessage(): """ Summary: - Verify that the On Entity Activation node is working as expected + Verify that the On Entity Activated/On Entity Deactivated nodes are working as expected Expected Behavior: Upon entering game mode, the Controller entity will wait 1 second and then activate the ActivationTest @@ -55,9 +51,9 @@ def OnEntityActivatedDeactivated_PrintMessage(): """ import os - from utils import TestHelper as helper from editor_entity_utils import EditorEntity as Entity from utils import Report + from utils import TestHelper as helper from utils import Tracer import azlmbr.legacy.general as general @@ -69,33 +65,45 @@ def OnEntityActivatedDeactivated_PrintMessage(): controller_dict = { "name": "Controller", "status": "active", - "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "controller.scriptcanvas") + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "controller.scriptcanvas"), } activated_dict = { "name": "ActivationTest", "status": "inactive", - "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "activator.scriptcanvas") + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "activator.scriptcanvas"), } deactivated_dict = { "name": "DeactivationTest", "status": "active", - "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "deactivator.scriptcanvas") + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "deactivator.scriptcanvas"), } def get_asset(asset_path): - return azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False) + return azlmbr.asset.AssetCatalogRequestBus( + azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False + ) def setup_level(): - def create_editor_entity(entity_dict:dict, entity_to_activate:EditorEntity=None, entity_to_deactivate:EditorEntity=None) -> EditorEntity: + def create_editor_entity( + entity_dict: dict, entity_to_activate: EditorEntity = None, entity_to_deactivate: EditorEntity = None + ) -> EditorEntity: entity = Entity.create_editor_entity(entity_dict["name"]) entity.set_start_status(entity_dict["status"]) sc_component = entity.add_component("Script Canvas") - sc_component.set_component_property_value("Script Canvas Asset|Script Canvas Asset", get_asset(entity_dict["path"])) + sc_component.set_component_property_value( + "Script Canvas Asset|Script Canvas Asset", get_asset(entity_dict["path"]) + ) if entity_dict["name"] == "Controller": sc_component.get_property_tree() - sc_component.set_component_property_value("Properties|Variable Fields|Variables|[0]|Name,Value|Datum|Datum|EntityToActivate", entity_to_activate.id) - sc_component.set_component_property_value("Properties|Variable Fields|Variables|[1]|Name,Value|Datum|Datum|EntityToDeactivate", entity_to_deactivate.id) + sc_component.set_component_property_value( + "Properties|Variable Fields|Variables|[0]|Name,Value|Datum|Datum|EntityToActivate", + entity_to_activate.id, + ) + sc_component.set_component_property_value( + "Properties|Variable Fields|Variables|[1]|Name,Value|Datum|Datum|EntityToDeactivate", + entity_to_deactivate.id, + ) return entity activated = create_editor_entity(activated_dict) @@ -111,7 +119,7 @@ def OnEntityActivatedDeactivated_PrintMessage(): Report.critical_result(test_tuple, entity.id.IsValid()) return entity - def validate_start_state(entity:EditorEntity, expected_state:str): + def validate_start_state(entity: EditorEntity, expected_state: str): """ Validate that the starting state of the entity is correct, if it isn't then attempt to rectify and recheck. :return: bool: Whether state is set as expected @@ -177,8 +185,8 @@ def OnEntityActivatedDeactivated_PrintMessage(): if __name__ == "__main__": import ImportPathHelper as imports - imports.init() + imports.init() from utils import Report - + Report.start_test(OnEntityActivatedDeactivated_PrintMessage) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py index 666f052240..a72a302760 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py @@ -7,11 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: C1702834 // C1702823 -Test Case Title: Opening pane // Closing pane -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702834 and - https://testrail.agscollab.com/index.php?/cases/view/1702823 """ @@ -26,10 +21,10 @@ class Tests(): def Opening_Closing_Pane(): """ Summary: - The Script Canvas window is opened to verify if Script canvas panes can be opened and closed. + The Script Canvas window is opened to verify if Script Canvas panes can be opened and closed. Expected Behavior: - The pane opens and closes successfully. + The panes open and close successfully. Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -115,7 +110,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from editor_python_test_tools.utils import Report Report.start_test(Opening_Closing_Pane) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py index fa5e9e6068..746efa500c 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py @@ -7,24 +7,19 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: C1702821 // C1702832 -Test Case Title: Retain visibility, size and location upon Script Canvas restart -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702821 and - https://testrail.agscollab.com/index.php?/cases/view/1702832 """ # fmt: off class Tests(): - relaunch_sc = ("Script Canvas window is relaunched", "Failed to relaunch Script Canvas window") - test_panes_visible = ("All the test panes are opened", "Failed to open one or more test panes") - close_pane_1 = ("Test pane 1 is closed", "Failed to close test pane 1") - visiblity_retained = ("Test pane retained its visiblity on SC restart", "Failed to retain visiblity of test pane on SC restart") - resize_pane_3 = ("Test pane 3 resized successfully", "Failed to resize Test pane 3") - size_retained = ("Test pane retained its size on SC restart", "Failed to retain size of test pane on SC restart") - location_changed = ("Location of test pane 2 changed successfully", "Failed to change locatio of test pane 2") - location_retained = ("Test pane retained its location on SC restart", "Failed to retain location of test pane on SC restart") + relaunch_sc = ("Script Canvas window is relaunched", "Failed to relaunch Script Canvas window") + test_panes_visible = ("All the test panes are opened", "Failed to open one or more test panes") + close_pane_1 = ("Test pane 1 is closed", "Failed to close test pane 1") + visibility_retained = ("Test pane retained its visibility on SC restart", "Failed to retain visibility of test pane on SC restart") + resize_pane_3 = ("Test pane 3 resized successfully", "Failed to resize Test pane 3") + size_retained = ("Test pane retained its size on SC restart", "Failed to retain size of test pane on SC restart") + location_changed = ("Location of test pane 2 changed successfully", "Failed to change location of test pane 2") + location_retained = ("Test pane retained its location on SC restart", "Failed to retain location of test pane on SC restart") # fmt: on @@ -35,7 +30,7 @@ def Pane_RetainOnSCRestart(): upon ScriptCanvas restart. Expected Behavior: - The ScriptCanvas pane retain it's visiblity, size and location upon ScriptCanvas restart. + The ScriptCanvas pane retain it's visibility, size and location upon ScriptCanvas restart. Test Steps: 1) Open Script Canvas window (Tools > Script Canvas) @@ -44,7 +39,7 @@ def Pane_RetainOnSCRestart(): 4) Change dock location of test pane 2 5) Resize test pane 3 6) Relaunch Script Canvas - 7) Verify if test pane 1 retain its visiblity + 7) Verify if test pane 1 retain its visibility 8) Verify if location of test pane 2 is retained 9) Verify if size of test pane 3 is retained 10) Restore default layout and close SC window @@ -57,6 +52,10 @@ def Pane_RetainOnSCRestart(): :return: None """ + # Pyside imports + from PySide2 import QtCore, QtWidgets + from PySide2.QtCore import Qt + # Helper imports from utils import Report from utils import TestHelper as helper @@ -65,11 +64,6 @@ def Pane_RetainOnSCRestart(): # Open 3D Engine Imports import azlmbr.legacy.general as general - # Pyside imports - from PySide2 import QtCore, QtWidgets - from PySide2.QtCore import Qt - - # Constants TEST_PANE_1 = "NodePalette" # test visibility TEST_PANE_2 = "VariableManager" # test location TEST_PANE_3 = "NodeInspector" # test size @@ -130,10 +124,10 @@ def Pane_RetainOnSCRestart(): sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) Report.result(Tests.relaunch_sc, sc_visible) - # 7) Verify if test pane 1 retain its visiblity + # 7) Verify if test pane 1 retain its visibility editor_window = pyside_utils.get_editor_main_window() sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") - Report.result(Tests.visiblity_retained, not find_pane(sc, TEST_PANE_1).isVisible()) + Report.result(Tests.visibility_retained, not find_pane(sc, TEST_PANE_1).isVisible()) # 8) Verify if location of test pane 2 is retained sc_main = sc.findChild(QtWidgets.QMainWindow) @@ -158,7 +152,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(Pane_RetainOnSCRestart) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py index 180f577953..a870bea86f 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py @@ -7,10 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: C1702829 -Test Case Title: Resizing pane -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702829 """ @@ -24,7 +20,7 @@ class Tests(): def Resizing_Pane(): """ Summary: - The Script Canvas window is opened to verify if Script canvas panes can be resized and scaled + The Script Canvas window is opened to verify if Script Canvas panes can be resized and scaled Expected Behavior: The pane is resized and scaled appropriately. @@ -33,7 +29,7 @@ def Resizing_Pane(): 1) Open Script Canvas window (Tools > Script Canvas) 2) Restore default layout 3) Make sure pane is opened - 4) Resize pane + 4) Resize pane and verify change 5) Restore default layout 6) Close Script Canvas window @@ -45,6 +41,8 @@ def Resizing_Pane(): :return: None """ + from PySide2 import QtWidgets + from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import editor_python_test_tools.pyside_utils as pyside_utils @@ -52,9 +50,6 @@ def Resizing_Pane(): # Open 3D Engine imports import azlmbr.legacy.general as general - # Pyside imports - from PySide2 import QtWidgets - PANE_WIDGET = "NodePalette" SCALE_INT = 10 @@ -87,7 +82,7 @@ def Resizing_Pane(): Report.result(Tests.open_pane, pane.isVisible()) - # 4) Resize pane + # 4) Resize pane and verify change initial_size = pane.frameSize() pane.resize(initial_size.width() + SCALE_INT, initial_size.height() + SCALE_INT) new_size = pane.frameSize() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py index 38d60ad871..a1e177f5ec 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py @@ -7,11 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92562986 -Test Case Title: Changing the assigned Script Canvas Asset on an entity properly updates -level functionality -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562986 """ @@ -58,7 +53,6 @@ def ScriptCanvas_ChangingAssets(): import azlmbr.math as math import azlmbr.asset as asset import azlmbr.bus as bus - import azlmbr.paths as paths LEVEL_NAME = "tmp_level" ASSET_1 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents0.scriptcanvas") @@ -84,7 +78,6 @@ def ScriptCanvas_ChangingAssets(): Report.result(Tests.found_lines, find_expected_line(EXP_LINE)) helper.exit_game_mode(Tests.game_mode_exited) - # 1) Create temp level general.idle_enable(True) result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py index 896bee96e5..5117069b64 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py @@ -7,10 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92563190 -Test Case Title: A single Entity with two Script Canvas components works properly -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563190 """ @@ -58,6 +54,7 @@ def ScriptCanvas_TwoComponents(): import hydra_editor_utils as hydra from utils import Report from utils import Tracer + import azlmbr.legacy.general as general import azlmbr.math as math import azlmbr.asset as asset @@ -112,7 +109,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(ScriptCanvas_TwoComponents) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py index 401e6c0271..53b3951c1a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py @@ -7,16 +7,12 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92563191 -Test Case Title: Two Entities can use the same Graph asset successfully at RunTime -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563191 """ # fmt: off class Tests(): - level_created = ("New level created", "New level not created") + level_created = ("New level created successfully", "New level failed to create") game_mode_entered = ("Game Mode successfully entered", "Game mode failed to enter") game_mode_exited = ("Game Mode successfully exited", "Game mode failed to exited") found_lines = ("Expected log lines were found", "Expected log lines were not found") @@ -27,7 +23,7 @@ def ScriptCanvas_TwoEntities(): """ Summary: Two Entities can use the same Graph asset successfully at RunTime. The script canvas asset - attached to the enties will print the respective entity names. + attached to the entities will print the respective entity names. Expected Behavior: When game mode is entered, respective strings of different entities should be printed. @@ -49,9 +45,10 @@ def ScriptCanvas_TwoEntities(): import os + import hydra_editor_utils as hydra from utils import TestHelper as helper from utils import Tracer - import hydra_editor_utils as hydra + import azlmbr.legacy.general as general import azlmbr.math as math import azlmbr.asset as asset diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py index d671229cdf..f58d6007a1 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py @@ -7,10 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92567321 -Test Case Title: Script Events: Can send and receive a script event across multiple entities successfully -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567321 """ @@ -28,7 +24,8 @@ class Tests(): def ScriptEvents_SendReceiveAcrossMultiple(): """ Summary: - EntityA and EntityB will be created in a level. Attached to both will be a Script Canvas component. The Script Event created for the test will be sent from EntityA to EntityB. + EntityA and EntityB will be created in a level. Attached to both will be a Script Canvas component. + The Script Event created for the test will be sent from EntityA to EntityB. Expected Behavior: The output of the Script Event should be printed to the console @@ -50,7 +47,7 @@ def ScriptEvents_SendReceiveAcrossMultiple(): :return: None """ import os - + from editor_entity_utils import EditorEntity as Entity from utils import Report from utils import TestHelper as helper @@ -66,20 +63,19 @@ def ScriptEvents_SendReceiveAcrossMultiple(): "assetA": os.path.join("ScriptCanvas", f"{ASSET_PREFIX}A.scriptcanvas"), "assetB": os.path.join("ScriptCanvas", f"{ASSET_PREFIX}B.scriptcanvas"), } - sc_for_entities = { - "EntityA": asset_paths["assetA"], - "EntityB": asset_paths["assetB"] - } + sc_for_entities = {"EntityA": asset_paths["assetA"], "EntityB": asset_paths["assetB"]} EXPECTED_LINES = ["Incoming Message Received"] def get_asset(asset_path): - return azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False) + return azlmbr.asset.AssetCatalogRequestBus( + azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False + ) def create_editor_entity(name, sc_asset): entity = Entity.create_editor_entity(name) sc_comp = entity.add_component("Script Canvas") sc_comp.set_component_property_value("Script Canvas Asset|Script Canvas Asset", get_asset(sc_asset)) - Report.critical_result(Tests.__dict__[name.lower()+"_created"], entity.id.isValid()) + Report.critical_result(Tests.__dict__[name.lower() + "_created"], entity.id.isValid()) def locate_expected_lines(line_list: list): found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] @@ -113,8 +109,8 @@ def ScriptEvents_SendReceiveAcrossMultiple(): if __name__ == "__main__": import ImportPathHelper as imports - imports.init() + imports.init() from utils import Report Report.start_test(ScriptEvents_SendReceiveAcrossMultiple) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py index b5e26d14ae..3f343221b0 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py @@ -7,10 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92567320 -Test Case Title: Script Events: Can send and receive a script event successfully -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567320 """ @@ -104,7 +100,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(ScriptEvents_SendReceiveSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index d87f2986bf..24e8eeda11 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -29,22 +29,18 @@ TEST_DIRECTORY = os.path.dirname(__file__) @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(TestAutomationBase): - @pytest.mark.test_case_id("C1702834", "C1702823") def test_Opening_Closing_Pane(self, request, workspace, editor, launcher_platform): from . import Opening_Closing_Pane as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("C1702824") def test_Docking_Pane(self, request, workspace, editor, launcher_platform): from . import Docking_Pane as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("C1702829") def test_Resizing_Pane(self, request, workspace, editor, launcher_platform): from . import Resizing_Pane as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92563190") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_TwoComponents(self, request, workspace, editor, launcher_platform, level): def teardown(): @@ -54,7 +50,6 @@ class TestAutomation(TestAutomationBase): from . import ScriptCanvas_TwoComponents as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92562986") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_ChangingAssets(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -64,18 +59,14 @@ class TestAutomation(TestAutomationBase): from . import ScriptCanvas_ChangingAssets as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569079", "T92569081") def test_Graph_ZoomInZoomOut(self, request, workspace, editor, launcher_platform): from . import Graph_ZoomInZoomOut as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92568940") def test_NodePalette_SelectNode(self, request, workspace, editor, launcher_platform): from . import NodePalette_SelectNode as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569253") - @pytest.mark.test_case_id("T92569254") @pytest.mark.parametrize("level", ["tmp_level"]) def test_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -85,12 +76,10 @@ class TestAutomation(TestAutomationBase): from . import OnEntityActivatedDeactivated_PrintMessage as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92562993") def test_NodePalette_ClearSelection(self, request, workspace, editor, launcher_platform, project): from . import NodePalette_ClearSelection as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92563191") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_TwoEntities(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -100,7 +89,6 @@ class TestAutomation(TestAutomationBase): from . import ScriptCanvas_TwoEntities as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569013") def test_AssetEditor_CreateScriptEventFile(self, request, workspace, editor, launcher_platform, project): def teardown(): file_system.delete( @@ -113,22 +101,18 @@ class TestAutomation(TestAutomationBase): from . import AssetEditor_CreateScriptEventFile as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569165", "T92569167", "T92569168", "T92569170") def test_Toggle_ScriptCanvasTools(self, request, workspace, editor, launcher_platform): from . import Toggle_ScriptCanvasTools as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92568982") def test_NodeInspector_RenameVariable(self, request, workspace, editor, launcher_platform, project): from . import NodeInspector_RenameVariable as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569137") def test_Debugging_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): from . import Debugging_TargetMultipleGraphs as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92568856") @pytest.mark.parametrize("level", ["tmp_level"]) def test_Debugging_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -138,17 +122,14 @@ class TestAutomation(TestAutomationBase): from . import Debugging_TargetMultipleEntities as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92569049", "T92569051") def test_EditMenu_UndoRedo(self, request, workspace, editor, launcher_platform, project): from . import EditMenu_UndoRedo as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("C1702825", "C1702831") def test_UnDockedPane_CloseSCWindow(self, request, workspace, editor, launcher_platform): from . import UnDockedPane_CloseSCWindow as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92562978") @pytest.mark.parametrize("level", ["tmp_level"]) def test_Entity_AddScriptCanvasComponent(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -158,12 +139,10 @@ class TestAutomation(TestAutomationBase): from . import Entity_AddScriptCanvasComponent as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("C1702821", "C1702832") def test_Pane_RetainOnSCRestart(self, request, workspace, editor, launcher_platform): from . import Pane_RetainOnSCRestart as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92567321") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptEvents_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -173,7 +152,6 @@ class TestAutomation(TestAutomationBase): from . import ScriptEvents_SendReceiveAcrossMultiple as test_module self._run_test(request, workspace, editor, test_module) - @pytest.mark.test_case_id("T92567320") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptEvents_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -193,7 +171,6 @@ class TestScriptCanvasTests(object): The following tests use hydra_test_utils.py to launch the editor and validate the results. """ - @pytest.mark.test_case_id("T92569037", "T92569039") def test_FileMenu_New_Open(self, request, editor, launcher_platform): expected_lines = [ "File->New action working as expected: True", @@ -203,7 +180,6 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, "FileMenu_New_Open.py", expected_lines, auto_test_mode=False, timeout=60, ) - @pytest.mark.test_case_id("T92568942") def test_AssetEditor_NewScriptEvent(self, request, editor, launcher_platform): expected_lines = [ "New Script event action found: True", @@ -221,7 +197,6 @@ class TestScriptCanvasTests(object): timeout=60, ) - @pytest.mark.test_case_id("T92563068", "T92563070") def test_GraphClose_SavePrompt(self, request, editor, launcher_platform): expected_lines = [ "New graph created: True", @@ -238,7 +213,6 @@ class TestScriptCanvasTests(object): timeout=60, ) - @pytest.mark.test_case_id("T92564789", "T92568873") def test_VariableManager_CreateDeleteVars(self, request, editor, launcher_platform): var_types = ["Boolean", "Color", "EntityID", "Number", "String", "Transform", "Vector2", "Vector3", "Vector4"] expected_lines = [f"Success: {var_type} variable is created" for var_type in var_types] diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py index 4024e28277..2b935a74b3 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py @@ -7,17 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: C92569165, C92569167, C92569168, C92569170 -Test Case Title: Tools > Node Palette toggles the Node Palette - Tools > Node Inspector toggles the Node Inspector - Tools > Bookmarks toggles the Bookmarks - Tools > Variable Manager toggles the Variable Manager - -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/92569165 - https://testrail.agscollab.com/index.php?/cases/view/92569167 - https://testrail.agscollab.com/index.php?/cases/view/92569168 - https://testrail.agscollab.com/index.php?/cases/view/92569170 """ @@ -63,6 +52,8 @@ def Toggle_ScriptCanvasTools(): :return: None """ + from PySide2 import QtWidgets + from utils import Report from utils import TestHelper as helper import pyside_utils @@ -70,9 +61,6 @@ def Toggle_ScriptCanvasTools(): # Open 3D Engine imports import azlmbr.legacy.general as general - # Pyside imports - from PySide2 import QtWidgets - def click_menu_option(window, option_text): action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) action.trigger() @@ -131,7 +119,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(Toggle_ScriptCanvasTools) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py index 875f28ec95..fbdba8fb38 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py @@ -7,11 +7,6 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: C1702825 // C1702831 -Test Case Title: Undocking // Closing script canvas with the pane floating -URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702825 & - https://testrail.agscollab.com/index.php?/cases/view/1702831 """ @@ -47,6 +42,8 @@ def UnDockedPane_CloseSCWindow(): :return: None """ + from PySide2 import QtWidgets + # Helper imports from utils import Report from utils import TestHelper as helper @@ -55,9 +52,6 @@ def UnDockedPane_CloseSCWindow(): # Open 3D Engine imports import azlmbr.legacy.general as general - # Pyside imports - from PySide2 import QtWidgets - TEST_PANE = "NodePalette" # Chosen most commonly used pane def click_menu_option(window, option_text): @@ -122,7 +116,6 @@ if __name__ == "__main__": import ImportPathHelper as imports imports.init() - from utils import Report Report.start_test(UnDockedPane_CloseSCWindow) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py index 6facc324d4..8f7557c01e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py @@ -7,20 +7,13 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - -Test case ID: T92564789 -Test Case Title: Each Variable type can be created -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92564789 -Test case ID: T92568873 -Test Case Title: Each Variable type can be deleted -URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568873 """ def VariableManager_CreateDeleteVars(): """ Summary: - Each variable type can be created and deleted in variable manager. + Creating and deleting each type of variable in the Variable Manager pane Expected Behavior: Each variable type can be created and deleted in variable manager. @@ -43,15 +36,13 @@ def VariableManager_CreateDeleteVars(): """ from PySide2 import QtWidgets, QtCore, QtTest - from PySide2.QtCore import Qt from utils import TestHelper as helper + import pyside_utils import azlmbr.legacy.general as general - import pyside_utils - def generate_test_tuple(var_type, action): return (f"{var_type} variable is {action}d", f"{var_type} variable is not {action}d") From be0f69d081a5643a7c298f84eb4f256709c05092 Mon Sep 17 00:00:00 2001 From: zsolleci Date: Fri, 7 May 2021 11:47:39 -0500 Subject: [PATCH 02/47] updated files to fit name convention --- ...ugger_HappyPath_TargetMultipleEntities.py} | 4 +- ...ebugger_HappyPath_TargetMultipleGraphs.py} | 4 +- ...doRedo.py => EditMenu_Default_UndoRedo.py} | 4 +- ...ity_HappyPath_AddScriptCanvasComponent.py} | 4 +- ...Open.py => FileMenu_Default_NewAndOpen.py} | 4 +- ...pt.py => GraphClose_Default_SavePrompt.py} | 4 +- ...ut.py => Graph_HappyPath_ZoomInZoomOut.py} | 4 +- ...entButton_HappyPath_ContainsSCCategory.py} | 0 ...odeInspector_HappyPath_VariableRenames.py} | 4 +- ...=> NodePalette_HappyPath_CanSelectNode.py} | 4 +- ...> NodePalette_HappyPath_ClearSelection.py} | 4 +- ...atedDeactivated_HappyPath_PrintMessage.py} | 4 +- ...t.py => Pane_Default_RetainOnSCRestart.py} | 4 +- ...ane.py => Pane_HappyPath_DocksProperly.py} | 4 +- ...> Pane_HappyPath_OpenCloseSuccessfully.py} | 4 +- ...e.py => Pane_HappyPath_ResizesProperly.py} | 4 +- ...py => Pane_Undocked_ClosesSuccessfully.py} | 4 +- ...iptCanvasTools_Toggle_OpenCloseSuccess.py} | 4 +- ...tCanvas_ChangingAssets_ComponentStable.py} | 4 +- ...vas_TwoComponents_InteractSuccessfully.py} | 4 +- ...ptCanvas_TwoEntities_UseSimultaneously.py} | 4 +- ...iptEvent_HappyPath_CreatedWithoutError.py} | 0 ...Events_Default_SendReceiveSuccessfully.py} | 4 +- ...ts_HappyPath_SendReceiveAcrossMultiple.py} | 4 +- .../PythonTests/scripting/TestSuite_Active.py | 104 +++++++++--------- ...riableManager_Default_CreateDeleteVars.py} | 4 +- 26 files changed, 98 insertions(+), 98 deletions(-) rename AutomatedTesting/Gem/PythonTests/scripting/{Debugging_TargetMultipleEntities.py => Debugger_HappyPath_TargetMultipleEntities.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{Debugging_TargetMultipleGraphs.py => Debugger_HappyPath_TargetMultipleGraphs.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{EditMenu_UndoRedo.py => EditMenu_Default_UndoRedo.py} (98%) rename AutomatedTesting/Gem/PythonTests/scripting/{Entity_AddScriptCanvasComponent.py => Entity_HappyPath_AddScriptCanvasComponent.py} (96%) rename AutomatedTesting/Gem/PythonTests/scripting/{FileMenu_New_Open.py => FileMenu_Default_NewAndOpen.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{GraphClose_SavePrompt.py => GraphClose_Default_SavePrompt.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{Graph_ZoomInZoomOut.py => Graph_HappyPath_ZoomInZoomOut.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{AssetEditor_NewScriptEvent.py => NewScriptEventButton_HappyPath_ContainsSCCategory.py} (100%) rename AutomatedTesting/Gem/PythonTests/scripting/{NodeInspector_RenameVariable.py => NodeInspector_HappyPath_VariableRenames.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{NodePalette_SelectNode.py => NodePalette_HappyPath_CanSelectNode.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{NodePalette_ClearSelection.py => NodePalette_HappyPath_ClearSelection.py} (96%) rename AutomatedTesting/Gem/PythonTests/scripting/{OnEntityActivatedDeactivated_PrintMessage.py => OnEntityActivatedDeactivated_HappyPath_PrintMessage.py} (98%) rename AutomatedTesting/Gem/PythonTests/scripting/{Pane_RetainOnSCRestart.py => Pane_Default_RetainOnSCRestart.py} (98%) rename AutomatedTesting/Gem/PythonTests/scripting/{Docking_Pane.py => Pane_HappyPath_DocksProperly.py} (97%) mode change 100755 => 100644 rename AutomatedTesting/Gem/PythonTests/scripting/{Opening_Closing_Pane.py => Pane_HappyPath_OpenCloseSuccessfully.py} (97%) mode change 100755 => 100644 rename AutomatedTesting/Gem/PythonTests/scripting/{Resizing_Pane.py => Pane_HappyPath_ResizesProperly.py} (97%) mode change 100755 => 100644 rename AutomatedTesting/Gem/PythonTests/scripting/{UnDockedPane_CloseSCWindow.py => Pane_Undocked_ClosesSuccessfully.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{Toggle_ScriptCanvasTools.py => ScriptCanvasTools_Toggle_OpenCloseSuccess.py} (98%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptCanvas_ChangingAssets.py => ScriptCanvas_ChangingAssets_ComponentStable.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptCanvas_TwoComponents.py => ScriptCanvas_TwoComponents_InteractSuccessfully.py} (96%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptCanvas_TwoEntities.py => ScriptCanvas_TwoEntities_UseSimultaneously.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{AssetEditor_CreateScriptEventFile.py => ScriptEvent_HappyPath_CreatedWithoutError.py} (100%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptEvents_SendReceiveSuccessfully.py => ScriptEvents_Default_SendReceiveSuccessfully.py} (96%) rename AutomatedTesting/Gem/PythonTests/scripting/{ScriptEvents_SendReceiveAcrossMultiple.py => ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py} (97%) rename AutomatedTesting/Gem/PythonTests/scripting/{VariableManager_CreateDeleteVars.py => VariableManager_Default_CreateDeleteVars.py} (97%) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py rename to AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py index 71e24139f4..2c36062acf 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleEntities.py @@ -21,7 +21,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def Debugging_TargetMultipleEntities(): +def Debugger_HappyPath_TargetMultipleEntities(): """ Summary: Multiple Entities can be targeted in the Debugger tool @@ -135,4 +135,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Debugging_TargetMultipleEntities) + Report.start_test(Debugger_HappyPath_TargetMultipleEntities) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py rename to AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py index 342f8f3cd4..906c198d43 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugger_HappyPath_TargetMultipleGraphs.py @@ -19,7 +19,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def Debugging_TargetMultipleGraphs(): +def Debugger_HappyPath_TargetMultipleGraphs(): """ Summary: Multiple Graphs can be targeted in the Debugger tool @@ -103,4 +103,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Debugging_TargetMultipleGraphs) + Report.start_test(Debugger_HappyPath_TargetMultipleGraphs) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py rename to AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py index 246a8894ba..34345cf36b 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_Default_UndoRedo.py @@ -18,7 +18,7 @@ class Tests(): # fmt: on -def EditMenu_UndoRedo(): +def EditMenu_Default_UndoRedo(): """ Summary: Edit > Undo undoes the last action @@ -110,4 +110,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(EditMenu_UndoRedo) + Report.start_test(EditMenu_Default_UndoRedo) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py b/AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py similarity index 96% rename from AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py rename to AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py index 4e8576d892..22530c90c1 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Entity_HappyPath_AddScriptCanvasComponent.py @@ -20,7 +20,7 @@ class Tests(): # fmt: on -def Entity_AddScriptCanvasComponent(): +def Entity_HappyPath_AddScriptCanvasComponent(): """ Summary: Script Canvas Component can be added to an entity @@ -80,4 +80,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Entity_AddScriptCanvasComponent) + Report.start_test(Entity_HappyPath_AddScriptCanvasComponent) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py rename to AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py index 094598e51d..4771a95ab7 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_Default_NewAndOpen.py @@ -26,7 +26,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -class TestFileMenuNewOpen: +class TestFileMenuDefaultNewOpen: """ Summary: When clicked on File->New, new script opens @@ -86,5 +86,5 @@ class TestFileMenuNewOpen: general.close_pane("Script Canvas") -test = TestFileMenuNewOpen() +test = TestFileMenuDefaultNewOpen() test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py rename to AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py index b2a4b22056..9720c846c7 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_Default_SavePrompt.py @@ -29,7 +29,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -class TestGraphCloseSavePrompt: +class TestGraphClose_Default_SavePrompt: """ Summary: The graph is closed when x button is clicked. @@ -98,5 +98,5 @@ class TestGraphCloseSavePrompt: general.close_pane("Script Canvas") -test = TestGraphCloseSavePrompt() +test = TestGraphClose_Default_SavePrompt() test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py b/AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py rename to AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py index 754a0ae686..11c83bb779 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Graph_HappyPath_ZoomInZoomOut.py @@ -20,7 +20,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def Graph_ZoomInZoomOut(): +def Graph_HappyPath_ZoomInZoomOut(): """ Summary: The graph can be zoomed in and zoomed out. @@ -108,4 +108,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Graph_ZoomInZoomOut) + Report.start_test(Graph_HappyPath_ZoomInZoomOut) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py b/AutomatedTesting/Gem/PythonTests/scripting/NewScriptEventButton_HappyPath_ContainsSCCategory.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py rename to AutomatedTesting/Gem/PythonTests/scripting/NewScriptEventButton_HappyPath_ContainsSCCategory.py diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py rename to AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py index 7351e45212..c235db6256 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_HappyPath_VariableRenames.py @@ -21,7 +21,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def NodeInspector_RenameVariable(): +def NodeInspector_HappyPath_VariableRenames(): """ Summary: Renaming variables in the Node Inspector, renames the actual variable. @@ -123,4 +123,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(NodeInspector_RenameVariable) + Report.start_test(NodeInspector_HappyPath_VariableRenames) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py rename to AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py index dfe1064a92..2fb1830b8f 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_CanSelectNode.py @@ -20,7 +20,7 @@ class Tests(): GENERAL_WAIT = 0.5 # seconds -def NodePalette_SelectNode(): +def NodePalette_HappyPath_CanSelectNode(): """ Summary: Categories and Nodes can be selected @@ -97,4 +97,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(NodePalette_SelectNode) + Report.start_test(NodePalette_HappyPath_CanSelectNode) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py similarity index 96% rename from AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py rename to AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py index 87a08346d0..93254dd377 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_HappyPath_ClearSelection.py @@ -17,7 +17,7 @@ class Tests(): # fmt: on -def NodePalette_ClearSelection(): +def NodePalette_HappyPath_ClearSelection(): """ Summary: Clicking the X button on the Search Box clears the currently entered string @@ -85,4 +85,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(NodePalette_ClearSelection) + Report.start_test(NodePalette_HappyPath_ClearSelection) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py rename to AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py index c331157e82..721ab53d8e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py @@ -23,7 +23,7 @@ class Tests(): # fmt: on -def OnEntityActivatedDeactivated_PrintMessage(): +def OnEntityActivatedDeactivated_HappyPath_PrintMessage(): """ Summary: Verify that the On Entity Activated/On Entity Deactivated nodes are working as expected @@ -189,4 +189,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(OnEntityActivatedDeactivated_PrintMessage) + Report.start_test(OnEntityActivatedDeactivated_HappyPath_PrintMessage) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py index 746efa500c..626b1cf0bd 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Default_RetainOnSCRestart.py @@ -23,7 +23,7 @@ class Tests(): # fmt: on -def Pane_RetainOnSCRestart(): +def Pane_Default_RetainOnSCRestart(): """ Summary: The Script Canvas window is opened to verify if Script canvas panes can retain its visibility, size and location @@ -154,4 +154,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Pane_RetainOnSCRestart) + Report.start_test(Pane_Default_RetainOnSCRestart) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py old mode 100755 new mode 100644 similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py index da9dc125bc..2186a8a54a --- a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_DocksProperly.py @@ -17,7 +17,7 @@ class Tests(): # fmt: on -def Docking_Pane(): +def Pane_HappyPath_DocksProperly(): """ Summary: The Script Canvas window is opened to verify if Script canvas panes can be docked into every @@ -103,4 +103,4 @@ if __name__ == "__main__": imports.init() from editor_python_test_tools.utils import Report - Report.start_test(Docking_Pane) + Report.start_test(Pane_HappyPath_DocksProperly) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py old mode 100755 new mode 100644 similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py index a72a302760..cedd68cd87 --- a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_OpenCloseSuccessfully.py @@ -18,7 +18,7 @@ class Tests(): # fmt: on -def Opening_Closing_Pane(): +def Pane_HappyPath_OpenCloseSuccessfully(): """ Summary: The Script Canvas window is opened to verify if Script Canvas panes can be opened and closed. @@ -112,4 +112,4 @@ if __name__ == "__main__": imports.init() from editor_python_test_tools.utils import Report - Report.start_test(Opening_Closing_Pane) + Report.start_test(Pane_HappyPath_OpenCloseSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py old mode 100755 new mode 100644 similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py index a870bea86f..36d734049d --- a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_HappyPath_ResizesProperly.py @@ -17,7 +17,7 @@ class Tests(): # fmt: on -def Resizing_Pane(): +def Pane_HappyPath_ResizesProperly(): """ Summary: The Script Canvas window is opened to verify if Script Canvas panes can be resized and scaled @@ -105,4 +105,4 @@ if __name__ == "__main__": imports.init() from editor_python_test_tools.utils import Report - Report.start_test(Resizing_Pane) + Report.start_test(Pane_HappyPath_ResizesProperly) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py rename to AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py index fbdba8fb38..0ddbe7e34f 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_Undocked_ClosesSuccessfully.py @@ -18,7 +18,7 @@ class Tests(): # fmt: on -def UnDockedPane_CloseSCWindow(): +def Pane_Undocked_ClosesSuccessfully(): """ Summary: The Script Canvas window is opened with one of the pane undocked. @@ -118,4 +118,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(UnDockedPane_CloseSCWindow) + Report.start_test(Pane_Undocked_ClosesSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py index 2b935a74b3..a105f1ef18 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasTools_Toggle_OpenCloseSuccess.py @@ -27,7 +27,7 @@ class Tests(): # fmt: on -def Toggle_ScriptCanvasTools(): +def ScriptCanvasTools_Toggle_OpenCloseSuccess(): """ Summary: Toggle Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas. @@ -121,4 +121,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(Toggle_ScriptCanvasTools) + Report.start_test(ScriptCanvasTools_Toggle_OpenCloseSuccess) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py index a1e177f5ec..d39c3d2590 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets_ComponentStable.py @@ -20,7 +20,7 @@ class Tests(): # fmt: on -def ScriptCanvas_ChangingAssets(): +def ScriptCanvas_ChangingAssets_ComponentStable(): """ Summary: Changing the assigned Script Canvas Asset on an entity properly updates level functionality @@ -106,4 +106,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptCanvas_ChangingAssets) + Report.start_test(ScriptCanvas_ChangingAssets_ComponentStable) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py similarity index 96% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py index 5117069b64..9bbda9bdbd 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents_InteractSuccessfully.py @@ -23,7 +23,7 @@ class LogLines: expected_lines = ["Greetings from the first script", "Greetings from the second script"] -def ScriptCanvas_TwoComponents(): +def ScriptCanvas_TwoComponents_InteractSuccessfully(): """ Summary: A test entity contains two Script Canvas components with different unique script canvas files. @@ -111,4 +111,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptCanvas_TwoComponents) + Report.start_test(ScriptCanvas_TwoComponents_InteractSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py index 53b3951c1a..d25ef64c4a 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities_UseSimultaneously.py @@ -19,7 +19,7 @@ class Tests(): # fmt: on -def ScriptCanvas_TwoEntities(): +def ScriptCanvas_TwoEntities_UseSimultaneously(): """ Summary: Two Entities can use the same Graph asset successfully at RunTime. The script canvas asset @@ -101,4 +101,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptCanvas_TwoEntities) + Report.start_test(ScriptCanvas_TwoEntities_UseSimultaneously) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_HappyPath_CreatedWithoutError.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptEvent_HappyPath_CreatedWithoutError.py diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py similarity index 96% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py index 3f343221b0..e0730b284c 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_Default_SendReceiveSuccessfully.py @@ -20,7 +20,7 @@ class Tests(): # fmt: on -def ScriptEvents_SendReceiveSuccessfully(): +def ScriptEvents_Default_SendReceiveSuccessfully(): """ Summary: An entity exists in the level that contains a Script Canvas component. In the graph is both a Send Event @@ -102,4 +102,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptEvents_SendReceiveSuccessfully) + Report.start_test(ScriptEvents_Default_SendReceiveSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py index f58d6007a1..be2665899f 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_HappyPath_SendReceiveAcrossMultiple.py @@ -21,7 +21,7 @@ class Tests(): # fmt: on -def ScriptEvents_SendReceiveAcrossMultiple(): +def ScriptEvents_HappyPath_SendReceiveAcrossMultiple(): """ Summary: EntityA and EntityB will be created in a level. Attached to both will be a Script Canvas component. @@ -113,4 +113,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(ScriptEvents_SendReceiveAcrossMultiple) + Report.start_test(ScriptEvents_HappyPath_SendReceiveAcrossMultiple) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index 24e8eeda11..a225ebd845 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -29,67 +29,67 @@ TEST_DIRECTORY = os.path.dirname(__file__) @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(TestAutomationBase): - def test_Opening_Closing_Pane(self, request, workspace, editor, launcher_platform): - from . import Opening_Closing_Pane as test_module + def test_Pane_HappyPath_OpenCloseSuccessfully(self, request, workspace, editor, launcher_platform): + from . import Pane_HappyPath_OpenCloseSuccessfully as test_module self._run_test(request, workspace, editor, test_module) - def test_Docking_Pane(self, request, workspace, editor, launcher_platform): - from . import Docking_Pane as test_module + def test_Pane_HappyPath_DocksProperly(self, request, workspace, editor, launcher_platform): + from . import Pane_HappyPath_DocksProperly as test_module self._run_test(request, workspace, editor, test_module) - def test_Resizing_Pane(self, request, workspace, editor, launcher_platform): - from . import Resizing_Pane as test_module + def test_Pane_HappyPath_ResizesProperly(self, request, workspace, editor, launcher_platform): + from . import Pane_HappyPath_ResizesProperly as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptCanvas_TwoComponents(self, request, workspace, editor, launcher_platform, level): + def test_ScriptCanvas_TwoComponents_InteractSuccessfully(self, request, workspace, editor, launcher_platform, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptCanvas_TwoComponents as test_module + from . import ScriptCanvas_TwoComponents_InteractSuccessfully as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptCanvas_ChangingAssets(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptCanvas_ChangingAssets_ComponentStable(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptCanvas_ChangingAssets as test_module + from . import ScriptCanvas_ChangingAssets_ComponentStable as test_module self._run_test(request, workspace, editor, test_module) - def test_Graph_ZoomInZoomOut(self, request, workspace, editor, launcher_platform): - from . import Graph_ZoomInZoomOut as test_module + def test_Graph_HappyPath_ZoomInZoomOut(self, request, workspace, editor, launcher_platform): + from . import Graph_HappyPath_ZoomInZoomOut as test_module self._run_test(request, workspace, editor, test_module) - def test_NodePalette_SelectNode(self, request, workspace, editor, launcher_platform): - from . import NodePalette_SelectNode as test_module + def test_NodePalette_HappyPath_CanSelectNode(self, request, workspace, editor, launcher_platform): + from . import NodePalette_HappyPath_CanSelectNode as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): + def test_OnEntityActivatedDeactivated_HappyPath_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import OnEntityActivatedDeactivated_PrintMessage as test_module + from . import OnEntityActivatedDeactivated_HappyPath_PrintMessage as test_module self._run_test(request, workspace, editor, test_module) - - def test_NodePalette_ClearSelection(self, request, workspace, editor, launcher_platform, project): - from . import NodePalette_ClearSelection as test_module + + def test_NodePalette_HappyPath_ClearSelection(self, request, workspace, editor, launcher_platform, project): + from . import NodePalette_HappyPath_ClearSelection as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptCanvas_TwoEntities(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptCanvas_TwoEntities_UseSimultaneously(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptCanvas_TwoEntities as test_module + from . import ScriptCanvas_TwoEntities_UseSimultaneously as test_module self._run_test(request, workspace, editor, test_module) - def test_AssetEditor_CreateScriptEventFile(self, request, workspace, editor, launcher_platform, project): + def test_ScriptEvent_HappyPath_CreatedWithoutError(self, request, workspace, editor, launcher_platform, project): def teardown(): file_system.delete( [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True @@ -98,67 +98,67 @@ class TestAutomation(TestAutomationBase): file_system.delete( [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True ) - from . import AssetEditor_CreateScriptEventFile as test_module + from . import ScriptEvent_HappyPath_CreatedWithoutError as test_module self._run_test(request, workspace, editor, test_module) - def test_Toggle_ScriptCanvasTools(self, request, workspace, editor, launcher_platform): - from . import Toggle_ScriptCanvasTools as test_module + def test_ScriptCanvasTools_Toggle_OpenCloseSuccess(self, request, workspace, editor, launcher_platform): + from . import ScriptCanvasTools_Toggle_OpenCloseSuccess as test_module self._run_test(request, workspace, editor, test_module) - def test_NodeInspector_RenameVariable(self, request, workspace, editor, launcher_platform, project): - from . import NodeInspector_RenameVariable as test_module + def test_NodeInspector_HappyPath_VariableRenames(self, request, workspace, editor, launcher_platform, project): + from . import NodeInspector_HappyPath_VariableRenames as test_module self._run_test(request, workspace, editor, test_module) - - def test_Debugging_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): - from . import Debugging_TargetMultipleGraphs as test_module + + def test_Debugger_HappyPath_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): + from . import Debugger_HappyPath_TargetMultipleGraphs as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_Debugging_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): + def test_Debugger_HappyPath_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import Debugging_TargetMultipleEntities as test_module + from . import Debugger_HappyPath_TargetMultipleEntities as test_module self._run_test(request, workspace, editor, test_module) - def test_EditMenu_UndoRedo(self, request, workspace, editor, launcher_platform, project): - from . import EditMenu_UndoRedo as test_module + def test_EditMenu_Default_UndoRedo(self, request, workspace, editor, launcher_platform, project): + from . import EditMenu_Default_UndoRedo as test_module self._run_test(request, workspace, editor, test_module) - def test_UnDockedPane_CloseSCWindow(self, request, workspace, editor, launcher_platform): - from . import UnDockedPane_CloseSCWindow as test_module + def test_Pane_Undocked_ClosesSuccessfully(self, request, workspace, editor, launcher_platform): + from . import Pane_Undocked_ClosesSuccessfully as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_Entity_AddScriptCanvasComponent(self, request, workspace, editor, launcher_platform, project, level): + def test_Entity_HappyPath_AddScriptCanvasComponent(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import Entity_AddScriptCanvasComponent as test_module + from . import Entity_HappyPath_AddScriptCanvasComponent as test_module self._run_test(request, workspace, editor, test_module) - def test_Pane_RetainOnSCRestart(self, request, workspace, editor, launcher_platform): - from . import Pane_RetainOnSCRestart as test_module + def test_Pane_Default_RetainOnSCRestart(self, request, workspace, editor, launcher_platform): + from . import Pane_Default_RetainOnSCRestart as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptEvents_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptEvents_HappyPath_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptEvents_SendReceiveAcrossMultiple as test_module + from . import ScriptEvents_HappyPath_SendReceiveAcrossMultiple as test_module self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_ScriptEvents_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptEvents_Default_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import ScriptEvents_SendReceiveSuccessfully as test_module + from . import ScriptEvents_Default_SendReceiveSuccessfully as test_module self._run_test(request, workspace, editor, test_module) # NOTE: We had to use hydra_test_utils.py, as TestAutomationBase run_test method @@ -171,16 +171,16 @@ class TestScriptCanvasTests(object): The following tests use hydra_test_utils.py to launch the editor and validate the results. """ - def test_FileMenu_New_Open(self, request, editor, launcher_platform): + def test_FileMenu_Default_NewAndOpen(self, request, editor, launcher_platform): expected_lines = [ "File->New action working as expected: True", "File->Open action working as expected: True", ] hydra.launch_and_validate_results( - request, TEST_DIRECTORY, editor, "FileMenu_New_Open.py", expected_lines, auto_test_mode=False, timeout=60, + request, TEST_DIRECTORY, editor, "FileMenu_Default_NewAndOpen.py", expected_lines, auto_test_mode=False, timeout=60, ) - def test_AssetEditor_NewScriptEvent(self, request, editor, launcher_platform): + def test_NewScriptEventButton_HappyPath_ContainsSCCategory(self, request, editor, launcher_platform): expected_lines = [ "New Script event action found: True", "Asset Editor opened: True", @@ -191,13 +191,13 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, - "AssetEditor_NewScriptEvent.py", + "NewScriptEventButton_HappyPath_ContainsSCCategory.py", expected_lines, auto_test_mode=False, timeout=60, ) - def test_GraphClose_SavePrompt(self, request, editor, launcher_platform): + def test_GraphClose_Default_SavePrompt(self, request, editor, launcher_platform): expected_lines = [ "New graph created: True", "Save prompt opened as expected: True", @@ -207,13 +207,13 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, - "GraphClose_SavePrompt.py", + "GraphClose_Default_SavePrompt.py", expected_lines, auto_test_mode=False, timeout=60, ) - def test_VariableManager_CreateDeleteVars(self, request, editor, launcher_platform): + def test_VariableManager_Default_CreateDeleteVars(self, request, editor, launcher_platform): var_types = ["Boolean", "Color", "EntityID", "Number", "String", "Transform", "Vector2", "Vector3", "Vector4"] expected_lines = [f"Success: {var_type} variable is created" for var_type in var_types] expected_lines.extend([f"Success: {var_type} variable is deleted" for var_type in var_types]) @@ -221,7 +221,7 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, - "VariableManager_CreateDeleteVars.py", + "VariableManager_Default_CreateDeleteVars.py", expected_lines, auto_test_mode=False, timeout=60, diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py similarity index 97% rename from AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py rename to AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py index 8f7557c01e..e53939172e 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_Default_CreateDeleteVars.py @@ -10,7 +10,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ -def VariableManager_CreateDeleteVars(): +def VariableManager_Default_CreateDeleteVars(): """ Summary: Creating and deleting each type of variable in the Variable Manager pane @@ -111,4 +111,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(VariableManager_CreateDeleteVars) + Report.start_test(VariableManager_Default_CreateDeleteVars) From eb8084d3f6c0e6973a8a250aeee9c231218c0691 Mon Sep 17 00:00:00 2001 From: srikappa Date: Fri, 7 May 2021 16:21:23 -0700 Subject: [PATCH 03/47] Initial draft for getting instantiation to work immediately after creation is undone --- .../PrefabEditorEntityOwnershipService.cpp | 4 +- .../Instance/InstanceToTemplatePropagator.cpp | 14 +++++- .../AzToolsFramework/Prefab/Link/Link.cpp | 3 ++ .../AzToolsFramework/Prefab/PrefabDomTypes.h | 1 + .../Prefab/PrefabPublicHandler.cpp | 47 +++++++++++++++---- .../Prefab/PrefabPublicHandler.h | 2 +- .../Prefab/PrefabSystemComponent.cpp | 6 +-- .../Prefab/PrefabSystemComponent.h | 2 +- .../Prefab/PrefabSystemComponentInterface.h | 2 +- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 23 +++++---- .../AzToolsFramework/Prefab/PrefabUndo.h | 2 +- .../Prefab/PrefabUndoHelpers.cpp | 8 ++-- .../Prefab/PrefabUndoHelpers.h | 4 +- .../Tests/Prefab/PrefabUndoLinkTests.cpp | 4 +- 14 files changed, 88 insertions(+), 34 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 81233069a9..58aa245397 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -281,13 +281,15 @@ namespace AzToolsFramework containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); HandleEntitiesAdded({containerEntity}); HandleEntitiesAdded(entities); - + + /* // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. Prefab::PrefabDom serializedInstance; if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(addedInstance, serializedInstance)) { m_prefabSystemComponent->UpdatePrefabTemplate(addedInstance.GetTemplateId(), serializedInstance); } + */ return addedInstance; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index b1c5f64ef9..d298e1e2b2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -176,10 +176,15 @@ namespace AzToolsFramework { PrefabDom& templateDomReference = m_prefabSystemComponentInterface->FindTemplateDom(templateId); + PrefabDomUtils::PrintPrefabDomValue("patch is ", providedPatch); + PrefabDomUtils::PrintPrefabDomValue("template dom before is ", templateDomReference); + //apply patch to template AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ApplyPatch(templateDomReference, templateDomReference.GetAllocator(), providedPatch, AZ::JsonMergeApproach::JsonPatch); + PrefabDomUtils::PrintPrefabDomValue("template dom after is ", templateDomReference); + //trigger propagation if (result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success) { @@ -270,7 +275,7 @@ namespace AzToolsFramework return parentInstance; } - void InstanceToTemplatePropagator::AddPatchesToLink(PrefabDom& patches, Link& link) + void InstanceToTemplatePropagator::AddPatchesToLink(const PrefabDom& patches, Link& link) { PrefabDom& linkDom = link.GetLinkDom(); PrefabDomValueReference linkPatchesReference = @@ -279,7 +284,12 @@ namespace AzToolsFramework // This logic only covers addition of patches. If patches already exists, the given list of patches must be appended to them. if (!linkPatchesReference.has_value()) { - linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patches, linkDom.GetAllocator()); + // If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the + // linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to + // associate them with the linkDom's allocator. This is a limitation with rapidjson. + PrefabDom patchesCopy; + patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); + linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patchesCopy, linkDom.GetAllocator()); } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp index e0834ed53b..e421e55a11 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp @@ -181,6 +181,8 @@ namespace AzToolsFramework } else { + PrefabDomUtils::PrintPrefabDomValue("Patches are : ", m_linkDom); + PrefabDomUtils::PrintPrefabDomValue("Linked instance dom before is : ", linkedInstanceDom); AZ::JsonSerializationResult::ResultCode applyPatchResult = AZ::JsonSerialization::ApplyPatch( linkedInstanceDom, targetTemplatePrefabDom.GetAllocator(), @@ -193,6 +195,7 @@ namespace AzToolsFramework "Link::UpdateTarget - " "ApplyPatches failed for Prefab DOM from source Template '%u' and target Template '%u'.", m_sourceTemplateId, m_targetTemplateId); + PrefabDomUtils::PrintPrefabDomValue("Linked instance dom after is : ", linkedInstanceDom); return false; } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h index e32f817227..e897630a91 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabDomTypes.h @@ -27,6 +27,7 @@ namespace AzToolsFramework using PrefabDomList = AZStd::vector; using PrefabDomReference = AZStd::optional>; + using PrefabDomConstReference = AZStd::optional>; using PrefabDomValueReference = AZStd::optional>; using PrefabDomValueConstReference = AZStd::optional>; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 475510c52f..80e1b558e7 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -122,6 +122,24 @@ namespace AzToolsFramework AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); + // Change top level entities to be parented to the container entity + // Mark them as dirty so this change is correctly applied to the template + for (AZ::Entity* topLevelEntity : entities) + { + //m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); + // undoBatch.MarkEntityDirty(topLevelEntity->GetId()); + AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + //ToolsApplicationRequests::Bus::Broadcast( + // &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); + } + + // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. + Prefab::PrefabDom serializedInstance; + if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(instanceToCreate->get(), serializedInstance)) + { + m_prefabSystemComponentInterface->UpdatePrefabTemplate(instanceToCreate->get().GetTemplateId(), serializedInstance); + } + instanceToCreate->get().GetNestedInstances([&](AZStd::unique_ptr& nestedInstance) { AZ_Assert(nestedInstance, "Invalid nested instance found in the new prefab created."); EntityOptionalReference nestedInstanceContainerEntity = nestedInstance->GetContainerEntity(); @@ -129,7 +147,7 @@ namespace AzToolsFramework nestedInstanceContainerEntity, "Invalid container entity found for the nested instance used in prefab creation."); CreateLink( {&nestedInstanceContainerEntity->get()}, *nestedInstance, instanceToCreate->get().GetTemplateId(), - undoBatch.GetUndoBatch(), containerEntityId); + undoBatch.GetUndoBatch(), containerEntityId, false); }); CreateLink( @@ -141,10 +159,13 @@ namespace AzToolsFramework for (AZ::Entity* topLevelEntity : topLevelEntities) { m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); - undoBatch.MarkEntityDirty(topLevelEntity->GetId()); - AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + //undoBatch.MarkEntityDirty(topLevelEntity->GetId()); + //AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + ToolsApplicationRequests::Bus::Broadcast( + &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); } + // Select Container Entity { auto selectionUndo = aznew SelectionCommand({containerEntityId}, "Select Prefab Container Entity"); @@ -244,7 +265,7 @@ namespace AzToolsFramework void PrefabPublicHandler::CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId) + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool IsUndoRedoSupportNeeded) { AZ::EntityId containerEntityId = sourceInstance.GetContainerEntityId(); AZ::Entity* containerEntity = GetEntityById(containerEntityId); @@ -270,9 +291,19 @@ namespace AzToolsFramework m_instanceToTemplateInterface->GeneratePatch(patch, containerEntityDomBefore, containerEntityDomAfter); m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId); - LinkId linkId = PrefabUndoHelpers::CreateLink( - sourceInstance.GetTemplateId(), targetTemplateId, patch, sourceInstance.GetInstanceAlias(), - undoBatch); + LinkId linkId; + if (IsUndoRedoSupportNeeded) + { + linkId = PrefabUndoHelpers::CreateLink( + sourceInstance.GetTemplateId(), targetTemplateId, AZStd::move(patch), sourceInstance.GetInstanceAlias(), undoBatch); + } + else + { + linkId = m_prefabSystemComponentInterface->CreateLink( + targetTemplateId, sourceInstance.GetTemplateId(), sourceInstance.GetInstanceAlias(), AZStd::move(patch), + InvalidLinkId); + m_prefabSystemComponentInterface->PropagateTemplateChanges(targetTemplateId); + } sourceInstance.SetLinkId(linkId); @@ -305,7 +336,7 @@ namespace AzToolsFramework patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator()); PrefabUndoHelpers::RemoveLink( sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(), - patchesCopyForUndoSupport, undoBatch); + AZStd::move(patchesCopyForUndoSupport), undoBatch); } PrefabOperationResult PrefabPublicHandler::SavePrefab(AZ::IO::Path filePath) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 5ade666a40..0e15fd9a15 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -80,7 +80,7 @@ namespace AzToolsFramework */ void CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId); + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool IsUndoRedoSupportNeeded = true); /** * Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index c6a95b01fe..0b447ef786 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -583,7 +583,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - const PrefabDomReference linkPatch, + PrefabDom linkPatch, const LinkId& linkId) { if (linkTargetId == InvalidTemplateId) @@ -667,9 +667,9 @@ namespace AzToolsFramework rapidjson::StringRef(PrefabDomUtils::SourceName), rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLink.GetLinkDom().GetAllocator()); - if (linkPatch && linkPatch->get().IsArray() && !(linkPatch->get().Empty())) + if (linkPatch.IsArray() && !(linkPatch.Empty())) { - m_instanceToTemplatePropagator.AddPatchesToLink(linkPatch.value(), newLink); + m_instanceToTemplatePropagator.AddPatchesToLink(AZStd::move(linkPatch), newLink); } //update the target template dom to have the proper values for the source template dom diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index 30d03ba2ef..b5f499296d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -156,7 +156,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - const PrefabDomReference linkPatch, + PrefabDom linkPatch, const LinkId& linkId = InvalidLinkId) override; /** diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h index 6491d67401..347b48a648 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h @@ -44,7 +44,7 @@ namespace AzToolsFramework //creates a new Link virtual LinkId CreateLink(const TemplateId& linkTargetId, const TemplateId& linkSourceId, - const InstanceAlias& instanceAlias, const PrefabDomReference linkPatch, + const InstanceAlias& instanceAlias, PrefabDom linkPatch, const LinkId& linkId = InvalidLinkId) = 0; virtual void RemoveLink(const LinkId& linkId) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index ad0cdc166a..e82e9da90a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -124,7 +124,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkPatches, + PrefabDom linkPatches, const LinkId linkId) { m_targetId = targetId; @@ -132,10 +132,7 @@ namespace AzToolsFramework m_instanceAlias = instanceAlias; m_linkId = linkId; - if (linkPatches.has_value()) - { - m_linkPatches = AZStd::move(linkPatches->get()); - } + m_linkPatches = AZStd::move(linkPatches); //if linkId is invalid, set as ADD if (m_linkId == InvalidLinkId) @@ -193,7 +190,9 @@ namespace AzToolsFramework void PrefabUndoInstanceLink::AddLink() { - m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkPatches, m_linkId); + PrefabDom linkPatchesCopy; + linkPatchesCopy.CopyFrom(m_linkPatches, linkPatchesCopy.GetAllocator()); + m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, AZStd::move(linkPatchesCopy), m_linkId); } void PrefabUndoInstanceLink::RemoveLink() @@ -228,9 +227,12 @@ namespace AzToolsFramework if (link.has_value()) { - m_linkDomPrevious = AZStd::move(link->get().GetLinkDom()); + m_linkDomPrevious.CopyFrom(link->get().GetLinkDom(), m_linkDomPrevious.GetAllocator()); } + PrefabDomUtils::PrintPrefabDomValue("m_linkDomPrevious is : ", m_linkDomPrevious); + PrefabDomUtils::PrintPrefabDomValue("link->get().GetLinkDom() is : ", link->get().GetLinkDom()); + //get source templateDom TemplateReference sourceTemplate = m_prefabSystemComponentInterface->FindTemplate(link->get().GetSourceTemplateId()); @@ -275,7 +277,7 @@ namespace AzToolsFramework if (patchesIter == m_linkDomNext.MemberEnd()) { m_linkDomNext.AddMember( - rapidjson::GenericStringRef(PrefabDomUtils::PatchesName), patchLinkCopy, m_linkDomNext.GetAllocator()); + rapidjson::GenericStringRef(PrefabDomUtils::PatchesName), AZStd::move(patchLinkCopy), m_linkDomNext.GetAllocator()); } else { @@ -303,9 +305,14 @@ namespace AzToolsFramework return; } + /* PrefabDom moveLink; moveLink.CopyFrom(linkDom, linkDom.GetAllocator()); link->get().GetLinkDom() = AZStd::move(moveLink); + */ + link->get().SetLinkDom(linkDom); + + PrefabDomUtils::PrintPrefabDomValue("dom after updating link is : ", link->get().GetLinkDom()); //propagate the link changes link->get().UpdateTarget(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h index 49bae4eda0..33d9e5ad33 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h @@ -101,7 +101,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkPatches = PrefabDomReference(), + PrefabDom linkPatches = PrefabDom(), const LinkId linkId = InvalidLinkId); void Undo() override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp index 24eb71e055..5ba8d3c940 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp @@ -34,11 +34,11 @@ namespace AzToolsFramework } LinkId CreateLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch, + TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDom patch, const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch) { auto linkAddUndo = aznew PrefabUndoInstanceLink("Create Link"); - linkAddUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, patch, InvalidLinkId); + linkAddUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, AZStd::move(patch), InvalidLinkId); linkAddUndo->SetParent(undoBatch); linkAddUndo->Redo(); @@ -47,10 +47,10 @@ namespace AzToolsFramework void RemoveLink( TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, - PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch) + PrefabDom linkPatches, UndoSystem::URSequencePoint* undoBatch) { auto linkRemoveUndo = aznew PrefabUndoInstanceLink("Remove Link"); - linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, linkPatches, linkId); + linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, AZStd::move(linkPatches), linkId); linkRemoveUndo->SetParent(undoBatch); linkRemoveUndo->Redo(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h index 6429df3b04..17cf7f52c1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h @@ -22,11 +22,11 @@ namespace AzToolsFramework const Instance& instance, AZStd::string_view undoMessage, const PrefabDom& instanceDomBeforeUpdate, UndoSystem::URSequencePoint* undoBatch); LinkId CreateLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch, + TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDom patch, const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch); void RemoveLink( TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, - PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch); + PrefabDom linkPatches, UndoSystem::URSequencePoint* undoBatch); } } // namespace Prefab } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp index 2122b116d8..3d540a7a95 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUndoLinkTests.cpp @@ -120,7 +120,7 @@ namespace UnitTest //create an undo node to apply the patch and prep for undo PrefabUndoInstanceLink undoInstanceLinkNode("Undo Link Patch"); - undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], patch, InvalidLinkId); + undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], AZStd::move(patch), InvalidLinkId); undoInstanceLinkNode.Redo(); m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue(); @@ -196,7 +196,7 @@ namespace UnitTest //create an undo node to apply the patch and prep for undo PrefabUndoInstanceLink undoInstanceLinkNode("Undo Link Patch"); - undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], linkPatch, InvalidLinkId); + undoInstanceLinkNode.Capture(rootTemplateId, nestedTemplateId, aliases[0], AZStd::move(linkPatch), InvalidLinkId); undoInstanceLinkNode.Redo(); m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue(); From 1c04160966bf3d358f07192ec81cf2247d26e1e3 Mon Sep 17 00:00:00 2001 From: srikappa Date: Fri, 7 May 2021 16:23:14 -0700 Subject: [PATCH 04/47] Added a missing header --- .../Prefab/Instance/InstanceToTemplatePropagator.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h index ca1f3a7c91..9a6aad8ac1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.h @@ -41,7 +41,7 @@ namespace AzToolsFramework void ApplyPatchesToInstance(const AZ::EntityId& entityId, PrefabDom& patches, const Instance& instanceToAddPatches) override; - void AddPatchesToLink(PrefabDom& patches, Link& link); + void AddPatchesToLink(const PrefabDom& patches, Link& link); private: From 23194376271a4f486495e890aa048e41836dac51 Mon Sep 17 00:00:00 2001 From: zsolleci Date: Mon, 10 May 2021 10:17:05 -0500 Subject: [PATCH 05/47] changed file name per review feedback --- ...vasComponent_OnEntityActivatedDeactivated_PrintMessage.py} | 4 ++-- .../Gem/PythonTests/scripting/TestSuite_Active.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) rename AutomatedTesting/Gem/PythonTests/scripting/{OnEntityActivatedDeactivated_HappyPath_PrintMessage.py => ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py} (98%) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py similarity index 98% rename from AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py rename to AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py index 721ab53d8e..14e0c849e3 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_HappyPath_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py @@ -23,7 +23,7 @@ class Tests(): # fmt: on -def OnEntityActivatedDeactivated_HappyPath_PrintMessage(): +def ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage(): """ Summary: Verify that the On Entity Activated/On Entity Deactivated nodes are working as expected @@ -189,4 +189,4 @@ if __name__ == "__main__": imports.init() from utils import Report - Report.start_test(OnEntityActivatedDeactivated_HappyPath_PrintMessage) + Report.start_test(ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index a225ebd845..1c52aa18fe 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -68,12 +68,12 @@ class TestAutomation(TestAutomationBase): self._run_test(request, workspace, editor, test_module) @pytest.mark.parametrize("level", ["tmp_level"]) - def test_OnEntityActivatedDeactivated_HappyPath_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): + def test_ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): def teardown(): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) request.addfinalizer(teardown) file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) - from . import OnEntityActivatedDeactivated_HappyPath_PrintMessage as test_module + from . import ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage as test_module self._run_test(request, workspace, editor, test_module) def test_NodePalette_HappyPath_ClearSelection(self, request, workspace, editor, launcher_platform, project): From 0da6e450a68ad2a20a8962a42ed52a58f34d2885 Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 10 May 2021 11:43:32 -0700 Subject: [PATCH 06/47] Improved comments --- .../PrefabEditorEntityOwnershipService.cpp | 10 ------- .../Instance/InstanceToTemplatePropagator.cpp | 13 ++++----- .../AzToolsFramework/Prefab/Link/Link.cpp | 3 --- .../Prefab/PrefabPublicHandler.cpp | 27 +++++++++---------- .../Prefab/PrefabPublicHandler.h | 1 + 5 files changed, 19 insertions(+), 35 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp index 58aa245397..59e50fdf65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Entity/PrefabEditorEntityOwnershipService.cpp @@ -281,16 +281,6 @@ namespace AzToolsFramework containerEntity->AddComponent(aznew Prefab::EditorPrefabComponent()); HandleEntitiesAdded({containerEntity}); HandleEntitiesAdded(entities); - - /* - // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. - Prefab::PrefabDom serializedInstance; - if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(addedInstance, serializedInstance)) - { - m_prefabSystemComponent->UpdatePrefabTemplate(addedInstance.GetTemplateId(), serializedInstance); - } - */ - return addedInstance; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index d298e1e2b2..6f812df89b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -176,15 +176,10 @@ namespace AzToolsFramework { PrefabDom& templateDomReference = m_prefabSystemComponentInterface->FindTemplateDom(templateId); - PrefabDomUtils::PrintPrefabDomValue("patch is ", providedPatch); - PrefabDomUtils::PrintPrefabDomValue("template dom before is ", templateDomReference); - //apply patch to template AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ApplyPatch(templateDomReference, templateDomReference.GetAllocator(), providedPatch, AZ::JsonMergeApproach::JsonPatch); - PrefabDomUtils::PrintPrefabDomValue("template dom after is ", templateDomReference); - //trigger propagation if (result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success) { @@ -284,9 +279,11 @@ namespace AzToolsFramework // This logic only covers addition of patches. If patches already exists, the given list of patches must be appended to them. if (!linkPatchesReference.has_value()) { - // If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the - // linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to - // associate them with the linkDom's allocator. This is a limitation with rapidjson. + /* + If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the + linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to + associate them with the linkDom's allocator. This is a limitation with rapidjson. + */ PrefabDom patchesCopy; patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); linkDom.AddMember(rapidjson::StringRef(PrefabDomUtils::PatchesName), patchesCopy, linkDom.GetAllocator()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp index e421e55a11..e0834ed53b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Link/Link.cpp @@ -181,8 +181,6 @@ namespace AzToolsFramework } else { - PrefabDomUtils::PrintPrefabDomValue("Patches are : ", m_linkDom); - PrefabDomUtils::PrintPrefabDomValue("Linked instance dom before is : ", linkedInstanceDom); AZ::JsonSerializationResult::ResultCode applyPatchResult = AZ::JsonSerialization::ApplyPatch( linkedInstanceDom, targetTemplatePrefabDom.GetAllocator(), @@ -195,7 +193,6 @@ namespace AzToolsFramework "Link::UpdateTarget - " "ApplyPatches failed for Prefab DOM from source Template '%u' and target Template '%u'.", m_sourceTemplateId, m_targetTemplateId); - PrefabDomUtils::PrintPrefabDomValue("Linked instance dom after is : ", linkedInstanceDom); return false; } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 80e1b558e7..9959ae18fa 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -122,18 +122,14 @@ namespace AzToolsFramework AZ::EntityId containerEntityId = instanceToCreate->get().GetContainerEntityId(); - // Change top level entities to be parented to the container entity - // Mark them as dirty so this change is correctly applied to the template + // Parent the entities to the container entity. Parenting the container entities of the instances passed to createPrefab + // will be done during the creation of links below. for (AZ::Entity* topLevelEntity : entities) { - //m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); - // undoBatch.MarkEntityDirty(topLevelEntity->GetId()); AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); - //ToolsApplicationRequests::Bus::Broadcast( - // &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); } - // Update the template of the instance since we modified the entities of the instance by calling HandleEntitiesAdded. + // Update the template of the instance since the entities are modified since the template creation. Prefab::PrefabDom serializedInstance; if (Prefab::PrefabDomUtils::StoreInstanceInPrefabDom(instanceToCreate->get(), serializedInstance)) { @@ -145,27 +141,28 @@ namespace AzToolsFramework EntityOptionalReference nestedInstanceContainerEntity = nestedInstance->GetContainerEntity(); AZ_Assert( nestedInstanceContainerEntity, "Invalid container entity found for the nested instance used in prefab creation."); + + // These link creations shouldn't be undone because that would put the template in a non-usable state if a user + // chooses to instantiate the template after undoing the creation. CreateLink( {&nestedInstanceContainerEntity->get()}, *nestedInstance, instanceToCreate->get().GetTemplateId(), undoBatch.GetUndoBatch(), containerEntityId, false); }); CreateLink( - topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), - commonRootEntityId); + topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), + undoBatch.GetUndoBatch(), commonRootEntityId); - // Change top level entities to be parented to the container entity - // Mark them as dirty so this change is correctly applied to the template for (AZ::Entity* topLevelEntity : topLevelEntities) { m_prefabUndoCache.UpdateCache(topLevelEntity->GetId()); - //undoBatch.MarkEntityDirty(topLevelEntity->GetId()); - //AZ::TransformBus::Event(topLevelEntity->GetId(), &AZ::TransformBus::Events::SetParent, containerEntityId); + + // Parenting entities would mark entities as dirty. But we want to unmark the top level entities as dirty because + // if we don't, the template created would be updated and cause issues with undo operation followed by instantiation. ToolsApplicationRequests::Bus::Broadcast( &ToolsApplicationRequests::Bus::Events::RemoveDirtyEntity, topLevelEntity->GetId()); } - // Select Container Entity { auto selectionUndo = aznew SelectionCommand({containerEntityId}, "Select Prefab Container Entity"); @@ -442,6 +439,8 @@ namespace AzToolsFramework PrefabDom patch; m_instanceToTemplateInterface->GeneratePatch(patch, beforeState, afterState); + PrefabDomUtils::PrintPrefabDomValue(entity->GetName(), patch); + if (patch.IsArray() && !patch.Empty() && beforeState.IsObject()) { if (IsInstanceContainerEntity(entityId) && !IsLevelInstanceContainerEntity(entityId)) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 0e15fd9a15..771f73a815 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -77,6 +77,7 @@ namespace AzToolsFramework * \param targetInstance The id of the target template. * \param undoBatch The undo batch to set as parent for this create link action. * \param commonRootEntityId The id of the entity that the source instance should be parented under. + * \param IsUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not. */ void CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, From 49941036276264c3248b42cf2fdba9fe8469f386 Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 10 May 2021 11:58:54 -0700 Subject: [PATCH 07/47] Add const ref function parameters as needed --- .../Prefab/PrefabSystemComponent.cpp | 6 +++--- .../Prefab/PrefabSystemComponent.h | 2 +- .../Prefab/PrefabSystemComponentInterface.h | 6 +++--- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 14 +------------- 4 files changed, 8 insertions(+), 20 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index 0b447ef786..985d2333bc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -583,7 +583,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - PrefabDom linkPatch, + const PrefabDomConstReference linkPatches, const LinkId& linkId) { if (linkTargetId == InvalidTemplateId) @@ -667,9 +667,9 @@ namespace AzToolsFramework rapidjson::StringRef(PrefabDomUtils::SourceName), rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLink.GetLinkDom().GetAllocator()); - if (linkPatch.IsArray() && !(linkPatch.Empty())) + if (linkPatches && linkPatches->get().IsArray() && !(linkPatches->get().Empty())) { - m_instanceToTemplatePropagator.AddPatchesToLink(AZStd::move(linkPatch), newLink); + m_instanceToTemplatePropagator.AddPatchesToLink(linkPatches.value(), newLink); } //update the target template dom to have the proper values for the source template dom diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h index b5f499296d..0a9a450f64 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.h @@ -156,7 +156,7 @@ namespace AzToolsFramework const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, - PrefabDom linkPatch, + const PrefabDomConstReference linkPatches, const LinkId& linkId = InvalidLinkId) override; /** diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h index 347b48a648..f47941254a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponentInterface.h @@ -43,9 +43,9 @@ namespace AzToolsFramework PrefabDomValue::MemberIterator& instanceIterator, InstanceOptionalReference instance) = 0; //creates a new Link - virtual LinkId CreateLink(const TemplateId& linkTargetId, const TemplateId& linkSourceId, - const InstanceAlias& instanceAlias, PrefabDom linkPatch, - const LinkId& linkId = InvalidLinkId) = 0; + virtual LinkId CreateLink( + const TemplateId& linkTargetId, const TemplateId& linkSourceId, const InstanceAlias& instanceAlias, + const PrefabDomConstReference linkPatches, const LinkId& linkId = InvalidLinkId) = 0; virtual void RemoveLink(const LinkId& linkId) = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index e82e9da90a..aadcdcdea0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -190,9 +190,7 @@ namespace AzToolsFramework void PrefabUndoInstanceLink::AddLink() { - PrefabDom linkPatchesCopy; - linkPatchesCopy.CopyFrom(m_linkPatches, linkPatchesCopy.GetAllocator()); - m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, AZStd::move(linkPatchesCopy), m_linkId); + m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkPatches, m_linkId); } void PrefabUndoInstanceLink::RemoveLink() @@ -230,9 +228,6 @@ namespace AzToolsFramework m_linkDomPrevious.CopyFrom(link->get().GetLinkDom(), m_linkDomPrevious.GetAllocator()); } - PrefabDomUtils::PrintPrefabDomValue("m_linkDomPrevious is : ", m_linkDomPrevious); - PrefabDomUtils::PrintPrefabDomValue("link->get().GetLinkDom() is : ", link->get().GetLinkDom()); - //get source templateDom TemplateReference sourceTemplate = m_prefabSystemComponentInterface->FindTemplate(link->get().GetSourceTemplateId()); @@ -305,15 +300,8 @@ namespace AzToolsFramework return; } - /* - PrefabDom moveLink; - moveLink.CopyFrom(linkDom, linkDom.GetAllocator()); - link->get().GetLinkDom() = AZStd::move(moveLink); - */ link->get().SetLinkDom(linkDom); - PrefabDomUtils::PrintPrefabDomValue("dom after updating link is : ", link->get().GetLinkDom()); - //propagate the link changes link->get().UpdateTarget(); m_prefabSystemComponentInterface->PropagateTemplateChanges(link->get().GetTargetTemplateId()); From b57dd02d90139ce33928d2d5cba1d569c8b8e7dd Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 10 May 2021 12:28:33 -0700 Subject: [PATCH 08/47] Removed a debug print command --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 9959ae18fa..4d1a657245 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -297,7 +297,7 @@ namespace AzToolsFramework else { linkId = m_prefabSystemComponentInterface->CreateLink( - targetTemplateId, sourceInstance.GetTemplateId(), sourceInstance.GetInstanceAlias(), AZStd::move(patch), + targetTemplateId, sourceInstance.GetTemplateId(), sourceInstance.GetInstanceAlias(), patch, InvalidLinkId); m_prefabSystemComponentInterface->PropagateTemplateChanges(targetTemplateId); } @@ -439,8 +439,6 @@ namespace AzToolsFramework PrefabDom patch; m_instanceToTemplateInterface->GeneratePatch(patch, beforeState, afterState); - PrefabDomUtils::PrintPrefabDomValue(entity->GetName(), patch); - if (patch.IsArray() && !patch.Empty() && beforeState.IsObject()) { if (IsInstanceContainerEntity(entityId) && !IsLevelInstanceContainerEntity(entityId)) From b5d54450d8511893da4663d84c93f4e95c9eb7ca Mon Sep 17 00:00:00 2001 From: catdo Date: Mon, 10 May 2021 15:55:31 -0700 Subject: [PATCH 09/47] added prefabnautomated test --- .../PrefabLevel_OpensLevelWithEntities.py | 78 ++++++++ .../PythonTests/prefab/TestSuite_Active.py | 39 ++++ .../Gem/PythonTests/prefab/__init__.py | 10 + .../PrefabLevel_OpensLevelWithEntities.prefab | 171 ++++++++++++++++++ .../tags.txt | 12 ++ 5 files changed, 310 insertions(+) create mode 100644 AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py create mode 100644 AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py create mode 100644 AutomatedTesting/Gem/PythonTests/prefab/__init__.py create mode 100644 AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab create mode 100644 AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py new file mode 100644 index 0000000000..45f44474e1 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py @@ -0,0 +1,78 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + + +# fmt:off +class Tests (): + find_empty_entity = ("Entity: 'EmptyEntity' found", "Entity: 'EmptyEntity' *not* found in level") + empty_entity_pos = ( + "'EmptyEntity' position is at the expected position", "'EmptyEntity' position is *not* at the expected position") + find_pxentity = ("Entity: 'EntityWithPxCollider' found", "Entity: 'EntityWithPxCollider' *not* found in level") + pxentity_component = ( + "Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' has *not* a Physx Collider") + +# fmt:on + +def PrefabLevel_OpensLevelWithEntities (): + """ + Opens the level that contains 2 entities, "EmptyEntity" and "EntityWithPxCollider". + This test makes sure that both entities exist after openning the level and that: + - EmptyEntity is at Position: (10, 20, 30) + - EntityWithPxCollider has a PhysXCollider component + """ + + import os + import sys + + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + + import editor_python_test_tools.hydra_editor_utils as hydra + + import azlmbr.legacy.general as general + import azlmbr.bus + from azlmbr.math import Vector3 + + EXPECTED_EMPTY_ENTITY_POS = Vector3 (10.00, 20.0, 30.0) + + helper.init_idle () + helper.open_level ("prefab", "PrefabLevel_OpensLevelWithEntities") + + class EmptyEntity (): + value = None + + def find_empty_entity (): + EmptyEntity.value = general.find_editor_entity ("EmptyEntity") + return EmptyEntity.value.IsValid () + + helper.wait_for_condition (find_empty_entity, 5.0) + Report.result (Tests.find_empty_entity, EmptyEntity.value.IsValid ()) + + empty_entity_pos = azlmbr.components.TransformBus (azlmbr.bus.Event, "GetWorldTranslation", EmptyEntity.value) + is_at_position = empty_entity_pos.IsClose (EXPECTED_EMPTY_ENTITY_POS) + Report.result (Tests.empty_entity_pos, is_at_position) + if not is_at_position: + Report.info (f'Expected position: {EXPECTED_EMPTY_ENTITY_POS.ToString ()}, actual position: {empty_entity_pos.ToString ()}') + + pxentity = general.find_editor_entity ("EntityWithPxCollider") + Report.result (Tests.find_pxentity, pxentity.IsValid ()) + + pxcollider_id = hydra.get_component_type_id ("PhysX Collider") + hasComponent = azlmbr.editor.EditorComponentAPIBus (azlmbr.bus.Broadcast, 'HasComponentOfType', pxentity, + pxcollider_id) + Report.result (Tests.pxentity_component, hasComponent) + + +if __name__ == "__main__": + + from editor_python_test_tools.utils import Report + Report.start_test (PrefabLevel_OpensLevelWithEntities) + PrefabLevel_OpensLevelWithEntities () \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py new file mode 100644 index 0000000000..3cd0a0d43d --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py @@ -0,0 +1,39 @@ +""" + All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + its licensors. + + For complete copyright and license terms please see the LICENSE at the root of this + distribution (the "License"). All use of this software is governed by the License, + or, if provided, by the license below or the license accompanying this file. Do not + remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + """ + +# This suite consists of all test cases that are passing and have been verified. + +import pytest +import os +import sys + +from ly_test_tools import LAUNCHERS + +sys.path.append (os.path.dirname (os.path.abspath (__file__)) + '/../automatedtesting_shared') + +from base import TestAutomationBase + + +@pytest.mark.SUITE_main +@pytest.mark.parametrize ("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize ("project", ["AutomatedTesting"]) +class TestAutomation (TestAutomationBase): + + def _run_prefab_test (self, request, workspace, editor, test_module): + self._run_test (request, workspace, editor, test_module, + ["--regset=/Amazon/Preferences/EnablePrefabSystem=true"]) + + def test_PrefabLevel_OpensLevelWithEntities (self, request, workspace, editor, launcher_platform): + from . import PrefabLevel_OpensLevelWithEntities as test_module + + + self._run_prefab_test (request, workspace, editor, test_module) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/prefab/__init__.py b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py new file mode 100644 index 0000000000..6ed3dc4bda --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py @@ -0,0 +1,10 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" \ No newline at end of file diff --git a/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab new file mode 100644 index 0000000000..0776f25935 --- /dev/null +++ b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab @@ -0,0 +1,171 @@ +{ + "Source": "Levels/PrefabLevel_OpensLevelWithEntities/PrefabLevel_OpensLevelWithEntities.prefab", + "ContainerEntity": { + "Id": "Entity_[403811863694]", + "Name": "Level", + "Components": { + "Component_[10582285743525614098]": { + "$type": "SelectionComponent", + "Id": 10582285743525614098 + }, + "Component_[12253783095375428046]": { + "$type": "EditorInspectorComponent", + "Id": 12253783095375428046 + }, + "Component_[13764860261821571747]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 13764860261821571747, + "Parent Entity": "" + }, + "Component_[15844324401733835865]": { + "$type": "EditorEntitySortComponent", + "Id": 15844324401733835865 + }, + "Component_[1605854641405361768]": { + "$type": "EditorLockComponent", + "Id": 1605854641405361768 + }, + "Component_[17698173984524983803]": { + "$type": "EditorOnlyEntityComponent", + "Id": 17698173984524983803 + }, + "Component_[3444251662966224826]": { + "$type": "EditorPendingCompositionComponent", + "Id": 3444251662966224826 + }, + "Component_[4231768881195179982]": { + "$type": "EditorVisibilityComponent", + "Id": 4231768881195179982 + }, + "Component_[4722360315410084479]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 4722360315410084479 + }, + "Component_[7614719100624882952]": { + "$type": "EditorPrefabComponent", + "Id": 7614719100624882952 + }, + "Component_[9585901769691795481]": { + "$type": "EditorEntityIconComponent", + "Id": 9585901769691795481 + } + }, + "IsDependencyReady": true + }, + "Entities": { + "Entity_[438171602062]": { + "Id": "Entity_[438171602062]", + "Name": "EntityWithPxCollider", + "Components": { + "Component_[11161653124805884473]": { + "$type": "EditorPendingCompositionComponent", + "Id": 11161653124805884473 + }, + "Component_[13116773315299882093]": { + "$type": "EditorOnlyEntityComponent", + "Id": 13116773315299882093 + }, + "Component_[15820915681461536711]": { + "$type": "EditorVisibilityComponent", + "Id": 15820915681461536711 + }, + "Component_[2222061938345834243]": { + "$type": "SelectionComponent", + "Id": 2222061938345834243 + }, + "Component_[3861913165076405600]": { + "$type": "EditorEntitySortComponent", + "Id": 3861913165076405600 + }, + "Component_[7118587015611303204]": { + "$type": "EditorLockComponent", + "Id": 7118587015611303204 + }, + "Component_[7751174327125555504]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 7751174327125555504 + }, + "Component_[8304730147756374057]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 8304730147756374057, + "Parent Entity": "Entity_[403811863694]", + "Transform Data": { + "Translate": [ + 0.0, + 20.0, + 34.0 + ] + } + }, + "Component_[8866353210615920259]": { + "$type": "EditorEntityIconComponent", + "Id": 8866353210615920259 + }, + "Component_[8988181228601932779]": { + "$type": "EditorInspectorComponent", + "Id": 8988181228601932779 + }, + "Component_[7103333782129541775]": { + "$type": "EditorColliderComponent", + "Id": 7103333782129541775 + } + }, + "IsDependencyReady": true + }, + "Entity_[532660882574]": { + "Id": "Entity_[532660882574]", + "Name": "EmptyEntity", + "Components": { + "Component_[16437814751543997955]": { + "$type": "EditorEntitySortComponent", + "Id": 16437814751543997955 + }, + "Component_[16751517102089557119]": { + "$type": "EditorPendingCompositionComponent", + "Id": 16751517102089557119 + }, + "Component_[16773275259304187949]": { + "$type": "EditorInspectorComponent", + "Id": 16773275259304187949 + }, + "Component_[17283539636910567200]": { + "$type": "SelectionComponent", + "Id": 17283539636910567200 + }, + "Component_[250004123617033400]": { + "$type": "EditorLockComponent", + "Id": 250004123617033400 + }, + "Component_[2791138963683667073]": { + "$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent", + "Id": 2791138963683667073, + "Parent Entity": "Entity_[403811863694]", + "Transform Data": { + "Translate": [ + 10.0, + 20.0, + 30.0 + ] + } + }, + "Component_[3296942400051129145]": { + "$type": "EditorEntityIconComponent", + "Id": 3296942400051129145 + }, + "Component_[3422076964671342434]": { + "$type": "EditorOnlyEntityComponent", + "Id": 3422076964671342434 + }, + "Component_[3431895414183121731]": { + "$type": "EditorVisibilityComponent", + "Id": 3431895414183121731 + }, + "Component_[7072085777705148766]": { + "$type": "EditorDisabledCompositionComponent", + "Id": 7072085777705148766 + } + }, + "IsDependencyReady": true + } + } +} \ No newline at end of file diff --git a/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt new file mode 100644 index 0000000000..0d6c1880e7 --- /dev/null +++ b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt @@ -0,0 +1,12 @@ +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 +0,0,0,0,0,0 From 333fe5232c6c3d77fa6ed92018616cf6b6192857 Mon Sep 17 00:00:00 2001 From: catdo Date: Mon, 10 May 2021 15:59:12 -0700 Subject: [PATCH 10/47] added prefab to cmakelists --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 31afab87ed..b3d74055f9 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -122,6 +122,22 @@ endif() # ) #endif() +## Prefab ## + if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_pytest( + NAME AutomatedTesting::PrefabTests + TEST_SUITE main + TEST_SERIAL + PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Active.py + TIMEOUT 3600 + RUNTIME_DEPENDENCIES + Legacy::Editor + Legacy::CryRenderNULL + AZ::AssetProcessor + AutomatedTesting.Assets + ) + endif() + ## Editor Python Bindings ## if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ly_add_pytest( From b11234097d8cc4741ef3e786a6823966633eb8ae Mon Sep 17 00:00:00 2001 From: srikappa Date: Tue, 11 May 2021 11:30:16 -0700 Subject: [PATCH 11/47] Fixed a capitalization issue --- .../Prefab/Instance/InstanceToTemplatePropagator.cpp | 2 +- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 4 ++-- .../AzToolsFramework/Prefab/PrefabPublicHandler.h | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp index 6f812df89b..a21c5301aa 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/Instance/InstanceToTemplatePropagator.cpp @@ -282,7 +282,7 @@ namespace AzToolsFramework /* If the original allocator the patches were created with gets destroyed, then the patches would become garbage in the linkDom. Since we cannot guarantee the lifecycle of the patch allocators, we are doing a copy of the patches here to - associate them with the linkDom's allocator. This is a limitation with rapidjson. + associate them with the linkDom's allocator. */ PrefabDom patchesCopy; patchesCopy.CopyFrom(patches, linkDom.GetAllocator()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index fee455b710..02fa2d14fc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -295,7 +295,7 @@ namespace AzToolsFramework void PrefabPublicHandler::CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool IsUndoRedoSupportNeeded) + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded) { AZ::EntityId containerEntityId = sourceInstance.GetContainerEntityId(); AZ::Entity* containerEntity = GetEntityById(containerEntityId); @@ -322,7 +322,7 @@ namespace AzToolsFramework m_instanceToTemplateInterface->AppendEntityAliasToPatchPaths(patch, containerEntityId); LinkId linkId; - if (IsUndoRedoSupportNeeded) + if (isUndoRedoSupportNeeded) { linkId = PrefabUndoHelpers::CreateLink( sourceInstance.GetTemplateId(), targetTemplateId, AZStd::move(patch), sourceInstance.GetInstanceAlias(), undoBatch); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 31937cf028..138bc84aa0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -77,11 +77,11 @@ namespace AzToolsFramework * \param targetInstance The id of the target template. * \param undoBatch The undo batch to set as parent for this create link action. * \param commonRootEntityId The id of the entity that the source instance should be parented under. - * \param IsUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not. + * \param isUndoRedoSupportNeeded The flag indicating whether the link should be created with undo/redo support or not. */ void CreateLink( const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, - UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool IsUndoRedoSupportNeeded = true); + UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId, const bool isUndoRedoSupportNeeded = true); /** * Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId. From 4d8ed6c0cb09b2abe43b01eea5003ab989377c6a Mon Sep 17 00:00:00 2001 From: zsolleci Date: Tue, 11 May 2021 14:19:45 -0500 Subject: [PATCH 12/47] T92563569 completed and suite updated --- .../scripting/Node_HappyPath_DuplicateNode.py | 116 ++++++++++++++++++ .../PythonTests/scripting/TestSuite_Active.py | 10 +- 2 files changed, 123 insertions(+), 3 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py new file mode 100644 index 0000000000..9d8cccd027 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py @@ -0,0 +1,116 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +""" + + +# fmt: off +class Tests(): + open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") + node_added = ("Successfully added node to graph", "Failed to add node to graph") + node_duplicated = ("Successfully duplicated node", "Failed to duplicate the node") +# fmt: on + + +def Node_HappyPath_DuplicateNode(): + """ + Summary: + Duplicating node in graph + + Expected Behavior: + Upon selecting a node and pressing Ctrl+D, the node will be duplicated + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Open a new graph + 3) Add node to graph + 4) Select node in graph to verify existence + 5) Mock Ctrl+D to duplicate node + 6) Verify the node was duplicated + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + from PySide2 import QtWidgets, QtTest + from PySide2.QtCore import Qt + + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + import editor_python_test_tools.pyside_utils as pyside_utils + + import azlmbr.legacy.general as general + + WAIT_FRAMES = 200 + + NODE_NAME = "Print" + NODE_CATEGORY = "Debug" + EXPECTED_STRING = f"{NODE_NAME} - {NODE_CATEGORY} (2 Selected)" + + def command_line_input(command_str): + cmd_action = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_ViewCommandLine", "type": QtWidgets.QAction} + ) + cmd_action.trigger() + textbox = sc.findChild(QtWidgets.QLineEdit, "commandText") + QtTest.QTest.keyClicks(textbox, command_str) + QtTest.QTest.keyClick(textbox, Qt.Key_Enter, Qt.NoModifier) + + def grab_title_text(): + scroll_area = node_inspector.findChild(QtWidgets.QScrollArea, "") + QtTest.QTest.keyClick(graph, "a", Qt.ControlModifier, WAIT_FRAMES) + general.idle_wait(1.0) + background = scroll_area.findChild(QtWidgets.QFrame, "Background") + title = background.findChild(QtWidgets.QLabel, "Title") + text = title.findChild(QtWidgets.QLabel, "Title") + print(text.text()) + return text.text() + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # # 2) Open a new graph + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + create_new_graph = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + node_inspector = sc.findChild(QtWidgets.QDockWidget, "NodeInspector") + create_new_graph.trigger() + + # 3) Add node + command_line_input("add_node Print") + + # 4) Select node in graph to verify existence + graph_view = sc.findChild(QtWidgets.QFrame, "graphicsViewFrame") + graph = graph_view.findChild(QtWidgets.QWidget, "") + + # 5) Duplicate node + sc_main.activateWindow() + QtTest.QTest.keyClick(graph, "a", Qt.ControlModifier, WAIT_FRAMES) + QtTest.QTest.keyClick(graph, "d", Qt.ControlModifier, WAIT_FRAMES) + + # 6) Verify the node was duplicated + after_dup = grab_title_text() + Report.result(Tests.node_duplicated, after_dup == EXPECTED_STRING) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from editor_python_test_tools.utils import Report + + Report.start_test(Node_HappyPath_DuplicateNode) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index dda75f0a0c..2cd41d1980 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -84,7 +84,7 @@ class TestAutomation(TestAutomationBase): file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) from . import OnEntityActivatedDeactivated_PrintMessage as test_module self._run_test(request, workspace, editor, test_module) - + @pytest.mark.test_case_id("T92562993") def test_NodePalette_ClearSelection(self, request, workspace, editor, launcher_platform, project): from . import NodePalette_ClearSelection as test_module @@ -122,7 +122,7 @@ class TestAutomation(TestAutomationBase): def test_NodeInspector_RenameVariable(self, request, workspace, editor, launcher_platform, project): from . import NodeInspector_RenameVariable as test_module self._run_test(request, workspace, editor, test_module) - + @pytest.mark.test_case_id("T92569137") def test_Debugging_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): from . import Debugging_TargetMultipleGraphs as test_module @@ -195,7 +195,7 @@ class TestAutomation(TestAutomationBase): def test_NodeCategory_ExpandOnClick(self, request, workspace, editor, launcher_platform): from . import NodeCategory_ExpandOnClick as test_module self._run_test(request, workspace, editor, test_module) - + def test_NodePalette_SearchText_Deletion(self, request, workspace, editor, launcher_platform): from . import NodePalette_SearchText_Deletion as test_module self._run_test(request, workspace, editor, test_module) @@ -204,6 +204,10 @@ class TestAutomation(TestAutomationBase): from . import VariableManager_UnpinVariableType_Works as test_module self._run_test(request, workspace, editor, test_module) + def test_Node_HappyPath_DuplicateNode(self, request, workspace, editor, launcher_platform): + from . import Node_HappyPath_DuplicateNode as test_module + self._run_test(request, workspace, editor, test_module) + # NOTE: We had to use hydra_test_utils.py, as TestAutomationBase run_test method # fails because of pyside_utils import @pytest.mark.SUITE_periodic From 21dfcfed74ed657656c2d67ccda70a871b6bfd24 Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 11 May 2021 15:26:07 -0500 Subject: [PATCH 13/47] Fix bug where setting autoLoad to false for one gem will prevent every gem after it from loading as well. --- Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index daf5b5efd2..b2fe4417d3 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -1304,7 +1304,7 @@ namespace AZ // Add all auto loadable non-asset gems to the list of gem modules to load if (!moduleLoadData.m_autoLoad) { - break; + continue; } for (AZ::OSString& dynamicLibraryPath : moduleLoadData.m_dynamicLibraryPaths) { From b5e87d3601d6fadf2a7f92531d317463efbb0cec Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 11 May 2021 16:13:04 -0500 Subject: [PATCH 14/47] Change SerializeContextTools into a ToolsApplication so that it can correctly read in slice data: - Uses ToolsApplication instead of ComponentApplication so that built-in Editor components are recognized and read in correctly - Starts up all the DynamicModules immediately so that the System Components are activated, which registers asset handlers and allows asset references to serialize in correctly - Adds a -specialization command-line flag to specify which project specialization to use (editor, game, etc) - Removes the filter to ignore unknown classes since they should all now be "known" - Adds a few gem autoload flags and a null thumbnail service so that Qt and Python systems can be skipped, as they aren't needed for the data conversions and would bring additional overhead and complications --- .../SerializeContextTools/Application.cpp | 43 ++++++++++++++++--- .../Tools/SerializeContextTools/Application.h | 5 ++- .../SerializeContextTools/CMakeLists.txt | 2 + .../Tools/SerializeContextTools/Utilities.cpp | 1 - Code/Tools/SerializeContextTools/main.cpp | 7 +-- .../gem_autoload.serializecontexttools.setreg | 15 +++++++ 6 files changed, 59 insertions(+), 14 deletions(-) create mode 100644 Registry/gem_autoload.serializecontexttools.setreg diff --git a/Code/Tools/SerializeContextTools/Application.cpp b/Code/Tools/SerializeContextTools/Application.cpp index 2ab9847aa6..72e68ebb1e 100644 --- a/Code/Tools/SerializeContextTools/Application.cpp +++ b/Code/Tools/SerializeContextTools/Application.cpp @@ -16,12 +16,23 @@ #include #include +#include + namespace AZ { + // SerializeContextTools is a full ToolsApplication that will load a project's Gem DLLs and initialize the system components. + // This level of initialization is required to get all the serialization contexts and asset handlers registered, so that when + // data transformations take place, none of the data is dropped due to not being recognized. + // However, as a simplification, anything requiring Python or Qt is skipped during initialization: + // - The gem_autoload.serializecontexttools.setreg file disables autoload for QtForPython, EditorPythonBindings, and PythonAssetBuilder + // - The system component initialization below uses ThumbnailerNullComponent so that other components relying on a ThumbnailService + // can still be started up, but the thumbnail service itself won't do anything. The real ThumbnailerComponent uses Qt, which is why + // it isn't used. + namespace SerializeContextTools { Application::Application(int argc, char** argv) - : AZ::ComponentApplication(argc, argv) + : AzToolsFramework::ToolsApplication(&argc, &argv) { AZ::IO::FixedMaxPath projectPath = AZ::Utils::GetProjectPath(); if (projectPath.empty()) @@ -51,14 +62,25 @@ namespace AZ else { AZ::SettingsRegistryInterface::Specializations projectSpecializations{ projectName }; - AZ::IO::PathView configFilenameStem = m_configFilePath.Stem(); - if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Editor")) + + // If a project specialization has been passed in via the command line, use it. + if (m_commandLine.HasSwitch("specialization")) { - projectSpecializations.Append("editor"); + AZStd::string specialization = m_commandLine.GetSwitchValue("specialization", 0); + projectSpecializations.Append(specialization); } - else if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Game")) + // Otherwise, if a config file was passed in, auto-set the specialization based on the config file name. + else { - projectSpecializations.Append(projectName + "_GameLauncher"); + AZ::IO::PathView configFilenameStem = m_configFilePath.Stem(); + if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Editor")) + { + projectSpecializations.Append("editor"); + } + else if (AZ::StringFunc::Equal(configFilenameStem.Native(), "Game")) + { + projectSpecializations.Append(projectName + "_GameLauncher"); + } } // Used the project specializations to merge the build dependencies *.setreg files @@ -78,5 +100,14 @@ namespace AZ AZ::ComponentApplication::SetSettingsRegistrySpecializations(specializations); specializations.Append("serializecontexttools"); } + + AZ::ComponentTypeList Application::GetRequiredSystemComponents() const + { + // Use all of the default system components, but also add in the ThumbnailerNullComponent so that components requiring + // a ThumbnailService can still be started up. + AZ::ComponentTypeList components = AzToolsFramework::ToolsApplication::GetRequiredSystemComponents(); + components.emplace_back(azrtti_typeid()); + return components; + } } // namespace SerializeContextTools } // namespace AZ diff --git a/Code/Tools/SerializeContextTools/Application.h b/Code/Tools/SerializeContextTools/Application.h index 63bc1892ed..b1b818e27d 100644 --- a/Code/Tools/SerializeContextTools/Application.h +++ b/Code/Tools/SerializeContextTools/Application.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace AZ @@ -20,13 +20,14 @@ namespace AZ namespace SerializeContextTools { class Application final - : public AZ::ComponentApplication + : public AzToolsFramework::ToolsApplication { public: Application(int argc, char** argv); ~Application() override = default; const char* GetConfigFilePath() const; + AZ::ComponentTypeList GetRequiredSystemComponents() const override; protected: void SetSettingsRegistrySpecializations(AZ::SettingsRegistryInterface::Specializations& specializations) override; diff --git a/Code/Tools/SerializeContextTools/CMakeLists.txt b/Code/Tools/SerializeContextTools/CMakeLists.txt index 1a993de53c..e73fd014ab 100644 --- a/Code/Tools/SerializeContextTools/CMakeLists.txt +++ b/Code/Tools/SerializeContextTools/CMakeLists.txt @@ -29,4 +29,6 @@ ly_add_target( BUILD_DEPENDENCIES PRIVATE AZ::AzCore + AZ::AzFramework + AZ::AzToolsFramework ) diff --git a/Code/Tools/SerializeContextTools/Utilities.cpp b/Code/Tools/SerializeContextTools/Utilities.cpp index 127f833f6b..1c50466443 100644 --- a/Code/Tools/SerializeContextTools/Utilities.cpp +++ b/Code/Tools/SerializeContextTools/Utilities.cpp @@ -236,7 +236,6 @@ namespace AZ::SerializeContextTools AZ::IO::MemoryStream stream(data.data(), fileLength); ObjectStream::FilterDescriptor filter; - filter.m_flags = ObjectStream::FILTERFLAG_IGNORE_UNKNOWN_CLASSES; // Never load dependencies. That's another file that would need to be processed // separately from this one. filter.m_assetCB = AZ::Data::AssetFilterNoAssetLoading; diff --git a/Code/Tools/SerializeContextTools/main.cpp b/Code/Tools/SerializeContextTools/main.cpp index ee505c9cc0..4bff597d81 100644 --- a/Code/Tools/SerializeContextTools/main.cpp +++ b/Code/Tools/SerializeContextTools/main.cpp @@ -23,6 +23,7 @@ void PrintHelp() AZ_Printf("Help", "Serialize Context Tool\n"); AZ_Printf("Help", " [-config] *\n"); AZ_Printf("Help", " [opt] -config=: optional path to application's config file. Default is 'config/editor.xml'.\n"); + AZ_Printf("Help", " [opt] -specialization=: optional Registry project specialization, such as 'editor' or 'game'. Default is none. \n"); AZ_Printf("Help", "\n"); AZ_Printf("Help", " 'help': Print this help\n"); AZ_Printf("Help", " example: 'help'\n"); @@ -81,11 +82,7 @@ int main(int argc, char** argv) bool result = false; Application application(argc, argv); AZ::ComponentApplication::StartupParameters startupParameters; - startupParameters.m_loadDynamicModules = false; - application.Create({}, startupParameters); - // Load the DynamicModules after the Application starts to prevent Gem System Components - // from activating - application.LoadDynamicModules(); + application.Start({}, startupParameters); const AZ::CommandLine* commandLine = application.GetAzCommandLine(); if (commandLine->GetNumMiscValues() < 1) diff --git a/Registry/gem_autoload.serializecontexttools.setreg b/Registry/gem_autoload.serializecontexttools.setreg new file mode 100644 index 0000000000..1f4a8931c5 --- /dev/null +++ b/Registry/gem_autoload.serializecontexttools.setreg @@ -0,0 +1,15 @@ +{ + "Amazon": { + "Gems": { + "QtForPython.Editor": { + "AutoLoad": false + }, + "EditorPythonBindings.Editor": { + "AutoLoad": false + }, + "PythonAssetBuilder.Editor": { + "AutoLoad": false + } + } + } +} From a2a315a6cd4d2e6bf4d9ade57e753c4e8b34528d Mon Sep 17 00:00:00 2001 From: catdo Date: Tue, 11 May 2021 16:29:26 -0700 Subject: [PATCH 15/47] Fixed all nits and took out the general module and its usage --- .../Gem/PythonTests/CMakeLists.txt | 5 +- .../PrefabLevel_OpensLevelWithEntities.py | 62 +++++++++---------- ...{TestSuite_Active.py => TestSuite_Main.py} | 18 +++--- .../Gem/PythonTests/prefab/__init__.py | 2 +- 4 files changed, 39 insertions(+), 48 deletions(-) rename AutomatedTesting/Gem/PythonTests/prefab/{TestSuite_Active.py => TestSuite_Main.py} (61%) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index e4b68b6120..86bcb967ab 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -129,11 +129,10 @@ endif() NAME AutomatedTesting::PrefabTests TEST_SUITE main TEST_SERIAL - PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Active.py - TIMEOUT 3600 + PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Main.py + TIMEOUT 1500 RUNTIME_DEPENDENCIES Legacy::Editor - Legacy::CryRenderNULL AZ::AssetProcessor AutomatedTesting.Assets ) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py index 45f44474e1..ca59bbc2f8 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py @@ -9,22 +9,19 @@ remove or modify any license notices. This file is distributed on an "AS IS" BAS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. """ - # fmt:off -class Tests (): +class Tests(): find_empty_entity = ("Entity: 'EmptyEntity' found", "Entity: 'EmptyEntity' *not* found in level") - empty_entity_pos = ( - "'EmptyEntity' position is at the expected position", "'EmptyEntity' position is *not* at the expected position") + empty_entity_pos = ("'EmptyEntity' position is at the expected position", "'EmptyEntity' position is *not* at the expected position") find_pxentity = ("Entity: 'EntityWithPxCollider' found", "Entity: 'EntityWithPxCollider' *not* found in level") - pxentity_component = ( - "Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' has *not* a Physx Collider") + pxentity_component = ("Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' has *not* a Physx Collider") # fmt:on -def PrefabLevel_OpensLevelWithEntities (): +def PrefabLevel_OpensLevelWithEntities(): """ Opens the level that contains 2 entities, "EmptyEntity" and "EntityWithPxCollider". - This test makes sure that both entities exist after openning the level and that: + This test makes sure that both entities exist after opening the level and that: - EmptyEntity is at Position: (10, 20, 30) - EntityWithPxCollider has a PhysXCollider component """ @@ -37,42 +34,41 @@ def PrefabLevel_OpensLevelWithEntities (): import editor_python_test_tools.hydra_editor_utils as hydra - import azlmbr.legacy.general as general - import azlmbr.bus + import azlmbr.entity as entity + import azlmbr.bus as bus from azlmbr.math import Vector3 - EXPECTED_EMPTY_ENTITY_POS = Vector3 (10.00, 20.0, 30.0) + EXPECTED_EMPTY_ENTITY_POS = Vector3(10.00, 20.0, 30.0) - helper.init_idle () - helper.open_level ("prefab", "PrefabLevel_OpensLevelWithEntities") + helper.init_idle() + helper.open_level("prefab", "PrefabLevel_OpensLevelWithEntities") - class EmptyEntity (): - value = None + def find_entity(entity_name): + searchFilter = entity.SearchFilter() + searchFilter.names = [entity_name] + entityIds = entity.SearchBus(bus.Broadcast, 'SearchEntities', searchFilter) + if entityIds[0].IsValid(): + return entityIds[0] + return None - def find_empty_entity (): - EmptyEntity.value = general.find_editor_entity ("EmptyEntity") - return EmptyEntity.value.IsValid () + helper.wait_for_condition(lambda: find_entity("EmptyEntity").IsValid(), 5.0) + empty_entity_id = find_entity("EmptyEntity") + Report.result(Tests.find_empty_entity, empty_entity_id.IsValid()) - helper.wait_for_condition (find_empty_entity, 5.0) - Report.result (Tests.find_empty_entity, EmptyEntity.value.IsValid ()) - - empty_entity_pos = azlmbr.components.TransformBus (azlmbr.bus.Event, "GetWorldTranslation", EmptyEntity.value) - is_at_position = empty_entity_pos.IsClose (EXPECTED_EMPTY_ENTITY_POS) - Report.result (Tests.empty_entity_pos, is_at_position) + empty_entity_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", empty_entity_id) + is_at_position = empty_entity_pos.IsClose(EXPECTED_EMPTY_ENTITY_POS) + Report.result(Tests.empty_entity_pos, is_at_position) if not is_at_position: - Report.info (f'Expected position: {EXPECTED_EMPTY_ENTITY_POS.ToString ()}, actual position: {empty_entity_pos.ToString ()}') + Report.info(f'Expected position: {EXPECTED_EMPTY_ENTITY_POS.ToString()}, actual position: {empty_entity_pos.ToString()}') - pxentity = general.find_editor_entity ("EntityWithPxCollider") - Report.result (Tests.find_pxentity, pxentity.IsValid ()) - - pxcollider_id = hydra.get_component_type_id ("PhysX Collider") - hasComponent = azlmbr.editor.EditorComponentAPIBus (azlmbr.bus.Broadcast, 'HasComponentOfType', pxentity, - pxcollider_id) - Report.result (Tests.pxentity_component, hasComponent) + pxentity = find_entity("EntityWithPxCollider") + Report.result(Tests.find_pxentity, pxentity.IsValid()) + pxcollider_id = hydra.get_component_type_id("PhysX Collider") + hasComponent = azlmbr.editor.EditorComponentAPIBus(azlmbr.bus.Broadcast, 'HasComponentOfType', pxentity, pxcollider_id) + Report.result(Tests.pxentity_component, hasComponent) if __name__ == "__main__": from editor_python_test_tools.utils import Report Report.start_test (PrefabLevel_OpensLevelWithEntities) - PrefabLevel_OpensLevelWithEntities () \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py similarity index 61% rename from AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py rename to AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py index 3cd0a0d43d..51c78a99e2 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/TestSuite_Main.py @@ -22,18 +22,14 @@ sys.path.append (os.path.dirname (os.path.abspath (__file__)) + '/../automatedte from base import TestAutomationBase - @pytest.mark.SUITE_main -@pytest.mark.parametrize ("launcher_platform", ['windows_editor']) -@pytest.mark.parametrize ("project", ["AutomatedTesting"]) -class TestAutomation (TestAutomationBase): +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): - def _run_prefab_test (self, request, workspace, editor, test_module): - self._run_test (request, workspace, editor, test_module, - ["--regset=/Amazon/Preferences/EnablePrefabSystem=true"]) + def _run_prefab_test(self, request, workspace, editor, test_module): + self._run_test(request, workspace, editor, test_module, ["--regset=/Amazon/Preferences/EnablePrefabSystem=true"]) - def test_PrefabLevel_OpensLevelWithEntities (self, request, workspace, editor, launcher_platform): + def test_PrefabLevel_OpensLevelWithEntities(self, request, workspace, editor, launcher_platform): from . import PrefabLevel_OpensLevelWithEntities as test_module - - - self._run_prefab_test (request, workspace, editor, test_module) \ No newline at end of file + self._run_prefab_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/__init__.py b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py index 6ed3dc4bda..79f8fa4422 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/__init__.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/__init__.py @@ -7,4 +7,4 @@ distribution (the "License"). All use of this software is governed by the Licens or, if provided, by the license below or the license accompanying this file. Do not remove or modify any license notices. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -""" \ No newline at end of file +""" From bf62687b37de60d3b5196dad620d1365c021cf2e Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Tue, 11 May 2021 18:58:26 -0700 Subject: [PATCH 16/47] Update android installation script to install gradle 7.0 --- .../build/build_node/Platform/Windows/install_android.ps1 | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/build/build_node/Platform/Windows/install_android.ps1 b/scripts/build/build_node/Platform/Windows/install_android.ps1 index 30e651cc3a..2fde5fcb8c 100644 --- a/scripts/build/build_node/Platform/Windows/install_android.ps1 +++ b/scripts/build/build_node/Platform/Windows/install_android.ps1 @@ -28,8 +28,8 @@ Start-Process -FilePath $sdkmanager -ArgumentList $build_tools -NoNewWindow -Wai Write-Host "Installing Gradle and Ninja" Import-Module C:\ProgramData\chocolatey\helpers\chocolateyInstaller.psm1 #Grade needs a custom installer due to being hardcoded to C:\Programdata in Chocolatey $packageName = 'gradle' -$version = '5.6.4' -$checksum = 'ABC10BCEDB58806E8654210F96031DB541BCD2D6FC3161E81CB0572D6A15E821' +$version = '7.0' +$checksum = '81003F83B0056D20EEDF48CDDD4F52A9813163D4BA185BCF8ABD34B8EEEA4CBD' $url = "https://services.gradle.org/distributions/gradle-$version-all.zip" $installDir = "C:\Gradle" @@ -38,6 +38,6 @@ Install-ChocolateyZipPackage $packageName $url $installDir -Checksum $checksum - $gradle_home = Join-Path $installDir "$packageName-$version" $gradle_bat = Join-Path $gradle_home 'bin/gradle.bat' -Install-ChocolateyEnvironmentVariable "GRADLE_HOME" $gradle_home 'Machine' +Install-ChocolateyEnvironmentVariable "GRADLE_BUILD_HOME" $gradle_home 'Machine' choco install -y ninja --version=1.10.0 --package-parameters="/installDir:C:\Ninja" \ No newline at end of file From 2558801a247498bb0ed05b7ebaf26d9ccd98a7f0 Mon Sep 17 00:00:00 2001 From: jjjoness <82226755+jjjoness@users.noreply.github.com> Date: Wed, 12 May 2021 08:58:16 +0100 Subject: [PATCH 17/47] Commit before merging main --- Code/Sandbox/Editor/MainWindow.cpp | 4 ++-- Code/Sandbox/Editor/ToolbarManager.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index 5abb780bac..5538df1424 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -1064,8 +1064,8 @@ void MainWindow::InitActions() .SetApplyHoverEffect() .SetCheckable(true) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnUpdatePlayGame); - am->AddAction(ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL, tr("Play Console")) - .SetText(tr("Play Console")); + am->AddAction(ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL, tr("Play Controls")) + .SetText(tr("Play Controls")); am->AddAction(ID_SWITCH_PHYSICS, tr("Simulate")) .SetShortcut(tr("Ctrl+P")) .SetToolTip(tr("Simulate (Ctrl+P)")) diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index bbb3ef6790..76fbe92fa8 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -613,7 +613,7 @@ AmazonToolbar ToolbarManager::GetObjectToolbar() const AmazonToolbar ToolbarManager::GetPlayConsoleToolbar() const { - AmazonToolbar t = AmazonToolbar("PlayConsole", QObject::tr("Play Console")); + AmazonToolbar t = AmazonToolbar("PlayConsole", QObject::tr("Play Controls")); t.SetMainToolbar(true); t.AddAction(ID_TOOLBAR_WIDGET_SPACER_RIGHT, ORIGINAL_TOOLBAR_VERSION); From f9fb61cc5df598f799d8b44d854fa6b1ea91b1ef Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Wed, 12 May 2021 09:40:37 +0100 Subject: [PATCH 18/47] Fix issue with viewport interaction ordering and viewport matrix changed handler (#695) * fix for ctrl+mouse-wheel to cycle transform modes in the viewport * ensure correct callback function is invoked * remove redundant check in CameraInput --- .../AzFramework/Viewport/CameraInput.cpp | 5 - .../Editor/ViewportManipulatorController.cpp | 354 ++++++++++-------- .../Editor/ViewportManipulatorController.h | 2 +- .../Source/RPI.Public/ViewportContext.cpp | 3 +- 4 files changed, 191 insertions(+), 173 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 4c95865938..8669b58911 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -407,11 +407,6 @@ namespace AzFramework { if (input->m_state == InputChannel::State::Began) { - if (input->m_state == InputChannel::State::Updated) - { - return; - } - m_translation |= translationFromKey(input->m_channelId); if (m_translation != TranslationType::Nil) { diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.cpp b/Code/Sandbox/Editor/ViewportManipulatorController.cpp index 0bf2bbc412..248d2ba52c 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.cpp +++ b/Code/Sandbox/Editor/ViewportManipulatorController.cpp @@ -21,206 +21,228 @@ #include -static const auto ManipulatorPriority = AzFramework::ViewportControllerPriority::High; -static const auto InteractionPriority = AzFramework::ViewportControllerPriority::Low; +static const auto ManipulatorPriority = AzFramework::ViewportControllerPriority::Highest; +static const auto InteractionPriority = AzFramework::ViewportControllerPriority::High; namespace SandboxEditor { - -ViewportManipulatorControllerInstance::ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport, ViewportManipulatorController* controller) - : AzFramework::MultiViewportControllerInstanceInterface(viewport, controller) -{ -} - -AzToolsFramework::ViewportInteraction::MouseButton ViewportManipulatorControllerInstance::GetMouseButton( - const AzFramework::InputChannel& inputChannel) -{ - using AzToolsFramework::ViewportInteraction::MouseButton; - using InputButton = AzFramework::InputDeviceMouse::Button; - const auto& id = inputChannel.GetInputChannelId(); - if (id == InputButton::Left) + ViewportManipulatorControllerInstance::ViewportManipulatorControllerInstance( + AzFramework::ViewportId viewport, ViewportManipulatorController* controller) + : AzFramework::MultiViewportControllerInstanceInterface(viewport, controller) { - return MouseButton::Left; - } - if (id == InputButton::Middle) - { - return MouseButton::Middle; - } - if (id == InputButton::Right) - { - return MouseButton::Right; - } - return MouseButton::None; -} - -bool ViewportManipulatorControllerInstance::IsMouseMove(const AzFramework::InputChannel& inputChannel) -{ - return inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::SystemCursorPosition; -} - -AzToolsFramework::ViewportInteraction::KeyboardModifier ViewportManipulatorControllerInstance::GetKeyboardModifier( - const AzFramework::InputChannel& inputChannel) -{ - using AzToolsFramework::ViewportInteraction::KeyboardModifier; - using Key = AzFramework::InputDeviceKeyboard::Key; - const auto& id = inputChannel.GetInputChannelId(); - if (id == Key::ModifierAltL || id == Key::ModifierAltR) - { - return KeyboardModifier::Alt; - } - if (id == Key::ModifierCtrlL || id == Key::ModifierCtrlR) - { - return KeyboardModifier::Ctrl; - } - if (id == Key::ModifierShiftL || id == Key::ModifierShiftR) - { - return KeyboardModifier::Shift; - } - return KeyboardModifier::None; -} - -bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) -{ - // We only care about manipulator and viewport interaction events - if (event.m_priority != ManipulatorPriority && event.m_priority != InteractionPriority) - { - return false; } - using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - using namespace AzToolsFramework::ViewportInteraction; - using AzFramework::InputChannel; - - bool interactionHandled = false; - AZStd::optional overrideButton; - AZStd::optional eventType; - - // Because we receive events multiple times at separate priorities for manipulator events and - // viewport interaction events, we want to avoid updating our "last tick state" until we're on our last event, - // which currently is the low priority Interaction processor. - const bool finishedProcessingEvents = event.m_priority == InteractionPriority; - - if (IsMouseMove(event.m_inputChannel)) + AzToolsFramework::ViewportInteraction::MouseButton ViewportManipulatorControllerInstance::GetMouseButton( + const AzFramework::InputChannel& inputChannel) { - // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after - if (event.m_priority == ManipulatorPriority) + using AzToolsFramework::ViewportInteraction::MouseButton; + using InputButton = AzFramework::InputDeviceMouse::Button; + const auto& id = inputChannel.GetInputChannelId(); + if (id == InputButton::Left) { - AzFramework::ScreenPoint screenPosition = AzFramework::ScreenPoint(0, 0); - ViewportMouseCursorRequestBus::EventResult( - screenPosition, GetViewportId(), &ViewportMouseCursorRequestBus::Events::ViewportCursorScreenPosition); - - m_state.m_mousePick.m_screenCoordinates = screenPosition; - AZStd::optional ray; - ViewportInteractionRequestBus::EventResult( - ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); - - if (ray.has_value()) - { - m_state.m_mousePick.m_rayOrigin = ray.value().origin; - m_state.m_mousePick.m_rayDirection = ray.value().direction; - } + return MouseButton::Left; } - eventType = MouseEvent::Move; - } - else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) - { - const AZ::u32 mouseButtonValue = static_cast(mouseButton); - overrideButton = mouseButton; - if (event.m_inputChannel.GetState() == InputChannel::State::Began) + if (id == InputButton::Middle) { - m_state.m_mouseButtons.m_mouseButtons |= mouseButtonValue; - if (IsDoubleClick(mouseButton)) + return MouseButton::Middle; + } + if (id == InputButton::Right) + { + return MouseButton::Right; + } + return MouseButton::None; + } + + bool ViewportManipulatorControllerInstance::IsMouseMove(const AzFramework::InputChannel& inputChannel) + { + return inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::SystemCursorPosition; + } + + AzToolsFramework::ViewportInteraction::KeyboardModifier ViewportManipulatorControllerInstance::GetKeyboardModifier( + const AzFramework::InputChannel& inputChannel) + { + using AzToolsFramework::ViewportInteraction::KeyboardModifier; + using Key = AzFramework::InputDeviceKeyboard::Key; + const auto& id = inputChannel.GetInputChannelId(); + if (id == Key::ModifierAltL || id == Key::ModifierAltR) + { + return KeyboardModifier::Alt; + } + if (id == Key::ModifierCtrlL || id == Key::ModifierCtrlR) + { + return KeyboardModifier::Ctrl; + } + if (id == Key::ModifierShiftL || id == Key::ModifierShiftR) + { + return KeyboardModifier::Shift; + } + return KeyboardModifier::None; + } + + bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) + { + // We only care about manipulator and viewport interaction events + if (event.m_priority != ManipulatorPriority && event.m_priority != InteractionPriority) + { + return false; + } + + using InteractionBus = AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; + using namespace AzToolsFramework::ViewportInteraction; + using AzFramework::InputChannel; + + bool interactionHandled = false; + float wheelDelta = 0.0f; + AZStd::optional overrideButton; + AZStd::optional eventType; + + // Because we receive events multiple times at separate priorities for manipulator events and + // viewport interaction events, we want to avoid updating our "last tick state" until we're on our last event, + // which currently is the low priority Interaction processor. + const bool finishedProcessingEvents = event.m_priority == InteractionPriority; + + const auto state = event.m_inputChannel.GetState(); + if (IsMouseMove(event.m_inputChannel)) + { + // Cache the ray trace results when doing manipulator interaction checks, no need to recalculate after + if (event.m_priority == ManipulatorPriority) { - // Only remove the double click flag once we're done processing both Manipulator and Interaction events - if (event.m_priority == InteractionPriority) + AzFramework::ScreenPoint screenPosition = AzFramework::ScreenPoint(0, 0); + ViewportMouseCursorRequestBus::EventResult( + screenPosition, GetViewportId(), &ViewportMouseCursorRequestBus::Events::ViewportCursorScreenPosition); + + m_mouseInteraction.m_mousePick.m_screenCoordinates = screenPosition; + AZStd::optional ray; + ViewportInteractionRequestBus::EventResult( + ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); + + if (ray.has_value()) { - m_pendingDoubleClicks.erase(mouseButton); + m_mouseInteraction.m_mousePick.m_rayOrigin = ray.value().origin; + m_mouseInteraction.m_mousePick.m_rayDirection = ray.value().direction; } - eventType = MouseEvent::DoubleClick; } - else + eventType = MouseEvent::Move; + } + else if (auto mouseButton = GetMouseButton(event.m_inputChannel); mouseButton != MouseButton::None) + { + const AZ::u32 mouseButtonValue = static_cast(mouseButton); + overrideButton = mouseButton; + if (state == InputChannel::State::Began) { - // Only insert the double click timing once we're done processing events, to avoid a false IsDoubleClick positive - if (finishedProcessingEvents) + m_mouseInteraction.m_mouseButtons.m_mouseButtons |= mouseButtonValue; + if (IsDoubleClick(mouseButton)) { - m_pendingDoubleClicks[mouseButton] = m_curTime; + // Only remove the double click flag once we're done processing both Manipulator and Interaction events + if (event.m_priority == InteractionPriority) + { + m_pendingDoubleClicks.erase(mouseButton); + } + eventType = MouseEvent::DoubleClick; + } + else + { + // Only insert the double click timing once we're done processing events, to avoid a false IsDoubleClick positive + if (finishedProcessingEvents) + { + m_pendingDoubleClicks[mouseButton] = m_curTime; + } + eventType = MouseEvent::Down; } - eventType = MouseEvent::Down; } - } - else if (event.m_inputChannel.GetState() == InputChannel::State::Ended) - { - // If we've actually logged a mouse down event, forward a mouse up event. - // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this viewport, - // due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. - if (m_state.m_mouseButtons.m_mouseButtons & mouseButtonValue) + else if (state == InputChannel::State::Ended) { - // Erase the button from our state if we're done processing events. - if (event.m_priority == InteractionPriority) + // If we've actually logged a mouse down event, forward a mouse up event. + // This prevents corner cases like the context menu thinking it should be opened even though no one clicked in this viewport, + // due to RenderViewportWidget ensuring all controllers get InputChannel::State::Ended events. + if (m_mouseInteraction.m_mouseButtons.m_mouseButtons & mouseButtonValue) { - m_state.m_mouseButtons.m_mouseButtons &= ~mouseButtonValue; + // Erase the button from our state if we're done processing events. + if (event.m_priority == InteractionPriority) + { + m_mouseInteraction.m_mouseButtons.m_mouseButtons &= ~mouseButtonValue; + } + eventType = MouseEvent::Up; } - eventType = MouseEvent::Up; } } - } - else if (auto keyboardModifier = GetKeyboardModifier(event.m_inputChannel); keyboardModifier != KeyboardModifier::None) - { - if (event.m_inputChannel.GetState() == InputChannel::State::Began || event.m_inputChannel.GetState() == InputChannel::State::Updated) + else if (auto keyboardModifier = GetKeyboardModifier(event.m_inputChannel); keyboardModifier != KeyboardModifier::None) { - m_state.m_keyboardModifiers.m_keyModifiers |= static_cast(keyboardModifier); + if (state == InputChannel::State::Began || state == InputChannel::State::Updated) + { + m_mouseInteraction.m_keyboardModifiers.m_keyModifiers |= static_cast(keyboardModifier); + } + else if (state == InputChannel::State::Ended) + { + m_mouseInteraction.m_keyboardModifiers.m_keyModifiers &= ~static_cast(keyboardModifier); + } } - else if (event.m_inputChannel.GetState() == InputChannel::State::Ended) + else if (event.m_inputChannel.GetInputChannelId() == AzFramework::InputDeviceMouse::Movement::Z) { - m_state.m_keyboardModifiers.m_keyModifiers &= ~static_cast(keyboardModifier); + if (state == InputChannel::State::Began || state == InputChannel::State::Updated) + { + eventType = MouseEvent::Wheel; + wheelDelta = event.m_inputChannel.GetValue(); + } } - } - if (eventType) - { - MouseInteraction mouseInteraction = m_state; - if (overrideButton) + if (eventType) { - mouseInteraction.m_mouseButtons.m_mouseButtons = static_cast(overrideButton.value()); + MouseInteraction mouseInteraction = m_mouseInteraction; + if (overrideButton) + { + mouseInteraction.m_mouseButtons.m_mouseButtons = static_cast(overrideButton.value()); + } + + mouseInteraction.m_interactionId.m_viewportId = GetViewportId(); + + // Depending on priority, we dispatch to either the manipulator or viewport interaction event + const auto& targetInteractionEvent = event.m_priority == ManipulatorPriority + ? &InteractionBus::Events::InternalHandleMouseManipulatorInteraction + : &InteractionBus::Events::InternalHandleMouseViewportInteraction; + + const auto mouseInteractionEvent = [mouseInteraction, event = eventType.value(), wheelDelta] { + switch (event) + { + case MouseEvent::Up: + case MouseEvent::Down: + case MouseEvent::Move: + case MouseEvent::DoubleClick: + return MouseInteractionEvent(AZStd::move(mouseInteraction), event); + case MouseEvent::Wheel: + return MouseInteractionEvent(AZStd::move(mouseInteraction), wheelDelta); + } + + AZ_Assert(false, "Unhandled MouseEvent"); + return MouseInteractionEvent(MouseInteraction{}, MouseEvent::Up); + }(); + + InteractionBus::EventResult( + interactionHandled, AzToolsFramework::GetEntityContextId(), targetInteractionEvent, mouseInteractionEvent); } - mouseInteraction.m_interactionId.m_viewportId = GetViewportId(); - // Depending on priority, we dispatch to either the manipulator or viewport interaction event - const auto& targetInteractionEvent = - event.m_priority == ManipulatorPriority - ? &InteractionBus::Events::InternalHandleMouseManipulatorInteraction - : &InteractionBus::Events::InternalHandleMouseViewportInteraction; - - InteractionBus::EventResult( - interactionHandled, - AzToolsFramework::GetEntityContextId(), - targetInteractionEvent, - MouseInteractionEvent(AZStd::move(mouseInteraction), eventType.value())); + return interactionHandled; } - return interactionHandled; -} - -void ViewportManipulatorControllerInstance::ResetInputChannels() -{ - m_pendingDoubleClicks.clear(); - m_state = AzToolsFramework::ViewportInteraction::MouseInteraction(); -} - -void ViewportManipulatorControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) -{ - m_curTime = event.m_time; -} - -bool ViewportManipulatorControllerInstance::IsDoubleClick(AzToolsFramework::ViewportInteraction::MouseButton button) const -{ - auto clickIt = m_pendingDoubleClicks.find(button); - if (clickIt == m_pendingDoubleClicks.end()) + void ViewportManipulatorControllerInstance::ResetInputChannels() { - return false; + m_pendingDoubleClicks.clear(); + m_mouseInteraction = AzToolsFramework::ViewportInteraction::MouseInteraction(); } - const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); - return (m_curTime.GetMilliseconds() - clickIt->second.GetMilliseconds()) < doubleClickThresholdMilliseconds; -} + void ViewportManipulatorControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) + { + m_curTime = event.m_time; + } + + bool ViewportManipulatorControllerInstance::IsDoubleClick(AzToolsFramework::ViewportInteraction::MouseButton button) const + { + auto clickIt = m_pendingDoubleClicks.find(button); + if (clickIt == m_pendingDoubleClicks.end()) + { + return false; + } + const double doubleClickThresholdMilliseconds = qApp->doubleClickInterval(); + return (m_curTime.GetMilliseconds() - clickIt->second.GetMilliseconds()) < doubleClickThresholdMilliseconds; + } } //namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.h b/Code/Sandbox/Editor/ViewportManipulatorController.h index d5540229c4..6d4ab4d1ba 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.h +++ b/Code/Sandbox/Editor/ViewportManipulatorController.h @@ -39,7 +39,7 @@ namespace SandboxEditor static bool IsMouseMove(const AzFramework::InputChannel& inputChannel); static AzToolsFramework::ViewportInteraction::KeyboardModifier GetKeyboardModifier(const AzFramework::InputChannel& inputChannel); - AzToolsFramework::ViewportInteraction::MouseInteraction m_state; + AzToolsFramework::ViewportInteraction::MouseInteraction m_mouseInteraction; AZStd::unordered_map m_pendingDoubleClicks; AZ::ScriptTimePoint m_curTime; }; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp index cc25fb39ba..0dae5ac2d0 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp @@ -40,9 +40,10 @@ namespace AZ { m_projectionMatrixChangedEvent.Signal(matrix); }); + m_onViewMatrixChangedHandler = ViewportContext::MatrixChangedEvent::Handler([this](const AZ::Matrix4x4& matrix) { - m_projectionMatrixChangedEvent.Signal(matrix); + m_viewMatrixChangedEvent.Signal(matrix); }); SetRenderScene(renderScene); From 552ebea1350898594de79471e6b683bf51bfbbf1 Mon Sep 17 00:00:00 2001 From: jjjoness <82226755+jjjoness@users.noreply.github.com> Date: Wed, 12 May 2021 11:40:36 +0100 Subject: [PATCH 19/47] Added Simulate button --- .../img/UI20/toolbar/Simulate_Physics.svg | 24 +++++++++++++++++++ .../AzQtComponents/Components/resources.qrc | 1 + Code/Sandbox/Editor/MainWindow.cpp | 3 +++ Code/Sandbox/Editor/ToolbarManager.cpp | 2 ++ 4 files changed, 30 insertions(+) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Simulate_Physics.svg diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Simulate_Physics.svg b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Simulate_Physics.svg new file mode 100644 index 0000000000..0839be31b1 --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/img/UI20/toolbar/Simulate_Physics.svg @@ -0,0 +1,24 @@ + + + Icon / Toolbar / Play Console / Simulate Physics + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc index 1e8ddb43e0..b995874a41 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/resources.qrc @@ -372,6 +372,7 @@ img/UI20/toolbar/Select.svg img/UI20/toolbar/select_object.svg img/UI20/toolbar/Select_terrain.svg + img/UI20/toolbar/Simulate_Physics.svg img/UI20/toolbar/Simulate_Physics_on_selected_objects.svg img/UI20/toolbar/Terrain.svg img/UI20/toolbar/Terrain_Texture.svg diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index c02b64f8b7..b6aece28e3 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -1023,10 +1023,13 @@ void MainWindow::InitActions() am->AddAction(ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL, tr("Play Controls")) .SetText(tr("Play Controls")); am->AddAction(ID_SWITCH_PHYSICS, tr("Simulate")) + .SetIcon(QIcon(":/stylesheet/img/UI20/toolbar/Simulate_Physics.svg")) .SetShortcut(tr("Ctrl+P")) .SetToolTip(tr("Simulate (Ctrl+P)")) .SetCheckable(true) .SetStatusTip(tr("Enable processing of Physics and AI.")) + .SetApplyHoverEffect() + .SetCheckable(true) .RegisterUpdateCallback(cryEdit, &CCryEditApp::OnSwitchPhysicsUpdate); am->AddAction(ID_GAME_SYNCPLAYER, tr("Move Player and Camera Separately")).SetCheckable(true) .SetStatusTip(tr("Move Player and Camera Separately")) diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index 7d7ac5112b..391eabae33 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -616,6 +616,8 @@ AmazonToolbar ToolbarManager::GetPlayConsoleToolbar() const t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_TOOLBAR_WIDGET_PLAYCONSOLE_LABEL, ORIGINAL_TOOLBAR_VERSION); t.AddAction(ID_VIEW_SWITCHTOGAME, TOOLBARS_WITH_PLAY_GAME); + t.AddAction(ID_TOOLBAR_SEPARATOR, ORIGINAL_TOOLBAR_VERSION); + t.AddAction(ID_SWITCH_PHYSICS, TOOLBARS_WITH_PLAY_GAME); return t; } From ae9b36c135ac17d1e3a22e626084b4a4e359717e Mon Sep 17 00:00:00 2001 From: mbalfour Date: Wed, 12 May 2021 08:56:49 -0500 Subject: [PATCH 20/47] PR feedback - now allows for multiple specializations on the command-line, and changed the switch name to "specializations" to reflect that. --- Code/Tools/SerializeContextTools/Application.cpp | 8 +++++--- Code/Tools/SerializeContextTools/main.cpp | 3 ++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Code/Tools/SerializeContextTools/Application.cpp b/Code/Tools/SerializeContextTools/Application.cpp index 72e68ebb1e..da0cca5ca6 100644 --- a/Code/Tools/SerializeContextTools/Application.cpp +++ b/Code/Tools/SerializeContextTools/Application.cpp @@ -64,10 +64,12 @@ namespace AZ AZ::SettingsRegistryInterface::Specializations projectSpecializations{ projectName }; // If a project specialization has been passed in via the command line, use it. - if (m_commandLine.HasSwitch("specialization")) + if (size_t specializationCount = m_commandLine.GetNumSwitchValues("specializations"); specializationCount > 0) { - AZStd::string specialization = m_commandLine.GetSwitchValue("specialization", 0); - projectSpecializations.Append(specialization); + for (size_t specializationIndex = 0; specializationIndex < specializationCount; ++specializationIndex) + { + projectSpecializations.Append(m_commandLine.GetSwitchValue("specializations", specializationIndex)); + } } // Otherwise, if a config file was passed in, auto-set the specialization based on the config file name. else diff --git a/Code/Tools/SerializeContextTools/main.cpp b/Code/Tools/SerializeContextTools/main.cpp index 4bff597d81..fb2dc442ed 100644 --- a/Code/Tools/SerializeContextTools/main.cpp +++ b/Code/Tools/SerializeContextTools/main.cpp @@ -23,7 +23,8 @@ void PrintHelp() AZ_Printf("Help", "Serialize Context Tool\n"); AZ_Printf("Help", " [-config] *\n"); AZ_Printf("Help", " [opt] -config=: optional path to application's config file. Default is 'config/editor.xml'.\n"); - AZ_Printf("Help", " [opt] -specialization=: optional Registry project specialization, such as 'editor' or 'game'. Default is none. \n"); + AZ_Printf("Help", " [opt] -specializations=: -separated list of optional Registry project\n"); + AZ_Printf("Help", " specializations, such as 'editor' or 'game' or 'editor;test'. Default is none. \n"); AZ_Printf("Help", "\n"); AZ_Printf("Help", " 'help': Print this help\n"); AZ_Printf("Help", " example: 'help'\n"); From 7cec2d8b076445ea8e2c965cc4a20bd424d74b50 Mon Sep 17 00:00:00 2001 From: bosnichd Date: Wed, 12 May 2021 08:30:15 -0600 Subject: [PATCH 21/47] Remove more unused things from CryCommon and CrySystem. (#709) Lots of unrelated removals, I basically tried to remove everything exposed via gEnv that isn't used anymore, and following the threads found a few other things to remove also. --- .../Engine/Config/engine_core.thread_config | 402 --- .../Config/engine_sandbox.thread_config | 128 - Code/CryEngine/CryCommon/CMakeLists.txt | 35 - Code/CryEngine/CryCommon/CryAssert_Android.h | 2 +- Code/CryEngine/CryCommon/CryAssert_Linux.h | 2 +- Code/CryEngine/CryCommon/CryAssert_Mac.h | 2 +- Code/CryEngine/CryCommon/CryAssert_iOS.h | 2 +- Code/CryEngine/CryCommon/CryAssert_impl.h | 2 +- Code/CryEngine/CryCommon/CrySystemBus.h | 6 - Code/CryEngine/CryCommon/CryThread.h | 3 - Code/CryEngine/CryCommon/CryThreadImpl.h | 19 - .../CryCommon/CryThreadImpl_windows.h | 2 - Code/CryEngine/CryCommon/CryThread_windows.h | 14 - .../CryCommon/EngineSettingsBackend.cpp | 34 - .../CryCommon/EngineSettingsBackend.h | 65 - .../CryCommon/EngineSettingsBackendApple.cpp | 486 --- .../CryCommon/EngineSettingsBackendApple.h | 51 - .../CryCommon/EngineSettingsBackendWin32.cpp | 431 --- .../CryCommon/EngineSettingsBackendWin32.h | 53 - .../CryCommon/EngineSettingsManager.cpp | 479 --- .../CryCommon/EngineSettingsManager.h | 89 - Code/CryEngine/CryCommon/IFlares.h | 228 -- Code/CryEngine/CryCommon/IMaterialEffects.h | 504 --- .../CryCommon/INotificationNetwork.h | 147 - Code/CryEngine/CryCommon/IRenderer.h | 28 +- .../CryCommon/IResourceCompilerHelper.cpp | 378 --- .../CryCommon/IResourceCompilerHelper.h | 167 - Code/CryEngine/CryCommon/IShader.h | 42 +- Code/CryEngine/CryCommon/ISoftCodeMgr.h | 276 -- Code/CryEngine/CryCommon/IStreamEngine.h | 1 - Code/CryEngine/CryCommon/ISystem.h | 327 +- Code/CryEngine/CryCommon/ISystemScheduler.h | 63 - Code/CryEngine/CryCommon/IThreadManager.h | 111 - Code/CryEngine/CryCommon/IThreadTask.h | 166 - .../CryEngine/CryCommon/Mocks/IRendererMock.h | 2 - Code/CryEngine/CryCommon/Mocks/ISystemMock.h | 44 - .../crycommon_enginesettings_mac_files.cmake | 15 - ...ycommon_enginesettings_windows_files.cmake | 15 - Code/CryEngine/CryCommon/ProfileLog.h | 70 - Code/CryEngine/CryCommon/ProjectDefines.h | 33 - .../CryCommon/ResourceCompilerHelper.cpp | 639 ---- .../CryCommon/ResourceCompilerHelper.h | 46 - .../CryCommon/SettingsManagerHelpers.cpp | 325 -- .../CryCommon/SettingsManagerHelpers.h | 491 --- .../crycommon_enginesettings_files.cmake | 27 - .../CryEngine/CryCommon/crycommon_files.cmake | 10 - Code/CryEngine/CryCommon/physinterface.h | 1 - Code/CryEngine/CryCommon/platform_impl.cpp | 3 +- Code/CryEngine/CrySystem/AutoDetectSpec.cpp | 4 +- Code/CryEngine/CrySystem/CMakeLists.txt | 2 - Code/CryEngine/CrySystem/ConsoleBatchFile.cpp | 17 - .../CrySystem/CrySystem_precompiled.h | 1 - .../CrySystem/CryThreadUtil_pthread.h | 259 -- .../CrySystem/CryThreadUtil_win32_thread.h | 432 --- Code/CryEngine/CrySystem/DebugCallStack.cpp | 926 ------ Code/CryEngine/CrySystem/DebugCallStack.h | 95 - Code/CryEngine/CrySystem/DllMain.cpp | 36 - Code/CryEngine/CrySystem/IDebugCallStack.cpp | 278 -- Code/CryEngine/CrySystem/IDebugCallStack.h | 90 - .../CrySystem/IThreadConfigManager.h | 59 - .../CrySystem/LevelSystem/LevelSystem.cpp | 17 - .../LevelSystem/SpawnableLevelSystem.cpp | 4 - Code/CryEngine/CrySystem/Log.cpp | 10 +- .../CrySystem/NotificationNetwork.cpp | 1345 -------- .../CryEngine/CrySystem/NotificationNetwork.h | 293 -- Code/CryEngine/CrySystem/ProfileLogSystem.cpp | 134 - Code/CryEngine/CrySystem/ProfileLogSystem.h | 74 - Code/CryEngine/CrySystem/ResourceManager.cpp | 11 +- .../CrySystem/SoftCode/SoftCodeMgr.cpp | 787 ----- .../CrySystem/SoftCode/SoftCodeMgr.h | 111 - Code/CryEngine/CrySystem/System.cpp | 562 ---- Code/CryEngine/CrySystem/System.h | 95 - Code/CryEngine/CrySystem/SystemInit.cpp | 164 +- Code/CryEngine/CrySystem/SystemRender.cpp | 48 - Code/CryEngine/CrySystem/SystemScheduler.cpp | 211 -- Code/CryEngine/CrySystem/SystemScheduler.h | 63 - Code/CryEngine/CrySystem/SystemThreading.cpp | 697 ---- Code/CryEngine/CrySystem/SystemWin32.cpp | 15 - .../CrySystem/ThreadConfigManager.cpp | 577 ---- .../CryEngine/CrySystem/ThreadConfigManager.h | 137 - Code/CryEngine/CrySystem/ThreadInfo.cpp | 123 - Code/CryEngine/CrySystem/ThreadInfo.h | 43 - Code/CryEngine/CrySystem/ThreadTask.cpp | 1046 ------ Code/CryEngine/CrySystem/ThreadTask.h | 181 - .../CrySystem/UnitTests/CryMathTests.cpp | 46 - .../CrySystem/UnitTests/CryPakUnitTests.cpp | 141 - Code/CryEngine/CrySystem/UnixConsole.cpp | 6 - Code/CryEngine/CrySystem/XConsole.cpp | 200 -- Code/CryEngine/CrySystem/XML/xml.cpp | 2 - .../CryEngine/CrySystem/crysystem_files.cmake | 21 - .../CrySystem/crysystem_test_files.cmake | 2 - .../AssetBrowser/AssetBrowserComponent.cpp | 2 - Code/LauncherUnified/Launcher.cpp | 5 - .../Editor/BackgroundScheduleManager.cpp | 629 ---- .../Editor/BackgroundScheduleManager.h | 117 - Code/Sandbox/Editor/BackgroundTaskManager.cpp | 410 --- Code/Sandbox/Editor/BackgroundTaskManager.h | 161 - Code/Sandbox/Editor/CMakeLists.txt | 1 - Code/Sandbox/Editor/CryEdit.cpp | 10 - Code/Sandbox/Editor/GameEngine.cpp | 21 - Code/Sandbox/Editor/IEditor.h | 2 - Code/Sandbox/Editor/IEditorImpl.cpp | 14 - Code/Sandbox/Editor/IEditorImpl.h | 17 - .../Include/IBackgroundScheduleManager.h | 207 -- .../Editor/Include/IBackgroundTaskManager.h | 230 -- Code/Sandbox/Editor/LevelInfo.cpp | 4 - Code/Sandbox/Editor/Lib/Tests/IEditorMock.h | 2 - Code/Sandbox/Editor/MainStatusBarItems.h | 1 - Code/Sandbox/Editor/MainWindow.cpp | 7 - Code/Sandbox/Editor/Objects/EntityObject.h | 1 - Code/Sandbox/Editor/UsedResources.cpp | 35 - Code/Sandbox/Editor/UsedResources.h | 2 - Code/Sandbox/Editor/editor_lib_files.cmake | 6 - .../SandboxIntegration.cpp | 25 - .../SandboxIntegration.h | 5 - .../CloudCanvasPythonWorkerInterface.h | 53 - .../MaglevControlPanelPlugin_stub.cpp | 31 - .../CryCommonTools/Export/AnimationData.cpp | 297 -- .../CryCommonTools/Export/AnimationData.h | 211 -- .../CryCommonTools/Export/CBAHelpers.cpp | 57 - Code/Tools/CryCommonTools/Export/CBAHelpers.h | 27 - .../Export/ColladaExportWriter.cpp | 556 ---- .../Export/ColladaExportWriter.h | 29 - .../CryCommonTools/Export/ColladaWriter.cpp | 2918 ----------------- .../CryCommonTools/Export/ColladaWriter.h | 32 - .../CryCommonTools/Export/ExportFileType.cpp | 66 - .../CryCommonTools/Export/ExportFileType.h | 42 - .../CryCommonTools/Export/ExportHelpers.h | 83 - .../Export/ExportSourceDecoratorBase.cpp | 130 - .../Export/ExportSourceDecoratorBase.h | 54 - .../Export/ExportStatusWindow.cpp | 215 -- .../Export/ExportStatusWindow.h | 67 - .../CryCommonTools/Export/GeometryData.cpp | 82 - .../CryCommonTools/Export/GeometryData.h | 102 - .../Export/GeometryExportSourceAdapter.cpp | 54 - .../Export/GeometryExportSourceAdapter.h | 36 - .../Export/GeometryFileData.cpp | 59 - .../CryCommonTools/Export/GeometryFileData.h | 52 - .../Export/GeometryMaterialData.cpp | 36 - .../Export/GeometryMaterialData.h | 35 - Code/Tools/CryCommonTools/Export/HelperData.h | 41 - .../CryCommonTools/Export/IAnimationData.h | 96 - .../CryCommonTools/Export/IExportContext.h | 55 - .../CryCommonTools/Export/IExportSource.h | 98 - .../CryCommonTools/Export/IExportWriter.h | 28 - .../CryCommonTools/Export/IGeometryData.h | 35 - .../CryCommonTools/Export/IGeometryFileData.h | 54 - .../Export/IGeometryMaterialData.h | 27 - .../CryCommonTools/Export/IMaterialData.h | 33 - Code/Tools/CryCommonTools/Export/IModelData.h | 36 - Code/Tools/CryCommonTools/Export/IMorphData.h | 29 - .../CryCommonTools/Export/ISkeletonData.h | 56 - .../CryCommonTools/Export/ISkinningData.h | 26 - .../CryCommonTools/Export/MaterialData.cpp | 69 - .../CryCommonTools/Export/MaterialData.h | 56 - .../CryCommonTools/Export/MaterialHelpers.cpp | 107 - .../CryCommonTools/Export/MaterialHelpers.h | 39 - Code/Tools/CryCommonTools/Export/MaxHelpers.h | 138 - .../Export/MaxUserPropertyHelpers.cpp | 99 - .../Export/MaxUserPropertyHelpers.h | 32 - Code/Tools/CryCommonTools/Export/MeshUtils.h | 914 ------ .../Tools/CryCommonTools/Export/ModelData.cpp | 118 - Code/Tools/CryCommonTools/Export/ModelData.h | 63 - .../Tools/CryCommonTools/Export/MorphData.cpp | 55 - Code/Tools/CryCommonTools/Export/MorphData.h | 52 - .../SingleAnimationExportSourceAdapter.cpp | 86 - .../SingleAnimationExportSourceAdapter.h | 45 - .../CryCommonTools/Export/SkeletonData.cpp | 309 -- .../CryCommonTools/Export/SkeletonData.h | 116 - .../CryCommonTools/Export/SkinningData.cpp | 45 - .../CryCommonTools/Export/SkinningData.h | 46 - .../CryCommonTools/Export/TransformHelpers.h | 119 - Code/Tools/CryCommonTools/UI/EULADialog.cpp | 132 - Code/Tools/CryCommonTools/UI/EULADialog.h | 55 - Code/Tools/CryCommonTools/UI/EditControl.cpp | 48 - Code/Tools/CryCommonTools/UI/EditControl.h | 36 - Code/Tools/CryCommonTools/UI/FrameWindow.cpp | 116 - Code/Tools/CryCommonTools/UI/FrameWindow.h | 44 - Code/Tools/CryCommonTools/UI/IUIComponent.h | 28 - Code/Tools/CryCommonTools/UI/Layout.cpp | 233 -- Code/Tools/CryCommonTools/UI/Layout.h | 61 - Code/Tools/CryCommonTools/UI/ListView.cpp | 96 - Code/Tools/CryCommonTools/UI/ListView.h | 42 - Code/Tools/CryCommonTools/UI/LogWindow.cpp | 158 - Code/Tools/CryCommonTools/UI/LogWindow.h | 71 - Code/Tools/CryCommonTools/UI/ProgressBar.cpp | 65 - Code/Tools/CryCommonTools/UI/ProgressBar.h | 39 - Code/Tools/CryCommonTools/UI/PushButton.cpp | 64 - Code/Tools/CryCommonTools/UI/PushButton.h | 78 - Code/Tools/CryCommonTools/UI/Spacer.cpp | 43 - Code/Tools/CryCommonTools/UI/Spacer.h | 40 - Code/Tools/CryCommonTools/UI/TaskList.cpp | 148 - Code/Tools/CryCommonTools/UI/TaskList.h | 48 - Code/Tools/CryCommonTools/UI/ToggleButton.cpp | 65 - Code/Tools/CryCommonTools/UI/ToggleButton.h | 78 - Code/Tools/CryCommonTools/UI/Win32GUI.cpp | 390 --- Code/Tools/CryCommonTools/UI/Win32GUI.h | 216 -- .../Code/Editor/PropertyHandlerSprite.cpp | 2 - 198 files changed, 29 insertions(+), 28558 deletions(-) delete mode 100644 Assets/Engine/Config/engine_core.thread_config delete mode 100644 Assets/Engine/Config/engine_sandbox.thread_config delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackend.cpp delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackend.h delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackendApple.h delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsManager.cpp delete mode 100644 Code/CryEngine/CryCommon/EngineSettingsManager.h delete mode 100644 Code/CryEngine/CryCommon/IFlares.h delete mode 100644 Code/CryEngine/CryCommon/IMaterialEffects.h delete mode 100644 Code/CryEngine/CryCommon/INotificationNetwork.h delete mode 100644 Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp delete mode 100644 Code/CryEngine/CryCommon/IResourceCompilerHelper.h delete mode 100644 Code/CryEngine/CryCommon/ISoftCodeMgr.h delete mode 100644 Code/CryEngine/CryCommon/ISystemScheduler.h delete mode 100644 Code/CryEngine/CryCommon/IThreadManager.h delete mode 100644 Code/CryEngine/CryCommon/IThreadTask.h delete mode 100644 Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake delete mode 100644 Code/CryEngine/CryCommon/ProfileLog.h delete mode 100644 Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp delete mode 100644 Code/CryEngine/CryCommon/ResourceCompilerHelper.h delete mode 100644 Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp delete mode 100644 Code/CryEngine/CryCommon/SettingsManagerHelpers.h delete mode 100644 Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake delete mode 100644 Code/CryEngine/CrySystem/CryThreadUtil_pthread.h delete mode 100644 Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h delete mode 100644 Code/CryEngine/CrySystem/DebugCallStack.cpp delete mode 100644 Code/CryEngine/CrySystem/DebugCallStack.h delete mode 100644 Code/CryEngine/CrySystem/IDebugCallStack.cpp delete mode 100644 Code/CryEngine/CrySystem/IDebugCallStack.h delete mode 100644 Code/CryEngine/CrySystem/IThreadConfigManager.h delete mode 100644 Code/CryEngine/CrySystem/NotificationNetwork.cpp delete mode 100644 Code/CryEngine/CrySystem/NotificationNetwork.h delete mode 100644 Code/CryEngine/CrySystem/ProfileLogSystem.cpp delete mode 100644 Code/CryEngine/CrySystem/ProfileLogSystem.h delete mode 100644 Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp delete mode 100644 Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h delete mode 100644 Code/CryEngine/CrySystem/SystemScheduler.cpp delete mode 100644 Code/CryEngine/CrySystem/SystemScheduler.h delete mode 100644 Code/CryEngine/CrySystem/SystemThreading.cpp delete mode 100644 Code/CryEngine/CrySystem/ThreadConfigManager.cpp delete mode 100644 Code/CryEngine/CrySystem/ThreadConfigManager.h delete mode 100644 Code/CryEngine/CrySystem/ThreadInfo.cpp delete mode 100644 Code/CryEngine/CrySystem/ThreadInfo.h delete mode 100644 Code/CryEngine/CrySystem/ThreadTask.cpp delete mode 100644 Code/CryEngine/CrySystem/ThreadTask.h delete mode 100644 Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp delete mode 100644 Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp delete mode 100644 Code/Sandbox/Editor/BackgroundScheduleManager.cpp delete mode 100644 Code/Sandbox/Editor/BackgroundScheduleManager.h delete mode 100644 Code/Sandbox/Editor/BackgroundTaskManager.cpp delete mode 100644 Code/Sandbox/Editor/BackgroundTaskManager.h delete mode 100644 Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h delete mode 100644 Code/Sandbox/Editor/Include/IBackgroundTaskManager.h delete mode 100644 Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h delete mode 100644 Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/AnimationData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/AnimationData.h delete mode 100644 Code/Tools/CryCommonTools/Export/CBAHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/CBAHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ColladaExportWriter.h delete mode 100644 Code/Tools/CryCommonTools/Export/ColladaWriter.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ColladaWriter.h delete mode 100644 Code/Tools/CryCommonTools/Export/ExportFileType.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ExportFileType.h delete mode 100644 Code/Tools/CryCommonTools/Export/ExportHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h delete mode 100644 Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ExportStatusWindow.h delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryData.h delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryFileData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryFileData.h delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/GeometryMaterialData.h delete mode 100644 Code/Tools/CryCommonTools/Export/HelperData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IAnimationData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IExportContext.h delete mode 100644 Code/Tools/CryCommonTools/Export/IExportSource.h delete mode 100644 Code/Tools/CryCommonTools/Export/IExportWriter.h delete mode 100644 Code/Tools/CryCommonTools/Export/IGeometryData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IGeometryFileData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IMaterialData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IModelData.h delete mode 100644 Code/Tools/CryCommonTools/Export/IMorphData.h delete mode 100644 Code/Tools/CryCommonTools/Export/ISkeletonData.h delete mode 100644 Code/Tools/CryCommonTools/Export/ISkinningData.h delete mode 100644 Code/Tools/CryCommonTools/Export/MaterialData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/MaterialData.h delete mode 100644 Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/MaterialHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/MaxHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Export/MeshUtils.h delete mode 100644 Code/Tools/CryCommonTools/Export/ModelData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/ModelData.h delete mode 100644 Code/Tools/CryCommonTools/Export/MorphData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/MorphData.h delete mode 100644 Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h delete mode 100644 Code/Tools/CryCommonTools/Export/SkeletonData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/SkeletonData.h delete mode 100644 Code/Tools/CryCommonTools/Export/SkinningData.cpp delete mode 100644 Code/Tools/CryCommonTools/Export/SkinningData.h delete mode 100644 Code/Tools/CryCommonTools/Export/TransformHelpers.h delete mode 100644 Code/Tools/CryCommonTools/UI/EULADialog.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/EULADialog.h delete mode 100644 Code/Tools/CryCommonTools/UI/EditControl.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/EditControl.h delete mode 100644 Code/Tools/CryCommonTools/UI/FrameWindow.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/FrameWindow.h delete mode 100644 Code/Tools/CryCommonTools/UI/IUIComponent.h delete mode 100644 Code/Tools/CryCommonTools/UI/Layout.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/Layout.h delete mode 100644 Code/Tools/CryCommonTools/UI/ListView.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/ListView.h delete mode 100644 Code/Tools/CryCommonTools/UI/LogWindow.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/LogWindow.h delete mode 100644 Code/Tools/CryCommonTools/UI/ProgressBar.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/ProgressBar.h delete mode 100644 Code/Tools/CryCommonTools/UI/PushButton.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/PushButton.h delete mode 100644 Code/Tools/CryCommonTools/UI/Spacer.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/Spacer.h delete mode 100644 Code/Tools/CryCommonTools/UI/TaskList.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/TaskList.h delete mode 100644 Code/Tools/CryCommonTools/UI/ToggleButton.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/ToggleButton.h delete mode 100644 Code/Tools/CryCommonTools/UI/Win32GUI.cpp delete mode 100644 Code/Tools/CryCommonTools/UI/Win32GUI.h diff --git a/Assets/Engine/Config/engine_core.thread_config b/Assets/Engine/Config/engine_core.thread_config deleted file mode 100644 index f9183d9174..0000000000 --- a/Assets/Engine/Config/engine_core.thread_config +++ /dev/null @@ -1,402 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Assets/Engine/Config/engine_sandbox.thread_config b/Assets/Engine/Config/engine_sandbox.thread_config deleted file mode 100644 index 7c0dc00b71..0000000000 --- a/Assets/Engine/Config/engine_sandbox.thread_config +++ /dev/null @@ -1,128 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Code/CryEngine/CryCommon/CMakeLists.txt b/Code/CryEngine/CryCommon/CMakeLists.txt index 4725489358..5105ff1a5b 100644 --- a/Code/CryEngine/CryCommon/CMakeLists.txt +++ b/Code/CryEngine/CryCommon/CMakeLists.txt @@ -32,41 +32,6 @@ ly_add_target( AZ::AzFramework ) -ly_add_target( - NAME CryCommon.EngineSettings.Static STATIC - NAMESPACE Legacy - FILES_CMAKE - crycommon_enginesettings_files.cmake - ${pal_dir}/crycommon_enginesettings_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - ${pal_dir} - BUILD_DEPENDENCIES - PUBLIC - AZ::AzCore - AZ::AzFramework -) - -ly_add_target( - NAME CryCommon.EngineSettings.RC.Static STATIC - NAMESPACE Legacy - FILES_CMAKE - crycommon_enginesettings_files.cmake - ${pal_dir}/crycommon_enginesettings_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - ${pal_dir} - COMPILE_DEFINITIONS - PRIVATE - RESOURCE_COMPILER - BUILD_DEPENDENCIES - PUBLIC - AZ::AzCore - AZ::AzFramework -) - if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( diff --git a/Code/CryEngine/CryCommon/CryAssert_Android.h b/Code/CryEngine/CryCommon/CryAssert_Android.h index 68f716ec28..6e60df1bb1 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Android.h +++ b/Code/CryEngine/CryCommon/CryAssert_Android.h @@ -31,7 +31,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_Linux.h b/Code/CryEngine/CryCommon/CryAssert_Linux.h index 7c52f78366..f0acdd79db 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Linux.h +++ b/Code/CryEngine/CryCommon/CryAssert_Linux.h @@ -34,7 +34,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_Mac.h b/Code/CryEngine/CryCommon/CryAssert_Mac.h index 9502605fea..f7f74c3b58 100644 --- a/Code/CryEngine/CryCommon/CryAssert_Mac.h +++ b/Code/CryEngine/CryCommon/CryAssert_Mac.h @@ -30,7 +30,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_iOS.h b/Code/CryEngine/CryCommon/CryAssert_iOS.h index ad668fb131..2cb08befff 100644 --- a/Code/CryEngine/CryCommon/CryAssert_iOS.h +++ b/Code/CryEngine/CryCommon/CryAssert_iOS.h @@ -31,7 +31,7 @@ void CryAssertTrace(const char* szFormat, ...) return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (szFormat == NULL) { diff --git a/Code/CryEngine/CryCommon/CryAssert_impl.h b/Code/CryEngine/CryCommon/CryAssert_impl.h index ed55162f1a..edbbb2f0c4 100644 --- a/Code/CryEngine/CryCommon/CryAssert_impl.h +++ b/Code/CryEngine/CryCommon/CryAssert_impl.h @@ -305,7 +305,7 @@ void CryAssertTrace(const char* _pszFormat, ...) { return; } - if (!gEnv->bIgnoreAllAsserts || gEnv->bTesting) + if (!gEnv->bIgnoreAllAsserts) { if (NULL == _pszFormat) { diff --git a/Code/CryEngine/CryCommon/CrySystemBus.h b/Code/CryEngine/CryCommon/CrySystemBus.h index f183de0fa9..def1ce4688 100644 --- a/Code/CryEngine/CryCommon/CrySystemBus.h +++ b/Code/CryEngine/CryCommon/CrySystemBus.h @@ -49,12 +49,6 @@ public: //! ISystem has shut down. virtual void OnCrySystemPostShutdown() {} - //! Engine pre physics update. - virtual void OnCrySystemPrePhysicsUpdate() {} - - //! Engine post physics update. - virtual void OnCrySystemPostPhysicsUpdate() {} - //! Sent when a new level is being created. virtual void OnCryEditorBeginCreate() {} diff --git a/Code/CryEngine/CryCommon/CryThread.h b/Code/CryEngine/CryCommon/CryThread.h index f1e97b2199..9aa7bce128 100644 --- a/Code/CryEngine/CryCommon/CryThread.h +++ b/Code/CryEngine/CryCommon/CryThread.h @@ -37,9 +37,6 @@ enum CryLockType #define CRYLOCK_HAVE_FASTLOCK 1 -void CryThreadSetName(threadID nThreadId, const char* sThreadName); -const char* CryThreadGetName(threadID nThreadId); - ///////////////////////////////////////////////////////////////////////////// // // Primitive locks and conditions. diff --git a/Code/CryEngine/CryCommon/CryThreadImpl.h b/Code/CryEngine/CryCommon/CryThreadImpl.h index b151b3da8a..da9be86dd5 100644 --- a/Code/CryEngine/CryCommon/CryThreadImpl.h +++ b/Code/CryEngine/CryCommon/CryThreadImpl.h @@ -31,22 +31,3 @@ #else // Put other platform specific includes here! #endif - -#include - -void CryThreadSetName(threadID dwThreadId, const char* sThreadName) -{ - if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIThreadTaskManager()) - { - gEnv->pSystem->GetIThreadTaskManager()->SetThreadName(dwThreadId, sThreadName); - } -} - -const char* CryThreadGetName(threadID dwThreadId) -{ - if (gEnv && gEnv->pSystem && gEnv->pSystem->GetIThreadTaskManager()) - { - return gEnv->pSystem->GetIThreadTaskManager()->GetThreadName(dwThreadId); - } - return ""; -} diff --git a/Code/CryEngine/CryCommon/CryThreadImpl_windows.h b/Code/CryEngine/CryCommon/CryThreadImpl_windows.h index 6f37edeea1..3ff28a81be 100644 --- a/Code/CryEngine/CryCommon/CryThreadImpl_windows.h +++ b/Code/CryEngine/CryCommon/CryThreadImpl_windows.h @@ -13,8 +13,6 @@ #pragma once -//#include - #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif diff --git a/Code/CryEngine/CryCommon/CryThread_windows.h b/Code/CryEngine/CryCommon/CryThread_windows.h index 1d9ea6dc31..b70260c7ac 100644 --- a/Code/CryEngine/CryCommon/CryThread_windows.h +++ b/Code/CryEngine/CryCommon/CryThread_windows.h @@ -249,10 +249,6 @@ public: void SetName(const char* Name) { m_name = Name; - if (m_threadId) - { - CryThreadSetName(m_threadId, m_name); - } } const char* GetName() { return m_name; } @@ -289,11 +285,6 @@ private: self->m_bIsStarted = true; self->m_bIsRunning = true; - if (!self->m_name.empty()) - { - CryThreadSetName(-1, self->m_name); - } - self->m_Runnable->Run(); self->m_bIsRunning = false; self->m_bCreatedThread = false; @@ -311,11 +302,6 @@ private: self->m_bIsStarted = true; self->m_bIsRunning = true; - if (!self->m_name.empty()) - { - CryThreadSetName(-1, self->m_name); - } - self->Run(); self->m_bIsRunning = false; self->m_bCreatedThread = false; diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp deleted file mode 100644 index caf7e03f31..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackend.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -CEngineSettingsBackend::CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName) - : m_parent(parent) - , m_moduleName() -{ - if (moduleName != nullptr) - { - m_moduleName = moduleName; - } -} - -CEngineSettingsBackend::~CEngineSettingsBackend() -{ - -} - -#endif // CRY_ENABLE_RC_HELPER - diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackend.h b/Code/CryEngine/CryCommon/EngineSettingsBackend.h deleted file mode 100644 index fce16517ec..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackend.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H -#pragma once - -#include "ProjectDefines.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "SettingsManagerHelpers.h" - -#include - -class CEngineSettingsManager; - -class CEngineSettingsBackend -{ -public: - CEngineSettingsBackend(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - virtual ~CEngineSettingsBackend(); - - virtual std::wstring GetModuleFilePath() const = 0; - - virtual bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) = 0; - virtual bool GetModuleSpecificIntEntry(const char* key, int& value) = 0; - virtual bool GetModuleSpecificBoolEntry(const char* key, bool& value) = 0; - - virtual bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) = 0; - virtual bool SetModuleSpecificIntEntry(const char* key, const int& value) = 0; - virtual bool SetModuleSpecificBoolEntry(const char* key, const bool& value) = 0; - - virtual bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) = 0; - - virtual void LoadEngineSettingsFromRegistry() = 0; - virtual bool StoreEngineSettingsToRegistry() = 0; - -protected: - CEngineSettingsManager* parent() const - { - return m_parent; - } - - const std::wstring& moduleName() const - { - return m_moduleName; - } - -private: - std::wstring m_moduleName; - CEngineSettingsManager* m_parent; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKEND_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp deleted file mode 100644 index 06f8d532d3..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.cpp +++ /dev/null @@ -1,486 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - -#include "EngineSettingsBackendApple.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "AzCore/PlatformDef.h" - -#if AZ_TRAIT_OS_PLATFORM_APPLE - -#include "EngineSettingsManager.h" -#include "SettingsManagerHelpers.h" - -#include "platform.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -using namespace SettingsManagerHelpers; - -static const char gDefaultRegistryLocation[] = "/EngineSettings.reg"; - -#define REG_SOFTWARE L"Software\\" -#define REG_COMPANY_NAME L"Amazon\\" -#define REG_PRODUCT_NAME L"Lumberyard\\" -#define REG_SETTING L"Settings\\" -#define REG_BASE_SETTING_KEY REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME REG_SETTING - -////////////////////////////////////////////////////////////////////////// -class SimpleRegistry -{ - typedef std::map< std::wstring, std::wstring > WStringMap; - std::map< std::wstring, WStringMap * > m_modules; - -public: - SimpleRegistry(); - ~SimpleRegistry(); - - void setBoolValue(const std::wstring& module, const std::wstring& key, bool value); - void setIntValue(const std::wstring& module, const std::wstring& key, int value); - void setStrValue(const std::wstring& module, const std::wstring& key, const std::wstring& value); - - bool getBoolValue(const std::wstring& module, const std::wstring& key, bool& value); - bool getIntValue(const std::wstring& module, const std::wstring& key, int& value); - bool getStrValue(const std::wstring& module, const std::wstring& key, std::wstring& value); - - bool loadFromFile(const char* fileName); - bool saveToFile(const char* fileName); - -protected: - void clear(); - -private: - static const wchar_t gSimpleMagic[]; - static const size_t gMetaCharCount; -}; - -const wchar_t SimpleRegistry::gSimpleMagic[] = L"FR0"; -const size_t SimpleRegistry::gMetaCharCount = sizeof(size_t) / sizeof(wchar_t); - -SimpleRegistry::SimpleRegistry() -{ -} - -SimpleRegistry::~SimpleRegistry() -{ - clear(); -} - -void SimpleRegistry::setBoolValue(const std::wstring& module, const std::wstring& key, bool value) -{ - return setStrValue(module, key, value ? L"true" : L"false"); -} - -void SimpleRegistry::setIntValue(const std::wstring& module, const std::wstring& key, int value) -{ - return setStrValue(module, key, std::to_wstring(value)); -} - -void SimpleRegistry::setStrValue(const std::wstring& module, const std::wstring& key, const std::wstring& value) -{ - WStringMap *map = nullptr; - - auto i = m_modules.find(module); - - if (i == m_modules.end()) - { - map = new WStringMap; - m_modules.emplace(module, map); - } - else - { - map = i->second; - } - - assert(map); - - (*map)[key] = value; -} - -bool SimpleRegistry::getBoolValue(const std::wstring& module, const std::wstring& key, bool& value) -{ - std::wstring str; - - if (!getStrValue(module, key, str)) - { - return false; - } - - value = (0 == str.compare(L"true")); - - return true; -} - -bool SimpleRegistry::getIntValue(const std::wstring& module, const std::wstring& key, int& value) -{ - std::wstring str; - - if (!getStrValue(module, key, str)) - { - return false; - } - - value = std::stoi(str); - - return true; -} - -bool SimpleRegistry::getStrValue(const std::wstring& module, const std::wstring& key, std::wstring& value) -{ - WStringMap *map = nullptr; - - auto mi = m_modules.find(module); - if (mi == m_modules.end()) - { - return false; - } - - map = mi->second; - assert(map); - - auto ki = map->find(key); - if (ki == map->end()) - { - return false; - } - - value = ki->second; - - return true; -} - -bool SimpleRegistry::loadFromFile(const char* fileName) -{ - clear(); - - std::wifstream file(fileName, std::ios_base::in|std::ios_base::binary); - file.imbue(std::locale(file.getloc(), new std::codecvt_utf16)); - if (!file.is_open()) - { - AZ_Warning("EngineSettings", false, "Failed to open registry settings file: %s", fileName); - return false; - } - - std::wstring module; - std::wstring key; - std::wstring value; - - wchar_t buffer[512]; - size_t size; - wchar_t meta[gMetaCharCount]; - - /* magic number */ - if(!file.read(buffer, sizeof(gSimpleMagic) / sizeof(wchar_t)) || - wcsncmp(gSimpleMagic, buffer, sizeof(gSimpleMagic) / sizeof(wchar_t)) != 0) - { - file.close(); - AZ_Warning("EngineSettings", false, "Failed to load registry settings from file: %s", fileName); - return false; - } - - while (file.good()) - { - file.read(meta, gMetaCharCount); - if (!file.good()) - { - break; - } - - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - module = buffer; - - file.read(meta, gMetaCharCount); - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - key = buffer; - - file.read(meta, gMetaCharCount); - memcpy(&size, meta, sizeof(size)); - file.read(buffer, size); - buffer[file.gcount()] = L'\0'; - value = buffer; - - setStrValue(module, key, value); - } - - file.close(); - - return true; -} - -bool SimpleRegistry::saveToFile(const char* fileName) -{ - std::wofstream file(fileName, std::ios_base::out|std::ios_base::trunc|std::ios_base::binary); - file.imbue(std::locale(file.getloc(), new std::codecvt_utf16)); - if (!file.is_open()) - { - return false; - } - - std::wstring module; - - size_t size; - wchar_t meta[gMetaCharCount]; - - /* magic number */ - file.write(gSimpleMagic, sizeof(gSimpleMagic) / sizeof(wchar_t)); - - for (auto j : m_modules) - { - module = j.first; - - for (auto i : *j.second) - { - size = module.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(module.c_str(), size); - - size = i.first.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(i.first.c_str(), size); - - size = i.second.size(); - memcpy(meta, &size, sizeof(meta)); - file.write(meta, gMetaCharCount); - file.write(i.second.c_str(), size); - } - } - - file.close(); - - return true; -} - -void SimpleRegistry::clear() -{ - for (auto pair : m_modules) - { - delete pair.second; - } - - m_modules.clear(); -} -////////////////////////////////////////////////////////////////////////// - -CEngineSettingsBackendApple::CEngineSettingsBackendApple(CEngineSettingsManager* parent, const wchar_t* moduleName) - : CEngineSettingsBackend(parent, moduleName) - , m_registry(new SimpleRegistry) - , m_registryFilePath() -{ - std::string rootValue = gEnv->pFileIO->GetAlias("@root@"); - if (rootValue.empty()) - { - AZ_Warning("EngineSettings", false, "Could not get engine root."); - return; - } - - rootValue.append(gDefaultRegistryLocation); - m_registryFilePath = rootValue; -} - -CEngineSettingsBackendApple::~CEngineSettingsBackendApple() -{ - delete m_registry, m_registry = nullptr; -} - -std::wstring CEngineSettingsBackendApple::GetModuleFilePath() const -{ - std::string path; - - std::wstring_convert> converter; - std::string module = converter.to_bytes(moduleName()); - - void* handle = ::dlopen(module.c_str(), RTLD_LAZY); - if (handle) - { - const int c = _dyld_image_count(); - for (int i = 0; i < c; ++i) - { - const char* image = _dyld_get_image_name(i); - const void* altHandle = dlopen(image, RTLD_LAZY); - if (handle == altHandle) - { - char absImage[PATH_MAX]; - realpath(image, absImage); - char *ext = rindex(absImage, '.'); - if (ext) - { - *ext = '\0'; - } - path.append(absImage); - path.append(".ini"); - break; - } - } - } - - return converter.from_bytes(path); -} - -bool CEngineSettingsBackendApple::GetModuleSpecificStringEntryUtf16(const char* key, CWCharBuffer wbuffer) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - std::wstring str; - if (!m_registry->getStrValue(moduleName(), wkey, str)) - { - return false; - } - - std::wcscpy(wbuffer.getPtr(), str.c_str()); - - return true; -} - -bool CEngineSettingsBackendApple::GetModuleSpecificIntEntry(const char* key, int& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - return m_registry->getIntValue(moduleName(), wkey, value); -} - -bool CEngineSettingsBackendApple::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - return m_registry->getBoolValue(moduleName(), wkey, value); -} - -bool CEngineSettingsBackendApple::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setStrValue(moduleName(), wkey, str); - - return true; -} - -bool CEngineSettingsBackendApple::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setIntValue(moduleName(), wkey, value); - - return true; -} - -bool CEngineSettingsBackendApple::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - std::wstring_convert> converter; - std::wstring wkey = converter.from_bytes(key); - - m_registry->setBoolValue(moduleName(), wkey, value); - - return true; -} - -bool CEngineSettingsBackendApple::GetInstalledBuildRootPathUtf16(const int index, CWCharBuffer name, CWCharBuffer path) -{ - return false; -} - -bool CEngineSettingsBackendApple::StoreEngineSettingsToRegistry() -{ - bool bRet = true; - wchar_t buffer[1024]; - - // ResourceCompiler Specific - if (parent()->GetValueByRef("RC_ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_ShowWindow", b); - } - - if (parent()->GetValueByRef("RC_HideCustom", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_HideCustom", b); - } - - if (parent()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - m_registry->setStrValue(REG_BASE_SETTING_KEY, L"RC_Parameters", buffer); - } - - if (parent()->GetValueByRef("RC_EnableSourceControl", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - m_registry->setBoolValue(REG_BASE_SETTING_KEY, L"RC_EnableSourceControl", b); - } - - bRet &= m_registry->saveToFile(m_registryFilePath.c_str()); - return bRet; -} - -void CEngineSettingsBackendApple::LoadEngineSettingsFromRegistry() -{ - if (!m_registry->loadFromFile(m_registryFilePath.c_str())) - { - return; - } - - std::wstring wStrResult; - bool bResult; - - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"RootPath", wStrResult)) - { - parent()->SetKey("ENG_RootPath", wStrResult.c_str()); - } - - // Engine Specific - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"ENG_RootPath", wStrResult)) - { - parent()->SetKey("ENG_RootPath", wStrResult.c_str()); - } - - // ResourceCompiler Specific - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_ShowWindow", bResult)) - { - parent()->SetKey("RC_ShowWindow", bResult); - } - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_HideCustom", bResult)) - { - parent()->SetKey("RC_HideCustom", bResult); - } - if (m_registry->getStrValue(REG_BASE_SETTING_KEY, L"RC_Parameters", wStrResult)) - { - parent()->SetKey("RC_Parameters", wStrResult.c_str()); - } - if (m_registry->getBoolValue(REG_BASE_SETTING_KEY, L"RC_EnableSourceControl", bResult)) - { - parent()->SetKey("RC_EnableSourceControl", bResult); - } -} - -#endif // AZ_TRAIT_OS_PLATFORM_APPLE -#endif // CRY_ENABLE_RC_HELPER - diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.h b/Code/CryEngine/CryCommon/EngineSettingsBackendApple.h deleted file mode 100644 index efc5a12bed..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendApple.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H -#pragma once - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -class CEngineSettingsManager; -class SimpleRegistry; - -class CEngineSettingsBackendApple : public CEngineSettingsBackend -{ -public: - CEngineSettingsBackendApple(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - ~CEngineSettingsBackendApple(); - - std::wstring GetModuleFilePath() const override; - - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) override; - bool GetModuleSpecificIntEntry(const char* key, int& value) override; - bool GetModuleSpecificBoolEntry(const char* key, bool& value) override; - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) override; - bool SetModuleSpecificIntEntry(const char* key, const int& value) override; - bool SetModuleSpecificBoolEntry(const char* key, const bool& value) override; - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) override; - - void LoadEngineSettingsFromRegistry() override; - bool StoreEngineSettingsToRegistry() override; - -private: - SimpleRegistry *m_registry; - std::string m_registryFilePath; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDAPPLE_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp b/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp deleted file mode 100644 index c2e9a67d57..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.cpp +++ /dev/null @@ -1,431 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - - -#include "EngineSettingsBackendWin32.h" - -#ifdef CRY_ENABLE_RC_HELPER - -#include "AzCore/PlatformDef.h" - -#ifdef AZ_PLATFORM_WINDOWS - -#include "EngineSettingsManager.h" - -#include "platform.h" -#include - -#define REG_SOFTWARE L"Software\\" -#define REG_COMPANY_NAME L"Amazon\\" -#define REG_PRODUCT_NAME L"Open 3D Engine\\" -#define REG_SETTING L"Settings\\" -#define REG_BASE_SETTING_KEY REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME REG_SETTING - -EXTERN_C IMAGE_DOS_HEADER __ImageBase; - -using namespace SettingsManagerHelpers; - -static bool g_bWindowQuit; -static CEngineSettingsManager* g_pThis = 0; -static const unsigned int IDC_hEditRootPath = 100; -static const unsigned int IDC_hBtnBrowse = 101; - -namespace -{ - class RegKey - { - public: - RegKey(const wchar_t* key, bool writeable); - ~RegKey(); - void* pKey; - }; - - RegKey::RegKey(const wchar_t* key, bool writeable) - { - HKEY hKey; - LONG result; - if (writeable) - { - result = RegCreateKeyExW(HKEY_CURRENT_USER, key, 0, 0, 0, KEY_WRITE, 0, &hKey, 0); - } - else - { - result = RegOpenKeyExW(HKEY_CURRENT_USER, key, 0, KEY_READ, &hKey); - } - pKey = hKey; - } - - RegKey::~RegKey() - { - RegCloseKey((HKEY)pKey); - } -} - -CEngineSettingsBackendWin32::CEngineSettingsBackendWin32(CEngineSettingsManager* parent, const wchar_t* moduleName) - : CEngineSettingsBackend(parent, moduleName) -{ -} - -std::wstring CEngineSettingsBackendWin32::GetModuleFilePath() const -{ - wchar_t szFilename[_MAX_PATH]; - GetModuleFileNameW((HINSTANCE)&__ImageBase, szFilename, _MAX_PATH); - wchar_t drive[_MAX_DRIVE]; - wchar_t dir[_MAX_DIR]; - wchar_t fname[_MAX_FNAME]; - wchar_t ext[1] = L""; - _wsplitpath_s(szFilename, drive, dir, fname, ext); - _wmakepath_s(szFilename, drive, dir, fname, L"ini"); - return szFilename; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificStringEntryUtf16(const char* key, CWCharBuffer wbuffer) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - wbuffer[0] = 0; - return false; - } - if (!GetRegValue(superKey.pKey, key, wbuffer)) - { - wbuffer[0] = 0; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificIntEntry(const char* key, int& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - return false; - } - if (!GetRegValue(superKey.pKey, key, value)) - { - value = 0; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), false); - if (!superKey.pKey) - { - return false; - } - if (!GetRegValue(superKey.pKey, key, value)) - { - value = false; - return false; - } - - return true; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, str); - } - return false; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, value); - } - return false; -} - -bool CEngineSettingsBackendWin32::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - CFixedString s = REG_BASE_SETTING_KEY; - s.append(moduleName().c_str()); - RegKey superKey(s.c_str(), true); - if (superKey.pKey) - { - return SetRegValue(superKey.pKey, key, value); - } - return false; -} - -bool CEngineSettingsBackendWin32::GetInstalledBuildRootPathUtf16(const int index, CWCharBuffer name, CWCharBuffer path) -{ - RegKey key(REG_BASE_SETTING_KEY L"O3DEExport\\ProjectBuilds", false); - if (key.pKey) - { - DWORD type; - DWORD nameSizeInBytes = DWORD(name.getSizeInBytes()); - DWORD pathSizeInBytes = DWORD(path.getSizeInBytes()); - LONG result = RegEnumValueW((HKEY)key.pKey, index, name.getPtr(), &nameSizeInBytes, NULL, &type, (BYTE*)path.getPtr(), &pathSizeInBytes); - if (result == ERROR_SUCCESS) - { - return true; - } - } - return false; -} - -bool CEngineSettingsBackendWin32::StoreEngineSettingsToRegistry() -{ - // make sure the path in registry exists - { - RegKey key0(REG_SOFTWARE REG_COMPANY_NAME, true); - if (!key0.pKey) - { - RegKey software(REG_SOFTWARE, true); - HKEY hKey; - RegCreateKeyW((HKEY)software.pKey, REG_COMPANY_NAME, &hKey); - if (!hKey) - { - return false; - } - } - - RegKey key1(REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME, true); - if (!key1.pKey) - { - RegKey softwareCompany(REG_SOFTWARE REG_COMPANY_NAME, true); - HKEY hKey; - RegCreateKeyW((HKEY)softwareCompany.pKey, REG_COMPANY_NAME, &hKey); - if (!hKey) - { - return false; - } - } - - RegKey key2(REG_BASE_SETTING_KEY, true); - if (!key2.pKey) - { - RegKey softwareCompanyProduct(REG_SOFTWARE REG_COMPANY_NAME REG_PRODUCT_NAME, true); - HKEY hKey; - RegCreateKeyW((HKEY)key2.pKey, REG_SETTING, &hKey); - if (!hKey) - { - return false; - } - } - } - - bool bRet = true; - - RegKey key(REG_BASE_SETTING_KEY, true); - if (!key.pKey) - { - bRet = false; - } - else - { - wchar_t buffer[1024]; - - // ResourceCompiler Specific - - if (parent()->GetValueByRef("RC_ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_ShowWindow", b); - } - - if (parent()->GetValueByRef("RC_HideCustom", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_HideCustom", b); - } - - if (parent()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - SetRegValue(key.pKey, "RC_Parameters", buffer); - } - - if (parent()->GetValueByRef("RC_EnableSourceControl", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - const bool b = wcscmp(buffer, L"true") == 0; - SetRegValue(key.pKey, "RC_EnableSourceControl", b); - } - } - - return bRet; -} - -void CEngineSettingsBackendWin32::LoadEngineSettingsFromRegistry() -{ - wchar_t buffer[1024]; - - bool bResult; - - // Engine Specific (Deprecated value) - RegKey key(REG_BASE_SETTING_KEY, false); - if (key.pKey) - { - if (GetRegValue(key.pKey, "RootPath", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("ENG_RootPath", buffer); - } - - // Engine Specific - if (GetRegValue(key.pKey, "ENG_RootPath", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("ENG_RootPath", buffer); - } - - // ResourceCompiler Specific - if (GetRegValue(key.pKey, "RC_ShowWindow", bResult)) - { - parent()->SetKey("RC_ShowWindow", bResult); - } - if (GetRegValue(key.pKey, "RC_HideCustom", bResult)) - { - parent()->SetKey("RC_HideCustom", bResult); - } - if (GetRegValue(key.pKey, "RC_Parameters", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - parent()->SetKey("RC_Parameters", buffer); - } - if (GetRegValue(key.pKey, "RC_EnableSourceControl", bResult)) - { - parent()->SetKey("RC_EnableSourceControl", bResult); - } - } -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, const wchar_t* value) -{ - CFixedString name; - name.appendAscii(valueName); - - size_t const sizeInBytes = (wcslen(value) + 1) * sizeof(value[0]); - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_SZ, (BYTE*)value, DWORD(sizeInBytes))); -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, bool value) -{ - CFixedString name; - name.appendAscii(valueName); - - DWORD dwVal = value; - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_DWORD, (BYTE*)&dwVal, sizeof(dwVal))); -} - -bool CEngineSettingsBackendWin32::SetRegValue(void* key, const char* valueName, int value) -{ - CFixedString name; - name.appendAscii(valueName); - - DWORD dwVal = value; - return (ERROR_SUCCESS == RegSetValueExW((HKEY)key, name.c_str(), 0, REG_DWORD, (BYTE*)&dwVal, sizeof(dwVal))); -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - CFixedString name; - name.appendAscii(valueName); - - DWORD type; - DWORD sizeInBytes = DWORD(wbuffer.getSizeInBytes()); - if (ERROR_SUCCESS != RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)wbuffer.getPtr(), &sizeInBytes)) - { - wbuffer[0] = 0; - return false; - } - - const size_t sizeInElements = sizeInBytes / sizeof(wbuffer[0]); - if (sizeInElements > wbuffer.getSizeInElements()) // paranoid check - { - wbuffer[0] = 0; - return false; - } - - // According to MSDN documentation for RegQueryValueEx(), strings returned by the function - // are not zero-terminated sometimes, so we need to terminate them by ourselves. - if (wbuffer[sizeInElements - 1] != 0) - { - if (sizeInElements >= wbuffer.getSizeInElements()) - { - // No space left to put terminating zero character - wbuffer[0] = 0; - return false; - } - wbuffer[sizeInElements] = 0; - } - - return true; -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, bool& value) -{ - CFixedString name; - name.appendAscii(valueName); - - // Open the appropriate registry key - DWORD type, dwVal = 0, size = sizeof(dwVal); - bool res = (ERROR_SUCCESS == RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)&dwVal, &size)); - if (res) - { - value = (dwVal != 0); - } - else - { - wchar_t buffer[100]; - res = GetRegValue(key, valueName, CWCharBuffer(buffer, sizeof(buffer))); - if (res) - { - value = (wcscmp(buffer, L"true") == 0); - } - } - return res; -} - -bool CEngineSettingsBackendWin32::GetRegValue(void* key, const char* valueName, int& value) -{ - CFixedString name; - name.appendAscii(valueName); - - // Open the appropriate registry key - DWORD type, dwVal = 0, size = sizeof(dwVal); - - bool res = (ERROR_SUCCESS == RegQueryValueExW((HKEY)key, name.c_str(), NULL, &type, (BYTE*)&dwVal, &size)); - if (res) - { - value = dwVal; - } - - return res; -} - -#endif // AZ_PLATFORM_WINDOWS -#endif // CRY_ENABLE_RC_HELPER diff --git a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h b/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h deleted file mode 100644 index 47b4772ede..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsBackendWin32.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H -#pragma once - -#include "EngineSettingsBackend.h" - -#ifdef CRY_ENABLE_RC_HELPER - -class CEngineSettingsManager; - -class CEngineSettingsBackendWin32 : public CEngineSettingsBackend -{ -public: - CEngineSettingsBackendWin32(CEngineSettingsManager* parent, const wchar_t* moduleName = NULL); - - std::wstring GetModuleFilePath() const override; - - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) override; - bool GetModuleSpecificIntEntry(const char* key, int& value) override; - bool GetModuleSpecificBoolEntry(const char* key, bool& value) override; - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) override; - bool SetModuleSpecificIntEntry(const char* key, const int& value) override; - bool SetModuleSpecificBoolEntry(const char* key, const bool& value) override; - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) override; - - void LoadEngineSettingsFromRegistry() override; - bool StoreEngineSettingsToRegistry() override; - -protected: - bool SetRegValue(void* key, const char* valueName, const wchar_t* value); - bool SetRegValue(void* key, const char* valueName, bool value); - bool SetRegValue(void* key, const char* valueName, int value); - bool GetRegValue(void* key, const char* valueName, SettingsManagerHelpers::CWCharBuffer wbuffer); - bool GetRegValue(void* key, const char* valueName, bool& value); - bool GetRegValue(void* key, const char* valueName, int& value); -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSBACKENDWIN32_H diff --git a/Code/CryEngine/CryCommon/EngineSettingsManager.cpp b/Code/CryEngine/CryCommon/EngineSettingsManager.cpp deleted file mode 100644 index 13ad568217..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsManager.cpp +++ /dev/null @@ -1,479 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#include "ProjectDefines.h" -#include "EngineSettingsManager.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include // assert() -#include "EngineSettingsBackend.h" - -#include "AzCore/PlatformDef.h" -#include "platform.h" - -#if defined(AZ_PLATFORM_WINDOWS) -#include "EngineSettingsBackendWin32.h" -#include -#elif AZ_TRAIT_OS_PLATFORM_APPLE -#include "EngineSettingsBackendApple.h" -#endif - - -#include -#include - -#define INFOTEXT L"Please specify the directory of your CryENGINE installation (RootPath):" - - -using namespace SettingsManagerHelpers; - - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -CEngineSettingsManager::CEngineSettingsManager(const wchar_t* moduleName, const wchar_t* iniFileName) - : m_hWndParent(0) - , m_backend(NULL) -{ - m_sModuleName.clear(); - -#if defined(AZ_PLATFORM_WINDOWS) - m_backend = new CEngineSettingsBackendWin32(this, moduleName); -#elif AZ_TRAIT_OS_PLATFORM_APPLE - m_backend = new CEngineSettingsBackendApple(this, moduleName); -#endif - assert(m_backend); - - // std initialization - RestoreDefaults(); - - // try to load content from INI file - if (moduleName != NULL) - { - m_sModuleName = moduleName; - - if (iniFileName == NULL) - { - // find INI filename located in module path - m_sModuleFileName = m_backend->GetModuleFilePath().c_str(); - } - else - { - m_sModuleFileName = iniFileName; - } - - if (LoadValuesFromConfigFile(m_sModuleFileName.c_str())) - { - m_bGetDataFromBackend = false; - return; - } - } - - m_bGetDataFromBackend = true; - - // load basic content from registry - LoadEngineSettingsFromRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -CEngineSettingsManager::~CEngineSettingsManager() -{ - delete m_backend, m_backend = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::RestoreDefaults() -{ - // Engine - SetKey("ENG_RootPath", L""); - - // RC - SetKey("RC_ShowWindow", false); - SetKey("RC_HideCustom", false); - SetKey("RC_Parameters", L""); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - wbuffer[0] = 0; - return false; - } - if (!GetValueByRef(key, wbuffer)) - { - wbuffer[0] = 0; - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificStringEntryUtf16(key, wbuffer); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificStringEntryUtf8(const char* key, SettingsManagerHelpers::CCharBuffer buffer) -{ - if (buffer.getSizeInElements() <= 0) - { - return false; - } - - wchar_t wBuffer[1024]; - - if (!GetModuleSpecificStringEntryUtf16(key, SettingsManagerHelpers::CWCharBuffer(wBuffer, sizeof(wBuffer)))) - { - buffer[0] = 0; - return false; - } - - SettingsManagerHelpers::ConvertUtf16ToUtf8(wBuffer, buffer); - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificIntEntry(const char* key, int& value) -{ - value = 0; - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - return false; - } - if (!GetValueByRef(key, value)) - { - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificIntEntry(key, value); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetModuleSpecificBoolEntry(const char* key, bool& value) -{ - value = false; - - if (!m_bGetDataFromBackend) - { - if (!HasKey(key)) - { - return false; - } - if (!GetValueByRef(key, value)) - { - return false; - } - } - else - { - assert(m_backend); - return m_backend->GetModuleSpecificBoolEntry(key, value); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str) -{ - SetKey(key, str); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificStringEntryUtf16(key, str); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificIntEntry(const char* key, const int& value) -{ - SetKey(key, value); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificIntEntry(key, value); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificBoolEntry(const char* key, const bool& value) -{ - SetKey(key, value); - if (!m_bGetDataFromBackend) - { - return StoreData(); - } - - assert(m_backend); - return m_backend->SetModuleSpecificBoolEntry(key, value); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::SetModuleSpecificStringEntryUtf8(const char* key, const char* str) -{ - wchar_t wbuffer[512]; - SettingsManagerHelpers::ConvertUtf8ToUtf16(str, SettingsManagerHelpers::CWCharBuffer(wbuffer, sizeof(wbuffer))); - - return SetModuleSpecificStringEntryUtf16(key, wbuffer); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::HasKey(const char* key) -{ - return m_keyValueArray.find(key) != 0; -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, const wchar_t* value) -{ - m_keyValueArray.set(key, value); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, bool value) -{ - m_keyValueArray.set(key, (value ? L"true" : L"false")); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetKey(const char* key, int value) -{ - m_keyValueArray.set(key, std::to_wstring(value).c_str()); -} - -bool CEngineSettingsManager::GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) -{ - assert(m_backend); - return m_backend->GetInstalledBuildRootPathUtf16(index, name, path); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::SetParentDialog(size_t window) -{ - m_hWndParent = window; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::StoreData() -{ - if (m_bGetDataFromBackend) - { - bool res = StoreEngineSettingsToRegistry(); - - if (!res) - { -#ifdef AZ_PLATFORM_WINDOWS - MessageBoxA(reinterpret_cast(m_hWndParent), "Could not store data to registry.", "Error", MB_OK | MB_ICONERROR); -#endif - } - return res; - } - - // store data to INI file - - FILE* file; -#ifdef AZ_PLATFORM_WINDOWS - _wfopen_s(&file, m_sModuleFileName.c_str(), L"wb"); -#else - char fname[MAX_PATH]; - memset(fname, 0, MAX_PATH); - wcstombs(fname, m_sModuleFileName.c_str(), MAX_PATH); - file = fopen(fname, "wb"); -#endif - if (file == NULL) - { - return false; - } - - char buffer[2048]; - - for (size_t i = 0; i < m_keyValueArray.size(); ++i) - { - const SKeyValue& kv = m_keyValueArray[i]; - - fprintf_s(file, kv.key.c_str()); - fprintf_s(file, " = "); - - if (kv.value.length() > 0) - { - SettingsManagerHelpers::ConvertUtf16ToUtf8(kv.value.c_str(), SettingsManagerHelpers::CCharBuffer(buffer, sizeof(buffer))); - fprintf_s(file, "%s", buffer); - } - - fprintf_s(file, "\r\n"); - } - - fclose(file); - - return true; -} - - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::LoadValuesFromConfigFile(const wchar_t* szFileName) -{ - m_keyValueArray.clear(); - - // read file to memory - - FILE* file; -#ifdef AZ_PLATFORM_WINDOWS - _wfopen_s(&file, szFileName, L"rb"); -#else - char fname[MAX_PATH]; - memset(fname, 0, MAX_PATH); - wcstombs(fname, szFileName, MAX_PATH); - file = fopen(fname, "rb"); -#endif - if (file == NULL) - { - return false; - } - - fseek(file, 0, SEEK_END); - long size = ftell(file); - fseek(file, 0, SEEK_SET); - char* data = new char[size + 1]; - fread_s(data, size, 1, size, file); - fclose(file); - - wchar_t wBuffer[1024]; - - // parse file for root path - - int start = 0, end = 0; - while (end < size) - { - while (end < size && data[end] != '\n') - { - end++; - } - - memcpy(data, &data[start], end - start); - data[end - start] = 0; - start = end = end + 1; - - CFixedString line(data); - size_t equalsOfs; - for (equalsOfs = 0; equalsOfs < line.length(); ++equalsOfs) - { - if (line[equalsOfs] == '=') - { - break; - } - } - if (equalsOfs < line.length()) - { - CFixedString key; - CFixedString value; - - key.appendAscii(line.c_str(), equalsOfs); - key.trim(); - - SettingsManagerHelpers::ConvertUtf8ToUtf16(line.c_str() + equalsOfs + 1, SettingsManagerHelpers::CWCharBuffer(wBuffer, sizeof(wBuffer))); - value.append(wBuffer); - value.trim(); - - m_keyValueArray.set(key.c_str(), value.c_str()); - } - } - delete[] data; - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::StoreEngineSettingsToRegistry() -{ - assert(m_backend); - return m_backend->StoreEngineSettingsToRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -void CEngineSettingsManager::LoadEngineSettingsFromRegistry() -{ - assert(m_backend); - m_backend->LoadEngineSettingsFromRegistry(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) const -{ - if (wbuffer.getSizeInElements() <= 0) - { - return false; - } - - const SKeyValue* p = m_keyValueArray.find(key); - if (!p || (p->value.length() + 1) > wbuffer.getSizeInElements()) - { - wbuffer[0] = 0; - return false; - } - azwcscpy(wbuffer.getPtr(), wbuffer.getSizeInElements(), p->value.c_str()); - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, bool& value) const -{ - wchar_t buffer[100]; - if (!GetValueByRef(key, SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - return false; - } - value = (wcscmp(buffer, L"true") == 0); - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CEngineSettingsManager::GetValueByRef(const char* key, int& value) const -{ - wchar_t buffer[100]; - if (!GetValueByRef(key, SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer)))) - { - return false; - } - value = wcstol(buffer, 0, 10); - return true; -} - -#endif //(CRY_ENABLE_RC_HELPER) diff --git a/Code/CryEngine/CryCommon/EngineSettingsManager.h b/Code/CryEngine/CryCommon/EngineSettingsManager.h deleted file mode 100644 index 95216b3bf3..0000000000 --- a/Code/CryEngine/CryCommon/EngineSettingsManager.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H -#define CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H -#pragma once - -#include "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "SettingsManagerHelpers.h" - -class CEngineSettingsBackend; - -////////////////////////////////////////////////////////////////////////// -// Manages storage and loading of all information for tools and CryENGINE, by either registry or an INI file. -// Information can be read and set by key-to-value functions. -// Specific information can be set by a dialog application called by this class. -// If the engine root path is not found, a fall-back dialog is opened. -class CEngineSettingsManager -{ -public: - // prepares CEngineSettingsManager to get requested information either from registry or an INI file, - // if existent as a file with name an directory equal to the module, or from registry. - CEngineSettingsManager(const wchar_t* moduleName = NULL, const wchar_t* iniFileName = NULL); - ~CEngineSettingsManager(); - - void RestoreDefaults(); - - // stores/loads user specific information for modules to/from registry or INI file - bool GetModuleSpecificStringEntryUtf16(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer); - bool GetModuleSpecificStringEntryUtf8(const char* key, SettingsManagerHelpers::CCharBuffer buffer); - bool GetModuleSpecificIntEntry(const char* key, int& value); - bool GetModuleSpecificBoolEntry(const char* key, bool& value); - - bool SetModuleSpecificStringEntryUtf16(const char* key, const wchar_t* str); - bool SetModuleSpecificStringEntryUtf8(const char* key, const char* str); - bool SetModuleSpecificIntEntry(const char* key, const int& value); - bool SetModuleSpecificBoolEntry(const char* key, const bool& value); - - bool GetValueByRef(const char* key, SettingsManagerHelpers::CWCharBuffer wbuffer) const; - bool GetValueByRef(const char* key, bool& value) const; - bool GetValueByRef(const char* key, int& value) const; - - void SetKey(const char* key, const wchar_t* value); - void SetKey(const char* key, bool value); - void SetKey(const char* key, int value); - - bool StoreData(); - - bool GetInstalledBuildRootPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path); - - void SetParentDialog(size_t window); - -private: - bool HasKey(const char* key); - - void LoadEngineSettingsFromRegistry(); - bool StoreEngineSettingsToRegistry(); - - // parses a file and stores all flags in a private key-value-map - bool LoadValuesFromConfigFile(const wchar_t* szFileName); - -private: - CEngineSettingsBackend *m_backend; - - SettingsManagerHelpers::CFixedString m_sModuleName; // name to store key-value pairs of modules in (registry) or to identify INI file - SettingsManagerHelpers::CFixedString m_sModuleFileName; // used in case of data being loaded from INI file - bool m_bGetDataFromBackend; - SettingsManagerHelpers::CKeyValueArray<30> m_keyValueArray; - - void* m_hBtnBrowse; - size_t m_hWndParent; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_ENGINESETTINGSMANAGER_H diff --git a/Code/CryEngine/CryCommon/IFlares.h b/Code/CryEngine/CryCommon/IFlares.h deleted file mode 100644 index d1626a83d9..0000000000 --- a/Code/CryEngine/CryCommon/IFlares.h +++ /dev/null @@ -1,228 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_IFLARES_H -#define CRYINCLUDE_CRYCOMMON_IFLARES_H -#pragma once - -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include "smartptr.h" - -struct IShader; -class CCamera; - -class __MFPA -{ -}; -class __MFPB -{ -}; -#define MFP_SIZE_ENFORCE : public __MFPA, public __MFPB - -enum EFlareType -{ - eFT__Base__, - eFT_Root, - eFT_Group, - eFT_Ghost, - eFT_MultiGhosts, - eFT_Glow, - eFT_ChromaticRing, - eFT_IrisShafts, - eFT_CameraOrbs, - eFT_ImageSpaceShafts, - eFT_Streaks, - eFT_Reference, - eFT_Proxy, - eFT_Max -}; - -#define FLARE_LIBS_PATH "libs/flares/" -#define FLARE_EXPORT_FILE "LensFlareList.xml" -#define FLARE_EXPORT_FILE_VERSION "1" - -struct FlareInfo -{ - EFlareType type; - const char* name; -#if defined(FLARES_SUPPORT_EDITING) - const char* imagename; -#endif -}; - -#if defined(FLARES_SUPPORT_EDITING) -# define ADD_FLARE_INFO(type, name, imagename) {type, name, imagename} -#else -# define ADD_FLARE_INFO(type, name, imagename) {type, name} -#endif - -class FlareInfoArray -{ -public: - struct Props - { - const FlareInfo* p; - size_t size; - }; - - static const Props Get() - { - static const FlareInfo flareInfoArray[] = - { - ADD_FLARE_INFO(eFT__Base__, "__Base__", NULL), - ADD_FLARE_INFO(eFT_Root, "Root", NULL), - ADD_FLARE_INFO(eFT_Group, "Group", NULL), - ADD_FLARE_INFO(eFT_Ghost, "Ghost", "EngineAssets/Textures/flares/icons/ghost.dds"), - ADD_FLARE_INFO(eFT_MultiGhosts, "Multi Ghost", "EngineAssets/Textures/flares/icons/multi_ghost.dds"), - ADD_FLARE_INFO(eFT_Glow, "Glow", "EngineAssets/Textures/flares/icons/glow.dds"), - ADD_FLARE_INFO(eFT_ChromaticRing, "ChromaticRing", "EngineAssets/Textures/flares/icons/ring.dds"), - ADD_FLARE_INFO(eFT_IrisShafts, "IrisShafts", "EngineAssets/Textures/flares/icons/iris_shafts.dds"), - ADD_FLARE_INFO(eFT_CameraOrbs, "CameraOrbs", "EngineAssets/Textures/flares/icons/orbs.dds"), - ADD_FLARE_INFO(eFT_ImageSpaceShafts, "Vol Shafts", "EngineAssets/Textures/flares/icons/vol_shafts.dds"), - ADD_FLARE_INFO(eFT_Streaks, "Streaks", "EngineAssets/Textures/flares/icons/iris_shafts.dds") - }; - - Props ret; - ret.p = flareInfoArray; - ret.size = sizeof(flareInfoArray) / sizeof(flareInfoArray[0]); - return ret; - } - -private: - FlareInfoArray(); - ~FlareInfoArray(); -}; - -struct SLensFlareRenderParam -{ - SLensFlareRenderParam() - : pCamera(NULL) - , pShader(NULL) - { - } - ~SLensFlareRenderParam(){} - bool IsValid() const - { - return pCamera && pShader; - } - CCamera* pCamera; - IShader* pShader; -}; - -class ISoftOcclusionQuery -{ -public: - // - virtual ~ISoftOcclusionQuery() {} - - virtual void AddRef() = 0; - virtual void Release() = 0; - // -}; - -class IOpticsElementBase MFP_SIZE_ENFORCE -{ -public: - - IOpticsElementBase() - : m_nRefCount(0) - { - } - void AddRef() - { - CryInterlockedIncrement(&m_nRefCount); - } - void Release() - { - if (CryInterlockedDecrement(&m_nRefCount) <= 0) - { - delete this; - } - } - - // - virtual EFlareType GetType() = 0; - virtual bool IsGroup() const = 0; - virtual string GetName() const = 0; - virtual void SetName(const char* ch_name) = 0; - virtual void Load(IXmlNode* pNode) = 0; - - virtual IOpticsElementBase* GetParent() const = 0; - virtual ~IOpticsElementBase() { - } - - virtual bool IsEnabled() const = 0; - - virtual void AddElement(IOpticsElementBase* pElement) = 0; - virtual void InsertElement(int nPos, IOpticsElementBase* pElement) = 0; - virtual void Remove(int i) = 0; - virtual void RemoveAll() = 0; - virtual int GetElementCount() const = 0; - virtual IOpticsElementBase* GetElementAt(int i) const = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - virtual void Invalidate() = 0; - - virtual void Render(SLensFlareRenderParam* pParam, const Vec3& vPos) = 0; - - virtual void SetOpticsReference([[maybe_unused]] IOpticsElementBase* pReference) {} - virtual IOpticsElementBase* GetOpticsReference() const { return NULL; } - // - -#if defined(FLARES_SUPPORT_EDITING) - virtual AZStd::vector GetEditorParamGroups() = 0; -#endif - - ///Basic Setters/////////////////////////////////////////////////////////////// - virtual void SetEnabled(bool enabled) { (void)enabled; } - virtual void SetSize(float size) { (void)size; } - virtual void SetPerspectiveFactor(float perspectiveFactor) { (void)perspectiveFactor; } - virtual void SetDistanceFadingFactor(float distanceFadingFactor) { (void)distanceFadingFactor; } - virtual void SetBrightness(float brightness) { (void)brightness; } - virtual void SetColor(ColorF color) { (void)color; } - virtual void SetMovement(Vec2 movement) { (void)movement; } - virtual void SetTransform(const Matrix33& xform) { (void)xform; } - virtual void SetOccBokehEnabled(bool occBokehEnabled) { (void)occBokehEnabled; } - virtual void SetOrbitAngle(float orbitAngle) { (void)orbitAngle; } - virtual void SetSensorSizeFactor(float sizeFactor) { (void)sizeFactor; } - virtual void SetSensorBrightnessFactor(float brightnessFactor) { (void)brightnessFactor; } - virtual void SetAutoRotation(bool autoRotation) { (void)autoRotation; } - virtual void SetAspectRatioCorrection(bool aspectRatioCorrection) { (void)aspectRatioCorrection; } - //////////////////////////////////////////////////////////////////////////////// - -private: - - volatile int m_nRefCount; -}; - -class IOpticsManager -{ -public: - // - virtual ~IOpticsManager(){} - virtual void Reset() = 0; - virtual IOpticsElementBase* Create(EFlareType type) const = 0; - virtual bool Load(const char* fullFlareName, int& nOutIndex, bool forceReload = false) = 0; - virtual bool Load(XmlNodeRef& rootNode, int& nOutIndex) = 0; - virtual IOpticsElementBase* GetOptics(int nIndex) = 0; - virtual bool AddOptics(IOpticsElementBase* pOptics, const char* name, int& nOutNewIndex, bool allowReplace = false) = 0; - virtual bool Rename(const char* fullFlareName, const char* newFullFlareName) = 0; - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - virtual void Invalidate() = 0; - // -}; - -typedef _smart_ptr IOpticsElementBasePtr; - -#endif // CRYINCLUDE_CRYCOMMON_IFLARES_H diff --git a/Code/CryEngine/CryCommon/IMaterialEffects.h b/Code/CryEngine/CryCommon/IMaterialEffects.h deleted file mode 100644 index 73e03a1d80..0000000000 --- a/Code/CryEngine/CryCommon/IMaterialEffects.h +++ /dev/null @@ -1,504 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Interface to the Material Effects System - - -#ifndef CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H -#define CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H -#pragma once - -#if !defined(_RELEASE) - #define MATERIAL_EFFECTS_DEBUG -#endif - - -#include "CryFixedArray.h" - -struct IRenderNode; -struct ISurfaceType; - -////////////////////////////////////////////////////////////////////////// -enum EMFXPlayFlags -{ - eMFXPF_Disable_Delay = BIT(0), - eMFXPF_Audio = BIT(1), - eMFXPF_Decal = BIT(2), - eMFXPF_Particles = BIT(3), - eMFXPF_Deprecated0 = BIT(4), // formerly eMFXPF_Flowgraph - eMFXPF_ForceFeedback = BIT(5), - eMFXPF_All = (eMFXPF_Audio | eMFXPF_Decal | eMFXPF_Particles | eMFXPF_Deprecated0 | eMFXPF_ForceFeedback), -}; - -#define MFX_INVALID_ANGLE (gf_PI2 + 1) - -////////////////////////////////////////////////////////////////////////// -struct SMFXAudioEffectRtpc -{ - SMFXAudioEffectRtpc() - { - rtpcName = ""; - rtpcValue = 0.0f; - } - const char* rtpcName; - float rtpcValue; -}; - -////////////////////////////////////////////////////////////////////////// -struct SMFXRunTimeEffectParams -{ - static const int MAX_AUDIO_RTPCS = 4; - - SMFXRunTimeEffectParams() - : playSoundFP(false) - , playflags(eMFXPF_All) - , fLastTime(0.0f) - , srcSurfaceId(0) - , trgSurfaceId(0) - , srcRenderNode(0) - , trgRenderNode(0) - , partID(0) - , pos(ZERO) - , decalPos(ZERO) - , normal(0.0f, 0.0f, 1.0f) - , angle(MFX_INVALID_ANGLE) - , scale(1.0f) - , audioComponentOffset(ZERO) - , numAudioRtpcs(0) - , fDecalPlacementTestMaxSize(1000.f) - { - dir[0].Set(0.0f, 0.0f, -1.0f); - dir[1].Set(0.0f, 0.0f, 1.0f); - } - - bool AddAudioRtpc(const char* name, float val) - { - if (numAudioRtpcs < MAX_AUDIO_RTPCS) - { - audioRtpcs[numAudioRtpcs].rtpcName = name; - audioRtpcs[numAudioRtpcs].rtpcValue = val; - ++numAudioRtpcs; - return true; - } - return false; - } - - void ResetAudioRtpcs() - { - numAudioRtpcs = 0; - } - -public: - uint16 playSoundFP; // Sets 1p/3p audio switch - uint16 playflags; // See EMFXPlayFlags - float fLastTime; // Last time this effect was played - float fDecalPlacementTestMaxSize; - - int srcSurfaceId; - int trgSurfaceId; - IRenderNode* srcRenderNode; - IRenderNode* trgRenderNode; - int partID; - - Vec3 pos; - Vec3 decalPos; - Vec3 dir[2]; - Vec3 normal; - float angle; - float scale; - - // audio related - Vec3 audioComponentOffset; // in case of audio component, uses this offset - - SMFXAudioEffectRtpc audioRtpcs[MAX_AUDIO_RTPCS]; - uint32 numAudioRtpcs; -}; - -struct SMFXBreakageParams -{ - enum EBreakageRequestFlags - { - eBRF_Matrix = BIT(0), - eBRF_HitPos = BIT(1), - eBRF_HitImpulse = BIT(2), - eBRF_Velocity = BIT(3), - eBRF_ExplosionImpulse = BIT(4), - eBRF_Mass = BIT(5), - eBFR_Entity = BIT(6), - }; - - SMFXBreakageParams() - : m_flags(0) - , m_worldTM(IDENTITY) - , m_vHitPos(ZERO) - , m_vHitImpulse(IDENTITY) - , m_vVelocity(ZERO) - , m_fExplosionImpulse(1.0f) - , m_fMass(0.0f) - { - } - - - // Matrix - void SetMatrix(const Matrix34& worldTM) - { - m_worldTM = worldTM; - SetFlag(eBRF_Matrix); - } - - const Matrix34& GetMatrix() const - { - return m_worldTM; - } - - // HitPos - void SetHitPos(const Vec3& vHitPos) - { - m_vHitPos = vHitPos; - SetFlag(eBRF_HitPos); - } - - const Vec3& GetHitPos() const - { - return m_vHitPos; - } - - // HitImpulse - void SetHitImpulse(const Vec3& vHitImpulse) - { - m_vHitImpulse = vHitImpulse; - SetFlag(eBRF_HitImpulse); - } - - const Vec3& GetHitImpulse() const - { - return m_vHitImpulse; - } - - // Velocity - void SetVelocity(const Vec3& vVelocity) - { - m_vVelocity = vVelocity; - SetFlag(eBRF_Velocity); - } - - const Vec3& GetVelocity() const - { - return m_vVelocity; - } - - // Explosion Impulse - void SetExplosionImpulse(float fExplosionImpulse) - { - m_fExplosionImpulse = fExplosionImpulse; - SetFlag(eBRF_ExplosionImpulse); - } - - float GetExplosionImpulse() const - { - return m_fExplosionImpulse; - } - - // Mass - void SetMass(float fMass) - { - m_fMass = fMass; - SetFlag(eBRF_Mass); - } - - float GetMass() const - { - return m_fMass; - } - - // Checking for flags - bool CheckFlag(EBreakageRequestFlags flag) const - { - return (m_flags & flag) != 0; - } - -protected: - void SetFlag(EBreakageRequestFlags flag) - { - m_flags |= flag; - } - - void ClearFlag(EBreakageRequestFlags flag) - { - m_flags &= ~flag; - } - - uint32 m_flags; - Matrix34 m_worldTM; - Vec3 m_vHitPos; - Vec3 m_vHitImpulse; - Vec3 m_vVelocity; - float m_fExplosionImpulse; - float m_fMass; -}; - -class IMFXParticleParams -{ -public: - IMFXParticleParams() - : name(NULL) - , userdata(NULL) - , scale(1.0f) - { - } - - const char* name; - const char* userdata; - float scale; -}; - -class SMFXParticleListNode -{ -public: - static SMFXParticleListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXParticleParams m_particleParams; - SMFXParticleListNode* pNext; - -private: - SMFXParticleListNode() - { - pNext = NULL; - } - ~SMFXParticleListNode() {} -}; - -class IMFXAudioParams -{ - const static uint MAX_SWITCH_DATA_ELEMENTS = 4; - -public: - - struct SSwitchData - { - SSwitchData() - : switchName(NULL) - , switchStateName(NULL) - { - } - - const char* switchName; - const char* switchStateName; - }; - - IMFXAudioParams() - : triggerName(NULL) - { - } - const char* triggerName; - - CryFixedArray triggerSwitches; -}; - -class SMFXAudioListNode -{ -public: - static SMFXAudioListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXAudioParams m_audioParams; - SMFXAudioListNode* pNext; - -private: - SMFXAudioListNode() - : pNext(NULL) - { - } - - ~SMFXAudioListNode() - { - } -}; - -class IMFXDecalParams -{ -public: - IMFXDecalParams() - { - filename = 0; - material = 0; - minscale = 1.f; - maxscale = 1.f; - rotation = -1.f; - lifetime = 10.0f; - assemble = false; - forceedge = false; - } - const char* filename; - const char* material; - float minscale; - float maxscale; - float rotation; - float lifetime; - bool assemble; - bool forceedge; -}; - -class SMFXDecalListNode -{ -public: - static SMFXDecalListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXDecalParams m_decalParams; - SMFXDecalListNode* pNext; - -private: - SMFXDecalListNode() - { - pNext = 0; - } - ~SMFXDecalListNode() {} -}; - -class IMFXForceFeedbackParams -{ -public: - IMFXForceFeedbackParams() - : forceFeedbackEventName (NULL) - , intensityFallOffMinDistanceSqr(0.0f) - , intensityFallOffMaxDistanceSqr(0.0f) - { - } - - const char* forceFeedbackEventName; - float intensityFallOffMinDistanceSqr; - float intensityFallOffMaxDistanceSqr; -}; - -class SMFXForceFeedbackListNode -{ -public: - static SMFXForceFeedbackListNode* Create(); - void Destroy(); - static void FreePool(); - - IMFXForceFeedbackParams m_forceFeedbackParams; - SMFXForceFeedbackListNode* pNext; - -private: - SMFXForceFeedbackListNode() - : pNext(NULL) - { - } - ~SMFXForceFeedbackListNode() {} -}; - -struct SMFXResourceList; -typedef _smart_ptr SMFXResourceListPtr; - -struct SMFXResourceList -{ -public: - SMFXParticleListNode* m_particleList; - SMFXAudioListNode* m_audioList; - SMFXDecalListNode* m_decalList; - SMFXForceFeedbackListNode* m_forceFeedbackList; - - void AddRef() { ++m_refs; } - void Release() - { - if (--m_refs <= 0) - { - Destroy(); - } - } - - static SMFXResourceListPtr Create(); - static void FreePool(); - -private: - int m_refs; - - virtual void Destroy(); - - SMFXResourceList() - : m_refs(0) - { - m_particleList = 0; - m_audioList = 0; - m_decalList = 0; - m_forceFeedbackList = 0; - } - virtual ~SMFXResourceList() - { - while (m_particleList != 0) - { - SMFXParticleListNode* next = m_particleList->pNext; - m_particleList->Destroy(); - m_particleList = next; - } - while (m_audioList != 0) - { - SMFXAudioListNode* next = m_audioList->pNext; - m_audioList->Destroy(); - m_audioList = next; - } - while (m_decalList != 0) - { - SMFXDecalListNode* next = m_decalList->pNext; - m_decalList->Destroy(); - m_decalList = next; - } - while (m_forceFeedbackList != 0) - { - SMFXForceFeedbackListNode* next = m_forceFeedbackList->pNext; - m_forceFeedbackList->Destroy(); - m_forceFeedbackList = next; - } - } -}; - -typedef uint16 TMFXEffectId; -static const TMFXEffectId InvalidEffectId = 0; - -struct SMFXCustomParamValue -{ - float fValue; -}; - -////////////////////////////////////////////////////////////////////////// -struct IMaterialEffects -{ - // - virtual ~IMaterialEffects(){} - virtual void LoadFXLibraries() = 0; - virtual void Reset(bool bCleanup) = 0; - virtual void ClearDelayedEffects() = 0; - virtual TMFXEffectId GetEffectIdByName(const char* libName, const char* effectName) = 0; - virtual TMFXEffectId GetEffectId(int surfaceIndex1, int surfaceIndex2) = 0; - virtual TMFXEffectId GetEffectId(const char* customName, int surfaceIndex2) = 0; - virtual SMFXResourceListPtr GetResources(TMFXEffectId effectId) const = 0; - virtual void PreLoadAssets() = 0; - virtual bool ExecuteEffect(TMFXEffectId effectId, SMFXRunTimeEffectParams& runtimeParams) = 0; - virtual int GetDefaultSurfaceIndex() = 0; - virtual int GetDefaultCanopyIndex() = 0; - - virtual bool PlayBreakageEffect(ISurfaceType* pSurfaceType, const char* breakageType, const SMFXBreakageParams& mfxBreakageParams) = 0; - - virtual void SetCustomParameter(TMFXEffectId effectId, const char* customParameter, const SMFXCustomParamValue& customParameterValue) = 0; - - virtual void CompleteInit() = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_IMATERIALEFFECTS_H diff --git a/Code/CryEngine/CryCommon/INotificationNetwork.h b/Code/CryEngine/CryCommon/INotificationNetwork.h deleted file mode 100644 index 9ad44b24ab..0000000000 --- a/Code/CryEngine/CryCommon/INotificationNetwork.h +++ /dev/null @@ -1,147 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H -#define CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H -#pragma once - - -// Constants - -#define NN_CHANNEL_NAME_LENGTH_MAX 16 - -struct INotificationNetworkClient; - -// User Interfaces - -struct INotificationNetworkListener -{ - // - virtual ~INotificationNetworkListener(){} - // Called upon receiving data from the Channel the Listener is binded to. - virtual void OnNotificationNetworkReceive(const void* pBuffer, size_t length) = 0; - // -}; - -struct INotificationNetworkConnectionCallback -{ - // - virtual ~INotificationNetworkConnectionCallback(){} - virtual void OnConnect(INotificationNetworkClient* pClient, bool bSucceeded) = 0; - virtual void OnDisconnected(INotificationNetworkClient* pClient) = 0; - // -}; - -// Interfaces - -struct INotificationNetworkClient -{ - // - virtual ~INotificationNetworkClient(){} - virtual void Release() = 0; - - // Binds a Listener to the given Notification Channel. - // Each Listener can be binded only to one Channel, calling the method - // again with an already added Listener and a different Channel will rebind it. - // The Channel name cannot exceed NN_CHANNEL_NAME_LENGTH_MAX chars. - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener) = 0; - - // If it exist, removes the given Listener form the Notification Network. - virtual bool ListenerRemove(INotificationNetworkListener* pListener) = 0; - - // Sends arbitrary data to the Notification Network the Client is connected to. - virtual bool Send(const char* channelName, const void* pBuffer, size_t length) = 0; - - // Checks if the current client is connected. - // Returns true if it is connected, false otherwise. - virtual bool IsConnected() = 0; - - // Checks if the connection attempt failed. - // Returns true if it failed to connect by any reason (such as timeout). - virtual bool IsFailedToConnect() const = 0; - - // Start the connection request for this particular client. - // Parameters: - // address - Is the host name or ipv4 (for now) address string to which - // we want to connect. - // port - Is the TCP port to which we want to connect. - // Remarks: Port 9432 is being used by the live preview already. - virtual bool Connect(const char* address, uint16 port) = 0; - - // Tries to register a callback listener object. - // A callback listener object will receive events from the client element, - // such as connection result information. - // Parameters: - // - pConnectionCallback - Is a pointer to an object implementing interface - // INotificationNetworkConnectionCallback which will be called when - // the events happen, such as connection, disconnection and failed attempt - // to connect. - // Return Value: - // - It will return true if registered the callback object successfully. - // - It will return false when there the callback object is already - // registered. - virtual bool RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) = 0; - - // Tries to unregister a callback listener object. - // A callback listener object will receive events from the client element, - // such as connection result information. - // Parameters: - // - pConnectionCallback - Is a pointer to an object implementing interface - // INotificationNetworkConnectionCallback which will be called when - // the events happen, such as connection, disconnection and failed attempt - // to connect and that we want to unregister. - // Return Value: - // - It will return true if unregistered the callback object successfully. - // - It will return false when no object matching the one requested is found - // int the object. - virtual bool UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) = 0; - // -}; - -struct INotificationNetwork -{ - // - virtual ~INotificationNetwork(){} - - virtual void Release() = 0; - - // Creates a disconnected client. - virtual INotificationNetworkClient* CreateClient() = 0; - - // Attempts to connect to the Notification Network at the given address, - // returns a Client interface if communication is possible. - virtual INotificationNetworkClient* Connect(const char* address, uint16 port) = 0; - - // Returns the Connection count of the given Channel. If NULL is passed - // instead of a valid Channel name the total count of all Connections is - // returned. - virtual size_t GetConnectionCount(const char* channelName = NULL) = 0; - - // Has to be called from the main thread to process received notifications. - virtual void Update() = 0; - - // Binds a Listener to the given Notification Channel. - // Each Listener can be binded only to one Channel, calling the method - // again with an already added Listener and a different Channel will rebind it. - // The Channel name cannot exceed NN_CHANNEL_NAME_LENGTH_MAX chars. - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener) = 0; - - // If it exist, removes the given Listener form the Notification Network. - virtual bool ListenerRemove(INotificationNetworkListener* pListener) = 0; - - // Sends arbitrary data to all the Connections listening to the given Channel. - virtual uint32 Send(const char* channel, const void* pBuffer, size_t length) = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_INOTIFICATIONNETWORK_H diff --git a/Code/CryEngine/CryCommon/IRenderer.h b/Code/CryEngine/CryCommon/IRenderer.h index 94f8772e71..bb8f8fa572 100644 --- a/Code/CryEngine/CryCommon/IRenderer.h +++ b/Code/CryEngine/CryCommon/IRenderer.h @@ -16,12 +16,12 @@ #include "Cry_Geo.h" #include "Cry_Camera.h" #include "ITexture.h" -#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include "smartptr.h" #include #include -#include "IResourceCompilerHelper.h" // for IResourceCompilerHelper::ERcCallResult - // forward declarations struct SRenderingPassInfo; struct SRTStack; @@ -95,7 +95,6 @@ struct IFFont; struct IFFont_RenderProxy; struct STextDrawContext; struct IRenderMesh; -class IOpticsManager; struct ShadowFrustumMGPUCache; struct IAsyncTextureCompileListener; struct IClipVolume; @@ -955,25 +954,6 @@ protected: virtual ~ITextureStreamListener() {} }; -#if defined(CRY_ENABLE_RC_HELPER) -//////////////////////////////////////////////////////////////////////////// -// Listener for asynchronous texture compilation. -// Connects the listener to the task-queue of pending compilation requests. -enum ERcExitCode; -struct IAsyncTextureCompileListener -{ -public: - virtual void OnCompilationStarted(const char* source, const char* target, int nPending) = 0; - virtual void OnCompilationFinished(const char* source, const char* target, IResourceCompilerHelper::ERcCallResult nReturnCode) = 0; - - virtual void OnCompilationQueueTriggered(int nPending) = 0; - virtual void OnCompilationQueueDepleted() = 0; - -protected: - virtual ~IAsyncTextureCompileListener() {} -}; -#endif - enum eDolbyVisionMode { eDVM_Disabled, @@ -1869,8 +1849,6 @@ struct IRenderer virtual SDepthTexture* CreateDepthSurface(int nWidth, int nHeight, bool shaderResourceView = false) = 0; virtual void DestroyDepthSurface(SDepthTexture* pDepthSurf) = 0; - virtual IOpticsElementBase* CreateOptics(EFlareType type) const = 0; - // Note: // Used for pausing timer related stuff. // Example: diff --git a/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp b/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp deleted file mode 100644 index 380c94e4c7..0000000000 --- a/Code/CryEngine/CryCommon/IResourceCompilerHelper.cpp +++ /dev/null @@ -1,378 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "IResourceCompilerHelper.h" - -#include -// DO NOT USE AZSTD. - -#include // std string used here. -#include -#include - -// the following block is for _mkdir on windows and mkdir on other platforms. -#if defined(_WIN32) -# include -#else -# include -# include -#endif - -namespace RCPathUtil -{ - const char* GetExt(const char* filepath) - { - const char* str = filepath; - size_t len = strlen(filepath); - for (const char* p = str + len - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return ""; - case '.': - // there's an extension in this file name - return p + 1; - } - } - return ""; - } - - const char* GetFile(const char* filepath) - { - const size_t len = strlen(filepath); - for (const char* p = filepath + len - 1; p >= filepath; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - return p + 1; - } - } - return filepath; - } - - - //! Replace extension for given file. - std::string RemoveExtension(const char* filepath) - { - std::string filepathstr = filepath; - const char* str = filepathstr.c_str(); - for (const char* p = str + filepathstr.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return filepathstr; - case '.': - // there's an extension in this file name - filepathstr.erase(p - str); - return filepathstr; - } - } - // it seems the file name is a pure name, without path or extension - return filepathstr; - } - - std::string ReplaceExtension(const char* filepath, const char* ext) - { - std::string str = filepath; - if (ext != 0) - { - str = RemoveExtension(str.c_str()); - if (ext[0] != 0 && ext[0] != '.') - { - str += "."; - } - str += ext; - } - return str; - } - - std::string GetPath(const char* filepath) - { - std::string filepathstr = filepath; - const char* str = filepathstr.c_str(); - for (const char* p = str + filepathstr.length() - 1; p >= str; --p) - { - switch (*p) - { - case ':': - case '/': - case '\\': - // we've reached a path separator - it means there's no extension in this name - return filepathstr.substr(0, p - str); - } - } - // it seems the file name is a pure name, without path - return ""; - } - - - ////////////////////////////////////////////////////////////////////////// - bool IsRelativePath(const char* p) - { - if (!p || !p[0]) - { - return true; - } - return p[0] != '/' && p[0] != '\\' && !strchr(p, ':'); - } -} - -const char* IResourceCompilerHelper::SourceImageFormatExts[NUM_SOURCE_IMAGE_TYPE] = { "tif", "bmp", "gif", "jpg", "jpeg", "jpe", "tga", "png" }; -const char* IResourceCompilerHelper::SourceImageFormatExtsWithDot[NUM_SOURCE_IMAGE_TYPE] = { ".tif", ".bmp", ".gif", ".jpg", ".jpeg", ".jpe", ".tga", ".png" }; -const char* IResourceCompilerHelper::EngineImageFormatExts[NUM_ENGINE_IMAGE_TYPE] = { "dds" }; -const char* IResourceCompilerHelper::EngineImageFormatExtsWithDot[NUM_ENGINE_IMAGE_TYPE] = { ".dds" }; - - -IResourceCompilerHelper::ERcCallResult IResourceCompilerHelper::ConvertResourceCompilerExitCodeToResultCode(int exitCode) -{ - switch (exitCode) - { - case eRcExitCode_Success: - case eRcExitCode_UserFixing: - return eRcCallResult_success; - - case eRcExitCode_Error: - return eRcCallResult_error; - - case eRcExitCode_FatalError: - return eRcCallResult_error; - case eRcExitCode_Crash: - return eRcCallResult_crash; - } - return eRcCallResult_error; -} - - -////////////////////////////////////////////////////////////////////////// -const char* IResourceCompilerHelper::GetCallResultDescription(IResourceCompilerHelper::ERcCallResult result) -{ - switch (result) - { - case eRcCallResult_success: - return "Success."; - case eRcCallResult_notFound: - return "ResourceCompiler executable was not found."; - case eRcCallResult_error: - return "ResourceCompiler exited with an error."; - case eRcCallResult_crash: - return "ResourceCompiler crashed! Please report this. Include source asset and this log in the report."; - default: - return "Unexpected failure in ResultCompilerHelper."; - } -} - -// Arguments: -// szFilePath - could be source or destination filename -void IResourceCompilerHelper::GetOutputFilename(const char* szFilePath, char* buffer, size_t bufferSizeInBytes) -{ - if (IResourceCompilerHelper::IsSourceImageFormatSupported(szFilePath)) - { - std::string newString = RCPathUtil::ReplaceExtension(szFilePath, "dds"); - azstrncpy(buffer, bufferSizeInBytes, newString.c_str(), bufferSizeInBytes - 1); - return; - } - - azstrncpy(buffer, bufferSizeInBytes, szFilePath, bufferSizeInBytes - 1); -} - -IResourceCompilerHelper::ERcCallResult IResourceCompilerHelper::InvokeResourceCompiler(const char* szSrcFilePath, const char* szDstFilePath, const bool bUserDialog) -{ - - const char* szDstFileName = RCPathUtil::GetFile(szDstFilePath); - std::string pathOnly = RCPathUtil::GetPath(szDstFilePath); - const int maxStringSize = 512; - char szRemoteCmdLine[maxStringSize] = { 0 }; - char szFullPathToSourceFile[maxStringSize] = { 0 }; - - if (RCPathUtil::IsRelativePath(szSrcFilePath)) - { - azstrcat(szFullPathToSourceFile, maxStringSize, "#ENGINEROOT#"); - azstrcat(szFullPathToSourceFile, maxStringSize, "\\"); - } - azstrcat(szFullPathToSourceFile, maxStringSize, szSrcFilePath); - - azstrcat(szRemoteCmdLine, maxStringSize, " /targetroot=\""); - azstrcat(szRemoteCmdLine, maxStringSize, pathOnly.c_str()); - azstrcat(szRemoteCmdLine, maxStringSize, "\""); - - azstrcat(szRemoteCmdLine, maxStringSize, " /overwritefilename=\""); - azstrcat(szRemoteCmdLine, maxStringSize, szDstFileName); - azstrcat(szRemoteCmdLine, maxStringSize, "\""); - - return CallResourceCompiler(szFullPathToSourceFile, szRemoteCmdLine, nullptr, true, false, !bUserDialog); -} - -unsigned int IResourceCompilerHelper::GetNumSourceImageFormats() -{ - return NUM_SOURCE_IMAGE_TYPE; -} - -const char* IResourceCompilerHelper::GetSourceImageFormat(unsigned int index, bool bWithDot) -{ - if (index >= GetNumSourceImageFormats()) - { - return nullptr; - } - - if (bWithDot) - { - return SourceImageFormatExtsWithDot[index]; - } - else - { - return SourceImageFormatExts[index]; - } -} - -unsigned int IResourceCompilerHelper::GetNumEngineImageFormats() -{ - return NUM_ENGINE_IMAGE_TYPE; -} - -const char* IResourceCompilerHelper::GetEngineImageFormat(unsigned int index, bool bWithDot) -{ - if (index >= GetNumEngineImageFormats()) - { - return nullptr; - } - - if (bWithDot) - { - return EngineImageFormatExtsWithDot[index]; - } - else - { - return EngineImageFormatExts[index]; - } -} - -bool IResourceCompilerHelper::IsSourceImageFormatSupported(const char* szFileNameOrExtension) -{ - if (!szFileNameOrExtension) // if this hits, might want to check the call site - { - return false; - } - - //check the string length - size_t len = strlen(szFileNameOrExtension); - if (len < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //find the ext by starting at the last character and moving backward to first he first '.' - const char* szExtension = nullptr; - size_t cur = len - 1; - while (cur && !szExtension) - { - if (szFileNameOrExtension[cur] == '.') - { - szExtension = &szFileNameOrExtension[cur]; - } - cur--; - } - if (len - cur < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //if we didn't find a '.' it could still be valid, they may not have - //passed it in. i.e. "dds" instead of ".dds" which is still valid - if (!szExtension) - { - //with no '.' the largest ext is currently 4 characters - //no point in going on if it is larger - if (len > 4) - { - return false; - } - - szExtension = szFileNameOrExtension; - } - - //loop over all the valid exts and see if it is one of them - for (unsigned int i = 0; i < GetNumSourceImageFormats(); ++i) - { - if (!azstricmp(szExtension, GetSourceImageFormat(i, szExtension[0] == '.'))) - { - return true; - } - } - - return false; -} - -bool IResourceCompilerHelper::IsGameImageFormatSupported(const char* szFileNameOrExtension) -{ - if (!szFileNameOrExtension) // if this hits, might want to check the call site - { - return false; - } - - //check the string length - size_t len = strlen(szFileNameOrExtension); - if (len < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //find the ext by starting at the last character and moving backward to first he first '.' - const char* szExtension = nullptr; - size_t cur = len - 1; - while (cur && !szExtension) - { - if (szFileNameOrExtension[cur] == '.') - { - szExtension = &szFileNameOrExtension[cur]; - } - cur--; - } - if (len - cur < 3)//no point in going on if the smallest valid ext is 3 characters - { - return false; - } - - //if we didn't find a '.' it could still be valid, they may not have - //passed it in. i.e. "dds" instead of ".dds" which is still valid - if (!szExtension) - { - //with no '.' the largest ext is currently 4 characters - //no point in going on if it is larger - if (len > 4) - { - return false; - } - - szExtension = szFileNameOrExtension; - } - - //loop over all the valid exts and see if it is one of them - for (unsigned int i = 0; i < GetNumEngineImageFormats(); ++i) - { - if (!azstricmp(szExtension, GetEngineImageFormat(i, szExtension[0] == '.'))) - { - return true; - } - } - - return false; -} diff --git a/Code/CryEngine/CryCommon/IResourceCompilerHelper.h b/Code/CryEngine/CryCommon/IResourceCompilerHelper.h deleted file mode 100644 index 52f05b0c84..0000000000 --- a/Code/CryEngine/CryCommon/IResourceCompilerHelper.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H -#define CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H - -#pragma once - -// DO NOT USE AZSTD - -#include - -// IResourceCompilerHelper exists to define an interface that allows -// remote or local compilation of resources through the "resource Compiler" executable -// in most tools it will be implemented as a local execution. However, in the engine -// it will be substituted for a remote RC invocation through the Asset Processor if -// that system is enabled (via con var and define) - -// DO NOT USE CRYSTRING or CRY ALLOCATORS HERE. This is used in maya plugins, that kind of thing. -// the following path utils are special versions of these functions which take pains -// to not use crystring. -// the functions in this interface must be cross platform. -namespace RCPathUtil -{ - // given a full path, return the extension (it will be a pointer into the existing string) - const char* GetExt(const char* filepath); - - // given a full path, return the file only (it will be a pointer into the existing string) - const char* GetFile(const char* filepath); - - // given a filepath, get only the path. - std::string GetPath(const char* filepath); - std::string ReplaceExtension(const char* filepath, const char* ext); - bool IsRelativePath(const char* p); -} - -class IResourceCompilerListener; - -enum ERcExitCode -{ - eRcExitCode_Success = 0, // must be 0 - eRcExitCode_Error = 1, - eRcExitCode_FatalError = 100, - eRcExitCode_Crash = 101, - eRcExitCode_UserFixing = 200, - eRcExitCode_Pending = 666, -}; - -/// A pure virtual interface to the RC Helper system -/// the RC helper system allows you to make requests to a remote process in order to process -/// an asset for you. -class IResourceCompilerHelper -{ -public: - virtual ~IResourceCompilerHelper() {} - - // defines the result of a call via this API to the RC system - enum ERcCallResult - { - eRcCallResult_success, // everything is OK - eRcCallResult_notFound, // the RC executable is not found - eRcCallResult_error, // the RC executable returned an error - eRcCallResult_crash, // the RC executable did not finish - }; - - // - // Arguments: - // szFileName null terminated ABSOLUTE file path or 0 can be used to test for rc.exe existence - // relative path needs to be relative to rc_plugins directory - // szAdditionalSettings - 0 or e.g. "/refresh" or "/refresh /xyz=56" - // - // this is a SYNCHRONOUS, BLOCKING call and will return once the process is complete - virtual ERcCallResult CallResourceCompiler( - const char* szFileName = 0, - const char* szAdditionalSettings = 0, - IResourceCompilerListener* listener = 0, - bool bMayShowWindow = true, - bool bSilent = false, - bool bNoUserDialog = false, - const wchar_t* szWorkingDirectory = 0, - const wchar_t* szRootPath = 0) = 0; - - // InvokeResourceCompiler - a utility that calls the above CallResourceCompiler function - // but generates appropriate settings so you don't have to specify each option. - // This is a BLOCKING call - // the srcFile can be relative to the project root or an absolute path - // the dstFilePath MUST be relative to the same folder as the Src File path - // this will output dstFilePath in the same folder as srcFile. - virtual ERcCallResult InvokeResourceCompiler(const char* szSrcFilePath, const char* szDstFilePath, const bool bUserDialog); - - // --------------------- utility functions --------------------------------- - - // given a RC.EXE process exit code like 101, convert it to the above ERcCallResult - ERcCallResult ConvertResourceCompilerExitCodeToResultCode(int exitCode); - - // given a ERcCallResult, convert it to a simple english string for debugging. - static const char* GetCallResultDescription(ERcCallResult result); - - // given a filename such as "blah.tif" convert it to the appropriate output name "blah.dds" for example - static void GetOutputFilename(const char* szFilePath, char* buffer, size_t bufferSizeInBytes); - - ////////////////////////////////////////////////////////////////////////// - - enum SourceImageTypes - { - SOURCE_IMAGE_TYPE_TIF, - SOURCE_IMAGE_TYPE_BMP, - SOURCE_IMAGE_TYPE_GIF, - SOURCE_IMAGE_TYPE_JPG, - SOURCE_IMAGE_TYPE_JPEG, - SOURCE_IMAGE_TYPE_JPE, - SOURCE_IMAGE_TYPE_TGA, - SOURCE_IMAGE_TYPE_PNG, - NUM_SOURCE_IMAGE_TYPE - }; - - enum EngineImageTypes - { - ENGINE_IMAGE_TYPE_DDS, - NUM_ENGINE_IMAGE_TYPE - }; - -private: - static const char* SourceImageFormatExts[NUM_SOURCE_IMAGE_TYPE]; - static const char* SourceImageFormatExtsWithDot[NUM_SOURCE_IMAGE_TYPE]; - static const char* EngineImageFormatExts[NUM_ENGINE_IMAGE_TYPE]; - static const char* EngineImageFormatExtsWithDot[NUM_ENGINE_IMAGE_TYPE]; - -public: - static unsigned int GetNumSourceImageFormats(); - static const char* GetSourceImageFormat(unsigned int index, bool bWithDot); - - static unsigned int GetNumEngineImageFormats(); - static const char* GetEngineImageFormat(unsigned int index, bool bWithDot); - - static bool IsSourceImageFormatSupported(const char* szExtension); - static bool IsGameImageFormatSupported(const char* szExtension); -}; - -//////////////////////////////////////////////////////////////////////////// -// Listener for synchronous resource-compilation. -// Connects the listener to the output of the RC process. -class IResourceCompilerListener -{ -public: - // FbxImportDialog relies on this enum being in the order from most verbose to least verbose - enum MessageSeverity - { - MessageSeverity_Debug = 0, - MessageSeverity_Info, - MessageSeverity_Warning, - MessageSeverity_Error - }; - - virtual void OnRCMessage(MessageSeverity /*severity*/, const char* /*text*/) {} - virtual ~IResourceCompilerListener() {} -}; - -#endif // CRYINCLUDE_CRYCOMMON_IRESOURCECOMPILERHELPER_H diff --git a/Code/CryEngine/CryCommon/IShader.h b/Code/CryEngine/CryCommon/IShader.h index a87144a8c2..5f5209992e 100644 --- a/Code/CryEngine/CryCommon/IShader.h +++ b/Code/CryEngine/CryCommon/IShader.h @@ -24,7 +24,9 @@ #endif #include "smartptr.h" -#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include // <> required for Interfuscator +#include "smartptr.h" #include "VertexFormats.h" #include #include @@ -2828,7 +2830,6 @@ struct SRenderLight m_ObjMatrix.SetIdentity(); m_BaseObjMatrix.SetIdentity(); m_sName = ""; - m_pSoftOccQuery = NULL; m_pLightAnim = NULL; m_fAreaWidth = 1; m_fAreaHeight = 1; @@ -2884,11 +2885,6 @@ struct SRenderLight return m_pLightImage ? m_pLightImage : NULL; } - IOpticsElementBase* GetLensOpticsElement() const - { - return m_pLensOpticsElement; - } - void SetOpticsParams(const SOpticsInstanceParameters& params) { m_opticsParams = params; @@ -2899,24 +2895,6 @@ struct SRenderLight return m_opticsParams; } - void SetLensOpticsElement(IOpticsElementBase* pOptics) - { - if (m_pLensOpticsElement == pOptics) - { - return; - } - if (pOptics && pOptics->GetType() != eFT_Root) - { - return; - } - SAFE_RELEASE(m_pLensOpticsElement); - m_pLensOpticsElement = pOptics; - if (m_pLensOpticsElement) - { - m_pLensOpticsElement->AddRef(); - } - } - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { /*LATER*/} void AcquireResources() @@ -2937,14 +2915,6 @@ struct SRenderLight { m_pSpecularCubemap->AddRef(); } - if (m_pLensOpticsElement) - { - m_pLensOpticsElement->AddRef(); - } - if (m_pSoftOccQuery) - { - m_pSoftOccQuery->AddRef(); - } if (m_pLightAnim) { m_pLightAnim->AddRef(); @@ -2961,8 +2931,6 @@ struct SRenderLight SAFE_RELEASE(m_pLightImage); SAFE_RELEASE(m_pDiffuseCubemap); SAFE_RELEASE(m_pSpecularCubemap); - SAFE_RELEASE(m_pLensOpticsElement); - SAFE_RELEASE(m_pSoftOccQuery); SAFE_RELEASE(m_pLightAnim); SAFE_RELEASE(m_pLightAttenMap); } @@ -3046,8 +3014,6 @@ struct SRenderLight const char* m_sName; // Optional name of the light source. SShaderItem m_Shader; // Shader item CRenderObject* m_pObject[MAX_RECURSION_LEVELS]; // Object for light coronas and light flares. - IOpticsElementBase* m_pLensOpticsElement; // Optics element for this shader instance - ISoftOcclusionQuery* m_pSoftOccQuery; ILightAnimWrapper* m_pLightAnim; Matrix34 m_BaseObjMatrix; @@ -3146,9 +3112,7 @@ public: m_fShadowSlopeBias = dl.m_fShadowSlopeBias; m_fShadowResolutionScale = dl.m_fShadowResolutionScale; m_fHDRDynamic = dl.m_fHDRDynamic; - m_pLensOpticsElement = dl.m_pLensOpticsElement; m_LensOpticsFrustumAngle = dl.m_LensOpticsFrustumAngle; - m_pSoftOccQuery = dl.m_pSoftOccQuery; m_fLightFrustumAngle = dl.m_fLightFrustumAngle; m_fProjectorNearPlane = dl.m_fProjectorNearPlane; m_Flags = dl.m_Flags; diff --git a/Code/CryEngine/CryCommon/ISoftCodeMgr.h b/Code/CryEngine/CryCommon/ISoftCodeMgr.h deleted file mode 100644 index b3cef7e1f0..0000000000 --- a/Code/CryEngine/CryCommon/ISoftCodeMgr.h +++ /dev/null @@ -1,276 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Interface to manage SoftCode module loading and patching - - -#ifndef CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H -#define CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H -#pragma once - - -// Provides the generic interface for exchanging member values between SoftCode modules, -struct IExchangeValue -{ - // - virtual ~IExchangeValue() {} - - // Allocates a new IExchangeValue with the underlying type - virtual IExchangeValue* Clone() const = 0; - // Returns the size of the underlying type (to check compatibility) - virtual size_t GetSizeOf() const = 0; - // -}; - -template -struct ExchangeValue - : public IExchangeValue -{ - ExchangeValue(T& value) - : m_value(value) - {} - - virtual IExchangeValue* Clone() const { return new ExchangeValue(*this); } - virtual size_t GetSizeOf() const { return sizeof(m_value); } - - T m_value; -}; - -template -struct ExchangeArray - : public IExchangeValue -{ - ExchangeArray(T* pArr) - { - for (size_t i = 0; i < S; ++i) - { - m_array[i] = pArr[i]; - } - } - - virtual IExchangeValue* Clone() const { return new ExchangeArray(*this); } - virtual size_t GetSizeOf() const { return sizeof(m_array); } - - T m_array[S]; -}; - -/* - This is a non-intrusive support function for types where default construction does no initialization. - SoftCoding relies on default construction to initialize object state correctly. - For most types this works as expected but for some types (typically things like vectors or matrices) - default initialization would be too costly and is therefore not implemented. - This function allows a specialized implementation to be used for such types that will perform - initialization on the newly constructed instance. For example: - - inline void DefaultInitialize(Matrix34& matrix) - { - matrix.SetIdentity(); - } -*/ -template -void DefaultInitialize(T& t) -{ - t = T(); -} - -// Vector support -template -struct Vec2_tpl; -template -struct Vec3_tpl; -template -void DefaultInitialize(Vec2_tpl& vec) { vec.zero(); } -template -void DefaultInitialize(Vec3_tpl& vec) { vec.zero(); } - -// Matrix support -template -struct Matrix33_tpl; -template -struct Matrix34_tpl; -template -struct Matrix44_tpl; - -template -void DefaultInitialize(Matrix33_tpl& matrix) { matrix.SetIdentity(); } -template -void DefaultInitialize(Matrix34_tpl& matrix) { matrix.SetIdentity(); } -template -void DefaultInitialize(Matrix44_tpl& matrix) { matrix.SetIdentity(); } - -// Quat support -template -struct Quat_tpl; -template -void DefaultInitialize(Quat_tpl& quat) { quat.SetIdentity(); } - -// Interface for performing an exchange of instance data -struct IExchanger -{ - // - virtual ~IExchanger() {} - - // True if data is being read from instance members - virtual bool IsLoading() const = 0; - - virtual size_t InstanceCount() const = 0; - - virtual bool BeginInstance(void* pInstance) = 0; - virtual bool SetValue(const char* name, IExchangeValue& value) = 0; - virtual IExchangeValue* GetValue(const char* name, void* pTarget, size_t targetSize) = 0; - // - - template - void Visit(const char* name, T& instance); - - template - void Visit(const char* name, T (&arr)[S]); -}; - -template -void IExchanger::Visit(const char* name, T& value) -{ - if (IsLoading()) - { - IExchangeValue* pValue = GetValue(name, &value, sizeof(value)); - if (pValue) - { - ExchangeValue* pTypedValue = static_cast*>(pValue); - value = pTypedValue->m_value; - } - } - else // Saving - { - // If this member is stored - if (SetValue(name, ExchangeValue(value))) - { - // Set the original value to the default state (to allow safe destruction) - DefaultInitialize(value); - } - } -} - -template -void IExchanger::Visit(const char* name, T (&arr)[S]) -{ - if (IsLoading()) - { - IExchangeValue* pValue = GetValue(name, &arr, sizeof(arr)); - if (pValue) - { - ExchangeArray* pTypedArray = static_cast*>(pValue); - // TODO: Accommodate array resizing? Complex however... - for (size_t i = 0; i < S; ++i) - { - arr[i] = pTypedArray->m_array[i]; - } - } - } - else // Saving - { - // If this member is stored - if (SetValue(name, ExchangeArray(arr))) - { - T defaultValue; - DefaultInitialize(defaultValue); - - // Set the original value to the default value (to allow safe destruction) - for (size_t i = 0; i < S; ++i) - { - arr[i] = defaultValue; - } - } - } -} - -struct InstanceTracker; - -struct ITypeRegistrar -{ - // - virtual ~ITypeRegistrar() {} - - virtual const char* GetName() const = 0; - - // Creates an instance of the type - virtual void* CreateInstance() = 0; - // - -#ifdef SOFTCODE_ENABLED - // How many active instances exist of this type? - virtual size_t InstanceCount() const = 0; - // Used to remove a tracked instance from the Registrar - virtual void RemoveInstance(InstanceTracker* pTracker) = 0; - // Exchanges the instance state with the given exchanger data set - virtual bool ExchangeInstances(IExchanger& exchanger) = 0; - // Destroys all tracked instances of this type - virtual bool DestroyInstances() = 0; - // Returns true if pInstance is of this type (linear search) - virtual bool HasInstance(void* pInstance) const = 0; -#endif -}; - -struct ITypeLibrary -{ - // - virtual ~ITypeLibrary() {} - - virtual const char* GetName() = 0; - virtual void* CreateInstanceVoid(const char* typeName) = 0; - // - -#ifdef SOFTCODE_ENABLED - virtual void SetOverride(ITypeLibrary* pOverrideLib) = 0; - - // Fills in the supplied type list if large enough, and sets count to number of types - virtual size_t GetTypes(ITypeRegistrar** ppRegistrar, size_t& count) const = 0; -#endif -}; - -struct ISoftCodeListener -{ - // - virtual ~ISoftCodeListener() {} - - // Called when an instance is replaced to allow managing systems to fixup pointers - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) = 0; - // -}; - -/// Interface for ... -struct ISoftCodeMgr -{ - // - virtual ~ISoftCodeMgr() {} - - // Used to register built-in libraries on first use - virtual void RegisterLibrary(ITypeLibrary* pLib) = 0; - - // Loads any new SoftCode modules - virtual void LoadNewModules() = 0; - - virtual void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) = 0; - virtual void RemoveListener(const char* libraryName, ISoftCodeListener* pListener) = 0; - - // To be called regularly to poll for library updates - virtual void PollForNewModules() = 0; - - // Stops thread execution until a new SoftCode instance is available - virtual void* WaitForUpdate(void* pInstance) = 0; - - /// Frees this instance from memory - //virtual void Release() = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_ISOFTCODEMGR_H diff --git a/Code/CryEngine/CryCommon/IStreamEngine.h b/Code/CryEngine/CryCommon/IStreamEngine.h index f325eec389..0536e1f486 100644 --- a/Code/CryEngine/CryCommon/IStreamEngine.h +++ b/Code/CryEngine/CryCommon/IStreamEngine.h @@ -34,7 +34,6 @@ #include #include "smartptr.h" -#include // <> required for Interfuscator #include "CryThread.h" #include "IStreamEngineDefs.h" diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index 86c2b57464..4c6bd73b61 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -49,19 +49,15 @@ #include // <> required for Interfuscator #include "CryVersion.h" #include "smartptr.h" -#include // <> required for Interfuscator #include // shared_ptr #include struct ISystem; struct ILog; -struct IProfileLogSystem; namespace AZ::IO { struct IArchive; } -struct IKeyboard; -struct IMouse; struct IConsole; struct IRemoteConsole; struct IRenderer; @@ -79,29 +75,21 @@ struct SFileVersion; struct INameTable; struct ILevelSystem; struct IViewSystem; -struct IMaterialEffects; -class IOpticsManager; class ICrySizer; class IXMLBinarySerializer; struct IReadWriteXMLSink; -struct IThreadTaskManager; struct IResourceManager; struct ITextModeConsole; struct IAVI_Reader; class CPNoise3; -struct IVisualLog; struct ILocalizationManager; -struct ISoftCodeMgr; struct IZLibCompressor; struct IZLibDecompressor; struct ILZ4Decompressor; class IZStdDecompressor; struct IOutputPrintSink; -struct IThreadManager; struct IWindowMessageHandler; struct IImageHandler; -class IResourceCompilerHelper; -class ILmbrAWS; namespace AZ { @@ -111,12 +99,6 @@ namespace AZ } } -class IResourceCompilerHelper; - -namespace Serialization { - struct IArchiveHost; -} - typedef void* WIN_HWND; class CCamera; @@ -124,39 +106,13 @@ struct CLoadingTimeProfiler; class ICmdLine; -struct INotificationNetwork; class ILyShine; -namespace JobManager { - struct IJobManager; -} - -#define PROC_MENU 1 -#define PROC_3DENGINE 2 - -// Summary: -// IDs for script userdata typing. -// Remarks: -// Maybe they should be moved into the game.dll . -//##@{ -#define USER_DATA_SOUND 1 -#define USER_DATA_TEXTURE 2 -#define USER_DATA_OBJECT 3 -#define USER_DATA_LIGHT 4 -#define USER_DATA_BONEHANDLER 5 -#define USER_DATA_POINTER 6 -//##@} - enum ESystemUpdateFlags { - ESYSUPDATE_IGNORE_PHYSICS = 0x0002, // Summary: // Special update mode for editor. - ESYSUPDATE_EDITOR = 0x0004, - ESYSUPDATE_MULTIPLAYER = 0x0008, - ESYSUPDATE_EDITOR_AI_PHYSICS = 0x0010, - ESYSUPDATE_EDITOR_ONLY = 0x0020, - ESYSUPDATE_UPDATE_VIEW_ONLY = 0x0040 + ESYSUPDATE_EDITOR = 0x0004 }; // Description: @@ -189,29 +145,6 @@ enum ESystemConfigPlatform END_CONFIG_PLATFORM_ENUM, // MUST BE LAST VALUE. USED FOR ERROR CHECKING. }; -enum ESubsystem -{ - ESubsys_3DEngine = 0, - ESubsys_AI = 1, - ESubsys_Physics = 2, - ESubsys_Renderer = 3, - ESubsys_Script = 4 -}; - -// Summary: -// Collates cycles taken per update. -struct sUpdateTimes -{ - uint32 PhysYields; - uint64 SysUpdateTime; - uint64 PhysStepTime; - uint64 RenderTime; - //extended yimes info - uint64 physWaitTime; - uint64 streamingWaitTime; - uint64 animationWaitTime; -}; - enum ESystemGlobalState { ESYSTEM_GLOBAL_STATE_UNKNOWN, @@ -568,33 +501,6 @@ struct IErrorObserver // }; -enum ESystemProtectedFunctions -{ - eProtectedFunc_Save = 0, - eProtectedFunc_Load = 1, - eProtectedFuncsLast = 10, -}; - -struct SCvarsDefault -{ - SCvarsDefault() - { - sz_r_DriverDef = NULL; - } - - const char* sz_r_DriverDef; -}; - -#if defined(CVARS_WHITELIST) -struct ICVarsWhitelist -{ - // - virtual ~ICVarsWhitelist() {}; - virtual bool IsWhiteListed(const string& command, bool silent) = 0; - // -}; -#endif // defined(CVARS_WHITELIST) - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_3 #include AZ_RESTRICTED_FILE(ISystem_h) @@ -616,9 +522,6 @@ struct SSystemInitParams { void* hInstance; // void* hWnd; // - void* hWndForInputSystem; // the HWND for the input devices, distinct from the hWnd, which the rendering system overrides anyways - - bool remoteResourceCompiler; ILog* pLog; // You can specify your own ILog to be used by System. ILogCallback* pLogCallback; // You can specify your own ILogCallback to be added on log creation (used by Editor). @@ -633,33 +536,14 @@ struct SSystemInitParams bool bPreview; // When running in Preview mode (Minimal initialization). bool bTestMode; // When running in Automated testing mode. bool bDedicatedServer; // When running a dedicated server. - bool bExecuteCommandLine; // can be switched of to suppress the feature or do it later during the initialization. - bool bSkipFont; // Don't load CryFont.dll bool bSkipConsole; // Don't create console - bool bSkipNetwork; // Don't create Network - bool bSkipWebsocketServer; // Don't create the WebSocket server - bool bMinimal; // Don't load banks - bool bTesting; // CryUnit - bool bNoRandom; //use fixed generator init/seed bool bUnattendedMode; // When running as part of a build on build-machines: Prevent popping up of any dialog bool bSkipMovie; // Don't load movie - bool bSkipAnimation; // Don't load animation bool bToolMode; // System is running inside a tool. Will not create USER directory or anything else that the game needs to do - bool bSkipPhysics; // Don't initialize CryPhysics. - ISystem* pSystem; // Pointer to existing ISystem interface, it will be reused if not NULL. - typedef void* (*ProtectedFunction)(void* param1, void* param2); - ProtectedFunction pProtectedFunctions[eProtectedFuncsLast]; // Protected functions. - - SCvarsDefault* pCvarsDefault; // to override the default value of some cvar - -#if defined(CVARS_WHITELIST) - ICVarsWhitelist* pCVarsWhitelist; // CVars whitelist callback -#endif // defined(CVARS_WHITELIST) - SharedEnvironmentInstance* pSharedEnvironment; // Summary: @@ -668,16 +552,10 @@ struct SSystemInitParams { hInstance = NULL; hWnd = NULL; - hWndForInputSystem = NULL; - - remoteResourceCompiler = false; pLog = NULL; pLogCallback = NULL; pUserCallback = NULL; -#if defined(CVARS_WHITELIST) - pCVarsWhitelist = NULL; -#endif // defined(CVARS_WHITELIST) sLogFileName = NULL; autoBackupLogs = true; pValidator = NULL; @@ -688,32 +566,13 @@ struct SSystemInitParams bPreview = false; bTestMode = false; bDedicatedServer = false; - bExecuteCommandLine = true; - bExecuteCommandLine = true; - bSkipFont = false; bSkipConsole = false; - bSkipNetwork = false; -#if defined(WIN32) || defined(WIN64) - // create websocket server by default. bear in mind that USE_HTTP_WEBSOCKETS is not defined in release. - bSkipWebsocketServer = false; -#else - // CTCPStreamSocket only seems to fully support Win32 and 64 - bSkipWebsocketServer = true; -#endif - bMinimal = false; - bTesting = false; - bNoRandom = false; bUnattendedMode = false; bSkipMovie = false; - bSkipAnimation = false; bToolMode = false; - bSkipPhysics = false; pSystem = NULL; - memset(pProtectedFunctions, 0, sizeof(pProtectedFunctions)); - pCvarsDefault = NULL; - pSharedEnvironment = nullptr; } }; @@ -782,8 +641,6 @@ struct SSystemGlobalEnvironment { AZ::IO::IArchive* pCryPak; AZ::IO::FileIOBase* pFileIO; - IProfileLogSystem* pProfileLogSystem; - IOpticsManager* pOpticsManager; ITimer* pTimer; ICryFont* pCryFont; ::IConsole* pConsole; @@ -791,81 +648,27 @@ struct SSystemGlobalEnvironment ILog* pLog; IMovieSystem* pMovieSystem; INameTable* pNameTable; - IVisualLog* pVisualLog; IRenderer* pRenderer; - IMaterialEffects* pMaterialEffects; - ISoftCodeMgr* pSoftCodeMgr; ILyShine* pLyShine; - IResourceCompilerHelper* pResourceCompilerHelper; SharedEnvironmentInstance* pSharedEnvironment; - IThreadManager* pThreadManager; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION ISYSTEM_H_SECTION_4 #include AZ_RESTRICTED_FILE(ISystem_h) #endif - ISystemScheduler* pSystemScheduler; - threadID mMainThreadId; //The main thread ID is used in multiple systems so should be stored globally - ////////////////////////////////////////////////////////////////////////// - uint32 nMainFrameID; - - ////////////////////////////////////////////////////////////////////////// - const char* szCmdLine; // Startup command line. - - ////////////////////////////////////////////////////////////////////////// - // Generic debug string which can be easily updated by any system and output by the debug handler - enum - { - MAX_DEBUG_STRING_LENGTH = 128 - }; - char szDebugStatus[MAX_DEBUG_STRING_LENGTH]; - - ////////////////////////////////////////////////////////////////////////// - // Used to tell if this is a server/multiplayer instance - bool bServer; - bool bMultiplayer; - bool bHostMigrating; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Indicate Editor status. - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// // Used by CRY_ASSERT bool bIgnoreAllAsserts; bool bNoAssertDialog; - bool bTesting; ////////////////////////////////////////////////////////////////////////// - bool bNoRandomSeed; - - SPlatformInfo pi; - - // Protected functions. - SSystemInitParams::ProtectedFunction pProtectedFunctions[eProtectedFuncsLast]; // Protected functions. - - ////////////////////////////////////////////////////////////////////////// - // Flag to able to print out of memory conditon - bool bIsOutOfMemory; - bool bIsOutOfVideoMemory; - bool bToolMode; int retCode = 0; - ILINE const bool IsClient() const - { -#if defined(CONSOLE) - return true; -#else - return bClient; -#endif - } - ILINE const bool IsDedicated() const { #if defined(CONSOLE) @@ -895,11 +698,6 @@ struct SSystemGlobalEnvironment { bDedicated = isDedicated; } - - ILINE void SetIsClient(bool isClient) - { - bClient = isClient; - } #endif //this way the compiler can strip out code for consoles @@ -939,26 +737,6 @@ struct SSystemGlobalEnvironment #endif } - ILINE const bool IsFMVPlaying() const - { - return m_isFMVPlaying; - } - - ILINE void SetFMVIsPlaying(const bool isPlaying) - { - m_isFMVPlaying = isPlaying; - } - - ILINE const bool IsCutscenePlaying() const - { - return m_isCutscenePlaying; - } - - ILINE void SetCutsceneIsPlaying(const bool isPlaying) - { - m_isCutscenePlaying = isPlaying; - } - ILINE bool IsInToolMode() const { return bToolMode; @@ -969,35 +747,17 @@ struct SSystemGlobalEnvironment bToolMode = bNewToolMode; } - ILINE void SetDynamicMergedMeshGenerationEnabled(bool mmgenEnable) - { - m_bDynamicMergedMeshGenerationEnabled = mmgenEnable; - } - - ILINE const bool IsDynamicMergedMeshGenerationEnabled() const - { - return m_bDynamicMergedMeshGenerationEnabled; - } - #if !defined(CONSOLE) private: - bool bClient; bool bEditor; // Engine is running under editor. bool bEditorGameMode; // Engine is in editor game mode. bool bEditorSimulationMode; // Engine is in editor simulation mode. bool bDedicated; // Engine is in dedicated #endif - bool m_isFMVPlaying; - bool m_isCutscenePlaying; - bool m_bDynamicMergedMeshGenerationEnabled; - public: SSystemGlobalEnvironment() - : pSystemScheduler(nullptr) - , szCmdLine("") - , bToolMode(false) - , m_bDynamicMergedMeshGenerationEnabled(false) + : bToolMode(false) { }; }; @@ -1035,37 +795,11 @@ struct IProfilingSystem // Initialize and dispatch all engine's subsystems. struct ISystem { - struct ILoadingProgressListener - { - // - virtual ~ILoadingProgressListener() {} - virtual void OnLoadingProgress(int steps) = 0; - // - }; - -#ifndef _RELEASE - enum LevelLoadOrigin - { - eLLO_Unknown, - eLLO_NewLevel, - eLLO_Level2Level, - eLLO_Resumed, - eLLO_MapCmd, - }; - - struct ICheckpointData - { - int m_totalLoads; - LevelLoadOrigin m_loadOrigin; - }; -#endif - // virtual ~ISystem() {} // Summary: // Releases ISystem. virtual void Release() = 0; - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const = 0; // will return NULL if no whitelisting // Summary: // Returns pointer to the global environment structure. @@ -1094,9 +828,6 @@ struct ISystem virtual void DoWorkDuringOcclusionChecks() = 0; virtual bool NeedDoWorkDuringOcclusionChecks() = 0; - //! Update screen and call some important tick functions during loading. - virtual void SynchronousLoadingTick(const char* pFunc, int line) = 0; - // Summary: // Returns the current used memory. virtual uint32 GetUsedMemory() = 0; @@ -1170,7 +901,6 @@ struct ISystem virtual IZLibDecompressor* GetIZLibDecompressor() = 0; virtual ILZ4Decompressor* GetLZ4Decompressor() = 0; virtual IZStdDecompressor* GetZStdDecompressor() = 0; - virtual INotificationNetwork* GetINotificationNetwork() = 0; virtual IViewSystem* GetIViewSystem() = 0; virtual ILevelSystem* GetILevelSystem() = 0; virtual INameTable* GetINameTable() = 0; @@ -1187,24 +917,10 @@ struct ISystem // Returns: // Can be NULL, because it only exists when running through the editor, not in pure game mode. virtual IResourceManager* GetIResourceManager() = 0; - virtual IThreadTaskManager* GetIThreadTaskManager() = 0; virtual IProfilingSystem* GetIProfilingSystem() = 0; virtual ISystemEventDispatcher* GetISystemEventDispatcher() = 0; - virtual IVisualLog* GetIVisualLog() = 0; virtual ITimer* GetITimer() = 0; - virtual IThreadManager* GetIThreadManager() = 0; - - virtual void SetLoadingProgressListener(ILoadingProgressListener* pListener) = 0; - virtual ISystem::ILoadingProgressListener* GetLoadingProgressListener() const = 0; - - // Summary: - // Game is created after System init, so has to be set explicitly. - virtual void SetIMaterialEffects(IMaterialEffects* pMaterialEffects) = 0; - virtual void SetIOpticsManager(IOpticsManager* pOpticsManager) = 0; - virtual void SetIVisualLog(IVisualLog* pVisualLog) = 0; - - //virtual const char *GetGamePath()=0; virtual void DebugStats(bool checkpoint, bool leaks) = 0; virtual void DumpWinHeaps() = 0; @@ -1219,7 +935,6 @@ struct ISystem virtual bool WasInDevMode() const = 0; virtual bool IsDevMode() const = 0; virtual bool IsMODValid(const char* szMODName) const = 0; - virtual bool IsMinimalMode() const = 0; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// @@ -1334,12 +1049,6 @@ struct ISystem // Detects and set optimal spec. virtual void AutoDetectSpec(bool detectResolution) = 0; - // Summary: - // Thread management for subsystems - // Return Value: - // Non-0 if the state was indeed changed, 0 if already in that state. - virtual int SetThreadState(ESubsystem subsys, bool bActive) = 0; - // Summary: // Query if system is now paused. // Pause flag is set when calling system update with pause mode. @@ -1406,14 +1115,6 @@ struct ISystem // Get log index of the currently running Open 3D Engine application. (0 = first instance, 1 = second instance, etc) virtual int GetApplicationLogInstance(const char* logFilePath) = 0; - // Summary: - // Retrieves the current stats for systems to update the respective time taken - virtual sUpdateTimes& GetCurrentUpdateTimeStats() = 0; - - // Summary: - // Retrieves the array of update times and the number of entries - virtual const sUpdateTimes* GetUpdateTimeStats(uint32&, uint32&) = 0; - // Summary: // Clear all currently logged and drawn on screen error messages virtual void ClearErrorMessages() = 0; @@ -1458,17 +1159,6 @@ struct ISystem virtual void AsyncMemcpy(void* dst, const void* src, size_t size, int nFlags, volatile int* sync) = 0; // - -#if defined(CVARS_WHITELIST) - virtual ICVarsWhitelist* GetCVarsWhiteList() const = 0; -#endif // defined(CVARS_WHITELIST) - -#ifndef _RELEASE - virtual void GetCheckpointData(ICheckpointData& data) = 0; - virtual void IncreaseCheckpointLoadCount() = 0; - virtual void SetLoadOrigin(LevelLoadOrigin origin) = 0; -#endif - #if !defined(_RELEASE) virtual bool IsSavingResourceList() const = 0; #endif @@ -1513,11 +1203,6 @@ struct ISystem using CrySystemNotificationBus = AZ::EBus; }; -//JAT - this is a very important function for the dedicated server - it lets us run >1000 players per piece of server hardware -//JAT - this saves us lots of money on the dedicated server hardware -#define SYNCHRONOUS_LOADING_TICK() do { if (gEnv && gEnv->pSystem) {gEnv->pSystem->SynchronousLoadingTick(__FUNC__, __LINE__); } \ -} while (0) - #if defined(USE_DISK_PROFILER) struct DiskOperationInfo @@ -1594,7 +1279,7 @@ typedef ISystem* (*PFNCREATESYSTEMINTERFACE)(SSystemInitParams& initParams); ////////////////////////////////////////////////////////////////////////// // Global environment variable. ////////////////////////////////////////////////////////////////////////// -extern SC_API SSystemGlobalEnvironment* gEnv; +extern SSystemGlobalEnvironment* gEnv; // Summary: @@ -1613,11 +1298,6 @@ inline ISystem* GetISystem() } return systemInterface; }; - -inline ISystemScheduler* GetISystemScheduler(void) -{ - return gEnv->pSystemScheduler; -}; ////////////////////////////////////////////////////////////////////////// // Description: @@ -1640,7 +1320,6 @@ void* GetDetachEnvironmentSymbol(); extern bool g_bProfilerEnabled; -extern int g_iTraceAllocations; // Summary: // Interface of the DLL. diff --git a/Code/CryEngine/CryCommon/ISystemScheduler.h b/Code/CryEngine/CryCommon/ISystemScheduler.h deleted file mode 100644 index 9280eb2ea6..0000000000 --- a/Code/CryEngine/CryCommon/ISystemScheduler.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H -#define CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H -#pragma once - -#if defined(__cplusplus) -#define SLICE_AND_SLEEP() do { if (GetISystemScheduler()) { GetISystemScheduler()->SliceAndSleep(__FUNC__, __LINE__); } \ -} while (0) -#define SLICE_SCOPE_DEFINE() CSliceLoadingMonitor sliceScope -#else -extern void SliceAndSleep(const char* pFunc, int line); -#define SLICE_AND_SLEEP() SliceAndSleep(__FILE__, __LINE__) -#endif - -struct ISystemScheduler -{ - virtual ~ISystemScheduler(){} - - // - // Map load slicing functionality support - virtual void SliceAndSleep(const char* sliceName, int line) = 0; - virtual void SliceLoadingBegin() = 0; - virtual void SliceLoadingEnd() = 0; - - virtual void SchedulingSleepIfNeeded(void) = 0; - // -}; - -ISystemScheduler* GetISystemScheduler(void); - -class CSliceLoadingMonitor -{ -public: - CSliceLoadingMonitor() - { - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceLoadingBegin(); - } - } - - ~CSliceLoadingMonitor() - { - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceLoadingEnd(); - } - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_ISYSTEMSCHEDULER_H diff --git a/Code/CryEngine/CryCommon/IThreadManager.h b/Code/CryEngine/CryCommon/IThreadManager.h deleted file mode 100644 index 448e3eec16..0000000000 --- a/Code/CryEngine/CryCommon/IThreadManager.h +++ /dev/null @@ -1,111 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -class IThreadConfigManager; - -enum EJoinMode -{ - eJM_TryJoin, - eJM_Join, -}; - -class IThread -{ -public: - // - virtual ~IThread() - { - } - - //! Entry functions for code executed on thread. - virtual void ThreadEntry() = 0; - // -}; - -enum EFPE_Severity -{ - eFPE_None, //!< No Floating Point Exceptions. - eFPE_Basic, //!< Invalid operation, Div by 0. - eFPE_All, //!< Invalid operation, Div by 0, Denormalized operand, Overflow, Underflow, Inexact. - eFPE_LastEntry -}; - -//temp disable CRY DX12 -//#define SCOPED_ENABLE_FLOAT_EXCEPTIONS(eFPESeverity) CScopedFloatingPointException scopedSetFloatExceptionMask(eFPESeverity) -//#define SCOPED_DISABLE_FLOAT_EXCEPTIONS() CScopedFloatingPointException scopedSetFloatExceptionMask(eFPE_None) - -struct IThreadManager -{ -public: - // - virtual ~IThreadManager() - { - } - - //! Get thread config manager. - virtual IThreadConfigManager* GetThreadConfigManager() = 0; - - //! Spawn a new thread and apply thread config settings at thread beginning. - virtual bool SpawnThread(IThread* pThread, const char* sThreadName, ...) = 0; - - //! Wait on another thread to exit (Blocking). - //! Use eJM_TryJoin if you cannot be sure that the target thread is awake. - //! \retval true if target thread has not been started yet or has already exited. - //! \retval false if target thread is still running and therefore not in a state to exit. - virtual bool JoinThread(IThread* pThreadTask, EJoinMode joinStatus) = 0; - - //! Register 3rd party thread with the thread manager. - //! Applies thread config for thread if found. - //! \param pThreadHandle If NULL, the current thread handle will be used. - virtual bool RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) = 0; - - //! Unregister 3rd party thread with the thread manager. - virtual bool UnRegisterThirdPartyThread(const char* sThreadName, ...) = 0; - - //! Get Thread Name. - //! Returns "" if thread not found. - virtual const char* GetThreadName(threadID nThreadId) = 0; - - //! Get ThreadID. - virtual threadID GetThreadId(const char* sThreadName, ...) = 0; - - //! Execute function for each other thread but this one. - typedef void (* ThreadModifFunction)(threadID nThreadId, void* pData); - virtual void ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData = 0) = 0; - - virtual void EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId = 0) = 0; - virtual void EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) = 0; - - virtual uint GetFloatingPointExceptionMask() = 0; - virtual void SetFloatingPointExceptionMask(uint nMask) = 0; - // -}; -/*TEMP DISABLE CRY DX12 -class CScopedFloatingPointException -{ -public: - CScopedFloatingPointException(EFPE_Severity eFPESeverity) - { - oldMask = gEnv->pThreadManager->GetFloatingPointExceptionMask(); - gEnv->pThreadManager->EnableFloatExceptions(eFPESeverity); - } - ~CScopedFloatingPointException() - { - gEnv->pThreadManager->SetFloatingPointExceptionMask(oldMask); - } -private: - uint oldMask; -}; -*/ diff --git a/Code/CryEngine/CryCommon/IThreadTask.h b/Code/CryEngine/CryCommon/IThreadTask.h deleted file mode 100644 index d4a565fcff..0000000000 --- a/Code/CryEngine/CryCommon/IThreadTask.h +++ /dev/null @@ -1,166 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "BitFiddling.h" - -#ifndef CRYINCLUDE_CRYCOMMON_ITHREADTASK_H -#define CRYINCLUDE_CRYCOMMON_ITHREADTASK_H -#pragma once - -#include - -// forward declarations -struct SThreadTaskInfo; - -enum EThreadTaskFlags -{ - THREAD_TASK_BLOCKING = BIT(0), // Blocking tasks will be allocated on their own thread. - THREAD_TASK_ASSIGN_TO_POOL = BIT(1), // Task can be assigned to any thread in the group of threads -}; - -class IThreadTask_Thread -{ -public: - // - virtual ~IThreadTask_Thread() {}; - virtual void AddTask(SThreadTaskInfo* pTaskInfo) = 0; - virtual void RemoveTask(SThreadTaskInfo* pTaskInfo) = 0; - virtual void RemoveAllTasks() = 0; - virtual void SingleUpdate() = 0; - // -}; - -typedef int ThreadPoolHandle; - -struct SThreadTaskParams -{ - uint32 nFlags; // Task flags. @see ETaskFlags - union - { - int nPreferedThread; // Preferred Thread index (0,1,2,3...) - ThreadPoolHandle nThreadsGroupId; // Id of group of threads(useful only if THREAD_TASK_ASSIGN_TO_POOL is set) - }; - int16 nPriorityOff; // If THREAD_TASK_BLOCKING, this will adjust the priority of the thread - int16 nStackSizeKB; // If THREAD_TASK_BLOCKING, this will adjust the stack size of the thread - const char* name; // Name for this task (thread for the blocking task will be named using this string) - - SThreadTaskParams() - : nFlags(0) - , nPreferedThread(-1) - , nPriorityOff(0) - , name("") - , nStackSizeKB(SIMPLE_THREAD_STACK_SIZE_KB) {} -}; - -////////////////////////////////////////////////////////////////////////// -// Tasks must implement this interface. -////////////////////////////////////////////////////////////////////////// -struct IThreadTask -{ - // - // The function to be called on every update for non bocking tasks. - // Or will be called only once for the blocking threads. - virtual void OnUpdate() = 0; - - // Called to indicate that this task must quit. - // Warning! can be called from different thread then OnUpdate call. - virtual void Stop() = 0; - - // Returns task info - virtual struct SThreadTaskInfo* GetTaskInfo() = 0; - - virtual ~IThreadTask() {} - // -}; - -struct SThreadTaskInfo - : public CMultiThreadRefCount -{ - IThreadTask_Thread* m_pThread; - IThreadTask* m_pTask; - SThreadTaskParams m_params; - - SThreadTaskInfo() - : m_pThread(NULL) - , m_pTask(NULL) { m_params.nFlags = 0; m_params.nPreferedThread = -1; } -}; - -// Might be changed to uint64 etc in the future -typedef uint32 ThreadPoolAffinityMask; -#define INVALID_AFFINITY 0 - -////////////////////////////////////////////////////////////////////////// -// Description of thread pool to create -////////////////////////////////////////////////////////////////////////// -struct ThreadPoolDesc -{ - ThreadPoolAffinityMask AffinityMask; // number of bits means number of threads. affinity overlapping is prohibited - string sPoolName; - int32 nThreadPriority; - int32 nThreadStackSizeKB; - - ThreadPoolDesc() - : AffinityMask(INVALID_AFFINITY) - , sPoolName("UnnamedPool") - , nThreadPriority(-1) - , nThreadStackSizeKB(-1) { } - - ILINE bool CreateThread(ThreadPoolAffinityMask affinityMask) - { - if (this->AffinityMask & affinityMask) - { - return false; - } - - this->AffinityMask |= affinityMask; - return true; - } - - ILINE uint32 GetThreadCount() const - { - return CountBits(AffinityMask); - } -}; - -////////////////////////////////////////////////////////////////////////// -// Task manager. -////////////////////////////////////////////////////////////////////////// -struct IThreadTaskManager -{ - // - virtual ~IThreadTaskManager(){} - // Register new task to the manager. - virtual void RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options) = 0; - virtual void UnregisterTask(IThreadTask* pTask) = 0; - - // Limit number of threads to this amount. - virtual void SetMaxThreadCount(int nMaxThreads) = 0; - - // Create a pool of threads - virtual ThreadPoolHandle CreateThreadsPool(const ThreadPoolDesc& desc) = 0; - virtual const bool DestroyThreadsPool(const ThreadPoolHandle& handle) = 0; - virtual const bool GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const = 0; - virtual const bool SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask) = 0; - - virtual void SetThreadName(threadID dwThreadId, const char* sThreadName) = 0; - virtual const char* GetThreadName(threadID dwThreadId) = 0; - - // Return thread handle by thread name - virtual threadID GetThreadByName(const char* sThreadName) = 0; - - // if bMark=true the calling thread will dump its stack during crashes - virtual void MarkThisThreadForDebugging(const char* name, bool bDump) = 0; - // -}; - -#endif // CRYINCLUDE_CRYCOMMON_ITHREADTASK_H diff --git a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h index 7b0b7b76a2..74d072c48c 100644 --- a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h @@ -585,8 +585,6 @@ public: SDepthTexture * (int, int, bool)); MOCK_METHOD1(DestroyDepthSurface, void(SDepthTexture * pDepthSurf)); - MOCK_CONST_METHOD1(CreateOptics, - IOpticsElementBase * (EFlareType type)); MOCK_METHOD1(PauseTimer, void(bool bPause)); MOCK_METHOD0(CreateShaderPublicParams, diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h index 1e28937764..cfe150c1df 100644 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h @@ -23,8 +23,6 @@ class SystemMock public: MOCK_METHOD0(Release, void()); - MOCK_CONST_METHOD0(GetCVarsWhiteListConfigSink, - ILoadConfigurationEntrySink * ()); MOCK_METHOD0(GetGlobalEnvironment, SSystemGlobalEnvironment * ()); MOCK_METHOD2(UpdatePreTickBus, @@ -37,8 +35,6 @@ public: void()); MOCK_METHOD0(NeedDoWorkDuringOcclusionChecks, bool()); - MOCK_METHOD2(SynchronousLoadingTick, - void(const char* pFunc, int line)); MOCK_METHOD0(RenderStatistics, void()); MOCK_METHOD0(GetUsedMemory, @@ -84,8 +80,6 @@ public: ILZ4Decompressor * ()); MOCK_METHOD0(GetZStdDecompressor, IZStdDecompressor * ()); - MOCK_METHOD0(GetINotificationNetwork, - INotificationNetwork * ()); MOCK_METHOD0(GetIViewSystem, IViewSystem * ()); MOCK_METHOD0(GetILevelSystem, @@ -116,28 +110,12 @@ public: IRemoteConsole * ()); MOCK_METHOD0(GetIResourceManager, IResourceManager * ()); - MOCK_METHOD0(GetIThreadTaskManager, - IThreadTaskManager * ()); MOCK_METHOD0(GetIProfilingSystem, IProfilingSystem * ()); MOCK_METHOD0(GetISystemEventDispatcher, ISystemEventDispatcher * ()); - MOCK_METHOD0(GetIVisualLog, - IVisualLog * ()); MOCK_METHOD0(GetITimer, ITimer * ()); - MOCK_METHOD0(GetIThreadManager, - IThreadManager * ()); - MOCK_METHOD1(SetLoadingProgressListener, - void(ILoadingProgressListener * pListener)); - MOCK_CONST_METHOD0(GetLoadingProgressListener, - ISystem::ILoadingProgressListener * ()); - MOCK_METHOD1(SetIMaterialEffects, - void(IMaterialEffects * pMaterialEffects)); - MOCK_METHOD1(SetIOpticsManager, - void(IOpticsManager * pOpticsManager)); - MOCK_METHOD1(SetIVisualLog, - void(IVisualLog * pVisualLog)); MOCK_METHOD2(DebugStats, void(bool checkpoint, bool leaks)); MOCK_METHOD0(DumpWinHeaps, @@ -154,8 +132,6 @@ public: bool()); MOCK_CONST_METHOD1(IsMODValid, bool(const char* szMODName)); - MOCK_CONST_METHOD0(IsMinimalMode, - bool()); MOCK_METHOD3(CreateXmlNode, XmlNodeRef(const char*, bool, bool)); MOCK_METHOD4(LoadXmlFromBuffer, @@ -209,8 +185,6 @@ public: void(ESystemConfigPlatform platform)); MOCK_METHOD1(AutoDetectSpec, void(bool detectResolution)); - MOCK_METHOD2(SetThreadState, - int(ESubsystem subsys, bool bActive)); MOCK_CONST_METHOD0(IsPaused, bool()); MOCK_METHOD0(GetLocalizationManager, @@ -239,10 +213,6 @@ public: int()); MOCK_METHOD1(GetApplicationLogInstance, int(const char* logFilePath)); - MOCK_METHOD0(GetCurrentUpdateTimeStats, - sUpdateTimes & ()); - MOCK_METHOD2(GetUpdateTimeStats, - const sUpdateTimes * (uint32 &, uint32 &)); MOCK_METHOD0(ClearErrorMessages, void()); MOCK_METHOD2(debug_GetCallStack, @@ -260,20 +230,6 @@ public: MOCK_METHOD5(AsyncMemcpy, void(void* dst, const void* src, size_t size, int nFlags, volatile int* sync)); -#if defined(CVARS_WHITELIST) - MOCK_CONST_METHOD0(GetCVarsWhiteList, - ICVarsWhitelist * ()); -#endif - -#ifndef _RELEASE - MOCK_METHOD1(GetCheckpointData, - void(ICheckpointData & data)); - MOCK_METHOD0(IncreaseCheckpointLoadCount, - void()); - MOCK_METHOD1(SetLoadOrigin, - void(LevelLoadOrigin origin)); -#endif - #if !defined(_RELEASE) MOCK_CONST_METHOD0(IsSavingResourceList, bool()); diff --git a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake b/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake deleted file mode 100644 index f862be24f6..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_enginesettings_mac_files.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../../EngineSettingsBackendApple.cpp - ../../EngineSettingsBackendApple.h -) diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake b/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake deleted file mode 100644 index db9fd5b464..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_enginesettings_windows_files.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../../EngineSettingsBackendWin32.cpp - ../../EngineSettingsBackendWin32.h -) diff --git a/Code/CryEngine/CryCommon/ProfileLog.h b/Code/CryEngine/CryCommon/ProfileLog.h deleted file mode 100644 index fbde619166..0000000000 --- a/Code/CryEngine/CryCommon/ProfileLog.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_PROFILELOG_H -#define CRYINCLUDE_CRYCOMMON_PROFILELOG_H -#pragma once - - -#include // <> required for Interfuscator -#include // <> required for Interfuscator - -struct ILogElement -{ - virtual ~ILogElement(){} - virtual ILogElement* Log (const char* name, const char* message) = 0; - virtual ILogElement* SetTime (float time) = 0; - virtual void Flush (stack_string& indent) = 0; -}; - -struct IProfileLogSystem -{ - virtual ~IProfileLogSystem(){} - virtual ILogElement* Log (const char* name, const char* msg) = 0; - virtual void SetTime (ILogElement* pElement, float time) = 0; - virtual void Release () = 0; -}; - -struct SHierProfileLogItem -{ - SHierProfileLogItem(const char* name, const char* msg, int inbDoLog) - : m_pLogElement(NULL) - , m_bDoLog(inbDoLog) - { - if (m_bDoLog) - { - m_pLogElement = gEnv->pProfileLogSystem->Log(name, msg); - m_startTime = gEnv->pTimer->GetAsyncTime(); - } - } - ~SHierProfileLogItem() - { - if (m_bDoLog) - { - CTimeValue endTime = gEnv->pTimer->GetAsyncTime(); - gEnv->pProfileLogSystem->SetTime(m_pLogElement, (endTime - m_startTime).GetMilliSeconds()); - } - } - -private: - int m_bDoLog; - CTimeValue m_startTime; - ILogElement* m_pLogElement; -}; - -#define HPROFILE_BEGIN(msg1, msg2, doLog) { SHierProfileLogItem __hier_profile_uniq_var_in_this_scope__(msg1, msg2, doLog); -#define HPROFILE_END() } - -#define HPROFILE(msg1, msg2, doLog) SHierProfileLogItem __hier_profile_uniq_var_in_this_scope__(msg1, msg2, doLog); - -#endif // CRYINCLUDE_CRYCOMMON_PROFILELOG_H diff --git a/Code/CryEngine/CryCommon/ProjectDefines.h b/Code/CryEngine/CryCommon/ProjectDefines.h index f82861d6e0..67ae58a324 100644 --- a/Code/CryEngine/CryCommon/ProjectDefines.h +++ b/Code/CryEngine/CryCommon/ProjectDefines.h @@ -78,9 +78,6 @@ typedef uint32 vtx_idx; #if defined(WIN32) || defined(WIN64) || LOG_CONST_CVAR_ACCESS #define RELEASE_LOGGING -//#if defined(_RELEASE) -//#define CVARS_WHITELIST -//#endif // defined(_RELEASE) #endif #if defined(_RELEASE) && !defined(RELEASE_LOGGING) @@ -181,32 +178,6 @@ typedef uint32 vtx_idx; #define SHADER_REFLECT_TEXTURE_SLOTS 0 #endif -#if (defined(WIN32) || defined(WIN64) || defined(AZ_PLATFORM_MAC)) && (!defined(AZ_MONOLITHIC_BUILD) || defined(RESOURCE_COMPILER)) -#define CRY_ENABLE_RC_HELPER 1 -#endif - -#if !defined(_RELEASE) && PROJECTDEFINES_H_TRAIT_ENABLE_SOFTCODE_SYSTEM - #define SOFTCODE_SYSTEM_ENABLED -#endif - -// Is SoftCoding enabled for this module? Usually set by the SoftCode AddIn in conjunction with a SoftCode.props file. -#ifdef SOFTCODE_ENABLED - -// Is this current compilation unit part of a SOFTCODE build? - #ifdef SOFTCODE -// Import any SC functions from the host module - #define SC_API __declspec(dllimport) - #else -// Export any SC functions from the host module - #define SC_API __declspec(dllexport) - #endif - -#else // SoftCode disabled - - #define SC_API - -#endif - // these enable and disable certain net features to give compatibility between PCs and consoles / profile and performance builds #define PC_CONSOLE_NET_COMPATIBLE 0 #define PROFILE_PERFORMANCE_NET_COMPATIBLE 0 @@ -292,10 +263,6 @@ typedef uint32 vtx_idx; # define ENABLE_LOADING_PROFILER // requires AZ_PROFILE_TELEMETRY to also be defined #endif -#if defined(SOFTCODE_ENABLED) - #error "SoftCode currently relies on CryMemoryManager being enabled. Either build without SoftCode support, or enable CryMemoryManager." -#endif - #if PROJECTDEFINES_H_TRAIT_USE_GPU_PARTICLES && !defined(NULL_RENDERER) #define GPU_PARTICLES 1 #else diff --git a/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp b/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp deleted file mode 100644 index 33373f7460..0000000000 --- a/Code/CryEngine/CryCommon/ResourceCompilerHelper.cpp +++ /dev/null @@ -1,639 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#include "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "ResourceCompilerHelper.h" -#include "EngineSettingsManager.h" - -// When complining CryTiffPlugin the mayaAssert.h is included that defined -// Assert as _Assert. This wreaks havoc with AZ_Assert since under the covers -// it calls AzCore::Debug::Trace::Assert, which gets transformed bo -// Trace::_Assert, which does not exist. Gotta love macros. Undefine Assert -// before we include semaphore so that it can compile correctly -#if defined(Assert) -#undef Assert -#endif - -#include -#include -#include -#include -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#include -#include // ShellExecuteW() -#endif - -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#include -#else -#undef RC_EXECUTABLE -#define RC_EXECUTABLE "rc.exe" -#endif - -#include -#include // lawsonn - we use std::string internally -#include - -namespace -{ - class LineStreamBuffer - { - public: - template - LineStreamBuffer(T* object, void (T::* method)(const char* line)) - : m_charCount(0) - , m_bTruncated(false) - { - m_target = new Target(object, method); - } - - ~LineStreamBuffer() - { - Flush(); - delete m_target; - } - - void HandleText(const char* text, int length) - { - const char* pos = text; - while (pos - text < length) - { - const char* start = pos; - - while (pos - text < length && *pos != '\n' && *pos != '\r') - { - ++pos; - } - - size_t n = pos - start; - if (m_charCount + n > kMaxCharCount) - { - n = kMaxCharCount - m_charCount; - m_bTruncated = true; - } - memcpy(&m_buffer[m_charCount], start, n); - m_charCount += n; - - if (pos - text < length) - { - Flush(); - while (pos - text < length && (*pos == '\n' || *pos == '\r')) - { - ++pos; - } - } - } - } - - void Flush() - { - if (m_charCount > 0) - { - m_buffer[m_charCount] = 0; - m_target->Call(m_buffer); - m_charCount = 0; - } - } - - bool IsTruncated() const - { - return m_bTruncated; - } - - private: - struct ITarget - { - virtual ~ITarget() {} - virtual void Call(const char* line) = 0; - }; - template - struct Target - : public ITarget - { - public: - Target(T* object, void (T::* method)(const char* line)) - : object(object) - , method(method) {} - virtual void Call(const char* line) - { - (object->*method)(line); - } - private: - T* object; - void (T::* method)(const char* line); - }; - - ITarget* m_target; - size_t m_charCount; - static const size_t kMaxCharCount = 2047; - char m_buffer[kMaxCharCount + 1]; - bool m_bTruncated; - }; - -#if !defined(AZ_PLATFORM_WINDOWS) - void MessageBoxW(int, const wchar_t* header, const wchar_t* message, unsigned long) - { -#if AZ_TRAIT_OS_PLATFORM_APPLE - CFStringEncoding encoding = (CFByteOrderLittleEndian == CFByteOrderGetCurrent()) ? - kCFStringEncodingUTF32LE : kCFStringEncodingUTF32BE; - CFStringRef header_ref = CFStringCreateWithBytes(nullptr, reinterpret_cast(header), wcslen(header) * sizeof(wchar_t), encoding, false); - CFStringRef message_ref = CFStringCreateWithBytes(nullptr, reinterpret_cast(message), wcslen(message) * sizeof(wchar_t), encoding, false); - - CFOptionFlags result; //result code from the message box - - CFUserNotificationDisplayAlert(0, kCFUserNotificationStopAlertLevel, 0, 0, 0, header_ref, message_ref, 0, 0, 0, &result); - - CFRelease(header_ref); - CFRelease(message_ref); -#endif - } -#endif -} - -namespace -{ - class RcLock - { - public: - RcLock() - : m_cs(0u, 1u) - { - m_cs.release(); - } - ~RcLock() - { - } - - void Lock() - { - m_cs.acquire(); - } - void Unlock() - { - m_cs.release(); - } - - private: - AZStd::semaphore m_cs; - }; - - - template - class RcAutoLock - { - public: - RcAutoLock(LockClass& lock) - : m_lock(lock) - { - m_lock.Lock(); - } - ~RcAutoLock() - { - m_lock.Unlock(); - } - - private: - RcAutoLock(); - RcAutoLock(const RcAutoLock&); - RcAutoLock& operator =(const RcAutoLock&); - - private: - LockClass& m_lock; - }; - - - HANDLE s_rcProcessHandle = 0; - RcLock s_rcProcessHandleLock; -} - -////////////////////////////////////////////////////////////////////////// -static void ShowMessageBoxRcNotFound([[maybe_unused]] const wchar_t* const szCmdLine, [[maybe_unused]] const wchar_t* const szDir) -{ - SettingsManagerHelpers::CFixedString tmp; - - tmp.append(L"The resource compiler (RC.EXE) was not found."); - MessageBoxW(0, tmp.c_str(), L"Error", MB_ICONERROR | MB_OK); -} - - -////////////////////////////////////////////////////////////////////////// -namespace -{ - class ResourceCompilerLineHandler - { - public: - ResourceCompilerLineHandler(IResourceCompilerListener* listener) - : m_listener(listener) - { - } - - void HandleLine(const char* line) - { - if (!m_listener || !line) - { - return; - } - - // check the first three characters to see if it's a warning or error. - bool bHasPrefix; - IResourceCompilerListener::MessageSeverity severity; - if ((line[0] == 'E') && (line[1] == ':') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Error; - line += 3; // skip the prefix - } - else if ((line[0] == 'W') && (line[1] == ':') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Warning; - line += 3; // skip the prefix - } - else if ((line[0] == ' ') && (line[1] == ' ') && (line[2] == ' ')) - { - bHasPrefix = true; - severity = IResourceCompilerListener::MessageSeverity_Info; - line += 3; // skip the prefix - } - else - { - bHasPrefix = false; - severity = IResourceCompilerListener::MessageSeverity_Info; - } - - if (bHasPrefix) - { - // skip thread info "%d>", if present - { - const char* p = line; - while (*p == ' ') - { - ++p; - } - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - if (*p == '>') - { - line = p + 1; - } - } - } - - // skip time info "%d:%d", if present - { - const char* p = line; - while (*p == ' ') - { - ++p; - } - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - if (*p == ':') - { - ++p; - if (isdigit(*p)) - { - while (isdigit(*p)) - { - ++p; - } - while (*p == ' ') - { - ++p; - } - line = p; - } - } - } - } - } - - m_listener->OnRCMessage(severity, line); - } - - private: - IResourceCompilerListener* m_listener; - }; - - // we now support macros like #ENGINEROOT# in the string: - void replaceAllInStringInPlace(std::string& inOut, const char* findValue, const char* replaceValue) - { - if (!findValue) - { - return; - } - - if (!replaceValue) - { - return; - } - - std::string::size_type pos = std::string::npos; - std::string::size_type replaceLen = strlen(findValue); - - while ((pos = inOut.find(findValue)) != std::string::npos) - { - inOut.replace(pos, replaceLen, replaceValue); - } - } - - // given a string that contains macros (like #ENGINEROOT#), eliminate the macros and replace them with the real data. - // note that in the 'remote' implementation, these macros are sent to the remote RC. It can then expand them for its own environment - // but in a local RC, these macros are expanded by the local environment. - void expandMacros(const char* inputString, char* outputString, std::size_t bufferSize) - { - if (!inputString) - { - return; - } - - if (!outputString) - { - return; - } - - AZStd::string_view rootFolder; - AZ::ComponentApplicationBus::BroadcastResult(rootFolder, &AZ::ComponentApplicationRequests::GetAppRoot); - - std::string finalString(inputString); - const AZStd::string rootFolderStr = rootFolder.data(); - replaceAllInStringInPlace(finalString, "#ENGINEROOT#", rootFolderStr.c_str()); - // put additional replacements here. - - azstrcpy(outputString, bufferSize, finalString.c_str()); - } -} - -////////////////////////////////////////////////////////////////////////// -IResourceCompilerHelper::ERcCallResult CResourceCompilerHelper::CallResourceCompiler( - const char* szFileName, - const char* szAdditionalSettings, - IResourceCompilerListener* listener, - bool bMayShowWindow, - bool bSilent, - bool bNoUserDialog, - const wchar_t* szWorkingDirectory, - [[maybe_unused]] const wchar_t* szRootPath) -{ -#if defined(AZ_PLATFORM_WINDOWS) - HANDLE hChildStdOutRd = INVALID_HANDLE_VALUE, hChildStdOutWr = INVALID_HANDLE_VALUE; - HANDLE hChildStdInRd = INVALID_HANDLE_VALUE, hChildStdInWr = INVALID_HANDLE_VALUE; - PROCESS_INFORMATION pi; -#else - FILE* hChildStdOutRd; -#endif - - { - RcAutoLock lock(s_rcProcessHandleLock); - - // make command for execution - SettingsManagerHelpers::CFixedString wRemoteCmdLine; - - - if (!szAdditionalSettings) - { - szAdditionalSettings = ""; - } - - // expand the additioanl settings. - char szActualFileName[512] = {0}; - char szActualAdditionalSettings[512] = {0}; - - expandMacros(szFileName, szActualFileName, 512); - expandMacros(szAdditionalSettings, szActualAdditionalSettings, 512); - - CSettingsManagerTools smTools = CSettingsManagerTools(); // moved this line to after macro expansion to avoid multiple of these existing at once. - - AZStd::string_view exeFolderName; - AZ::ComponentApplicationBus::BroadcastResult(exeFolderName, &AZ::ComponentApplicationRequests::GetExecutableFolder); - - wchar_t szRegSettingsBuffer[1024]; - smTools.GetEngineSettingsManager()->GetValueByRef("RC_Parameters", SettingsManagerHelpers::CWCharBuffer(szRegSettingsBuffer, sizeof(szRegSettingsBuffer))); - bool enableSourceControl = true; - smTools.GetEngineSettingsManager()->GetValueByRef("RC_EnableSourceControl", enableSourceControl); - - wRemoteCmdLine.appendAscii("\""); - wRemoteCmdLine.appendAscii(exeFolderName.data(), exeFolderName.size()); - wRemoteCmdLine.appendAscii("/"); - wRemoteCmdLine.appendAscii(RC_EXECUTABLE); - wRemoteCmdLine.appendAscii("\""); - - if (!enableSourceControl) - { - wRemoteCmdLine.appendAscii(" -nosourcecontrol "); - } - - if (!szFileName) - { - wRemoteCmdLine.appendAscii(" -userdialog=0 "); - wRemoteCmdLine.appendAscii(szActualAdditionalSettings); - wRemoteCmdLine.appendAscii(" "); - wRemoteCmdLine.append(szRegSettingsBuffer); - } - else - { - wRemoteCmdLine.appendAscii(" \""); - wRemoteCmdLine.appendAscii(szActualFileName); - wRemoteCmdLine.appendAscii("\""); - wRemoteCmdLine.appendAscii(bNoUserDialog ? " -userdialog=0 " : " -userdialog=1 "); - wRemoteCmdLine.appendAscii(szActualAdditionalSettings); - wRemoteCmdLine.appendAscii(" "); - wRemoteCmdLine.append(szRegSettingsBuffer); - } - - // Create a pipe to read the stdout of the RC. - SECURITY_ATTRIBUTES saAttr; - if (listener) - { -#if defined(AZ_PLATFORM_WINDOWS) - ZeroMemory(&saAttr, sizeof(saAttr)); - saAttr.bInheritHandle = TRUE; - saAttr.lpSecurityDescriptor = 0; - CreatePipe(&hChildStdOutRd, &hChildStdOutWr, &saAttr, 0); - SetHandleInformation(hChildStdOutRd, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN - CreatePipe(&hChildStdInRd, &hChildStdInWr, &saAttr, 0); - SetHandleInformation(hChildStdInWr, HANDLE_FLAG_INHERIT, 0); // Need to do this according to MSDN -#endif - } - -#if defined(AZ_PLATFORM_WINDOWS) - STARTUPINFOW si; - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - si.dwX = 100; - si.dwY = 100; - if (listener) - { - si.hStdError = hChildStdOutWr; - si.hStdOutput = hChildStdOutWr; - si.hStdInput = hChildStdInRd; - si.dwFlags = STARTF_USEPOSITION | STARTF_USESTDHANDLES; - } - else - { - si.dwFlags = STARTF_USEPOSITION; - } - - ZeroMemory(&pi, sizeof(pi)); -#endif - - bool bShowWindow; - if (bMayShowWindow) - { - wchar_t buffer[20]; - smTools.GetEngineSettingsManager()->GetValueByRef("ShowWindow", SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))); - bShowWindow = (wcscmp(buffer, L"true") == 0); - } - else - { - bShowWindow = false; - } - -#if defined(AZ_PLATFORM_WINDOWS) - const wchar_t* szStartingDirectory = szWorkingDirectory; - if (!szStartingDirectory) - { - char currentDirectory[MAX_PATH]; - AZ::Utils::GetExecutableDirectory(currentDirectory, MAX_PATH); - SettingsManagerHelpers::CFixedString wCurrentDirectory; - wCurrentDirectory.appendAscii(currentDirectory); - szStartingDirectory = wCurrentDirectory.c_str(); - } - - - if (!CreateProcessW( - NULL, // No module name (use command line). - const_cast(wRemoteCmdLine.c_str()), // Command line. - NULL, // Process handle not inheritable. - NULL, // Thread handle not inheritable. - TRUE, // Set handle inheritance to TRUE. - bShowWindow ? 0 : CREATE_NO_WINDOW, // creation flags. - NULL, // Use parent's environment block. - szStartingDirectory, // Set starting directory. - &si, // Pointer to STARTUPINFO structure. - &pi)) // Pointer to PROCESS_INFORMATION structure. - { - // The following code block is commented out instead of being deleted - // because it's good to have at hand for a debugging session. - #if 0 - const size_t charsInMessageBuffer = 32768; // msdn about FormatMessage(): "The output buffer cannot be larger than 64K bytes." - wchar_t szMessageBuffer[charsInMessageBuffer] = L""; - FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, szMessageBuffer, charsInMessageBuffer, NULL); - GetCurrentDirectoryW(charsInMessageBuffer, szMessageBuffer); - #endif - - if (!bSilent) - { - ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szStartingDirectory); - } - - return eRcCallResult_notFound; - } - - s_rcProcessHandle = pi.hProcess; -#else - int fd = open(".", O_RDONLY); - char remoteCmdLineUtf8[MAX_PATH * 8]; - char workingDirectory[MAX_PATH * 8]; - ConvertUtf16ToUtf8(wRemoteCmdLine.c_str(), SettingsManagerHelpers::CCharBuffer(remoteCmdLineUtf8, MAX_PATH * 8)); - if (szWorkingDirectory) - { - ConvertUtf16ToUtf8(szWorkingDirectory, SettingsManagerHelpers::CCharBuffer(workingDirectory, MAX_PATH * 8)); - chdir(workingDirectory); - } - hChildStdOutRd = popen(remoteCmdLineUtf8, "r"); - fchdir(fd); - if (hChildStdOutRd == nullptr) - { - if (!bSilent) - { - ShowMessageBoxRcNotFound(wRemoteCmdLine.c_str(), szWorkingDirectory); - } - return eRcCallResult_notFound; - } -#endif - } - - bool bFailedToReadOutput = false; - - if (listener) - { -#if defined(AZ_PLATFORM_WINDOWS) - // Close the pipe that writes to the child process, since we don't actually have any input for it. - CloseHandle(hChildStdInWr); - - // Read all the output from the child process. - CloseHandle(hChildStdOutWr); -#endif - ResourceCompilerLineHandler lineHandler(listener); - LineStreamBuffer lineBuffer(&lineHandler, &ResourceCompilerLineHandler::HandleLine); - for (;; ) - { - char buffer[2048]; - DWORD bytesRead; -#if defined(AZ_PLATFORM_WINDOWS) - if (!ReadFile(hChildStdOutRd, buffer, sizeof(buffer), &bytesRead, NULL) || (bytesRead == 0)) -#else - if (fgets(buffer, sizeof(buffer), hChildStdOutRd) == nullptr || (bytesRead = strlen(buffer) == 0)) -#endif - { - break; - } - lineBuffer.HandleText(buffer, bytesRead); - } - - bFailedToReadOutput = lineBuffer.IsTruncated(); - } - -#if defined(AZ_PLATFORM_WINDOWS) - // Wait until child process exits. - WaitForSingleObject(pi.hProcess, INFINITE); -#else - DWORD exitCode = pclose(hChildStdOutRd); -#endif - -#if defined(AZ_PLATFORM_WINDOWS) - RcAutoLock lock(s_rcProcessHandleLock); - s_rcProcessHandle = 0; - - DWORD exitCode = eRcExitCode_Error; - if (bFailedToReadOutput || GetExitCodeProcess(pi.hProcess, &exitCode) == 0) - { - exitCode = eRcExitCode_Error; - } - - // Close process and thread handles. - CloseHandle(pi.hProcess); - CloseHandle(pi.hThread); -#endif - - return ConvertResourceCompilerExitCodeToResultCode(exitCode); -} - - -#endif //(CRY_ENABLE_RC_HELPER) diff --git a/Code/CryEngine/CryCommon/ResourceCompilerHelper.h b/Code/CryEngine/CryCommon/ResourceCompilerHelper.h deleted file mode 100644 index 913d72f642..0000000000 --- a/Code/CryEngine/CryCommon/ResourceCompilerHelper.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H -#define CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H - -#pragma once - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "IResourceCompilerHelper.h" - -////////////////////////////////////////////////////////////////////////// -// Provides settings and functions to make calls to RC. -// calls RC locally. only works on windows, does not exist on other platforms -// note: You shouldn't be calling this directly -// instead, you should be calling it via the IResourceCompilerHelper interface. -// since it may be replaced with a custom RC for your platform or a remote invocation -class CResourceCompilerHelper - : public IResourceCompilerHelper -{ -public: - virtual ERcCallResult CallResourceCompiler( - const char* szFileName = 0, - const char* szAdditionalSettings = 0, - IResourceCompilerListener* listener = 0, - bool bMayShowWindow = true, - bool bSilent = false, - bool bNoUserDialog = false, - const wchar_t* szWorkingDirectory = 0, - const wchar_t* szRootPath = 0) override; -}; - -#endif // CRY_ENABLE_RC_HELPER - -#endif // CRYINCLUDE_CRYCOMMON_RESOURCECOMPILERHELPER_H diff --git a/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp b/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp deleted file mode 100644 index 9746b00574..0000000000 --- a/Code/CryEngine/CryCommon/SettingsManagerHelpers.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "ProjectDefines.h" - -#if defined(CRY_ENABLE_RC_HELPER) - -#include "SettingsManagerHelpers.h" -#include "EngineSettingsManager.h" - -#include -#include -#include - -#include -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#include -#include //ShellExecuteW() -#pragma comment(lib, "Shell32.lib") -#endif -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#endif - -bool SettingsManagerHelpers::Utf16ContainsAsciiOnly(const wchar_t* wstr) -{ - while (*wstr) - { - if (*wstr > 127 || *wstr < 0) - { - return false; - } - ++wstr; - } - return true; -} - - -void SettingsManagerHelpers::ConvertUtf16ToUtf8(const wchar_t* src, CCharBuffer dst) -{ - if (dst.getSizeInElements() <= 0) - { - return; - } - - if (src[0] == 0) - { - dst[0] = 0; - } - else - { - const std::codecvt& utf8Utf16Facet = std::use_facet>(std::locale()); - std::mbstate_t mb{}; - const wchar_t* from_next; - char* to_next; - std::codecvt_base::result result = utf8Utf16Facet.out(mb, src, src + wcslen(src), from_next, dst.getPtr(), dst.getPtr() + dst.getSizeInElements(), to_next); - if (result != std::codecvt_base::ok) - { - dst[0] = 0; - } - else - { - to_next = 0; - } - } -} - - -void SettingsManagerHelpers::ConvertUtf8ToUtf16(const char* src, CWCharBuffer dst) -{ - if (dst.getSizeInElements() <= 0) - { - return; - } - - if (src[0] == 0) - { - dst[0] = 0; - } - else - { - const std::codecvt& utf8Utf16Facet = std::use_facet>(std::locale()); - std::mbstate_t mb{}; - const char* from_next; - wchar_t* to_next; - std::codecvt_base::result result = utf8Utf16Facet.in(mb, src, src + strlen(src), from_next, dst.getPtr(), dst.getPtr() + dst.getSizeInElements(), to_next); - if (result != std::codecvt_base::ok) - { - dst[0] = 0; - } - else - { - to_next = 0; - } - } -} - - -void SettingsManagerHelpers::GetAsciiFilename(const wchar_t* wfilename, CCharBuffer buffer) -{ - if (buffer.getSizeInElements() <= 0) - { - return; - } - - if (wfilename[0] == 0) - { - buffer[0] = 0; - return; - } - - if (Utf16ContainsAsciiOnly(wfilename)) - { - ConvertUtf16ToUtf8(wfilename, buffer); - return; - } - -#if defined(AZ_PLATFORM_WINDOWS) - // The path is non-ASCII unicode, so let's resort to short filenames (they are always ASCII-only, I hope) - wchar_t shortW[MAX_PATH]; - const int bufferCharCount = sizeof(shortW) / sizeof(shortW[0]); - const int charCount = GetShortPathNameW(wfilename, shortW, bufferCharCount); - if (charCount <= 0 || charCount >= bufferCharCount) - { - buffer[0] = 0; - return; - } - - shortW[charCount] = 0; - if (!Utf16ContainsAsciiOnly(shortW)) - { - buffer[0] = 0; - return; - } - - ConvertUtf16ToUtf8(shortW, buffer); -#else - buffer[0] = 0; -#endif -} - - -////////////////////////////////////////////////////////////////////////// -CSettingsManagerTools::CSettingsManagerTools(const wchar_t* szModuleName) -{ - m_pSettingsManager = new CEngineSettingsManager(szModuleName); -} - -////////////////////////////////////////////////////////////////////////// -CSettingsManagerTools::~CSettingsManagerTools() -{ - delete m_pSettingsManager; -} - -////////////////////////////////////////////////////////////////////////// -bool CSettingsManagerTools::GetInstalledBuildPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path) -{ - return m_pSettingsManager->GetInstalledBuildRootPathUtf16(index, name, path); -} - - -bool CSettingsManagerTools::GetInstalledBuildPathAscii(const int index, SettingsManagerHelpers::CCharBuffer name, SettingsManagerHelpers::CCharBuffer path) -{ - wchar_t wName[MAX_PATH]; - wchar_t wPath[MAX_PATH]; - if (GetInstalledBuildPathUtf16(index, SettingsManagerHelpers::CWCharBuffer(wName, sizeof(wName)), SettingsManagerHelpers::CWCharBuffer(wPath, sizeof(wPath)))) - { - SettingsManagerHelpers::GetAsciiFilename(wName, name); - SettingsManagerHelpers::GetAsciiFilename(wPath, path); - return true; - } - return false; -} - - - -////////////////////////////////////////////////////////////////////////// -static bool FileExists(const wchar_t* filename) -{ -#if defined(AZ_PLATFORM_WINDOWS) - const DWORD dwAttrib = GetFileAttributesW(filename); - return dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY); -#else - char utf8Filename[MAX_PATH]; - SettingsManagerHelpers::ConvertUtf16ToUtf8(filename, SettingsManagerHelpers::CCharBuffer(utf8Filename, sizeof(utf8Filename))); - struct stat buffer; - return (stat(utf8Filename, &buffer) == 0); -#endif -} - - -////////////////////////////////////////////////////////////////////////// -void CSettingsManagerTools::GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer wbuffer) -{ - if (wbuffer.getSizeInElements() <= 0) - { - return; - } - - AZStd::string_view exePath; - AZ::ComponentApplicationBus::BroadcastResult(exePath, &AZ::ComponentApplicationRequests::GetExecutableFolder); - - SettingsManagerHelpers::CFixedString editorExe; - editorExe = wbuffer.getPtr(); - editorExe.appendAscii(exePath.data(), exePath.size()); - - if (editorExe.length() <= 0) - { - wbuffer[0] = 0; - return; - } - - bool bFound = false; - if (Is64bitWindows()) - { - const size_t len = editorExe.length(); - editorExe.appendAscii("/Editor.exe"); - bFound = FileExists(editorExe.c_str()); - if (!bFound) - { - editorExe.setLength(len); - } - } - - const size_t sizeToCopy = (editorExe.length() + 1) * sizeof(wbuffer[0]); - if (!bFound || sizeToCopy > wbuffer.getSizeInBytes()) - { - wbuffer[0] = 0; - } - else - { - memcpy(wbuffer.getPtr(), editorExe.c_str(), sizeToCopy); - } -} - - -////////////////////////////////////////////////////////////////////////// -bool CSettingsManagerTools::CallEditor(void** pEditorWindow, [[maybe_unused]] void* hParent, const char* pWindowName, const char* pFlag) -{ -#if !defined(AZ_PLATFORM_WINDOWS) - AZ_Assert(false, "CSettingsManagerTools::CallEditor is not supported on this platform!"); - return false; -#else - HWND window = ::FindWindowA(NULL, pWindowName); - if (window) - { - *pEditorWindow = window; - return true; - } - else - { - *pEditorWindow = 0; - - wchar_t buffer[512] = { L'\0' }; - GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer(buffer, sizeof(buffer))); - - SettingsManagerHelpers::CFixedString wFlags; - SettingsManagerHelpers::ConvertUtf8ToUtf16(pFlag, wFlags.getBuffer()); - wFlags.setLength(wcslen(wFlags.c_str())); - - if (buffer[0] != '\0') - { - INT_PTR hIns = (INT_PTR)ShellExecuteW(NULL, L"open", buffer, wFlags.c_str(), NULL, SW_SHOWNORMAL); - if (hIns > 32) - { - return true; - } - else - { - MessageBoxA(0, "Editor.exe was not found.\n\nPlease verify CryENGINE root path.", "Error", MB_ICONERROR | MB_OK); - } - } - } - - return false; -#endif -} - -////////////////////////////////////////////////////////////////////////// -// Modified version of -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms684139(v=vs.85).aspx -bool CSettingsManagerTools::Is64bitWindows() -{ -#if defined(_WIN64) - // 64-bit programs run only on 64-bit Windows - return true; -#elif !defined(AZ_PLATFORM_WINDOWS) - return false; -#else - // 32-bit programs run on both 32-bit and 64-bit Windows - static bool bWin64 = false; - static bool bOnce = true; - if (bOnce) - { - typedef BOOL (WINAPI * LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); - LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process"); - if (fnIsWow64Process != NULL) - { - BOOL itIsWow64Process = FALSE; - if (fnIsWow64Process(GetCurrentProcess(), &itIsWow64Process)) - { - bWin64 = (itIsWow64Process == TRUE); - } - } - bOnce = false; - } - return bWin64; -#endif -} - -#endif // #if defined(CRY_ENABLE_RC_HELPER) - -// eof diff --git a/Code/CryEngine/CryCommon/SettingsManagerHelpers.h b/Code/CryEngine/CryCommon/SettingsManagerHelpers.h deleted file mode 100644 index e05d2b97aa..0000000000 --- a/Code/CryEngine/CryCommon/SettingsManagerHelpers.h +++ /dev/null @@ -1,491 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SETTINGSMANAGERHELPERS_H -#define CRYINCLUDE_CRYCOMMON_SETTINGSMANAGERHELPERS_H -#pragma once - -#include "ProjectDefines.h" -#include // memcpy -#include // std::min - - -namespace SettingsManagerHelpers -{ - namespace Utils - { - inline size_t strlen(const char* p) - { - return p ? ::strlen(p) : 0; - } - - inline size_t strcmp(const char* p0, const char* p1) - { - return ::strcmp(p0, p1); - } - - - inline size_t strlen(const wchar_t* p) - { - return p ? ::wcslen(p) : 0; - } - - inline size_t strcmp(const wchar_t* p0, const wchar_t* p1) - { - return ::wcscmp(p0, p1); - } - } - - // The function copies characters from src to dst one by one until any of - // the following conditions is met: - // 1) the end of the destination buffer (minus one character) is reached - // 2) the end of the source buffer is reached - // 3) zero character is found in the source buffer - // - // When any of 1), 2), 3) happens, the function writes the terminating zero - // character to the destination buffer and return. - // - // The function guarantees writing the terminating zero character to the - // destination buffer (if the buffer can fit at least one character). - // - // The function returns false when a null pointer is passed or when - // clamping happened (i.e. when the end of the destination buffer is - // reached but the source has some characters left). - inline bool strcpy_with_clamp(char* const dst, size_t const dst_size_in_bytes, const char* const src, size_t const src_size_in_bytes = (size_t)-1) - { - if (!dst || dst_size_in_bytes < sizeof(char)) - { - return false; - } - - if (!src || src_size_in_bytes < sizeof(char)) - { - dst[0] = 0; - return src != 0; // we return true for non-null src without characters - } - - const size_t src_n = src_size_in_bytes; - const size_t n = (std::min)(dst_size_in_bytes - 1, src_n); - - for (size_t i = 0; i < n; ++i) - { - dst[i] = src[i]; - if (!src[i]) - { - return true; - } - } - - dst[n] = 0; - return n >= src_n || src[n] == 0; - } - - - template - class CBuffer - { - public: - typedef T element_type; - - private: - element_type* m_ptr; - size_t m_sizeInBytes; - - public: - CBuffer(element_type* ptr, size_t sizeInBytes) - : m_ptr(ptr) - , m_sizeInBytes(ptr ? sizeInBytes : 0) - { - } - - const element_type* getPtr() const - { - return m_ptr; - } - - element_type* getPtr() - { - return m_ptr; - } - - size_t getSizeInElements() const - { - return m_sizeInBytes / sizeof(element_type); - } - - size_t getSizeInBytes() const - { - return m_sizeInBytes; - } - - const element_type& operator[](size_t pos) const - { - return m_ptr[pos]; - } - - element_type& operator[](size_t pos) - { - return m_ptr[pos]; - } - }; - - typedef CBuffer CCharBuffer; - typedef CBuffer CWCharBuffer; - - - template - class CFixedString - { - public: - typedef T char_type; - static const size_t npos = ~size_t(0); - private: - size_t m_count; // # chars (not counting trailing zero) - char_type m_buffer[CAPACITY + 1]; // '+ 1' is for trailing zero - - public: - CFixedString() - { - clear(); - } - - CFixedString(const char_type* p) - { - set(p); - } - - CFixedString& operator=(const char_type* p) - { - set(p); - return *this; - } - - CFixedString& operator=(const CFixedString& s) - { - if (&s != this) - { - set(s.m_buffer, s.m_count); - } - return *this; - } - - CBuffer getBuffer() - { - return CBuffer(m_buffer, (CAPACITY + 1) * sizeof(char_type)); - } - - char_type operator[](const size_t i) const - { - return m_buffer[i]; - } - - const char_type* c_str() const - { - return &m_buffer[0]; - } - - const size_t length() const - { - return m_count; - } - - void clear() - { - m_count = 0; - m_buffer[m_count] = 0; - } - - void setLength(size_t n) - { - m_count = (n <= CAPACITY) ? n : CAPACITY; - m_buffer[m_count] = 0; - } - - char_type* ptr() - { - return &m_buffer[0]; - } - - CFixedString substr(size_t pos = 0, size_t n = npos) const - { - CFixedString s; - if (pos < m_count && n > 0) - { - if (n > m_count || pos + n > m_count) - { - n = m_count - pos; - } - s.set(&m_buffer[pos], n); - } - return s; - } - - void set(const char_type* p, size_t n) - { - if (p == 0 || n <= 0) - { - m_count = 0; - } - else - { - m_count = (n > CAPACITY) ? CAPACITY : n; - // memmove() is used because p may point to m_buffer - memmove(m_buffer, p, m_count * sizeof(*p)); - } - m_buffer[m_count] = 0; - } - - void set(const char_type* p) - { - if (p && p[0]) - { - set(p, Utils::strlen(p)); - } - else - { - clear(); - } - } - - void append(const char_type* p, size_t n) - { - if (p && n > 0) - { - if (n > CAPACITY || m_count + n > CAPACITY) - { - // assert(0); - n = CAPACITY - m_count; - } - if (n > 0) - { - memcpy(&m_buffer[m_count], p, n * sizeof(*p)); - m_count += n; - m_buffer[m_count] = 0; - } - } - } - - void append(const char_type* p) - { - if (p && p[0]) - { - append(p, Utils::strlen(p)); - } - } - - void appendAscii(const char* p, size_t n) - { - if (p && n > 0) - { - if (n > CAPACITY || m_count + n > CAPACITY) - { - // assert(0); - n = CAPACITY - m_count; - } - if (n > 0) - { - for (size_t i = 0; i < n; ++i) - { - m_buffer[m_count + i] = p[i]; - } - m_count += n; - m_buffer[m_count] = 0; - } - } - } - - void appendAscii(const char* p) - { - if (p && p[0]) - { - appendAscii(p, Utils::strlen(p)); - } - } - - bool equals(const char_type* p) const - { - return (p == 0 || p[0] == 0) - ? (m_count == 0) - : (Utils::strcmp(m_buffer, p) == 0); - } - - void trim() - { - size_t begin = 0; - while (begin < m_count && (m_buffer[begin] == ' ' || m_buffer[begin] == '\r' || m_buffer[begin] == '\t' || m_buffer[begin] == '\n')) - { - ++begin; - } - - if (begin >= m_count) - { - clear(); - return; - } - - size_t end = m_count - 1; - while (end > begin && (m_buffer[begin] == ' ' || m_buffer[begin] == '\r' || m_buffer[begin] == '\t' || m_buffer[begin] == '\n')) - { - --end; - } - - m_count = end + 1; - m_buffer[m_count] = 0; - - if (begin > 0) - { - set(&m_buffer[begin], m_count - begin); - } - } - }; - - - struct SKeyValue - { - CFixedString key; - CFixedString value; - }; - - - template - class CKeyValueArray - { - private: - size_t count; - SKeyValue data[CAPACITY]; - - public: - CKeyValueArray() - : count(0) - { - } - - size_t size() const - { - return count; - } - - const SKeyValue& operator[](size_t i) const - { - return data[i]; - } - - void clear() - { - count = 0; - } - - const SKeyValue* find(const char* key) const - { - for (size_t i = 0; i < count; ++i) - { - if (data[i].key.equals(key)) - { - return &data[i]; - } - } - return 0; - } - - SKeyValue* find(const char* key) - { - for (size_t i = 0; i < count; ++i) - { - if (data[i].key.equals(key)) - { - return &data[i]; - } - } - return 0; - } - - SKeyValue* set(const char* key, const wchar_t* value) - { - SKeyValue* p = find(key); - if (!p) - { - if (count >= CAPACITY) - { - return 0; - } - p = &data[count++]; - p->key = key; - } - p->value = value; - return p; - } - }; - - -#if defined(CRY_ENABLE_RC_HELPER) - - bool Utf16ContainsAsciiOnly(const wchar_t* wstr); - - void ConvertUtf16ToUtf8(const wchar_t* src, CCharBuffer dst); - - void ConvertUtf8ToUtf16(const char* src, CWCharBuffer dst); - - template - void AddPathSeparator(CFixedString& wstr) - { - if (wstr.length() <= 0) - { - return; - } - - if (wstr[wstr.length() - 1] == L'/' || wstr[wstr.length() - 1] == L'\\') - { - return; - } - - wstr.appendAscii("/"); - } - - void GetAsciiFilename(const wchar_t* wfilename, CCharBuffer buffer); - -#endif // #if defined(CRY_ENABLE_RC_HELPER) -} // namespace SettingsManagerHelpers - - -#if defined(CRY_ENABLE_RC_HELPER) - -////////////////////////////////////////////////////////////////////////// -// Provides settings and functions to make calls to RC. -class CEngineSettingsManager; -class CSettingsManagerTools -{ -public: - CSettingsManagerTools(const wchar_t* szModuleName = 0); - ~CSettingsManagerTools(); - -private: - CEngineSettingsManager* m_pSettingsManager; - -public: - CEngineSettingsManager* GetEngineSettingsManager() - { - return m_pSettingsManager; - } - - bool GetInstalledBuildPathUtf16(const int index, SettingsManagerHelpers::CWCharBuffer name, SettingsManagerHelpers::CWCharBuffer path); - bool GetInstalledBuildPathAscii(const int index, SettingsManagerHelpers::CCharBuffer name, SettingsManagerHelpers::CCharBuffer path); - - void GetEditorExecutable(SettingsManagerHelpers::CWCharBuffer wbuffer); - bool CallEditor(void** pEditorWindow, void* hParent, const char* pWndName, const char* pFlag); - - static bool Is64bitWindows(); -}; - -#endif // #if defined(CRY_ENABLE_RC_HELPER) - -#endif // CRYINCLUDE_CRYCOMMON_SETTINGSMANAGERHELPERS_H diff --git a/Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake b/Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake deleted file mode 100644 index 0fbd223d21..0000000000 --- a/Code/CryEngine/CryCommon/crycommon_enginesettings_files.cmake +++ /dev/null @@ -1,27 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ProjectDefines.h - SettingsManagerHelpers.cpp - SettingsManagerHelpers.h - EngineSettingsManager.cpp - EngineSettingsManager.h - EngineSettingsBackend.cpp - EngineSettingsBackend.h - ResourceCompilerHelper.cpp - ResourceCompilerHelper.h -) - -# Remove files that cause #define collisions on Mac due to multiple inclusions of 'AppleSpecific.h' and include orders -set(SKIP_UNITY_BUILD_INCLUSION_FILES - SettingsManagerHelpers.cpp -) diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index ca95802fd9..77b51825f1 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -22,7 +22,6 @@ set(FILES IConsole.h IEntityRenderState.h IEntityRenderState_info.cpp - IFlares.h IFont.h IFunctorBase.h IFuncVariable.h @@ -40,12 +39,10 @@ set(FILES ILog.h ILZ4Decompressor.h IMaterial.h - IMaterialEffects.h IMemory.h IMeshBaking.h IMiniLog.h IMovieSystem.h - INotificationNetwork.h IPhysics.h IPhysicsDebugRenderer.h IPostEffectGroup.h @@ -55,12 +52,10 @@ set(FILES IRenderer.h IRenderMesh.h IResourceCollector.h - IResourceCompilerHelper.h IResourceManager.h ISerialize.h IShader.h IShader_info.h - ISoftCodeMgr.h ISplines.h IStatObj.h StatObjBus.h @@ -69,11 +64,8 @@ set(FILES IStreamEngineDefs.h ISurfaceType.h ISystem.h - ISystemScheduler.h ITextModeConsole.h ITexture.h - IThreadManager.h - IThreadTask.h ITimer.h IValidator.h IVideoRenderer.h @@ -108,7 +100,6 @@ set(FILES MaterialUtils.h MTPseudoRandom.cpp CryTypeInfo.cpp - IResourceCompilerHelper.cpp BaseTypes.h CompileTimeAssert.h CryThreadSafeWorkerContainer.h @@ -170,7 +161,6 @@ set(FILES PoolAllocator.h primitives.h primitives_info.h - ProfileLog.h ProjectDefines.h Range.h RenderContextConfig.h diff --git a/Code/CryEngine/CryCommon/physinterface.h b/Code/CryEngine/CryCommon/physinterface.h index 036f7e29ab..dd787d48b7 100644 --- a/Code/CryEngine/CryCommon/physinterface.h +++ b/Code/CryEngine/CryCommon/physinterface.h @@ -3244,7 +3244,6 @@ struct PhysicsVars int nBodiesLargeGroup; int bBreakOnValidation; int bLogActiveObjects; - int bMultiplayer; int bProfileEntities; int bProfileFunx; int bProfileGroups; diff --git a/Code/CryEngine/CryCommon/platform_impl.cpp b/Code/CryEngine/CryCommon/platform_impl.cpp index 142f07e5e7..885ea2984d 100644 --- a/Code/CryEngine/CryCommon/platform_impl.cpp +++ b/Code/CryEngine/CryCommon/platform_impl.cpp @@ -33,7 +33,7 @@ #define PLATFORM_IMPL_H_SECTION_VIRTUAL_ALLOCATORS 7 #endif -SC_API struct SSystemGlobalEnvironment* gEnv = nullptr; +struct SSystemGlobalEnvironment* gEnv = nullptr; // Traits #if defined(AZ_RESTRICTED_PLATFORM) @@ -147,7 +147,6 @@ void* GetDetachEnvironmentSymbol() #endif // !defined(SOFTCODE) bool g_bProfilerEnabled = false; -int g_iTraceAllocations = 0; ////////////////////////////////////////////////////////////////////////// // global random number generator used by cry_random functions diff --git a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp b/Code/CryEngine/CrySystem/AutoDetectSpec.cpp index 31eee85d90..aa344684e3 100644 --- a/Code/CryEngine/CrySystem/AutoDetectSpec.cpp +++ b/Code/CryEngine/CrySystem/AutoDetectSpec.cpp @@ -1044,11 +1044,9 @@ void CSystem::AutoDetectSpec(const bool detectResolution) unsigned int numSysCores(1), numProcCores(1); Win32SysInspect::GetNumCPUCores(numSysCores, numProcCores); CryLogAlways("--- Number of available cores: %d (out of %d)", numProcCores, numSysCores); - const int numLogicalProcs = gEnv->pi.numLogicalProcessors; - CryLogAlways("--- Number of logical processors: %d", numLogicalProcs); // get CPU rating - const int cpuRating = numLogicalProcs >= 8 ? 3 : (numLogicalProcs >= 6 ? 2 : 1); + const int cpuRating = numProcCores >= 4 ? 3 : (numProcCores >= 3 ? 2 : 1); // get GPU info unsigned int gpuVendorId(0), gpuDeviceId(0), totVidMem(0); diff --git a/Code/CryEngine/CrySystem/CMakeLists.txt b/Code/CryEngine/CrySystem/CMakeLists.txt index 1a5593e5d8..3261526e8e 100644 --- a/Code/CryEngine/CrySystem/CMakeLists.txt +++ b/Code/CryEngine/CrySystem/CMakeLists.txt @@ -89,7 +89,6 @@ ly_add_target( Legacy::CrySystem.Static AZ::AzCore Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static ) ################################################################################ @@ -109,7 +108,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) PRIVATE AZ::AzTest Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static Legacy::CrySystem.Static AZ::AzFramework ) diff --git a/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp b/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp index 946edb9b64..b6eced4df3 100644 --- a/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp +++ b/Code/CryEngine/CrySystem/ConsoleBatchFile.cpp @@ -87,14 +87,6 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) filename = PathUtil::ReplaceExtension(filename, "cfg"); } -#if defined(CVARS_WHITELIST) - bool ignoreWhitelist = true; - if (_stricmp(sFilename, "autoexec.cfg") == 0) - { - ignoreWhitelist = false; - } -#endif // defined(CVARS_WHITELIST) - ////////////////////////////////////////////////////////////////////////// CCryFile file; @@ -179,18 +171,9 @@ bool CConsoleBatchFile::ExecuteConfigFile(const char* sFilename) continue; } -#if defined(CVARS_WHITELIST) - if (ignoreWhitelist || (gEnv->pSystem->GetCVarsWhiteList() && gEnv->pSystem->GetCVarsWhiteList()->IsWhiteListed(strLine, false))) -#endif // defined(CVARS_WHITELIST) { m_pConsole->ExecuteString(strLine); } -#if defined(CVARS_WHITELIST) - else if (gEnv->IsDedicated()) - { - gEnv->pSystem->GetILog()->LogError("Failed to execute command: '%s' as it is not whitelisted\n", strLine.c_str()); - } -#endif // defined(CVARS_WHITELIST) } // See above // ((CXConsole*)m_pConsole)->SetStatus(bConsoleStatus); diff --git a/Code/CryEngine/CrySystem/CrySystem_precompiled.h b/Code/CryEngine/CrySystem/CrySystem_precompiled.h index b446199b4e..1fab2d4ce1 100644 --- a/Code/CryEngine/CrySystem/CrySystem_precompiled.h +++ b/Code/CryEngine/CrySystem/CrySystem_precompiled.h @@ -117,7 +117,6 @@ struct IRenderer; struct ISystem; struct ITimer; struct IFFont; -struct IKeyboard; struct ICVar; struct IConsole; struct IProcess; diff --git a/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h b/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h deleted file mode 100644 index 4c920898f0..0000000000 --- a/Code/CryEngine/CrySystem/CryThreadUtil_pthread.h +++ /dev/null @@ -1,259 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -////////////////////////////////////////////////////////////////////////// -// NOTE: INTERNAL HEADER NOT FOR PUBLIC USE -// This header should only be include by SystemThreading.cpp only -// It provides an interface for PThread intrinsics -// It's only client should be CThreadManager which should manage all thread interaction -#if !defined(INCLUDED_FROM_SYSTEM_THREADING_CPP) -# error "CRYTEK INTERNAL HEADER. ONLY INCLUDE FROM SYSTEMTHRADING.CPP." -#endif -////////////////////////////////////////////////////////////////////////// - -#define DEFAULT_THREAD_STACK_SIZE_KB 0 -#define CRY_PTHREAD_THREAD_NAME_MAX 16 - -////////////////////////////////////////////////////////////////////////// -// THREAD CREATION AND MANAGMENT -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - // Define type for platform specific thread handle - typedef pthread_t TThreadHandle; - - struct SThreadCreationDesc - { - // Define platform specific thread entry function functor type - typedef void* (* EntryFunc)(void*); - - const char* szThreadName; - EntryFunc fpEntryFunc; - void* pArgList; - uint32 nStackSizeInBytes; - }; - - ////////////////////////////////////////////////////////////////////////// - TThreadHandle CryGetCurrentThreadHandle() - { - return (TThreadHandle)pthread_self(); - } - - ////////////////////////////////////////////////////////////////////////// - // Note: Handle must be closed lated via CryCloseThreadHandle() - TThreadHandle CryDuplicateThreadHandle(const TThreadHandle& hThreadHandle) - { - // Do not do anything - // If you add a new platform which duplicates handles make sure to mirror the change in CryCloseThreadHandle(..) - return hThreadHandle; - } - - ////////////////////////////////////////////////////////////////////////// - void CryCloseThreadHandle(TThreadHandle& hThreadHandle) - { - pthread_detach(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetCurrentThreadId() - { - return threadID(pthread_self()); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetThreadId(TThreadHandle hThreadHandle) - { - return threadID(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - // Note: On OSX the thread name can only be set by the thread itself. - void CrySetThreadName(TThreadHandle pThreadHandle, const char* sThreadName) - { - char threadName[CRY_PTHREAD_THREAD_NAME_MAX]; - if (!cry_strcpy(threadName, sThreadName)) - { - CryLog(" CrySetThreadName: input thread name '%s' truncated to '%s'", sThreadName, threadName); - } -#if AZ_TRAIT_OS_PLATFORM_APPLE - // On OSX the thread name can only be set by the thread itself. - assert(pthread_equal(pthread_self(), (pthread_t )pThreadHandle)); - - if (pthread_setname_np(threadName) != 0) -#else - if (pthread_setname_np(pThreadHandle, threadName) != 0) -#endif - { - switch (errno) - { - case ERANGE: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadName: Unable to rename thread \"%s\". Error Msg: \"Name to long. Exceeds %d bytes.\"", sThreadName, CRY_PTHREAD_THREAD_NAME_MAX); - break; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadName: Unsupported error code: %i", errno); - break; - } - } - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadAffinityMask(TThreadHandle pThreadHandle, DWORD dwAffinityMask) - { -#if defined(AZ_PLATFORM_ANDROID) - // Not supported on ANDROID - // Alternative solution - // Watch out that android will clear the mask after a core has been switched off hence loosing the affinity mask setting! - // http://stackoverflow.com/questions/16319725/android-set-thread-affinity -#elif AZ_TRAIT_OS_PLATFORM_APPLE -# pragma message "Warning: CrySetThreadAffinityMask not implemented for platform" - // Implementation details can be found here - // https://developer.apple.com/library/mac/releasenotes/Performance/RN-AffinityAPI/ -#else - cpu_set_t cpu_mask; - CPU_ZERO(&cpu_mask); - for (int cpu = 0; cpu < sizeof(cpu_mask) * 8; ++cpu) - { - if (dwAffinityMask & (1 << cpu)) - { - CPU_SET(cpu, &cpu_mask); - } - } - - if (sched_setaffinity(0, sizeof(cpu_mask), &cpu_mask) != 0) - { - switch (errno) - { - case EFAULT: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: Supplied memory address was invalid."); - break; - case EINVAL: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The affinity bit mask [%u] contains no processors that are currently physically on the system and permitted to the process .", dwAffinityMask); - break; - case EPERM: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The calling process does not have appropriate privileges. Mask [%u].", dwAffinityMask); - break; - case ESRCH: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: The process whose ID is pid could not be found."); - break; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " CrySetThreadAffinityMask: Unsupported error code: %i", errno); - break; - } - } -#endif - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriority(TThreadHandle pThreadHandle, DWORD dwPriority) - { - int policy; - struct sched_param param; - - pthread_getschedparam(pThreadHandle, &policy, ¶m); - param.sched_priority = sched_get_priority_max(dwPriority); - pthread_setschedparam(pThreadHandle, policy, ¶m); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriorityBoost(TThreadHandle pThreadHandle, bool bEnabled) - { - // Not supported - } - - ////////////////////////////////////////////////////////////////////////// - bool CryCreateThread(TThreadHandle* pThreadHandle, const SThreadCreationDesc& threadDesc) - { - uint32 nStackSize = threadDesc.nStackSizeInBytes != 0 ? threadDesc.nStackSizeInBytes : DEFAULT_THREAD_STACK_SIZE_KB * 1024; - - assert(pThreadHandle != reinterpret_cast(THREADID_NULL)); - pthread_attr_t threadAttr; - sched_param schedParam; - pthread_attr_init(&threadAttr); - pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_JOINABLE); - pthread_attr_setstacksize(&threadAttr, nStackSize); - - const int err = pthread_create( - pThreadHandle, - &threadAttr, - threadDesc.fpEntryFunc, - threadDesc.pArgList); - - // Handle error on thread creation - switch (err) - { - case 0: - // No error - break; - case EAGAIN: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"Insufficient resources to create another thread, or a system-imposed limit on the number of threads was encountered.\"", threadDesc.szThreadName); - return false; - case EINVAL: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"Invalid attribute setting for thread creation.\"", threadDesc.szThreadName); - return false; - case EPERM: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Error Msg: \"No permission to set the scheduling policy and parameters specified in attribute setting\"", threadDesc.szThreadName); - return false; - default: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". Unknown error message. Error code %i", threadDesc.szThreadName, err); - break; - } - - // Print info to log - CryComment(": New thread \"%s\" | StackSize: %u(KB)", threadDesc.szThreadName, threadDesc.nStackSizeInBytes / 1024); - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void CryThreadExitCall() - { - // Notes on: pthread_exit - // A thread that was create with pthread_create implicitly calls pthread_exit when the thread returns from its start routine (the function that was first called after a thread was created). - // pthread_exit(NULL); - } -} - - -////////////////////////////////////////////////////////////////////////// -// FLOATING POINT EXCEPTIONS -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - /////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(EFPE_Severity eFPESeverity) - { - // TODO: - // Not implemented - // for potential implementation see http://linux.die.net/man/3/feenableexcept - } - - ////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(threadID nThreadId, EFPE_Severity eFPESeverity) - { - // TODO: - // Not implemented - // for potential implementation see http://linux.die.net/man/3/feenableexcept - } - - ////////////////////////////////////////////////////////////////////////// - uint GetFloatingPointExceptionMask() - { - // Not implemented - return ~0; - } - - ////////////////////////////////////////////////////////////////////////// - void SetFloatingPointExceptionMask(uint nMask) - { - // Not implemented - } -} diff --git a/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h b/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h deleted file mode 100644 index e5c7510feb..0000000000 --- a/Code/CryEngine/CrySystem/CryThreadUtil_win32_thread.h +++ /dev/null @@ -1,432 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -////////////////////////////////////////////////////////////////////////// -// NOTE: INTERNAL HEADER NOT FOR PUBLIC USE -// This header should only be include by SystemThreading.cpp only -// It provides an interface for WinApi intrinsics -// It's only client should be CThreadManager which should manage all thread interaction - -#pragma once - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define CRYTHREADUTIL_WIN32_THREAD_H_SECTION_1 1 -#define CRYTHREADUTIL_WIN32_THREAD_H_SECTION_2 2 -#endif - -#if !defined(INCLUDED_FROM_SYSTEM_THREADING_CPP) -# error "CRYTEK INTERNAL HEADER. ONLY INCLUDE FROM SYSTEMTHRADING.CPP." -#endif -////////////////////////////////////////////////////////////////////////// - -#define DEFAULT_THREAD_STACK_SIZE_KB 0 - -// Returns the last Win32 error, in string format. Returns an empty string if there is no error. -static string GetLastErrorAsString() -{ - // Get the error message, if any. - DWORD errorMessageID = GetLastError(); - if (errorMessageID == 0) - { - return ""; - } - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CRYTHREADUTIL_WIN32_THREAD_H_SECTION_1 -#include AZ_RESTRICTED_FILE(CryThreadUtil_win32_thread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - LPSTR messageBuffer = nullptr; - size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), messageBuffer, 0, NULL); - - string message(messageBuffer, size); - - // Free the buffer. - LocalFree(messageBuffer); - - return message; -#endif -} - -////////////////////////////////////////////////////////////////////////// -// THREAD CREATION AND MANAGMENT -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - // Define type for platform specific thread handle - typedef THREAD_HANDLE TThreadHandle; - - struct SThreadCreationDesc - { - // Define platform specific thread entry function functor type - typedef unsigned int(_stdcall * EntryFunc)(void*); - - const char* szThreadName; - EntryFunc fpEntryFunc; - void* pArgList; - uint32 nStackSizeInBytes; - }; - - ////////////////////////////////////////////////////////////////////////// - TThreadHandle CryGetCurrentThreadHandle() - { - return GetCurrentThread(); // most likely returns pseudo handle (0xfffffffe) - } - - ////////////////////////////////////////////////////////////////////////// - // Note: Handle must be closed lated via CryCloseThreadHandle() - TThreadHandle CryDuplicateThreadHandle(const TThreadHandle& hThreadHandle) - { - // NOTES: - // GetCurrentThread() may return a psydo handle to the current thread - // to avoid going into the slower kernel mode. - // Hence the handle is useless when being used from an other thread. - // - GetCurrentThread() -> 0xfffffffe - // - GetCurrentProcess() -> 0xffffffff - - HANDLE hRealHandle = 0; - DuplicateHandle(GetCurrentProcess(), // Source Process Handle. - hThreadHandle, // Source Handle to dup. - GetCurrentProcess(), // Target Process Handle. - &hRealHandle, // Target Handle pointer. - 0, // Options flag. - TRUE, // Inheritable flag - DUPLICATE_SAME_ACCESS); // Options - - return (TThreadHandle)hRealHandle; - } - - ////////////////////////////////////////////////////////////////////////// - void CryCloseThreadHandle(TThreadHandle& hThreadHandle) - { - if (hThreadHandle) - { - CloseHandle(hThreadHandle); - } - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetCurrentThreadId() - { - return GetCurrentThreadId(); - } - - ////////////////////////////////////////////////////////////////////////// - threadID CryGetThreadId(TThreadHandle hThreadHandle) - { - return GetThreadId(hThreadHandle); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadName(TThreadHandle pThreadHandle, const char* sThreadName) - { - const DWORD MS_VC_EXCEPTION = 0x406D1388; - - struct SThreadNameDesc - { - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). - DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. - }; - - SThreadNameDesc info; - info.dwType = 0x1000; - info.szName = sThreadName; - info.dwThreadID = GetThreadId(pThreadHandle); - info.dwFlags = 0; -AZ_PUSH_DISABLE_WARNING(6312 6322, "-Wunknown-warning-option") - // warning C6312: Possible infinite loop: use of the constant EXCEPTION_CONTINUE_EXECUTION in the exception-filter expression of a try-except - // warning C6322: empty _except block - __try - { - // Raise exception to set thread name for attached debugger - RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR*)&info); - } - __except (GetExceptionCode() == MS_VC_EXCEPTION ? EXCEPTION_CONTINUE_EXECUTION : EXCEPTION_EXECUTE_HANDLER) - { - } -AZ_POP_DISABLE_WARNING - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadAffinityMask(TThreadHandle pThreadHandle, DWORD dwAffinityMask) - { - SetThreadAffinityMask(pThreadHandle, dwAffinityMask); - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriority(TThreadHandle pThreadHandle, DWORD dwPriority) - { - if (!SetThreadPriority(pThreadHandle, dwPriority)) - { - string errMsg = GetLastErrorAsString(); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to set thread priority. System Error Msg: \"%s\"", errMsg.c_str()); - return; - } - } - - ////////////////////////////////////////////////////////////////////////// - void CrySetThreadPriorityBoost(TThreadHandle pThreadHandle, bool bEnabled) - { - SetThreadPriorityBoost(pThreadHandle, !bEnabled); - } - - ////////////////////////////////////////////////////////////////////////// - bool CryCreateThread(TThreadHandle* pThreadHandle, const SThreadCreationDesc& threadDesc) - { - const uint32 nStackSize = threadDesc.nStackSizeInBytes != 0 ? threadDesc.nStackSizeInBytes : DEFAULT_THREAD_STACK_SIZE_KB * 1024; - - // Create thread - unsigned int threadId = 0; -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION CRYTHREADUTIL_WIN32_THREAD_H_SECTION_2 -#include AZ_RESTRICTED_FILE(CryThreadUtil_win32_thread_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - *pThreadHandle = (void*)_beginthreadex(NULL, nStackSize, threadDesc.fpEntryFunc, threadDesc.pArgList, CREATE_SUSPENDED, &threadId); -#endif - - if (!(*pThreadHandle)) - { - string errMsg = GetLastErrorAsString(); - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Unable to create thread \"%s\". System Error Msg: \"%s\"", threadDesc.szThreadName, errMsg.c_str()); - return false; - } - - // Start thread - ResumeThread(*pThreadHandle); - - // Print info to log - CryComment(": New thread \"%s\" | StackSize: %u(KB)", threadDesc.szThreadName, threadDesc.nStackSizeInBytes / 1024); - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void CryThreadExitCall() - { - // Note on: ExitThread() (from MSDN) - // ExitThread is the preferred method of exiting a thread in C code. - // However, in C++ code, the thread is exited before any destructor can be called or any other automatic cleanup can be performed. - // Therefore, in C++ code, you should return from your thread function. - } -} - -////////////////////////////////////////////////////////////////////////// -// FLOATING POINT EXCEPTIONS -////////////////////////////////////////////////////////////////////////// -namespace CryThreadUtil -{ - /////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions([[maybe_unused]] EFPE_Severity eFPESeverity) - { -AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option") - - // Optimization - // Enable DAZ/FZ - // Denormals Are Zeros - // Flush-to-Zero - _controlfp(_DN_FLUSH, _MCW_DN); - _mm_setcsr(_mm_getcsr() | _MM_FLUSH_ZERO_ON); - -#ifndef _RELEASE - if (eFPESeverity == eFPE_None) - { - // mask all floating exceptions off. - _controlfp(_MCW_EM, _MCW_EM); - _mm_setcsr(_mm_getcsr() | _MM_MASK_MASK); - } - else - { - // Clear pending exceptions - _fpreset(); - - if (eFPESeverity == eFPE_Basic) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - // Disable: - // - _EM_DENORMAL - // - _EM_OVERFLOW - // - _EM_UNDERFLOW - // - _EM_INEXACT - - _controlfp(_EM_INEXACT | _EM_DENORMAL | _EM_UNDERFLOW | _EM_OVERFLOW, _MCW_EM); - _mm_setcsr((_mm_getcsr() & ~_MM_MASK_MASK) | (_MM_MASK_DENORM | _MM_MASK_INEXACT | _MM_MASK_UNDERFLOW | _MM_MASK_OVERFLOW)); - - //_mm_setcsr(_mm_getcsr() & ~0x280); - } - - if (eFPESeverity == eFPE_All) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - _EM_UNDERFLOW - // - _EM_OVERFLOW - // - // Disable: - // - _EM_INEXACT - // - _EM_DENORMAL - - _controlfp(_EM_INEXACT | _EM_DENORMAL, _MCW_EM); - _mm_setcsr((_mm_getcsr() & ~_MM_MASK_MASK) | (_MM_MASK_INEXACT | _MM_MASK_DENORM)); - } - } -#endif // _RELEASE - -AZ_POP_DISABLE_WARNING -} - - ////////////////////////////////////////////////////////////////////////// - void EnableFloatExceptions(threadID nThreadId, EFPE_Severity eFPESeverity) - { - if (eFPESeverity >= eFPE_LastEntry) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Floating Point Exception (FPE) severity is out of range. (%i)", eFPESeverity); - } - - // Check if the thread ID matches the current thread - if (nThreadId == 0 || nThreadId == CryGetCurrentThreadId()) - { - EnableFloatExceptions(eFPESeverity); - return; - } - - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, true, nThreadId); - - if (hThread == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Unable to open thread. %p", hThread); - return; - } - - SuspendThread(hThread); - - CONTEXT ctx; - memset(&ctx, 0, sizeof(ctx)); - ctx.ContextFlags = CONTEXT_ALL; - if (GetThreadContext(hThread, &ctx) == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Unable to get thread context"); - ResumeThread(hThread); - CloseHandle(hThread); - return; - } - -#ifdef PLATFORM_64BIT - ////////////////////////////////////////////////////////////////////////// - // Note: - // DO NOT USE ctx.FltSave.MxCsr ... SetThreadContext() will copy the value of ctx.MxCsr into it - ////////////////////////////////////////////////////////////////////////// - DWORD& floatMxCsr = ctx.MxCsr; // Hold FPE Mask and Status for MMX (SSE) floating point registers - WORD& floatControlWord = ctx.FltSave.ControlWord; // Hold FPE Mask for floating point registers - #ifndef _RELEASE - WORD& floatStatuslWord = ctx.FltSave.StatusWord; // Holds FPE Status for floating point registers - #endif -#else - DWORD& floatMxCsr = *(DWORD*)(&ctx.ExtendedRegisters[24]); // Hold FPE Mask and Status for MMX (SSE) floating point registers - DWORD& floatControlWord = ctx.FloatSave.ControlWord; // Hold FPE Mask for floating point registers - DWORD& floatStatuslWord = ctx.FloatSave.StatusWord; // Holds FPE Status for floating point registers -#endif - - // Flush-To-Zero Mode - // Two conditions must be met for FTZ processing to occur: - // - The FTZ bit (bit 15) in the MXCSR register must be masked (value = 1). - // - The underflow exception (bit 11) needs to be masked (value = 1). - - // Set flush mode to zero mode - floatControlWord = (floatControlWord & ~_MCW_DN) | _DN_FLUSH; - floatMxCsr = (floatMxCsr & ~_MM_FLUSH_ZERO_MASK) | (_MM_FLUSH_ZERO_ON); - -#ifndef _RELEASE - - // Reset FPE bits - floatControlWord = floatControlWord | _MCW_EM; - floatMxCsr = floatMxCsr | _MM_MASK_MASK; - - // Clear pending exceptions - floatStatuslWord = floatStatuslWord & ~(_SW_INEXACT | _SW_UNDERFLOW | _SW_OVERFLOW | _SW_ZERODIVIDE | _SW_INVALID | _SW_DENORMAL); - floatMxCsr = floatMxCsr & ~(_MM_EXCEPT_INEXACT | _MM_EXCEPT_UNDERFLOW | _MM_EXCEPT_OVERFLOW | _MM_EXCEPT_DIV_ZERO | _MM_EXCEPT_INVALID | _MM_EXCEPT_DENORM); - - if (eFPESeverity == eFPE_Basic) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - // Disable: - // - _EM_DENORMAL - // - _EM_OVERFLOW - // - _EM_UNDERFLOW - // - _EM_INEXACT - - floatControlWord = (floatControlWord & ~_MCW_EM) | (_EM_DENORMAL | _EM_INEXACT | EM_UNDERFLOW | _EM_OVERFLOW); - floatMxCsr = (floatMxCsr & ~_MM_MASK_MASK) | (_MM_MASK_DENORM | _MM_MASK_INEXACT | _MM_MASK_UNDERFLOW | _MM_MASK_OVERFLOW); - } - - if (eFPESeverity == eFPE_All) - { - // Enable: - // - _EM_ZERODIVIDE - // - _EM_INVALID - // - _EM_UNDERFLOW - // - _EM_OVERFLOW - // - // Disable: - // - _EM_INEXACT - // - _EM_DENORMAL - - floatControlWord = (floatControlWord & ~_MCW_EM) | (_EM_INEXACT | _EM_DENORMAL); - floatMxCsr = (floatMxCsr & ~_MM_MASK_MASK) | (_MM_MASK_INEXACT | _MM_MASK_DENORM); - } -#endif - - ctx.ContextFlags = CONTEXT_ALL; - if (SetThreadContext(hThread, &ctx) == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Error setting ThreadContext for ThreadID: %u", nThreadId); - ResumeThread(hThread); - CloseHandle(hThread); - return; - } - - ResumeThread(hThread); - CloseHandle(hThread); - } - - ////////////////////////////////////////////////////////////////////////// - uint GetFloatingPointExceptionMask() - { - uint nMask = 0; - _clearfp(); - _controlfp_s(&nMask, 0, 0); - return nMask; - } - - ////////////////////////////////////////////////////////////////////////// - void SetFloatingPointExceptionMask(uint nMask) - { - uint temp = 0; - _clearfp(); - const unsigned int kAllowedBits = _MCW_DN | _MCW_EM | _MCW_RC; - _controlfp_s(&temp, nMask, kAllowedBits); - } -} diff --git a/Code/CryEngine/CrySystem/DebugCallStack.cpp b/Code/CryEngine/CrySystem/DebugCallStack.cpp deleted file mode 100644 index f33e793db6..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.cpp +++ /dev/null @@ -1,926 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "DebugCallStack.h" - -#if defined(WIN32) || defined(WIN64) - -#include -#include -#include -#include "System.h" - -#include -#include - -#include "resource.h" -__pragma(comment(lib, "version.lib")) - -//! Needs one external of DLL handle. -extern HMODULE gDLLHandle; - -#include - -#define MAX_PATH_LENGTH 1024 -#define MAX_SYMBOL_LENGTH 512 - -static HWND hwndException = 0; -static bool g_bUserDialog = true; // true=on crash show dialog box, false=supress user interaction - -static int PrintException(EXCEPTION_POINTERS* pex); - -static bool IsFloatingPointException(EXCEPTION_POINTERS* pex); - -extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); -extern LONG WINAPI CryEngineExceptionFilterMiniDump(struct _EXCEPTION_POINTERS* pExceptionPointers, const char* szDumpPath, MINIDUMP_TYPE mdumpValue); - -//============================================================================= -CONTEXT CaptureCurrentContext() -{ - CONTEXT context; - memset(&context, 0, sizeof(context)); - context.ContextFlags = CONTEXT_FULL; - RtlCaptureContext(&context); - - return context; -} - -LONG __stdcall CryUnhandledExceptionHandler(EXCEPTION_POINTERS* pex) -{ - return DebugCallStack::instance()->handleException(pex); -} - - -BOOL CALLBACK EnumModules( - PCSTR ModuleName, - DWORD64 BaseOfDll, - PVOID UserContext) -{ - DebugCallStack::TModules& modules = *static_cast(UserContext); - modules[(void*)BaseOfDll] = ModuleName; - - return TRUE; -} -//============================================================================= -// Class Statics -//============================================================================= - -// Return single instance of class. -IDebugCallStack* IDebugCallStack::instance() -{ - static DebugCallStack sInstance; - return &sInstance; -} - -//------------------------------------------------------------------------------------------------------------------------ -// Sets up the symbols for functions in the debug file. -//------------------------------------------------------------------------------------------------------------------------ -DebugCallStack::DebugCallStack() - : prevExceptionHandler(0) - , m_pSystem(0) - , m_nSkipNumFunctions(0) - , m_bCrash(false) - , m_szBugMessage(NULL) -{ -} - -DebugCallStack::~DebugCallStack() -{ -} - -void DebugCallStack::RemoveOldFiles() -{ - RemoveFile("error.log"); - RemoveFile("error.bmp"); - RemoveFile("error.dmp"); -} - -void DebugCallStack::RemoveFile(const char* szFileName) -{ - FILE* pFile = nullptr; - azfopen(&pFile, szFileName, "r"); - const bool bFileExists = (pFile != NULL); - - if (bFileExists) - { - fclose(pFile); - - WriteLineToLog("Removing file \"%s\"...", szFileName); - if (remove(szFileName) == 0) - { - WriteLineToLog("File successfully removed."); - } - else - { - WriteLineToLog("Couldn't remove file!"); - } - } -} - -void DebugCallStack::installErrorHandler(ISystem* pSystem) -{ - m_pSystem = pSystem; - prevExceptionHandler = (void*)SetUnhandledExceptionFilter(CryUnhandledExceptionHandler); -} - -////////////////////////////////////////////////////////////////////////// -void DebugCallStack::SetUserDialogEnable(const bool bUserDialogEnable) -{ - g_bUserDialog = bUserDialogEnable; -} - - -DWORD g_idDebugThreads[10]; -const char* g_nameDebugThreads[10]; -int g_nDebugThreads = 0; -volatile int g_lockThreadDumpList = 0; - -void MarkThisThreadForDebugging(const char* name) -{ - EBUS_EVENT(AZ::Debug::EventTraceDrillerSetupBus, SetThreadName, AZStd::this_thread::get_id(), name); - - WriteLock lock(g_lockThreadDumpList); - DWORD id = GetCurrentThreadId(); - if (g_nDebugThreads == sizeof(g_idDebugThreads) / sizeof(g_idDebugThreads[0])) - { - return; - } - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] == id) - { - return; - } - } - g_nameDebugThreads[g_nDebugThreads] = name; - g_idDebugThreads[g_nDebugThreads++] = id; - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); -} - -void UnmarkThisThreadFromDebugging() -{ - WriteLock lock(g_lockThreadDumpList); - DWORD id = GetCurrentThreadId(); - for (int i = g_nDebugThreads - 1; i >= 0; i--) - { - if (g_idDebugThreads[i] == id) - { - memmove(g_idDebugThreads + i, g_idDebugThreads + i + 1, (g_nDebugThreads - 1 - i) * sizeof(g_idDebugThreads[0])); - memmove(g_nameDebugThreads + i, g_nameDebugThreads + i + 1, (g_nDebugThreads - 1 - i) * sizeof(g_nameDebugThreads[0])); - --g_nDebugThreads; - } - } -} - -extern int prev_sys_float_exceptions; -void UpdateFPExceptionsMaskForThreads() -{ - int mask = -iszero(g_cvars.sys_float_exceptions); - CONTEXT ctx; - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i]); - ctx.ContextFlags = CONTEXT_ALL; - SuspendThread(hThread); - GetThreadContext(hThread, &ctx); -#ifndef WIN64 - (ctx.FloatSave.ControlWord |= 7) &= ~5 | mask; - (*(WORD*)(ctx.ExtendedRegisters + 24) |= 0x280) &= ~0x280 | mask; -#else - (ctx.FltSave.ControlWord |= 7) &= ~5 | mask; - (ctx.FltSave.MxCsr |= 0x280) &= ~0x280 | mask; -#endif - SetThreadContext(hThread, &ctx); - ResumeThread(hThread); - } - } -} - -////////////////////////////////////////////////////////////////////////// -int DebugCallStack::handleException(EXCEPTION_POINTERS* exception_pointer) -{ - if (gEnv == NULL) - { - return EXCEPTION_EXECUTE_HANDLER; - } - - ResetFPU(exception_pointer); - - prev_sys_float_exceptions = 0; - const int cached_sys_float_exceptions = g_cvars.sys_float_exceptions; - - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(0); - - if (g_cvars.sys_WER) - { - gEnv->pLog->FlushAndClose(); - return CryEngineExceptionFilterWER(exception_pointer); - } - - if (g_cvars.sys_no_crash_dialog) - { - DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); - SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX); - } - - m_bCrash = true; - - if (g_cvars.sys_no_crash_dialog) - { - DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); - SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX); - } - - static bool firstTime = true; - - if (g_cvars.sys_dump_aux_threads) - { - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - SuspendThread(OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i])); - } - } - } - - // uninstall our exception handler. - SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)prevExceptionHandler); - - if (!firstTime) - { - WriteLineToLog("Critical Exception! Called Multiple Times!"); - gEnv->pLog->FlushAndClose(); - // Exception called more then once. - return EXCEPTION_EXECUTE_HANDLER; - } - - // Print exception info: - { - char excCode[80]; - char excAddr[80]; - WriteLineToLog(""); - sprintf_s(excAddr, "0x%04X:0x%p", exception_pointer->ContextRecord->SegCs, exception_pointer->ExceptionRecord->ExceptionAddress); - sprintf_s(excCode, "0x%08X", exception_pointer->ExceptionRecord->ExceptionCode); - WriteLineToLog("Exception: %s, at Address: %s", excCode, excAddr); - - { - IMemoryManager::SProcessMemInfo memInfo; - if (gEnv->pSystem->GetIMemoryManager()->GetProcessMemInfo(memInfo)) - { - uint32 nMemUsage = (uint32)(memInfo.PagefileUsage / (1024 * 1024)); - WriteLineToLog("Virtual memory usage: %dMb", nMemUsage); - } - gEnv->szDebugStatus[SSystemGlobalEnvironment::MAX_DEBUG_STRING_LENGTH - 1] = '\0'; - WriteLineToLog("Debug Status: %s", gEnv->szDebugStatus); - } - } - - firstTime = false; - - const int ret = SubmitBug(exception_pointer); - - if (ret != IDB_IGNORE) - { - CryEngineExceptionFilterWER(exception_pointer); - } - - gEnv->pLog->FlushAndClose(); - - if (exception_pointer->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) - { - // This is non continuable exception. abort application now. - exit(exception_pointer->ExceptionRecord->ExceptionCode); - } - - //typedef long (__stdcall *ExceptionFunc)(EXCEPTION_POINTERS*); - //ExceptionFunc prevFunc = (ExceptionFunc)prevExceptionHandler; - //return prevFunc( (EXCEPTION_POINTERS*)exception_pointer ); - if (ret == IDB_EXIT) - { - // Immediate exit. - // on windows, exit() and _exit() do all sorts of things, unfortuantely - // TerminateProcess is the only way to die. - TerminateProcess(GetCurrentProcess(), exception_pointer->ExceptionRecord->ExceptionCode); // we crashed, so don't return a zero exit code! - // on linux based systems, _exit will not call ATEXIT and other things, which makes it more suitable for termination in an emergency such - // as an unhandled exception. - // however, this function is a windows exception handler. - } - else if (ret == IDB_IGNORE) - { -#ifndef WIN64 - exception_pointer->ContextRecord->FloatSave.StatusWord &= ~31; - exception_pointer->ContextRecord->FloatSave.ControlWord |= 7; - (*(WORD*)(exception_pointer->ContextRecord->ExtendedRegisters + 24) &= 31) |= 0x1F80; -#else - exception_pointer->ContextRecord->FltSave.StatusWord &= ~31; - exception_pointer->ContextRecord->FltSave.ControlWord |= 7; - (exception_pointer->ContextRecord->FltSave.MxCsr &= 31) |= 0x1F80; -#endif - firstTime = true; - prevExceptionHandler = (void*)SetUnhandledExceptionFilter(CryUnhandledExceptionHandler); - g_cvars.sys_float_exceptions = cached_sys_float_exceptions; - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); - return EXCEPTION_CONTINUE_EXECUTION; - } - - // Continue; - return EXCEPTION_EXECUTE_HANDLER; -} - -void DebugCallStack::ReportBug(const char* szErrorMessage) -{ - WriteLineToLog("Reporting bug: %s", szErrorMessage); - - m_szBugMessage = szErrorMessage; - m_context = CaptureCurrentContext(); - SubmitBug(NULL); - m_szBugMessage = NULL; -} - -void DebugCallStack::dumpCallStack(std::vector& funcs) -{ - WriteLineToLog("============================================================================="); - int len = (int)funcs.size(); - for (int i = 0; i < len; i++) - { - const char* str = funcs[i].c_str(); - WriteLineToLog("%2d) %s", len - i, str); - } - WriteLineToLog("============================================================================="); -} - - -////////////////////////////////////////////////////////////////////////// -void DebugCallStack::LogExceptionInfo(EXCEPTION_POINTERS* pex) -{ - string path(""); - if ((gEnv) && (gEnv->pFileIO)) - { - const char* logAlias = gEnv->pFileIO->GetAlias("@log@"); - if (!logAlias) - { - logAlias = gEnv->pFileIO->GetAlias("@root@"); - } - if (logAlias) - { - path = logAlias; - path += "/"; - } - } - - string fileName = path; - fileName += "error.log"; - - struct stat fileInfo; - string timeStamp; - string backupPath; - if (gEnv->IsDedicated()) - { - backupPath = PathUtil::ToUnixPath(PathUtil::AddSlash(path + "DumpBackups")); - gEnv->pFileIO->CreatePath(backupPath.c_str()); - - if (stat(fileName.c_str(), &fileInfo) == 0) - { - // Backup log - tm creationTime; - localtime_s(&creationTime, &fileInfo.st_mtime); - char tempBuffer[32]; - strftime(tempBuffer, sizeof(tempBuffer), "%d %b %Y (%H %M %S)", &creationTime); - timeStamp = tempBuffer; - - string backupFileName = backupPath + timeStamp + " error.log"; - CopyFile(fileName.c_str(), backupFileName.c_str(), true); - } - } - - FILE* f = nullptr; - azfopen(&f, fileName.c_str(), "wt"); - - CDebugAllowFileAccess ignoreInvalidFileAccess; - - static char errorString[s_iCallStackSize]; - errorString[0] = 0; - - // Time and Version. - char versionbuf[1024]; - azstrcpy(versionbuf, AZ_ARRAY_SIZE(versionbuf), ""); - PutVersion(versionbuf, AZ_ARRAY_SIZE(versionbuf)); - cry_strcat(errorString, versionbuf); - cry_strcat(errorString, "\n"); - - char excCode[MAX_WARNING_LENGTH]; - char excAddr[80]; - char desc[1024]; - char excDesc[MAX_WARNING_LENGTH]; - - // make sure the mouse cursor is visible - ShowCursor(TRUE); - - const char* excName; - if (m_bIsFatalError || !pex) - { - const char* const szMessage = m_bIsFatalError ? s_szFatalErrorCode : m_szBugMessage; - excName = szMessage; - cry_strcpy(excCode, szMessage); - cry_strcpy(excAddr, ""); - cry_strcpy(desc, ""); - cry_strcpy(m_excModule, ""); - cry_strcpy(excDesc, szMessage); - } - else - { - sprintf_s(excAddr, "0x%04X:0x%p", pex->ContextRecord->SegCs, pex->ExceptionRecord->ExceptionAddress); - sprintf_s(excCode, "0x%08X", pex->ExceptionRecord->ExceptionCode); - excName = TranslateExceptionCode(pex->ExceptionRecord->ExceptionCode); - cry_strcpy(desc, ""); - sprintf_s(excDesc, "%s\r\n%s", excName, desc); - - - if (pex->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION) - { - if (pex->ExceptionRecord->NumberParameters > 1) - { - ULONG_PTR iswrite = pex->ExceptionRecord->ExceptionInformation[0]; - DWORD64 accessAddr = pex->ExceptionRecord->ExceptionInformation[1]; - if (iswrite) - { - sprintf_s(desc, "Attempt to write data to address 0x%08llu\r\nThe memory could not be \"written\"", accessAddr); - } - else - { - sprintf_s(desc, "Attempt to read from address 0x%08llu\r\nThe memory could not be \"read\"", accessAddr); - } - } - } - } - - - WriteLineToLog("Exception Code: %s", excCode); - WriteLineToLog("Exception Addr: %s", excAddr); - WriteLineToLog("Exception Module: %s", m_excModule); - WriteLineToLog("Exception Name : %s", excName); - WriteLineToLog("Exception Description: %s", desc); - - - cry_strcpy(m_excDesc, excDesc); - cry_strcpy(m_excAddr, excAddr); - cry_strcpy(m_excCode, excCode); - - - char errs[32768]; - sprintf_s(errs, "Exception Code: %s\nException Addr: %s\nException Module: %s\nException Description: %s, %s\n", - excCode, excAddr, m_excModule, excName, desc); - - - IMemoryManager::SProcessMemInfo memInfo; - if (gEnv->pSystem->GetIMemoryManager()->GetProcessMemInfo(memInfo)) - { - char memoryString[256]; - double MB = 1024 * 1024; - sprintf_s(memoryString, "Memory in use: %3.1fMB\n", (double)(memInfo.PagefileUsage) / MB); - cry_strcat(errs, memoryString); - } - { - const int tempStringSize = 256; - char tempString[tempStringSize]; - - gEnv->szDebugStatus[SSystemGlobalEnvironment::MAX_DEBUG_STRING_LENGTH - 1] = '\0'; - sprintf_s(tempString, tempStringSize, "Debug Status: %s\n", gEnv->szDebugStatus); - cry_strcat(errs, tempString); - - sprintf_s(tempString, tempStringSize, "Out of Memory: %d\n", gEnv->bIsOutOfMemory); - cry_strcat(errs, tempString); - } - cry_strcat(errs, "\nCall Stack Trace:\n"); - - std::vector funcs; - if (gEnv->bIsOutOfMemory) - { - cry_strcat(errs, "1) OUT_OF_MEMORY()\n"); - } - else - { - AZ::Debug::StackFrame frames[25]; - AZ::Debug::SymbolStorage::StackLine lines[AZ_ARRAY_SIZE(frames)]; - unsigned int numFrames = AZ::Debug::StackRecorder::Record(frames, AZ_ARRAY_SIZE(frames), 3); - if (numFrames) - { - AZ::Debug::SymbolStorage::DecodeFrames(frames, numFrames, lines); - for (unsigned int i = 0; i < numFrames; i++) - { - funcs.push_back(lines[i]); - } - } - dumpCallStack(funcs); - // Fill call stack. - char str[s_iCallStackSize]; - cry_strcpy(str, ""); - for (unsigned int i = 0; i < funcs.size(); i++) - { - char temp[s_iCallStackSize]; - sprintf_s(temp, "%2zd) %s", funcs.size() - i, (const char*)funcs[i].c_str()); - cry_strcat(str, temp); - cry_strcat(str, "\r\n"); - cry_strcat(errs, temp); - cry_strcat(errs, "\n"); - } - cry_strcpy(m_excCallstack, str); - } - - cry_strcat(errorString, errs); - - if (f) - { - fwrite(errorString, strlen(errorString), 1, f); - if (!gEnv->bIsOutOfMemory) - { - if (g_cvars.sys_dump_aux_threads) - { - for (int i = 0; i < g_nDebugThreads; i++) - { - if (g_idDebugThreads[i] != GetCurrentThreadId()) - { - fprintf(f, "\n\nSuspended thread (%s):\n", g_nameDebugThreads[i]); - HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, TRUE, g_idDebugThreads[i]); - - // mirrors the AZ::Debug::Trace::PrintCallstack() functionality, but prints to a file - { - AZ::Debug::StackFrame frames[10]; - - // Without StackFrame explicit alignment frames array is aligned to 4 bytes - // which causes the stack tracing to fail. - AZ::Debug::SymbolStorage::StackLine lines[AZ_ARRAY_SIZE(frames)]; - - unsigned int numFrames = AZ::Debug::StackRecorder::Record(frames, AZ_ARRAY_SIZE(frames), 0, hThread); - if (numFrames) - { - AZ::Debug::SymbolStorage::DecodeFrames(frames, numFrames, lines); - for (unsigned int i2 = 0; i2 < numFrames; ++i2) - { - fprintf(f, "%2d) %s\n", numFrames - i2, lines[i2]); - } - } - } - - ResumeThread(hThread); - } - } - } - } - fflush(f); - fclose(f); - } - - if (pex) - { - MINIDUMP_TYPE mdumpValue; - bool bDump = true; - switch (g_cvars.sys_dump_type) - { - case 0: - bDump = false; - break; - case 1: - mdumpValue = MiniDumpNormal; - break; - case 2: - mdumpValue = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithDataSegs); - break; - case 3: - mdumpValue = MiniDumpWithFullMemory; - break; - default: - mdumpValue = (MINIDUMP_TYPE)g_cvars.sys_dump_type; - break; - } - if (bDump) - { - fileName = path + "error.dmp"; - - if (gEnv->IsDedicated() && stat(fileName.c_str(), &fileInfo) == 0) - { - // Backup dump (use timestamp from error.log if available) - if (timeStamp.empty()) - { - tm creationTime; - localtime_s(&creationTime, &fileInfo.st_mtime); - char tempBuffer[32]; - strftime(tempBuffer, sizeof(tempBuffer), "%d %b %Y (%H %M %S)", &creationTime); - timeStamp = tempBuffer; - } - - string backupFileName = backupPath + timeStamp + " error.dmp"; - CopyFile(fileName.c_str(), backupFileName.c_str(), true); - } - - CryEngineExceptionFilterMiniDump(pex, fileName.c_str(), mdumpValue); - } - } - - //if no crash dialog don't even submit the bug - if (m_postBackupProcess && g_cvars.sys_no_crash_dialog == 0 && g_bUserDialog) - { - m_postBackupProcess(); - } - else - { - // lawsonn: Disabling the JIRA-based crash reporter for now - // we'll need to deal with it our own way, pending QA. - // if you're customizing the engine this is also your opportunity to deal with it. - if (g_cvars.sys_no_crash_dialog != 0 || !g_bUserDialog) - { - // ------------ place custom crash handler here --------------------- - // it should launch an executable! - /// by this time, error.bmp will be in the engine root folder - // error.log and error.dmp will also be present in the engine root folder - // if your error dumper wants those, it should zip them up and send them or offer to do so. - // ------------------------------------------------------------------ - } - } - const bool bQuitting = !gEnv || !gEnv->pSystem || gEnv->pSystem->IsQuitting(); - - //[AlexMcC|16.04.10] When the engine is shutting down, MessageBox doesn't display a box - // and immediately returns IDYES. Avoid this by just not trying to save if we're quitting. - // Don't ask to save if this isn't a real crash (a real crash has exception pointers) - if (g_cvars.sys_no_crash_dialog == 0 && g_bUserDialog && gEnv->IsEditor() && !bQuitting && pex) - { - BackupCurrentLevel(); - - const INT_PTR res = DialogBoxParam(gDLLHandle, MAKEINTRESOURCE(IDD_CONFIRM_SAVE_LEVEL), NULL, DebugCallStack::ConfirmSaveDialogProc, NULL); - if (res == IDB_CONFIRM_SAVE) - { - if (SaveCurrentLevel()) - { - MessageBox(NULL, "Level has been successfully saved!\r\nPress Ok to terminate Editor.", "Save", MB_OK); - } - else - { - MessageBox(NULL, "Error saving level.\r\nPress Ok to terminate Editor.", "Save", MB_OK | MB_ICONWARNING); - } - } - } - - if (g_cvars.sys_no_crash_dialog != 0 || !g_bUserDialog) - { - // terminate immediately - since we're in a crash, there is no point unwinding stack, we've already done access violation or worse. - // calling exit will only cause further death down the line... - TerminateProcess(GetCurrentProcess(), pex->ExceptionRecord->ExceptionCode); - } -} - - -INT_PTR CALLBACK DebugCallStack::ExceptionDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) -{ - static EXCEPTION_POINTERS* pex; - - static char errorString[32768] = ""; - - switch (message) - { - case WM_INITDIALOG: - { - pex = (EXCEPTION_POINTERS*)lParam; - HWND h; - - if (pex->ExceptionRecord->ExceptionFlags & EXCEPTION_NONCONTINUABLE) - { - // Disable continue button for non continuable exceptions. - //h = GetDlgItem( hwndDlg,IDB_CONTINUE ); - //if (h) EnableWindow( h,FALSE ); - } - - DebugCallStack* pDCS = static_cast(DebugCallStack::instance()); - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_DESC); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excDesc); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_CODE); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excCode); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_MODULE); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excModule); - } - - h = GetDlgItem(hwndDlg, IDC_EXCEPTION_ADDRESS); - if (h) - { - SendMessage(h, EM_REPLACESEL, FALSE, (LONG_PTR)pDCS->m_excAddr); - } - - // Fill call stack. - HWND callStack = GetDlgItem(hwndDlg, IDC_CALLSTACK); - if (callStack) - { - SendMessage(callStack, WM_SETTEXT, FALSE, (LPARAM)pDCS->m_excCallstack); - } - - if (hwndException) - { - DestroyWindow(hwndException); - hwndException = 0; - } - - if (IsFloatingPointException(pex)) - { - EnableWindow(GetDlgItem(hwndDlg, IDB_IGNORE), TRUE); - } - } - break; - - case WM_COMMAND: - switch (LOWORD(wParam)) - { - case IDB_EXIT: - case IDB_IGNORE: - // Fall through. - - EndDialog(hwndDlg, wParam); - return TRUE; - } - } - return FALSE; -} - -INT_PTR CALLBACK DebugCallStack::ConfirmSaveDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, [[maybe_unused]] LPARAM lParam) -{ - switch (message) - { - case WM_INITDIALOG: - { - // The user might be holding down the spacebar while the engine crashes. - // If we don't remove keyboard focus from this dialog, the keypress will - // press the default button before the dialog actually appears, even if - // the user has already released the key, which is bad. - SetFocus(NULL); - } break; - case WM_COMMAND: - { - switch (LOWORD(wParam)) - { - case IDB_CONFIRM_SAVE: // Fall through - case IDB_DONT_SAVE: - { - EndDialog(hwndDlg, wParam); - return TRUE; - } - } - } break; - } - - return FALSE; -} - -bool DebugCallStack::BackupCurrentLevel() -{ - CSystem* pSystem = static_cast(m_pSystem); - if (pSystem && pSystem->GetUserCallback()) - { - return pSystem->GetUserCallback()->OnBackupDocument(); - } - - return false; -} - -bool DebugCallStack::SaveCurrentLevel() -{ - CSystem* pSystem = static_cast(m_pSystem); - if (pSystem && pSystem->GetUserCallback()) - { - return pSystem->GetUserCallback()->OnSaveDocument(); - } - - return false; -} - -int DebugCallStack::SubmitBug(EXCEPTION_POINTERS* exception_pointer) -{ - int ret = IDB_EXIT; - - assert(!hwndException); - - RemoveOldFiles(); - - AZ::Debug::Trace::PrintCallstack("", 2); - - LogExceptionInfo(exception_pointer); - - if (IsFloatingPointException(exception_pointer)) - { - //! Print exception dialog. - ret = PrintException(exception_pointer); - } - - return ret; -} - -void DebugCallStack::ResetFPU(EXCEPTION_POINTERS* pex) -{ - if (IsFloatingPointException(pex)) - { - // How to reset FPU: http://www.experts-exchange.com/Programming/System/Windows__Programming/Q_10310953.html - _clearfp(); -#ifndef WIN64 - pex->ContextRecord->FloatSave.ControlWord |= 0x2F; - pex->ContextRecord->FloatSave.StatusWord &= ~0x8080; -#endif - } -} - -string DebugCallStack::GetModuleNameForAddr(void* addr) -{ - if (m_modules.empty()) - { - return "[unknown]"; - } - - if (addr < m_modules.begin()->first) - { - return "[unknown]"; - } - - TModules::const_iterator it = m_modules.begin(); - TModules::const_iterator end = m_modules.end(); - for (; ++it != end; ) - { - if (addr < it->first) - { - return (--it)->second; - } - } - - //if address is higher than the last module, we simply assume it is in the last module. - return m_modules.rbegin()->second; -} - -void DebugCallStack::GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line) -{ - AZ::Debug::SymbolStorage::StackLine func, file, module; - AZ::Debug::SymbolStorage::FindFunctionFromIP(addr, &func, &file, &module, line, baseAddr); - procName = func; - filename = file; -} - -string DebugCallStack::GetCurrentFilename() -{ - char fullpath[MAX_PATH_LENGTH + 1]; - GetModuleFileName(NULL, fullpath, MAX_PATH_LENGTH); - return fullpath; -} - -static bool IsFloatingPointException(EXCEPTION_POINTERS* pex) -{ - if (!pex) - { - return false; - } - - DWORD exceptionCode = pex->ExceptionRecord->ExceptionCode; - switch (exceptionCode) - { - case EXCEPTION_FLT_DENORMAL_OPERAND: - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - case EXCEPTION_FLT_INEXACT_RESULT: - case EXCEPTION_FLT_INVALID_OPERATION: - case EXCEPTION_FLT_OVERFLOW: - case EXCEPTION_FLT_UNDERFLOW: - case STATUS_FLOAT_MULTIPLE_FAULTS: - case STATUS_FLOAT_MULTIPLE_TRAPS: - return true; - - default: - return false; - } -} - -int DebugCallStack::PrintException(EXCEPTION_POINTERS* exception_pointer) -{ - return (int)DialogBoxParam(gDLLHandle, MAKEINTRESOURCE(IDD_CRITICAL_ERROR), NULL, DebugCallStack::ExceptionDialogProc, (LPARAM)exception_pointer); -} - -#else -void MarkThisThreadForDebugging(const char*) {} -void UnmarkThisThreadFromDebugging() {} -void UpdateFPExceptionsMaskForThreads() {} -#endif //WIN32 diff --git a/Code/CryEngine/CrySystem/DebugCallStack.h b/Code/CryEngine/CrySystem/DebugCallStack.h deleted file mode 100644 index c37e6ba0d4..0000000000 --- a/Code/CryEngine/CrySystem/DebugCallStack.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_DEBUGCALLSTACK_H -#define CRYINCLUDE_CRYSYSTEM_DEBUGCALLSTACK_H -#pragma once - - -#include "IDebugCallStack.h" - -#if defined (WIN32) || defined (WIN64) - -//! Limits the maximal number of functions in call stack. -const int MAX_DEBUG_STACK_ENTRIES_FILE_DUMP = 12; - -struct ISystem; - -//!============================================================================ -//! -//! DebugCallStack class, capture call stack information from symbol files. -//! -//!============================================================================ -class DebugCallStack - : public IDebugCallStack -{ -public: - DebugCallStack(); - virtual ~DebugCallStack(); - - ISystem* GetSystem() { return m_pSystem; }; - - virtual string GetModuleNameForAddr(void* addr); - virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line); - virtual string GetCurrentFilename(); - - void installErrorHandler(ISystem* pSystem); - virtual int handleException(EXCEPTION_POINTERS* exception_pointer); - - virtual void ReportBug(const char*); - - void dumpCallStack(std::vector& functions); - - void SetUserDialogEnable(const bool bUserDialogEnable); - - typedef std::map TModules; -protected: - static void RemoveOldFiles(); - static void RemoveFile(const char* szFileName); - - static int PrintException(EXCEPTION_POINTERS* exception_pointer); - static INT_PTR CALLBACK ExceptionDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam); - static INT_PTR CALLBACK ConfirmSaveDialogProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam); - - void LogExceptionInfo(EXCEPTION_POINTERS* exception_pointer); - bool BackupCurrentLevel(); - bool SaveCurrentLevel(); - int SubmitBug(EXCEPTION_POINTERS* exception_pointer); - void ResetFPU(EXCEPTION_POINTERS* pex); - - static const int s_iCallStackSize = 32768; - - char m_excLine[256]; - char m_excModule[128]; - - char m_excDesc[MAX_WARNING_LENGTH]; - char m_excCode[MAX_WARNING_LENGTH]; - char m_excAddr[80]; - char m_excCallstack[s_iCallStackSize]; - - void* prevExceptionHandler; - - bool m_bCrash; - const char* m_szBugMessage; - - ISystem* m_pSystem; - - int m_nSkipNumFunctions; - CONTEXT m_context; - - TModules m_modules; -}; - -#endif //WIN32 - -#endif // CRYINCLUDE_CRYSYSTEM_DEBUGCALLSTACK_H diff --git a/Code/CryEngine/CrySystem/DllMain.cpp b/Code/CryEngine/CrySystem/DllMain.cpp index 6173ebc0c6..c3a15812ce 100644 --- a/Code/CryEngine/CrySystem/DllMain.cpp +++ b/Code/CryEngine/CrySystem/DllMain.cpp @@ -14,7 +14,6 @@ #include "CrySystem_precompiled.h" #include "System.h" #include -#include "DebugCallStack.h" #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -72,10 +71,6 @@ public: { switch (event) { - case ESYSTEM_EVENT_LEVEL_UNLOAD: - gEnv->pSystem->SetThreadState(ESubsys_Physics, false); - break; - case ESYSTEM_EVENT_LEVEL_LOAD_START: case ESYSTEM_EVENT_LEVEL_LOAD_END: { @@ -87,7 +82,6 @@ public: { CryCleanup(); STLALLOCATOR_CLEANUP; - gEnv->pSystem->SetThreadState(ESubsys_Physics, true); break; } } @@ -135,21 +129,6 @@ CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupPar startupParams.pUserCallback->OnSystemConnect(pSystem); } - // Environment Variable to signal we don't want to override our exception handler - our crash report system will set this - auto envVar = AZ::Environment::FindVariable("ExceptionHandlerIsSet"); - bool handlerIsSet = (envVar && *envVar); - - if (!startupParams.bMinimal && !handlerIsSet) // in minimal mode, we want to crash when we crash! - { -#if defined(WIN32) - // Install exception handler in Release modes. - ((DebugCallStack*)IDebugCallStack::instance())->installErrorHandler(pSystem); -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE(DllMain_cpp) -#endif - } - bool retVal = false; { AZ::Debug::StartupLogSinkReporter initLogSink; @@ -171,20 +150,5 @@ CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupPar return pSystem; } - -CRYSYSTEM_API void WINAPI CryInstallUnhandledExceptionHandler() -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_4 -#include AZ_RESTRICTED_FILE(DllMain_cpp) -#endif -} - -#if defined(ENABLE_PROFILING_CODE) && !defined(LINUX) && !defined(APPLE) -CRYSYSTEM_API void CryInstallPostExceptionHandler(void (* PostExceptionHandlerCallback)()) -{ - return IDebugCallStack::instance()->FileCreationCallback(PostExceptionHandlerCallback); -} -#endif }; diff --git a/Code/CryEngine/CrySystem/IDebugCallStack.cpp b/Code/CryEngine/CrySystem/IDebugCallStack.cpp deleted file mode 100644 index 3d865dee6c..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.cpp +++ /dev/null @@ -1,278 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : A multiplatform base class for handling errors and collecting call stacks - - -#include "CrySystem_precompiled.h" -#include "IDebugCallStack.h" -#include -#include "System.h" -#include -#include -#include -#include -//#if !defined(LINUX) - -#include - -const char* const IDebugCallStack::s_szFatalErrorCode = "FATAL_ERROR"; - -IDebugCallStack::IDebugCallStack() - : m_bIsFatalError(false) - , m_postBackupProcess(0) - , m_memAllocFileHandle(AZ::IO::InvalidHandle) -{ -} - -IDebugCallStack::~IDebugCallStack() -{ - StopMemLog(); -} - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_SINGLETON -IDebugCallStack* IDebugCallStack::instance() -{ - static IDebugCallStack sInstance; - return &sInstance; -} -#endif - -void IDebugCallStack::FileCreationCallback(void (* postBackupProcess)()) -{ - m_postBackupProcess = postBackupProcess; -} -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::LogCallstack() -{ - AZ::Debug::Trace::PrintCallstack("", 2); -} - -const char* IDebugCallStack::TranslateExceptionCode(DWORD dwExcept) -{ - switch (dwExcept) - { -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_TRANSLATE - case EXCEPTION_ACCESS_VIOLATION: - return "EXCEPTION_ACCESS_VIOLATION"; - break; - case EXCEPTION_DATATYPE_MISALIGNMENT: - return "EXCEPTION_DATATYPE_MISALIGNMENT"; - break; - case EXCEPTION_BREAKPOINT: - return "EXCEPTION_BREAKPOINT"; - break; - case EXCEPTION_SINGLE_STEP: - return "EXCEPTION_SINGLE_STEP"; - break; - case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: - return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED"; - break; - case EXCEPTION_FLT_DENORMAL_OPERAND: - return "EXCEPTION_FLT_DENORMAL_OPERAND"; - break; - case EXCEPTION_FLT_DIVIDE_BY_ZERO: - return "EXCEPTION_FLT_DIVIDE_BY_ZERO"; - break; - case EXCEPTION_FLT_INEXACT_RESULT: - return "EXCEPTION_FLT_INEXACT_RESULT"; - break; - case EXCEPTION_FLT_INVALID_OPERATION: - return "EXCEPTION_FLT_INVALID_OPERATION"; - break; - case EXCEPTION_FLT_OVERFLOW: - return "EXCEPTION_FLT_OVERFLOW"; - break; - case EXCEPTION_FLT_STACK_CHECK: - return "EXCEPTION_FLT_STACK_CHECK"; - break; - case EXCEPTION_FLT_UNDERFLOW: - return "EXCEPTION_FLT_UNDERFLOW"; - break; - case EXCEPTION_INT_DIVIDE_BY_ZERO: - return "EXCEPTION_INT_DIVIDE_BY_ZERO"; - break; - case EXCEPTION_INT_OVERFLOW: - return "EXCEPTION_INT_OVERFLOW"; - break; - case EXCEPTION_PRIV_INSTRUCTION: - return "EXCEPTION_PRIV_INSTRUCTION"; - break; - case EXCEPTION_IN_PAGE_ERROR: - return "EXCEPTION_IN_PAGE_ERROR"; - break; - case EXCEPTION_ILLEGAL_INSTRUCTION: - return "EXCEPTION_ILLEGAL_INSTRUCTION"; - break; - case EXCEPTION_NONCONTINUABLE_EXCEPTION: - return "EXCEPTION_NONCONTINUABLE_EXCEPTION"; - break; - case EXCEPTION_STACK_OVERFLOW: - return "EXCEPTION_STACK_OVERFLOW"; - break; - case EXCEPTION_INVALID_DISPOSITION: - return "EXCEPTION_INVALID_DISPOSITION"; - break; - case EXCEPTION_GUARD_PAGE: - return "EXCEPTION_GUARD_PAGE"; - break; - case EXCEPTION_INVALID_HANDLE: - return "EXCEPTION_INVALID_HANDLE"; - break; - //case EXCEPTION_POSSIBLE_DEADLOCK: return "EXCEPTION_POSSIBLE_DEADLOCK"; break ; - - case STATUS_FLOAT_MULTIPLE_FAULTS: - return "STATUS_FLOAT_MULTIPLE_FAULTS"; - break; - case STATUS_FLOAT_MULTIPLE_TRAPS: - return "STATUS_FLOAT_MULTIPLE_TRAPS"; - break; - - -#endif - default: - return "Unknown"; - break; - } -} - -void IDebugCallStack::PutVersion(char* str, size_t length) -{ -AZ_PUSH_DISABLE_WARNING(4996, "-Wunknown-warning-option") - - if (!gEnv || !gEnv->pSystem) - { - return; - } - - char sFileVersion[128]; - gEnv->pSystem->GetFileVersion().ToString(sFileVersion, sizeof(sFileVersion)); - - char sProductVersion[128]; - gEnv->pSystem->GetProductVersion().ToString(sProductVersion, sizeof(sFileVersion)); - - - //! Get time. - time_t ltime; - time(<ime); - tm* today = localtime(<ime); - - char s[1024]; - //! Use strftime to build a customized time string. - strftime(s, 128, "Logged at %#c\n", today); - azstrcat(str, length, s); - sprintf_s(s, "FileVersion: %s\n", sFileVersion); - azstrcat(str, length, s); - sprintf_s(s, "ProductVersion: %s\n", sProductVersion); - azstrcat(str, length, s); - - if (gEnv->pLog) - { - const char* logfile = gEnv->pLog->GetFileName(); - if (logfile) - { - sprintf (s, "LogFile: %s\n", logfile); - azstrcat(str, length, s); - } - } - - AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); - azstrcat(str, length, "ProjectDir: "); - azstrcat(str, length, projectPath.c_str()); - azstrcat(str, length, "\n"); - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_DEBUGCALLSTACK_APPEND_MODULENAME - GetModuleFileNameA(NULL, s, sizeof(s)); - - // Log EXE filename only if possible (not full EXE path which could contain sensitive info) - AZStd::string exeName; - if (AZ::StringFunc::Path::GetFullFileName(s, exeName)) - { - azstrcat(str, length, "Executable: "); - azstrcat(str, length, exeName.c_str()); - -# ifdef AZ_DEBUG_BUILD - azstrcat(str, length, " (debug: yes"); -# else - azstrcat(str, length, " (debug: no"); -# endif - } -#endif -AZ_POP_DISABLE_WARNING -} - - -//Crash the application, in this way the debug callstack routine will be called and it will create all the necessary files (error.log, dump, and eventually screenshot) -void IDebugCallStack::FatalError(const char* description) -{ - m_bIsFatalError = true; - WriteLineToLog(description); - -#ifndef _RELEASE - bool bShowDebugScreen = g_cvars.sys_no_crash_dialog == 0; - // showing the debug screen is not safe when not called from mainthread - // it normally leads to a infinity recursion followed by a stack overflow, preventing - // useful call stacks, thus they are disabled - bShowDebugScreen = bShowDebugScreen && gEnv->mMainThreadId == CryGetCurrentThreadId(); - if (bShowDebugScreen) - { - EBUS_EVENT(AZ::NativeUI::NativeUIRequestBus, DisplayOkDialog, "Open 3D Engine Fatal Error", description, false); - } -#endif - -#if defined(WIN32) || !defined(_RELEASE) - int* p = 0x0; - PREFAST_SUPPRESS_WARNING(6011) * p = 1; // we're intentionally crashing here -#endif -} - -void IDebugCallStack::WriteLineToLog(const char* format, ...) -{ - CDebugAllowFileAccess allowFileAccess; - - va_list ArgList; - char szBuffer[MAX_WARNING_LENGTH]; - va_start(ArgList, format); - vsnprintf_s(szBuffer, sizeof(szBuffer), sizeof(szBuffer) - 1, format, ArgList); - cry_strcat(szBuffer, "\n"); - szBuffer[sizeof(szBuffer) - 1] = '\0'; - va_end(ArgList); - - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - AZ::IO::FileIOBase::GetDirectInstance()->Open("@Log@\\error.log", AZ::IO::GetOpenModeFromStringMode("a+t"), fileHandle); - if (fileHandle != AZ::IO::InvalidHandle) - { - AZ::IO::FileIOBase::GetDirectInstance()->Write(fileHandle, szBuffer, strlen(szBuffer)); - AZ::IO::FileIOBase::GetDirectInstance()->Flush(fileHandle); - AZ::IO::FileIOBase::GetDirectInstance()->Close(fileHandle); - } -} - -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::StartMemLog() -{ - AZ::IO::FileIOBase::GetDirectInstance()->Open("@Log@\\memallocfile.log", AZ::IO::OpenMode::ModeWrite, m_memAllocFileHandle); - - assert(m_memAllocFileHandle != AZ::IO::InvalidHandle); -} - -////////////////////////////////////////////////////////////////////////// -void IDebugCallStack::StopMemLog() -{ - if (m_memAllocFileHandle != AZ::IO::InvalidHandle) - { - AZ::IO::FileIOBase::GetDirectInstance()->Close(m_memAllocFileHandle); - m_memAllocFileHandle = AZ::IO::InvalidHandle; - } -} -//#endif //!defined(LINUX) diff --git a/Code/CryEngine/CrySystem/IDebugCallStack.h b/Code/CryEngine/CrySystem/IDebugCallStack.h deleted file mode 100644 index f181b73913..0000000000 --- a/Code/CryEngine/CrySystem/IDebugCallStack.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : A multiplatform base class for handling errors and collecting call stacks - -#ifndef CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H -#define CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H -#pragma once - -#include "System.h" - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_FORWARD_EXCEPTION_POINTERS -struct EXCEPTION_POINTERS; -#endif -//! Limits the maximal number of functions in call stack. -enum -{ - MAX_DEBUG_STACK_ENTRIES = 80 -}; - -class IDebugCallStack -{ -public: - // Returns single instance of DebugStack - static IDebugCallStack* instance(); - - virtual int handleException([[maybe_unused]] EXCEPTION_POINTERS* exception_pointer){return 0; } - - // returns the module name of a given address - virtual string GetModuleNameForAddr([[maybe_unused]] void* addr) { return "[unknown]"; } - - // returns the function name of a given address together with source file and line number (if available) of a given address - virtual void GetProcNameForAddr(void* addr, string& procName, void*& baseAddr, string& filename, int& line) - { - filename = "[unknown]"; - line = 0; - baseAddr = addr; -#if defined(PLATFORM_64BIT) - procName.Format("[%016llX]", addr); -#else - procName.Format("[%08X]", addr); -#endif - } - - // returns current filename - virtual string GetCurrentFilename() { return "[unknown]"; } - - //! Dumps Current Call Stack to log. - virtual void LogCallstack(); - //triggers a fatal error, so the DebugCallstack can create the error.log and terminate the application - void FatalError(const char*); - - //Reports a bug and continues execution - virtual void ReportBug(const char*) {} - - virtual void FileCreationCallback(void (* postBackupProcess)()); - - static void WriteLineToLog(const char* format, ...); - - virtual void StartMemLog(); - virtual void StopMemLog(); - -protected: - IDebugCallStack(); - virtual ~IDebugCallStack(); - - static const char* TranslateExceptionCode(DWORD dwExcept); - static void PutVersion(char* str, size_t length); - - bool m_bIsFatalError; - static const char* const s_szFatalErrorCode; - - void (* m_postBackupProcess)(); - - AZ::IO::HandleType m_memAllocFileHandle; -}; - - - -#endif // CRYINCLUDE_CRYSYSTEM_IDEBUGCALLSTACK_H diff --git a/Code/CryEngine/CrySystem/IThreadConfigManager.h b/Code/CryEngine/CrySystem/IThreadConfigManager.h deleted file mode 100644 index 97c4d7237b..0000000000 --- a/Code/CryEngine/CrySystem/IThreadConfigManager.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -struct SThreadConfig -{ - enum eThreadParamFlag - { - eThreadParamFlag_ThreadName = BIT(0), - eThreadParamFlag_StackSize = BIT(1), - eThreadParamFlag_Affinity = BIT(2), - eThreadParamFlag_Priority = BIT(3), - eThreadParamFlag_PriorityBoost = BIT(4), - }; - - typedef uint32 TThreadParamFlag; - - const char* szThreadName; - uint32 stackSizeBytes; - uint32 affinityFlag; - int32 priority; - bool bDisablePriorityBoost; - - TThreadParamFlag paramActivityFlag; -}; - -class IThreadConfigManager -{ -public: - virtual ~IThreadConfigManager() - { - } - - //! Called once during System startup. - //! Loads the thread configuration for the executing platform from file. - virtual bool LoadConfig(const char* pcPath) = 0; - - //! Returns true if a config has been loaded. - virtual bool ConfigLoaded() const = 0; - - //! Gets the thread configuration for the specified thread on the active platform. - //! If no matching config is found a default configuration is returned (which does not have the same name as the search string). - virtual const SThreadConfig* GetThreadConfig(const char* sThreadName, ...) = 0; - virtual const SThreadConfig* GetDefaultThreadConfig() const = 0; - - //! Dump a detailed description of the thread startup configurations for this platform to the log file. - virtual void DumpThreadConfigurationsToLog() = 0; -}; diff --git a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp index b8002b74a9..0af52d8cc4 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp @@ -17,7 +17,6 @@ #include "LevelSystem.h" #include #include "IMovieSystem.h" -#include "IMaterialEffects.h" #include #include #include "CryPath.h" @@ -648,20 +647,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) AZStd::string levelPath(pLevelInfo->GetPath()); - /* - ICVar *pFileCache = gEnv->pConsole->GetCVar("sys_FileCache"); CRY_ASSERT(pFileCache); - - if(pFileCache->GetIVal()) - { - if(pPak->OpenPack("",pLevelInfo->GetPath()+string("/FileCache.dat"))) - gEnv->pLog->Log("FileCache.dat loaded"); - else - gEnv->pLog->Log("FileCache.dat not loaded"); - } - */ - - m_pSystem->SetThreadState(ESubsys_Physics, false); - ICVar* pSpamDelay = gEnv->pConsole->GetCVar("log_SpamDelay"); float spamDelay = 0.0f; if (pSpamDelay) @@ -768,8 +753,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - m_pSystem->SetThreadState(ESubsys_Physics, true); - return m_pCurrentLevel; } diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 2a7f8d5c5e..8b3c75cce2 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -247,8 +247,6 @@ namespace LegacyLevelSystem auto pPak = gEnv->pCryPak; - m_pSystem->SetThreadState(ESubsys_Physics, false); - ICVar* pSpamDelay = gEnv->pConsole->GetCVar("log_SpamDelay"); float spamDelay = 0.0f; if (pSpamDelay) @@ -343,8 +341,6 @@ namespace LegacyLevelSystem gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - m_pSystem->SetThreadState(ESubsys_Physics, true); - return true; } diff --git a/Code/CryEngine/CrySystem/Log.cpp b/Code/CryEngine/CrySystem/Log.cpp index 62cf29fef9..c51947d8bc 100644 --- a/Code/CryEngine/CrySystem/Log.cpp +++ b/Code/CryEngine/CrySystem/Log.cpp @@ -920,13 +920,7 @@ bool CLog::LogToMainThread(const char* szString, ELogType logType, bool bAdd, SL msg.bAdd = bAdd; msg.destination = destination; msg.logType = logType; - // don't try to store the log message for later in case of out of memory, since then its very likely that this allocation - // also fails and results in a stack overflow. This way we should at least get a out of memory on-screen message instead of - // a not obvious crash - if ((gEnv) && (gEnv->bIsOutOfMemory == false)) - { - m_threadSafeMsgQueue.push(msg); - } + m_threadSafeMsgQueue.push(msg); return true; } return false; @@ -1448,8 +1442,6 @@ void CLog::UpdateLoadingScreen(const char* szFormat, ...) if (CryGetCurrentThreadId() == m_nMainThreadId) { - ((CSystem*)m_pSystem)->UpdateLoadingScreen(); - #ifndef LINUX // Take this opportunity to update streaming engine. if (IStreamEngine* pStreamEngine = GetISystem()->GetStreamEngine()) diff --git a/Code/CryEngine/CrySystem/NotificationNetwork.cpp b/Code/CryEngine/CrySystem/NotificationNetwork.cpp deleted file mode 100644 index a0bd3fb9e6..0000000000 --- a/Code/CryEngine/CrySystem/NotificationNetwork.cpp +++ /dev/null @@ -1,1345 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "NotificationNetwork.h" -#include - -#include -#include - -#undef LockDebug -//#define LockDebug(str1,str2) {string strMessage;strMessage.Format(str1,str2);if (m_clients.size()) OutputDebugString(strMessage.c_str());} -#define LockDebug(str1, str2) - -// - -extern bool RCON_IsRemoteAllowedToConnect(const AZ::AzSock::AzSocketAddress& connectee); - -using namespace NotificationNetwork; - -// - -#include -class CQueryNotification - : public INotificationNetworkListener -{ - // INotificationNetworkListener -public: - virtual void OnNotificationNetworkReceive([[maybe_unused]] const void* pBuffer, [[maybe_unused]] size_t length) - { - INotificationNetwork* pNotificationNetwork = - gEnv->pSystem->GetINotificationNetwork(); - if (!pNotificationNetwork) - { - return; - } - - AZ::IO::FixedMaxPathString projectPath = AZ::Utils::GetProjectPath(); - if (projectPath.empty()) - { - return; - } - - pNotificationNetwork->Send("SystemInfo", projectPath.c_str(), projectPath.size()); - } -} g_queryNotification; - -AZSOCKET CConnectionBase::CreateSocket() -{ - AZSOCKET sock = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - CryLog("CNotificationNetworkClient::Create: Failed to create socket."); - return AZ_SOCKET_INVALID; - } - - if (AZ::AzSock::SetSocketOption(sock, AZ::AzSock::AzSocketOption::REUSEADDR, true)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set SO_REUSEADDR option."); - return AZ_SOCKET_INVALID; - } - -#if defined (WIN32) || defined(WIN64) //MS Platforms - if (AZ::AzSock::SetSocketBlockingMode(sock, false)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Connect: Failed to set socket to asynchronous operation."); - return AZ_SOCKET_INVALID; - } - -#endif - - // TCP_NODELAY required for win32 because of high latency connection otherwise -#if defined(WIN32) - if (AZ::AzSock::EnableTCPNoDelay(sock, true)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set TCP_NODELAY option."); - return AZ_SOCKET_INVALID; - } -#endif - - return sock; -} - -bool CConnectionBase::Connect(const char* address, uint16 port) -{ - AZ::AzSock::AzSocketAddress socketAddress; - socketAddress.SetAddress(address, port); - - int result = AZ::AzSock::Connect(m_socket, socketAddress); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::AzSockError err = AZ::AzSock::AzSockError(result); - if (err == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK_CONN) - { - return true; - } - - if (err == AZ::AzSock::AzSockError::eASE_EISCONN) - { - if (!m_boIsConnected) - { - m_boIsConnected = true; - m_boIsFailedToConnect = false; - OnConnect(true); - } - return true; - } - - if (err == AZ::AzSock::AzSockError::eASE_EALREADY) - { - // It will happen, in case of DNS problems, or if the console is not - // reachable or turned off. - //CryLog("CNotificationNetworkClient::Connect: Failed to connect. Reason: already conencted."); - return true; - } - - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - CryLog("CNotificationNetworkClient::Connect: Failed to connect. Reason: %d ", result); - return false; - } - - return true; -} - -/* - - CChannel - -*/ - -bool CChannel::IsNameValid(const char* name) -{ - if (!name) - { - return false; - } - if (!*name) - { - return false; - } - - if (::strlen(name) > NN_CHANNEL_NAME_LENGTH_MAX) - { - return false; - } - - return true; -} - -// - -CChannel::CChannel() -{ -} - -CChannel::CChannel(const char* name) -{ - if (!name) - { - return; - } - - if (!*name) - { - return; - } - - size_t length = MIN(::strlen(name), NN_CHANNEL_NAME_LENGTH_MAX); - ::memset(m_name, 0, NN_CHANNEL_NAME_LENGTH_MAX); - ::memcpy(m_name, name, length); -} - -CChannel::~CChannel() -{ -} - -// - -void CChannel::WriteToPacketHeader(void* pPacket) const -{ - ::memcpy((uint8*)pPacket + NN_PACKET_HEADER_OFFSET_CHANNEL, - m_name, NN_CHANNEL_NAME_LENGTH_MAX); -} - -void CChannel::ReadFromPacketHeader(void* pPacket) -{ - ::memcpy(m_name, (uint8*)pPacket + NN_PACKET_HEADER_OFFSET_CHANNEL, - NN_CHANNEL_NAME_LENGTH_MAX); -} - -// - -bool CChannel::operator ==(const CChannel& channel) const -{ - return ::strncmp(m_name, channel.m_name, NN_CHANNEL_NAME_LENGTH_MAX) == 0; -} - -bool CChannel::operator !=(const CChannel& channel) const -{ - return ::strncmp(m_name, channel.m_name, NN_CHANNEL_NAME_LENGTH_MAX) != 0; -} - -/* - - CListeners - -*/ - -CListeners::CListeners() -{ - m_pNotificationWrite = &m_notifications[0]; - m_pNotificationRead = &m_notifications[1]; -} - -CListeners::~CListeners() -{ - while (!m_pNotificationRead->empty()) - { - SBuffer buffer = m_pNotificationRead->front(); - m_pNotificationRead->pop(); - delete[] buffer.pData; - } - - while (!m_pNotificationWrite->empty()) - { - SBuffer buffer = m_pNotificationWrite->front(); - m_pNotificationWrite->pop(); - delete[] buffer.pData; - } -} - -// - -size_t CListeners::Count(const CChannel& channel) -{ - size_t count = 0; - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].second != channel) - { - continue; - } - - ++count; - } - - return count; -} - -CChannel* CListeners::Channel(INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first != pListener) - { - continue; - } - - return &m_listeners[i].second; - } - - return nullptr; -} - -bool CListeners::Bind(const CChannel& channel, INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first == pListener) - { - m_listeners[i].second = channel; - return true; - } - } - - m_listeners.push_back(std::pair()); - m_listeners.back().first = pListener; - m_listeners.back().second = channel; - return true; -} - -bool CListeners::Remove(INotificationNetworkListener* pListener) -{ - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].first != pListener) - { - continue; - } - - m_listeners[i] = m_listeners.back(); - m_listeners.pop_back(); - return true; - } - - return false; -} - -void CListeners::NotificationPush(const SBuffer& buffer) -{ - // TODO: Use auto lock. - m_notificationCriticalSection.Lock(); - m_pNotificationWrite->push(buffer); - m_notificationCriticalSection.Unlock(); -} - -void CListeners::NotificationsProcess() -{ - m_notificationCriticalSection.Lock(); - std::swap(m_pNotificationWrite, m_pNotificationRead); - m_notificationCriticalSection.Unlock(); - - while (!m_pNotificationRead->empty()) - { - SBuffer buffer = m_pNotificationRead->front(); - m_pNotificationRead->pop(); - - for (size_t i = 0; i < m_listeners.size(); ++i) - { - if (m_listeners[i].second != buffer.channel) - { - continue; - } - - m_listeners[i].first->OnNotificationNetworkReceive( - buffer.pData, buffer.length); - } - - delete[] buffer.pData; - } -} - -/* - - CConnectionBase - -*/ - -CConnectionBase::CConnectionBase(CNotificationNetwork* pNotificationNetwork) -{ - m_pNotificationNetwork = pNotificationNetwork; - - m_port = 0; - - m_socket = AZ_SOCKET_INVALID; - - m_buffer.pData = nullptr; - m_buffer.length = 0; - m_dataLeft = 0; - - m_boIsConnected = false; - m_boIsFailedToConnect = false; -} - -CConnectionBase::~CConnectionBase() -{ - if (m_buffer.pData) - { - delete[] m_buffer.pData; - } - - if (m_socket != AZ_SOCKET_INVALID) - { - CloseSocket_Internal(); - } -} - -// - -void CConnectionBase::SetAddress(const char* address, uint16 port) -{ - size_t length = MIN(::strlen(address), 15); - ::memset(m_address, 0, sizeof(m_address)); - ::memcpy(m_address, address, length); - m_port = port; -} - -bool CConnectionBase::Validate() -{ - if (m_socket != AZ_SOCKET_INVALID) - { - if (!m_port) - { - AZ::AzSock::AzSocketAddress socketAddress; - int result = AZ::AzSock::GetSockName(m_socket, socketAddress); - if (AZ::AzSock::SocketErrorOccured(result)) - { - return false; - } - } - - return Select_Internal(); - } - - if (!m_port) // If port is not set we don't want to try to reconnect. - { - return false; - } - - m_socket = CreateSocket(); - // If the create sockect will fail, it is likely that we will never be able to connect, - // we might want to signal that. - - Connect(m_address, m_port); - - return false; -} - -bool CConnectionBase::Send(const void* pBuffer, size_t length) -{ - if (!Validate()) - { - return false; - } - - size_t sent = 0; - while (sent < length) - { - int r = AZ::AzSock::Send(m_socket, (const char*)pBuffer + sent, length - sent, 0); - if (AZ::AzSock::SocketErrorOccured(r)) - { - AZ::AzSock::AzSockError nCurrentError = AZ::AzSock::AzSockError(r); - if (nCurrentError == AZ::AzSock::AzSockError::eASE_ENOTCONN) - { - r = 0; - break; - } - else if (nCurrentError == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK) - { - r = 0; - } - else - { - CryLog("CNotificationNetworkClient::Send: Failed to send package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - } - - sent += r; - } - - return true; -} - -bool CConnectionBase::SendMessage(EMessage eMessage, const CChannel& channel, uint32 data) -{ - char header[NN_PACKET_HEADER_LENGTH]; - ::memset(header, 0, NN_PACKET_HEADER_LENGTH); - *(uint32*)&header[NN_PACKET_HEADER_OFFSET_MESSAGE] = AZ::AzSock::HostToNetLong(eMessage); - *(uint32*)&header[NN_PACKET_HEADER_OFFSET_DATA_LENGTH] = AZ::AzSock::HostToNetLong(data); - channel.WriteToPacketHeader(header); - - if (!Send(header, NN_PACKET_HEADER_LENGTH)) - { - return false; - } - - return true; -} - -bool CConnectionBase::Select_Internal() -{ - if (m_socket == AZ_SOCKET_INVALID) - { - return false; - } - - AZFD_SET stExceptions; - AZFD_SET stWriteSockets; - - FD_ZERO(&stExceptions); - FD_SET(m_socket, &stExceptions); - - FD_ZERO(&stWriteSockets); - FD_SET(m_socket, &stWriteSockets); - - AZTIMEVAL timeOut = { 0, 0 }; - - int r = AZ::AzSock::Select(m_socket, nullptr, &stWriteSockets, &stExceptions, &timeOut); - if (AZ::AzSock::SocketErrorOccured(r)) - { - CryLog("CNotificationNetworkClient:: Failed to select socket. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - m_boIsFailedToConnect = true; - return false; - } - else if (!r) - { - return m_boIsConnected; - } - - if (FD_ISSET(m_socket, &stExceptions)) - { - CloseSocket_Internal(); - m_boIsFailedToConnect = true; - OnConnect(m_boIsConnected); // Handles failed attempt to connect. - return false; - } - else if (FD_ISSET(m_socket, &stWriteSockets)) // In Windows a socket can be in both lists. - { - if (!m_boIsConnected) - { - m_boIsConnected = true; - m_boIsFailedToConnect = false; - OnConnect(m_boIsConnected); // Handles successful attempt to connect. - } - return true; - } - - return false; -} - -void CConnectionBase::CloseSocket_Internal() -{ - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - if (m_boIsConnected) - { - OnDisconnect(); - } - m_boIsConnected = false; -} - -bool CConnectionBase::SendNotification(const CChannel& channel, const void* pBuffer, size_t length) -{ - if (!SendMessage(eMessage_DataTransfer, channel, length)) - { - return false; - } - if (!length) - { - return true; - } - - if (!Send(pBuffer, length)) - { - return false; - } - - return true; -} - -bool CConnectionBase::ReceiveMessage(CListeners& listeners) -{ - if (!Validate()) - { - return false; - } - - if (!m_dataLeft) - { - m_dataLeft = NN_PACKET_HEADER_LENGTH; - } - int r = AZ::AzSock::Recv(m_socket, (char*)&m_bufferHeader[NN_PACKET_HEADER_LENGTH - m_dataLeft], m_dataLeft, 0); - if (!r) - { - // Connection terminated. - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - if (AZ::AzSock::SocketErrorOccured(r)) - { - m_dataLeft = 0; - - CryLog("CNotificationNetworkClient::ReceiveMessage: Failed to receive package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - - if (m_dataLeft -= r) - { - return true; - } - - // The whole message was received, process it... - - EMessage eMessage = (EMessage)AZ::AzSock::NetToHostLong( - *(uint32*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_MESSAGE]); - const CChannel& channel = *(CChannel*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_CHANNEL]; - - if (eMessage == eMessage_DataTransfer) - { - m_dataLeft = AZ::AzSock::NetToHostLong(*(uint32*)&m_bufferHeader[NN_PACKET_HEADER_OFFSET_DATA_LENGTH]); - if (!m_dataLeft) - { - SBuffer buffer; - buffer.channel = channel; - buffer.pData = nullptr; - buffer.length = 0; - listeners.NotificationPush(buffer); - return true; - } - - m_buffer.pData = new uint8[m_buffer.length = m_dataLeft]; - if (!m_buffer.pData) - { - CryLog("CNotificationNetwork::CConnection::Receive: Failed to allocate buffer.\n"); - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - m_buffer.channel.ReadFromPacketHeader(m_bufferHeader); - return +1; - } - - if (!OnMessage(eMessage, channel)) - { - CryLog("NotificationNetwork::CConnectionBase::ReceiveMessage: " - "Unknown message received, terminating Connection...\n"); - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - return true; -} - -bool CConnectionBase::ReceiveNotification(CListeners& listeners) -{ - int r = AZ::AzSock::Recv(m_socket, (char*)&m_buffer.pData[m_buffer.length - m_dataLeft], m_dataLeft, 0); - if (!r) - { - CryLog("CNotificationNetworkClient::ReceiveNotification: Failed to receive package. Reason: Connection terminated."); - // Connection terminated. - m_dataLeft = 0; - - CloseSocket_Internal(); - return false; - } - - if (AZ::AzSock::SocketErrorOccured(r)) - { - m_dataLeft = 0; - - CryLog("CNotificationNetworkClient::ReceiveNotification: Failed to receive package. Reason: %s", AZ::AzSock::GetStringForError(r)); - CloseSocket_Internal(); - return false; - } - - if (m_dataLeft -= r) - { - return true; - } - - listeners.NotificationPush(m_buffer); - m_buffer.pData = nullptr; - m_buffer.length = 0; - m_dataLeft = 0; - return true; -} - -bool CConnectionBase::Receive(CListeners& listeners) -{ - if (m_buffer.pData) - { - return ReceiveNotification(listeners); - } - - return ReceiveMessage(listeners); -} - -bool CConnectionBase::GetIsConnectedFlag() -{ - return Select_Internal() || m_boIsConnected; -} - -bool CConnectionBase::GetIsFailedToConnectFlag() const -{ - return m_boIsFailedToConnect; -} - -/* - - CClient - -*/ - -CClient* CClient::Create(CNotificationNetwork* pNotificationNetwork, const char* address, uint16 port) -{ - CClient* pClient = new CClient(pNotificationNetwork); - AZSOCKET sock = pClient->CreateSocket(); - // In the current implementation, this is REALLY UNLIKELY to happen. - if (sock == AZ_SOCKET_INVALID) - { - delete pClient; - return nullptr; - } - - // - pClient->SetSocket(sock); - pClient->Connect(address, port); - - pClient->SetAddress(address, port); - pClient->SetSocket(sock); - return pClient; -} - -CClient* CClient::Create(CNotificationNetwork* pNotificationNetwork) -{ - CClient* pClient = new CClient(pNotificationNetwork); - return pClient; -} - -// - -CClient::CClient(CNotificationNetwork* pNotificationNetwork) - : CConnectionBase(pNotificationNetwork) -{ -} - -CClient::~CClient() -{ - GetNotificationNetwork()->ReleaseClients(this); -} - -// - -void CClient::Update() -{ - m_listeners.NotificationsProcess(); -} - -// CConnectionBase - -bool CClient::OnConnect(bool boConnected) -{ - if (boConnected) - { - for (size_t i = 0; i < m_listeners.Count(); ++i) - { - if (!SendMessage(eMessage_ChannelRegister, m_listeners.Channel(i), 0)) - { - return false; - } - } - } - - CryAutoLock lock(m_stConnectionCallbacksLock); - for (size_t nCount = 0; nCount < m_cNotificationNetworkConnectionCallbacks.size(); ++nCount) - { - m_cNotificationNetworkConnectionCallbacks[nCount]->OnConnect(this, boConnected); - } - - return boConnected; -} - -bool CClient::OnDisconnect() -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - for (size_t nCount = 0; nCount < m_cNotificationNetworkConnectionCallbacks.size(); ++nCount) - { - m_cNotificationNetworkConnectionCallbacks[nCount]->OnDisconnected(this); - } - - return true; -} - -bool CClient::OnMessage([[maybe_unused]] EMessage eMessage, [[maybe_unused]] const CChannel& channel) -{ - return false; -} - -// INotificationNetworkClient - -bool CClient::Connect(const char* address, uint16 port) -{ - bool bReturnValue(false); - - if (m_socket == AZ_SOCKET_INVALID) - { - m_socket = CreateSocket(); - } - - bReturnValue = CConnectionBase::Connect(address, port); - if (bReturnValue) - { - SetAddress(address, port); - } - - return bReturnValue; -} - -bool CClient::ListenerBind(const char* channelName, INotificationNetworkListener* pListener) -{ - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - - if (!m_listeners.Bind(CChannel(channelName), pListener)) - { - return false; - } - - if (!SendMessage(eMessage_ChannelRegister, CChannel(channelName), 0)) - { - return false; - } - - return true; -} - -bool CClient::ListenerRemove(INotificationNetworkListener* pListener) -{ - CChannel* pChannel = m_listeners.Channel(pListener); - if (!pChannel) - { - return false; - } - - if (!m_listeners.Remove(pListener)) - { - return false; - } - - if (!SendMessage(eMessage_ChannelUnregister, *pChannel, 0)) - { - return false; - } - - return true; -} - -bool CClient::Send(const char* channelName, const void* pBuffer, size_t length) -{ - CRY_ASSERT(CChannel::IsNameValid(channelName)); - // CRY_ASSERT_MESSAGE(channelLength <= NN_CHANNEL_NAME_LENGTH_MAX, - // "Channel name \"%s\" was passed to a Notification Network method, the name cannot be longer than %d chars.", - // channel, NN_CHANNEL_NAME_LENGTH_MAX); - - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - if (!SendNotification(CChannel(channelName), pBuffer, length)) - { - return false; - } - - return true; -} - -bool CClient::RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - return stl::push_back_unique(m_cNotificationNetworkConnectionCallbacks, pConnectionCallback); -} - -bool CClient::UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback) -{ - CryAutoLock lock(m_stConnectionCallbacksLock); - return stl::find_and_erase(m_cNotificationNetworkConnectionCallbacks, pConnectionCallback); -} - -/* - - CNotificationNetwork::CConnection - -*/ - -CNotificationNetwork::CConnection::CConnection(CNotificationNetwork* pNotificationNetwork, AZSOCKET sock) - : CConnectionBase(pNotificationNetwork) -{ - SetSocket(sock); - m_listeningChannels.reserve(8); -} - -CNotificationNetwork::CConnection::~CConnection() -{ -} - -// - -bool CNotificationNetwork::CConnection::IsListening(const CChannel& channel) -{ - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] == channel) - { - return true; - } - } - - return false; -} - -// CConnectionBase - -bool CNotificationNetwork::CConnection::OnMessage(EMessage eMessage, const CChannel& channel) -{ - switch (eMessage) - { - case eMessage_ChannelRegister: - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] == channel) - { - return true; - } - } - m_listeningChannels.push_back(channel); - return true; - - case eMessage_ChannelUnregister: - for (size_t i = 0; i < m_listeningChannels.size(); ++i) - { - if (m_listeningChannels[i] != channel) - { - continue; - } - - m_listeningChannels[i] = m_listeningChannels.back(); - m_listeningChannels.pop_back(); - return true; - } - return true; - } - - return false; -} - -/* - - CNotificationNetwork::CThread - -*/ - -CNotificationNetwork::CThread::CThread() -{ - m_pNotificationNetwork = nullptr; - m_bRun = true; -} - -CNotificationNetwork::CThread::~CThread() -{ -} - -// - -bool CNotificationNetwork::CThread::Begin(CNotificationNetwork* pNotificationNetwork) -{ - m_pNotificationNetwork = pNotificationNetwork; - Start(-1, (char*)NN_THREAD_NAME); - return true; -} - - -void CNotificationNetwork::CThread::End() -{ - m_bRun = false; - // WaitForThread(); - - // TODO: Should properly close! -} - -// CryRunnable - -void CNotificationNetwork::CThread::Run() -{ - CryThreadSetName(threadID(THREADID_NULL), NN_THREAD_NAME); - while (m_bRun) - { - m_pNotificationNetwork->ProcessSockets(); - } -} - -/* - - CNotificationNetwork - -*/ - -CNotificationNetwork* CNotificationNetwork::Create() -{ - AZ::AzSock::Startup(); - - AZSOCKET sock = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - CryLog("CNotificationNetwork::Create: Failed to create socket.\n"); - return nullptr; - } - - // Disable nagling of small blocks to fight high latency connection - int result = AZ::AzSock::EnableTCPNoDelay(sock, true); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Create: Failed to set TCP_NODELAY option."); - return nullptr; - } - - result = AZ::AzSock::SetSocketBlockingMode(sock, false); - if (AZ::AzSock::SocketErrorOccured(result)) - { - AZ::AzSock::CloseSocket(sock); - CryLog("CNotificationNetworkClient::Connect: Failed to set socket to asynchronous operation."); - return nullptr; - } - - // Editor uses a different port to avoid conflicts when running both editor and game on same PC - // But allows the lua remote debugger to connect to the editor - unsigned short port = gEnv && gEnv->IsEditor() ? 9433 : 9432; - - AZ::AzSock::AzSocketAddress addr; - addr.SetAddrPort(port); - - result = AZ::AzSock::Bind(sock, addr); - if (AZ::AzSock::SocketErrorOccured(result)) - { - CryLog("CNotificationNetwork::Create: Failed to bind socket.\n"); - AZ::AzSock::CloseSocket(sock); - return nullptr; - } - - result = AZ::AzSock::Listen(sock, 8); - if (AZ::AzSock::SocketErrorOccured(result)) - { - CryLog("CNotificationNetwork::Create: Failed to listen.\n"); - AZ::AzSock::CloseSocket(sock); - return nullptr; - } - - CNotificationNetwork* pNotificationNetwork = new CNotificationNetwork(); - pNotificationNetwork->m_socket = sock; - - pNotificationNetwork->m_thread.Begin(pNotificationNetwork); - - return pNotificationNetwork; -} - -// - -CNotificationNetwork::CNotificationNetwork() -{ - m_socket = AZ_SOCKET_INVALID; - - m_connections.reserve(4); - - m_listeners.Bind("Query", &g_queryNotification); -} - -CNotificationNetwork::~CNotificationNetwork() -{ - m_thread.End(); - m_thread.Stop(); - m_thread.WaitForThread(); - while (!m_connections.empty()) - { - delete m_connections.back(); - m_connections.pop_back(); - } - - if (m_socket != AZ_SOCKET_INVALID) - { - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - AZ::AzSock::Cleanup(); -} - -// - -void CNotificationNetwork::ReleaseClients(CClient* pClient) -{ - // TODO: Use CryAutoLock - LockDebug("Lock %s\n", "CNotificationNetwork::ReleaseClients()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (m_clients[i] != pClient) - { - continue; - } - - m_clients[i] = m_clients.back(); - m_clients.pop_back(); - break; - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::ReleaseClients()"); -} - -void CNotificationNetwork::ProcessSockets() -{ - fd_set read; - FD_ZERO(&read); - AZSOCKET socketMax = 0; - if (m_socket != AZ_SOCKET_INVALID) - { - FD_SET(m_socket, &read); - socketMax = m_socket; - } - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (m_connections[i]->Validate()) - { - AZSOCKET sock = m_connections[i]->GetSocket(); - FD_SET(sock, &read); - - if (socketMax < sock) - { - socketMax = sock; - } - - continue; - } - - // The Connection is invalid, remove it. - CConnection* pConnection = m_connections[i]; - m_connections[i] = m_connections.back(); - m_connections.pop_back(); - delete pConnection; - - // Invalidate the loop increment since we just removed a Connection and - // in the process potentially replaced its slot with an unprocessed one. - --i; - - CryLog("Notification Network Connection terminated, current total: %d\n", - (int)m_connections.size()); - } - - LockDebug("Lock %s\n", "CNotificationNetwork::ProcessSockets()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (!m_clients[i]->Validate()) - { - continue; - } - - AZSOCKET sock = m_clients[i]->GetSocket(); - FD_SET(sock, &read); - - if (socketMax < sock) - { - socketMax = sock; - } - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::ProcessSockets()"); - - AZTIMEVAL timeOut = { 1, 0 }; - int r = AZ::AzSock::Select(socketMax, &read, nullptr, nullptr, &timeOut); - if (r == 0) - { - return; - } - - // When we have no sockets, the select statement will fail and not - // block for even 1 second, as it should... - if (AZ::AzSock::SocketErrorOccured(r)) - { - // So we force the sleep here for now. - Sleep(1000); - return; - } - - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!FD_ISSET(m_connections[i]->GetSocket(), &read)) - { - continue; - } - - m_connections[i]->Receive(m_listeners); - } - - LockDebug("Lock 2 %s\n", "CNotificationNetwork::ProcessSockets()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - if (!FD_ISSET(m_clients[i]->GetSocket(), &read)) - { - continue; - } - - m_clients[i]->Receive(); - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock 2 %s\n", "CNotificationNetwork::ProcessSockets()"); - - if (m_socket == AZ_SOCKET_INVALID) - { - return; - } - if (!FD_ISSET(m_socket, &read)) - { - return; - } - - AZ::AzSock::AzSocketAddress addr; - AZSOCKET sock = AZ::AzSock::Accept(m_socket, addr); - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - return; - } - - if (!RCON_IsRemoteAllowedToConnect(addr)) - { - AZ::AzSock::CloseSocket(sock); - return; - } - - m_connections.push_back(new CConnection(this, sock)); - - CryLog("Notification Network accepted new Connection, current total: %d\n", - (int)m_connections.size()); -} - -// INotificationNetwork - -INotificationNetworkClient* CNotificationNetwork::CreateClient() -{ - CClient* pClient = CClient::Create(this); - - LockDebug("Lock %s\n", "CNotificationNetwork::CreateClient()"); - m_clientsCriticalSection.Lock(); - m_clients.push_back(pClient); - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::CreateClient()"); - - return pClient; -} - -INotificationNetworkClient* CNotificationNetwork::Connect(const char* address, uint16 port) -{ - CClient* pClient = CClient::Create(this, address, port); - if (!pClient) - { - return nullptr; - } - - LockDebug("Lock %s\n", "CNotificationNetwork::Connect()"); - m_clientsCriticalSection.Lock(); - m_clients.push_back(pClient); - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::Connect()"); - - return pClient; -} - -size_t CNotificationNetwork::GetConnectionCount(const char* channelName) -{ - if (!channelName) - { - return m_connections.size(); - } - - if (!CChannel::IsNameValid(channelName)) - { - return 0; - } - - CChannel channel(channelName); - size_t count = 0; - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!m_connections[i]->IsListening(channel)) - { - continue; - } - - ++count; - } - return count; -} - -bool CNotificationNetwork::ListenerBind(const char* channelName, INotificationNetworkListener* pListener) -{ - if (!CChannel::IsNameValid(channelName)) - { - return false; - } - - return m_listeners.Bind(CChannel(channelName), pListener); -} - -bool CNotificationNetwork::ListenerRemove(INotificationNetworkListener* pListener) -{ - return m_listeners.Remove(pListener); -} - -void CNotificationNetwork::Update() -{ - m_listeners.NotificationsProcess(); - - LockDebug("Lock %s\n", "CNotificationNetwork::Update()"); - m_clientsCriticalSection.Lock(); - for (size_t i = 0; i < m_clients.size(); ++i) - { - m_clients[i]->Update(); - } - m_clientsCriticalSection.Unlock(); - LockDebug("Unlock %s\n", "CNotificationNetwork::Update()"); -} - -uint32 CNotificationNetwork::Send(const char* channelName, const void* pBuffer, size_t length) -{ - if (!CChannel::IsNameValid(channelName)) - { - return 0; - } - - CChannel channel(channelName); - - // TODO: There should be a mutex lock here to ensure thread safety. - - uint32 count = 0; - for (size_t i = 0; i < m_connections.size(); ++i) - { - if (!m_connections[i]->IsListening(channel)) - { - continue; - } - - if (m_connections[i]->SendNotification(channel, pBuffer, length)) - { - ++count; - } - } - - return count; -} diff --git a/Code/CryEngine/CrySystem/NotificationNetwork.h b/Code/CryEngine/CrySystem/NotificationNetwork.h deleted file mode 100644 index ee336dbbb0..0000000000 --- a/Code/CryEngine/CrySystem/NotificationNetwork.h +++ /dev/null @@ -1,293 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_NOTIFICATIONNETWORK_H -#define CRYINCLUDE_CRYSYSTEM_NOTIFICATIONNETWORK_H - -#pragma once - -#include -#include -#include - -#include - -class CNotificationNetwork; -namespace NotificationNetwork { - // Constants - - static const uint32 NN_PACKET_HEADER_LENGTH = 2 * sizeof(uint32) + NN_CHANNEL_NAME_LENGTH_MAX; - - static const uint32 NN_PACKET_HEADER_OFFSET_MESSAGE = 0; - static const uint32 NN_PACKET_HEADER_OFFSET_DATA_LENGTH = sizeof(uint32); - static const uint32 NN_PACKET_HEADER_OFFSET_CHANNEL = sizeof(uint32) + sizeof(uint32); - - static const char* NN_THREAD_NAME = "NotificationNetwork"; - - enum EMessage - { - eMessage_DataTransfer = 0xbada2217, - - eMessage_ChannelRegister = 0xab4eda30, - eMessage_ChannelUnregister = 0xfa4e3423, - }; - - // Classes - - struct CChannel - { - public: - static bool IsNameValid(const char* name); - - public: - CChannel(); - CChannel(const char* name); - ~CChannel(); - - public: - void WriteToPacketHeader(void* pPacket) const; - void ReadFromPacketHeader(void* pPacket); - - public: - bool operator ==(const CChannel& channel) const; - bool operator !=(const CChannel& channel) const; - - private: - char m_name[NN_CHANNEL_NAME_LENGTH_MAX]; - }; - - // TEMP - struct SBuffer - { - uint8* pData; - uint32 length; - CChannel channel; - }; - - class CListeners - { - public: - CListeners(); - ~CListeners(); - - public: - size_t Count() { return m_listeners.size(); } - size_t Count(const CChannel& channel); - - CChannel& Channel(size_t index) { return m_listeners[index].second; } - CChannel* Channel(INotificationNetworkListener* pListener); - - bool Bind(const CChannel& channel, INotificationNetworkListener* pListener); - bool Remove(INotificationNetworkListener* pListener); - - void NotificationPush(const SBuffer& buffer); - void NotificationsProcess(); - - private: - std::vector< std::pair > m_listeners; - - std::queue m_notifications[2]; - std::queue* m_pNotificationWrite; - std::queue* m_pNotificationRead; - CryCriticalSection m_notificationCriticalSection; - }; - - class CConnectionBase - { - public: - CConnectionBase(CNotificationNetwork* pNotificationNetwork); - virtual ~CConnectionBase(); - - public: - AZSOCKET CreateSocket(); - - bool Connect(const char* address, uint16 port); - - AZSOCKET GetSocket() { return m_socket; } - - bool Validate(); - - bool SendNotification(const CChannel& channel, const void* pBuffer, size_t length); - - bool Receive(CListeners& listeners); - - bool GetIsConnectedFlag(); - bool GetIsFailedToConnectFlag() const; - - protected: - CNotificationNetwork* GetNotificationNetwork() { return m_pNotificationNetwork; } - - void SetAddress(const char* address, uint16 port); - void SetSocket(AZSOCKET sock) { m_socket = sock; } - - bool Send(const void* pBuffer, size_t length); - bool SendMessage(EMessage eMessage, const CChannel& channel, uint32 data); - - bool Select_Internal(); - void CloseSocket_Internal(); - - virtual bool OnConnect([[maybe_unused]] bool bConnectionResult) { return true; } - virtual bool OnDisconnect() {return true; } - virtual bool OnMessage([[maybe_unused]] EMessage eMessage, [[maybe_unused]] const CChannel& channel) { return false; } - - private: - bool ReceiveMessage(CListeners& listeners); - bool ReceiveNotification(CListeners& listeners); - - protected: - CNotificationNetwork* m_pNotificationNetwork; - - char m_address[16]; - uint16 m_port; - - AZSOCKET m_socket; - - uint8 m_bufferHeader[NN_PACKET_HEADER_LENGTH]; - SBuffer m_buffer; - uint32 m_dataLeft; - - volatile bool m_boIsConnected; - volatile bool m_boIsFailedToConnect; - }; - - class CClient - : public CConnectionBase - , public INotificationNetworkClient - { - public: - typedef std::vector TDNotificationNetworkConnectionCallbacks; - - static CClient* Create(CNotificationNetwork* pNotificationNetwork, const char* address, uint16 port); - static CClient* Create(CNotificationNetwork* pNotificationNetwork); - - private: - CClient(CNotificationNetwork* pNotificationNetwork); - ~CClient(); - - public: - bool Receive() { return CConnectionBase::Receive(m_listeners); } - - void Update(); - - // CConnectionBase - public: - virtual bool OnConnect(bool bConnectionResult); - virtual bool OnDisconnect(); - virtual bool OnMessage(EMessage eMessage, const CChannel& channel); - - // INotificationNetworkClient - public: - bool Connect(const char* address, uint16 port); - - void Release() { delete this; } - - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener); - virtual bool ListenerRemove(INotificationNetworkListener* pListener); - - virtual bool Send(const char* channelName, const void* pBuffer, size_t length); - - virtual bool IsConnected() {return CConnectionBase::GetIsConnectedFlag(); } - virtual bool IsFailedToConnect() const{return CConnectionBase::GetIsFailedToConnectFlag(); } - - virtual bool RegisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback); - virtual bool UnregisterCallbackListener(INotificationNetworkConnectionCallback* pConnectionCallback); - private: - CListeners m_listeners; - - TDNotificationNetworkConnectionCallbacks m_cNotificationNetworkConnectionCallbacks; - CryCriticalSection m_stConnectionCallbacksLock; - }; -} // namespace NotificationNetwork -class CNotificationNetwork - : public INotificationNetwork -{ -private: - class CConnection - : public NotificationNetwork::CConnectionBase - { - public: - CConnection(CNotificationNetwork* pNotificationNetwork, AZSOCKET sock); - virtual ~CConnection(); - - public: - bool IsListening(const NotificationNetwork::CChannel& channel); - - // CConnectionBase - protected: - virtual bool OnMessage(NotificationNetwork::EMessage eMessage, const NotificationNetwork::CChannel& channel); - - private: - std::vector m_listeningChannels; - }; - - class CThread - : public CryThread - { - public: - CThread(); - ~CThread(); - - public: - bool Begin(CNotificationNetwork* pNotificationNetwork); - void End(); - - // CryRunnable - public: - virtual void Run(); - - private: - CNotificationNetwork* m_pNotificationNetwork; - bool m_bRun; - } m_thread; - -public: - static CNotificationNetwork* Create(); - -public: - CNotificationNetwork(); - ~CNotificationNetwork(); - -public: - void ReleaseClients(NotificationNetwork::CClient* pClient); - -private: - void ProcessSockets(); - - // INotificationNetwork -public: - virtual void Release() { delete this; } - - virtual INotificationNetworkClient* CreateClient(); - - virtual INotificationNetworkClient* Connect(const char* address, uint16 port); - - virtual size_t GetConnectionCount(const char* channelName); - - virtual void Update(); - - virtual bool ListenerBind(const char* channelName, INotificationNetworkListener* pListener); - virtual bool ListenerRemove(INotificationNetworkListener* pListener); - - virtual uint32 Send(const char* channelName, const void* pBuffer, size_t length); - -private: - AZSOCKET m_socket; - - std::vector m_connections; - std::vector m_clients; - NotificationNetwork::CListeners m_listeners; - - CryCriticalSection m_clientsCriticalSection; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_NOTIFICATIONNETWORK_H diff --git a/Code/CryEngine/CrySystem/ProfileLogSystem.cpp b/Code/CryEngine/CrySystem/ProfileLogSystem.cpp deleted file mode 100644 index 2a86dfc2ef..0000000000 --- a/Code/CryEngine/CrySystem/ProfileLogSystem.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ProfileLogSystem.h" - -////////////////////////////////////////////////////////////////////////// -// class CLogElement -////////////////////////////////////////////////////////////////////////// - -CLogElement::CLogElement() - : m_pParent (NULL) - , m_time (0) -{ -} - -CLogElement::CLogElement(CLogElement* pParent) - : m_pParent (pParent) - , m_time (0) -{ -} - -CLogElement::CLogElement(CLogElement* pParent, const char* name, const char* message) - : m_pParent (pParent) - , m_strName (name) - , m_strMessage(message) - , m_time (0) -{ -} - -void CLogElement::Flush(stack_string& indent) -{ - if (m_logElements.empty()) - { - CryLog("%s%s [%.3f ms] %s", indent.c_str(), m_strName.c_str(), m_time, m_strMessage.c_str()); - return; - } - - CryLog("%s+%s [%.3f ms] %s", indent.c_str(), m_strName.c_str(), m_time, m_strMessage.c_str()); - - indent += " "; - for (std::list::iterator it = m_logElements.begin(); it != m_logElements.end(); ++it) - { - (*it).Flush(indent); - } - indent.erase(0, 2); - - CryLog("%s-%s", indent.c_str(), m_strName.c_str()); -} - -ILogElement* CLogElement::Log(const char* name, const char* message) -{ - m_logElements.push_back(CLogElement(this)); - m_logElements.back().m_strName = name; - m_logElements.back().m_strMessage = message; - - return &m_logElements.back(); -} - -ILogElement* CLogElement::SetTime(float time) -{ - m_time = time; - - return m_pParent; -} - -void CLogElement::Clear() -{ - m_logElements.resize(0); -} - -////////////////////////////////////////////////////////////////////////// -// class CProfileLogSystem -////////////////////////////////////////////////////////////////////////// - -CProfileLogSystem::CProfileLogSystem() - : m_rootElelent(NULL) - , m_pLastElelent(NULL) -{ -} - -CProfileLogSystem::~CProfileLogSystem() -{ -} - -ILogElement* CProfileLogSystem::Log(const char* name, const char* message) -{ - if (m_pLastElelent) - { - m_pLastElelent = m_pLastElelent->Log(name, message); - } - else - { - m_rootElelent.Clear(); - m_rootElelent.SetName(name); - m_rootElelent.SetMessage(message); - m_pLastElelent = &m_rootElelent; - } - - return m_pLastElelent; -} - -void CProfileLogSystem::SetTime(ILogElement* pElement, float time) -{ - if (pElement == NULL) - { - return; - } - - m_pLastElelent = pElement->SetTime(time); - if (m_pLastElelent) - { - return; - } - - stack_string indent; - m_rootElelent.Flush(indent); - m_rootElelent.Clear(); -} - -void CProfileLogSystem::Release() -{ - delete this; -} diff --git a/Code/CryEngine/CrySystem/ProfileLogSystem.h b/Code/CryEngine/CrySystem/ProfileLogSystem.h deleted file mode 100644 index b54e3067ec..0000000000 --- a/Code/CryEngine/CrySystem/ProfileLogSystem.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Implementation of the IProfileLogSystem interface, which is used to -// save hierarchical log with SHierProfileLogItem - - -#ifndef CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H -#define CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H - -#pragma once - -#include "ProfileLog.h" - -class CLogElement - : public ILogElement -{ -public: - CLogElement(); - CLogElement(CLogElement* pParent); - CLogElement(CLogElement* pParent, const char* name, const char* message); - - virtual ILogElement* Log (const char* name, const char* message); - virtual ILogElement* SetTime (float time); - virtual void Flush (stack_string& indent); - - void Clear (); - - inline void SetName(const char* name) - { - m_strName = name; - } - - inline void SetMessage(const char* message) - { - m_strMessage = message; - } - -private: - string m_strName; - string m_strMessage; - float m_time; // milliSeconds - - CLogElement* m_pParent; - std::list m_logElements; -}; - -class CProfileLogSystem - : public IProfileLogSystem -{ -public: - CProfileLogSystem(); - ~CProfileLogSystem(); - - virtual ILogElement* Log (const char* name, const char* message); - virtual void SetTime (ILogElement* pElement, float time); - virtual void Release (); - -private: - CLogElement m_rootElelent; - ILogElement* m_pLastElelent; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_PROFILELOGSYSTEM_H diff --git a/Code/CryEngine/CrySystem/ResourceManager.cpp b/Code/CryEngine/CrySystem/ResourceManager.cpp index f78538760f..5e9477a99c 100644 --- a/Code/CryEngine/CrySystem/ResourceManager.cpp +++ b/Code/CryEngine/CrySystem/ResourceManager.cpp @@ -699,7 +699,7 @@ void CResourceManager::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_P if (g_cvars.archiveVars.nLoadCache) { //Load the frontend common mode switch pak, this can considerably reduce the time spent switching especially from disc - if (!gEnv->bMultiplayer && LoadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP) == false) + if (LoadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP) == false) { CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "Could not load %s during init. This file can significantly reduce frontend loading times.\n", FRONTEND_COMMON_PAK_FILENAME_SP); } @@ -710,14 +710,7 @@ void CResourceManager::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_P case ESYSTEM_EVENT_LEVEL_LOAD_PREPARE: { - if (!gEnv->bMultiplayer) - { - UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP, FRONTEND_COMMON_LIST_FILENAME "_sp"); - } - else - { - UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_MP, FRONTEND_COMMON_LIST_FILENAME "_mp"); - } + UnloadMenuCommonPak(FRONTEND_COMMON_PAK_FILENAME_SP, FRONTEND_COMMON_LIST_FILENAME "_sp"); m_bLevelTransitioning = !m_sLevelName.empty(); diff --git a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp b/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp deleted file mode 100644 index 9e141cc5a5..0000000000 --- a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.cpp +++ /dev/null @@ -1,787 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" - -#ifdef SOFTCODE_SYSTEM_ENABLED - -#ifndef SOFTCODE_ENABLED -// Even if this module isn't built with SC enabled, if the SC system is enabled we define -// it for this compilation unit to ensure we use the correct versions of the IType* interfaces. - #define SOFTCODE_ENABLED -#endif - -#include "SoftCodeMgr.h" -#include -#include -#include -#include // for function<> in find files - -// This should resolve to "GetTypeLibrary" but we export by ordinal to avoid overheads on 360 -// and keep everything consistent. -static const char* DLL_GETTYPELIBRARY = (LPCSTR)1; - -struct CInstanceData -{ - CInstanceData(void* pInstance, size_t memberCount) - : m_pOldInstance(pInstance) - , m_pNewInstance() - { - m_members.resize(memberCount); - } - - ~CInstanceData() - { - // Delete all members - for (TMemberVec::iterator iter(m_members.begin()); - iter != m_members.end(); - ++iter) - { - // TODO: Safe cross module? Same allocator? Use a Destroy() method? - delete *iter; - } - } - - void* Instance() { return m_pOldInstance; } - - void AddMember(size_t index, IExchangeValue& value) - { - // TODO: Add support for members with same name at different hierarchy levels - assert(m_members[index] == NULL); - assert(index != ~0); - - // Support expansion of m_members during while resolving members - if (index >= m_members.size()) - { - m_members.resize(index + 1); - } - - m_members[index] = value.Clone(); - } - - IExchangeValue* GetMember(size_t index) const - { - assert(index < m_members.size()); - return m_members[index]; - } - - void SetNewInstance(void* pNewInstance) { m_pNewInstance = pNewInstance; } - - void* m_pOldInstance; - void* m_pNewInstance; - - typedef std::vector TMemberVec; - TMemberVec m_members; -}; - - -class CExchanger - : public IExchanger -{ -public: - CExchanger() - : m_pInstanceData() - , m_instanceIndex(~0) - , m_state(eState_ResolvingMembers) - {} - - virtual ~CExchanger() - { - DestroyInstanceData(); - } - - virtual bool IsLoading() const { return m_state >= eState_WritingNewMembers; } - virtual size_t InstanceCount() const { return m_instances.size(); } - - virtual bool BeginInstance(void* pInstance) - { - if (IsLoading()) - { - if (++m_instanceIndex < m_instances.size()) - { - m_pInstanceData = m_instances[m_instanceIndex]; - m_pInstanceData->SetNewInstance(pInstance); - } - else - { - m_pInstanceData = NULL; - } - } - else // Reading/resolving members - { - m_instanceIndex = m_instances.size(); - m_pInstanceData = new CInstanceData(pInstance, m_memberMap.size()); - m_instances.push_back(m_pInstanceData); - } - - return m_pInstanceData != NULL; - } - - virtual bool SetValue(const char* name, IExchangeValue& value) - { - assert(!IsLoading()); - - const size_t index = FindMemberIndex(name); - const bool consumingValue = index != ~0; - - if (consumingValue) - { - m_pInstanceData->AddMember(index, value); - } - - return consumingValue; - } - - virtual IExchangeValue* GetValue(const char* name, void* pTarget, size_t targetSize) - { - assert(IsLoading()); - - const size_t index = FindMemberIndex(name); - - // If member resolved (may not be if restoring to old instances) - if (index != ~0) - { - // If member data available (may not be if member is new) - if (IExchangeValue* pValue = m_pInstanceData->GetMember(index)) - { - if (pValue->GetSizeOf() == targetSize) - { - return pValue; - } - else // Member size mismatch - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - "SoftCode: Member %s of instance %p has changed size (old: %d new: %d), setting to default value.", - name, m_pInstanceData->Instance(), (int)pValue->GetSizeOf(), (int)targetSize); - } - } - else // Member unknown - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - "SoftCode: Member %s (of instance %p) appears to be new.", - name, m_pInstanceData->Instance()); - - // TODO: Could attempt to validate against a known wipe pattern ie. 0xfefefefe - // This could catch most uninitialized variables... - - if (targetSize <= sizeof(void*)) - { - switch (targetSize) - { - case 1: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %d", *reinterpret_cast(pTarget)); - break; - case 2: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %04x", *reinterpret_cast(pTarget)); - break; - case 4: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %08x", *reinterpret_cast(pTarget)); - break; - case 8: - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "\tLeaving as: %llx", *reinterpret_cast(pTarget)); - break; - } - } - } - } - - // Indicate value should be default constructed - return NULL; - } - - // Used once required members have been established, members not already - // encountered will be ignored. - void LockMemberSet() - { - assert(m_state == eState_ResolvingMembers); - - DestroyInstanceData(); - m_state = eState_ReadingOldMembers; - } - - // Rewinds instance data and prepare for loading - void RewindForLoading() - { - assert(m_state == eState_ReadingOldMembers); - - m_pInstanceData = NULL; - m_instanceIndex = ~0; - m_state = eState_WritingNewMembers; - } - - // Rewinds instance data to prepare to restore old members (UNDO) - void RewindForRestore() - { - assert(m_state == eState_WritingNewMembers); - - m_pInstanceData = NULL; - m_instanceIndex = ~0; - m_state = eState_RestoringOldMembers; - } - - void NotifyListenerOfReplacements(ISoftCodeListener* pListener) - { - for (TInstanceVec::const_iterator iter(m_instances.begin()); iter != m_instances.end(); ++iter) - { - CInstanceData* pInstanceData = *iter; - pListener->InstanceReplaced(pInstanceData->m_pOldInstance, pInstanceData->m_pNewInstance); - } - } - -private: - void DestroyInstanceData() - { - m_pInstanceData = NULL; - m_instanceIndex = ~0; - - for (TInstanceVec::iterator iter(m_instances.begin()); iter != m_instances.end(); ++iter) - { - delete *iter; - } - - m_instances.resize(0); - } - - inline size_t FindMemberIndex(const string& memberName) - { - size_t index = ~0; - - // If needed members have been resolved - if (m_state != eState_ResolvingMembers) - { - TMemberMap::const_iterator iter(m_memberMap.find(memberName)); - if (iter != m_memberMap.end()) - { - index = iter->second; - } - } - else // Add this member to the map with a new index - { - // Ensure there's no member name duplicates - assert(m_memberMap.find(memberName) == m_memberMap.end()); - - // A new entry - index = m_memberMap.size(); - size_t& newIndex = m_memberMap[memberName]; - newIndex = index; - } - - return index; - } - -private: - CInstanceData* m_pInstanceData; - size_t m_instanceIndex; - - typedef std::vector TInstanceVec; - TInstanceVec m_instances; - - // Maps instance members to offsets in instance member vectors - typedef std::map TMemberMap; - TMemberMap m_memberMap; - - enum EState - { - eState_ResolvingMembers = 0, // Record new member names as found - eState_ReadingOldMembers, // Scrape requested member data from old instances - eState_WritingNewMembers, // Write old member data to new instances - eState_RestoringOldMembers, // Restore scraped values to old instances (UNDO) - }; - - EState m_state; -}; - - -// ---- - -DynamicTypeLibrary::DynamicTypeLibrary(const char* name) - : m_name(name) - , m_listeners(1) -{} - -const char* DynamicTypeLibrary::GetName() -{ - return m_name; -} - -void* DynamicTypeLibrary::CreateInstanceVoid(const char* typeName) -{ - TTypeMap::const_iterator typeIter(m_types.find(typeName)); - if (typeIter != m_types.end()) - { - ITypeRegistrar* pRegistrar = typeIter->second; - return pRegistrar->CreateInstance(); - } - - return NULL; -} - -void DynamicTypeLibrary::SetOverride(ITypeLibrary* /*pOverrideLib*/) -{ - CryFatalError("Unsupported: Attempting to SetOverride on a DynamicTypeLibrary!"); -} - -size_t DynamicTypeLibrary::GetTypes([[maybe_unused]] ITypeRegistrar** ppRegistrar, [[maybe_unused]] size_t& count) const -{ - CryFatalError("Unsupported: Attempting to GetTypes on a DynamicTypeLibrary!"); - return 0; -} - -void DynamicTypeLibrary::AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) -{ - // This DynamicTypeLibrary could have been created by this listener request - // So ensure we have a name...! - if (!m_name) - { - m_name = libraryName; - } - - m_listeners.Add(pListener, listenerName); -} - -void DynamicTypeLibrary::RemoveListener(ISoftCodeListener* pListener) -{ - m_listeners.Remove(pListener); -} - -void DynamicTypeLibrary::IntegrateLibrary(ITypeLibrary* pLib, bool isDefault) -{ - typedef std::vector TTypeVec; - - // Resolve our name if we haven't already - if (!m_name) - { - m_name = pLib->GetName(); - } - - // Override the new lib immediately - pLib->SetOverride(this); - - // Query the new library for its types - size_t typeCount = 0; - pLib->GetTypes(NULL, typeCount); - if (typeCount > 0) - { - TTypeVec typeVec; - typeVec.resize(typeCount); - pLib->GetTypes(&(typeVec.front()), typeCount); - - if (!isDefault) - { - CryLogAlways("SoftCode: Integrating %d new types defined in %s...", (int)typeCount, m_name); - } - - // Attempt to integrate each type found - for (TTypeVec::iterator typeIter(typeVec.begin()); typeIter != typeVec.end(); ++typeIter) - { - IntegrateType(*typeIter, isDefault); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: New %s library has no registered types. Nothing to integrate.", pLib->GetName()); - } -} - -ITypeRegistrar* DynamicTypeLibrary::FindTypeForInstance(void* pInstance) const -{ - for (TTypeMap::const_iterator iter(m_types.begin()); iter != m_types.end(); ++iter) - { - ITypeRegistrar* pType = iter->second; - if (pType->HasInstance(pInstance)) - { - return pType; - } - } - - return NULL; -} - -void DynamicTypeLibrary::IntegrateType(ITypeRegistrar* pType, bool isDefault) -{ - const char* typeName = pType->GetName(); - - // If there's an existing registrar - ITypeRegistrar* pExistingType = m_types[typeName]; - assert(pExistingType != pType); // Sanity check - - // If the new type is the default (built-in) type but it's already been overridden - if (isDefault && pExistingType) - { - return; // Nothing to do - } - // TODO: Inform listeners that there's a new library available - // and ask if we should use it immediately or defer - - CExchanger exchanger; - - // If the type can be safely created, visited and destroyed - if (EvaluateType(pType, exchanger)) - { - // Override the type - m_types[typeName] = pType; - - if (!isDefault) - { - CryLogAlways("SoftCode: Overridden %s in library %s", typeName, m_name); - } - - const size_t instanceCount = (pExistingType) ? pExistingType->InstanceCount() : 0; - - // If there are any existing instances - if (instanceCount > 0) - { - CryLogAlways("SoftCode: Attempting to exchange %d %s instances to the new version...", (int)instanceCount, typeName); - - // Read instance members for type (removes data for resolved members) - if (pExistingType->ExchangeInstances(exchanger)) - { - exchanger.RewindForLoading(); - - // Write instance members for type - if (pType->ExchangeInstances(exchanger)) - { - // Success! Tell the listeners to fix up their pointers - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - exchanger.NotifyListenerOfReplacements(*notifier); - } - - CryLogAlways("SoftCode: %d %s instances successfully overridden to latest!", (int)instanceCount, typeName); - - // Clean up old instances - if (!pExistingType->DestroyInstances()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: Failed to destroy old instances of type %s - leak probable.", typeName); - } - } - else // Failed to create & write into new instances - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to create and write into new instances of %s. Attempting restore of old instances...", typeName); - if (!pType->DestroyInstances()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, "SoftCode: Failed to destroy new instances of type %s - leak probable.", typeName); - } - - // Restore the original type library as the active one - m_types[typeName] = pExistingType; - - // Attempt to restore the old instances with their original data - exchanger.RewindForRestore(); - if (pExistingType->ExchangeInstances(exchanger)) - { - CryLogAlways("SoftCode: Type %s in library %s successfully restored to previous revision!", typeName, m_name); - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Restore of old %s instances failed. State now undefined!", typeName); - } - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to read members on %s", typeName); - } - } - } -} - -bool DynamicTypeLibrary::EvaluateType(ITypeRegistrar* pType, CExchanger& exchanger) -{ - // Try a full object life-time with a single instance of the - // new type before attempting a member exchange. This also allow the - // exchanger to determine the required members to be removed from the - // old instances. - bool testPassed = false; - - // Create a single test instance of the type - if (pType->CreateInstance()) - { - // Read the instance members (also prepares the exchanger member set) - if (pType->ExchangeInstances(exchanger)) - { - // Destroy the old instance - if (pType->DestroyInstances()) - { - // Indicate required members are now resolved - exchanger.LockMemberSet(); - testPassed = true; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to destroy test instance of type: %s. New type will be skipped.", pType->GetName()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to read members in test instance of type: %s. New type will be skipped.", pType->GetName()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to create test instance of type: %s. New type will be skipped.", pType->GetName()); - } - - return testPassed; -} - -// ---- - -// The export we expect to find in the SoftCode modules -typedef ITypeLibrary* (__stdcall * TGetTypeLibraryFcn)(); - -static void SoftCode_UpdateCmd([[maybe_unused]] IConsoleCmdArgs* pArgs) -{ - gEnv->pSoftCodeMgr->LoadNewModules(); -} - -static int g_autoUpdatePeriod = 0; - -SoftCodeMgr::SoftCodeMgr() -{ - REGISTER_CVAR2("sc_autoupdate", &g_autoUpdatePeriod, 5, VF_CHEAT, "Set the auto-update poll period for new SoftCode modules. Set to zero to disable"); - REGISTER_COMMAND("sc_update", reinterpret_cast(&SoftCode_UpdateCmd), VF_CHEAT, "Loads any new SoftCode modules"); - - // Clear out any old modules - { - typedef std::vector TStringVec; - TStringVec filePaths; - - if (FindSoftCodeFiles("*", filePaths) > 0) - { - for (TStringVec::const_iterator iter(filePaths.begin()); iter != filePaths.end(); ++iter) - { - if (!DeleteFile(iter->c_str())) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "SoftCode: Failed to clean %s", iter->c_str()); - } - } - } - } -} - -SoftCodeMgr::~SoftCodeMgr() -{ - if (gEnv->pConsole) - { - gEnv->pConsole->RemoveCommand("sc_update"); - gEnv->pConsole->UnregisterVariable("sc_autoupdate"); - } -} - -// Used to register built-in libraries on first use -void SoftCodeMgr::RegisterLibrary(ITypeLibrary* pDefaultLib) -{ - DynamicTypeLibrary& typeLib = m_libraryMap[pDefaultLib->GetName()]; - typeLib.IntegrateLibrary(pDefaultLib, true); -} - -// Look for new SoftCode modules and load them, adding their types to the registry -void SoftCodeMgr::LoadNewModules() -{ - typedef std::vector TStringVec; - typedef TStringVec::const_iterator TModuleIter; - TStringVec modulePaths; - - // Find modules - FindSoftCodeFiles("*.dll", modulePaths); - - for (TModuleIter libIter(modulePaths.begin()); libIter != modulePaths.end(); ++libIter) - { - const char* moduleName = libIter->c_str(); - LoadModule(moduleName); - } -} - -void SoftCodeMgr::AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName) -{ - // Find an existing lib or create a new one to add the listener to - DynamicTypeLibrary& lib = m_libraryMap[libraryName]; - lib.AddListener(libraryName, pListener, listenerName); -} - -void SoftCodeMgr::RemoveListener(const char* libraryName, ISoftCodeListener* pListener) -{ - TLibMap::iterator iter(m_libraryMap.find(libraryName)); - - if (iter != m_libraryMap.end()) - { - iter->second.RemoveListener(pListener); - } -} - -// To be called regularly to poll for library updates -void SoftCodeMgr::PollForNewModules() -{ - if (g_autoUpdatePeriod > 0) - { - const CTimeValue frameStartTime(gEnv->pTimer->GetFrameStartTime(ITimer::ETIMER_UI)); - if (m_nextAutoCheckTime <= frameStartTime) - { - m_nextAutoCheckTime.SetSeconds((int64)g_autoUpdatePeriod); - m_nextAutoCheckTime += frameStartTime; - - // Attempt to find and load any new modules - LoadNewModules(); - } - } -} - -namespace -{ - // Util - class InstanceFixup - : public ISoftCodeListener - { - public: - InstanceFixup(void* pOldInstance) - : m_pOldInstance(pOldInstance) - , m_pNewInstance() {} - - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) - { - if (m_pOldInstance == pOldInstance) - { - m_pNewInstance = pNewInstance; - } - } - - void* NewInstance() const { return m_pNewInstance; } - - private: - void* m_pOldInstance; - void* m_pNewInstance; - }; -} - -// Stops thread execution until a new SoftCode module is available -void* SoftCodeMgr::WaitForUpdate(void* pInstance) -{ - DynamicTypeLibrary* pOwningLib = NULL; - ITypeRegistrar* pOldType = NULL; - - // Find existing instance - for (TLibMap::iterator libIter(m_libraryMap.begin()); libIter != m_libraryMap.end(); ++libIter) - { - DynamicTypeLibrary& lib = libIter->second; - if (ITypeRegistrar* pType = lib.FindTypeForInstance(pInstance)) - { - pOwningLib = &lib; - pOldType = pType; - break; - } - } - - if (!pOwningLib) - { - CryFatalError("SoftCode: Attempting to wait for update on an unknown instance!"); - return NULL; - } - - InstanceFixup instanceFixup(pInstance); - pOwningLib->AddListener(pOwningLib->GetName(), &instanceFixup, "InstanceFixup"); - - while (true) - { - // Find and load new modules - LoadNewModules(); - - // Got a new instance? - if (instanceFixup.NewInstance()) - { - break; - } - - // Wait for a new module - CryLogAlways("SoftCode: Pausing execution until class %s in %s library is updated...", pOldType->GetName(), pOwningLib->GetName()); - __debugbreak(); // Stopped here? Check your log! - } - - pOwningLib->RemoveListener(&instanceFixup); - - return instanceFixup.NewInstance(); -} - -bool SoftCodeMgr::LoadModule(const char* moduleName) -{ - bool success = false; - - // If module not yet loaded - if (m_loadedSet.find(moduleName) == m_loadedSet.end()) - { - m_loadedSet.insert(moduleName); - - CryLogAlways("SoftCode: Found new module %s, attempting to load...", moduleName); - - HMODULE hModule = CryLoadLibrary(moduleName); - - if (hModule) - { - TGetTypeLibraryFcn pGetTypeLibraryFcn = reinterpret_cast(GetProcAddress(hModule, DLL_GETTYPELIBRARY)); - if (pGetTypeLibraryFcn) - { - // Add to list of loaded libs & override any earlier TypeLibraries already registered - ITypeLibrary* pTypeLibrary = pGetTypeLibraryFcn(); - if (pTypeLibrary) - { - const char* libraryName = pTypeLibrary->GetName(); - m_libraryMap[libraryName].IntegrateLibrary(pTypeLibrary, false); - - CryLogAlways("SoftCode: Loaded new type library \"%s\" from module %s.", libraryName, moduleName); - success = true; - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Failed to resolve GetTypeLibrary() export in: %s (error: %x)", moduleName, GetLastError()); - } - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, "Failed to load: %s (error: %x)", moduleName, GetLastError()); - } - } - - return success; -} - -size_t SoftCodeMgr::FindSoftCodeFiles(const string& searchName, std::vector& foundPaths) const -{ - foundPaths.clear(); - - stack_string scSoftCodeDir; - - TCHAR modulePath[MAX_PATH]; - GetModuleFileName(NULL, modulePath, sizeof(modulePath)); - scSoftCodeDir = PathUtil::GetParentDirectory(modulePath); - scSoftCodeDir += "\\SoftCode\\"; - - - gEnv->pFileIO->FindFiles(scSoftCodeDir.c_str(), searchName, [&](const char* filePath) -> bool - { - if (!gEnv->pFileIO->IsDirectory(filePath) && !gEnv->pFileIO->IsReadOnly(filePath)) - { - foundPaths.push_back(filePath); - } - - // Keep asking for more files, no early out - return true; - }); - - // Sort the paths into name order - std::sort(foundPaths.begin(), foundPaths.end()); - - return foundPaths.size(); -} - -#endif // SOFTCODE_ENABLED diff --git a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h b/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h deleted file mode 100644 index f3f1b931a5..0000000000 --- a/Code/CryEngine/CrySystem/SoftCode/SoftCodeMgr.h +++ /dev/null @@ -1,111 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H -#define CRYINCLUDE_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H -#pragma once - -#include - -#include "ISoftCodeMgr.h" - -struct ITypeLibrary; -struct ITypeRegistrar; -class CExchanger; - -// Internal: Performs the dynamic type management needed for SoftCoding -class DynamicTypeLibrary - : public ITypeLibrary -{ -public: - DynamicTypeLibrary(const char* name = NULL); - - // ITypeLibrary impl. - virtual const char* GetName(); - virtual void* CreateInstanceVoid(const char* typeName); - virtual void SetOverride(ITypeLibrary* pOverrideLib); - virtual size_t GetTypes(ITypeRegistrar** ppRegistrar, size_t& count) const; - - void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName); - void RemoveListener(ISoftCodeListener* pListener); - - // Attempts to add the library types the active set - void IntegrateLibrary(ITypeLibrary* pLib, bool isDefault); - - ITypeRegistrar* FindTypeForInstance(void* pInstance) const; - -private: - // Attempts to add the type the active set - void IntegrateType(ITypeRegistrar* pType, bool isDefault); - // Ensure the type can be safely created, visited, destroyed and prep exchanger - bool EvaluateType(ITypeRegistrar* pType, CExchanger& exchanger); - -private: - typedef std::vector TLibVec; - typedef std::map TTypeMap; - typedef CListenerSet TListeners; - - // The current set of active types - std::map m_types; - // Current set of loaded libraries - TLibVec m_history; - // Set of listeners to SC changes - TListeners m_listeners; - - const char* m_name; // Supplied by the first real library that registers -}; - - -// Implements the global singleton responsible for SoftCode management -class SoftCodeMgr - : public ISoftCodeMgr -{ -public: - SoftCodeMgr(); - virtual ~SoftCodeMgr(); - - // Used to register built-in libraries on first use - virtual void RegisterLibrary(ITypeLibrary* pLib); - - // Look for new SoftCode modules and load them, adding their types to the registry - virtual void LoadNewModules(); - - virtual void AddListener(const char* libraryName, ISoftCodeListener* pListener, const char* listenerName); - virtual void RemoveListener(const char* libraryName, ISoftCodeListener* pListener); - - // To be called regularly to poll for library updates - virtual void PollForNewModules(); - - // Stops thread execution until a new SoftCode module is available - virtual void* WaitForUpdate(void* pInstance); - -private: - bool LoadModule(const char* moduleName); - size_t FindSoftCodeFiles(const string& searchName, std::vector& foundPaths) const; - -private: - typedef std::map TLibMap; - typedef std::set TLoadedLibSet; - - // Records the history for each TypeLibrary keyed by library name - TLibMap m_libraryMap; - - // Records the library files already loaded - TLoadedLibSet m_loadedSet; - - // Used to determine when the next auto-update will occur - CTimeValue m_nextAutoCheckTime; -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_SOFTCODE_SOFTCODEMGR_H diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index 8a8cf14d91..9016ea99f1 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -124,8 +124,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include #include -#include -#include #include #include @@ -133,8 +131,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include "XConsole.h" #include "Log.h" -#include "NotificationNetwork.h" -#include "ProfileLog.h" #include "XML/xml.h" #include "XML/ReadWriteXMLSink.h" @@ -148,7 +144,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include "ServerThrottle.h" #include "ResourceManager.h" #include "HMDBus.h" -#include #include "IZLibCompressor.h" #include "IZlibDecompressor.h" @@ -267,22 +262,6 @@ namespace } #endif -#if defined(CVARS_WHITELIST) -struct SCVarsWhitelistConfigSink - : public ILoadConfigurationEntrySink -{ - virtual void OnLoadConfigurationEntry(const char* szKey, const char* szValue, const char* szGroup) - { - ICVarsWhitelist* pCVarsWhitelist = gEnv->pSystem->GetCVarsWhiteList(); - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(szKey, false) : true; - if (whitelisted) - { - gEnv->pConsole->LoadConfigVar(szKey, szValue); - } - } -} g_CVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) - ///////////////////////////////////////////////////////////////////////////////// // System Implementation. ////////////////////////////////////////////////////////////////////////// @@ -322,27 +301,13 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_env.pSystem = this; m_env.pTimer = &m_Time; m_env.pNameTable = &m_nameTable; - m_env.bServer = false; - m_env.bMultiplayer = false; - m_env.bHostMigrating = false; m_env.bIgnoreAllAsserts = false; m_env.bNoAssertDialog = false; - m_env.bTesting = false; m_env.pSharedEnvironment = pSharedEnvironment; - - m_env.SetFMVIsPlaying(false); - m_env.SetCutsceneIsPlaying(false); - - m_env.szDebugStatus[0] = '\0'; - -#if !defined(CONSOLE) - m_env.SetIsClient(false); -#endif ////////////////////////////////////////////////////////////////////////// m_pStreamEngine = NULL; - m_PhysThread = 0; m_pIFont = NULL; m_pIFontUi = NULL; @@ -370,7 +335,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pILZ4Decompressor = NULL; m_pIZStdDecompressor = nullptr; m_pLocalizationManager = NULL; - m_sys_physics_CPU = 0; #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_2 #include AZ_RESTRICTED_FILE(System_cpp) @@ -378,15 +342,9 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_sys_min_step = 0; m_sys_max_step = 0; - m_pNotificationNetwork = NULL; - m_cvAIUpdate = NULL; m_pUserCallback = NULL; -#if defined(CVARS_WHITELIST) - m_pCVarsWhitelist = NULL; - m_pCVarsWhitelistConfigSink = &g_CVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) m_sys_memory_debug = NULL; m_sysWarnings = NULL; m_sysKeyboard = NULL; @@ -409,13 +367,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_bNoCrashDialog = false; m_bNoErrorReportWindow = false; -#ifndef _RELEASE - m_checkpointLoadCount = 0; - m_loadOrigin = eLLO_Unknown; - m_hasJustResumed = false; - m_expectingMapCommand = false; -#endif - m_pCVarQuit = NULL; m_bForceNonDevMode = false; @@ -429,13 +380,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_nServerConfigSpec = CONFIG_VERYHIGH_SPEC; m_nMaxConfigSpec = CONFIG_VERYHIGH_SPEC; - //m_hPhysicsThread = INVALID_HANDLE_VALUE; - //m_hPhysicsActive = INVALID_HANDLE_VALUE; - //m_bStopPhysics = 0; - //m_bPhysicsActive = 0; - - m_pProgressListener = 0; - m_bPaused = false; m_bNoUpdate = false; m_nUpdateCounter = 0; @@ -444,12 +388,9 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pXMLUtils = new CXmlUtils(this); m_pMemoryManager = CryGetIMemoryManager(); - m_pThreadTaskManager = new CThreadTaskManager; m_pResourceManager = new CResourceManager; m_pTextModeConsole = NULL; - InitThreadSystem(); - g_pPakHeap = new CMTSafeHeap; if (!AZ::AllocatorInstance::IsReady()) @@ -464,7 +405,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) AZ::Debug::Trace::Instance().Init(); } - m_UpdateTimesIdx = 0U; m_bNeedDoWorkDuringOcclusionChecks = false; m_eRuntimeState = ESYSTEM_EVENT_LEVEL_UNLOAD; @@ -478,15 +418,12 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) #endif m_ConfigPlatform = CONFIG_INVALID_PLATFORM; - - AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusConnect(); } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// CSystem::~CSystem() { - AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusDisconnect(); ShutDown(); #if AZ_LEGACY_CRYSYSTEM_TRAIT_USE_MESSAGE_HANDLER @@ -496,16 +433,8 @@ CSystem::~CSystem() CRY_ASSERT(m_windowMessageHandlers.empty() && "There exists a dangling window message handler somewhere"); SAFE_DELETE(m_pXMLUtils); - SAFE_DELETE(m_pThreadTaskManager); SAFE_DELETE(m_pResourceManager); SAFE_DELETE(m_pSystemEventDispatcher); - // SAFE_DELETE(m_pMemoryManager); - - if (gEnv && gEnv->pThreadManager) - { - gEnv->pThreadManager->UnRegisterThirdPartyThread("Main"); - } - ShutDownThreadSystem(); SAFE_DELETE(g_pPakHeap); @@ -617,8 +546,6 @@ void CSystem::ShutDown() SAFE_DELETE(m_pTextModeConsole); - KillPhysicsThread(); - if (m_sys_firstlaunch) { m_sys_firstlaunch->Set("0"); @@ -664,8 +591,6 @@ void CSystem::ShutDown() gEnv->pLyShine = nullptr; } - SAFE_DELETE(m_env.pResourceCompilerHelper); - SAFE_RELEASE(m_env.pMovieSystem); SAFE_RELEASE(m_env.pLyShine); SAFE_RELEASE(m_env.pCryFont); @@ -706,7 +631,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_sys_GraphicsQuality); SAFE_RELEASE(m_sys_firstlaunch); SAFE_RELEASE(m_sys_enable_budgetmonitoring); - SAFE_RELEASE(m_sys_physics_CPU); #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_3 @@ -716,9 +640,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_sys_min_step); SAFE_RELEASE(m_sys_max_step); - SAFE_RELEASE(m_pNotificationNetwork); - - SAFE_DELETE(m_env.pSoftCodeMgr); SAFE_DELETE(m_pDefaultValidator); m_pValidator = nullptr; @@ -743,7 +664,6 @@ void CSystem::ShutDown() SAFE_RELEASE(m_env.pConsole); // Log must be last thing released. - SAFE_RELEASE(m_env.pProfileLogSystem); if (m_env.pLog) { m_env.pLog->FlushAndClose(); @@ -752,10 +672,6 @@ void CSystem::ShutDown() ShutdownFileSystem(); -#if defined(MAP_LOADING_SLICING) - delete gEnv->pSystemScheduler; -#endif // defined(MAP_LOADING_SLICING) - ShutdownModuleLibraries(); EBUS_EVENT(CrySystemEventBus, OnCrySystemPostShutdown); @@ -841,273 +757,6 @@ ISystem* CSystem::GetCrySystem() return this; } -////////////////////////////////////////////////////////////////////////// -// Physics thread task -////////////////////////////////////////////////////////////////////////// -class CPhysicsThreadTask - : public IThreadTask -{ -public: - - CPhysicsThreadTask() - { - m_bStopRequested = 0; - m_bIsActive = 0; - m_stepRequested = 0; - m_bProcessing = 0; - m_doZeroStep = 0; - m_lastStepTimeTaken = 0U; - m_lastWaitTimeTaken = 0U; - } - - ////////////////////////////////////////////////////////////////////////// - // IThreadTask implementation. - ////////////////////////////////////////////////////////////////////////// - virtual void OnUpdate() - { - Run(); - // At the end.. delete the task - delete this; - } - virtual void Stop() - { - Cancel(); - } - virtual SThreadTaskInfo* GetTaskInfo() { return &m_TaskInfo; } - ////////////////////////////////////////////////////////////////////////// - - virtual void Run() - { - m_bStopRequested = 0; - m_bIsActive = 1; - - float step, timeTaken, kSlowdown = 1.0f; - int nSlowFrames = 0; - int64 timeStart; -#ifdef ENABLE_LW_PROFILERS - LARGE_INTEGER stepStart, stepEnd; -#endif - LARGE_INTEGER waitStart, waitEnd; - MarkThisThreadForDebugging("Physics"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_5 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - while (true) - { - QueryPerformanceCounter(&waitStart); - m_FrameEvent.Wait(); // Wait untill new frame - QueryPerformanceCounter(&waitEnd); - m_lastWaitTimeTaken = waitEnd.QuadPart - waitStart.QuadPart; - - if (m_bStopRequested) - { - UnmarkThisThreadFromDebugging(); - return; - } - bool stepped = false; -#ifdef ENABLE_LW_PROFILERS - QueryPerformanceCounter(&stepStart); -#endif - while ((step = m_stepRequested) > 0 || m_doZeroStep) - { - stepped = true; - m_stepRequested = 0; - m_bProcessing = 1; - m_doZeroStep = 0; - - if (kSlowdown != 1.0f) - { - step = max(1, FtoI(step * kSlowdown * 50 - 0.5f)) * 0.02f; - } - timeStart = CryGetTicks(); - timeTaken = gEnv->pTimer->TicksToSeconds(CryGetTicks() - timeStart); - if (timeTaken > step * 0.9f) - { - if (++nSlowFrames > 5) - { - kSlowdown = step * 0.9f / timeTaken; - } - } - else - { - kSlowdown = 1.0f, nSlowFrames = 0; - } - m_bProcessing = 0; - //int timeSleep = (int)((m_timeTarget-gEnv->pTimer->GetAsyncTime()).GetMilliSeconds()*0.9f); - //Sleep(max(0,timeSleep)); - } - if (!stepped) - { - Sleep(0); - } - m_FrameDone.Set(); -#ifdef ENABLE_LW_PROFILERS - QueryPerformanceCounter(&stepEnd); - m_lastStepTimeTaken = stepEnd.QuadPart - stepStart.QuadPart; -#endif - } - } - virtual void Cancel() - { - Pause(); - m_bStopRequested = 1; - m_FrameEvent.Set(); - m_bIsActive = 0; - } - - int Pause() - { - if (m_bIsActive) - { - AZ_PROFILE_FUNCTION_STALL(AZ::Debug::ProfileCategory::System); - m_bIsActive = 0; - while (m_bProcessing) - { - ; - } - return 1; - } - return 0; - } - int Resume() - { - if (!m_bIsActive) - { - m_bIsActive = 1; - return 1; - } - return 0; - } - int IsActive() { return m_bIsActive; } - int RequestStep(float dt) - { - if (m_bIsActive && dt > FLT_EPSILON) - { - m_stepRequested += dt; - if (dt <= 0.0f) - { - m_doZeroStep = 1; - } - m_FrameEvent.Set(); - } - - return m_bProcessing; - } - float GetRequestedStep() { return m_stepRequested; } - - uint64 LastStepTaken() const - { - return m_lastStepTimeTaken; - } - - uint64 LastWaitTime() const - { - return m_lastWaitTimeTaken; - } - - void EnsureStepDone() - { - FRAME_PROFILER("SysUpdate:PhysicsEnsureDone", gEnv->pSystem, PROFILE_SYSTEM); - if (m_bIsActive) - { - while (m_stepRequested > 0.0f || m_bProcessing) - { - m_FrameDone.Wait(); - } - } - } - -protected: - - volatile int m_bStopRequested; - volatile int m_bIsActive; - volatile float m_stepRequested; - volatile int m_bProcessing; - volatile int m_doZeroStep; - volatile uint64 m_lastStepTimeTaken; - volatile uint64 m_lastWaitTimeTaken; - - CryEvent m_FrameEvent; - CryEvent m_FrameDone; - - SThreadTaskInfo m_TaskInfo; -}; - -void CSystem::CreatePhysicsThread() -{ - if (!m_PhysThread) - { - ////////////////////////////////////////////////////////////////////////// - SThreadTaskParams threadParams; - threadParams.name = "Physics"; - threadParams.nFlags = THREAD_TASK_BLOCKING; - threadParams.nStackSizeKB = PHYSICS_STACK_SIZE >> 10; -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_6 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif - - { - m_PhysThread = new CPhysicsThreadTask; - GetIThreadTaskManager()->RegisterTask(m_PhysThread, threadParams); - } - } - -} - -void CSystem::KillPhysicsThread() -{ - if (m_PhysThread) - { - GetIThreadTaskManager()->UnregisterTask(m_PhysThread); - m_PhysThread = 0; - } -} - -/////////////////////////////////////////////////////////////////////////// -// AzFramework::Terrain::TerrainDataNotificationBus START -void CSystem::OnTerrainDataCreateBegin() -{ - KillPhysicsThread(); -} - -void CSystem::OnTerrainDataDestroyBegin() -{ - OnTerrainDataCreateBegin(); -} - -// AzFramework::Terrain::TerrainDataNotificationBus END -/////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -int CSystem::SetThreadState(ESubsystem subsys, bool bActive) -{ - switch (subsys) - { - case ESubsys_Physics: - { - if (m_PhysThread) - { - return bActive ? ((CPhysicsThreadTask*)m_PhysThread)->Resume() : ((CPhysicsThreadTask*)m_PhysThread)->Pause(); - } - } - break; - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::SleepIfInactive() -{ - // ProcessSleep() - if (m_bDedicatedServer || m_bEditor || gEnv->bMultiplayer) - { - return; - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::SleepIfNeeded() { @@ -1180,11 +829,7 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) // do the dedicated sleep earlier than the frame profiler to avoid having it counted if (gEnv->IsDedicated()) { -#if defined(MAP_LOADING_SLICING) - gEnv->pSystemScheduler->SchedulingSleepIfNeeded(); -#else SleepIfNeeded(); -#endif // defined(MAP_LOADING_SLICING) } #endif //EXCLUDE_UPDATE_ON_CONSOLE @@ -1199,9 +844,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) m_nUpdateCounter++; #ifndef EXCLUDE_UPDATE_ON_CONSOLE - // Check if game needs to be sleeping when not active. - SleepIfInactive(); - if (m_pUserCallback) { m_pUserCallback->OnUpdate(); @@ -1216,7 +858,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) prev_sys_float_exceptions = g_cvars.sys_float_exceptions; EnableFloatExceptions(g_cvars.sys_float_exceptions); - UpdateFPExceptionsMaskForThreads(); } #endif //EXCLUDE_UPDATE_ON_CONSOLE ////////////////////////////////////////////////////////////////////////// @@ -1263,13 +904,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } #endif //PROFILE_WITH_VTUNE -#ifdef SOFTCODE_SYSTEM_ENABLED - if (m_env.pSoftCodeMgr) - { - m_env.pSoftCodeMgr->PollForNewModules(); - } -#endif - if (m_pStreamEngine) { FRAME_PROFILER("StreamEngine::Update()", this, PROFILE_SYSTEM); @@ -1290,7 +924,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) if (m_sysNoUpdate && m_sysNoUpdate->GetIVal()) { bNoUpdate = true; - updateFlags = ESYSUPDATE_IGNORE_PHYSICS; } m_bNoUpdate = bNoUpdate; @@ -1373,16 +1006,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) return false; } -#ifndef EXCLUDE_UPDATE_ON_CONSOLE - - ////////////////////////////////////////////////////////////////////// - //update notification network system - if (m_pNotificationNetwork) - { - FRAME_PROFILER("SysUpdate:NotificationNetwork", this, PROFILE_SYSTEM); - m_pNotificationNetwork->Update(); - } -#endif //EXCLUDE_UPDATE_ON_CONSOLE ////////////////////////////////////////////////////////////////////// //update sound system Part 1 if in Editor / in Game Mode Viewsystem updates the Listeners if (!m_env.IsEditorGameMode()) @@ -1401,15 +1024,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } } - ////////////////////////////////////////////////////////////////////////// - // Update Threads Task Manager. - ////////////////////////////////////////////////////////////////////////// - if (m_pThreadTaskManager) - { - FRAME_PROFILER("SysUpdate:ThreadTaskManager", this, PROFILE_SYSTEM); - m_pThreadTaskManager->OnUpdate(); - } - ////////////////////////////////////////////////////////////////////////// // Update Resource Manager. ////////////////////////////////////////////////////////////////////////// @@ -1418,77 +1032,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) m_pResourceManager->Update(); } - ////////////////////////////////////////////////////////////////////// - // update physic system - //static float time_zero = 0; - if (m_sys_physics_CPU->GetIVal() > 0 && !gEnv->IsDedicated()) - { - CreatePhysicsThread(); - } - else - { - KillPhysicsThread(); - } - - static int g_iPausedPhys = 0; - - CPhysicsThreadTask* pPhysicsThreadTask = ((CPhysicsThreadTask*)m_PhysThread); - if (!pPhysicsThreadTask) - { - FRAME_PROFILER_LEGACYONLY("SysUpdate:AllAIAndPhysics", this, PROFILE_SYSTEM); - AZ_TRACE_METHOD_NAME("SysUpdate::AllAIAndPhysics"); - - ////////////////////////////////////////////////////////////////////// - // update entity system (a little bit) before physics - if (nPauseMode != 1) - { - if (!bNoUpdate) - { - EBUS_EVENT(CrySystemEventBus, OnCrySystemPrePhysicsUpdate); - } - } - - // intermingle physics/AI updates so that if we get a big timestep (frame rate glitch etc) the - // AI gets to steer entities before they travel over cliffs etc. - const float maxTimeStep = 0.25f; - int maxSteps = 1; - //float fCurTime = m_Time.GetCurrTime(); - float timeToDo = m_Time.GetFrameTime();//fCurTime - fPrevTime; - if (m_env.bMultiplayer) - { - timeToDo = m_Time.GetRealFrameTime(); - } - - - - while (timeToDo > 0.0001f && maxSteps-- > 0) - { - float thisStep = min(maxTimeStep, timeToDo); - timeToDo -= thisStep; - - - EBUS_EVENT(CrySystemEventBus, OnCrySystemPostPhysicsUpdate); - } - - } - else - { - - // In multithreaded physics mode, post physics fires after physics events are dispatched on the main thread. - EBUS_EVENT(CrySystemEventBus, OnCrySystemPostPhysicsUpdate); - - ////////////////////////////////////////////////////////////////////// - // update entity system (a little bit) before physics - if (nPauseMode != 1) - { - if (!bNoUpdate) - { - EBUS_EVENT(CrySystemEventBus, OnCrySystemPrePhysicsUpdate); - } - } - - } - // Use UI timer for CryMovie, because it should not be affected by pausing game time const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI); @@ -1550,8 +1093,6 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/) m_updateTimes.push_back(std::make_pair(cur_time, updateTime)); } - UpdateUpdateTimes(); - { FRAME_PROFILER("SysUpdate - SystemEventDispatcher::Update", this, PROFILE_SYSTEM); m_pSystemEventDispatcher->Update(); @@ -1890,12 +1431,6 @@ ILocalizationManager* CSystem::GetLocalizationManager() return m_pLocalizationManager; } -////////////////////////////////////////////////////////////////////////// -IThreadTaskManager* CSystem::GetIThreadTaskManager() -{ - return m_pThreadTaskManager; -} - ////////////////////////////////////////////////////////////////////////// IResourceManager* CSystem::GetIResourceManager() { @@ -1960,10 +1495,6 @@ void CSystem::ExecuteCommandLine(bool deferred) if (pCmd->GetType() == eCLAT_Post) { string sLine = pCmd->GetName(); - -#if defined(CVARS_WHITELIST) - if (!GetCVarsWhiteList() || GetCVarsWhiteList()->IsWhiteListed(sLine, false)) -#endif { if (pCmd->GetValue()) { @@ -1973,12 +1504,6 @@ void CSystem::ExecuteCommandLine(bool deferred) GetILog()->Log("Executing command from command line: \n%s\n", sLine.c_str()); // - the actual command might be executed much later (e.g. level load pause) GetIConsole()->ExecuteString(sLine.c_str(), false, deferred); } -#if defined(CVARS_WHITELIST) - else if (gEnv->IsDedicated()) - { - GetILog()->LogError("Failed to execute command: '%s' as it is not whitelisted\n", sLine.c_str()); - } -#endif } } @@ -2078,93 +1603,6 @@ void CProfilingSystem::VTunePause() #endif } -////////////////////////////////////////////////////////////////////////// -sUpdateTimes& CSystem::GetCurrentUpdateTimeStats() -{ - return m_UpdateTimes[m_UpdateTimesIdx]; -} - -////////////////////////////////////////////////////////////////////////// -const sUpdateTimes* CSystem::GetUpdateTimeStats(uint32& index, uint32& num) -{ - index = m_UpdateTimesIdx; - num = NUM_UPDATE_TIMES; - return m_UpdateTimes; -} - -void CSystem::UpdateUpdateTimes() -{ - sUpdateTimes& sample = m_UpdateTimes[m_UpdateTimesIdx]; - if (m_PhysThread) - { - static uint64 lastPhysTime = 0U; - static uint64 lastMainTime = 0U; - static uint64 lastYields = 0U; - static uint64 lastPhysWait = 0U; - uint64 physTime = 0, mainTime = 0; - uint32 yields = 0; - physTime = ((CPhysicsThreadTask*)m_PhysThread)->LastStepTaken(); - mainTime = CryGetTicks() - lastMainTime; - lastMainTime = mainTime; - lastPhysWait = ((CPhysicsThreadTask*)m_PhysThread)->LastWaitTime(); - sample.PhysStepTime = physTime; - sample.SysUpdateTime = mainTime; - sample.PhysYields = yields; - sample.physWaitTime = lastPhysWait; - } - ++m_UpdateTimesIdx; - if (m_UpdateTimesIdx >= NUM_UPDATE_TIMES) - { - m_UpdateTimesIdx = 0; - } -} - - -#ifndef _RELEASE -void CSystem::GetCheckpointData(ICheckpointData& data) -{ - data.m_totalLoads = m_checkpointLoadCount; - data.m_loadOrigin = m_loadOrigin; -} - -void CSystem::IncreaseCheckpointLoadCount() -{ - if (!m_hasJustResumed) - { - ++m_checkpointLoadCount; - } - - m_hasJustResumed = false; -} - -void CSystem::SetLoadOrigin(LevelLoadOrigin origin) -{ - switch (origin) - { - case eLLO_NewLevel: // Intentional fall through - case eLLO_Level2Level: - m_expectingMapCommand = true; - break; - - case eLLO_Resumed: - m_hasJustResumed = true; - break; - - case eLLO_MapCmd: - if (m_expectingMapCommand) - { - // We knew a map command was coming, so don't process this. - m_expectingMapCommand = false; - return; - } - break; - } - - m_loadOrigin = origin; - m_checkpointLoadCount = 0; -} -#endif - bool CSystem::SteamInit() { #if USE_STEAM diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index c4f3bfabd6..e27dfe4866 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -26,14 +26,12 @@ #include "MTSafeAllocator.h" #include "CPUDetect.h" #include -#include "ThreadTask.h" #include "RenderBus.h" #include #include #include -#include namespace AzFramework { @@ -44,7 +42,6 @@ struct IConsoleCmdArgs; class CServerThrottle; struct IZLibCompressor; class CWatchdogThread; -class CThreadManager; #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -183,8 +180,6 @@ class CThreadManager; #include "CryLibrary.h" #endif -#define NUM_UPDATE_TIMES (128U) - #ifdef WIN32 typedef void* WIN_HMODULE; #else @@ -241,7 +236,6 @@ struct SSystemCVars int sys_WER; int sys_dump_type; int sys_ai; - int sys_physics; int sys_entitysystem; int sys_trackview; int sys_vtune; @@ -342,7 +336,6 @@ class CSystem , public IWindowMessageHandler , public AZ::RenderNotificationsBus::Handler , public CrySystemRequestBus::Handler - , private AzFramework::Terrain::TerrainDataNotificationBus::Handler { public: @@ -397,20 +390,8 @@ public: ISystem* GetCrySystem() override; //////////////////////////////////////////////////////////////////////// - //! Update screen during loading. - void UpdateLoadingScreen(); - - //! Update screen and call some important tick functions during loading. - void SynchronousLoadingTick(const char* pFunc, int line); - uint32 GetUsedMemory(); -#ifndef _RELEASE - virtual void GetCheckpointData(ICheckpointData& data); - virtual void IncreaseCheckpointLoadCount(); - virtual void SetLoadOrigin(LevelLoadOrigin origin); -#endif - virtual bool SteamInit(); void Relaunch(bool bRelaunch); @@ -425,8 +406,6 @@ public: virtual const char* GetUserName(); virtual int GetApplicationInstance(); int GetApplicationLogInstance(const char* logFilePath) override; - virtual sUpdateTimes& GetCurrentUpdateTimeStats(); - virtual const sUpdateTimes* GetUpdateTimeStats(uint32&, uint32&); ITimer* GetITimer(){ return m_env.pTimer; } AZ::IO::IArchive* GetIPak() { return m_env.pCryPak; }; @@ -434,7 +413,6 @@ public: IRemoteConsole* GetIRemoteConsole(); IMovieSystem* GetIMovieSystem() { return m_env.pMovieSystem; }; IMemoryManager* GetIMemoryManager(){ return m_pMemoryManager; } - IThreadManager* GetIThreadManager() override {return m_env.pThreadManager; } ICryFont* GetICryFont(){ return m_env.pCryFont; } ILog* GetILog(){ return m_env.pLog; } ICmdLine* GetICmdLine(){ return m_pCmdLine; } @@ -444,11 +422,8 @@ public: IViewSystem* GetIViewSystem(); ILevelSystem* GetILevelSystem(); ISystemEventDispatcher* GetISystemEventDispatcher() { return m_pSystemEventDispatcher; } - IThreadTaskManager* GetIThreadTaskManager(); IResourceManager* GetIResourceManager(); ITextModeConsole* GetITextModeConsole(); - IVisualLog* GetIVisualLog() { return m_env.pVisualLog; } - INotificationNetwork* GetINotificationNetwork() { return m_pNotificationNetwork; } IProfilingSystem* GetIProfilingSystem() { return &m_ProfilingSystem; } IZLibCompressor* GetIZLibCompressor() { return m_pIZLibCompressor; } IZLibDecompressor* GetIZLibDecompressor() { return m_pIZLibDecompressor; } @@ -459,19 +434,6 @@ public: CPNoise3* GetNoiseGen(); virtual uint64 GetUpdateCounter() { return m_nUpdateCounter; }; - virtual void SetLoadingProgressListener(ILoadingProgressListener* pLoadingProgressListener) - { - m_pProgressListener = pLoadingProgressListener; - }; - - virtual ILoadingProgressListener* GetLoadingProgressListener() const - { - return m_pProgressListener; - }; - - void SetIMaterialEffects(IMaterialEffects* pMaterialEffects) { m_env.pMaterialEffects = pMaterialEffects; } - void SetIOpticsManager(IOpticsManager* pOpticsManager) { m_env.pOpticsManager = pOpticsManager; } - void SetIVisualLog(IVisualLog* pVisualLog) { m_env.pVisualLog = pVisualLog; } void DetectGameFolderAccessRights(); virtual void ExecuteCommandLine(bool deferred=true); @@ -554,12 +516,6 @@ public: //! Return pointer to user defined callback. ISystemUserCallback* GetUserCallback() const { return m_pUserCallback; }; -#if defined(CVARS_WHITELIST) - virtual ICVarsWhitelist* GetCVarsWhiteList() const { return m_pCVarsWhitelist; }; - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const { return m_pCVarsWhitelistConfigSink; } -#else - virtual ILoadConfigurationEntrySink* GetCVarsWhiteListConfigSink() const { return nullptr; } -#endif // defined(CVARS_WHITELIST) ////////////////////////////////////////////////////////////////////////// virtual void SaveConfiguration(); @@ -571,7 +527,6 @@ public: virtual void SetConfigPlatform(ESystemConfigPlatform platform); ////////////////////////////////////////////////////////////////////////// - virtual int SetThreadState(ESubsystem subsys, bool bActive); virtual bool IsPaused() const { return m_bPaused; }; virtual ILocalizationManager* GetLocalizationManager(); @@ -608,8 +563,6 @@ private: // Release all resources. void ShutDown(); - void SleepIfInactive(); - bool LoadEngineDLLs(); //! @name Initialization routines @@ -623,12 +576,6 @@ private: //@} - ////////////////////////////////////////////////////////////////////////// - // Threading functions. - ////////////////////////////////////////////////////////////////////////// - void InitThreadSystem(); - void ShutDownThreadSystem(); - ////////////////////////////////////////////////////////////////////////// // Helper functions. ////////////////////////////////////////////////////////////////////////// @@ -645,9 +592,6 @@ private: void LogBuildInfo(); void SetDevMode(bool bEnable); - void CreatePhysicsThread(); - void KillPhysicsThread(); - #ifndef _RELEASE static void SystemVersionChanged(ICVar* pCVar); #endif // #ifndef _RELEASE @@ -676,7 +620,6 @@ public: virtual bool GetForceNonDevMode() const; virtual bool WasInDevMode() const { return m_bWasInDevMode; }; virtual bool IsDevMode() const { return m_bInDevMode && !GetForceNonDevMode(); } - virtual bool IsMinimalMode() const { return m_bMinimal; } virtual bool IsMODValid(const char* szMODName) const { if (!szMODName || strstr(szMODName, ".") || strstr(szMODName, "\\")) @@ -727,7 +670,6 @@ private: // ------------------------------------------------------ bool m_bRelaunch; //!< relaunching the app or not (true beforerelaunch) int m_iLoadingMode; //!< Game is loading w/o changing context (0 not, 1 quickloading, 2 full loading) bool m_bTestMode; //!< If running in testing mode. - bool m_bMinimal; //!< If running in 'minimal mode'. bool m_bEditor; //!< If running in Editor. bool m_bNoCrashDialog; bool m_bNoErrorReportWindow; @@ -742,16 +684,6 @@ private: // ------------------------------------------------------ SDefaultValidator* m_pDefaultValidator; //!< CCpuFeatures* m_pCpu; //!< CPU features int m_ttMemStatSS; //!< Time to memstat screenshot - string m_szCmdLine; - - int m_iTraceAllocations; - -#ifndef _RELEASE - int m_checkpointLoadCount;// Total times game has loaded from a checkpoint - LevelLoadOrigin m_loadOrigin; // Where the load was initiated from - bool m_hasJustResumed; // Has resume game just been called - bool m_expectingMapCommand; -#endif bool m_bDrawConsole; //!< Set to true if OK to draw the console. bool m_bDrawUI; //!< Set to true if OK to draw UI. @@ -867,8 +799,6 @@ private: // ------------------------------------------------------ ICVar* m_sys_asset_processor; ICVar* m_sys_load_files_to_memory; - ICVar* m_sys_physics_CPU; - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEM_H_SECTION_4 #include AZ_RESTRICTED_FILE(System_h) @@ -891,15 +821,6 @@ private: // ------------------------------------------------------ //! User define callback for system events. ISystemUserCallback* m_pUserCallback; -#if defined(CVARS_WHITELIST) - ////////////////////////////////////////////////////////////////////////// - //! User define callback for whitelisting cvars - ICVarsWhitelist* m_pCVarsWhitelist; - ILoadConfigurationEntrySink* m_pCVarsWhitelistConfigSink; -#endif // defined(CVARS_WHITELIST) - - //int m_nCurrentLogVerbosity; - SFileVersion m_fileVersion; SFileVersion m_productVersion; SFileVersion m_buildVersion; @@ -910,8 +831,6 @@ private: // ------------------------------------------------------ // Name table. CNameTable m_nameTable; - IThreadTask* m_PhysThread; - ESystemConfigSpec m_nServerConfigSpec; ESystemConfigSpec m_nMaxConfigSpec; ESystemConfigPlatform m_ConfigPlatform; @@ -919,8 +838,6 @@ private: // ------------------------------------------------------ std::unique_ptr m_pServerThrottle; CProfilingSystem m_ProfilingSystem; - sUpdateTimes m_UpdateTimes[NUM_UPDATE_TIMES]; - uint32 m_UpdateTimesIdx; // Pause mode. bool m_bPaused; @@ -991,26 +908,14 @@ private: ESystemGlobalState m_systemGlobalState; static const char* GetSystemGlobalStateName(const ESystemGlobalState systemGlobalState); - /////////////////////////////////////////////////////////////////////////// - // AzFramework::Terrain::TerrainDataNotificationBus START - void OnTerrainDataCreateBegin() override; - void OnTerrainDataDestroyBegin() override; - // AzFramework::Terrain::TerrainDataNotificationBus END - /////////////////////////////////////////////////////////////////////////// - public: void InitLocalization(); - void UpdateUpdateTimes(); protected: // ------------------------------------------------------------- - ILoadingProgressListener* m_pProgressListener; CCmdLine* m_pCmdLine; - CThreadManager* m_pThreadManager; - CThreadTaskManager* m_pThreadTaskManager; class CResourceManager* m_pResourceManager; ITextModeConsole* m_pTextModeConsole; - INotificationNetwork* m_pNotificationNetwork; string m_currentLanguageAudio; string m_systemConfigName; // computed from system_(hardwareplatform)_(assetsPlatform) - eg, system_android_es3.cfg or system_android_opengl.cfg or system_windows_pc.cfg diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 8bf2fb8930..48cb5e0d9e 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -35,13 +35,9 @@ #define SYSTEMINIT_CPP_SECTION_17 17 #endif -#if defined(MAP_LOADING_SLICING) -#include "SystemScheduler.h" -#endif // defined(MAP_LOADING_SLICING) #include "CryLibrary.h" #include "CryPath.h" #include -#include #include #include @@ -103,16 +99,12 @@ #include "PhysRenderer.h" #include "LocalizedStringManager.h" #include "SystemEventDispatcher.h" -#include "ThreadConfigManager.h" #include "Validator.h" #include "ServerThrottle.h" #include "SystemCFG.h" #include "AutoDetectSpec.h" #include "ResourceManager.h" #include "MTSafeAllocator.h" -#include "NotificationNetwork.h" -#include "ProfileLogSystem.h" -#include "SoftCode/SoftCodeMgr.h" #include "ZLibCompressor.h" #include "ZLibDecompressor.h" #include "ZStdDecompressor.h" @@ -146,8 +138,6 @@ #include "MobileDetectSpec.h" #endif -#include "IDebugCallStack.h" - #include "WindowsConsole.h" #if defined(EXTERNAL_CRASH_REPORTING) @@ -163,11 +153,6 @@ # include #endif -// if we enable the built-in local version instead of remote: -#if defined(CRY_ENABLE_RC_HELPER) -#include "ResourceCompilerHelper.h" -#endif - #ifdef WIN32 extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); #endif @@ -400,26 +385,20 @@ struct SysSpecOverrideSink } else { - // This could bypass the restricted/whitelisted cvar checks that exist elsewhere depending on + // This could bypass the restricted cvar checks that exist elsewhere depending on // the calling code so we also need check here before setting. bool isConst = pCvar->IsConstCVar(); bool isCheat = ((pCvar->GetFlags() & (VF_CHEAT | VF_CHEAT_NOCHECK | VF_CHEAT_ALWAYS_CHECK)) != 0); bool isReadOnly = ((pCvar->GetFlags() & VF_READONLY) != 0); bool isDeprecated = ((pCvar->GetFlags() & VF_DEPRECATED) != 0); bool allowApplyCvar = true; - bool whitelisted = true; - -#if defined CVARS_WHITELIST - ICVarsWhitelist* cvarWhitelist = gEnv->pSystem->GetCVarsWhiteList(); - whitelisted = cvarWhitelist ? cvarWhitelist->IsWhiteListed(szKey, true) : true; -#endif if ((isConst || isCheat || isReadOnly) || isDeprecated) { allowApplyCvar = !isDeprecated && (gEnv->pSystem->IsDevMode()) || (gEnv->IsEditor()); } - if ((allowApplyCvar && whitelisted) || ALLOW_CONST_CVAR_MODIFICATIONS) + if ((allowApplyCvar) || ALLOW_CONST_CVAR_MODIFICATIONS) { applyCvar = true; } @@ -1028,7 +1007,6 @@ bool CSystem::InitFileSystem() // get the DirectInstance FileIOBase which should be the AZ::LocalFileIO m_env.pFileIO = AZ::IO::FileIOBase::GetDirectInstance(); - m_env.pResourceCompilerHelper = nullptr; m_env.pCryPak = AZ::Interface::Get(); m_env.pFileIO = AZ::IO::FileIOBase::GetInstance(); @@ -1107,8 +1085,7 @@ bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams&) { LOADING_TIME_PROFILE_SECTION; { - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetCVarsWhiteListConfigSink(); - LoadConfiguration(m_systemConfigName.c_str(), pCVarsWhiteListConfigSink); + LoadConfiguration(m_systemConfigName.c_str()); AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Loading system configuration from %s...", m_systemConfigName.c_str()); } @@ -1118,13 +1095,6 @@ bool CSystem::InitFileSystem_LoadEngineFolders(const SSystemInitParams&) GetISystem()->SetConfigPlatform(GetDevicePlatform()); -#if defined(CRY_ENABLE_RC_HELPER) - if (!m_env.pResourceCompilerHelper) - { - m_env.pResourceCompilerHelper = new CResourceCompilerHelper(); - } -#endif - auto projectPath = AZ::Utils::GetProjectPath(); AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Project Path: %s\n", projectPath.empty() ? "None specified" : projectPath.c_str()); @@ -1179,7 +1149,6 @@ bool CSystem::InitAudioSystem(const SSystemInitParams& initParams) bool useRealAudioSystem = false; if (!initParams.bPreview - && !initParams.bMinimal && !m_bDedicatedServer && m_sys_audio_disable->GetIVal() == 0) { @@ -1672,12 +1641,8 @@ bool CSystem::Init(const SSystemInitParams& startupParams) gEnv->mMainThreadId = GetCurrentThreadId(); //Set this ASAP on startup InlineInitializationProcessing("CSystem::Init start"); - m_szCmdLine = startupParams.szSystemCmdLine; - m_env.szCmdLine = m_szCmdLine.c_str(); - m_env.bTesting = startupParams.bTesting; - m_env.bNoAssertDialog = startupParams.bTesting; - m_env.bNoRandomSeed = startupParams.bNoRandom; + m_env.bNoAssertDialog = false; m_bNoCrashDialog = gEnv->IsDedicated(); @@ -1754,16 +1719,10 @@ AZ_POP_DISABLE_WARNING m_bPreviewMode = startupParams.bPreview; m_bTestMode = startupParams.bTestMode; m_pUserCallback = startupParams.pUserCallback; - m_bMinimal = startupParams.bMinimal; -#if defined(CVARS_WHITELIST) - m_pCVarsWhitelist = startupParams.pCVarsWhitelist; -#endif // defined(CVARS_WHITELIST) m_bDedicatedServer = startupParams.bDedicatedServer; m_currentLanguageAudio = ""; - memcpy(gEnv->pProtectedFunctions, startupParams.pProtectedFunctions, sizeof(startupParams.pProtectedFunctions)); - #if !defined(CONSOLE) m_env.SetIsEditor(m_bEditor); m_env.SetIsEditorGameMode(false); @@ -1771,7 +1730,6 @@ AZ_POP_DISABLE_WARNING #endif m_env.SetToolMode(startupParams.bToolMode); - m_env.bIsOutOfMemory = false; if (m_bEditor) { @@ -1935,23 +1893,6 @@ AZ_POP_DISABLE_WARNING // so we log this immediately after setting the log filename LogVersion(); - //here we should be good to ask Crypak to do something - - // Initialise after pLog and CPU feature initialization - // AND after console creation (Editor only) - // May need access to engine folder .pak files - gEnv->pThreadManager->GetThreadConfigManager()->LoadConfig("config/engine_core.thread_config"); - - if (m_bEditor) - { - gEnv->pThreadManager->GetThreadConfigManager()->LoadConfig("config/engine_sandbox.thread_config"); - } - - // Setup main thread - void* pThreadHandle = 0; // Let system figure out thread handle - gEnv->pThreadManager->RegisterThirdPartyThread(pThreadHandle, "Main"); - m_env.pProfileLogSystem = new CProfileLogSystem(); - bool devModeEnable = true; #if defined(_RELEASE) @@ -1967,22 +1908,6 @@ AZ_POP_DISABLE_WARNING SetDevMode(devModeEnable); - ////////////////////////////////////////////////////////////////////////// - // CREATE NOTIFICATION NETWORK - ////////////////////////////////////////////////////////////////////////// - m_pNotificationNetwork = nullptr; -#ifndef _RELEASE - #ifndef LINUX - - if (!startupParams.bMinimal) - { - m_pNotificationNetwork = CNotificationNetwork::Create(); - } - #endif//LINUX -#endif // _RELEASE - - InlineInitializationProcessing("CSystem::Init NotificationNetwork"); - ////////////////////////////////////////////////////////////////////////// // CREATE CONSOLE ////////////////////////////////////////////////////////////////////////// @@ -2051,8 +1976,6 @@ AZ_POP_DISABLE_WARNING // CPU features detection. m_pCpu = new CCpuFeatures; m_pCpu->Detect(); - m_env.pi.numCoresAvailableToProcess = m_pCpu->GetCPUCount(); - m_env.pi.numLogicalProcessors = m_pCpu->GetLogicalCPUCount(); // Check hard minimum CPU requirements if (!CheckCPURequirements(m_pCpu, this)) @@ -2102,17 +2025,15 @@ AZ_POP_DISABLE_WARNING } { - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetCVarsWhiteListConfigSink(); - // We have to load this file again since first time we did it without devmode - LoadConfiguration(m_systemConfigName.c_str(), pCVarsWhiteListConfigSink); + LoadConfiguration(m_systemConfigName.c_str()); // Optional user defined overrides - LoadConfiguration("user.cfg", pCVarsWhiteListConfigSink); + LoadConfiguration("user.cfg"); #if defined(ENABLE_STATS_AGENT) if (m_pCmdLine->FindArg(eCLAT_Pre, "useamblecfg")) { - LoadConfiguration("amble.cfg", pCVarsWhiteListConfigSink); + LoadConfiguration("amble.cfg"); } #endif } @@ -2159,7 +2080,7 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init LoadConfigurations"); #ifdef WIN32 - if ((g_cvars.sys_WER) && (!startupParams.bMinimal)) + if ((g_cvars.sys_WER)) { SetUnhandledExceptionFilter(CryEngineExceptionFilterWER); } @@ -2169,7 +2090,6 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // Localization ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) { InitLocalization(); } @@ -2187,7 +2107,6 @@ AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////// // AUDIO ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bMinimal) { if (InitAudioSystem(startupParams)) { @@ -2210,12 +2129,6 @@ AZ_POP_DISABLE_WARNING m_pUserCallback->OnInitProgress("First time asset processing - may take a minute..."); } -#ifdef SOFTCODE_SYSTEM_ENABLED - m_env.pSoftCodeMgr = new SoftCodeMgr(); -#else - m_env.pSoftCodeMgr = nullptr; -#endif - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // System cursor @@ -2225,8 +2138,7 @@ AZ_POP_DISABLE_WARNING // - System cursor has to be enabled manually by the Game if needed; the custom UiCursor will typically be used instead if (!gEnv->IsDedicated() && - !gEnv->IsEditor() && - !startupParams.bTesting) + !gEnv->IsEditor()) { AzFramework::InputSystemCursorRequestBus::Event(AzFramework::InputDeviceMouse::Id, &AzFramework::InputSystemCursorRequests::SetSystemCursorState, @@ -2322,27 +2234,6 @@ AZ_POP_DISABLE_WARNING InlineInitializationProcessing("CSystem::Init ZStdDecompressor"); - ////////////////////////////////////////////////////////////////////////// - // Initialize task threads. - ////////////////////////////////////////////////////////////////////////// - { - m_pThreadTaskManager->InitThreads(); - - SetAffinity(); - AZ_Assert(CryMemory::IsHeapValid(), "CryMemory heap must be valid before initializing VTune."); - - - if (strstr(startupParams.szSystemCmdLine, "-VTUNE") != 0 || g_cvars.sys_vtune != 0) - { - if (!InitVTuneProfiler()) - { - return false; - } - } - } - - InlineInitializationProcessing("CSystem::Init InitTaskThreads"); - if (m_env.pLyShine) { m_env.pLyShine->PostInit(); @@ -2366,8 +2257,6 @@ AZ_POP_DISABLE_WARNING } } EnableFloatExceptions(g_cvars.sys_float_exceptions); - - MarkThisThreadForDebugging("Main"); } InlineInitializationProcessing("CSystem::Init End"); @@ -2422,8 +2311,7 @@ static void LoadConfigurationCmd(IConsoleCmdArgs* pParams) return; } - ILoadConfigurationEntrySink* pCVarsWhiteListConfigSink = GetISystem()->GetCVarsWhiteListConfigSink(); - GetISystem()->LoadConfiguration(string("Config/") + pParams->GetArg(1), pCVarsWhiteListConfigSink); + GetISystem()->LoadConfiguration(string("Config/") + pParams->GetArg(1)); } @@ -2648,20 +2536,6 @@ void CmdDrillToFile(IConsoleCmdArgs* pArgs) } } -void ChangeLogAllocations(ICVar* pVal) -{ - g_iTraceAllocations = pVal->GetIVal(); - - if (g_iTraceAllocations == 2) - { - IDebugCallStack::instance()->StartMemLog(); - } - else - { - IDebugCallStack::instance()->StopMemLog(); - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::CreateSystemVars() { @@ -2719,9 +2593,6 @@ void CSystem::CreateSystemVars() m_cvAIUpdate = REGISTER_INT("ai_NoUpdate", 0, VF_CHEAT, "Disables AI system update when 1"); - m_iTraceAllocations = g_iTraceAllocations; - REGISTER_CVAR2_CB("sys_logallocations", &m_iTraceAllocations, m_iTraceAllocations, VF_DUMPTODISK, "Save allocation call stack", ChangeLogAllocations); - m_cvMemStats = REGISTER_INT("MemStats", 0, 0, "0/x=refresh rate in milliseconds\n" "Use 1000 to switch on and 0 to switch off\n" @@ -2860,16 +2731,6 @@ void CSystem::CreateSystemVars() m_sys_TaskThread_CPU[5] = REGISTER_INT("sys_TaskThread5_CPU", 1, 0, "Specifies the physical CPU index taskthread5 will run on"); - //if physics thread is excluded all locks inside are mapped to NO_LOCK - //var must be not visible to accidentally get enabled -#if defined(EXCLUDE_PHYSICS_THREAD) - m_sys_physics_CPU = REGISTER_INT("sys_physics_CPU_disabled", 0, 0, - "Specifies the physical CPU index physics will run on"); -#else - m_sys_physics_CPU = REGISTER_INT("sys_physics_CPU", 1, 0, - "Specifies the physical CPU index physics will run on"); -#endif - #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_12 #include AZ_RESTRICTED_FILE(SystemInit_cpp) @@ -3033,7 +2894,6 @@ void CSystem::CreateSystemVars() "0=off / 1=enabled"); */ REGISTER_CVAR2("sys_AI", &g_cvars.sys_ai, 1, 0, "Enables AI Update"); - REGISTER_CVAR2("sys_physics", &g_cvars.sys_physics, 1, 0, "Enables Physics Update"); REGISTER_CVAR2("sys_entities", &g_cvars.sys_entitysystem, 1, 0, "Enables Entities Update"); REGISTER_CVAR2("sys_trackview", &g_cvars.sys_trackview, 1, 0, "Enables TrackView Update"); @@ -3068,10 +2928,6 @@ void CSystem::CreateSystemVars() REGISTER_STRING("dlc_directory", "", 0, "Holds the path to the directory where DLC should be installed to and read from"); -#if defined(MAP_LOADING_SLICING) - CreateSystemScheduler(this); -#endif // defined(MAP_LOADING_SLICING) - #if defined(WIN32) || defined(WIN64) REGISTER_INT("sys_screensaver_allowed", 0, VF_NULL, "Specifies if screen saver is allowed to start up while the game is running."); #endif diff --git a/Code/CryEngine/CrySystem/SystemRender.cpp b/Code/CryEngine/CrySystem/SystemRender.cpp index 9e148bbc2b..b608ef5335 100644 --- a/Code/CryEngine/CrySystem/SystemRender.cpp +++ b/Code/CryEngine/CrySystem/SystemRender.cpp @@ -39,8 +39,6 @@ #include #include -#include "ThreadInfo.h" - #include #if defined(AZ_RESTRICTED_PLATFORM) @@ -90,52 +88,6 @@ void CSystem::OnScene3DEnd() } } - -//! Update screen and call some important tick functions during loading. -void CSystem::SynchronousLoadingTick([[maybe_unused]] const char* pFunc, [[maybe_unused]] int line) -{ - LOADING_TIME_PROFILE_SECTION; - if (gEnv && gEnv->bMultiplayer && !gEnv->IsEditor()) - { - //UpdateLoadingScreen currently contains a couple of tick functions that need to be called regularly during the synchronous level loading, - //when the usual engine and game ticks are suspended. - UpdateLoadingScreen(); - -#if defined(MAP_LOADING_SLICING) - GetISystemScheduler()->SliceAndSleep(pFunc, line); -#endif - } -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::UpdateLoadingScreen() -{ - // Do not update the network thread from here - it will cause context corruption - use the NetworkStallTicker thread system - - if (GetCurrentThreadId() != gEnv->mMainThreadId) - { - return; - } - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMRENDERER_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemRender_cpp) -#endif - -#if AZ_LOADSCREENCOMPONENT_ENABLED - EBUS_EVENT(LoadScreenBus, UpdateAndRender); -#endif // if AZ_LOADSCREENCOMPONENT_ENABLED - - if (!m_bEditor && !IsQuitting()) - { - if (m_pProgressListener) - { - m_pProgressListener->OnLoadingProgress(0); - } - } -} - ////////////////////////////////////////////////////////////////////////// void CSystem::DisplayErrorMessage(const char* acMessage, diff --git a/Code/CryEngine/CrySystem/SystemScheduler.cpp b/Code/CryEngine/CrySystem/SystemScheduler.cpp deleted file mode 100644 index 5cee6d5529..0000000000 --- a/Code/CryEngine/CrySystem/SystemScheduler.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Implementation of the CSystemScheduler class - - -#include "CrySystem_precompiled.h" - -#include "ProjectDefines.h" -#if defined(MAP_LOADING_SLICING) - -#include "SystemScheduler.h" - -#include "MiniQueue.h" -#include "ClientHandler.h" -#include "ServerHandler.h" - -void CreateSystemScheduler(CSystem* pSystem) -{ - gEnv->pSystemScheduler = new CSystemScheduler(pSystem); -} - -CSystemScheduler::CSystemScheduler(CSystem* pSystem) - : m_pSystem(pSystem) - , m_lastSliceCheckTime(0.0f) - , m_sliceLoadingRef(0) -{ - int defaultSchedulingMode = 0; - if (gEnv->IsDedicated()) - { - defaultSchedulingMode = 2; - } - - m_svSchedulingMode = REGISTER_INT("sv_scheduling", defaultSchedulingMode, 0, "Scheduling mode\n" - " 0: Normal mode\n" - " 1: Client\n" - " 2: Server\n"); - - m_svSchedulingBucket = REGISTER_INT("sv_schedulingBucket", 0, 0, "Scheduling bucket\n"); - - m_svSchedulingAffinity = REGISTER_INT("sv_SchedulingAffinity", 0, 0, "Scheduling affinity\n"); - - m_svSchedulingClientTimeout = REGISTER_INT("sv_schedulingClientTimeout", 1000, 0, "Client wait server\n"); - m_svSchedulingServerTimeout = REGISTER_INT("sv_schedulingServerTimeout", 100, 0, "Server wait server\n"); - -#if defined(MAP_LOADING_SLICING) - m_svSliceLoadEnable = REGISTER_INT("sv_sliceLoadEnable", 1, 0, "Enable/disable slice loading logic\n"); - ; - m_svSliceLoadBudget = REGISTER_INT("sv_sliceLoadBudget", 10, 0, "Slice budget\n"); - ; - m_svSliceLoadLogging = REGISTER_INT("sv_sliceLoadLogging", 0, 0, "Enable/disable slice loading logging\n"); -#endif - - m_pLastSliceName = "INACTIVE"; - m_lastSliceLine = 0; -} - -CSystemScheduler::~CSystemScheduler(void) -{ -} - -void CSystemScheduler::SliceLoadingBegin() -{ - m_lastSliceCheckTime = gEnv->pTimer->GetAsyncTime(); - m_sliceLoadingRef++; - m_pLastSliceName = "START"; - m_lastSliceLine = 0; -} - -void CSystemScheduler::SliceLoadingEnd() -{ - m_sliceLoadingRef--; - m_pLastSliceName = "INACTIVE"; - m_lastSliceLine = 0; -} - -void CSystemScheduler::SliceAndSleep(const char* sliceName, int line) -{ -#if defined(MAP_LOADING_SLICING) - if (!gEnv->IsDedicated()) - { - return; - } - - if (!m_sliceLoadingRef) - { - return; - } - - if (!m_svSliceLoadEnable->GetIVal()) - { - return; - } - - SchedulingModeUpdate(); - - CTimeValue currTime = gEnv->pTimer->GetAsyncTime(); - - float sliceBudget = CLAMP(m_svSliceLoadBudget->GetFVal(), 0, 1000.0f / m_pSystem->GetDedicatedMaxRate()->GetFVal()); - bool doSleep = true; - if ((currTime - m_pSystem->GetLastTickTime()).GetMilliSeconds() < sliceBudget) - { - m_lastSliceCheckTime = currTime; - doSleep = false; - } - - if (doSleep) - { - if (m_svSliceLoadLogging->GetIVal()) - { - float diff = (currTime - m_lastSliceCheckTime).GetMilliSeconds(); - if (diff > sliceBudget) - { - CryLogAlways("[SliceAndSleep]: Interval between slice [%s:%i] and [%s:%i] was [%f] out of budget [%f]", m_pLastSliceName, m_lastSliceLine, sliceName, line, diff, sliceBudget); - } - } - - m_pSystem->SleepIfNeeded(); - } - - m_pLastSliceName = sliceName; - m_lastSliceLine = line; -#endif -} - -void CSystemScheduler::SchedulingSleepIfNeeded() -{ - if (!gEnv->IsDedicated()) - { - return; - } - - SchedulingModeUpdate(); - m_pSystem->SleepIfNeeded(); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Scheduling mode routines -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - - - - - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -// Scheduling mode update logic -// -/////////////////////////////////////////////////////////////////////////////////////////////////// - -void CSystemScheduler::SchedulingModeUpdate() -{ - static std::unique_ptr m_client; - static std::unique_ptr m_server; - - if (int scheduling = m_svSchedulingMode->GetIVal()) - { - if (scheduling == 1) //client - { - if (!m_client.get()) - { - m_server.reset(); - m_client.reset(new ClientHandler(m_svSchedulingBucket->GetString(), m_svSchedulingAffinity->GetIVal(), m_svSchedulingClientTimeout->GetIVal())); - } - if (m_client->Sync()) - { - return; - } - } - else if (scheduling == 2) //server - { - if (!m_server.get()) - { - m_client.reset(); - m_server.reset(new ServerHandler(m_svSchedulingBucket->GetString(), m_svSchedulingAffinity->GetIVal(), m_svSchedulingServerTimeout->GetIVal())); - } - if (m_server->Sync()) - { - return; - } - } - } - else - { - m_client.reset(); - m_server.reset(); - } -} - -#endif // defined(MAP_LOADING_SLICING) - -extern "C" void SliceAndSleep(const char* pFunc, int line) -{ - if (GetISystemScheduler()) - { - GetISystemScheduler()->SliceAndSleep(pFunc, line); - } -} - diff --git a/Code/CryEngine/CrySystem/SystemScheduler.h b/Code/CryEngine/CrySystem/SystemScheduler.h deleted file mode 100644 index feb6e2850c..0000000000 --- a/Code/CryEngine/CrySystem/SystemScheduler.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_SYSTEMSCHEDULER_H -#define CRYINCLUDE_CRYSYSTEM_SYSTEMSCHEDULER_H - -#pragma once - -#include "System.h" -#include - -class CSystemScheduler - : public ISystemScheduler -{ -public: - CSystemScheduler(CSystem* pSystem); - virtual ~CSystemScheduler(void); - - // ISystemScheduler - virtual void SliceAndSleep(const char* sliceName, int line); - virtual void SliceLoadingBegin(); - virtual void SliceLoadingEnd(); - - virtual void SchedulingSleepIfNeeded(void); - // ~ISystemScheduler - -protected: - void SchedulingModeUpdate(void); - -private: - CSystem* m_pSystem; - ICVar* m_svSchedulingAffinity; - ICVar* m_svSchedulingClientTimeout; - ICVar* m_svSchedulingServerTimeout; - ICVar* m_svSchedulingBucket; - ICVar* m_svSchedulingMode; - ICVar* m_svSliceLoadEnable; - ICVar* m_svSliceLoadBudget; - ICVar* m_svSliceLoadLogging; - - CTimeValue m_lastSliceCheckTime; - - int m_sliceLoadingRef; - - const char* m_pLastSliceName; - int m_lastSliceLine; -}; - -// Summary: -// Creates the system scheduler interface. -void CreateSystemScheduler(CSystem* pSystem); - -#endif // CRYINCLUDE_CRYSYSTEM_SYSTEMSCHEDULER_H diff --git a/Code/CryEngine/CrySystem/SystemThreading.cpp b/Code/CryEngine/CrySystem/SystemThreading.cpp deleted file mode 100644 index 9354e4e1c3..0000000000 --- a/Code/CryEngine/CrySystem/SystemThreading.cpp +++ /dev/null @@ -1,697 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "System.h" -#include "ThreadConfigManager.h" -#include "IThreadManager.h" -#include -#include "CryUtils.h" - -#define INCLUDED_FROM_SYSTEM_THREADING_CPP - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define SYSTEMTHREADING_CPP_SECTION_1 1 -#define SYSTEMTHREADING_CPP_SECTION_2 2 -#define SYSTEMTHREADING_CPP_SECTION_3 3 -#endif - -#if defined(WIN32) || defined(WIN64) - #include "CryThreadUtil_win32_thread.h" -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - #include "CryThreadUtil_pthread.h" -#endif -#undef INCLUDED_FROM_SYSTEM_THREADING_CPP - -////////////////////////////////////////////////////////////////////////// -static void ApplyThreadConfig(CryThreadUtil::TThreadHandle pThreadHandle, const SThreadConfig& rThreadDesc) -{ - // Apply config - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) - { - CryThreadUtil::CrySetThreadName(pThreadHandle, rThreadDesc.szThreadName); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) - { - CryThreadUtil::CrySetThreadAffinityMask(pThreadHandle, rThreadDesc.affinityFlag); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) - { - CryThreadUtil::CrySetThreadPriority(pThreadHandle, rThreadDesc.priority); - } - if (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) - { - CryThreadUtil::CrySetThreadPriorityBoost(pThreadHandle, !rThreadDesc.bDisablePriorityBoost); - } - - CryComment(" Configured thread \"%s\" %s | AffinityMask: %u %s | Priority: %i %s | PriorityBoost: %s %s", - rThreadDesc.szThreadName, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) ? "" : "(ignored)", - rThreadDesc.affinityFlag, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) ? "" : "(ignored)", - rThreadDesc.priority, (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) ? "" : "(ignored)", - !rThreadDesc.bDisablePriorityBoost ? "enabled" : "disabled", (rThreadDesc.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) ? "" : "(ignored)"); -} - -////////////////////////////////////////////////////////////////////////// -struct SThreadMetaData - : public CMultiThreadRefCount -{ - SThreadMetaData() - : m_pThreadTask(0) - , m_threadHandle(0) - , m_threadId(0) - , m_threadName("Cry_UnnamedThread") - , m_isRunning(false) - { - } - - IThread* m_pThreadTask; // Pointer to thread task to be executed - CThreadManager* m_pThreadMngr; // Pointer to thread manager - - CryThreadUtil::TThreadHandle m_threadHandle; // Thread handle - threadID m_threadId; // The active threadId, 0 = Invalid Id - - CryMutex m_threadExitMutex; // Mutex used to safeguard thread exit condition signaling - CryConditionVariable m_threadExitCondition; // Signaled when the thread is about to exit - - CryFixedStringT m_threadName; // Thread name - volatile bool m_isRunning; // Indicates the thread is not ready to exit yet -}; - -////////////////////////////////////////////////////////////////////////// -class CThreadManager - : public IThreadManager -{ -public: - // - virtual ~CThreadManager() - { - } - - virtual bool SpawnThread(IThread* pThread, const char* sThreadName, ...) override; - virtual bool JoinThread(IThread* pThreadTask, EJoinMode eJoinMode) override; - - virtual bool RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) override; - virtual bool UnRegisterThirdPartyThread(const char* sThreadName, ...) override; - - virtual const char* GetThreadName(threadID nThreadId) override; - virtual threadID GetThreadId(const char* sThreadName, ...) override; - - virtual void ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData = 0) override; - - virtual void EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId = 0) override; - virtual void EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) override; - - virtual uint GetFloatingPointExceptionMask() override; - virtual void SetFloatingPointExceptionMask(uint nMask) override; - - IThreadConfigManager* GetThreadConfigManager() override - { - return &m_threadConfigManager; - } - // -private: -#if defined(WIN32) || defined(WIN64) - static unsigned __stdcall RunThread(void* thisPtr); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - static void* RunThread(void* thisPtr); -#endif - -private: - bool UnregisterThread(IThread* pThreadTask); - - bool SpawnThreadImpl(IThread* pThread, const char* sThreadName); - - bool RegisterThirdPartyThreadImpl(CryThreadUtil::TThreadHandle pThreadHandle, const char* sThreadName); - bool UnRegisterThirdPartyThreadImpl(const char* sThreadName); - - threadID GetThreadIdImpl(const char* sThreadName); - -private: - // Note: Guard SThreadMetaData with a _smart_ptr and lock to ensure that a thread waiting to be signaled by another still - // has access to valid SThreadMetaData even though the other thread terminated and as a result unregistered itself from the CThreadManager. - // An example would be the join method. Where one thread waits on a signal from an other thread to terminate and release its SThreadMetaData, - // sharing the same SThreadMetaData condition variable. - typedef std::map > SpawnedThreadMap; - typedef std::map >::iterator SpawnedThreadMapIter; - typedef std::map >::const_iterator SpawnedThreadMapConstIter; - typedef std::pair > ThreadMapPair; - - typedef std::map, _smart_ptr > SpawnedThirdPartyThreadMap; - typedef std::map, _smart_ptr >::iterator SpawnedThirdPartyThreadMapIter; - typedef std::map, _smart_ptr >::const_iterator SpawnedThirdPartyThreadMapConstIter; - typedef std::pair, _smart_ptr > ThirdPartyThreadMapPair; - - CryCriticalSection m_spawnedThreadsLock; // Use lock for the rare occasion a thread is created/destroyed - SpawnedThreadMap m_spawnedThreads; // Holds information of all spawned threads (through this system) - - CryCriticalSection m_spawnedThirdPartyThreadsLock; // Use lock for the rare occasion a thread is created/destroyed - SpawnedThirdPartyThreadMap m_spawnedThirdPartyThread; // Holds information of all registered 3rd party threads (through this system) - - CThreadConfigManager m_threadConfigManager; -}; - -////////////////////////////////////////////////////////////////////////// -#if defined(WIN32) || defined(WIN64) -unsigned __stdcall CThreadManager::RunThread(void* thisPtr) -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMTHREADING_CPP_SECTION_3 -#include AZ_RESTRICTED_FILE(SystemThreading_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else -void* CThreadManager::RunThread(void* thisPtr) -#endif -{ - // Check that we are not spawning a thread before gEnv->pSystem has been set - // Otherwise we cannot enable floating point exceptions - if (!gEnv || !gEnv->pSystem) - { - CryFatalError("[Error]: CThreadManager::RunThread requires gEnv->pSystem to be initialized."); - } - - IThreadConfigManager* pThreadConfigMngr = gEnv->pThreadManager->GetThreadConfigManager(); - - SThreadMetaData* pThreadData = reinterpret_cast(thisPtr); - pThreadData->m_threadId = CryThreadUtil::CryGetCurrentThreadId(); - - // Apply config - const SThreadConfig* pThreadConfig = pThreadConfigMngr->GetThreadConfig(pThreadData->m_threadName.c_str()); - ApplyThreadConfig(pThreadData->m_threadHandle, *pThreadConfig); - - // Config not found, append thread name with no config tag - if (pThreadConfig == pThreadConfigMngr->GetDefaultThreadConfig()) - { - CryFixedStringT tmpString(pThreadData->m_threadName); - const char* cNoConfigAppendix = "(NoCfgFound)"; - int nNumCharsToReplace = strlen(cNoConfigAppendix); - - // Replace thread name ending - if (pThreadData->m_threadName.size() > THREAD_NAME_LENGTH_MAX - nNumCharsToReplace) - { - tmpString.replace(THREAD_NAME_LENGTH_MAX - nNumCharsToReplace, nNumCharsToReplace, cNoConfigAppendix, nNumCharsToReplace); - } - else - { - tmpString.append(cNoConfigAppendix); - } - - // Print to log - if (pThreadConfigMngr->ConfigLoaded()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " No Thread config found for thread %s using ... default config.", pThreadData->m_threadName.c_str()); - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, " Thread config not loaded yet. Hence no thread config was found for thread %s ... using default config.", pThreadData->m_threadName.c_str()); - } - - // Rename Thread - CryThreadUtil::CrySetThreadName(pThreadData->m_threadHandle, tmpString.c_str()); - } - - // Enable FPEs - gEnv->pThreadManager->EnableFloatExceptions((EFPE_Severity)g_cvars.sys_float_exceptions); - - // Execute thread code - pThreadData->m_pThreadTask->ThreadEntry(); - - // Disable FPEs - gEnv->pThreadManager->EnableFloatExceptions(eFPE_None); - - // Signal imminent thread end - pThreadData->m_threadExitMutex.Lock(); - pThreadData->m_isRunning = false; - pThreadData->m_threadExitCondition.Notify(); - pThreadData->m_threadExitMutex.Unlock(); - - // Unregister thread - // Note: Unregister after m_threadExitCondition.Notify() to ensure pThreadData is still valid - pThreadData->m_pThreadMngr->UnregisterThread(pThreadData->m_pThreadTask); - - CryThreadUtil::CryThreadExitCall(); - - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::JoinThread(IThread* pThreadTask, EJoinMode eJoinMode) -{ - // Get thread object - _smart_ptr pThreadImpl = 0; - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res == m_spawnedThreads.end()) - { - // Thread has already finished and unregistered itself. - // As it is complete we cannot wait for it. - // Hence return true. - return true; - } - - pThreadImpl = res->second; // Keep object alive - } - - // On try join, exit if the thread is not in a state to exit - if (eJoinMode == eJM_TryJoin && pThreadImpl->m_isRunning) - { - return false; - } - - // Wait for completion of the target thread exit condition - pThreadImpl->m_threadExitMutex.Lock(); - while (pThreadImpl->m_isRunning) - { - pThreadImpl->m_threadExitCondition.Wait(pThreadImpl->m_threadExitMutex); - } - pThreadImpl->m_threadExitMutex.Unlock(); - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnregisterThread(IThread* pThreadTask) -{ - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res == m_spawnedThreads.end()) - { - // Duplicate thread deletion - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": UnregisterThread: Unable to unregister thread. Thread name could not be found. Double deletion? IThread pointer: %p", pThreadTask); - return false; - } - - m_spawnedThreads.erase(res); - return true; -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadManager::GetThreadName(threadID nThreadId) -{ - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId == nThreadId) - { - return iter->second->m_threadName.c_str(); - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId == nThreadId) - { - return iter->second->m_threadName.c_str(); - } - } - } - - return ""; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::ForEachOtherThread(IThreadManager::ThreadModifFunction fpThreadModiFunction, void* pFuncData) -{ - threadID nCurThreadId = CryThreadUtil::CryGetCurrentThreadId(); - - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId != nCurThreadId) - { - fpThreadModiFunction(iter->second->m_threadId, pFuncData); - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadId != nCurThreadId) - { - fpThreadModiFunction(iter->second->m_threadId, pFuncData); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::SpawnThread(IThread* pThreadTask, const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1 || cNumCharsNeeded < 0) - { - strThreadName[THREAD_NAME_LENGTH_MAX - 1] = '\0'; // The WinApi only null terminates if strLen < bufSize - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Spawn thread - bool ret = SpawnThreadImpl(pThreadTask, strThreadName); - - if (!ret) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": CSystem::SpawnThread error spawning thread: \"%s\" ", strThreadName); - } - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::SpawnThreadImpl(IThread* pThreadTask, const char* sThreadName) -{ - if (pThreadTask == NULL) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_ERROR, ": SpawnThread '%s' ThreadTask is NULL : ignoring", sThreadName); - return false; - } - - // Init thread meta data - SThreadMetaData* pThreadMetaData = new SThreadMetaData(); - pThreadMetaData->m_pThreadTask = pThreadTask; - pThreadMetaData->m_pThreadMngr = this; - pThreadMetaData->m_threadName = sThreadName; - - // Add thread to map - { - AUTO_LOCK(m_spawnedThreadsLock); - SpawnedThreadMapIter res = m_spawnedThreads.find(pThreadTask); - if (res != m_spawnedThreads.end()) - { - // Thread with same name already spawned - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": SpawnThread: Thread \"%s\" already exists.", sThreadName); - delete pThreadMetaData; - return false; - } - - // Insert thread data - m_spawnedThreads.insert(ThreadMapPair(pThreadTask, pThreadMetaData)); - } - - // Load config if we can and if no config has been defined to be loaded - const SThreadConfig* pThreadConfig = gEnv->pThreadManager->GetThreadConfigManager()->GetThreadConfig(sThreadName); - - // Create thread description - CryThreadUtil::SThreadCreationDesc desc = {sThreadName, RunThread, pThreadMetaData, pThreadConfig->paramActivityFlag & SThreadConfig::eThreadParamFlag_StackSize ? pThreadConfig->stackSizeBytes : 0}; - - // Spawn new thread - pThreadMetaData->m_isRunning = CryThreadUtil::CryCreateThread(&(pThreadMetaData->m_threadHandle), desc); - - // Validate thread creation - if (!pThreadMetaData->m_isRunning) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": SpawnThread: Could not spawn thread \"%s\" .", sThreadName); - - // Remove thread from map (also releases SThreadMetaData _smart_ptr) - m_spawnedThreads.erase(m_spawnedThreads.find(pThreadTask)); - return false; - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::RegisterThirdPartyThread(void* pThreadHandle, const char* sThreadName, ...) -{ - if (!pThreadHandle) - { - pThreadHandle = reinterpret_cast(CryThreadUtil::CryGetCurrentThreadHandle()); - } - - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Register 3rd party thread - bool ret = RegisterThirdPartyThreadImpl(reinterpret_cast(pThreadHandle), strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::RegisterThirdPartyThreadImpl(CryThreadUtil::TThreadHandle threadHandle, const char* sThreadName) -{ - if (strcmp(sThreadName, "") == 0) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": CThreadManager::RegisterThirdPartyThread error registering third party thread. No name provided."); - return false; - } - // Init thread meta data - SThreadMetaData* pThreadMetaData = new SThreadMetaData(); - pThreadMetaData->m_pThreadTask = 0; - pThreadMetaData->m_pThreadMngr = this; - pThreadMetaData->m_threadName = sThreadName; - pThreadMetaData->m_threadHandle = CryThreadUtil::CryDuplicateThreadHandle(threadHandle); // Ensure that we are not storing a pseudo handle - pThreadMetaData->m_threadId = CryThreadUtil::CryGetThreadId(pThreadMetaData->m_threadHandle); - - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - // Check for duplicate - SpawnedThirdPartyThreadMapConstIter res = m_spawnedThirdPartyThread.find(sThreadName); - if (res != m_spawnedThirdPartyThread.end()) - { - CryFatalError("CThreadManager::RegisterThirdPartyThread - Unable to register thread \"%s\"" - "because another third party thread with the same name \"%s\" has already been registered with ThreadHandle: %p", - sThreadName, res->second->m_threadName.c_str(), reinterpret_cast(threadHandle)); - - delete pThreadMetaData; - return false; - } - - // Insert thread data - m_spawnedThirdPartyThread.insert(ThirdPartyThreadMapPair(pThreadMetaData->m_threadName.c_str(), pThreadMetaData)); - } - - // Get thread config - const SThreadConfig* pThreadConfig = gEnv->pThreadManager->GetThreadConfigManager()->GetThreadConfig(sThreadName); - - // Apply config (if not default config) - if (strcmp(pThreadConfig->szThreadName, sThreadName) == 0) - { - ApplyThreadConfig(threadHandle, *pThreadConfig); - } - - // Update FP exception mask for 3rd party thread - if (pThreadMetaData->m_threadId) - { - CryThreadUtil::EnableFloatExceptions(pThreadMetaData->m_threadId, (EFPE_Severity)g_cvars.sys_float_exceptions); - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnRegisterThirdPartyThread(const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Unregister 3rd party thread - bool ret = UnRegisterThirdPartyThreadImpl(strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadManager::UnRegisterThirdPartyThreadImpl(const char* sThreadName) -{ - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapIter res = m_spawnedThirdPartyThread.find(sThreadName); - if (res == m_spawnedThirdPartyThread.end()) - { - // Duplicate thread deletion - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": UnRegisterThirdPartyThread: Unable to unregister thread. Thread name \"%s\" could not be found. Double deletion? ", sThreadName); - return false; - } - - // Close thread handle - CryThreadUtil::CryCloseThreadHandle(res->second->m_threadHandle); - - // Delete reference from container - m_spawnedThirdPartyThread.erase(res); - return true; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadManager::GetThreadId(const char* sThreadName, ...) -{ - va_list args; - va_start(args, sThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), sThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Get thread name - threadID ret = GetThreadIdImpl(strThreadName); - - va_end(args); - return ret; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadManager::GetThreadIdImpl(const char* sThreadName) -{ - // Loop over internally spawned threads - { - AUTO_LOCK(m_spawnedThreadsLock); - - SpawnedThreadMapConstIter iter = m_spawnedThreads.begin(); - SpawnedThreadMapConstIter iterEnd = m_spawnedThreads.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadName.compare(sThreadName) == 0) - { - return iter->second->m_threadId; - } - } - } - - // Loop over third party threads - { - AUTO_LOCK(m_spawnedThirdPartyThreadsLock); - - SpawnedThirdPartyThreadMapConstIter iter = m_spawnedThirdPartyThread.begin(); - SpawnedThirdPartyThreadMapConstIter iterEnd = m_spawnedThirdPartyThread.end(); - - for (; iter != iterEnd; ++iter) - { - if (iter->second->m_threadName.compare(sThreadName) == 0) - { - return iter->second->m_threadId; - } - } - } - - return 0; -} - -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -static void EnableFPExceptionsForThread(threadID nThreadId, void* pData) -{ - EFPE_Severity eFPESeverity = *(EFPE_Severity*)pData; - CryThreadUtil::EnableFloatExceptions(nThreadId, eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::EnableFloatExceptions(EFPE_Severity eFPESeverity, threadID nThreadId /*=0*/) -{ - CryThreadUtil::EnableFloatExceptions(nThreadId, eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::EnableFloatExceptionsForEachOtherThread(EFPE_Severity eFPESeverity) -{ - ForEachOtherThread(EnableFPExceptionsForThread, &eFPESeverity); -} - -////////////////////////////////////////////////////////////////////////// -uint CThreadManager::GetFloatingPointExceptionMask() -{ - return CryThreadUtil::GetFloatingPointExceptionMask(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadManager::SetFloatingPointExceptionMask(uint nMask) -{ - CryThreadUtil::SetFloatingPointExceptionMask(nMask); -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::InitThreadSystem() -{ - m_pThreadManager = new CThreadManager(); - m_env.pThreadManager = m_pThreadManager; -} - -////////////////////////////////////////////////////////////////////////// -void CSystem::ShutDownThreadSystem() -{ - SAFE_DELETE(m_pThreadManager); -} diff --git a/Code/CryEngine/CrySystem/SystemWin32.cpp b/Code/CryEngine/CrySystem/SystemWin32.cpp index c694979a14..72c43bceed 100644 --- a/Code/CryEngine/CrySystem/SystemWin32.cpp +++ b/Code/CryEngine/CrySystem/SystemWin32.cpp @@ -46,8 +46,6 @@ #include #endif -#include "IDebugCallStack.h" - #if defined(APPLE) || defined(LINUX) #include #endif @@ -752,13 +750,6 @@ void CSystem::FatalError(const char* format, ...) } // Dump callstack. -#endif -#if defined (WIN32) - //Triggers a fatal error, so the DebugCallstack can create the error.log and terminate the application - IDebugCallStack::instance()->FatalError(szBuffer); -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMWIN32_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(SystemWin32_cpp) #endif CryDebugBreak(); @@ -800,8 +791,6 @@ void CSystem::ReportBug([[maybe_unused]] const char* format, ...) va_start(ArgList, format); azvsnprintf(szBuffer + strlen(sPrefix), MAX_WARNING_LENGTH - strlen(sPrefix), format, ArgList); va_end(ArgList); - - IDebugCallStack::instance()->ReportBug(szBuffer); #endif } @@ -910,10 +899,6 @@ void CSystem::LogSystemInfo() OSVERSIONINFO OSVerInfo; OSVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - // log Windows type - Win32SysInspect::GetOS(m_env.pi.winVer, m_env.pi.win64Bit, szBuffer, sizeof(szBuffer)); - CryLogAlways(szBuffer); - // log system language GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, LOCALE_SENGLANGUAGE, szLanguageBuffer, sizeof(szLanguageBuffer)); azsprintf(szBuffer, "System language: %s", szLanguageBuffer); diff --git a/Code/CryEngine/CrySystem/ThreadConfigManager.cpp b/Code/CryEngine/CrySystem/ThreadConfigManager.cpp deleted file mode 100644 index b582aac578..0000000000 --- a/Code/CryEngine/CrySystem/ThreadConfigManager.cpp +++ /dev/null @@ -1,577 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ThreadConfigManager.h" -#include "IConsole.h" -#include "System.h" -#include -#include -#include "CryUtils.h" -namespace -{ - const char* sCurThreadConfigFilename = ""; - const uint32 sPlausibleStackSizeLimitKB = (1024 * 100); // 100mb -} - -////////////////////////////////////////////////////////////////////////// -CThreadConfigManager::CThreadConfigManager() -{ - m_defaultConfig.szThreadName = "CryThread_Unnamed"; - m_defaultConfig.stackSizeBytes = 0; - m_defaultConfig.affinityFlag = -1; - m_defaultConfig.priority = THREAD_PRIORITY_NORMAL; - m_defaultConfig.bDisablePriorityBoost = false; - m_defaultConfig.paramActivityFlag = (SThreadConfig::TThreadParamFlag)~0; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetThreadConfig(const char* szThreadName, ...) -{ - va_list args; - va_start(args, szThreadName); - - // Format thread name - char strThreadName[THREAD_NAME_LENGTH_MAX]; - const int cNumCharsNeeded = azvsnprintf(strThreadName, CRY_ARRAY_COUNT(strThreadName), szThreadName, args); - if (cNumCharsNeeded > THREAD_NAME_LENGTH_MAX - 1) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": ThreadName \"%s\" has been truncated. Max characters allowed: %i. ", strThreadName, THREAD_NAME_LENGTH_MAX - 1); - } - - // Get Thread Config - const SThreadConfig* retThreasdConfig = GetThreadConfigImpl(strThreadName); - - va_end(args); - return retThreasdConfig; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetThreadConfigImpl(const char* szThreadName) -{ - // Get thread config for platform - ThreadConfigMapConstIter threatRet = m_threadConfig.find(CryFixedStringT(szThreadName)); - if (threatRet == m_threadConfig.end()) - { - // Search in wildcard setups - ThreadConfigMapConstIter wildCardIter = m_wildcardThreadConfig.begin(); - ThreadConfigMapConstIter wildCardIterEnd = m_wildcardThreadConfig.end(); - for (; wildCardIter != wildCardIterEnd; ++wildCardIter) - { - if (CryStringUtils::MatchWildcard(szThreadName, wildCardIter->second.szThreadName)) - { - // Store new thread config - SThreadConfig threadConfig = wildCardIter->second; - std::pair res; - res = m_threadConfig.insert(ThreadConfigMapPair(CryFixedStringT(szThreadName), threadConfig)); - - // Store name (ref to key) - SThreadConfig& rMapThreadConfig = res.first->second; - rMapThreadConfig.szThreadName = res.first->first.c_str(); - - // Return new thread config - return &res.first->second; - } - } - - // Failure case, no match found - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Unable to find config for thread:%s", szThreadName); - return &m_defaultConfig; - } - - // Return thread config - return &threatRet->second; -} - -////////////////////////////////////////////////////////////////////////// -const SThreadConfig* CThreadConfigManager::GetDefaultThreadConfig() const -{ - return &m_defaultConfig; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadConfig(const char* pcPath) -{ - // Adjust filename for OnDisk or in .pak file loading - char szFullPathBuf[AZ::IO::IArchive::MaxPath]; - gEnv->pCryPak->AdjustFileName(pcPath, szFullPathBuf, AZ_ARRAY_SIZE(szFullPathBuf), 0); - - // Open file - XmlNodeRef xmlRoot = GetISystem()->LoadXmlFromFile(szFullPathBuf); - if (!xmlRoot) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": File \"%s\" not found!", pcPath); - return false; - } - - // Load config for active platform - sCurThreadConfigFilename = pcPath; - const char* strPlatformId = IdentifyPlatform(); - CryFixedStringT<32> tmpPlatformStr; - bool retValue = false; - - // Try load common platform settings - tmpPlatformStr.Format("%s_Common", strPlatformId); - LoadPlatformConfig(xmlRoot, tmpPlatformStr.c_str()); - -#if defined(CRY_PLATFORM_DESKTOP) - // Handle PC specifically as we do not know the core setup of the executing machine. - // Try and find the next power of 2 core setup. Otherwise fallback to a lower power of 2 core setup spec - - // Try and load next pow of 2 setup for active pc core configuration - const unsigned int numCPUs = ((CSystem*)GetISystem())->GetCPUFeatures()->GetLogicalCPUCount(); - uint32 i = numCPUs; - for (; i > 0; --i) - { - tmpPlatformStr.Format("%s_%i", strPlatformId, i); - retValue = LoadPlatformConfig(xmlRoot, tmpPlatformStr.c_str()); - if (retValue) - { - break; - } - } - - if (retValue && i != numCPUs) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": (%s: %u core) Unable to find platform config \"%s\". Next valid config found was %s_%u.", - strPlatformId, numCPUs, tmpPlatformStr.c_str(), strPlatformId, i); - } - -#else - tmpPlatformStr.Format("%s", strPlatformId); - retValue = LoadPlatformConfig(xmlRoot, strPlatformId); -#endif - - // Print out info - if (retValue) - { - CryLogAlways(": Thread profile loaded: \"%s\" (%s) ", tmpPlatformStr.c_str(), pcPath); - } - else - { - // Could not find any matching platform - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Active platform identifier string \"%s\" not found in config \"%s\".", strPlatformId, sCurThreadConfigFilename); - } - - sCurThreadConfigFilename = ""; - return retValue; -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::ConfigLoaded() const -{ - return !m_threadConfig.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadPlatformConfig(const XmlNodeRef& rXmlRoot, const char* sPlatformId) -{ - // Validate node - if (!rXmlRoot->isTag("ThreadConfig")) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": Unable to find root xml node \"ThreadConfig\""); - return false; - } - - // Find active platform - const uint32 numPlatforms = rXmlRoot->getChildCount(); - for (uint32 i = 0; i < numPlatforms; ++i) - { - const XmlNodeRef xmlPlatformNode = rXmlRoot->getChild(i); - - // Is platform node - if (!xmlPlatformNode->isTag("Platform")) - { - continue; - } - - // Is has Name attribute - if (!xmlPlatformNode->haveAttr("Name")) - { - continue; - } - - // Is platform of interest - const char* platformName = xmlPlatformNode->getAttr("Name"); - if (_stricmp(sPlatformId, platformName) == 0) - { - // Load platform - LoadThreadDefaultConfig(xmlPlatformNode); - LoadPlatformThreadConfigs(xmlPlatformNode); - return true; - } - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadPlatformThreadConfigs(const XmlNodeRef& rXmlPlatformRef) -{ - // Get thread configurations for active platform - const uint32 numThreads = rXmlPlatformRef->getChildCount(); - for (uint32 j = 0; j < numThreads; ++j) - { - const XmlNodeRef xmlThreadNode = rXmlPlatformRef->getChild(j); - - if (!xmlThreadNode->isTag("Thread")) - { - continue; - } - - // Ensure thread config has name - if (!xmlThreadNode->haveAttr("Name")) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Thread node without \"name\" attribute encountered."); - continue; - } - - // Load thread config - SThreadConfig loadedThreadConfig = SThreadConfig(m_defaultConfig); - LoadThreadConfig(xmlThreadNode, loadedThreadConfig); - - // Get thread name and check if it contains wildcard characters - const char* szThreadName = xmlThreadNode->getAttr("Name"); - bool bWildCard = strchr(szThreadName, '*') ? true : false; - ThreadConfigMap& threadConfig = bWildCard ? m_wildcardThreadConfig : m_threadConfig; - - // Check for duplicate and override it with new config if found - if (threadConfig.find(szThreadName) != threadConfig.end()) - { - CryLogAlways(": [XML Parsing] Thread with name \"%s\" already loaded. Overriding with new configuration", szThreadName); - threadConfig[szThreadName] = loadedThreadConfig; - continue; - } - - // Store new thread config - std::pair res; - res = threadConfig.insert(ThreadConfigMapPair(CryFixedStringT(szThreadName), loadedThreadConfig)); - - // Store name (ref to key) - SThreadConfig& rMapThreadConfig = res.first->second; - rMapThreadConfig.szThreadName = res.first->first.c_str(); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CThreadConfigManager::LoadThreadDefaultConfig(const XmlNodeRef& rXmlPlatformRef) -{ - // Find default thread config node - const uint32 numNodes = rXmlPlatformRef->getChildCount(); - for (uint32 j = 0; j < numNodes; ++j) - { - const XmlNodeRef xmlNode = rXmlPlatformRef->getChild(j); - - // Load default config - if (xmlNode->isTag("ThreadDefault")) - { - LoadThreadConfig(xmlNode, m_defaultConfig); - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadAffinity(const XmlNodeRef& rXmlThreadRef, uint32& rAffinity, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* szValidCharacters = "-,0123456789"; - uint32 affinity = 0; - - // Validate node - if (!rXmlThreadRef->haveAttr("Affinity")) - { - return; - } - - // Validate token - CryFixedStringT<32> affinityRawStr(rXmlThreadRef->getAttr("Affinity")); - if (affinityRawStr.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"Affinity\" encountered"); - return; - } - - if (affinityRawStr.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_Affinity; - return; - } - - CryFixedStringT<32>::size_type nPos = affinityRawStr.find_first_not_of(" -,0123456789"); - if (nPos != CryFixedStringT<32>::npos) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, - ": [XML Parsing] Invalid character \"%c\" encountered in \"Affinity\" attribute. Valid characters:\"%s\" Offending token:\"%s\"", affinityRawStr.at(nPos), - szValidCharacters, affinityRawStr.c_str()); - return; - } - - // Tokenize comma separated string - int pos = 0; - CryFixedStringT<32> affnityTokStr = affinityRawStr.Tokenize(",", pos); - while (!affnityTokStr.empty()) - { - affnityTokStr.Trim(); - - long affinityId = strtol(affnityTokStr.c_str(), NULL, 10); - if (affinityId == LONG_MAX || affinityId == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unknown value \"%s\" encountered for attribute \"Affinity\"", affnityTokStr.c_str()); - return; - } - - // Allow scheduler to pick thread - if (affinityId == -1) - { - affinity = ~0; - break; - } - - // Set affinity bit - affinity |= BIT(affinityId); - - // Move to next token - affnityTokStr = affinityRawStr.Tokenize(",", pos); - } - - // Set affinity reference - rAffinity = affinity; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadPriority(const XmlNodeRef& rXmlThreadRef, int32& rPriority, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* szValidCharacters = "-,0123456789"; - - // Validate node - if (!rXmlThreadRef->haveAttr("Priority")) - { - return; - } - - // Validate token - CryFixedStringT<32> threadPrioStr(rXmlThreadRef->getAttr("Priority")); - threadPrioStr.Trim(); - if (threadPrioStr.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"Priority\" encountered"); - return; - } - - if (threadPrioStr.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_Priority; - return; - } - - // Test for character string (no numbers allowed) - if (threadPrioStr.find_first_of(szValidCharacters) == CryFixedStringT<32>::npos) - { - threadPrioStr.MakeLower(); - - // Set priority - if (threadPrioStr.compare("below_normal") == 0) - { - rPriority = THREAD_PRIORITY_BELOW_NORMAL; - } - else if (threadPrioStr.compare("normal") == 0) - { - rPriority = THREAD_PRIORITY_NORMAL; - } - else if (threadPrioStr.compare("above_normal") == 0) - { - rPriority = THREAD_PRIORITY_ABOVE_NORMAL; - } - else if (threadPrioStr.compare("idle") == 0) - { - rPriority = THREAD_PRIORITY_IDLE; - } - else if (threadPrioStr.compare("lowest") == 0) - { - rPriority = THREAD_PRIORITY_LOWEST; - } - else if (threadPrioStr.compare("highest") == 0) - { - rPriority = THREAD_PRIORITY_HIGHEST; - } - else if (threadPrioStr.compare("time_critical") == 0) - { - rPriority = THREAD_PRIORITY_TIME_CRITICAL; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Platform unsupported value \"%s\" encountered for attribute \"Priority\"", threadPrioStr.c_str()); - return; - } - } - // Test for number string (no alphabetical characters allowed) - else if (threadPrioStr.find_first_not_of(szValidCharacters) == CryFixedStringT<32>::npos) - { - long numValue = strtol(threadPrioStr.c_str(), NULL, 10); - if (numValue == LONG_MAX || numValue == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported number type \"%s\" for for attribute \"Priority\"", threadPrioStr.c_str()); - return; - } - - // Set priority - rPriority = numValue; - } - else - { - // String contains characters and numbers - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported type \"%s\" encountered for attribute \"Priority\". Token containers numbers and characters", threadPrioStr.c_str()); - return; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadDisablePriorityBoost(const XmlNodeRef& rXmlThreadRef, bool& rPriorityBoost, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - // Validate node - if (!rXmlThreadRef->haveAttr("DisablePriorityBoost")) - { - return; - } - - // Extract bool info - CryFixedStringT<16> sAttribToken(rXmlThreadRef->getAttr("DisablePriorityBoost")); - sAttribToken.Trim(); - sAttribToken.MakeLower(); - - if (sAttribToken.compare("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_PriorityBoost; - return; - } - else if (sAttribToken.compare("true") == 0 || sAttribToken.compare("1") == 0) - { - rPriorityBoost = true; - } - else if (sAttribToken.compare("false") == 0 || sAttribToken.compare("0") == 0) - { - rPriorityBoost = false; - } - else - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Unsupported bool type \"%s\" encountered for attribute \"DisablePriorityBoost\"", - rXmlThreadRef->getAttr("DisablePriorityBoost")); - return; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadStackSize(const XmlNodeRef& rXmlThreadRef, uint32& rStackSize, SThreadConfig::TThreadParamFlag& rParamActivityFlag) -{ - const char* sValidCharacters = "0123456789"; - - if (rXmlThreadRef->haveAttr("StackSizeKB")) - { - // Read stack size - CryFixedStringT<32> stackSize(rXmlThreadRef->getAttr("StackSizeKB")); - - // Validate stack size - if (stackSize.empty()) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Empty attribute \"StackSize\" encountered"); - return; - } - else if (stackSize.compareNoCase("ignore") == 0) - { - // Param is inactive, clear bit - rParamActivityFlag &= ~SThreadConfig::eThreadParamFlag_StackSize; - return; - } - else if (stackSize.find_first_not_of(sValidCharacters) == CryFixedStringT<32>::npos) - { - // Convert string to long - long stackSizeVal = strtol(stackSize.c_str(), NULL, 10); - if (stackSizeVal == LONG_MAX || stackSizeVal == LONG_MIN) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] Invalid number for \"StackSize\" encountered. \"%s\"", stackSize.c_str()); - return; - } - else if (stackSizeVal <= 0 || stackSizeVal > sPlausibleStackSizeLimitKB) - { - CryWarning(VALIDATOR_MODULE_SYSTEM, VALIDATOR_WARNING, ": [XML Parsing] \"StackSize\" value not plausible \"%" PRId64 "KB\"", (int64)stackSizeVal); - return; - } - - // Set stack size - rStackSize = stackSizeVal * 1024; // Convert to bytes - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::LoadThreadConfig(const XmlNodeRef& rXmlThreadRef, SThreadConfig& rThreadConfig) -{ - LoadAffinity(rXmlThreadRef, rThreadConfig.affinityFlag, rThreadConfig.paramActivityFlag); - LoadPriority(rXmlThreadRef, rThreadConfig.priority, rThreadConfig.paramActivityFlag); - LoadDisablePriorityBoost(rXmlThreadRef, rThreadConfig.bDisablePriorityBoost, rThreadConfig.paramActivityFlag); - LoadStackSize(rXmlThreadRef, rThreadConfig.stackSizeBytes, rThreadConfig.paramActivityFlag); -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadConfigManager::IdentifyPlatform() -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(ThreadConfigManager_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(ANDROID) - return "android"; -#elif defined(LINUX) - return "linux"; -#elif defined(APPLE) - return "mac"; -#elif defined(WIN32) || defined(WIN64) - return "pc"; -#else -#error "Undefined platform" -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CThreadConfigManager::DumpThreadConfigurationsToLog() -{ -#if !defined(RELEASE) - - // Print header - CryLogAlways("== Thread Startup Config List (\"%s\") ==", IdentifyPlatform()); - - // Print loaded default config - CryLogAlways(" (Default) 1. \"%s\" (StackSize:%uKB | Affinity:%u | Priority:%i | PriorityBoost:\"%s\")", m_defaultConfig.szThreadName, m_defaultConfig.stackSizeBytes / 1024, - m_defaultConfig.affinityFlag, m_defaultConfig.priority, m_defaultConfig.bDisablePriorityBoost ? "disabled" : "enabled"); - - // Print loaded thread configs - int listItemCounter = 1; - ThreadConfigMapConstIter iter = m_threadConfig.begin(); - ThreadConfigMapConstIter iterEnd = m_threadConfig.end(); - for (; iter != iterEnd; ++iter) - { - const SThreadConfig& threadConfig = iter->second; - CryLogAlways("%3d.\"%s\" %s (StackSize:%uKB %s | Affinity:%u %s | Priority:%i %s | PriorityBoost:\"%s\" %s)", ++listItemCounter, - threadConfig.szThreadName, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_ThreadName) ? "" : "(ignored)", - threadConfig.stackSizeBytes / 1024u, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_StackSize) ? "" : "(ignored)", - threadConfig.affinityFlag, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_Affinity) ? "" : "(ignored)", - threadConfig.priority, (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_Priority) ? "" : "(ignored)", - !threadConfig.bDisablePriorityBoost ? "enabled" : "disabled", (threadConfig.paramActivityFlag & SThreadConfig::eThreadParamFlag_PriorityBoost) ? "" : "(ignored)"); - } -#endif -} diff --git a/Code/CryEngine/CrySystem/ThreadConfigManager.h b/Code/CryEngine/CrySystem/ThreadConfigManager.h deleted file mode 100644 index ef0c9dca3d..0000000000 --- a/Code/CryEngine/CrySystem/ThreadConfigManager.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include -#include "IThreadConfigManager.h" - -/* -ThreadConfigManager: -Loads a thread configuration from an xml file and stores them. - -== XML File Layout and Rules: === - -= Platform names = -(case insensitive) -"ANDROID" -"PC" -"MAC" -etc. - -= Basic Layout = - - - - - -... - - - -... - - - -= Parser Order for Platform = -1. PlatformName_Common (valid for all potential platform configurations. Can be overridden by concert platform configuration) -2. PlatformName or PlatformName_X (for platforms with unknown CPU count where X is the number of potential cores. The equal or next lower matching configuration for the identified core count at runtime will be taken) - -Note: Overriding of thread configuration by later parsed configuration allowed. - -= and XML attributes = - -!!! -Note: Use "ignore" as value if you do not want the thread system to set the value specifically! - If a value is not defines the value of the parameter will be used. - This is useful when dealing with 3rdParty threads where you are not in control of the parameter setup. -!!! - -Name: - "x" (string) : Name of thread - "x*y" (string) : Name of thread with wildcard character - -Affinity: - "-1" : Put SW thread affinity in the hands of the scheduler - (default) - - "x" : Run thread on specified core - "x, y, ..." : Run thread on specified cores - -Priority: - "idle" : Hint to CryEngine to run thread with pre-set priority - "below_normal" : Hint to CryEngine to run thread with pre-set priority - "normal" : Hint to CryEngine to run thread with pre-set priority - (default) - - "above_normal" : Hint to CryEngine to run thread with pre-set priority - "highest" : Hint to CryEngine to run thread with pre-set priority - "time_critical" : Hint to CryEngine to run thread with pre-set priority - "x" (number) : User defined thread priority number - -StackSizeKB: - "0" : Let platform decide on the stack size - (default) - - "x" : Create thread with "x" KB of stack size - -DisablePriorityBoost: - "true" : Disable priority boosting - (default) - - "false" : Enable priority boosting -*/ - -class CThreadConfigManager - : public IThreadConfigManager -{ -public: - typedef std::map, SThreadConfig> ThreadConfigMap; - typedef std::pair, SThreadConfig> ThreadConfigMapPair; - typedef std::map, SThreadConfig>::iterator ThreadConfigMapIter; - typedef std::map, SThreadConfig>::const_iterator ThreadConfigMapConstIter; - -public: - CThreadConfigManager(); - ~CThreadConfigManager() - { - } - - // Called once during System startup. - // Loads the thread configuration for the executing platform from file. - virtual bool LoadConfig(const char* pcPath) override; - - // Returns true if a config has been loaded - virtual bool ConfigLoaded() const override; - - // Gets the thread configuration for the specified thread on the active platform. - // If no matching config is found a default configuration is returned - // (which does not have the same name as the search string). - virtual const SThreadConfig* GetThreadConfig(const char* sThreadName, ...) override; - virtual const SThreadConfig* GetDefaultThreadConfig() const override; - - virtual void DumpThreadConfigurationsToLog() override; - -private: - const char* IdentifyPlatform(); - - const SThreadConfig* GetThreadConfigImpl(const char* cThreadName); - - bool LoadPlatformConfig(const XmlNodeRef& rXmlRoot, const char* sPlatformId); - - void LoadPlatformThreadConfigs(const XmlNodeRef& rXmlPlatformRef); - bool LoadThreadDefaultConfig(const XmlNodeRef& rXmlPlatformRef); - void LoadThreadConfig(const XmlNodeRef& rXmlThreadRef, SThreadConfig& rThreadConfig); - - void LoadAffinity(const XmlNodeRef& rXmlThreadRef, uint32& rAffinity, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadPriority(const XmlNodeRef& rXmlThreadRef, int32& rPriority, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadDisablePriorityBoost(const XmlNodeRef& rXmlThreadRef, bool& rPriorityBoost, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - void LoadStackSize(const XmlNodeRef& rXmlThreadRef, uint32& rStackSize, SThreadConfig::TThreadParamFlag& rParamActivityFlag); - -private: - ThreadConfigMap m_threadConfig; // Note: The map key is referenced by as const char* by the value's storage class. Other containers may not support this behaviour as they will re-allocate memory as they grow/shrink. - ThreadConfigMap m_wildcardThreadConfig; - SThreadConfig m_defaultConfig; -}; diff --git a/Code/CryEngine/CrySystem/ThreadInfo.cpp b/Code/CryEngine/CrySystem/ThreadInfo.cpp deleted file mode 100644 index 14285215b8..0000000000 --- a/Code/CryEngine/CrySystem/ThreadInfo.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ThreadInfo.h" -#include "System.h" - -//////////////////////////////////////////////////////////////////////////// - - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define THREADINFO_CPP_SECTION_1 1 -#define THREADINFO_CPP_SECTION_2 2 -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADINFO_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(ThreadInfo_cpp) -#endif - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -#if AZ_LEGACY_CRYSYSTEM_TRAIT_THREADINFO_WINDOWS_STYLE -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::GetCurrentThreads(TThreadInfo& threadsOut) -{ - HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); - DWORD currProcessId = GetCurrentProcessId(); - if (h != INVALID_HANDLE_VALUE) - { - THREADENTRY32 te; - te.dwSize = sizeof(te); - if (Thread32First(h, &te)) - { - do - { - if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) - { - if (te.th32OwnerProcessID == currProcessId) - { - threadsOut[te.th32ThreadID] = CryThreadGetName(te.th32ThreadID); - } - } - te.dwSize = sizeof(te); - } while (Thread32Next(h, &te)); - } - CloseHandle(h); - } -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds /* = TThreadIds()*/, bool ignoreCurrThread /* = true*/) -{ - TThreadIds threadids = threadIds; - if (threadids.empty()) - { - TThreadInfo threads; - GetCurrentThreads(threads); - DWORD currThreadId = GetCurrentThreadId(); - for (TThreadInfo::iterator it = threads.begin(), end = threads.end(); it != end; ++it) - { - if (!ignoreCurrThread || it->first != currThreadId) - { - threadids.push_back(it->first); - } - } - } - for (TThreadIds::iterator it = threadids.begin(), end = threadids.end(); it != end; ++it) - { - SThreadHandle thread; - thread.Id = *it; - thread.Handle = OpenThread(THREAD_ALL_ACCESS, FALSE, *it); - threadsOut.push_back(thread); - } -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::CloseThreadHandles(const TThreads& threads) -{ - for (TThreads::const_iterator it = threads.begin(), end = threads.end(); it != end; ++it) - { - CloseHandle(it->Handle); - } -} - -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////// -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADINFO_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(ThreadInfo_cpp) -#elif defined(LINUX) || defined(APPLE) -void SThreadInfo::GetCurrentThreads(TThreadInfo& threadsOut) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds /* = TThreadIds()*/, bool ignoreCurrThread /* = true*/) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -void SThreadInfo::CloseThreadHandles(const TThreads& threads) -{ - assert(false); // not implemented! -} - -//////////////////////////////////////////////////////////////////////////// -#endif diff --git a/Code/CryEngine/CrySystem/ThreadInfo.h b/Code/CryEngine/CrySystem/ThreadInfo.h deleted file mode 100644 index 4bcacf71d5..0000000000 --- a/Code/CryEngine/CrySystem/ThreadInfo.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_THREADINFO_H -#define CRYINCLUDE_CRYSYSTEM_THREADINFO_H -#pragma once - - -struct SThreadInfo -{ -public: - struct SThreadHandle - { - HANDLE Handle; - uint32 Id; - }; - - typedef std::vector TThreadIds; - typedef std::vector TThreads; - typedef std::map TThreadInfo; - - // returns thread info - static void GetCurrentThreads(TThreadInfo& threadsOut); - - // fills threadsOut vector with thread handles of given thread ids; if threadIds vector is emtpy it fills all running threads - // if ignoreCurrThread is true it will not return the current thread - static void OpenThreadHandles(TThreads& threadsOut, const TThreadIds& threadIds = TThreadIds(), bool ignoreCurrThread = true); - - // closes thread handles; should be called whenever GetCurrentThreads was called! - static void CloseThreadHandles(const TThreads& threads); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_THREADINFO_H diff --git a/Code/CryEngine/CrySystem/ThreadTask.cpp b/Code/CryEngine/CrySystem/ThreadTask.cpp deleted file mode 100644 index d1ae7304e6..0000000000 --- a/Code/CryEngine/CrySystem/ThreadTask.cpp +++ /dev/null @@ -1,1046 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "ThreadTask.h" -#include "CPUDetect.h" -#include "IConsole.h" -#include "System.h" - -#if defined(AZ_RESTRICTED_PLATFORM) -#undef AZ_RESTRICTED_SECTION -#define THREADTASK_CPP_SECTION_1 1 -#define THREADTASK_CPP_SECTION_2 2 -#endif - -#ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -#include -#endif //WIN32 - -#include "BitFiddling.h" - -#if defined(ANDROID) -#include -#include -#endif -#if defined(LINUX) - -#endif -#if defined(APPLE) -// include for thread_policy_set -#include -#include -#endif - -#include - -////////////////////////////////////////////////////////////////////////// -CThreadTask_Thread::CThreadTask_Thread(CThreadTaskManager* pTaskMgr, const char* sName, - int nIndex, int nProcessor, int nThreadPriority, ThreadPoolHandle poolHandle /* = -1*/) - : tasks(64) -{ - m_nThreadPriority = nThreadPriority; - m_pTaskManager = pTaskMgr; - m_sThreadName = sName; - bStopThread = false; - bRunning = false; - m_hThreadHandle = 0; - m_nThreadIndex = nIndex; - m_nProcessor = nProcessor; - m_poolHandle = poolHandle; -} - -CThreadTask_Thread::~CThreadTask_Thread() -{ - while (!tasks.empty()) - { - tasks.pop()->m_pThread = 0; - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::SingleUpdate() -{ - while (true) - { - m_pProcessingTask = NULL; - - { - if (tasks.empty()) - { - break; - } - // remove from queue - m_pProcessingTask = tasks.pop(); - } - - if (m_pProcessingTask) - { - m_pProcessingTask->m_pTask->OnUpdate(); - } - - if (m_pProcessingTask) // push it back - { - tasks.push(m_pProcessingTask); - } - - if (bStopThread) - { - break; - } - } - - if (m_poolHandle != -1) // if this thread is in the pool, we need to reassign some tasks for it - { - m_pTaskManager->BalanceThreadInPool(this); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Run() -{ - Init(); - - bRunning = true; - while (!bStopThread) - { - while (tasks.empty() && !bStopThread) - { - m_waitForTasks.Wait(); - } - - if (!bStopThread) - { - SingleUpdate(); - } - } - bRunning = false; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Cancel() -{ - bStopThread = true; - m_waitForTasks.Set(); - Stop(); - - // for blocking thread notify the blocking task - if (m_nThreadIndex == -1) - { - if (m_pProcessingTask && m_pProcessingTask->m_params.nFlags & THREAD_TASK_BLOCKING) // check if we have a blocking task - { - if (m_pProcessingTask->m_pTask) // cancel it - { - m_pProcessingTask->m_pTask->Stop(); - } - } - } - - WaitForThread(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::Terminate() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::AddTask(SThreadTaskInfo* pTaskInfo) -{ - pTaskInfo->m_pThread = this; - tasks.push(pTaskInfo); - m_waitForTasks.Set(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::RemoveTask(SThreadTaskInfo* pTaskInfo) -{ - if (!pTaskInfo) - { - return; - } - - if (m_pProcessingTask == pTaskInfo) - { - pTaskInfo->m_pThread = NULL; - m_pProcessingTask = NULL; - return; - } - - // search for task(mirrored search because of locklessness) - bool bFound = false; - Tasks newTasks; - while (!tasks.empty()) - { - SThreadTaskInfo* pTask = tasks.pop(); - if (pTask == pTaskInfo) - { - pTaskInfo->m_pThread = NULL; - bFound = true; - break; - } - if (pTask) - { - newTasks.push(pTask); - } - } - (void)bFound; - // Don't assert if newTasks is empty. There is a thread race condition between - // the thread shutting down and this code being executed (both update/use - // m_pProcessTask with no locks). newTasks will be empty - // and bFound == false when the race condition is won by the task thread and - // not by the thread that is executing this code - CRY_ASSERT(bFound || newTasks.empty()); - - // fill back - while (!newTasks.empty()) - { - tasks.push(newTasks.pop()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTask_Thread::RemoveAllTasks() -{ - while (!tasks.empty()) - { - tasks.pop()->m_pThread = NULL; - } -} - -void CThreadTask_Thread::Init() -{ -#if AZ_TRAIT_OS_USE_WINDOWS_THREADS - m_hThreadHandle = GetCurrentThread(); -#endif - - // Name this thread. - CryThreadSetName(GetCurrentThreadId(), m_sThreadName); - - // Set affinity - if (m_nProcessor > 0) - { - ChangeProcessor(m_nProcessor); - } -#if defined(WIN32) - ((CSystem*)gEnv->pSystem)->EnableFloatExceptions(g_cvars.sys_float_exceptions); -#endif -} - -void CThreadTask_Thread::ChangeProcessor(int nProcessor) -{ - // note this function is not thread-safe - m_nProcessor = nProcessor; -#if defined(WIN32) - DWORD_PTR mask1, mask2; - GetProcessAffinityMask(GetCurrentProcess(), &mask1, &mask2); - if (BIT64(m_nProcessor) & mask1) // Check if we have this affinity - { - SetThreadAffinityMask(m_hThreadHandle, BIT64(m_nProcessor)); - } - else // Reserve CPU 1 for main thread. - { - SetThreadAffinityMask(m_hThreadHandle, (mask1 & (~1))); - } - assert(THREAD_PRIORITY_IDLE <= m_nThreadPriority && m_nThreadPriority <= THREAD_PRIORITY_TIME_CRITICAL); - SetThreadPriority(m_hThreadHandle, m_nThreadPriority); -#define AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADTASK_CPP_SECTION_1 -#include AZ_RESTRICTED_FILE(ThreadTask_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(ANDROID) - int err, syscallres; - pid_t pid = gettid(); - syscallres = syscall(__NR_sched_setaffinity, pid, sizeof(nProcessor), &nProcessor); - if (syscallres) - { - err = errno; - CryLog("Error in the syscall setaffinity: mask=%d=0x%x sysconf#=%ld err=%d=0x%x", nProcessor, nProcessor, sysconf(_SC_NPROCESSORS_ONLN), err, err); - } -#elif defined(LINUX) - // Check if the processor is valid - assert(nProcessor < sysconf(_SC_NPROCESSORS_ONLN)); - cpu_set_t cpuset; - CPU_ZERO(&cpuset); - CPU_SET(nProcessor, &cpuset); - pthread_t current_thread = pthread_self(); - int ret = pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset); - (void) ret; - // check if the operation completed succesfully - assert(ret == 0 && "ChangeProcessor operation failed"); -#elif defined(APPLE) - assert(nProcessor != 0 && "CThreadTask_Thread::ChangeProcessor - If " - "nProcessor is equal to 0, the default afinity will be applied " - "to the thread. Can be fixed by incrementing nProcess by 1."); - thread_affinity_policy_data_t thread_affinity; - thread_affinity.affinity_tag = nProcessor; - thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_AFFINITY_POLICY, (thread_policy_t)&thread_affinity, THREAD_AFFINITY_POLICY_COUNT); - //CryWarning(VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING, "CThreadTask_Thread::ChangeProcessor: Feature is not supported on Mac OS X."); -#else - assert(0); -#endif -} - -////////////////////////////////////////////////////////////////////////// -CThreadTaskManager::CThreadTaskManager() -{ - m_nMaxThreads = 1; - - SetThreadName(GetCurrentThreadId(), "Main"); - - m_systemThreads.push_back(GetCurrentThreadId()); -} - -////////////////////////////////////////////////////////////////////////// -CThreadTaskManager::~CThreadTaskManager() -{ - CloseThreads(); - - AUTO_MODIFYLOCK(m_threadsPoolsLock); - while (!m_threadsPools.empty()) - { -#if !defined(NDEBUG) - bool res = -#endif - DestroyThreadsPool(m_threadsPools.begin()->m_hHandle); - assert(res); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::StopAllThreads() -{ - if (m_threads.empty()) - { - return; - } - - size_t i; - // Start from 2nd thread, 1st is main thread. - for (i = 1; i < m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - pThread->Cancel(); - } - bool bAllStoped = true; - do - { - bAllStoped = true; - CrySleep(10); - for (i = 1; i < m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - // Needs ReadWriteBarrier here. - if (pThread->bRunning) - { - bAllStoped = false; - } - } - } - while (!bAllStoped); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::CloseThreads() -{ - if (m_threads.size() > 0) - { - StopAllThreads(); - } - for (size_t i = MAIN_THREAD_INDEX, numThreads = m_threads.size(); i < numThreads; i++) - { - delete m_threads[i]; - } - m_threads.clear(); - //make sure blocking threads are cancelled - for (bool repeat = true; repeat; ) - { - CThreadTask_Thread* thr = NULL; - { - CryAutoCriticalSection lock(m_threadRemove); - - if (!m_blockingThreads.empty()) - { - thr = *m_blockingThreads.rbegin(); - m_blockingThreads.pop_back(); - } - } - - if (thr) - { - thr->Cancel(); - delete thr; - } - else - { - repeat = false; - } - } - - m_blockingThreads.clear(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::InitThreads() -{ - m_nMaxThreads = gEnv->IsDedicated() ? 1 : 4; - CloseThreads(); - - // Create a dummy thread that is used for main thread. - m_threads.resize(1); - m_threads[0] = new CThreadTask_Thread(this, "Main Thread", 0, AFFINITY_MASK_MAINTHREAD, THREAD_PRIORITY_NORMAL); - - CCpuFeatures* pCPU = ((CSystem*)gEnv->pSystem)->GetCPUFeatures(); - - int nThreads = min((int)m_nMaxThreads, (int)pCPU->GetCPUCount()); - - if (nThreads < 1) - { - nThreads = 1; - } - int nAddThreads = nThreads - 1; - - char str[32]; - m_threads.resize(1 + nAddThreads); - for (int i = 0; i < nAddThreads; i++) - { - int nIndex = i + 1; - int nCPU = i + 1; - sprintf_s(str, "TaskThread%d", i); - if (i < m_nMaxThreads) - { - nCPU = ((CSystem*)gEnv->pSystem)->m_sys_TaskThread_CPU[i]->GetIVal(); - } - - // Clamp to random thread between 1 and max, avoid cpu 0 with main thread - if (nCPU >= nThreads) - { - nCPU = (rand() % (nThreads - 1)) + 1; - } - m_threads[nIndex] = new CThreadTask_Thread(this, str, nIndex, nCPU, THREAD_PRIORITY_NORMAL); - m_threads[nIndex]->Start(0, str, THREAD_PRIORITY_NORMAL, SIMPLE_THREAD_STACK_SIZE_KB * 1024); - } - RescheduleTasks(); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::SetMaxThreadCount(int nMaxThreads) -{ - if (nMaxThreads == m_nMaxThreads) - { - return; - } - - m_nMaxThreads = nMaxThreads; - - bool bReallocateThreads = false; - if (m_nMaxThreads < (int)m_threads.size()) - { - bReallocateThreads = true; - } - if (m_nMaxThreads > (int)m_threads.size()) - { - CCpuFeatures* pCPU = ((CSystem*)gEnv->pSystem)->GetCPUFeatures(); - if (m_threads.size() < pCPU->GetCPUCount()) - { - bReallocateThreads = true; - } - } - if (bReallocateThreads) - { - CloseThreads(); - InitThreads(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options) -{ - if (!pTask) - { - assert(0); - return; - } - SThreadTaskInfo* pTaskInfo = pTask->GetTaskInfo(); - pTaskInfo->m_pTask = pTask; - pTaskInfo->m_params = options; - - if ((options.nFlags & THREAD_TASK_BLOCKING) == 0) - { - ScheduleTask(pTaskInfo); - } - else - { - CryAutoCriticalSection lock(m_threadRemove); - // Blocking task will need it`s own thread. - const int threadPriority = THREAD_PRIORITY_NORMAL; - CThreadTask_Thread* pThread = - new CThreadTask_Thread(this, options.name, -1, options.nPreferedThread, threadPriority); - pThread->Start(0, (char*)options.name, threadPriority, options.nStackSizeKB * 1024); - pThread->AddTask(pTaskInfo); - - m_blockingThreads.push_back(pThread); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::UnregisterTask(IThreadTask* pTask) -{ - assert(pTask); - if (!pTask) - { - return; - } - SThreadTaskInfo* pTaskInfo = pTask->GetTaskInfo(); - assert(pTaskInfo); - - IThreadTask_Thread* pThread = pTaskInfo->m_pThread; - uint32 flags = pTaskInfo->m_params.nFlags; - - // Remove from thread. - if (pThread) - { - pThread->RemoveTask(pTaskInfo); - } - - pTask->Stop(); - - if (flags & THREAD_TASK_BLOCKING) - { - CThreadTask_Thread* thr = NULL; - { - CryAutoCriticalSection lock(m_threadRemove); - Threads::iterator end = m_blockingThreads.end(); - Threads::iterator toErase = std::find(m_blockingThreads.begin(), end, pThread); - - if (toErase != end) // impossible to find anything. no push_back done on m_blockingThreads - { - thr = *toErase; - m_blockingThreads.erase(toErase); - } - } - - if (thr) - { - thr->Cancel(); - delete thr; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::ScheduleTask(SThreadTaskInfo* pTaskInfo) -{ - size_t i; - - if (pTaskInfo->m_pThread) - { - assert(0); - pTaskInfo->m_pThread->RemoveTask(pTaskInfo); - } - - CThreadTask_Thread* pGoodThread = NULL; - - if (pTaskInfo->m_params.nFlags & THREAD_TASK_ASSIGN_TO_POOL) - { - AUTO_READLOCK(m_threadsPoolsLock); - - // find the pool - CThreadsPool* pool = NULL; - size_t nSize = m_threadsPools.size(); - for (i = 0; i < nSize; ++i) - { - if (m_threadsPools[i].m_hHandle == pTaskInfo->m_params.nThreadsGroupId) - { - pool = &m_threadsPools[i]; - } - } - - if (pool) - { - // Find available thread for the task. - for (i = 0; i < (int)pool->m_Threads.size(); ++i) - { - CThreadTask_Thread* pThread = pool->m_Threads[i]; - const bool threadIsFree = pThread->tasks.empty() && pThread->m_pProcessingTask == NULL; - if (threadIsFree || pGoodThread == NULL) - { - pGoodThread = pThread; - if (threadIsFree) - { - break; - } - } - } - } - else - { - gEnv->pLog->LogError("[Error]Task manager: threads pool not found!"); - assert(0); - } - } - else if (pTaskInfo->m_params.nPreferedThread >= 0 && pTaskInfo->m_params.nPreferedThread < (int)m_threads.size()) - { - assert((int)m_threads.size() > pTaskInfo->m_params.nPreferedThread); - // Assign task to desired thread. - pGoodThread = m_threads[pTaskInfo->m_params.nPreferedThread]; - } - else - { - // Find available thread for the task. - for (i = MAIN_THREAD_INDEX + 1; i < (int)m_threads.size(); i++) - { - CThreadTask_Thread* pThread = m_threads[i]; - PREFAST_ASSUME(pThread); - if (pThread->tasks.empty() || pGoodThread == NULL) - { - pGoodThread = pThread; - if (pThread->tasks.empty()) - { - break; - } - } - } - } - if (!pGoodThread && !m_threads.empty()) - { - // Assign to last thread. - pGoodThread = m_threads[m_threads.size() - 1]; - } - - if (pGoodThread) - { - pGoodThread->AddTask(pTaskInfo); - } - else - { - m_unassignedTasks.push(pTaskInfo); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RescheduleTasks() -{ - // Un-schedule all tasks. - for (int i = 0; i < (int)m_threads.size(); i++) - { - while (!m_threads[i]->tasks.empty()) - { - SThreadTaskInfo* pTask = m_threads[i]->tasks.pop(); - if (!pTask) - { - break; - } - if (pTask->m_params.nFlags & THREAD_TASK_BLOCKING) // Do not schedule blocking tasks. - { - m_threads[i]->tasks.push(pTask); - break; - } - pTask->m_pThread = NULL; - m_unassignedTasks.push(pTask); - } - } - - while (!m_unassignedTasks.empty()) - { - ScheduleTask(m_unassignedTasks.pop()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::OnUpdate() -{ - AZ_TRACE_METHOD(); - FUNCTION_PROFILER_LEGACYONLY(GetISystem(), PROFILE_SYSTEM); - - // Emulate single update of the main thread. - if (m_threads[0]) - { - m_threads[0]->SingleUpdate(); - } - - // assign unassigned tasks - while (!m_unassignedTasks.empty()) - { - ScheduleTask(m_unassignedTasks.pop()); - } - - // balance all pools - AUTO_READLOCK(m_threadsPoolsLock); - size_t nSize = m_threadsPools.size(); - for (size_t itPool = 0; itPool < nSize; ++itPool) - { - BalanceThreadsPool(m_threadsPools[itPool].m_hHandle); - } -} - -struct THREADNAME_INFO_TASK -{ - DWORD dwType; - LPCSTR szName; - DWORD dwThreadID; - DWORD dwFlags; -}; - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::SetThreadName(threadID dwThreadId, const char* sThreadName) -{ - if (dwThreadId == (THREADID_NULL)) - { - dwThreadId = GetCurrentThreadId(); - } - -#if defined(AZ_PROFILE_TELEMETRY) && AZ_TRAIT_OS_USE_WINDOWS_THREADS - AZStd::thread_desc desc; - desc.m_name = sThreadName; - // we broadcast to the "client" bus and then to the "driller" (profiling) bus - AZStd::ThreadEventBus::Broadcast(&AZStd::ThreadEventBus::Events::OnThreadEnter, AZStd::thread::id(dwThreadId), &desc); - AZStd::ThreadDrillerEventBus::Broadcast(&AZStd::ThreadDrillerEventBus::Events::OnThreadEnter, AZStd::thread::id(dwThreadId), &desc); -#endif - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_THREADTASK_EXCEPTIONS - ////////////////////////////////////////////////////////////////////////// - // Raise exception to set thread name for debugger. - ////////////////////////////////////////////////////////////////////////// - THREADNAME_INFO_TASK threadName; - threadName.dwType = 0x1000; - threadName.szName = sThreadName; - threadName.dwThreadID = dwThreadId; - threadName.dwFlags = 0; - - __try - { - RaiseException(0x406D1388, 0, sizeof(threadName) / sizeof(DWORD), (ULONG_PTR*)&threadName); - } - __except (EXCEPTION_CONTINUE_EXECUTION) - { - } -#endif - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION THREADTASK_CPP_SECTION_2 -#include AZ_RESTRICTED_FILE(ThreadTask_cpp) -#endif - - { - m_threadNameLock.Lock(); - m_threadNames[dwThreadId] = sThreadName; - m_threadNameLock.Unlock(); - } -} - -////////////////////////////////////////////////////////////////////////// -const char* CThreadTaskManager::GetThreadName(threadID dwThreadId) -{ - CryAutoCriticalSection lock(m_threadNameLock); - ThreadNames::const_iterator it = m_threadNames.find(dwThreadId); - if (it != m_threadNames.end()) - { - return it->second.c_str(); - } - - return ""; -} - -////////////////////////////////////////////////////////////////////////// -threadID CThreadTaskManager::GetThreadByName(const char* sThreadName) -{ - CryAutoCriticalSection lock(m_threadNameLock); - for (ThreadNames::const_iterator it = m_threadNames.begin(); it != m_threadNames.end(); ++it) - { - if (it->second.compareNoCase(sThreadName) == 0) - { - return it->first; - } - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::AddSystemThread(threadID nThreadId) -{ - CryAutoCriticalSection lock(m_systemThreadsLock); - m_systemThreads.push_back(nThreadId); -} - -////////////////////////////////////////////////////////////////////////// -void CThreadTaskManager::RemoveSystemThread(threadID nThreadId) -{ - CryAutoCriticalSection lock(m_systemThreadsLock); - stl::find_and_erase(m_systemThreads, nThreadId); -} - -////////////////////////////////////////////////////////////////////////// -ThreadPoolHandle CThreadTaskManager::CreateThreadsPool(const ThreadPoolDesc& desc) -{ - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - ThreadPoolHandle newId = m_threadsPools.empty() ? 0 : m_threadsPools.rbegin()->m_hHandle + 1; - - if (desc.AffinityMask == INVALID_AFFINITY) - { - assert(0); - return -1; - } - - // create the pool - m_threadsPools.push_back(CThreadsPool()); - CThreadsPool& rPool = m_threadsPools.back(); - - // assign the new handle - rPool.m_hHandle = newId; - - // fill up the desc - rPool.m_pDescription = desc; - - Threads& threads = rPool.m_Threads; - - size_t threadNameSize = desc.sPoolName.size() + 30; - std::vector threadName(threadNameSize); - uint32 iThread = 0; - for (uint32 nIndex = 0; nIndex < sizeof(desc.AffinityMask) * 8; ++nIndex) - { - // check if we have affinity mask bit set for this thread - if (!(desc.AffinityMask & (1 << nIndex))) - { - continue; - } - - const int32 nThreadPriority = (desc.nThreadPriority == -1) ? THREAD_PRIORITY_NORMAL : desc.nThreadPriority; - const int32 nThreadStackSizeKB = (desc.nThreadStackSizeKB == -1) ? SIMPLE_THREAD_STACK_SIZE_KB : desc.nThreadStackSizeKB; - - // create a thread - sprintf_s(&threadName[0], threadNameSize, "%s%d", desc.sPoolName.c_str(), iThread); - CThreadTask_Thread* thread = new CThreadTask_Thread(this, &threadName[0], iThread, nIndex, nThreadPriority, newId); - - // start thread - thread->Start(0, (char*)&threadName[0], nThreadPriority, nThreadStackSizeKB * 1024); - - // add to pool - threads.push_back(thread); - - iThread++; - } - - return newId; -} - -const bool CThreadTaskManager::DestroyThreadsPool(const ThreadPoolHandle& handle) -{ - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - CThreadsPool* pPool = NULL; - size_t nSize = m_threadsPools.size(); - size_t iPool = 0; - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - Threads& threads = pPool->m_Threads; - size_t nThreads = threads.size(); - for (size_t iThread = 0; iThread < nThreads; ++iThread) - { - CThreadTask_Thread* pThread = threads[iThread]; - PREFAST_ASSUME(pThread); - pThread->Cancel(); - assert(!(pThread->bRunning)); - delete pThread; - } - - m_threadsPools.erase(m_threadsPools.begin() + iPool); - return true; - } - return false; -} - -const bool CThreadTaskManager::GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const -{ - AUTO_READLOCK(m_threadsPoolsLock); - - const CThreadsPool* pPool = NULL; - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - if (pDesc) - { - *pDesc = pPool->m_pDescription; - return true; - } - } - - return false; -} - -const bool CThreadTaskManager::SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask) -{ - CThreadsPool* pPool = NULL; - - AUTO_MODIFYLOCK(m_threadsPoolsLock); - - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - return pPool->SetAffinity(AffinityMask); - } - - return false; -} - -void CThreadTaskManager::BalanceThreadsPool(const ThreadPoolHandle& handle) -{ - CThreadsPool* pPool = NULL; - - AUTO_READLOCK(m_threadsPoolsLock); - - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == handle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - // balancing tasks in the pool - for (size_t itThread = 0, nThreads = pPool->m_Threads.size(); itThread < nThreads; ++itThread) - { - CThreadTask_Thread* pThread = pPool->m_Threads[itThread]; - if (pThread->tasks.empty()) // found free thread(without tasks) - { - BalanceThreadInPool(pThread, &pPool->m_Threads); - } - } - } - else - { - assert(0); - } -} - -void CThreadTaskManager::BalanceThreadInPool(CThreadTask_Thread* pFreeThread, Threads* pThreads /* = NULL */) -{ - assert(pFreeThread->m_poolHandle != -1); - - AUTO_READLOCK(m_threadsPoolsLock); - - if (pThreads == NULL) - { - CThreadsPool* pPool = NULL; - size_t iPool = 0, nSize = m_threadsPools.size(); - for (; iPool < nSize; ++iPool) - { - if (m_threadsPools[iPool].m_hHandle == pFreeThread->m_poolHandle) - { - pPool = &m_threadsPools[iPool]; - break; - } - } - - if (pPool) - { - pThreads = &pPool->m_Threads; - } - } - assert(pThreads); - PREFAST_ASSUME(pThreads); - // search for thread with tasks - for (size_t itAnotherThread = 0, nThreads = pThreads->size(); itAnotherThread < nThreads; ++itAnotherThread) - { - CThreadTask_Thread* pAnotherThread = (*pThreads)[itAnotherThread]; - if (pFreeThread == pAnotherThread) - { - continue; - } - if (pAnotherThread->tasks.empty()) - { - continue; - } - - // we found a thread with more than one task - SThreadTaskInfo* pTask = pAnotherThread->tasks.pop(); - if (pTask) - { - assert(pTask->m_pThread == pAnotherThread); - // reassign the last task to another thread - pFreeThread->AddTask(pTask); - break; // process next free thread - } - } -} - -void CThreadTaskManager::MarkThisThreadForDebugging(const char* name, bool bDump) -{ - bDump ? ::MarkThisThreadForDebugging(name) : ::UnmarkThisThreadFromDebugging(); -} - - -const bool CThreadTaskManager::CThreadsPool::SetAffinity(const ThreadPoolAffinityMask AffinityMask) -{ - // check if all threads in the pool are covered by the bits of this mask - if (CountBits(AffinityMask) != m_Threads.size()) - { - // wrong arguments - return false; - } - - // update affinity mask - m_pDescription.AffinityMask = AffinityMask; - - size_t itThread = 0; - for (uint32 nProcessorIndex = 0; nProcessorIndex < sizeof(AffinityMask) * 8; ++nProcessorIndex) - { - assert(itThread < m_Threads.size()); - // check if we have affinity mask bit set for this thread - if (!(AffinityMask & (1 << nProcessorIndex))) - { - continue; - } - - // changin thread's affinity in the pool - m_Threads[itThread]->ChangeProcessor(nProcessorIndex); - ++itThread; - } - return true; -} diff --git a/Code/CryEngine/CrySystem/ThreadTask.h b/Code/CryEngine/CrySystem/ThreadTask.h deleted file mode 100644 index e528fedf5f..0000000000 --- a/Code/CryEngine/CrySystem/ThreadTask.h +++ /dev/null @@ -1,181 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYSYSTEM_THREADTASK_H -#define CRYINCLUDE_CRYSYSTEM_THREADTASK_H -#pragma once - - -#include -#include -#include - -#define MAIN_THREAD_INDEX 0 - -class CThreadTask_Thread; - - -void MarkThisThreadForDebugging(const char* name); -void UnmarkThisThreadFromDebugging(); -void UpdateFPExceptionsMaskForThreads(); - - -class CThreadTaskManager; -/// -struct IThreadTaskRunnable -{ - virtual ~IThreadTaskRunnable(){} - virtual void Run() = 0; - virtual void Cancel() = 0; -}; -////////////////////////////////////////////////////////////////////////// -class CThreadTask_Thread - : public CryThread - , public IThreadTask_Thread -{ -protected: - void Init(); -public: - CThreadTask_Thread(CThreadTaskManager* pTaskMgr, const char* sName, int nThreadIndex, int nProcessor, int nThreadPriority, ThreadPoolHandle poolHandle = -1); - ~CThreadTask_Thread(); - - // see IThreadTaskRunnable, CryThread<> - void Run() override; - void Cancel() override; - - // see CryThread<> - void Terminate() override; - - // IThreadTask_Thread - void AddTask(SThreadTaskInfo* pTaskInfo) override; - void RemoveTask(SThreadTaskInfo* pTaskInfo) override; - void RemoveAllTasks() override; - void SingleUpdate() override; - - void ChangeProcessor(int nProcessor); -public: - CThreadTaskManager* m_pTaskManager; - string m_sThreadName; - int m_nThreadIndex; // -1 means the thread is blocking - int m_nProcessor; - int m_nThreadPriority; - - THREAD_HANDLE m_hThreadHandle; - - // Tasks running on this thread. - typedef CryMT::CLocklessPointerQueue > Tasks; - Tasks tasks; - - // The task is being processing now - SThreadTaskInfo* m_pProcessingTask; - - CryEvent m_waitForTasks; - - // Set to true when thread must stop. - volatile bool bStopThread; - volatile bool bRunning; - - // handle of threads pool which this thread belongs to(if any) - ThreadPoolHandle m_poolHandle; -}; - -////////////////////////////////////////////////////////////////////////// -class CThreadTaskManager - : public IThreadTaskManager -{ -private: - typedef std::vector > Threads; - // note: this struct is auxilary and NOT thread-safe - // it is only for internal use inside the task manager - struct CThreadsPool - { - ThreadPoolHandle m_hHandle; - Threads m_Threads; - ThreadPoolDesc m_pDescription; - const bool SetAffinity(const ThreadPoolAffinityMask AffinityMask); - const bool operator < (const CThreadsPool& p) const { return m_hHandle < p.m_hHandle; } - const bool operator == (const CThreadsPool& p) const { return m_hHandle == p.m_hHandle; } - }; - - typedef std::vector ThreadsPools; - -public: - CThreadTaskManager(); - ~CThreadTaskManager(); - - void InitThreads(); - void CloseThreads(); - void StopAllThreads(); - - ////////////////////////////////////////////////////////////////////////// - // IThreadTaskManager - ////////////////////////////////////////////////////////////////////////// - virtual void RegisterTask(IThreadTask* pTask, const SThreadTaskParams& options); - virtual void UnregisterTask(IThreadTask* pTask); - virtual void SetMaxThreadCount(int nMaxThreads); - virtual void SetThreadName(threadID dwThreadId, const char* sThreadName); - virtual const char* GetThreadName(threadID dwThreadId); - virtual threadID GetThreadByName(const char* sThreadName); - - // Thread pool framework - virtual ThreadPoolHandle CreateThreadsPool(const ThreadPoolDesc& desc); - virtual const bool DestroyThreadsPool(const ThreadPoolHandle& handle); - virtual const bool GetThreadsPoolDesc(const ThreadPoolHandle handle, ThreadPoolDesc* pDesc) const; - virtual const bool SetThreadsPoolAffinity(const ThreadPoolHandle handle, const ThreadPoolAffinityMask AffinityMask); - - virtual void MarkThisThreadForDebugging(const char* name, bool bDump); - ////////////////////////////////////////////////////////////////////////// - - // This is on update function of the main thread. - void OnUpdate(); - - void AddSystemThread(threadID nThreadId); - void RemoveSystemThread(threadID nThreadId); - - // Balancing tasks in the pool between threads - void BalanceThreadsPool(const ThreadPoolHandle& handle); - void BalanceThreadInPool(CThreadTask_Thread* pFreeThread, Threads* pThreads = NULL); - -private: - void ScheduleTask(SThreadTaskInfo* pTaskInfo); - void RescheduleTasks(); -private: - - // User created threads pools - mutable CryReadModifyLock m_threadsPoolsLock; - ThreadsPools m_threadsPools; - - // Physical threads available to system. - Threads m_threads; - - // Threads with single blocking task attached. - Threads m_blockingThreads; - - typedef CryMT::CLocklessPointerQueue Tasks; - - Tasks m_unassignedTasks; - - mutable CryCriticalSection m_threadNameLock; - mutable CryCriticalSection m_threadRemove; - typedef std::map ThreadNames; - ThreadNames m_threadNames; - - mutable CryCriticalSection m_systemThreadsLock; - std::vector m_systemThreads; - - // Max threads that can be executed at same time. - int m_nMaxThreads; -}; - - -#endif // CRYINCLUDE_CRYSYSTEM_THREADTASK_H diff --git a/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp b/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp deleted file mode 100644 index 6fc9ae7830..0000000000 --- a/Code/CryEngine/CrySystem/UnitTests/CryMathTests.cpp +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "CrySystem_precompiled.h" -#include -#include - -namespace UnitTest -{ - class CryMathTestFixture - : public ::testing::Test - {}; - -#if AZ_TRAIT_DISABLE_FAILED_MATH_TESTS - TEST_F(CryMathTestFixture, DISABLED_InverserSqrt_HasAtLeast22BitsOfAccuracy) -#else - TEST_F(CryMathTestFixture, InverserSqrt_HasAtLeast22BitsOfAccuracy) -#endif - { - float testFloat(0.336950600); - const float result = isqrt_safe_tpl(testFloat * testFloat); - const float epsilon = 0.00001f; - EXPECT_NEAR(2.96779, result, epsilon); - } - -#if AZ_TRAIT_DISABLE_FAILED_MATH_TESTS - TEST_F(CryMathTestFixture, DISABLED_SimdSqrt_HasAtLeast23BitsOfAccuracy) -#else - TEST_F(CryMathTestFixture, SimdSqrt_HasAtLeast23BitsOfAccuracy) -#endif - { - float testFloat(3434.34839439); - const float result = sqrt_tpl(testFloat); - const float epsilon = 0.00001f; - EXPECT_NEAR(58.60331, result, epsilon); - } -} diff --git a/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp b/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp deleted file mode 100644 index 1935196570..0000000000 --- a/Code/CryEngine/CrySystem/UnitTests/CryPakUnitTests.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CrySystem_precompiled.h" - -#include -#include - -#include -#include // for max path decl -#include -#include -#include // for function<> in the find files callback. -#include -#include -#include -#include -#include - -namespace CryPakUnitTests -{ - -#if defined(AZ_PLATFORM_WINDOWS) - - // Note: none of the below is really a unit test, its all basic feature tests - // for critical functionality - - class Integ_CryPakUnitTests - : public ::testing::Test - { - protected: - bool IsPackValid(const char* path) - { - AZ::IO::IArchive* pak = gEnv->pCryPak; - if (!pak) - { - return false; - } - - if (!pak->OpenPack(path, AZ::IO::IArchive::FLAGS_PATH_REAL)) - { - return false; - } - - pak->ClosePack(path); - return true; - } - }; - - TEST_F(Integ_CryPakUnitTests, TestCryPakModTime) - { - AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance(); - ASSERT_NE(nullptr, fileIo); - - AZ::IO::IArchive* pak = gEnv->pCryPak; - // repeat the following test multiple times, since timing (seconds) can affect it and it involves time! - for (int iteration = 0; iteration < 10; ++iteration) - { - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds{ 100 }); - - // helper paths and strings - AZStd::string gameFolder = fileIo->GetAlias("@usercache@"); - - AZStd::string testFile = "unittest.bin"; - AZStd::string testFilePath = gameFolder + "\\" + testFile; - AZStd::string testPak = "unittest.pak"; - AZStd::string testPakPath = gameFolder + "\\" + testPak; - AZStd::string zipCmd = "-zip=" + testPakPath; - - // delete test files in case they already exist - fileIo->Remove(testFilePath.c_str()); - pak->ClosePack(testPakPath); - fileIo->Remove(testPakPath.c_str()); - - // create a test file - char data[] = "unittest"; - FILE* f = nullptr; - azfopen(&f, testFilePath.c_str(), "wb"); - EXPECT_TRUE(f != nullptr); // file successfully opened for writing - EXPECT_TRUE(fwrite(data, sizeof(char), sizeof(data), f) == sizeof(data)); // file written to successfully - EXPECT_TRUE(fclose(f) == 0); // file closed successfully - - AZ::IO::HandleType fDisk = pak->FOpen(testFilePath.c_str(), "rb"); - EXPECT_TRUE(fDisk > 0); // opened file on disk successfully - uint64_t modTimeDisk = pak->GetModificationTime(fDisk); // high res mod time extracted from file on disk - EXPECT_TRUE(pak->FClose(fDisk) == 0); // file closed successfully - - // create a low res copy of disk file's mod time - uint64_t absDiff, maxDiff = 20000000ul; - uint16_t dosDate, dosTime; - FILETIME ft; - LARGE_INTEGER lt; - - ft.dwHighDateTime = modTimeDisk >> 32; - ft.dwLowDateTime = modTimeDisk & 0xFFFFFFFF; - EXPECT_TRUE(FileTimeToDosDateTime(&ft, &dosDate, &dosTime) != FALSE); // converted to DOSTIME successfully - ft.dwHighDateTime = 0; - ft.dwLowDateTime = 0; - EXPECT_TRUE(DosDateTimeToFileTime(dosDate, dosTime, &ft) != FALSE); // converted to FILETIME successfully - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - uint64_t modTimeDiskLowRes = lt.QuadPart; - - absDiff = modTimeDiskLowRes >= modTimeDisk ? modTimeDiskLowRes - modTimeDisk : modTimeDisk - modTimeDiskLowRes; - EXPECT_LE(absDiff, maxDiff); // FILETIME (high res) and DOSTIME (low res) should be at most 2 seconds apart - - gEnv->pResourceCompilerHelper->CallResourceCompiler(testFilePath.c_str(), zipCmd.c_str()); - EXPECT_EQ(AZ::IO::ResultCode::Success, fileIo->Remove(testFilePath.c_str())); // test file on disk deleted successfully - - EXPECT_TRUE(pak->OpenPack(testPakPath)); // opened pak successfully - - AZ::IO::HandleType fPak = pak->FOpen(testFilePath.c_str(), "rb"); - EXPECT_GT(fPak, 0); // file (in pak) opened correctly - uint64_t modTimePak = pak->GetModificationTime(fPak); // low res mod time extracted from file in pak - EXPECT_EQ(0, pak->FClose(fPak)); // file closed successfully - - EXPECT_TRUE(pak->ClosePack(testPakPath)); // closed pak successfully - EXPECT_EQ(AZ::IO::ResultCode::Success, fileIo->Remove(testPakPath.c_str())); // test pak file deleted successfully - - absDiff = modTimePak >= modTimeDisk ? modTimePak - modTimeDisk : modTimeDisk - modTimePak; - // compare mod times. They are allowed to be up to 2 seconds apart but no more - EXPECT_LE(absDiff, maxDiff); // FILETIME (disk) and DOSTIME (pak) should be at most 2 seconds apart - // note: Do not directly compare the disk time and pack time, the resolution drops the last digit off in some cases in pak - // it only has a 2 second resolution. you may compare to make sure that the pak time is WITHIN 2 seconds (as above) but not equal. - - // we depend on the fact that crypak is rounding up, instead of down - EXPECT_GE(modTimePak, modTimeDisk); - } - } - - -#endif -} diff --git a/Code/CryEngine/CrySystem/UnixConsole.cpp b/Code/CryEngine/CrySystem/UnixConsole.cpp index d0a7bc15ff..5ec186b8b8 100644 --- a/Code/CryEngine/CrySystem/UnixConsole.cpp +++ b/Code/CryEngine/CrySystem/UnixConsole.cpp @@ -783,12 +783,6 @@ void CUNIXConsole::KeyEnter() if (pushCommand) { - CSystem* pSystem = static_cast(gEnv->pSystem); -#if defined(CVARS_WHITELIST) - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool execute = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(m_InputLine, false) : true; - if (execute) -#endif // defined(CVARS_WHITELIST) { m_CommandQueue.push_back(m_InputLine); } diff --git a/Code/CryEngine/CrySystem/XConsole.cpp b/Code/CryEngine/CrySystem/XConsole.cpp index 3b30a7eeed..32fe67dcc0 100644 --- a/Code/CryEngine/CrySystem/XConsole.cpp +++ b/Code/CryEngine/CrySystem/XConsole.cpp @@ -140,147 +140,6 @@ void Command_SetWaitFrames(IConsoleCmdArgs* pCmd) } } -/* - - CNotificationNetworkConsole - -*/ - -#include -class CNotificationNetworkConsole - : public INotificationNetworkListener -{ -private: - static const uint32 LENGTH_MAX = 256; - static CNotificationNetworkConsole* s_pInstance; - -public: - static bool Initialize() - { - if (s_pInstance) - { - return true; - } - - INotificationNetwork* pNotificationNetwork = gEnv->pSystem->GetINotificationNetwork(); - if (!pNotificationNetwork) - { - return false; - } - - s_pInstance = new CNotificationNetworkConsole(); - pNotificationNetwork->ListenerBind("Command", s_pInstance); - return true; - } - - static void Shutdown() - { - if (!s_pInstance) - { - return; - } - - delete s_pInstance; - s_pInstance = NULL; - } - - static void Update() - { - if (s_pInstance) - { - s_pInstance->ProcessCommand(); - } - } - -private: - CNotificationNetworkConsole() - { - m_pConsole = NULL; - - m_commandBuffer[0][0] = '\0'; - m_commandBuffer[1][0] = '\0'; - m_commandBufferIndex = 0; - m_commandCriticalSection = ::CryCreateCriticalSection(); - } - - ~CNotificationNetworkConsole() - { - if (m_commandCriticalSection) - { - ::CryDeleteCriticalSection(m_commandCriticalSection); - } - } - -private: - void ProcessCommand() - { - if (!ValidateConsole()) - { - return; - } - - char* command = NULL; - ::CryEnterCriticalSection(m_commandCriticalSection); - if (*m_commandBuffer[m_commandBufferIndex]) - { - command = m_commandBuffer[m_commandBufferIndex]; - } - ++m_commandBufferIndex &= 1; - ::CryLeaveCriticalSection(m_commandCriticalSection); - - if (command) - { - m_pConsole->ExecuteString(command); - *command = '\0'; - } - } - - bool ValidateConsole() - { - if (m_pConsole) - { - return true; - } - - if (!gEnv->pConsole) - { - return false; - } - - m_pConsole = gEnv->pConsole; - return true; - } - - // INotificationNetworkListener -public: - void OnNotificationNetworkReceive(const void* pBuffer, size_t length) - { - if (!ValidateConsole()) - { - return; - } - - if (length > LENGTH_MAX) - { - length = LENGTH_MAX; - } - - ::CryEnterCriticalSection(m_commandCriticalSection); - ::memcpy(m_commandBuffer[m_commandBufferIndex], pBuffer, length); - m_commandBuffer[m_commandBufferIndex][LENGTH_MAX - 1] = '\0'; - ::CryLeaveCriticalSection(m_commandCriticalSection); - } - -private: - IConsole* m_pConsole; - - char m_commandBuffer[2][LENGTH_MAX]; - size_t m_commandBufferIndex; - void* m_commandCriticalSection; -}; - -CNotificationNetworkConsole* CNotificationNetworkConsole::s_pInstance = NULL; - void ConsoleShow(IConsoleCmdArgs*) { gEnv->pConsole->ShowConsole(true); @@ -359,8 +218,6 @@ CXConsole::CXConsole() m_waitSeconds = 0.0f; m_blockCounter = 0; - CNotificationNetworkConsole::Initialize(); - AzFramework::ConsoleRequestBus::Handler::BusConnect(); AzFramework::CommandRegistrationBus::Handler::BusConnect(); @@ -379,8 +236,6 @@ CXConsole::~CXConsole() gEnv->pSystem->GetIRemoteConsole()->UnregisterListener(this); } - CNotificationNetworkConsole::Shutdown(); - if (!m_mapVariables.empty()) { while (!m_mapVariables.empty()) @@ -1205,8 +1060,6 @@ void CXConsole::Update() } } } - - CNotificationNetworkConsole::Update(); } //enable this for now, we need it for profiling etc @@ -1749,11 +1602,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyMask = VF_DEV_ONLY; int dediOnlyMask = VF_DEDI_ONLY; int excludeMask = cheatMask | constMask | readOnlyMask | devOnlyMask | dediOnlyMask; -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool excludeWhitelist = true; -#endif // defined(CVARS_WHITELIST) if (numArgs > 1) { @@ -1786,13 +1634,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) excludeMask &= ~dediOnlyMask; } -#if defined(CVARS_WHITELIST) - if (azstricmp(arg, "whitelist") == 0) - { - excludeWhitelist = false; - } -#endif // defined(CVARS_WHITELIST) - --numArgs; } } @@ -1810,11 +1651,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyFlags = (command.m_nFlags & devOnlyMask); int dediOnlyFlags = (command.m_nFlags & dediOnlyMask); bool shouldLog = ((cheatFlags | devOnlyFlags | dediOnlyFlags) == 0) || (((cheatFlags | devOnlyFlags | dediOnlyFlags) & ~excludeMask) != 0); -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(command.m_sName, true) : true; - shouldLog &= (!whitelisted || (whitelisted & !excludeWhitelist)); -#endif // defined(CVARS_WHITELIST) - if (shouldLog) { CryLogAlways("[CVARS]: [COMMAND] %s%s%s%s%s", @@ -1822,11 +1658,7 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) (cheatFlags != 0) ? " [VF_CHEAT]" : "", (devOnlyFlags != 0) ? " [VF_DEV_ONLY]" : "", (dediOnlyFlags != 0) ? " [VF_DEDI_ONLY]" : "", -#if defined(CVARS_WHITELIST) - (whitelisted == true) ? " [WHITELIST]" : "" -#else "" -#endif // defined(CVARS_WHITELIST) ); ++commandCount; } @@ -1843,11 +1675,6 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) int devOnlyFlags = (flags & devOnlyMask); int dediOnlyFlags = (flags & dediOnlyMask); bool shouldLog = ((cheatFlags | constFlags | readOnlyFlags | devOnlyFlags | dediOnlyFlags) == 0) || (((cheatFlags | constFlags | readOnlyFlags | devOnlyFlags | dediOnlyFlags) & ~excludeMask) != 0); -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(pVariable->GetName(), true) : true; - shouldLog &= (!whitelisted || (whitelisted & !excludeWhitelist)); -#endif // defined(CVARS_WHITELIST) - if (shouldLog) { CryLogAlways("[CVARS]: [VARIABLE] %s%s%s%s%s%s%s", @@ -1857,11 +1684,7 @@ void CXConsole::AuditCVars(IConsoleCmdArgs* pArg) (readOnlyFlags != 0) ? " [VF_READONLY]" : "", (devOnlyFlags != 0) ? " [VF_DEV_ONLY]" : "", (dediOnlyFlags != 0) ? " [VF_DEDI_ONLY]" : "", -#if defined(CVARS_WHITELIST) - (whitelisted == true) ? " [WHITELIST]" : "" -#else "" -#endif // defined(CVARS_WHITELIST) ); ++cvarCount; } @@ -2520,11 +2343,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) } } //try to search in command list - -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); -#endif // defined(CVARS_WHITELIST) bool bArgumentAutoComplete = false; std::vector matches; @@ -2565,10 +2383,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) string cmd = string(sVar) + " " + pArgumentAutoComplete->GetValue(i); if (_strnicmp(m_sPrevTab.c_str(), cmd.c_str(), m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(cmd, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { bArgumentAutoComplete = true; matches.push_back(cmd); @@ -2590,10 +2404,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) { if (_strnicmp(m_sPrevTab.c_str(), itrCmds->first.c_str(), m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(itrCmds->first, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { matches.push_back((char* const)itrCmds->first.c_str()); } @@ -2613,10 +2423,6 @@ const char* CXConsole::ProcessCompletion(const char* szInputBuffer) {//if(itrVars->first.compare(0,m_sPrevTab.length(),m_sPrevTab)==0) if (_strnicmp(m_sPrevTab.c_str(), itrVars->first, m_sPrevTab.length()) == 0) { -#if defined(CVARS_WHITELIST) - bool whitelisted = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(itrVars->first, true) : true; - if (whitelisted) -#endif // defined(CVARS_WHITELIST) { matches.push_back((char* const)itrVars->first); } @@ -2990,12 +2796,6 @@ void CXConsole::ExecuteInputBuffer() AddCommandToHistory(sTemp.c_str()); -#if defined(CVARS_WHITELIST) - CSystem* pSystem = static_cast(gEnv->pSystem); - ICVarsWhitelist* pCVarsWhitelist = pSystem->GetCVarsWhiteList(); - bool execute = (pCVarsWhitelist) ? pCVarsWhitelist->IsWhiteListed(sTemp, false) : true; - if (execute) -#endif // defined(CVARS_WHITELIST) { ExecuteStringInternal(sTemp.c_str(), true); // from console } diff --git a/Code/CryEngine/CrySystem/XML/xml.cpp b/Code/CryEngine/CrySystem/XML/xml.cpp index 601b14eeb3..438b35b6c8 100644 --- a/Code/CryEngine/CrySystem/XML/xml.cpp +++ b/Code/CryEngine/CrySystem/XML/xml.cpp @@ -1809,8 +1809,6 @@ XmlNodeRef XmlParserImp::ParseFile(const char* filename, XmlString& errorString, ParseEnd(); } - SYNCHRONOUS_LOADING_TICK(); - delete [] pFileContents; return root; diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 5dc8a68f8b..50cbdc24e4 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -19,14 +19,11 @@ set(FILES ConsoleBatchFile.cpp ConsoleHelpGen.cpp CryAsyncMemcpy.cpp - DebugCallStack.cpp GeneralMemoryHeap.cpp HandlerBase.cpp - IDebugCallStack.cpp AsyncPakManager.cpp Log.cpp SystemRender.cpp - NotificationNetwork.cpp PhysRenderer.cpp ResourceManager.cpp ServerHandler.cpp @@ -36,7 +33,6 @@ set(FILES SystemCFG.cpp SystemEventDispatcher.cpp SystemInit.cpp - SystemScheduler.cpp SystemWin32.cpp Timer.cpp UnixConsole.cpp @@ -52,7 +48,6 @@ set(FILES ServerHandler.h ServerThrottle.h SyncLock.h - SystemScheduler.h UnixConsole.h SystemInit.h XML/ReadWriteXMLSink.h @@ -63,12 +58,8 @@ set(FILES ConsoleBatchFile.h ConsoleHelpGen.h CryWaterMark.h - DebugCallStack.h GeneralMemoryHeap.h - IDebugCallStack.h - IThreadConfigManager.h Log.h - NotificationNetwork.h resource.h SimpleStringPool.h CrySystem_precompiled.h @@ -107,24 +98,12 @@ set(FILES XML/WriteXMLSource.cpp ZipFile.h ZipFileFormat_info.h - ProfileLogSystem.cpp Sampler.cpp - ProfileLogSystem.h Sampler.h LocalizedStringManager.cpp LocalizedStringManager.h - CryThreadUtil_win32_thread.h - ThreadInfo.cpp - ThreadInfo.h - ThreadTask.h - ThreadTask.cpp - ThreadConfigManager.h - ThreadConfigManager.cpp - SystemThreading.cpp ZLibCompressor.cpp ZLibCompressor.h - SoftCode/SoftCodeMgr.cpp - SoftCode/SoftCodeMgr.h Huffman.cpp Huffman.h RemoteConsole/RemoteConsole.cpp diff --git a/Code/CryEngine/CrySystem/crysystem_test_files.cmake b/Code/CryEngine/CrySystem/crysystem_test_files.cmake index a57ba57f77..d8f6887da6 100644 --- a/Code/CryEngine/CrySystem/crysystem_test_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_test_files.cmake @@ -18,7 +18,5 @@ set(FILES Tests/Test_Localization.cpp Tests/test_Main.cpp Tests/test_MaterialUtils.cpp - UnitTests/CryMathTests.cpp - UnitTests/CryPakUnitTests.cpp DllMain.cpp ) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp index 8d3513cbcb..c505639338 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserComponent.cpp @@ -263,8 +263,6 @@ namespace AzToolsFramework return SourceFileDetails("Icons/AssetBrowser/XML_16.svg"); } - - // this is here to prevent having to include IResourceCompilerHelper, which is in CryCommon. static const char* sourceFormats[] = { ".tif", ".bmp", ".gif", ".jpg", ".jpeg", ".jpe", ".tga", ".png" }; for (unsigned int sourceImageFormatIndex = 0, numSources = AZ_ARRAY_SIZE(sourceFormats); sourceImageFormatIndex < numSources; ++sourceImageFormatIndex) diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index 033169ac6d..1f29478399 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -573,11 +573,6 @@ namespace O3DELauncher systemInitParams.hWnd = mainInfo.m_window; systemInitParams.pPrintSync = mainInfo.m_printSink; - if (strstr(mainInfo.m_commandLine, "-norandom")) - { - systemInitParams.bNoRandom = true; - } - systemInitParams.bDedicatedServer = IsDedicatedServer(); if (IsDedicatedServer()) { diff --git a/Code/Sandbox/Editor/BackgroundScheduleManager.cpp b/Code/Sandbox/Editor/BackgroundScheduleManager.cpp deleted file mode 100644 index 23eee6daf4..0000000000 --- a/Code/Sandbox/Editor/BackgroundScheduleManager.cpp +++ /dev/null @@ -1,629 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "BackgroundScheduleManager.h" - -namespace BackgroundScheduleManager -{ - //----------------------------------------------------------------------------- - - CScheduleItem::CScheduleItem(const char* szName) - : m_name(szName) - , m_refCount(1) - , m_state(eScheduleItemState_Pending) - { - } - - CScheduleItem::~CScheduleItem() - { - CRY_ASSERT(m_refCount == 0); - - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - (*it)->Release(); - } - } - - const char* CScheduleItem::GetDescription() const - { - return m_name.c_str(); - } - - EScheduleItemState CScheduleItem::GetState() const - { - return m_state; - } - - const float CScheduleItem::GetProgress() const - { - if (m_workItems.empty()) - { - return 1.0f; - } - else - { - float totalProgress = 0.0f; - - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - totalProgress += (*it)->GetProgress(); - } - - return totalProgress / (float)m_workItems.size(); - } - } - - const uint32 CScheduleItem::GetNumWorkItems() const - { - return m_workItems.size(); - } - - IBackgroundScheduleItemWork* CScheduleItem::GetWorkItem(const uint32 index) const - { - return m_workItems[index]; - } - - void CScheduleItem::AddWorkItem(IBackgroundScheduleItemWork* pWork) - { - // cannot add new work items when item has finished or failed - if (m_state == eScheduleItemState_Failed || m_state == eScheduleItemState_Completed) - { - CryFatalError("Cannot add new work items when item has finished or failed"); - return; - } - - // add to the work list - if (m_state == eScheduleItemState_Processing) - { - m_addedWorkItems.push_back(pWork); - } - else - { - m_workItems.push_back(pWork); - } - } - - void CScheduleItem::AddRef() - { - CryInterlockedIncrement(&m_refCount); - } - - void CScheduleItem::Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - delete this; - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - void CScheduleItem::RequestStop() - { - if (m_state == eScheduleItemState_Pending) - { - // we can stop right away :) - m_state = eScheduleItemState_Failed; - } - else if (m_state == eScheduleItemState_Processing) - { - m_state = eScheduleItemState_Stopping; - - // signal all pending work to stop - uint32 curIndex = 0; - while (curIndex < m_processedWorkItems.size()) - { - IBackgroundScheduleItemWork* pWork = m_processedWorkItems[curIndex]; - if (pWork->OnStop()) - { - // if the work was stopped remove it from list - m_processedWorkItems.erase(m_processedWorkItems.begin() + curIndex); - continue; - } - else - { - // this work item cannot be stopped this frame - curIndex += 1; - } - } - - // if all pending work has been stopped we can assume the failed state - if (m_processedWorkItems.empty()) - { - m_state = eScheduleItemState_Failed; - } - } - } - - EScheduleWorkItemStatus CScheduleItem::Update() - { - EScheduleWorkItemStatus retStatus = eScheduleWorkItemStatus_NotFinished; - - switch (m_state) - { - // finial state - work failed - case eScheduleItemState_Failed: - { - retStatus = eScheduleWorkItemStatus_Failed; - break; - } - - // final state - work completed - case eScheduleItemState_Completed: - { - retStatus = eScheduleWorkItemStatus_Finished; - break; - } - - // first update, start all the work items - case eScheduleItemState_Pending: - { - // start all of the tasks - bool bHasFailedStarts = false; - for (TWorkItems::const_iterator it = m_workItems.begin(); - it != m_workItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - - if (pWork->OnStart()) - { - m_processedWorkItems.push_back(pWork); - } - else - { - bHasFailedStarts = true; - break; - } - } - - if (bHasFailedStarts) - { - m_state = eScheduleItemState_Stopping; - break; - } - else - { - m_state = eScheduleItemState_Processing; - /* FALLS THROUGHT TO PROCESSING STATE */ - } - } - - // work processing state - case eScheduleItemState_Processing: - { - // process new work items that were added while the schedule was created - if (!m_addedWorkItems.empty()) - { - for (TWorkItems::const_iterator it = m_addedWorkItems.begin(); - it != m_addedWorkItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - pWork->OnStart(); - m_processedWorkItems.push_back(pWork); - m_workItems.push_back(pWork); - } - - m_addedWorkItems.clear(); - } - - // update work items - bool bHasFailedItems = false; - TWorkItems completedItems; - for (TWorkItems::const_iterator it = m_processedWorkItems.begin(); - it != m_processedWorkItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - - // update given work item - const EScheduleWorkItemStatus status = pWork->OnUpdate(); - if (status == eScheduleWorkItemStatus_Finished) - { - completedItems.push_back(pWork); - continue; - } - - // item failed - we need to stop other tasks - if (status == eScheduleWorkItemStatus_Failed) - { - bHasFailedItems = true; - break; - } - } - - // cleanup completed items - for (TWorkItems::iterator it = completedItems.begin(); - it != completedItems.end(); ++it) - { - IBackgroundScheduleItemWork* pWork = (*it); - TWorkItems::iterator jt = std::find(m_processedWorkItems.begin(), m_processedWorkItems.end(), pWork); - m_processedWorkItems.erase(jt); - } - - if (!bHasFailedItems) - { - // all work has finished - if (m_processedWorkItems.empty()) - { - retStatus = eScheduleWorkItemStatus_Finished; - m_state = eScheduleItemState_Completed; - } - - break; - } - else - { - // some of the items failed - m_state = eScheduleItemState_Stopping; - /* FALL THROUGH TO STOPPING STATE */ - } - } - - // We are stopping failed work - case eScheduleItemState_Stopping: - { - uint32 curIndex = 0; - while (curIndex < m_processedWorkItems.size()) - { - IBackgroundScheduleItemWork* pWork = m_processedWorkItems[curIndex]; - if (pWork->OnStop()) - { - // if the work was stopped remove it from list - m_processedWorkItems.erase(m_processedWorkItems.begin() + curIndex); - continue; - } - else - { - // this work item cannot be stopped this frame - curIndex += 1; - } - } - - // if all pending work has been stopped we can assume the failed state - if (m_processedWorkItems.empty()) - { - m_state = eScheduleItemState_Failed; - return eScheduleWorkItemStatus_Failed; - } - } - } - - return retStatus; - } - - //----------------------------------------------------------------------------- - - CSchedule::CSchedule(const char* szName) - : m_name(szName) - , m_refCount(1) - , m_bCanceled(false) - , m_currentItem(0) - , m_state(eScheduleState_Pending) - { - } - - CSchedule::~CSchedule() - { - CRY_ASSERT(m_refCount == 0); - - for (TItems::const_iterator it = m_items.begin(); - it != m_items.end(); ++it) - { - CScheduleItem* pItem = *it; - SAFE_RELEASE(pItem); - } - - m_items.clear(); - } - - const char* CSchedule::GetDescription() const - { - return m_name.c_str(); - } - - float CSchedule::GetProgress() const - { - if (m_currentItem >= m_items.size()) - { - return 1.0f; - } - else - { - const float itemProgress = 1.0f / (float)(m_items.size()); - const IBackgroundScheduleItem* pItem = m_items[m_currentItem]; - return (m_currentItem + pItem->GetProgress()) * itemProgress; - } - } - - IBackgroundScheduleItem* CSchedule::GetProcessedItem() const - { - if (m_currentItem >= m_items.size()) - { - return NULL; - } - else - { - IBackgroundScheduleItem* pItem = m_items[m_currentItem]; - return pItem; - } - } - - const uint32 CSchedule::GetNumItems() const - { - return m_items.size(); - } - - IBackgroundScheduleItem* CSchedule::GetItem(const uint32 index) const - { - return m_items[index]; - } - - EScheduleState CSchedule::GetState() const - { - return m_state; - } - - void CSchedule::Cancel() - { - m_bCanceled = true; - } - - bool CSchedule::IsCanceled() const - { - return m_bCanceled; - } - - void CSchedule::AddItem(IBackgroundScheduleItem* pItem) - { - if (NULL == pItem) - { - return; - } - - // we can add items only in the "pending" state - if (pItem->GetState() != eScheduleItemState_Pending) - { - CryFatalError("Schedule items can be added to schedule only before their work starts"); - return; - } - - // item has no jobs, do not add - if (pItem->GetNumWorkItems() == 0) - { - return; - } - - m_items.push_back(static_cast(pItem)); - pItem->AddRef(); - } - - void CSchedule::AddRef() - { - CryInterlockedIncrement(&m_refCount); - } - - void CSchedule::Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - delete this; - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - } - - EScheduleWorkItemStatus CSchedule::Update() - { - EScheduleWorkItemStatus retStatus = eScheduleWorkItemStatus_NotFinished; - - // we have a cancel request - if (m_bCanceled) - { - CryLog("Schedule '%s' was canceled", GetDescription()); - - if (m_state == eScheduleState_Processing && m_currentItem < m_items.size()) - { - // stop the current item - CScheduleItem* pItem = m_items[m_currentItem]; - pItem->RequestStop(); - m_state = eSccheduleState_Stopping; - } - else if (m_state != eScheduleState_Completed) - { - m_state = eScheduleState_Failed; - return eScheduleWorkItemStatus_Failed; - } - } - - // process internal state machine - switch (m_state) - { - // final state - work failed - case eScheduleState_Failed: - { - retStatus = eScheduleWorkItemStatus_Failed; - break; - } - - // final state - work completed - case eScheduleState_Completed: - { - retStatus = eScheduleWorkItemStatus_Finished; - break; - } - - // stopping current task - case eSccheduleState_Stopping: - { - if (m_currentItem < m_items.size()) - { - CScheduleItem* pItem = m_items[m_currentItem]; - if (pItem->Update() != eScheduleWorkItemStatus_NotFinished) - { - // task was finally stopped - m_state = eScheduleState_Failed; - retStatus = eScheduleWorkItemStatus_Failed; - } - } - - break; - } - - // first update, switch to processing - case eScheduleState_Pending: - { - m_state = eScheduleState_Processing; - m_currentItem = 0; - /* FALLS THROUGHT */ - } - - // if we were in the processing phase inform the current schedule item to stop all it's work - case eScheduleState_Processing: - { - // update schedule items - while (m_currentItem < m_items.size()) - { - CScheduleItem* pItem = m_items[m_currentItem]; - - const EScheduleWorkItemStatus itemStatus = pItem->Update(); - if (itemStatus == eScheduleWorkItemStatus_Finished) - { - m_currentItem += 1; - continue; - } - else if (itemStatus == eScheduleWorkItemStatus_Failed) - { - m_state = eScheduleState_Failed; - retStatus = eScheduleWorkItemStatus_Failed; - gEnv->pLog->LogWarning("Schedule '%s' failed on item '%s'.", GetDescription(), pItem->GetDescription()); - } - - break; - } - - // all items updated - if (m_currentItem >= m_items.size()) - { - // empty schedule, complete in one tick - m_state = eScheduleState_Completed; - retStatus = eScheduleWorkItemStatus_Finished; - CryLog("Schedule '%s' completed", GetDescription()); - } - - break; - } - } - - return retStatus; - } - - //----------------------------------------------------------------------------- - - CScheduleManager::CScheduleManager() - { - GetIEditor()->RegisterNotifyListener(this); - } - - CScheduleManager::~CScheduleManager() - { - GetIEditor()->UnregisterNotifyListener(this); - - for (TSchedules::const_iterator it = m_schedules.begin(); - it != m_schedules.end(); ++it) - { - CSchedule* pSchedule = *it; - SAFE_RELEASE(pSchedule); - } - - m_schedules.clear(); - } - - IBackgroundSchedule* CScheduleManager::CreateSchedule(const char* szName) - { - return new CSchedule(szName); - } - - IBackgroundScheduleItem* CScheduleManager::CreateScheduleItem(const char* szName) - { - return new CScheduleItem(szName); - } - - void CScheduleManager::SubmitSchedule(IBackgroundSchedule* pSchedule) - { - if (NULL != pSchedule) - { - if (pSchedule->GetState() != eScheduleState_Pending) - { - CryFatalError("Only schedules with pending state can be submitted"); - return; - } - - pSchedule->AddRef(); - m_schedules.push_back(static_cast(pSchedule)); - } - } - - const uint32 CScheduleManager::GetNumSchedules() const - { - return m_schedules.size(); - } - - IBackgroundSchedule* CScheduleManager::GetSchedule(const uint32 index) const - { - return m_schedules[index]; - } - - void CScheduleManager::Update() - { - while (!m_schedules.empty()) - { - CSchedule* pSchedule = m_schedules[0]; - - const EScheduleWorkItemStatus status = pSchedule->Update(); - if (status == eScheduleWorkItemStatus_NotFinished) - { - // we need more work next frame - break; - } - - // schedule has finished, remove current reference - m_schedules.erase(m_schedules.begin()); - SAFE_RELEASE(pSchedule); - } - } - - void CScheduleManager::OnEditorNotifyEvent(EEditorNotifyEvent ev) - { - switch (ev) - { - case eNotify_OnQuit: - GetIEditor()->UnregisterNotifyListener(this); - break; - } - } - - //----------------------------------------------------------------------------- -} // BackgroundScheduleManager diff --git a/Code/Sandbox/Editor/BackgroundScheduleManager.h b/Code/Sandbox/Editor/BackgroundScheduleManager.h deleted file mode 100644 index 4deeaba64f..0000000000 --- a/Code/Sandbox/Editor/BackgroundScheduleManager.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_BACKGROUNDSCHEDULEMANAGER_H -#define CRYINCLUDE_EDITOR_BACKGROUNDSCHEDULEMANAGER_H -#pragma once - -#include "Include/IBackgroundScheduleManager.h" - -namespace BackgroundScheduleManager -{ - class CScheduleItem - : public IBackgroundScheduleItem - { - private: - std::string m_name; - volatile int m_refCount; - - EScheduleItemState m_state; - - typedef std::vector TWorkItems; - TWorkItems m_workItems; - TWorkItems m_addedWorkItems; - TWorkItems m_processedWorkItems; - - public: - CScheduleItem(const char* szName); - virtual ~CScheduleItem(); - - // IBackgroundScheduleItem interface - virtual const char* GetDescription() const; - virtual EScheduleItemState GetState() const; - virtual const float GetProgress() const; - virtual const uint32 GetNumWorkItems() const; - virtual IBackgroundScheduleItemWork* GetWorkItem(const uint32 index) const; - virtual void AddWorkItem(IBackgroundScheduleItemWork* pWork); - virtual void AddRef(); - virtual void Release(); - - // Update schedule item - EScheduleWorkItemStatus Update(); - - // Request to stop work in this item - void RequestStop(); - }; - - class CSchedule - : public IBackgroundSchedule - { - private: - std::string m_name; - volatile int m_refCount; - bool m_bCanceled; - - EScheduleState m_state; - - typedef std::vector TItems; - TItems m_items; - - uint32 m_currentItem; - - public: - CSchedule(const char* szName); - virtual ~CSchedule(); - - // IBackgroundSchedule interface - virtual const char* GetDescription() const; - virtual float GetProgress() const; - virtual IBackgroundScheduleItem* GetProcessedItem() const; - virtual const uint32 GetNumItems() const; - virtual IBackgroundScheduleItem* GetItem(const uint32 index) const; - virtual EScheduleState GetState() const; - virtual void Cancel(); - virtual bool IsCanceled() const; - virtual void AddItem(IBackgroundScheduleItem* pItem); - virtual void AddRef(); - virtual void Release(); - - // Update schedule item - EScheduleWorkItemStatus Update(); - }; - - class CScheduleManager - : public IBackgroundScheduleManager - , public IEditorNotifyListener - { - private: - typedef std::vector TSchedules; - TSchedules m_schedules; - - public: - CScheduleManager(); - virtual ~CScheduleManager(); - - // IBackgroundScheduleManager interface - virtual IBackgroundSchedule* CreateSchedule(const char* szName); - virtual IBackgroundScheduleItem* CreateScheduleItem(const char* szName); - virtual void SubmitSchedule(IBackgroundSchedule* pSchedule); - virtual const uint32 GetNumSchedules() const; - virtual IBackgroundSchedule* GetSchedule(const uint32 index) const; - virtual void Update(); - - // IEditorNotifyListener interface implementation - virtual void OnEditorNotifyEvent(EEditorNotifyEvent ev) override; - }; -} -#endif // CRYINCLUDE_EDITOR_BACKGROUNDSCHEDULEMANAGER_H diff --git a/Code/Sandbox/Editor/BackgroundTaskManager.cpp b/Code/Sandbox/Editor/BackgroundTaskManager.cpp deleted file mode 100644 index c05e709fd0..0000000000 --- a/Code/Sandbox/Editor/BackgroundTaskManager.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "BackgroundTaskManager.h" - -namespace BackgroundTaskManager -{ - //----------------------------------------------------------------------------- - - CTaskManager::CThread::CThread(class CTaskManager* pManager, CQueue* pQueue) - : m_pManager(pManager) - , m_pQueue(pQueue) - { - start(); - } - - CTaskManager::CThread::~CThread() - { - } - - void CTaskManager::CThread::WaitForThread() - { - wait(); - } - - void CTaskManager::CThread::run() - { - CryThreadSetName(-1, "BackgroundTaskThread"); - - while (!m_pManager->IsStopped()) - { - STaskHandle taskHandle; - - // This blocks on Semaphore waiting for task from queue - m_pQueue->PopTask(taskHandle); - - // Should not happen but it's a stupid way to crash :) - if (NULL == taskHandle.pTask) - { - continue; - } - - if (taskHandle.pTask->IsCanceled()) - { - // Task was canceled before we got here - m_pManager->AddCompletedTask(taskHandle, eTaskResult_Canceled); - } - else - { - const ETaskResult state = taskHandle.pTask->Work(); - - if (state == eTaskResult_Resume) - { - // Put it back into queue, so more important task can take over. - m_pManager->AddTask(taskHandle); - } - else - { - // Finish task - m_pManager->AddCompletedTask(taskHandle, state); - } - } - } - } - - //----------------------------------------------------------------------------- - - CTaskManager::CQueue::CQueue() - : m_semaphore(INT_MAX, 0) // no good maximum value, assume worst case - { - } - - void CTaskManager::CQueue::AddTask(const STaskHandle& taskHandle) - { - { - CryAutoLock lock(m_lock); - - // TODO: use heap? - m_pendingTasks.insert(m_pendingTasks.begin(), taskHandle); - std::stable_sort(m_pendingTasks.begin(), m_pendingTasks.end()); - } - - taskHandle.pTask->SetState(eTaskState_Pending); - - // release internal semaphore so threads can pick up the work - m_semaphore.Release(); - } - - void CTaskManager::CQueue::PopTask(STaskHandle& outTaskHandle) - { - // wait for job - m_semaphore.Acquire(); - - { - CryAutoLock lock(m_lock); - - if (m_pendingTasks.empty()) - { - outTaskHandle.pTask = NULL; - } - else - { - outTaskHandle = m_pendingTasks.back(); - outTaskHandle.pTask->SetState(eTaskState_Working); - m_pendingTasks.pop_back(); - } - } - } - - void CTaskManager::CQueue::ReleaseSemaphore() - { - m_semaphore.Release(); - } - - void CTaskManager::CQueue::Clear() - { - CryAutoLock lock(m_lock); - for (uint i = 0; i < m_pendingTasks.size(); ++i) - { - m_pendingTasks[i].pTask->Release(); - } - - m_pendingTasks.clear(); - } - - //----------------------------------------------------------------------------- - - CTaskManager::CTaskManager() - : m_bStop(false) - , m_nextTaskID(1) - , m_listeners(1) - { - GetIEditor()->RegisterNotifyListener(this); - } - - CTaskManager::~CTaskManager() - { - if (!m_bStop) - { - Stop(); - } - } - - void CTaskManager::Start(const uint32 threadCount /*=kDefaultThreadCount*/) - { - m_bStop = false; - - if (m_pThreads.empty()) - { - // Always create one IO thread - { - CThread* pThread = new CThread(this, &m_pendingTasks[ eTaskThreadMask_IO ]); - m_pThreads.push_back(pThread); - } - - // We also need at least one generic thread - const uint32 numGenericThreads = max(threadCount, 1); - for (uint32 i = 0; i < numGenericThreads; ++i) - { - CThread* pThread = new CThread(this, &m_pendingTasks[ eTaskThreadMask_Any ]); - m_pThreads.push_back(pThread); - } - } - } - - void CTaskManager::StartScheduledTasks() - { - CryAutoLock lock(m_tasksLock); - - if (!m_scheduledTasks.empty()) - { - const unsigned int time = GetTickCount(); - while (!m_scheduledTasks.empty()) - { - const int delta = (int)(time - m_scheduledTasks[0].time); - if (delta > 0) - { - // the soonest task on the list is still in the future, no point in looking at the next entries in the list - break; - } - - // promote the scheduled task to be a full task - AddTask(m_scheduledTasks[0].handle); - - // We held a reference to the task on list, release it - m_scheduledTasks[0].handle.pTask->Release(); - - m_scheduledTasks.erase(m_scheduledTasks.begin()); - } - } - } - - void CTaskManager::Stop() - { - if (!m_bStop) - { - m_bStop = true; - GetIEditor()->UnregisterNotifyListener(this); - - // clear queues - no new tasks will be processed - for (uint32 i = 0; i < eTaskThreadMask_COUNT; ++i) - { - m_pendingTasks[i].Clear(); - } - - // kick all the threads to allow them to quit - for (uint32 j = 0; j < m_pThreads.size(); ++j) - { - for (uint32 i = 0; i < eTaskThreadMask_COUNT; ++i) - { - m_pendingTasks[i].ReleaseSemaphore(); - } - } - - // Stop threads - for (TWorkerThreads::iterator it = m_pThreads.begin(); - it != m_pThreads.end(); ++it) - { - (*it)->WaitForThread(); - delete *it; - } - - m_pThreads.clear(); - } - } - - void CTaskManager::AddListener(IBackgroundTaskManagerListener* pListener, const char* name) - { - m_listeners.Add(pListener, name); - } - - void CTaskManager::RemoveListener(IBackgroundTaskManagerListener* pListener) - { - m_listeners.Remove(pListener); - } - - void CTaskManager::AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) - { - MAKE_SURE(pTask != 0, return ); - - // keep an extra reference to the task in the manager - pTask->AddRef(); - - STaskHandle handle; - handle.id = CryInterlockedIncrement(&m_nextTaskID); - handle.priority = priority; - handle.threadMask = threadMask; - handle.pTask = pTask; - - AddTask(handle); - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskAdded(pTask->Description()); - } - } - - void CTaskManager::ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) - { - MAKE_SURE(delayMilliseconds >= 0, return ); - MAKE_SURE(pTask != 0, return ); - - // keep an extra reference to the task in the manager - pTask->AddRef(); - - SScheduledTask task; - task.time = GetTickCount() + delayMilliseconds; - task.handle.pTask = pTask; - task.handle.id = CryInterlockedIncrement(&m_nextTaskID); - task.handle.threadMask = threadMask; - task.handle.priority = priority; - - { - CryAutoLock lock(m_tasksLock); - m_scheduledTasks.push_back(task); - } - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskAdded(pTask->Description()); - } - } - - void CTaskManager::AddTask(const STaskHandle& handle) - { - MAKE_SURE(handle.pTask != 0, return ); - MAKE_SURE(handle.id != 0, return ); - - // add task to appropriate queue (every thread mask has it's own queue) - m_pendingTasks[handle.threadMask].AddTask(handle); - } - - void CTaskManager::AddCompletedTask(const STaskHandle& handle, ETaskResult resultState) - { - CryAutoLock lock(m_tasksLock); - - CRY_ASSERT(handle.pTask->GetState() == eTaskState_Working); - CRY_ASSERT(resultState != eTaskResult_Resume); - - // Update task state - switch (resultState) - { - case eTaskResult_Canceled: - { - handle.pTask->SetState(eTaskState_Canceled); - break; - } - - case eTaskResult_Completed: - { - handle.pTask->SetState(eTaskState_Completed); - break; - } - - case eTaskResult_Failed: - { - handle.pTask->SetState(eTaskState_Failed); - break; - } - } - - // add to the list of completed tasks (for calling the Finalize) - // TODO: some of the tasks do not require Finalize() and they could be released here instead of the main thread - SCompletedTask info; - info.pTask = handle.pTask; - info.id = handle.id; - info.state = resultState; - m_completedTasks.push_back(info); - } - - void CTaskManager::Update() - { - std::vector completedTasks; - { - CryAutoLock lock(m_tasksLock); - m_completedTasks.swap(completedTasks); - } - - // call finalize for the completed tasks - for (size_t i = 0; i < completedTasks.size(); ++i) - { - SCompletedTask& handle = completedTasks[i]; - - if (NULL != handle.pTask) - { - string description = handle.pTask->Description(); // copy string as the description is used after pTask is destroyed - - if (handle.state == eTaskResult_Completed) - { - if (description && description[0] != '\0') - { - gEnv->pLog->Log("Task Completed: %s", description.c_str()); - } - } - else if (handle.state == eTaskResult_Failed) - { - if (description && description[0] != '\0' && !handle.pTask->FailReported()) - { - gEnv->pLog->LogError("Task Failed: %s ", description.c_str()); - - const char* errorMessage = handle.pTask->ErrorMessage(); - if (errorMessage && errorMessage[0] != '\0') - { - gEnv->pLog->LogError("\tReason: [%s]", errorMessage); - } - } - } - - handle.pTask->Finalize(); - - // release the internal (task manager) reference. - // Tthis is usually the last reference to the task so it gets deleted here. - handle.pTask->Release(); - - for (TListeners::Notifier notifier(m_listeners); notifier.IsValid(); notifier.Next()) - { - notifier->OnBackgroundTaskCompleted(handle.state, description.c_str()); - } - } - } - } - - void CTaskManager::OnEditorNotifyEvent(EEditorNotifyEvent ev) - { - switch (ev) - { - case eNotify_OnInit: - Start(); - break; - case eNotify_OnIdleUpdate: - Update(); - break; - case eNotify_OnQuit: - Stop(); - break; - } - } -} diff --git a/Code/Sandbox/Editor/BackgroundTaskManager.h b/Code/Sandbox/Editor/BackgroundTaskManager.h deleted file mode 100644 index b440c66f1a..0000000000 --- a/Code/Sandbox/Editor/BackgroundTaskManager.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_BACKGROUNDTASKMANAGER_H -#define CRYINCLUDE_EDITOR_BACKGROUNDTASKMANAGER_H -#pragma once - -#include "Include/IBackgroundTaskManager.h" -#include "CryListenerSet.h" - -#include - -namespace BackgroundTaskManager -{ - typedef int TTaskID; - - struct STaskHandle - { - ETaskPriority priority; - ETaskThreadMask threadMask; - TTaskID id; - IBackgroundTask* pTask; - - bool operator<(const STaskHandle& rhs) const - { - if (priority < rhs.priority) - { - return true; - } - if (priority > rhs.priority) - { - return false; - } - return id < rhs.id; - } - }; - - struct SCompletedTask - { - ETaskResult state; - TTaskID id; - ETaskThreadMask threadMask; - IBackgroundTask* pTask; - }; - - struct SScheduledTask - { - unsigned int time; - STaskHandle handle; - }; - - class CTaskManager - : public IBackgroundTaskManager - , public IEditorNotifyListener - { - public: - CTaskManager(); - ~CTaskManager(); - - // IBackgroundTaskManager interface implementation - virtual void AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) override; - virtual void ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) override; - void AddListener(IBackgroundTaskManagerListener* pListener, const char* name) override; - void RemoveListener(IBackgroundTaskManagerListener* pListener) override; - - private: - // IEditorNotifyListener interface implementation - virtual void OnEditorNotifyEvent(EEditorNotifyEvent ev) override; - - void Start(const uint32 threadCount = kDefaultThreadCount); - void Stop(); - void StartScheduledTasks(); - void AddTask(const STaskHandle& outTask); - void AddCompletedTask(const STaskHandle& outTask, ETaskResult resultState); - void Update(); - - inline bool IsStopped() const - { - return m_bStop; - } - - private: - // Internal queue (per thread mask) - class CQueue - { - public: - CQueue(); - - // Add task to list - void AddTask(const STaskHandle& taskHandle); - - // Pop task from list - void PopTask(STaskHandle& outTaskHandle); - - // Release thread semaphore without adding a task - void ReleaseSemaphore(); - - // Remove all pending tasks - void Clear(); - - private: - CrySemaphore m_semaphore; - std::vector m_pendingTasks; - CryMutex m_lock; - }; - - // Worker thread class implementation - class CThread : public QThread - { - public: - CThread(CTaskManager* pManager, CQueue* pQueue); - ~CThread(); - - void WaitForThread(); - - private: - void run() override; - - private: - CTaskManager* m_pManager; - CQueue* m_pQueue; - }; - - private: - static const uint32 kMaxThreadCloseWaitTime = 10000; // ms - static const uint32 kDefaultThreadCount = 4; // good enough for LiveCreate (main user right now), do not set to less than 2 - - CQueue m_pendingTasks[ eTaskThreadMask_COUNT ]; - - // Task scheduled for execution in the future - std::vector m_scheduledTasks; - - // Completed tasks (waiting for the "finalize" call) - std::vector m_completedTasks; - - volatile TTaskID m_nextTaskID; - - typedef std::vector TWorkerThreads; - TWorkerThreads m_pThreads; - - CryMutex m_tasksLock; - bool m_bStop; - - typedef CListenerSet TListeners; - TListeners m_listeners; - }; -} - -//----------------------------------------------------------------------------- - -#endif // CRYINCLUDE_EDITOR_BACKGROUNDTASKMANAGER_H diff --git a/Code/Sandbox/Editor/CMakeLists.txt b/Code/Sandbox/Editor/CMakeLists.txt index 726f7ac2c7..7d89717391 100644 --- a/Code/Sandbox/Editor/CMakeLists.txt +++ b/Code/Sandbox/Editor/CMakeLists.txt @@ -112,7 +112,6 @@ ly_add_target( 3rdParty::zlib 3rdParty::AWSNativeSDK::STS Legacy::CryCommon - Legacy::CryCommon.EngineSettings.Static Legacy::EditorCommon AZ::AzCore AZ::AzToolsFramework diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index 6e33d32c6e..0bbc48d5f9 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -85,7 +85,6 @@ AZ_POP_DISABLE_WARNING // Editor #include "Settings.h" -#include "Include/IBackgroundScheduleManager.h" #include "GameExporter.h" #include "GameResourcesExporter.h" @@ -2314,15 +2313,6 @@ int CCryEditApp::IdleProcessing(bool bBackgroundUpdate) #endif } - // process the work schedule - regardless if the app is active or not - GetIEditor()->GetBackgroundScheduleManager()->Update(); - - // if there are active schedules keep updating the application - if (GetIEditor()->GetBackgroundScheduleManager()->GetNumSchedules() > 0) - { - bActive = true; - } - m_bPrevActive = bActive; AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now(); diff --git a/Code/Sandbox/Editor/GameEngine.cpp b/Code/Sandbox/Editor/GameEngine.cpp index 1c91ce58aa..2112d00d64 100644 --- a/Code/Sandbox/Editor/GameEngine.cpp +++ b/Code/Sandbox/Editor/GameEngine.cpp @@ -420,7 +420,6 @@ AZ::Outcome CGameEngine::Init( #else sip.hWnd = hwndForInputSystem; #endif - sip.hWndForInputSystem = hwndForInputSystem; sip.pLogCallback = &m_logFile; sip.sLogFileName = "@log@/Editor.log"; @@ -503,7 +502,6 @@ AZ::Outcome CGameEngine::Init( bool CGameEngine::InitGame(const char*) { - // in editor we do it later, bExecuteCommandLine was set to false m_pISystem->ExecuteCommandLine(); return true; @@ -608,8 +606,6 @@ void CGameEngine::SwitchToInGame() GetIEditor()->Notify(eNotify_OnBeginGameMode); - m_pISystem->SetThreadState(ESubsys_Physics, false); - m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(true); m_bInGameMode = true; @@ -646,8 +642,6 @@ void CGameEngine::SwitchToInEditor() } m_pISystem->GetIMovieSystem()->Reset(false, false); - m_pISystem->SetThreadState(ESubsys_Physics, false); - CViewport* pGameViewport = GetIEditor()->GetViewManager()->GetGameViewport(); m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(m_bSimulationMode); @@ -791,8 +785,6 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) // Enables engine to know about simulation mode. gEnv->SetIsEditorSimulationMode(enabled); - m_pISystem->SetThreadState(ESubsys_Physics, false); - if (m_bSimulationMode) { // [Anton] the order of the next 3 calls changed, since, EVENT_INGAME loads physics state (if any), @@ -903,19 +895,6 @@ void CGameEngine::Update() // [marco] check current sound and vis areas for music etc. // but if in game mode, 'cos is already done in the above call to game->update() unsigned int updateFlags = ESYSUPDATE_EDITOR; - - if (!m_bSimulationMode) - { - updateFlags |= ESYSUPDATE_IGNORE_PHYSICS; - } - - bool bUpdateAIPhysics = GetSimulationMode(); - - if (bUpdateAIPhysics) - { - updateFlags |= ESYSUPDATE_EDITOR_AI_PHYSICS; - } - GetIEditor()->GetAnimation()->Update(); GetIEditor()->GetSystem()->UpdatePreTickBus(updateFlags); componentApplication->Tick(gEnv->pTimer->GetFrameTime(ITimer::ETIMER_GAME)); diff --git a/Code/Sandbox/Editor/IEditor.h b/Code/Sandbox/Editor/IEditor.h index 62672a6505..af98158037 100644 --- a/Code/Sandbox/Editor/IEditor.h +++ b/Code/Sandbox/Editor/IEditor.h @@ -550,7 +550,6 @@ struct IEditor virtual class CViewManager* GetViewManager() = 0; virtual class CViewport* GetActiveView() = 0; virtual void SetActiveView(CViewport* viewport) = 0; - virtual struct IBackgroundTaskManager* GetBackgroundTaskManager() = 0; virtual struct IEditorFileMonitor* GetFileMonitor() = 0; // These are needed for Qt integration: @@ -720,7 +719,6 @@ struct IEditor virtual ESystemConfigPlatform GetEditorConfigPlatform() const = 0; virtual void ReloadTemplates() = 0; virtual IResourceSelectorHost* GetResourceSelectorHost() = 0; - virtual struct IBackgroundScheduleManager* GetBackgroundScheduleManager() = 0; virtual void ShowStatusText(bool bEnable) = 0; // Provides a way to extend the context menu of an object. The function gets called every time the menu is opened. diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index fb9b737733..380fc80e66 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -66,8 +66,6 @@ AZ_POP_DISABLE_WARNING #include "Objects/SelectionGroup.h" #include "Objects/ObjectManager.h" -#include "BackgroundTaskManager.h" -#include "BackgroundScheduleManager.h" #include "EditorFileMonitor.h" #include "MainStatusBar.h" @@ -176,8 +174,6 @@ CEditorImpl::CEditorImpl() regCtx.pCommandManager = m_pCommandManager; regCtx.pClassFactory = m_pClassFactory; m_pEditorFileMonitor.reset(new CEditorFileMonitor()); - m_pBackgroundTaskManager.reset(new BackgroundTaskManager::CTaskManager); - m_pBackgroundScheduleManager.reset(new BackgroundScheduleManager::CScheduleManager); m_pUIEnumsDatabase = new CUIEnumsDatabase; m_pDisplaySettings = new CDisplaySettings; m_pDisplaySettings->LoadRegistry(); @@ -843,16 +839,6 @@ IIconManager* CEditorImpl::GetIconManager() return m_pIconManager; } -IBackgroundTaskManager* CEditorImpl::GetBackgroundTaskManager() -{ - return m_pBackgroundTaskManager.get(); -} - -IBackgroundScheduleManager* CEditorImpl::GetBackgroundScheduleManager() -{ - return m_pBackgroundScheduleManager.get(); -} - IEditorFileMonitor* CEditorImpl::GetFileMonitor() { return m_pEditorFileMonitor.get(); diff --git a/Code/Sandbox/Editor/IEditorImpl.h b/Code/Sandbox/Editor/IEditorImpl.h index 7ad97d79e5..0ebd02b5fd 100644 --- a/Code/Sandbox/Editor/IEditorImpl.h +++ b/Code/Sandbox/Editor/IEditorImpl.h @@ -43,15 +43,12 @@ class CGameEngine; class CExportManager; class CErrorsDlg; class CIconManager; -class CBackgroundTaskManager; class CTrackViewSequenceManager; class CEditorFileMonitor; class AzAssetWindow; class AzAssetBrowserRequestHandler; class AssetEditorRequestsHandler; class CAlembicCompiler; -struct IBackgroundTaskManager; -struct IBackgroundScheduleManager; struct IEditorFileMonitor; class CVegetationMap; @@ -61,16 +58,6 @@ namespace Editor class EditorQtApplication; } -namespace BackgroundScheduleManager -{ - class CScheduleManager; -} - -namespace BackgroundTaskManager -{ - class CTaskManager; -} - namespace WinWidget { class WinWidgetManager; @@ -179,8 +166,6 @@ public: IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType); CMusicManager* GetMusicManager() { return m_pMusicManager; }; - IBackgroundTaskManager* GetBackgroundTaskManager() override; - IBackgroundScheduleManager* GetBackgroundScheduleManager() override; IEditorFileMonitor* GetFileMonitor() override; void RegisterEventLoopHook(IEventLoopHook* pHook) override; void UnregisterEventLoopHook(IEventLoopHook* pHook) override; @@ -394,8 +379,6 @@ protected: //! Export manager for exporting objects and a terrain from the game to DCC tools CExportManager* m_pExportManager; - std::unique_ptr m_pBackgroundTaskManager; - std::unique_ptr m_pBackgroundScheduleManager; std::unique_ptr m_pEditorFileMonitor; std::unique_ptr m_pResourceSelectorHost; QString m_selectFileBuffer; diff --git a/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h b/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h deleted file mode 100644 index bfa9eb6333..0000000000 --- a/Code/Sandbox/Editor/Include/IBackgroundScheduleManager.h +++ /dev/null @@ -1,207 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// -// IBackgroundScheduleManager manages schedule of group of larger operations that should be run in sequence -// -// Schedules are derived from IBackgroundSchedule and consist of a list of IBackgroundScheduleItems. -// Each schedule item is executed IN ORDER for the previous item to complete first. -// Each IBackgroundScheduleItems consists of list of user defined work via IBackgroundScheduleItemsWork classes. -// Each schedule item work is executed IN PARALEL (they are all started when the item starts). -// -// Whenever a work item fails to complete the other work items are stopped, the schedule item is marked as "failed" -// and so is the whole schedule. -// -// All logic is performed on the main thread although schedule items are free to use threads. -// It is recommended to use IBackgroundTaskManager for dispatching a task list for every schedule work item. -// -// All objects in the schedule system are reference counted. -// - -// State of the whole schedule - -#ifndef CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H -#define CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H -#pragma once -enum EScheduleState -{ - // Item has not started yet but is on the list - eScheduleState_Pending, - - // We are processing this item - eScheduleState_Processing, - - // We are stopping the schedule - eSccheduleState_Stopping, - - // Schedule item has failed - eScheduleState_Failed, - - // Schedule item was canceled - eScheduleState_Canceled, - - // Schedule item has completed it's work - eScheduleState_Completed, -}; - -// State of the single schedule item -enum EScheduleItemState -{ - // Item has not started yet but is on the list - eScheduleItemState_Pending, - - // We are processing this item - eScheduleItemState_Processing, - - // We are stopping this item - eScheduleItemState_Stopping, - - // Schedule item has failed - eScheduleItemState_Failed, - - // Schedule item has completed it's work - eScheduleItemState_Completed, -}; - -// Work item status -enum EScheduleWorkItemStatus -{ - // Work is still not finished - eScheduleWorkItemStatus_NotFinished, - - // Work has failed - eScheduleWorkItemStatus_Failed, - - // Work has finished - eScheduleWorkItemStatus_Finished, -}; - -struct IBackgroundScheduleItemWork -{ - // Get human readable description - virtual const char* GetDescription() const = 0; - - // Get work item progress - virtual float GetProgress() const = 0; - - // Called when the schedule item containing this work piece has started - // If the work cannot be started for any reason return false. - virtual bool OnStart() = 0; - - // Called when the schedule item containing this work piece has been canceled or failed externally - // Not called when schedule item completed without errors. - // If the work cannot be stopped this frame return false. - virtual bool OnStop() = 0; - - // Called every frame to advance and check the work state - // Should return one of the EBackgroundScheduleWorkItemStatus value - virtual EScheduleWorkItemStatus OnUpdate() = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundScheduleItemWork() {}; -}; - -struct IBackgroundScheduleItem -{ - // Get name of the schedule (debug & display) - virtual const char* GetDescription() const = 0; - - // Get interal state - virtual EScheduleItemState GetState() const = 0; - - // Get overall progress of this schedule item - virtual const float GetProgress() const = 0; - - // Get number of work items in this schedule item - virtual const uint32 GetNumWorkItems() const = 0; - - // Get n-th work item from the schedule item - virtual IBackgroundScheduleItemWork* GetWorkItem(const uint32 index) const = 0; - - // Add work item to the schedule item - virtual void AddWorkItem(IBackgroundScheduleItemWork* pWork) = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundScheduleItem() {}; -}; - -struct IBackgroundSchedule -{ - // Get name of the schedule (debug & display) - virtual const char* GetDescription() const = 0; - - // Get overall progress of the whole schedule - virtual float GetProgress() const = 0; - - // Get item being currently processed - virtual IBackgroundScheduleItem* GetProcessedItem() const = 0; - - // Get number of items in the schedule - virtual const uint32 GetNumItems() const = 0; - - // Get single schedule item - virtual IBackgroundScheduleItem* GetItem(const uint32 index) const = 0; - - // Get schedule item - virtual EScheduleState GetState() const = 0; - - // Cancel the whole schedule - virtual void Cancel() = 0; - - // Is the schedule canceled ? - virtual bool IsCanceled() const = 0; - - // Add schedule item at the end of the list - virtual void AddItem(IBackgroundScheduleItem* pItem) = 0; - - // Reference counting - virtual void AddRef() = 0; - virtual void Release() = 0; - -protected: - virtual ~IBackgroundSchedule() {}; -}; - -struct IBackgroundScheduleManager -{ - virtual ~IBackgroundScheduleManager() {}; - - // Create empty schedule - virtual IBackgroundSchedule* CreateSchedule(const char* szName) = 0; - - // Create empty schedule item - virtual IBackgroundScheduleItem* CreateScheduleItem(const char* szName) = 0; - - // Issue a schedule to the list (will start processing it) - virtual void SubmitSchedule(IBackgroundSchedule* pSchedule) = 0; - - // Get number of schedules on the list - virtual const uint32 GetNumSchedules() const = 0; - - // Get n-th schedule - virtual IBackgroundSchedule* GetSchedule(const uint32 index) const = 0; - - // Advance work on the schedules - virtual void Update() = 0; -}; - - -#endif // CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDSCHEDULEMANAGER_H diff --git a/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h b/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h deleted file mode 100644 index b586e3022f..0000000000 --- a/Code/Sandbox/Editor/Include/IBackgroundTaskManager.h +++ /dev/null @@ -1,230 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// -// IBackgroundTaskManager runs background tasks in worker thread. -// -// Tasks are derived from IBackgroundTask. Each task is split in two parts for: -// Work - done in background thread. -// Finalize - called afterward in main thread to apply results. -// -// Task objects are reference counted. Task manager will hold its own reference to the task object -// for as long as the task is pending or being executed. If you want to keep the task object around -// in your code you will have to call AddRef() and Release() on the task object by yourself so there -// will be an extra reference to the task object held by your code. -// -// Work returns the state of the task. Task can be resumed, then the Work -// method will be called again. Other tasks can work between calls to Work. -// It is possible to Cancel task. Work method is not invoked any more for -// Canceled tasks. -// - -#ifndef CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H -#define CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H -#pragma once - -enum ETaskPriority -{ - eTaskPriority_FileUpdateFinal, - eTaskPriority_BackgroundScan, - eTaskPriority_FileUpdate, - eTaskPriority_RealtimePreview -}; - -// Result code returned by task Work() function -enum ETaskResult -{ - // Task has not yet completed, add it back to the task queue with the same parameters (priority and thread mask) - eTaskResult_Resume, - - // Task has completed without errors (it's assumed that the result the task was supposed to achieve was achieved) - eTaskResult_Completed, - - // Task was canceled - eTaskResult_Canceled, - - // Task has failed to complete it's work - eTaskResult_Failed, -}; - -// Internal task tracking state -enum ETaskState -{ - // Task was just created. - eTaskState_Created, - - // Task was scheduled to be executed in the future. - eTaskState_Scheduled, - - // Task was added to the task queue and is waiting for it's time to be executed. - eTaskState_Pending, - - // Task is being processed right now. - eTaskState_Working, - - // Task was canceled before it has finished (indication that TaskManager has seen the Cancel() call). - eTaskState_Canceled, - - // Task Work() function was called but it ended with an error code. - eTaskState_Failed, - - // Task has completed it's Work() function without errors. - eTaskState_Completed, -}; - -// Thread mask controls which on which threads given task can be executed. -enum ETaskThreadMask -{ - // Task can run only on the IO thread (default) - // There is only one IO thread so all task with this flag are run in a sequence. - eTaskThreadMask_IO, - - // Task can run on any thread (concurrent tasks allowed) - // There can be many threads with this mask so there's no limit on the concurrent task count. - eTaskThreadMask_Any, - - eTaskThreadMask_COUNT, -}; - -struct IBackgroundTask -{ -public: - IBackgroundTask() - : m_bCanceled(false) - , m_state(eTaskState_Created) - , m_progress(-1.0f) - , m_refCount(0) - , m_bFailReported(false) - {} - - void Cancel() - { - m_bCanceled = true; - } - - bool IsCanceled() const - { - return m_bCanceled; - } - - bool HasFinished() const - { - return (m_state == eTaskState_Canceled) || - (m_state == eTaskState_Completed) || - (m_state == eTaskState_Failed); - } - - bool HasFinishedWithoutError() const - { - return (m_state == eTaskState_Completed); - } - - ETaskState GetState() const - { - return m_state; - } - - void SetState(ETaskState state) - { - m_state = state; - } - - float GetProgress() const - { - return m_progress; - } - - int AddRef() - { - return CryInterlockedIncrement(&m_refCount); - } - - int Release() - { - const int nCount = CryInterlockedDecrement(&m_refCount); - assert(nCount >= 0); - if (nCount == 0) - { - Delete(); - } - else if (nCount < 0) - { - assert(0); - CryFatalError("Deleting Reference Counted Object Twice"); - } - return nCount; - } - - bool FailReported() const{ return m_bFailReported; } - - // Get the user readable description (name) of this task, used for logging - virtual const char* Description() const { return ""; } - - // Get the user readable error message (in case when the task fails), used for logging the errors - virtual const char* ErrorMessage() const { return ""; } - - // Called from main thread after task is completed just before the task gets destroyed - virtual void Finalize() {} - - // Since there's a possibility that task object were created using different allocator - // we need a way to delete the task object once we are done with it - virtual void Delete() = 0; - - // Invoked from worker thread, actual work is done here - virtual ETaskResult Work() = 0; - -protected: - void SetProgress(float progress) { m_progress = progress; } - void SetFailReported() { m_bFailReported = true; } - - // destructor is hidden to indicate that we should use Release() method - virtual ~IBackgroundTask() {} - -private: - volatile int m_refCount; - ETaskState m_state; - float m_progress; - bool m_bCanceled; - bool m_bFailReported; -}; - -struct IBackgroundTaskManagerListener -{ - virtual ~IBackgroundTaskManagerListener() {} - - virtual void OnBackgroundTaskAdded(const char* description) = 0; - virtual void OnBackgroundTaskCompleted(ETaskResult taskResult, const char* description) = 0; -}; - -struct IBackgroundTaskManager -{ - enum - { - BACKGROUND_TASK_ID_INVALID = 0 - }; - - virtual ~IBackgroundTaskManager() {} - - // Add task to the queue with given priority and thread mask - virtual void AddTask(IBackgroundTask* pTask, ETaskPriority priority, ETaskThreadMask threadMask) = 0; - - // Schedule task to be executed in the future - virtual void ScheduleTask(IBackgroundTask* pTask, ETaskPriority priority, int delayMilliseconds, ETaskThreadMask threadMask) = 0; - - virtual void AddListener(IBackgroundTaskManagerListener* pListener, const char* name) = 0; - - virtual void RemoveListener(IBackgroundTaskManagerListener* pListener) = 0; -}; - - -#endif // CRYINCLUDE_EDITOR_INCLUDE_IBACKGROUNDTASKMANAGER_H diff --git a/Code/Sandbox/Editor/LevelInfo.cpp b/Code/Sandbox/Editor/LevelInfo.cpp index 81441a3797..55c432094a 100644 --- a/Code/Sandbox/Editor/LevelInfo.cpp +++ b/Code/Sandbox/Editor/LevelInfo.cpp @@ -97,10 +97,6 @@ void CLevelInfo::ValidateObjects() pObject->Validate(m_pReport); - CUsedResources rs; - pObject->GatherUsedResources(rs); - rs.Validate(m_pReport); - m_pReport->SetCurrentValidatorObject(NULL); } diff --git a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h index 38a35e6684..949bc72e03 100644 --- a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h @@ -102,7 +102,6 @@ public: MOCK_METHOD0(GetViewManager, class CViewManager* ()); MOCK_METHOD0(GetActiveView, class CViewport* ()); MOCK_METHOD1(SetActiveView, void(CViewport*)); - MOCK_METHOD0(GetBackgroundTaskManager, struct IBackgroundTaskManager* ()); MOCK_METHOD0(GetFileMonitor, struct IEditorFileMonitor* ()); MOCK_METHOD1(RegisterEventLoopHook, void(IEventLoopHook* )); MOCK_METHOD1(UnregisterEventLoopHook, void(IEventLoopHook* )); @@ -184,7 +183,6 @@ public: MOCK_CONST_METHOD0(GetEditorConfigPlatform, ESystemConfigPlatform()); MOCK_METHOD0(ReloadTemplates, void()); MOCK_METHOD0(GetResourceSelectorHost, IResourceSelectorHost* ()); - MOCK_METHOD0(GetBackgroundScheduleManager, struct IBackgroundScheduleManager* ()); MOCK_METHOD1(ShowStatusText, void(bool )); MOCK_METHOD1(RegisterObjectContextMenuExtension, void(TContextMenuExtensionFunc )); MOCK_METHOD0(GetEnv, SSystemGlobalEnvironment* ()); diff --git a/Code/Sandbox/Editor/MainStatusBarItems.h b/Code/Sandbox/Editor/MainStatusBarItems.h index 3f43f1818f..095183363f 100644 --- a/Code/Sandbox/Editor/MainStatusBarItems.h +++ b/Code/Sandbox/Editor/MainStatusBarItems.h @@ -13,7 +13,6 @@ #pragma once #include -#include #include #include #include diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index e9b27ee9b8..6f6b600a84 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -92,7 +92,6 @@ AZ_POP_DISABLE_WARNING #include "ErrorReportDialog.h" #include "Dialogs/PythonScriptsDialog.h" -#include "EngineSettingsManager.h" #include "AzAssetBrowser/AzAssetBrowserWindow.h" #include "AssetEditor/AssetEditorWindow.h" @@ -1941,12 +1940,6 @@ void MainWindow::ConnectivityStateChanged(const AzToolsFramework::SourceControlS } } -#if defined(CRY_ENABLE_RC_HELPER) - CEngineSettingsManager settingsManager; - settingsManager.SetModuleSpecificBoolEntry("RC_EnableSourceControl", connected); - settingsManager.StoreData(); -#endif - gSettings.enableSourceControl = connected; gSettings.SaveEnableSourceControlFlag(false); } diff --git a/Code/Sandbox/Editor/Objects/EntityObject.h b/Code/Sandbox/Editor/Objects/EntityObject.h index 85368f7804..b367384f08 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.h +++ b/Code/Sandbox/Editor/Objects/EntityObject.h @@ -35,7 +35,6 @@ class CEntityObject; class QMenu; -class IOpticsElementBase; /*! * CEntityEventTarget is an Entity event target and type. diff --git a/Code/Sandbox/Editor/UsedResources.cpp b/Code/Sandbox/Editor/UsedResources.cpp index 35384b0f34..013d35d4a7 100644 --- a/Code/Sandbox/Editor/UsedResources.cpp +++ b/Code/Sandbox/Editor/UsedResources.cpp @@ -27,38 +27,3 @@ void CUsedResources::Add(const char* pResourceFileName) files.insert(pResourceFileName); } } - -void CUsedResources::Validate(IErrorReport* pReport) -{ - auto pPak = gEnv->pCryPak; - - for (TResourceFiles::iterator it = files.begin(); it != files.end(); ++it) - { - const QString& filename = *it; - - bool fileExists = pPak->IsFileExist(filename.toUtf8().data()); - - if (!fileExists) - { - for (int i = 0; !fileExists && i < IResourceCompilerHelper::GetNumEngineImageFormats(); ++i) - { - fileExists = gEnv->pCryPak->IsFileExist(PathUtil::ReplaceExtension(filename.toUtf8().data(), IResourceCompilerHelper::GetEngineImageFormat(i, true)).c_str()); - } - for (int i = 0; !fileExists && i < IResourceCompilerHelper::GetNumSourceImageFormats(); ++i) - { - fileExists = gEnv->pCryPak->IsFileExist(PathUtil::ReplaceExtension(filename.toUtf8().data(), IResourceCompilerHelper::GetSourceImageFormat(i, true)).c_str()); - } - } - - - if (!fileExists) - { - CErrorRecord err; - - err.error = QObject::tr("Resource File %1 not found,").arg(filename); - err.severity = CErrorRecord::ESEVERITY_ERROR; - err.flags |= CErrorRecord::FLAG_NOFILE; - pReport->ReportError(err); - } - } -} diff --git a/Code/Sandbox/Editor/UsedResources.h b/Code/Sandbox/Editor/UsedResources.h index e22c672d30..acf8b79783 100644 --- a/Code/Sandbox/Editor/UsedResources.h +++ b/Code/Sandbox/Editor/UsedResources.h @@ -36,8 +36,6 @@ public: CUsedResources(); void Add(const char* pResourceFileName); - //! validate gathered resources, reports warning if resource is not found - void Validate(struct IErrorReport* pReport); AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING TResourceFiles files; diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index 3d6112d186..401b7c6e39 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -280,8 +280,6 @@ set(FILES Include/IAnimationCompressionManager.h Include/IAssetItem.h Include/IAssetItemDatabase.h - Include/IBackgroundScheduleManager.h - Include/IBackgroundTaskManager.h Include/ICommandManager.h Include/IConsoleConnectivity.h Include/IDataBaseItem.h @@ -343,10 +341,6 @@ set(FILES AssetEditor/AssetEditorWindow.cpp AssetEditor/AssetEditorWindow.h AssetEditor/AssetEditorWindow.ui - BackgroundTaskManager.cpp - BackgroundScheduleManager.cpp - BackgroundTaskManager.h - BackgroundScheduleManager.h Commands/CommandManager.cpp Commands/CommandManager.h Controls/BitmapToolTip.cpp diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 33d4b5baf4..f38b295128 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -160,7 +160,6 @@ void SandboxIntegrationManager::Setup() AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); AzFramework::DisplayContextRequestBus::Handler::BusConnect(); - SetupFileExtensionMap(); MainWindow::instance()->GetActionManager()->RegisterActionHandler(ID_FILE_SAVE_SLICE_TO_ROOT, [this]() { SaveSlice(false); @@ -1926,30 +1925,6 @@ void SandboxIntegrationManager::MakeSliceFromEntities(const AzToolsFramework::En AzToolsFramework::SliceUtilities::MakeNewSlice(entitiesAndDescendants, path, inheritSlices, setAsDynamic); } -void SandboxIntegrationManager::SetupFileExtensionMap() -{ - // There's no central registry for geometry file types. - const char* geometryFileExtensions[] = - { - CRY_GEOMETRY_FILE_EXT, // .cgf - CRY_SKEL_FILE_EXT, // .chr - CRY_CHARACTER_DEFINITION_FILE_EXT, // .cdf - }; - - // Cry geometry file extensions. - for (const char* extension : geometryFileExtensions) - { - m_extensionToFileType[AZ::Crc32(extension)] = IFileUtil::EFILE_TYPE_GEOMETRY; - } - - // Cry image file extensions. - for (size_t i = 0; i < IResourceCompilerHelper::GetNumSourceImageFormats(); ++i) - { - const char* extension = IResourceCompilerHelper::GetSourceImageFormat(i, false); - m_extensionToFileType[AZ::Crc32(extension)] = IFileUtil::EFILE_TYPE_TEXTURE; - } -} - void SandboxIntegrationManager::RegisterViewPane(const char* name, const char* category, const AzToolsFramework::ViewPaneOptions& viewOptions, const WidgetCreationFunc& widgetCreationFunc) { QtViewPaneManager::instance()->RegisterPane(name, category, widgetCreationFunc, viewOptions); diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h index b3c60bca45..14f52591a4 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h @@ -319,12 +319,10 @@ private: void OnLayerComponentDeactivated(AZ::EntityId entityId) override; private: - void SetupFileExtensionMap(); // Right click context menu when a layer is included in the selection. void SetupLayerContextMenu(QMenu* menu); void SetupSliceContextMenu(QMenu* menu); void SetupSliceContextMenu_Modify(QMenu* menu, const AzToolsFramework::EntityIdList& selectedEntities, const AZ::u32 numEntitiesInSlices); - void SetupScriptCanvasContextMenu(QMenu* menu); void SaveSlice(const bool& QuickPushToFirstLevel); void GetEntitiesInSlices(const AzToolsFramework::EntityIdList& selectedEntities, AZ::u32& entitiesInSlices, AZStd::vector& sliceInstances); @@ -348,9 +346,6 @@ private: }; private: - typedef AZStd::unordered_map ExtensionMap; - ExtensionMap m_extensionToFileType; - AZ::Vector2 m_contextMenuViewPoint; AZ::Vector3 m_sliceWorldPos; diff --git a/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h b/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h deleted file mode 100644 index 1d557e35f7..0000000000 --- a/Code/Sandbox/Plugins/MaglevControlPanel/CloudCanvasPythonWorkerInterface.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include - -#include - -using PythonWorkerRequestId = int; - -//! Interface to signal the python worker output -class PythonWorkerEventsInterface -{ -protected: - PythonWorkerEventsInterface() = default; - virtual ~PythonWorkerEventsInterface() = default; - PythonWorkerEventsInterface(PythonWorkerEventsInterface&&) = delete; - PythonWorkerEventsInterface& operator=(PythonWorkerEventsInterface&&) = delete; - -public: - AZ_RTTI(PythonWorkerEventsInterface, "{60C83A5A-B8DD-4B98-B8C6-DC2F5914D7C4}"); - - // if any OnOutput returns true, it means the command was handled and the worker won't process any further - virtual bool OnPythonWorkerOutput(PythonWorkerRequestId requestId, const QString& key, const QVariant& value) = 0; -}; - -//! Interface to send the python worker requests -class PythonWorkerRequestsInterface -{ -protected: - PythonWorkerRequestsInterface() = default; - virtual ~PythonWorkerRequestsInterface() = default; - PythonWorkerRequestsInterface(PythonWorkerRequestsInterface&&) = delete; - PythonWorkerRequestsInterface& operator=(PythonWorkerRequestsInterface&&) = delete; - -public: - AZ_RTTI(PythonWorkerRequestsInterface, "{B0293028-3575-408E-8CE3-D1B7F3C59A6C}"); - - virtual PythonWorkerRequestId AllocateRequestId() = 0; - virtual void ExecuteAsync(PythonWorkerRequestId requestId, const char* command, const QVariantMap& args = QVariantMap{}) = 0; - virtual bool IsStarted() = 0; -}; - diff --git a/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp b/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp deleted file mode 100644 index 1508e9f7b0..0000000000 --- a/Code/Sandbox/Plugins/MaglevControlPanel/MaglevControlPanelPlugin_stub.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "stdafx.h" -#include -#include - -const char* TAG = "MaglevControlPanelPlugin"; - -MaglevControlPanelPlugin::MaglevControlPanelPlugin(IEditor* editor) - : m_pluginSettings(QSettings::IniFormat, QSettings::UserScope, "Amazon", "Lumberyard") -{ - -} - -void MaglevControlPanelPlugin::Release() -{ -} - -void MaglevControlPanelPlugin::OnEditorNotify(EEditorNotifyEvent aEventId) -{ -} - diff --git a/Code/Tools/CryCommonTools/Export/AnimationData.cpp b/Code/Tools/CryCommonTools/Export/AnimationData.cpp deleted file mode 100644 index 2b2c5966a6..0000000000 --- a/Code/Tools/CryCommonTools/Export/AnimationData.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "AnimationData.h" - -AnimationData::AnimationData(int modelCount, float fps, float startTime) - : m_entries(modelCount) - , m_frameCount(0) - , m_startTime(startTime) - , m_fps(fps) -{ -} - -void AnimationData::SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) -{ - State& state = m_entries[modelIndex].samples[frameIndex]; - state.translation[0] = translation[0]; - state.translation[1] = translation[1]; - state.translation[2] = translation[2]; - state.rotation[0] = rotation[0]; - state.rotation[1] = rotation[1]; - state.rotation[2] = rotation[2]; - state.scale[0] = scale[0]; - state.scale[1] = scale[1]; - state.scale[2] = scale[2]; -} - -void AnimationData::SetFrameCount(int frameCount) -{ - m_frameCount = frameCount; - for (int modelIndex = 0, modelCount = int(m_entries.size()); modelIndex < modelCount; ++modelIndex) - { - m_entries[modelIndex].samples.resize(frameCount); - } -} - -void AnimationData::SetModelFlags(int modelIndex, unsigned modelFlags) -{ - m_entries[modelIndex].flags = modelFlags; -} - -void AnimationData::GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const -{ - translation = m_entries[modelIndex].samples[frameIndex].translation; - rotation = m_entries[modelIndex].samples[frameIndex].rotation; - scale = m_entries[modelIndex].samples[frameIndex].scale; -} - -void AnimationData::GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const -{ - translation = m_entries[modelIndex].samples[frameIndex].translation; -} - -void AnimationData::GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const -{ - rotation = m_entries[modelIndex].samples[frameIndex].rotation; -} - -void AnimationData::GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const -{ - scale = m_entries[modelIndex].samples[frameIndex].scale; -} - -int AnimationData::GetFrameCount() const -{ - return m_frameCount; -} - -unsigned AnimationData::GetModelFlags(int modelIndex) const -{ - return m_entries[modelIndex].flags; -} - -AnimationData::State::State() -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} - -AnimationData::ModelEntry::ModelEntry() - : flags(0) -{ -} - -/////////////////////////////////////////////////////////////////////////// -NonSkeletalAnimationData::NonSkeletalAnimationData(int modelCount) - : m_entries(modelCount) -{ -} - -void NonSkeletalAnimationData::SetModelFlags(int modelIndex, unsigned modelFlags) -{ - m_entries[modelIndex].flags = modelFlags; -} - -unsigned NonSkeletalAnimationData::GetModelFlags(int modelIndex) const -{ - return m_entries[modelIndex].flags; -} - -void NonSkeletalAnimationData::SetFrameTimePos(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.data[0] = translation[0]; - state.data[1] = translation[1]; - state.data[2] = translation[2]; -} - -void NonSkeletalAnimationData::SetFrameCountPos(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesPos.resize(frameCount); -} - -void NonSkeletalAnimationData::SetFrameTimeRot(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.data[0] = rotation[0]; - state.data[1] = rotation[1]; - state.data[2] = rotation[2]; -} - -void NonSkeletalAnimationData::SetFrameCountRot(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesRot.resize(frameCount); -} - -void NonSkeletalAnimationData::SetFrameTimeScl(int modelIndex, int frameIndex, float time) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.time = time; -} - -void NonSkeletalAnimationData::SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.data[0] = scale[0]; - state.data[1] = scale[1]; - state.data[2] = scale[2]; -} - -void NonSkeletalAnimationData::SetFrameCountScl(int modelIndex, int frameCount) -{ - m_entries[modelIndex].samplesScl.resize(frameCount); -} - -float NonSkeletalAnimationData::GetFrameTimePos(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesPos[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const -{ - translation = m_entries[modelIndex].samplesPos[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountPos(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesPos.size()); -} - -float NonSkeletalAnimationData::GetFrameTimeRot(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesRot[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const -{ - rotation = m_entries[modelIndex].samplesRot[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountRot(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesRot.size()); -} - -float NonSkeletalAnimationData::GetFrameTimeScl(int modelIndex, int frameIndex) const -{ - return m_entries[modelIndex].samplesScl[frameIndex].time; -} - -void NonSkeletalAnimationData::GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const -{ - scale = m_entries[modelIndex].samplesScl[frameIndex].data; -} - -int NonSkeletalAnimationData::GetFrameCountScl(int modelIndex) const -{ - return int(m_entries[modelIndex].samplesScl.size()); -} - -void NonSkeletalAnimationData::SetFrameTCBPos(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameTCBRot(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameTCBScl(int modelIndex, int frameIndex, IAnimationData::TCB tcb) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.tcb = tcb; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutPos(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesPos[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutRot(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesRot[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::SetFrameEaseInOutScl(int modelIndex, int frameIndex, IAnimationData::Ease ease) -{ - State& state = m_entries[modelIndex].samplesScl[frameIndex]; - state.ease = ease; -} - -void NonSkeletalAnimationData::GetFrameTCBPos(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesPos[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameTCBRot(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesRot[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameTCBScl(int modelIndex, int frameIndex, IAnimationData::TCB& tcb) const -{ - const State& state = m_entries[modelIndex].samplesScl[frameIndex]; - tcb = state.tcb; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutPos(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesPos[frameIndex]; - ease = state.ease; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutRot(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesRot[frameIndex]; - ease = state.ease; -} - -void NonSkeletalAnimationData::GetFrameEaseInOutScl(int modelIndex, int frameIndex, IAnimationData::Ease& ease) const -{ - const State& state = m_entries[modelIndex].samplesScl[frameIndex]; - ease = state.ease; -} - - -NonSkeletalAnimationData::State::State() -{ - time = 0.0f; - data[0] = data[1] = data[2] = 0.0f; -} - -NonSkeletalAnimationData::ModelEntry::ModelEntry() - : flags(0) -{ -} diff --git a/Code/Tools/CryCommonTools/Export/AnimationData.h b/Code/Tools/CryCommonTools/Export/AnimationData.h deleted file mode 100644 index 65b699e49b..0000000000 --- a/Code/Tools/CryCommonTools/Export/AnimationData.h +++ /dev/null @@ -1,211 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H -#pragma once - - -#include "IAnimationData.h" - -#include - -// Animation data class for skeletal animations -// It has a same count of samples for all models(bones) -// and always has translation/rotation/scaling data together as a set. -class AnimationData - : public IAnimationData -{ -public: - AnimationData(int modelCount, float fps, float startTime); - virtual ~AnimationData() {} - - // IAnimationData - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]); - virtual void SetFrameCount(int frameCount); - virtual void SetModelFlags(int modelIndex, unsigned modelFlags); - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) - { assert(0); } - virtual void SetFrameCountPos(int modelIndex, int frameCount) - { assert(0); } - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) - { assert(0); } - virtual void SetFrameCountRot(int modelIndex, int frameCount) - { assert(0); } - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time) - { assert(0); } - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) - { assert(0); } - virtual void SetFrameCountScl(int modelIndex, int frameCount) - { assert(0); } - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const; - virtual int GetFrameCount() const; - virtual unsigned GetModelFlags(int modelIndex) const; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const; - virtual int GetFrameCountPos(int) const - { return GetFrameCount(); } - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const; - virtual int GetFrameCountRot(int) const - { return GetFrameCount(); } - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const - { return m_startTime + frameIndex / m_fps; } - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const; - virtual int GetFrameCountScl(int) const - { return GetFrameCount(); } - - // TCB & Ease-In/-Out not supported for the skeletal animation. - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb) - { assert(0); } - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease) - { assert(0); } - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const - { assert(0); } - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const - { assert(0); } - -private: - struct State - { - public: - State(); - float translation[3]; - float rotation[3]; - float scale[3]; - }; - - struct ModelEntry - { - ModelEntry(); - - unsigned flags; - std::vector samples; - }; - - std::vector m_entries; - int m_frameCount; - float m_startTime; - float m_fps; -}; - -// Animation data class for non-skeletal animations -// It can have different counts of samples for each model -// and each channel of transformation data. -class NonSkeletalAnimationData - : public IAnimationData -{ -public: - NonSkeletalAnimationData(int modelCount); - virtual ~NonSkeletalAnimationData() {} - - // IAnimationData - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) - { assert(0); } - virtual void SetFrameCount(int frameCount) - { assert(0); } - virtual void SetModelFlags(int modelIndex, unsigned modelFlags); - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]); - virtual void SetFrameCountPos(int modelIndex, int frameCount); - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]); - virtual void SetFrameCountRot(int modelIndex, int frameCount); - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time); - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]); - virtual void SetFrameCountScl(int modelIndex, int frameCount); - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const - { assert(0); } - virtual int GetFrameCount() const - { - assert(0); - return 0; - } - virtual unsigned GetModelFlags(int modelIndex) const; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const; - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const; - virtual int GetFrameCountPos(int) const; - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const; - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const; - virtual int GetFrameCountRot(int) const; - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const; - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const; - virtual int GetFrameCountScl(int) const; - - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb); - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease); - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease); - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease); - - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const; - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const; - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const; - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const; - -private: - struct State - { - public: - State(); - float time; - float data[3]; - TCB tcb; - Ease ease; - }; - - struct ModelEntry - { - ModelEntry(); - - unsigned flags; - std::vector samplesPos; - std::vector samplesRot; - std::vector samplesScl; - }; - - std::vector m_entries; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ANIMATIONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp b/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp deleted file mode 100644 index d724e349be..0000000000 --- a/Code/Tools/CryCommonTools/Export/CBAHelpers.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "CBAHelpers.h" -#include "../PathHelpers.h" -#include "StringHelpers.h" - -static string FindRootContainingFileGoingUpwards(const char* filePath, const char* filePathToLookFor, IPakSystem* pakSystem) -{ - // Here we just search upwards from the current directory, looking for a directory that - // contains a file at the relative path "Animations/Animations.cba". This is designed to - // handle root Game paths that differ from the default "Game". - string rootDirCandidate = PathHelpers::GetDirectory(filePath); - string rootDir; - while (!rootDirCandidate.empty()) - { - string cbaCandidatePath = PathHelpers::Join(rootDirCandidate, filePathToLookFor); - if (PakSystemFile* file = pakSystem->Open(cbaCandidatePath.c_str(), "r")) - { - // File exists, we have found the correct root path. - pakSystem->Close(file); - - rootDir = rootDirCandidate; - break; - } - - string previousCandidate = rootDirCandidate; - rootDirCandidate = PathHelpers::GetDirectory(rootDirCandidate); - if (rootDirCandidate == previousCandidate) - { - break; - } - } - - return (rootDir.empty() ? rootDir : PathHelpers::Join(rootDir, filePathToLookFor)); -} - -string CBAHelpers::FindCBAFileForFile(const char* filePath, IPakSystem* pakSystem) -{ - return FindRootContainingFileGoingUpwards(filePath, "Animations/Animations.cba", pakSystem); -} - -string CBAHelpers::FindSkeletonListForFile(const char* filePath, IPakSystem* pakSystem) -{ - return FindRootContainingFileGoingUpwards(filePath, "Animations/SkeletonList.xml", pakSystem); -} diff --git a/Code/Tools/CryCommonTools/Export/CBAHelpers.h b/Code/Tools/CryCommonTools/Export/CBAHelpers.h deleted file mode 100644 index 48af5c74d2..0000000000 --- a/Code/Tools/CryCommonTools/Export/CBAHelpers.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H -#pragma once - - -#include "IPakSystem.h" - -namespace CBAHelpers -{ - string FindCBAFileForFile(const char* filePath, IPakSystem* pakSystem); - string FindSkeletonListForFile(const char* filePath, IPakSystem* pakSystem); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_CBAHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp b/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp deleted file mode 100644 index d0796a4838..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.cpp +++ /dev/null @@ -1,556 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" - -#include "ColladaExportWriter.h" -#include "ColladaWriter.h" -#include "IExportSource.h" -#include "PathHelpers.h" -#include "ResourceCompilerHelper.h" -#include "SettingsManagerHelpers.h" -#include "IExportContext.h" -#include "ProgressRange.h" -#include "XMLWriter.h" -#include "XMLPakFileSink.h" -#include "ISettings.h" -#include "SingleAnimationExportSourceAdapter.h" -#include "GeometryExportSourceAdapter.h" -#include "ModelData.h" -#include "MaterialData.h" -#include "GeometryFileData.h" -#include "FileUtil.h" -#include "CBAHelpers.h" -#include "ModuleHelpers.h" -#include "PropertyHelpers.h" -#include "StringHelpers.h" -#include -#include - -namespace -{ - class ResourceCompilerLogListener - : public IResourceCompilerListener - { - public: - ResourceCompilerLogListener(IExportContext* context) - : m_context(context) - { - } - - virtual void OnRCMessage(IResourceCompilerListener::MessageSeverity severity, const char* text) - { - ILogger::ESeverity outSeverity; - switch (severity) - { - case IResourceCompilerListener::MessageSeverity_Debug: - case IResourceCompilerListener::MessageSeverity_Info: // normal RC text should just be debug - outSeverity = ILogger::eSeverity_Debug; - break; - case IResourceCompilerListener::MessageSeverity_Warning: - outSeverity = ILogger::eSeverity_Warning; - break; - case IResourceCompilerListener::MessageSeverity_Error: - outSeverity = ILogger::eSeverity_Error; - break; - default: - outSeverity = ILogger::eSeverity_Error; - break; - } - - m_context->Log(outSeverity, "%s", text); - } - - private: - IExportContext* m_context; - }; -} - -void ColladaExportWriter::Export(IExportSource* source, IExportContext* context) -{ - // Create an object to report on our progress to the export context. - ProgressRange progressRange(context, &IExportContext::SetProgress); - CResourceCompilerHelper compiler; // we need a real instance of this specific implementation. - - // Log build information. - context->Log(ILogger::eSeverity_Info, "Exporter build created on " __DATE__); - -#ifdef STLPORT - context->Log(ILogger::eSeverity_Info, "Using STLport C++ Standard Library implementation"); -#else //STLPORT - context->Log(ILogger::eSeverity_Info, "Using Microsoft (tm) C++ Standard Library implementation"); -#endif //STLPORT - -#if defined(_DEBUG) - context->Log(ILogger::eSeverity_Info, "******DEBUG BUILD******"); -#else //_DEBUG - context->Log(ILogger::eSeverity_Info, "Release build."); -#endif //_DEBUG - - context->Log(ILogger::eSeverity_Debug, "Bit count == %d.", (sizeof(void*) * 8)); - - std::string exePath = StringHelpers::ConvertString(ModuleHelpers::GetCurrentModulePath(ModuleHelpers::CurrentModuleSpecifier_Executable)); - context->Log(ILogger::eSeverity_Debug, "Application path: %s", exePath.c_str()); - - std::string exporterPath = StringHelpers::ConvertString(ModuleHelpers::GetCurrentModulePath(ModuleHelpers::CurrentModuleSpecifier_Library)); - context->Log(ILogger::eSeverity_Debug, "Exporter path: %s", exporterPath.c_str()); - - bool const bExportCompressed = (GetSetting(context->GetSettings(), "ExportCompressedCOLLADA", 1)) != 0; - context->Log(ILogger::eSeverity_Debug, "ExportCompressedCOLLADA key: %d", (bExportCompressed ? 1 : 0)); - - std::string const exportExtension = bExportCompressed ? ".dae.zip" : ".dae"; - - // Log the start time. - { - char buf[1024]; - std::time_t t = std::time(0); - std::strftime(buf, sizeof(buf) / sizeof(buf[0]), "%H:%M:%S on %a, %d/%m/%Y", std::localtime(&t)); - context->Log(ILogger::eSeverity_Info, "Export begun at %s", buf); - } - - // Select the name of the directory to export to. - std::string const originalExportDirectory = source->GetExportDirectory(); - if (originalExportDirectory.empty()) - { - throw IExportContext::NeedSaveError("Scene must be saved before exporting."); - } - - GeometryFileData geometryFileData; - std::vector colladaGeometryFileNameList; - std::vector assetGeometryFileNameList; - typedef std::vector, std::string> > AnimationFileNameList; - AnimationFileNameList animationFileNameList; - AnimationFileNameList animationCompileFileNameList; - { - CurrentTaskScope currentTask(context, "dae"); - - // Choose the files to which to export all the animations. - std::list animationExportSources; - std::list geometryExportSources; - typedef std::vector > ExportList; - ExportList exportList; - std::vector geometryFileIndices; - { - ProgressRange readProgressRange(progressRange, 0.2f); - - source->ReadGeometryFiles(context, &geometryFileData); - - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileData.GetGeometryFileCount(); ++geometryFileIndex) - { - const std::string geometryFileName = geometryFileData.GetGeometryFileName(geometryFileIndex); - - IGeometryFileData::SProperties properties = geometryFileData.GetProperties(geometryFileIndex); - if (properties.filetypeInt == CRY_FILE_TYPE_CAF) - { - // LDS: This is a temporary fix for some old hacky code that would activate a deprecated compression path during export - // It needs a proper fix by tearing out the old compression code and moving the system to the new i_caf system by default. - // See for http://docs.cryengine.com/display/SDKDOC3/Transition+from+CBA+to+AnimSettings details. - properties.filetypeInt = CRY_FILE_TYPE_INTERMEDIATE_CAF; - geometryFileData.SetProperties(geometryFileIndex, properties); - } - - bool const hasGeometry = (properties.filetypeInt != CRY_FILE_TYPE_CAF && - properties.filetypeInt != CRY_FILE_TYPE_INTERMEDIATE_CAF); - - if (hasGeometry && !geometryFileName.empty()) - { - geometryFileIndices.push_back(geometryFileIndex); - } - } - - if (!geometryFileIndices.empty()) - { - std::string name = PathHelpers::RemoveExtension(PathHelpers::GetFilename(source->GetDCCFileName())); - std::replace(name.begin(), name.end(), ' ', '_'); - std::string const colladaPath = PathHelpers::Join(originalExportDirectory, name + exportExtension); - colladaGeometryFileNameList.push_back(colladaPath); - - geometryExportSources.push_back(GeometryExportSourceAdapter(source, &geometryFileData, geometryFileIndices)); - exportList.push_back(std::make_pair(colladaPath, &geometryExportSources.back())); - } - - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileData.GetGeometryFileCount(); ++geometryFileIndex) - { - std::string const geometryFileName = geometryFileData.GetGeometryFileName(geometryFileIndex); - int const fileTypeInt = geometryFileData.GetProperties(geometryFileIndex).filetypeInt; - std::string customExportPath = geometryFileData.GetProperties(geometryFileIndex).customExportPath; - bool const hasGeometry = (fileTypeInt != CRY_FILE_TYPE_CAF && - fileTypeInt != CRY_FILE_TYPE_INTERMEDIATE_CAF); - - if (hasGeometry && !geometryFileName.empty()) - { - std::string extension = "missingextension"; - if (fileTypeInt == CRY_FILE_TYPE_CGF) - { - extension = "cgf"; - } - else if ((fileTypeInt == CRY_FILE_TYPE_CGA) || (fileTypeInt == (CRY_FILE_TYPE_CGA | CRY_FILE_TYPE_ANM))) - { - extension = "cga"; - } - else if (fileTypeInt == CRY_FILE_TYPE_ANM) - { - extension = "anm"; - } - else if (fileTypeInt == CRY_FILE_TYPE_CHR || - (fileTypeInt == (CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_CAF)) || - (fileTypeInt == (CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_INTERMEDIATE_CAF))) - { - extension = "chr"; - } - else if (fileTypeInt == CRY_FILE_TYPE_SKIN) - { - extension = "skin"; - } - - std::string safeGeometryFileName = geometryFileName; - std::replace(safeGeometryFileName.begin(), safeGeometryFileName.end(), ' ', '_'); - std::string finalFileName; - if (customExportPath.size() > 0) - { - if (PathHelpers::IsRelative(customExportPath)) - { - std::string const assetRelativePath = PathHelpers::Join(originalExportDirectory, customExportPath); - finalFileName = PathHelpers::Join(assetRelativePath, safeGeometryFileName + "." + extension); - } - else - { - context->Log(ILogger::eSeverity_Warning, "An absolute path was specified for export of node %s (%s) - This is unlikely to be correct", geometryFileName.c_str(), customExportPath.c_str()); - finalFileName = PathHelpers::Join(customExportPath, safeGeometryFileName + "." + extension); - } - } - else - { - // no relative path, just export it in the original directory. - finalFileName = PathHelpers::Join(originalExportDirectory, safeGeometryFileName + "." + extension); - } - if (finalFileName.size() > 0) - { - assetGeometryFileNameList.push_back(finalFileName); - if (!FileUtil::EnsureDirectoryExists(PathHelpers::GetDirectory(finalFileName).c_str())) - { - context->Log(ILogger::eSeverity_Error, "Unable to create directory for %s", finalFileName.c_str()); - return; - } - } - } - - if ((fileTypeInt & (CRY_FILE_TYPE_CAF | CRY_FILE_TYPE_INTERMEDIATE_CAF)) != 0) - { - for (int animationIndex = 0; animationIndex < source->GetAnimationCount(); ++animationIndex) - { - std::string const animationName = source->GetAnimationName(&geometryFileData, geometryFileIndex, animationIndex); - - // Animations beginning with an underscore should be ignored. - bool const ignoreAnimation = animationName.empty() || (animationName[0] == '_'); - - if (!ignoreAnimation) - { - std::string safeAnimationName = animationName; - std::replace(safeAnimationName.begin(), safeAnimationName.end(), ' ', '_'); - - std::string exportPath = PathHelpers::Join(originalExportDirectory, safeAnimationName + exportExtension); - animationFileNameList.push_back(std::make_pair(std::make_pair(animationIndex, geometryFileIndex), exportPath)); - if (fileTypeInt & CRY_FILE_TYPE_CAF) - { - animationCompileFileNameList.push_back(std::make_pair(std::make_pair(animationIndex, geometryFileIndex), exportPath)); - } - animationExportSources.push_back(SingleAnimationExportSourceAdapter(source, &geometryFileData, geometryFileIndex, animationIndex)); - exportList.push_back(std::make_pair(exportPath, &animationExportSources.back())); - } - } - } - } - } - - // Export the COLLADA file to the chosen file. - { - ProgressRange exportProgressRange(progressRange, 0.6f); - - size_t const daeCount = exportList.size(); - float const daeProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (ExportList::iterator itFile = exportList.begin(); itFile != exportList.end(); ++itFile) - { - const std::string& colladaFileName = (*itFile).first; - IExportSource* fileExportSource = (*itFile).second; - - ProgressRange animationExportProgressRange(exportProgressRange, daeProgressRangeSlice); - - try - { - context->Log(ILogger::eSeverity_Info, "Exporting to file '%s'", colladaFileName.c_str()); - - // Try to create the directory for the file. - if (!FileUtil::EnsureDirectoryExists(PathHelpers::GetDirectory(colladaFileName).c_str())) - { - context->Log(ILogger::eSeverity_Error, "Unable to create directory for %s", colladaFileName.c_str()); - return; - } - - bool ok; - - if (bExportCompressed) - { - IPakSystem* pakSystem = (context ? context->GetPakSystem() : 0); - if (!pakSystem) - { - throw IExportContext::PakSystemError("No pak system provided."); - } - - std::string const archivePath = colladaFileName; - std::string archiveRelativePath = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()) + ".dae"; - archiveRelativePath = PathHelpers::GetFilename(archiveRelativePath); - - XMLPakFileSink sink(pakSystem, archivePath, archiveRelativePath); - ok = ColladaWriter::Write(fileExportSource, context, &sink, animationExportProgressRange); - } - else - { - XMLFileSink fileSink(colladaFileName); - ok = ColladaWriter::Write(fileExportSource, context, &fileSink, animationExportProgressRange); - } - - if (!ok) - { - // FIXME: erase the resulting file somehow - context->Log(ILogger::eSeverity_Error, "Failed to export '%s'", colladaFileName.c_str()); - return; - } - } - catch (IXMLSink::OpenFailedError e) - { - context->Log(ILogger::eSeverity_Error, "Unable to open output file: %s", e.what()); - return; - } - catch (...) - { - context->Log(ILogger::eSeverity_Error, "Unexpected crash in COLLADA exporter"); - return; - } - } - } - } - - // Get the RC path. If a custom one isn't specified then fall back to the registry method as per the default. - wchar_t resourceCompilerPath[512]; - { - const std::string resourceCompilerPathString = source->GetResourceCompilerPath(); - if (!resourceCompilerPathString.empty()) - { - SettingsManagerHelpers::ConvertUtf8ToUtf16(resourceCompilerPathString.c_str(), SettingsManagerHelpers::CWCharBuffer(resourceCompilerPath, sizeof(resourceCompilerPath))); - } - } - - // Run the resource compiler on the COLLADA file to generate uncompressed CAFs. - { - ProgressRange compilerProgressRange(progressRange, 0.075f); - - CurrentTaskScope currentTask(context, "rc"); - - size_t const daeCount = animationFileNameList.size(); - float const animationProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (AnimationFileNameList::iterator itFile = animationFileNameList.begin(); itFile != animationFileNameList.end(); ++itFile) - { - std::string colladaFileName = (*itFile).second; - int geometryFileIndex = itFile->first.second; - - std::string expectedCAFPath; - { - bool isIntermediateCAF = (geometryFileData.GetProperties(geometryFileIndex).filetypeInt & CRY_FILE_TYPE_INTERMEDIATE_CAF) != 0; - string nameWithoutExtension = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()); - expectedCAFPath = nameWithoutExtension + (isIntermediateCAF ? ".i_caf" : ".caf"); - } - - if (FileUtil::FileExists(expectedCAFPath.c_str())) - { - if (!DeleteFileA(expectedCAFPath.c_str())) - { - context->Log(ILogger::eSeverity_Error, "Failed to remove existing animation file: %s", expectedCAFPath.c_str()); - continue; - } - } - - string arguments = "/refresh"; - - ProgressRange animationCompileProgressRange(compilerProgressRange, animationProgressRangeSlice); - ResourceCompilerLogListener listener(context); - - context->Log(ILogger::eSeverity_Info, "Calling RC to generate uncompressed CAF file: %s", colladaFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler( // actual instance of compiler used - colladaFileName.c_str(), - arguments.c_str(), - &listener, - true, false, false, 0, resourceCompilerPath); - - if (result != CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - continue; - } - - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", colladaFileName.c_str()); - if (!FileUtil::FileExists(expectedCAFPath.c_str())) - { - context->Log(ILogger::eSeverity_Error, "Following Animation file is expected to be created by RC: %s", expectedCAFPath.c_str()); - context->Log(ILogger::eSeverity_Error, "Do you have an old RC version?"); - } - -#if !defined(_DEBUG) - // Delete the Collada file. - DeleteFileA(colladaFileName.c_str()); -#endif - } - } - - // Run the resource compiler on the COLLADA file to generate the geometry assets. - { - ProgressRange compilerProgressRange(progressRange, 0.075f); - - CurrentTaskScope currentTask(context, "rc"); - - size_t const daeCount = colladaGeometryFileNameList.size(); - float const assetProgressRangeSlice = 1.0f / (daeCount > 0 ? daeCount : 1); - for (size_t i = 0; i < daeCount; ++i) - { - const std::string& colladaFileName = colladaGeometryFileNameList[i]; - - ProgressRange assetCompileProgressRange(compilerProgressRange, assetProgressRangeSlice); - ResourceCompilerLogListener listener(context); - context->Log(ILogger::eSeverity_Info, "Calling RC to generate raw asset file: %s", colladaFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler( - colladaFileName.c_str(), - "/refresh", - &listener, - true, false, false, 0, resourceCompilerPath); - -#if !defined(_DEBUG) - // Delete the Collada file. - DeleteFileA(colladaFileName.c_str()); -#endif - - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", colladaFileName.c_str()); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - - { - // Create an RC helper - do it outside the loop, since it queries the registry on construction. - ResourceCompilerLogListener listener(context); - - // Check the registry to see whether we should compress the animations or not. - int processAnimations = GetSetting(context->GetSettings(), "CompressCAFs", 1); - - if (!processAnimations) - { - context->Log(ILogger::eSeverity_Warning, "CompressCAFs registry key set to 0 - not compressing CAFs"); - } - else - { - // Run the resource compiler again on the generated CAF files to compress/process them. - context->Log(ILogger::eSeverity_Debug, "CompressCAFs not set or set to 1 - compressing CAFs"); - - CurrentTaskScope currentTask(context, "compress"); - ProgressRange compressRange(progressRange, 0.025f); - - size_t const cafCount = animationCompileFileNameList.size(); - float const animationProgressRangeSlice = 1.0f / (cafCount > 0 ? cafCount : 1); - for (AnimationFileNameList::iterator itFile = animationCompileFileNameList.begin(); itFile != animationCompileFileNameList.end(); ++itFile) - { - std::string colladaFileName = (*itFile).second; - ProgressRange animationProgressRange(compressRange, animationProgressRangeSlice); - - // Assume the RC generated the CAF file using the take name and adding .CAF. - std::string cafPath = colladaFileName.substr(0, colladaFileName.length() - exportExtension.length()) + ".caf"; - std::string cbaPath = StringHelpers::ConvertString(CBAHelpers::FindCBAFileForFile(cafPath.c_str(), context->GetPakSystem())); - - if (cbaPath.empty()) - { - context->Log(ILogger::eSeverity_Error, "Unable to find CBA file for file \"%s\" (looked for a root game directory that contains a relative path of \"Animations/Animations.cba\"", cafPath.c_str()); - } - else - { - char buffer[2048]; - sprintf(buffer, "/file=\"%s\" /refresh /SkipDba", cafPath.c_str()); - context->Log(ILogger::eSeverity_Info, "Calling RC to compress CAF file: (CBA file = %s) %s", cbaPath.c_str(), buffer); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(cbaPath.c_str(), buffer, &listener, true, resourceCompilerPathType, false, false, 0, resourceCompilerPath); - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s %s", cbaPath.c_str(), buffer); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - } - - // Check the registry to see whether we should optimize the geometry files or not. - int optimizeGeometry = GetSetting(context->GetSettings(), "OptimizeAssets", 1); - - // Run the resource compiler again on the generated geometry files to compress/process them. - // TODO: This should not be necessary, the RC should be modified so that assets are automatically - // compressed when exported from COLLADA. - if (!optimizeGeometry) - { - context->Log(ILogger::eSeverity_Warning, "OptimizeAssets registry key set to 0 - not compressing CAFs"); - } - else - { - context->Log(ILogger::eSeverity_Debug, "OptimizeAssets not set or set to 1 - optimizing geometry"); - - CurrentTaskScope currentTask(context, "compress"); - ProgressRange compressRange(progressRange, 0.025f); - - size_t const assetCount = assetGeometryFileNameList.size(); - float const assetProgressRangeSlice = 1.0f / (assetCount > 0 ? assetCount : 1); - for (size_t i = 0; i < assetCount; ++i) - { - const std::string& assetFileName = assetGeometryFileNameList[i]; - ProgressRange animationProgressRange(compressRange, assetProgressRangeSlice); - - // note: we skip some asset types because we know that they are "optimized" already - if (StringHelpers::EndsWithIgnoreCase(assetFileName, ".anm") || StringHelpers::EndsWithIgnoreCase(assetFileName, ".chr") || StringHelpers::EndsWithIgnoreCase(assetFileName, ".skin")) - { - context->Log(ILogger::eSeverity_Info, "Calling RC to optimize asset \"%s\"", assetFileName.c_str()); - CResourceCompilerHelper::ERcCallResult result = compiler.CallResourceCompiler(assetFileName.c_str(), "/refresh", &listener, true, resourceCompilerPathType, false, false, 0, resourceCompilerPath); - if (result == CResourceCompilerHelper::eRcCallResult_success) - { - context->Log(ILogger::eSeverity_Debug, "RC finished: %s", assetFileName.c_str()); - } - else - { - context->Log(ILogger::eSeverity_Error, "%s", compiler.GetCallResultDescription(result)); - return; - } - } - } - } - } - - // Log the end time. - { - char buf[1024]; - std::time_t t = std::time(0); - std::strftime(buf, sizeof(buf) / sizeof(buf[0]), "%H:%M:%S on %a, %d/%m/%Y", std::localtime(&t)); - context->Log(ILogger::eSeverity_Info, "Export finished at %s", buf); - } -} diff --git a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h b/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h deleted file mode 100644 index 8dc53ad62f..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaExportWriter.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H -#pragma once - - -#include "IExportWriter.h" - -class ColladaExportWriter - : public IExportWriter -{ -public: - // IExportWriter - virtual void Export(IExportSource* source, IExportContext* context); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAEXPORTWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp b/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp deleted file mode 100644 index 106ed02ba4..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaWriter.cpp +++ /dev/null @@ -1,2918 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ColladaWriter.h" -#include "IExportSource.h" -#include "ISettings.h" -#include "XMLWriter.h" -#include "SkeletonData.h" -#include "AnimationData.h" -#include "ProgressRange.h" -#include "ModelData.h" -#include "IExportContext.h" -#include "GeometryFileData.h" -#include "GeometryData.h" -#include "MaterialData.h" -#include "SkinningData.h" -#include "Cry_Math.h" -#include "LocaleChanger.h" -#include "MorphData.h" -#include "StringHelpers.h" -#include "GeometryMaterialData.h" -#include "ColladaShared.h" -#include -#include -#include -#include - -namespace -{ - bool FloatingPointHasPrecisionIssues() - { - Matrix44 m; - - m.m00 = 0.729367f; - m.m01 = -0.143863f; - m.m02 = -0.668825f; - m.m03 = 0.595435f; - - m.m10 = -0.573746f; - m.m11 = 0.403844f; - m.m12 = -0.712549f; - m.m13 = 1.14523f; - - m.m20 = 0.37261f; - m.m21 = 0.903445f; - m.m22 = 0.21201f; - m.m23 = 0.0669039f; - - m.m30 = 0; - m.m31 = 0; - m.m32 = 0; - m.m33 = 1; - - m.Invert(); - - return m.m33 <= 0.999f || m.m33 >= 1.001f; - - // For testing with www.wolframalpha.com: - // string a = StringHelpers::Format("inverse{{%g,%g,%g,%g},{%g,%g,%g,%g},{%g,%g,%g,%g},{%g,%g,%g,%g}}", - // m.m00, m.m01, m.m02, m.m03, - // m.m10, m.m11, m.m12, m.m13, - // m.m20, m.m21, m.m22, m.m23, - // m.m30, m.m31, m.m32, m.m33); - } -} - - -namespace -{ - void DecomposeTransform(Vec3& translation, CryQuat& rotation, Vec3& scale, const Matrix34& transform) - { - translation = transform.GetTranslation(); - Matrix33 orientation(transform); - scale.x = Vec3(orientation.m00, orientation.m10, orientation.m20).GetLength(); - scale.y = Vec3(orientation.m01, orientation.m11, orientation.m21).GetLength(); - scale.z = Vec3(orientation.m02, orientation.m12, orientation.m22).GetLength(); - orientation.OrthonormalizeFast(); - rotation = !CryQuat(orientation); - } - - struct BoneEntry - { - std::string name; - std::string physName; - std::string parentFrameName; - }; - - typedef std::map, SkeletonData> SkeletonDataMap; - typedef std::map, MorphData> MorphDataMap; - typedef std::map, std::vector > BoneDataMap; - - struct GeometryEntry - { - GeometryEntry(const std::string& name, int geometryFileIndex, int modelIndex) - : name(name) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) {} - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - struct BoneGeometryEntry - { - BoneGeometryEntry(const std::string& name, int geometryFileIndex, int modelIndex, int boneIndex) - : name(name) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) - , boneIndex(boneIndex) {} - std::string name; - int geometryFileIndex; - int modelIndex; - int boneIndex; - }; - - struct MorphGeometryEntry - { - MorphGeometryEntry(const std::string& name, const std::string& morphName, int geometryFileIndex, int modelIndex, int morphIndex) - : name(name) - , morphName(morphName) - , geometryFileIndex(geometryFileIndex) - , modelIndex(modelIndex) - , morphIndex(morphIndex) {} - std::string name; - std::string morphName; - int geometryFileIndex; - int modelIndex; - int morphIndex; - }; - - struct EffectsEntry - { - EffectsEntry(const std::string& name) - : name(name) {} - - std::string name; - }; - - struct MaterialEntry - { - MaterialEntry(const std::string& name) - : name(name) {} - - std::string name; - }; - - struct SkinControllerEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - struct MorphControllerEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - }; - - typedef std::map, MorphControllerEntry> MorphControllerMap; - - void BindMaterials(XMLWriter& writer, IExportContext* context, MaterialData& materialData, const ModelData& modelData, int modelIndex, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source) - { - // Instance any materials that the node uses. - GeometryMaterialData geometryMaterialData; - source->ReadGeometryMaterialData(context, &geometryMaterialData, &modelData, &materialData, modelIndex); - - std::set usedMaterialIndices; - for (int materialIndex = 0, materialCount = geometryMaterialData.GetUsedMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - usedMaterialIndices.insert(geometryMaterialData.GetUsedMaterialIndex(materialIndex)); - } - if (!usedMaterialIndices.empty()) - { - XMLWriter::Element bindMaterialElement(writer, "bind_material"); - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - for (std::set::const_iterator usedMtlPos = usedMaterialIndices.begin(), usedMtlEnd = usedMaterialIndices.end(); usedMtlPos != usedMtlEnd; ++usedMtlPos) - { - std::map::const_iterator entryMapPos = materialMaterialMap.find(*usedMtlPos); - int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - std::string name = (entryIndex >= 0 ? materials[entryIndex].name : "UNKNOWN_INSTANCED_MATERIAL"); - - XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - instanceMaterialElement.Attribute("symbol", name); - instanceMaterialElement.Attribute("target", "#" + name); - } - } - } - - void BindBoneMaterials(XMLWriter& writer, IExportContext* context, MaterialData& materialData, SkeletonData& skeletonData, int boneIndex, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source) - { - // Instance any materials that the node uses. - GeometryMaterialData geometryMaterialData; - source->ReadBoneGeometryMaterialData(context, &geometryMaterialData, &skeletonData, boneIndex, &materialData); - - std::set usedMaterialIndices; - for (int materialIndex = 0, materialCount = geometryMaterialData.GetUsedMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - usedMaterialIndices.insert(geometryMaterialData.GetUsedMaterialIndex(materialIndex)); - } - if (!usedMaterialIndices.empty()) - { - XMLWriter::Element bindMaterialElement(writer, "bind_material"); - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - for (std::set::const_iterator usedMtlPos = usedMaterialIndices.begin(), usedMtlEnd = usedMaterialIndices.end(); usedMtlPos != usedMtlEnd; ++usedMtlPos) - { - std::map::const_iterator entryMapPos = materialMaterialMap.find(*usedMtlPos); - int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - std::string name = (entryIndex >= 0 ? materials[entryIndex].name : "UNKNOWN_INSTANCED_MATERIAL"); - - XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - instanceMaterialElement.Attribute("symbol", name); - instanceMaterialElement.Attribute("target", "#" + name); - } - } - - //// Instance any materials that the node uses. - //std::vector materialIDs; - //for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - //{ - // int parentIndex = materialData.GetParentIndex(materialIndex); - // if (parentIndex >= 0 && parentIndex == skeletonData.GetMaterial(boneIndex)) - // materialIDs.push_back(materialIndex); - //} - - //if (!materialIDs.empty()) - //{ - // XMLWriter::Element bindMaterialElement(writer, "bind_material"); - // XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - // for (int i = 0, count = int(materialIDs.size()); i < count; ++i) - // { - // std::map::const_iterator entryMapPos = materialMaterialMap.find(materialIDs[i]); - // int entryIndex = (entryMapPos != materialMaterialMap.end() ? (*entryMapPos).second : -1); - // std::string name = (entryIndex >= 0 ? materials[entryIndex].name : 0); - - // XMLWriter::Element instanceMaterialElement(writer, "instance_material"); - // instanceMaterialElement.Attribute("symbol", name); - // instanceMaterialElement.Attribute("target", "#" + name); - // } - //} - } - - void WriteExtraData(XMLWriter& writer, const SHelperData& helperData, const std::string& properties) - { - // Write helper data (if it's helper node) and properties - if ((!properties.empty()) || (helperData.m_eHelperType != SHelperData::eHelperType_UNKNOWN)) - { - XMLWriter::Element elem(writer, "extra"); - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "CryEngine"); - { - if (!properties.empty()) - { - // TODO: Sokov: check for invalid characters in properties string, like '<', '>', <' ', >127 etc. - XMLWriter::Element elem(writer, "properties"); - elem.Content(properties); - } - - if (helperData.m_eHelperType != SHelperData::eHelperType_UNKNOWN) - { - XMLWriter::Element elem(writer, "helper"); - switch (helperData.m_eHelperType) - { - case SHelperData::eHelperType_Point: - elem.Attribute("type", "point"); - break; - case SHelperData::eHelperType_Dummy: - elem.Attribute("type", "dummy"); - { - XMLWriter::Element elem(writer, "bound_box_min"); - elem.ContentArrayElement(helperData.m_boundBoxMin[0]); - elem.ContentArrayElement(helperData.m_boundBoxMin[1]); - elem.ContentArrayElement(helperData.m_boundBoxMin[2]); - } - { - XMLWriter::Element elem(writer, "bound_box_max"); - elem.ContentArrayElement(helperData.m_boundBoxMax[0]); - elem.ContentArrayElement(helperData.m_boundBoxMax[1]); - elem.ContentArrayElement(helperData.m_boundBoxMax[2]); - } - break; - default: - assert(false); - elem.Attribute("type", "UNKNOWN"); - break; - } - } - } - } - } - - // ****** I dont think we need this anymore. These files are not readable by XSI as far as I know. ****** - // ****** Removed 03-Jan-2012 - // Write special properties for importing to the XSI. - /*{ - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile","XSI"); - { - XMLWriter::Element elem(writer, "XSI_CustomPSet"); - elem.Attribute("name","ObjectProperties"); - { - XMLWriter::Element elem(writer, "propagation"); - elem.Content("NODE"); - } - { - XMLWriter::Element elem(writer, "type"); - elem.Content("CryNodeProperties"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id","Props"); - elem.Attribute("type","Text"); - elem.Attribute("value",properties.c_str()); - } - } - }*/ - } - - void WriteSkeletonRecurse(XMLWriter& writer, IExportContext* context, const std::string& modelName, SkeletonData& skeletonData, int boneIndex, const std::string& name, const std::vector& bones, std::map, int>, int>& boneGeometryMap, std::vector& boneGeometries, int geometryFileIndex, int modelIndex, MaterialData& materialData, const std::map& materialMaterialMap, const std::vector& materials, IExportSource* source, ProgressRange& progressRange) - { - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", name); // The ID must be unique. - nodeElement.Attribute("name", name); // The name must not include model name as prefix, so it can match the skeleton. - - // Calculate the transforms for the bone and its parent. This could be made a lot simpler by using proper - // transforms in the skeleton data. - Matrix34 transform; - { - Matrix44 transforms[2]; - int boneIndices[2] = {boneIndex, skeletonData.GetBoneParentIndex(boneIndex)}; - for (int i = 0; i < 2; ++i) - { - transforms[i] = IDENTITY; - - if (boneIndices[i] >= 0) - { - Vec3 scaleParams; - skeletonData.GetScale((float*)&scaleParams, boneIndices[i]); - Matrix44 scale = Matrix33::CreateScale(scaleParams); - - Ang3 rotationParams; - skeletonData.GetRotation((float*)&rotationParams, boneIndices[i]); - Matrix44 rotation = Matrix33::CreateRotationXYZ(rotationParams); - - Vec3 translationParams; - skeletonData.GetTranslation((float*)&translationParams, boneIndices[i]); - Matrix44 translation(IDENTITY); - translation.SetTranslation(translationParams); - - transforms[i] = translation * (rotation * scale); - } - } - transform = Matrix34(transforms[1].GetInverted() * transforms[0]); - } - - Vec3 translation, scaling; - CryQuat orientation; - DecomposeTransform(translation, orientation, scaling, transform); - Ang3 rotation = Ang3::GetAnglesXYZ(orientation); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - // If the node has geometry, write out the reference to it. - std::map, int>, int>::iterator boneGeometryMapPos = boneGeometryMap.find(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), boneIndex)); - if (boneGeometryMapPos != boneGeometryMap.end()) - { - const std::string& boneGeometryName = boneGeometries[(*boneGeometryMapPos).second].name; - XMLWriter::Element instanceGeometryElement(writer, "instance_geometry"); - instanceGeometryElement.Attribute("url", std::string("#") + boneGeometryName); - - BindBoneMaterials(writer, context, materialData, skeletonData, boneIndex, materialMaterialMap, materials, source); - } - - SHelperData dummyHelperData; - WriteExtraData(writer, dummyHelperData, skeletonData.GetBoneProperties(boneIndex)); - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = skeletonData.GetChildIndex(boneIndex, childIndexIndex); - WriteSkeletonRecurse(writer, context, modelName, skeletonData, childIndex, bones[childIndex].name, bones, boneGeometryMap, boneGeometries, geometryFileIndex, modelIndex, materialData, materialMaterialMap, materials, source, ProgressRange(progressRange, progressRangeSlice)); - } - } - - void WritePhysSkeletonRecurse(XMLWriter& writer, const std::string& modelName, const SkeletonData& skeletonData, int boneIndex, const std::vector& bones, ProgressRange& progressRange, const Matrix34& physFrameTM, const Matrix34& parentTM) - { - Matrix34 currentPhysFrameTM = physFrameTM; - - // Output a node for the parent frame. - bool shouldWriteParentFrame = skeletonData.HasParentFrame(boneIndex); - XMLWriter::Element parentFrameElement(writer, "node", shouldWriteParentFrame); - if (shouldWriteParentFrame) - { - parentFrameElement.Attribute("id", bones[boneIndex].parentFrameName); // The ID must be unique. - parentFrameElement.Attribute("name", bones[boneIndex].parentFrameName); // The name must not include model name as prefix, so it can match the skeleton. - - // Write translation element. - float translation[3]; - skeletonData.GetParentFrameTranslation(boneIndex, translation); - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - float rotation[3]; - skeletonData.GetParentFrameRotation(boneIndex, rotation); - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - float scaling[3]; - skeletonData.GetParentFrameScale(boneIndex, scaling); - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - Matrix34 tm(IDENTITY); - Matrix34 translationTM(IDENTITY); - translationTM.SetTranslation(Vec3(translation[0], translation[1], translation[2])); - Matrix34 rotationTM = Matrix33::CreateRotationXYZ(Ang3(rotation[0], rotation[1], rotation[2])); - Matrix34 scaleTM = Matrix33::CreateScale(Vec3(scaling[0], scaling[1], scaling[2])); - Matrix34 transform = translationTM * (rotationTM * scaleTM); - - currentPhysFrameTM = transform * currentPhysFrameTM; - } - - Matrix34 worldTM; - { - float translation[3]; - skeletonData.GetTranslation(translation, boneIndex); - float rotation[3]; - skeletonData.GetRotation(rotation, boneIndex); - float scaling[3]; - skeletonData.GetScale(scaling, boneIndex); - Matrix34 tm(IDENTITY); - Matrix34 translationTM(IDENTITY); - translationTM.SetTranslation(Vec3(translation[0], translation[1], translation[2])); - Matrix34 rotationTM = Matrix33::CreateRotationXYZ(Ang3(rotation[0], rotation[1], rotation[2])); - Matrix34 scaleTM = Matrix33::CreateScale(Vec3(scaling[0], scaling[1], scaling[2])); - worldTM = translationTM * (rotationTM * scaleTM); - } - Matrix34 transform = parentTM.GetInverted() * worldTM; - - XMLWriter::Element nodeElement(writer, "node", skeletonData.GetPhysicalized(boneIndex)); - if (skeletonData.GetPhysicalized(boneIndex)) - { - Matrix34 physTM = currentPhysFrameTM.GetInverted() * worldTM; - Vec3 translation, scaling; - CryQuat orientation; - DecomposeTransform(translation, orientation, scaling, physTM); - Ang3 rotation = Ang3::GetAnglesXYZ(orientation); - - nodeElement.Attribute("id", bones[boneIndex].physName); // The ID must be unique. - nodeElement.Attribute("name", bones[boneIndex].physName); // The name must not include model name as prefix, so it can match the skeleton. - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - - currentPhysFrameTM = worldTM; - } - - SHelperData dummyHelperData; - WriteExtraData(writer, dummyHelperData, skeletonData.GetBoneGeomProperties(boneIndex)); - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = skeletonData.GetChildIndex(boneIndex, childIndexIndex); - WritePhysSkeletonRecurse(writer, modelName, skeletonData, childIndex, bones, ProgressRange(progressRange, progressRangeSlice), currentPhysFrameTM, worldTM); - } - } - - void WriteGeometryData(XMLWriter& writer, const std::string& id, const std::string& name, GeometryData& geometryData, MaterialData& materialData, std::map& materialMaterialMap, std::vector& materials) - { - XMLWriter::Element geometryElement(writer, "geometry"); - geometryElement.Attribute("id", id); - if (!name.empty()) - { - geometryElement.Attribute("name", name); - } - XMLWriter::Element meshElement(writer, "mesh"); - - // Write out the positions. - std::string posSourceName = id + "-pos"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", posSourceName); - - std::string arrayName = posSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.positions.size()) * 3); - for (int positionIndex = 0, positionCount = int(geometryData.positions.size()); positionIndex < positionCount; ++positionIndex) - { - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].x); - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].y); - arrayElement.ContentArrayElement(geometryData.positions[positionIndex].z); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.positions.size())); - accessorElement.Attribute("stride", 3); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "X"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Y"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Z"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the normals. - std::string normalSourceName = id + "-normal"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", normalSourceName); - - std::string arrayName = normalSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.normals.size()) * 3); - for (int normalIndex = 0, normalCount = int(geometryData.normals.size()); normalIndex < normalCount; ++normalIndex) - { - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].x); - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].y); - arrayElement.ContentArrayElement(geometryData.normals[normalIndex].z); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.normals.size())); - accessorElement.Attribute("stride", 3); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "X"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Y"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "Z"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the texture coordinates. - std::string textureCoordinateSourceName = id + "-uvs"; - if (!geometryData.textureCoordinates.empty()) - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", textureCoordinateSourceName); - - std::string arrayName = textureCoordinateSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.textureCoordinates.size()) * 2); - for (int textureCoordinateIndex = 0, textureCoordinateCount = int(geometryData.textureCoordinates.size()); textureCoordinateIndex < textureCoordinateCount; ++textureCoordinateIndex) - { - arrayElement.ContentArrayElement(geometryData.textureCoordinates[textureCoordinateIndex].u); - arrayElement.ContentArrayElement(geometryData.textureCoordinates[textureCoordinateIndex].v); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.textureCoordinates.size())); - accessorElement.Attribute("stride", 2); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "S"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "T"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the vertex colors. - std::string vertexColorSourceName = id + "-vcol"; - if (!geometryData.vertexColors.empty()) - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", vertexColorSourceName); - - std::string arrayName = vertexColorSourceName + "-array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", int(geometryData.vertexColors.size()) * 4); - for (int vertexColorIndex = 0, vertexColorCount = int(geometryData.vertexColors.size()); vertexColorIndex < vertexColorCount; ++vertexColorIndex) - { - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].r); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].g); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].b); - arrayElement.ContentArrayElement(geometryData.vertexColors[vertexColorIndex].a); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", std::string("#") + arrayName); - accessorElement.Attribute("count", int(geometryData.vertexColors.size())); - accessorElement.Attribute("stride", 4); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "R"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "G"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "B"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "A"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the vertex elements. - std::string vertexName = id + "-vtx"; - { - XMLWriter::Element vertexElement(writer, "vertices"); - vertexElement.Attribute("id", vertexName); - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "POSITION"); - inputElement.Attribute("source", std::string("#") + posSourceName); - } - - // Sort the triangles by material. - std::vector > polygonsByMaterial(materialData.GetMaterialCount() + 1); - for (int polygonIndex = 0, polygonCount = int(geometryData.polygons.size()); polygonIndex < polygonCount; ++polygonIndex) - { - polygonsByMaterial[geometryData.polygons[polygonIndex].mtlID + 1].push_back(geometryData.polygons[polygonIndex]); - } - - // Write out the triangles. - for (int materialIndex = -1, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - if (!polygonsByMaterial[materialIndex + 1].empty()) - { - std::map::iterator materialMapPos = materialMaterialMap.find(materialIndex); - int materialEntryIndex = (materialMapPos != materialMaterialMap.end() ? (*materialMapPos).second : -1); - - std::vector& polygons = polygonsByMaterial[materialIndex + 1]; - - XMLWriter::Element trianglesElement(writer, "triangles"); - trianglesElement.Attribute("count", int(polygons.size())); - if (materialEntryIndex >= 0) - { - trianglesElement.Attribute("material", materials[materialEntryIndex].name); - } - int offset = 0; - bool hasPositions = false; - if (!geometryData.positions.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "VERTEX"); - inputElement.Attribute("source", std::string("#") + vertexName); - inputElement.Attribute("offset", offset++); - hasPositions = true; - } - bool hasNormals = false; - if (!geometryData.normals.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "NORMAL"); - inputElement.Attribute("source", std::string("#") + normalSourceName); - inputElement.Attribute("offset", offset++); - hasNormals = true; - } - bool hasUVs = false; - if (!geometryData.textureCoordinates.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "TEXCOORD"); - inputElement.Attribute("source", std::string("#") + textureCoordinateSourceName); - inputElement.Attribute("offset", offset++); - hasUVs = true; - } - bool hasColors = false; - if (!geometryData.vertexColors.empty()) - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "COLOR"); - inputElement.Attribute("source", std::string("#") + vertexColorSourceName); - inputElement.Attribute("offset", offset++); - hasColors = true; - } - - XMLWriter::Element pElement(writer, "p"); - for (int polygonIndex = 0, polygonCount = int(polygons.size()); polygonIndex < polygonCount; ++polygonIndex) - { - for (int vertexIndex = 0; vertexIndex < 3; ++vertexIndex) - { - if (hasPositions && polygons[polygonIndex].v[vertexIndex].positionIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].positionIndex); - } - if (hasNormals && polygons[polygonIndex].v[vertexIndex].normalIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].normalIndex); - } - if (hasUVs && polygons[polygonIndex].v[vertexIndex].textureCoordinateIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].textureCoordinateIndex); - } - if (hasColors && polygons[polygonIndex].v[vertexIndex].vertexColorIndex >= 0) - { - pElement.ContentArrayElement(polygons[polygonIndex].v[vertexIndex].vertexColorIndex); - } - } - } - } - } - } - - bool WriteGeometries(IExportContext* context, XMLWriter& writer, std::vector& geometries, GeometryFileData& geometryFileData, const std::vector& modelData, MorphDataMap& morphData, MaterialData& materialData, std::vector& materials, std::map& materialMaterialMap, SkeletonDataMap& skeletonData, std::vector& boneGeometries, std::map, int>, int>& boneGeometryMap, std::map, int>, int>& morphGeometryMap, std::vector& morphGeometries, IExportSource* source, ProgressRange& progressRange) - { - XMLWriter::Element libraryGeometriesElement(writer, "library_geometries"); - - // Loop through all the geometries. - for (int geometryIndex = 0, geometryCount = int(geometries.size()); geometryIndex < geometryCount; ++geometryIndex) - { - GeometryEntry& geometryEntry = geometries[geometryIndex]; - - // Read in the geometry data. - GeometryData geometryData; - bool ok = source->ReadGeometry(context, &geometryData, &modelData[geometryEntry.geometryFileIndex], &materialData, geometryEntry.modelIndex); - if (!ok) - { - return false; - } - - WriteGeometryData(writer, geometryEntry.name, "", geometryData, materialData, materialMaterialMap, materials); - } - - // Loop through all the bone geometries. - for (int boneGeometryIndex = 0, boneGeometryCount = int(boneGeometries.size()); boneGeometryIndex < boneGeometryCount; ++boneGeometryIndex) - { - BoneGeometryEntry& boneGeometryEntry = boneGeometries[boneGeometryIndex]; - - GeometryData geometryData; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(boneGeometryEntry.geometryFileIndex, boneGeometryEntry.modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - source->ReadBoneGeometry(context, &geometryData, &(*skeletonDataPos).second, boneGeometryEntry.boneIndex, &materialData); - } - - WriteGeometryData(writer, boneGeometryEntry.name, "", geometryData, materialData, materialMaterialMap, materials); - } - - // Loop through all the morph geometries. - for (int morphGeometryIndex = 0, morphGeometryCount = int(morphGeometries.size()); morphGeometryIndex < morphGeometryCount; ++morphGeometryIndex) - { - MorphGeometryEntry& morphGeometryEntry = morphGeometries[morphGeometryIndex]; - - GeometryData geometryData; - MorphDataMap::iterator morphDataPos = morphData.find(std::make_pair(morphGeometryEntry.geometryFileIndex, morphGeometryEntry.modelIndex)); - if (morphDataPos != morphData.end()) - { - source->ReadMorphGeometry(context, &geometryData, &modelData[morphGeometryEntry.geometryFileIndex], morphGeometryEntry.modelIndex, &(*morphDataPos).second, morphGeometryEntry.morphIndex, &materialData); - } - - WriteGeometryData(writer, morphGeometryEntry.name, morphGeometryEntry.morphName, geometryData, materialData, materialMaterialMap, materials); - } - - return true; - } - - void WriteExportNodeProperties(const IExportSource& source, XMLWriter& writer, const char* geomFilename, const IGeometryFileData::SProperties& properties) - { - XMLWriter::Element elem(writer, "extra"); - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "CryEngine"); - { - std::string const filetypeStr = ExportFileTypeHelpers::CryFileTypeToString(properties.filetypeInt); - std::string props = std::string("fileType=") + filetypeStr; - if (properties.bDoNotMerge) - { - props += std::string("\r\n") + "DoNotMerge"; - } - if (properties.bUseCustomNormals) - { - props += std::string("\r\n") + "UseCustomNormals"; - } - if (properties.filetypeInt == CRY_FILE_TYPE_SKIN && properties.b8WeightsPerVertex) - { - props += std::string("\r\n") + "EightWeightsPerVertex"; - } - if (properties.bUseF32VertexFormat) - { - props += std::string("\r\n") + "UseF32VertexFormat"; - } - - props += std::string("\r\n") + std::string("CustomExportPath=") + properties.customExportPath; - XMLWriter::Element elem(writer, "properties"); - elem.Content(props); - } - } - - // Write special properties for importing to the XSI. - { - XMLWriter::Element elem(writer, "technique"); - elem.Attribute("profile", "XSI"); - { - XMLWriter::Element elem(writer, "XSI_CustomPSet"); - elem.Attribute("name", "ExportProperties"); - { - XMLWriter::Element elem(writer, "propagation"); - elem.Content("NODE"); - } - { - XMLWriter::Element elem(writer, "type"); - elem.Content("CryExportNodeProperties"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Filetype"); - elem.Attribute("type", "Integer"); - elem.Attribute("value", properties.filetypeInt); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Filename"); - elem.Attribute("type", "Text"); - elem.Attribute("value", geomFilename); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "Exportable"); - elem.Attribute("type", "Boolean"); - elem.Attribute("value", "1"); - } - { - XMLWriter::Element elem(writer, "XSI_Parameter"); - elem.Attribute("id", "MergeObjects"); - elem.Attribute("type", "Boolean"); - elem.Attribute("value", (!properties.bDoNotMerge)); - } - } - } - } - - - void WriteHierarchyRecurse( - XMLWriter& writer, - IExportContext* context, - int geometryFileIndex, - MaterialData& materialData, - const std::map& materialMaterialMap, - const std::vector& materials, - const ModelData& modelData, - int const modelIndex, - std::map, int>& modelGeometryMap, - std::vector& geometries, - std::map, int>& modelControllerMap, - std::vector& controllers, - std::map, int>& modelMorphControllerMap, - std::vector& morphControllers, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", modelData.GetModelName(modelIndex)); // The ID must be unique. - - { - float translation[3]; - float rotation[3]; - float scaling[3]; - modelData.GetTranslationRotationScale(modelIndex, translation, rotation, scaling); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.ContentArrayElement(translation[0]); - translateElement.ContentArrayElement(translation[1]); - translateElement.ContentArrayElement(translation[2]); - } - - // Write rotation elements. - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - XMLWriter::Element rotateElement(writer, "rotate"); - char sidBuffer[1024]; - sprintf(sidBuffer, "rotation_%c", 'z' - axisIndex); - rotateElement.Attribute("sid", sidBuffer); - rotateElement.ContentArrayElement(axisIndex == 2 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 1 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(axisIndex == 0 ? 1.0f : 0.0f); - rotateElement.ContentArrayElement(rotation[2 - axisIndex] * 180.0f / 3.14159f); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.ContentArrayElement(scaling[0]); - scaleElement.ContentArrayElement(scaling[1]); - scaleElement.ContentArrayElement(scaling[2]); - } - } - - // If the node has a controller, write out the reference to it. - std::map, int>::iterator modelControllerMapPos = modelControllerMap.find(std::make_pair(geometryFileIndex, modelIndex)); - std::map, int>::iterator modelMorphControllerMapPos = modelMorphControllerMap.find(std::make_pair(geometryFileIndex, modelIndex)); - if (modelControllerMapPos != modelControllerMap.end()) - { - const std::string& controllerName = controllers[(*modelControllerMapPos).second].name; - XMLWriter::Element instanceControllerElement(writer, "instance_controller"); - instanceControllerElement.Attribute("url", "#" + controllerName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - else if (modelMorphControllerMapPos != modelMorphControllerMap.end()) - { - const std::string& controllerName = morphControllers[(*modelMorphControllerMapPos).second].name; - XMLWriter::Element instanceControllerElement(writer, "instance_controller"); - instanceControllerElement.Attribute("url", "#" + controllerName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - else - { - // If the node has geometry, write out the reference to it. - std::map, int>::iterator modelGeometryMapPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - if (modelGeometryMapPos != modelGeometryMap.end()) - { - const std::string& geometryName = geometries[(*modelGeometryMapPos).second].name; - XMLWriter::Element instanceGeometryElement(writer, "instance_geometry"); - instanceGeometryElement.Attribute("url", std::string("#") + geometryName); - - BindMaterials(writer, context, materialData, modelData, modelIndex, materialMaterialMap, materials, source); - } - } - - // Recurse to the child nodes. - int childIndexCount = modelData.GetChildCount(modelIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - int childIndex = modelData.GetChildIndex(modelIndex, childIndexIndex); - WriteHierarchyRecurse(writer, context, geometryFileIndex, materialData, materialMaterialMap, materials, modelData, childIndex, modelGeometryMap, geometries, modelControllerMap, controllers, modelMorphControllerMap, morphControllers, source, ProgressRange(progressRange, progressRangeSlice)); - } - - // Write properties, HelperData - WriteExtraData(writer, modelData.GetHelperData(modelIndex), modelData.GetProperties(modelIndex)); - } - - void WriteHierarchy( - XMLWriter& writer, - IExportContext* context, - const GeometryFileData& geometryFileData, - MaterialData& materialData, - const std::map& materialMaterialMap, - const std::vector& materials, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - std::map, int>& modelGeometryMap, - std::vector& geometries, - std::map, int>& modelControllerMap, - std::vector& controllers, - BoneDataMap& boneDataMap, - std::map, int>, int>& boneGeometryMap, - std::vector& boneGeometries, - std::map, int>& modelMorphControllerMap, - std::vector& morphControllers, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element libraryVisualScenesElement(writer, "library_visual_scenes"); - XMLWriter::Element visualSceneElement(writer, "visual_scene"); - visualSceneElement.Attribute("id", "visual_scene_0"); - visualSceneElement.Attribute("name", "untitled"); - - int geometryFileCount = geometryFileData.GetGeometryFileCount(); - float geometryFileRangeSlice = 1.0f / (geometryFileCount > 0 ? float(geometryFileCount) : 1.0f); - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - ProgressRange geometryFileRange(progressRange, geometryFileRangeSlice); - - // Make sure to write out a LumberyardExportNode - this is expected by the RC. - std::string nodeName; - - nodeName = geometryFileData.GetGeometryFileName(geometryFileIndex); - XMLWriter::Element nodeElement(writer, "node"); - nodeElement.Attribute("id", nodeName); - nodeElement.Attribute(g_LumberyardExportNodeTag, true); - - // Write translation element. - { - XMLWriter::Element translateElement(writer, "translate"); - translateElement.Attribute("sid", "translation"); - translateElement.Content("0 0 0"); - } - - // Write rotation elements. - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_z"); - rotateElement.Content("0 0 1 0"); - } - - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_y"); - rotateElement.Content("0 1 0 0"); - } - - { - XMLWriter::Element rotateElement(writer, "rotate"); - rotateElement.Attribute("sid", "rotation_x"); - rotateElement.Content("1 0 0 0"); - } - - // Write scale elements - { - XMLWriter::Element scaleElement(writer, "scale"); - scaleElement.Attribute("sid", "scale"); - scaleElement.Content("1 1 1"); - } - - { - ProgressRange modelProgressRange(geometryFileRange, 0.5f); - int rootIndexCount = modelData[geometryFileIndex].GetRootCount(); - float progressRangeSlice = 1.0f / (rootIndexCount > 0 ? float(rootIndexCount) : 1.0f); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - int rootModelIndex = modelData[geometryFileIndex].GetRootIndex(rootIndexIndex); - WriteHierarchyRecurse(writer, context, geometryFileIndex, materialData, materialMaterialMap, materials, modelData[geometryFileIndex], rootModelIndex, modelGeometryMap, geometries, modelControllerMap, controllers, modelMorphControllerMap, morphControllers, source, ProgressRange(modelProgressRange, progressRangeSlice)); - } - } - - { - ProgressRange skeletonProgressRange(geometryFileRange, 0.5f); - //write the skeleton for the first model in the geometry file only - //for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - if (modelData[geometryFileIndex].GetModelCount() > 0) - { - int modelIndex = 0; - int modelCount = 1; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - const std::vector& bones = (*boneDataMap.find(std::make_pair(geometryFileIndex, modelIndex))).second; - int rootIndexCount = skeletonDataInstance.GetRootCount(); - float progressRangeSlice = 1.0f / ((rootIndexCount > 0 ? float(rootIndexCount) : 1.0f) * modelCount); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - int rootBoneIndex = skeletonDataInstance.GetRootIndex(rootIndexIndex); - WriteSkeletonRecurse(writer, context, geometryFileData.GetGeometryFileName(geometryFileIndex), skeletonDataInstance, rootBoneIndex, bones[rootBoneIndex].name, bones, boneGeometryMap, boneGeometries, geometryFileIndex, modelIndex, materialData, materialMaterialMap, materials, source, ProgressRange(skeletonProgressRange, progressRangeSlice * 0.5f)); - WritePhysSkeletonRecurse(writer, geometryFileData.GetGeometryFileName(geometryFileIndex), skeletonDataInstance, rootBoneIndex, bones, ProgressRange(skeletonProgressRange, progressRangeSlice * 0.5f), Matrix34(IDENTITY), Matrix34(IDENTITY)); - } - } - } - } - - // Write properties if they exist - WriteExportNodeProperties(*source, writer, geometryFileData.GetGeometryFileName(geometryFileIndex), geometryFileData.GetProperties(geometryFileIndex)); - } - } - - void WriteMetaData(IExportSource* pExportSource, XMLWriter& writer, ProgressRange& progressRange) - { - SExportMetaData metaData; - pExportSource->GetMetaData(metaData); - - XMLWriter::Element assetElement(writer, "asset"); - { - XMLWriter::Element contributorElement(writer, "contributor"); - contributorElement.Child("author", metaData.author); - contributorElement.Child("authoring_tool", metaData.authoring_tool); - contributorElement.Child("source_data", metaData.source_data); - } - - std::time_t time = std::time(0); - std::tm dateTime = *std::localtime(&time); - char scratchBuffer[1024]; - std::strftime(scratchBuffer, sizeof(scratchBuffer) / sizeof(scratchBuffer[0]), "%Y-%m-%dT%H:%M:%SZ", &dateTime); - assetElement.Child("created", scratchBuffer); - assetElement.Child("modified", scratchBuffer); - assetElement.Child("revision", metaData.revision); - { - XMLWriter::Element unitElement(writer, "unit"); - unitElement.Attribute("meter", metaData.fMeterUnit); - unitElement.Attribute("name", "meter"); - } - - switch (metaData.up_axis) - { - case SExportMetaData::X_UP: - assetElement.Child("up_axis", "X_UP"); - break; - case SExportMetaData::Y_UP: - assetElement.Child("up_axis", "Y_UP"); - break; - case SExportMetaData::Z_UP: - default: - assetElement.Child("up_axis", "Z_UP"); - break; - } - - int framesPerSecond = metaData.fFramesPerSecond <= 0.f ? 30 : static_cast(metaData.fFramesPerSecond); - sprintf_s(scratchBuffer, sizeof(scratchBuffer) / sizeof(scratchBuffer[0]), "%i", framesPerSecond); - XMLWriter::Element frameRateElement(writer, "framerate"); - frameRateElement.Attribute("fps", scratchBuffer); - } - - enum AnimationBoneParameter - { - AnimationBoneParameter_TransX, - AnimationBoneParameter_TransY, - AnimationBoneParameter_TransZ, - AnimationBoneParameter_RotX, - AnimationBoneParameter_RotY, - AnimationBoneParameter_RotZ, - AnimationBoneParameter_SclX, - AnimationBoneParameter_SclY, - AnimationBoneParameter_SclZ, - }; - const char* parameterStrings[] = { - "posx", - "posy", - "posz", - "rotx", - "roty", - "rotz", - "sclx", - "scly", - "sclz" - }; - const char* parameterTargetStrings[] = { - "translation.X", - "translation.Y", - "translation.Z", - "rotation_x.ANGLE", - "rotation_y.ANGLE", - "rotation_z.ANGLE", - "scale.X", - "scale.Y", - "scale.Z" - }; - struct AnimationBoneParameterEntry - { - std::string name; - int boneIndex; - AnimationBoneParameter parameter; - }; - struct AnimationEntry - { - std::string name; - int geometryFileIndex; - int modelIndex; - int animationIndex; - float start; - float stop; - std::vector parameters; - }; - void AddParametersRecursive(AnimationEntry& animation, AnimationData& animationData, const SkeletonData& skeletonData, int boneIndex, ProgressRange& progressRange) - { - for (AnimationBoneParameter parameter = AnimationBoneParameter_TransX; parameter <= AnimationBoneParameter_SclZ; parameter = AnimationBoneParameter(parameter + 1)) - { - animation.parameters.push_back(AnimationBoneParameterEntry()); - AnimationBoneParameterEntry& parameterEntry = animation.parameters.back(); - parameterEntry.boneIndex = boneIndex; - parameterEntry.parameter = parameter; - parameterEntry.name = animation.name + "-" + skeletonData.GetSafeName(boneIndex) + "_" + parameterStrings[parameter] + "-anim"; - - // Encode the flags as naming conventions. - unsigned modelFlags = animationData.GetModelFlags(boneIndex); - if (modelFlags & IAnimationData::ModelFlags_NoExport) - { - parameterEntry.name += "-NoExport"; - } - } - - int childIndexCount = skeletonData.GetChildCount(boneIndex); - float progressRangeSlice = 1.0f / (childIndexCount > 0 ? float(childIndexCount) : 1.0f); - for (int childIndexIndex = 0; childIndexIndex < childIndexCount; ++childIndexIndex) - { - AddParametersRecursive(animation, animationData, skeletonData, skeletonData.GetChildIndex(boneIndex, childIndexIndex), ProgressRange(progressRange, progressRangeSlice)); - } - } - - void AddParametersForNoSkeleton(AnimationEntry& animation, int modelIndex, const std::string& modelName, AnimationBoneParameter whichParameter) - { - for (AnimationBoneParameter parameter = whichParameter; parameter < whichParameter + 3; parameter = AnimationBoneParameter(parameter + 1)) - { - animation.parameters.push_back(AnimationBoneParameterEntry()); - AnimationBoneParameterEntry& parameterEntry = animation.parameters.back(); - parameterEntry.boneIndex = modelIndex; - parameterEntry.parameter = parameter; - parameterEntry.name = animation.name + "-" + modelName + "_" + parameterStrings[parameter] + "-anim"; - } - } - - void AddAnimationEntry(std::vector& animations, int animationIndex, int geometryFileIndex, int modelIndex, IExportSource* source, GeometryFileData& geometryFileData) - { - animations.push_back(AnimationEntry()); - AnimationEntry& animation = animations.back(); - animation.animationIndex = animationIndex; - animation.geometryFileIndex = geometryFileIndex; - animation.modelIndex = modelIndex; - - std::string safeAnimationName = source->GetAnimationName(&geometryFileData, geometryFileIndex, animationIndex); - std::replace(safeAnimationName.begin(), safeAnimationName.end(), ' ', '_'); - animation.name = safeAnimationName + std::string("-") + geometryFileData.GetGeometryFileName(geometryFileIndex); - source->GetAnimationTimeSpan(animation.start, animation.stop, animationIndex); - } - - void GenerateAnimationList(IExportContext* context, std::vector& animations, GeometryFileData& geometryFileData, const std::vector& modelData, SkeletonDataMap& skeletonData, IExportSource* source, ProgressRange& progressRange) - { - int geometryFileCount = geometryFileData.GetGeometryFileCount(); - float geometryFileProgressRangeSlice = 1.0f / (geometryFileCount > 0 ? float(geometryFileCount) : 1.0f); - for (int geometryFileIndex = 0; geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - ProgressRange geometryFileProgressRange(progressRange, geometryFileProgressRangeSlice); - - int modelCount = modelData[geometryFileIndex].GetModelCount(); - float modelProgressRangeSlice = 1.0f / (modelCount > 0 ? float(modelCount) : 1.0f); - - int animationCount = source->GetAnimationCount(); - float animProgressRangeSlice = 1.0f / (animationCount > 0 ? float(animationCount) : 1.0f); - for (int animationIndex = 0; animationIndex < animationCount; ++animationIndex) - { - ProgressRange animationProgressRange(geometryFileProgressRange, animProgressRangeSlice); - - if (skeletonData.empty()) // Non-skeletal mesh - { - AddAnimationEntry(animations, animationIndex, geometryFileIndex, -1, source, geometryFileData); - } - else // Skeletal mesh - { - AddAnimationEntry(animations, animationIndex, geometryFileIndex, 0, source, geometryFileData); - } - AnimationEntry& animation = animations.back(); - for (int modelIndex = 0; modelIndex < modelCount; ++modelIndex) - { - ProgressRange modelProgressRange(animationProgressRange, modelProgressRangeSlice); - - if (skeletonData.empty()) // Non-skeletal mesh - { - bool hasPos = source->HasValidPosController(&modelData[geometryFileIndex], modelIndex); - bool hasRot = source->HasValidRotController(&modelData[geometryFileIndex], modelIndex); - bool hasScl = source->HasValidSclController(&modelData[geometryFileIndex], modelIndex); - if (hasPos || hasRot || hasScl) - { - std::string modelName = modelData[geometryFileIndex].GetModelName(modelIndex); - std::replace_if(modelName.begin(), modelName.end(), std::isspace, '_'); - if (hasPos) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_TransX); - } - if (hasRot) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_RotX); - } - if (hasScl) - { - AddParametersForNoSkeleton(animation, modelIndex, modelName, - AnimationBoneParameter_SclX); - } - } - } - else // Skeletal mesh - { - ProgressRange animationProgressRange(modelProgressRange, animProgressRangeSlice); - - // Read the animation flags. - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - const SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - float FPS = ExportGlobal::g_defaultFrameRate; // This is only used for reading flags, using the default since it will have no impact - AnimationData animationData(skeletonDataInstance.GetBoneCount(), FPS, 0); - source->ReadAnimationFlags(context, &animationData, &geometryFileData, &modelData[geometryFileIndex], modelIndex, &skeletonDataInstance, animationIndex); - - int rootIndexCount = skeletonDataInstance.GetRootCount(); - float rootProgressRangeSlice = 1.0f / (rootIndexCount > 0 ? float(rootIndexCount) : 1.0f); - for (int rootIndexIndex = 0; rootIndexIndex < rootIndexCount; ++rootIndexIndex) - { - ProgressRange rootProgressRange(animationProgressRange, rootProgressRangeSlice); - - int rootBoneIndex = skeletonDataInstance.GetRootIndex(rootIndexIndex); - - // Generate the list of animated parameters for this animation - by generating the names in one place, we can - // use them in both passes to refer to each other. - AddParametersRecursive(animation, animationData, skeletonDataInstance, rootBoneIndex, rootProgressRange); - } - } - } - } - } - } - } - - void GenerateSkinControllerList(IExportContext* context, std::vector& controllers, std::map, int>& modelControllerMap, SkeletonDataMap& skeletonData, GeometryFileData& geometryFileData, const std::vector& modelData, std::map, int>& modelGeometryMap, std::vector& geometries, ProgressRange& progressRange) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - std::map, int>::iterator modelGeometryPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end() && modelGeometryPos != modelGeometryMap.end()) - { - const SkeletonData& skeleton = (*skeletonDataPos).second; - - int controllerIndex = int(controllers.size()); - controllers.resize(controllers.size() + 1); - - SkinControllerEntry& entry = controllers.back(); - char nameBuf[1024]; - sprintf(nameBuf, "controller_%d", controllerIndex); - entry.name = nameBuf; - entry.geometryFileIndex = geometryFileIndex; - entry.modelIndex = modelIndex; - - modelControllerMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), controllerIndex)); - } - } - } - } - - void GenerateMorphControllerList(IExportContext* context, std::vector& morphControllers, std::map, int>& modelMorphControllerMap, MorphDataMap& morphData, GeometryFileData& geometryFileData, const std::vector& modelData, std::map, int>& modelGeometryMap, std::vector& geometries, ProgressRange& progressRange) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - std::map, int>::iterator modelGeometryPos = modelGeometryMap.find(std::make_pair(geometryFileIndex, modelIndex)); - MorphDataMap::const_iterator morphDataPos = morphData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (morphDataPos != morphData.end() && modelGeometryPos != modelGeometryMap.end()) - { - int controllerIndex = int(morphControllers.size()); - morphControllers.resize(morphControllers.size() + 1); - - MorphControllerEntry& entry = morphControllers.back(); - char nameBuf[1024]; - sprintf(nameBuf, "morphController_%d", controllerIndex); - entry.name = nameBuf; - entry.geometryFileIndex = geometryFileIndex; - entry.modelIndex = modelIndex; - - modelMorphControllerMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), controllerIndex)); - } - } - } - } - - void GenerateEffectsList(IExportContext* context, std::map& materialFXMap, std::vector& effects, MaterialData& materialData) - { - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - std::string name; - - std::string mtlName = materialData.GetName(materialIndex); - assert(!mtlName.empty()); - - name = mtlName; - - char buffer[100]; - const int id = materialData.GetID(materialIndex); - assert(id >= 0); - sprintf(buffer, "-%d", id + 1); - - name += buffer; - - name += "-submat"; - - name += "-effect"; - - const int effectIndex = int(effects.size()); - effects.push_back(EffectsEntry(name)); - - materialFXMap.insert(std::make_pair(materialIndex, effectIndex)); - } - } - - void GenerateMaterialList(IExportContext* context, std::map& materialMaterialMap, std::map& materialFXMap, std::vector& effects, std::vector& materials, MaterialData& materialData) - { - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - // Material needs to be named according to a specific format - this communicates information to - // the resource compiler about the settings to be used for the material. - // Format is: ____[__...] - - std::string name; - - std::string mtlName = materialData.GetName(materialIndex); - assert(!mtlName.empty()); - - std::string mtlProperties = materialData.GetProperties(materialIndex); - assert(!mtlProperties.empty()); - - name = mtlName; - - char buffer[100]; - const int id = materialData.GetID(materialIndex); - assert(id >= 0); - sprintf(buffer, "__%d", id + 1); - - name += buffer; - - name += "__"; - name += materialData.GetSubMatName(materialIndex); - - name += mtlProperties; - - const int index = int(materials.size()); - materials.push_back(MaterialEntry(name)); - - materialMaterialMap.insert(std::make_pair(materialIndex, index)); - } - } - - void GenerateGeometryList(IExportContext* context, std::map, int>& modelGeometryMap, std::vector& geometries, GeometryFileData& geometryFileData, const std::vector& modelData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - if (modelData[geometryFileIndex].HasGeometry(modelIndex)) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_geometry"; - int geometryIndex = int(geometries.size()); - geometries.push_back(GeometryEntry(geometryName, geometryFileIndex, modelIndex)); - modelGeometryMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), geometryIndex)); - } - } - } - } - - void GenerateBoneGeometryList(IExportContext* context, std::map, int>, int>& boneGeometryMap, std::vector& boneGeometries, GeometryFileData& geometryFileData, const std::vector& modelData, SkeletonDataMap& skeletonData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData& modelSkeletonData = (*skeletonDataPos).second; - for (int boneIndex = 0, boneCount = modelSkeletonData.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - if (modelSkeletonData.HasGeometry(boneIndex)) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_" + modelSkeletonData.GetSafeName(boneIndex) + "_boneGeometry"; - int geometryIndex = int(boneGeometries.size()); - boneGeometries.push_back(BoneGeometryEntry(geometryName, geometryFileIndex, modelIndex, boneIndex)); - boneGeometryMap.insert(std::make_pair(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), boneIndex), geometryIndex)); - } - } - } - } - } - } - - void GenerateMorphGeometryList(IExportContext* context, std::map, int>, int>& morphGeometryMap, std::vector& morphGeometries, GeometryFileData& geometryFileData, const std::vector& modelData, MorphDataMap& morphData) - { - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - MorphDataMap::iterator morphDataPos = morphData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (morphDataPos != morphData.end()) - { - MorphData& modelMorphData = (*morphDataPos).second; - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - std::string geometryName = std::string(geometryFileData.GetGeometryFileName(geometryFileIndex)) + "_" + modelData[geometryFileIndex].GetModelName(modelIndex) + "_" + modelMorphData.GetMorphFullName(morphIndex) + "_morphGeometry"; - int geometryIndex = int(morphGeometries.size()); - morphGeometries.push_back(MorphGeometryEntry(geometryName, modelMorphData.GetMorphName(morphIndex), geometryFileIndex, modelIndex, morphIndex)); - morphGeometryMap.insert(std::make_pair(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), morphIndex), geometryIndex)); - } - } - } - } - } - - void GenerateIKPropertyList(const SkeletonData& skeletonData, int boneIndex, std::vector >& propertyList) - { - // Loop through each axis, adding the properties for this axis to the list. - for (int axis = 0; axis < 3; ++axis) - { - // Add the limit properties for this axis. - const char* extremeNames[] = {"min", "max"}; - for (int extreme = 0; extreme < 2; ++extreme) - { - std::string key; - key += ('x' + axis); - key += extremeNames[extreme]; - if (skeletonData.HasLimit(boneIndex, ISkeletonData::Axis(axis), ISkeletonData::Limit(extreme))) - { - float limit = skeletonData.GetLimit(boneIndex, ISkeletonData::Axis(axis), ISkeletonData::Limit(extreme)); - char buffer[1024]; - sprintf(buffer, "%f", limit * 180.0f / 3.14159f); // Convert to degrees. - propertyList.push_back(std::make_pair(key, buffer)); - } - } - - // Add the remaining properties. - const char* propNames[] = {"damping", "springangle", "springtension"}; - typedef bool (SkeletonData::* HasMember)(int boneIndex, ISkeletonData::Axis axis) const; - typedef float (SkeletonData::* GetMember)(int boneIndex, ISkeletonData::Axis axis) const; - HasMember hasMembers[] = {&SkeletonData::HasAxisDamping, &SkeletonData::HasSpringAngle, &SkeletonData::HasSpringTension}; - GetMember getMembers[] = {&SkeletonData::GetAxisDamping, &SkeletonData::GetSpringAngle, &SkeletonData::GetSpringTension}; - for (int propIndex = 0; propIndex < 3; ++propIndex) - { - std::string key; - key += ('x' + axis); - key += propNames[propIndex]; - if ((skeletonData.*(hasMembers[propIndex]))(boneIndex, ISkeletonData::Axis(axis))) - { - float value = (skeletonData.*(getMembers[propIndex]))(boneIndex, ISkeletonData::Axis(axis)); - char buffer[1024]; - sprintf(buffer, "%f", value); - propertyList.push_back(std::make_pair(key, buffer)); - } - } - } - } - - void GenerateBoneList(IExportContext* context, BoneDataMap& boneDataMap, const SkeletonDataMap& skeletonData, const std::vector& modelData) - { - for (SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.begin(), skeletonDataEnd = skeletonData.end(); skeletonDataPos != skeletonDataEnd; ++skeletonDataPos) - { - int geometryFileIndex = (*skeletonDataPos).first.first; - int modelIndex = (*skeletonDataPos).first.second; - const SkeletonData& skeleton = (*skeletonDataPos).second; - - BoneDataMap::iterator boneDataPos = boneDataMap.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), std::vector())).first; - std::vector& bones = (*boneDataPos).second; - bones.resize(skeleton.GetBoneCount()); - - std::string modelName = modelData[geometryFileIndex].GetModelName(modelIndex); - - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - typedef std::string BoneEntry::* BoneNamePtr; - BoneNamePtr boneNames[3] = {&BoneEntry::name, &BoneEntry::physName, &BoneEntry::parentFrameName}; - const char* suffixes[3] = {"", " Phys", " Phys ParentFrame"}; - std::vector > properties[3]; - - // Add the IK properties to the phys bone. - GenerateIKPropertyList(skeleton, boneIndex, properties[1]); - - for (int nameIndex = 0; nameIndex < 3; ++nameIndex) - { - std::string unsafeName = skeleton.GetName(boneIndex); - unsafeName += suffixes[nameIndex]; - bool containsSpaces = (unsafeName.find_first_of(" \t") != std::string::npos); - std::string name = unsafeName; - if (containsSpaces) - { - std::string overrideName = unsafeName; - std::replace_if(overrideName.begin(), overrideName.end(), std::isspace, '*'); - - std::string safeName = unsafeName; - std::replace_if(safeName.begin(), safeName.end(), std::isspace, '_'); - - name = safeName + "%" + modelName + "%" + "--PRprops_name=" + overrideName; - - // Add all the properties. - for (size_t propIndex = 0, propCount = properties[nameIndex].size(); propIndex < propCount; ++propIndex) - { - name += "_" + properties[nameIndex][propIndex].first + "=" + properties[nameIndex][propIndex].second; - } - - name += "__"; - } - else - { - name = unsafeName + "%" + modelName + "%"; - } - (bones[boneIndex].*(boneNames[nameIndex])) = name; - } - } - } - } - - void WriteAnimationList(XMLWriter& writer, std::vector& animations, ProgressRange& progressRange) - { - // Write out all the animations in the library_animation_clips element. Each animation lists the name and timespan - // of the clip, and the controllers for each model parameter. The actual animation data is written out in a separate pass. - XMLWriter::Element libraryAnimationClipsElement(writer, "library_animation_clips"); - - for (int animationEntryIndex = 0, animationEntryCount = int(animations.size()); animationEntryIndex < animationEntryCount; ++animationEntryIndex) - { - AnimationEntry& entry = animations[animationEntryIndex]; - - XMLWriter::Element animationClipElement(writer, "animation_clip"); - animationClipElement.Attribute("start", entry.start); - animationClipElement.Attribute("end", entry.stop); - animationClipElement.Attribute("id", entry.name); - - // For each parameter write out a reference to the controller for that parameter. - for (int parameterEntryIndex = 0, parameterEntryCount = int(entry.parameters.size()); parameterEntryIndex < parameterEntryCount; ++parameterEntryIndex) - { - AnimationBoneParameterEntry& parameter = entry.parameters[parameterEntryIndex]; - - XMLWriter::Element instanceAnimationElement(writer, "instance_animation"); - instanceAnimationElement.Attribute("url", std::string("#") + parameter.name); - } - } - } - - void WriteAnimationTags( - ProgressRange& animationEntryProgressRange, - const AnimationEntry& entry, - const IAnimationData* animationData, - XMLWriter& writer, - const std::vector* pBones, - const IModelData* pModelData) - { - // Loop through all the parameters of all the models. - ProgressRange writeAnimProgressRange(animationEntryProgressRange, 0.5f); - for (int parameterEntryIndex = 0, parameterEntryCount = int(entry.parameters.size()); parameterEntryIndex < parameterEntryCount; ++parameterEntryIndex) - { - const AnimationBoneParameterEntry& parameter = entry.parameters[parameterEntryIndex]; - - int frameCount = 0; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - frameCount = animationData->GetFrameCountPos(parameter.boneIndex); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - frameCount = animationData->GetFrameCountRot(parameter.boneIndex); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - frameCount = animationData->GetFrameCountScl(parameter.boneIndex); - break; - } - - XMLWriter::Element animationElement(writer, "animation"); - animationElement.Attribute("id", parameter.name); - - std::string inputID = parameter.name + "-input"; - std::string outputID = parameter.name + "-output"; - std::string interpID = parameter.name + "-interp"; - std::string tcbID = parameter.name + "-tcb"; - std::string easeinoutID = parameter.name + "-easeinout"; - - // Write out the times. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", inputID); - std::string arrayID = inputID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - - float floatBuffer[24]; - int bufferCount = 0; - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimePos(parameter.boneIndex, frameIndex); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimeRot(parameter.boneIndex, frameIndex); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - floatBuffer[bufferCount++] = animationData->GetFrameTimeScl(parameter.boneIndex, frameIndex); - break; - } - if (bufferCount == 24) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - if (bufferCount > 0) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "TIME"); - paramElement.Attribute("type", "float"); - } - - // Write out the values. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", outputID); - std::string arrayID = outputID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - - float floatBuffer[24]; - int bufferCount = 0; - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - const float* translation, * rotation, * scale; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameDataPos(parameter.boneIndex, frameIndex, translation); - floatBuffer[bufferCount++] = translation[parameter.parameter - AnimationBoneParameter_TransX]; - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameDataRot(parameter.boneIndex, frameIndex, rotation); - floatBuffer[bufferCount++] = rotation[parameter.parameter - AnimationBoneParameter_RotX]; - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameDataScl(parameter.boneIndex, frameIndex, scale); - floatBuffer[bufferCount++] = scale[parameter.parameter - AnimationBoneParameter_SclX]; - break; - } - if (bufferCount == 24) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - if (bufferCount > 0) - { - array.ContentArrayFloat24(floatBuffer, bufferCount); - bufferCount = 0; - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "VALUE"); - paramElement.Attribute("type", "float"); - } - - // Write out the interpolation method. - { - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", interpID); - std::string arrayID = interpID + "-array"; - { - XMLWriter::Element array(writer, "Name_array"); - array.Attribute("count", frameCount); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - array.WriteDirectText(" CONSTANT"); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "INTERPOLATION"); - paramElement.Attribute("type", "Name"); - } - - if (pModelData) // only for the non-skeletal animation - { - // Write out the TCB values. - { - const int stride = 3; - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", tcbID); - std::string arrayID = tcbID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount * stride); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - IAnimationData::TCB tcb; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameTCBPos(parameter.boneIndex, frameIndex, tcb); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameTCBRot(parameter.boneIndex, frameIndex, tcb); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameTCBScl(parameter.boneIndex, frameIndex, tcb); - break; - } - array.ContentArrayElement(tcb.tension); - array.ContentArrayElement(tcb.continuity); - array.ContentArrayElement(tcb.bias); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", stride); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "TENSION"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "CONTINUITY"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "BIAS"); - paramElement.Attribute("type", "float"); - } - } - - // Write out the ease-in/-out values. - { - const int stride = 2; - XMLWriter::Element inputElement(writer, "source"); - inputElement.Attribute("id", easeinoutID); - std::string arrayID = easeinoutID + "-array"; - { - XMLWriter::Element array(writer, "float_array"); - array.Attribute("count", frameCount * stride); - array.Attribute("id", arrayID); - for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) - { - IAnimationData::Ease ease; - switch (parameter.parameter) - { - case AnimationBoneParameter_TransX: - case AnimationBoneParameter_TransY: - case AnimationBoneParameter_TransZ: - animationData->GetFrameEaseInOutPos(parameter.boneIndex, frameIndex, ease); - break; - case AnimationBoneParameter_RotX: - case AnimationBoneParameter_RotY: - case AnimationBoneParameter_RotZ: - animationData->GetFrameEaseInOutRot(parameter.boneIndex, frameIndex, ease); - break; - case AnimationBoneParameter_SclX: - case AnimationBoneParameter_SclY: - case AnimationBoneParameter_SclZ: - animationData->GetFrameEaseInOutScl(parameter.boneIndex, frameIndex, ease); - break; - } - array.ContentArrayElement(ease.in); - array.ContentArrayElement(ease.out); - } - } - - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", arrayID); - accessorElement.Attribute("count", frameCount); - accessorElement.Attribute("stride", stride); - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "EASE_IN"); - paramElement.Attribute("type", "float"); - } - { - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "EASE_OUT"); - paramElement.Attribute("type", "float"); - } - } - } - - // Write out the sampler element. - std::string samplerID = parameter.name + "-sampler"; - { - XMLWriter::Element samplerElement(writer, "sampler"); - samplerElement.Attribute("id", samplerID); - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INPUT"); - inputElement.Attribute("source", std::string("#") + inputID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "OUTPUT"); - inputElement.Attribute("source", std::string("#") + outputID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INTERPOLATION"); - inputElement.Attribute("source", std::string("#") + interpID); - } - if (pModelData) // only for the non-skeletal animation - { - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "TCB"); - inputElement.Attribute("source", std::string("#") + tcbID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "EASE_IN_OUT"); - inputElement.Attribute("source", std::string("#") + easeinoutID); - } - } - } - - // Write out the channel element. - XMLWriter::Element channelElement(writer, "channel"); - channelElement.Attribute("source", std::string("#") + samplerID); - std::string targetName; - if (pBones) - { - targetName = (*pBones)[parameter.boneIndex].name; - } - else - { - assert(pModelData); - targetName = pModelData->GetModelName(parameter.boneIndex); - } - targetName = targetName + "/" + parameterTargetStrings[parameter.parameter]; - channelElement.Attribute("target", targetName); - } - } - - void WriteAnimationData( - IExportContext* context, - XMLWriter& writer, - std::vector& animations, - GeometryFileData& geometryFileData, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - const BoneDataMap& boneDataMap, - IExportSource* source, - ProgressRange& progressRange) - { - XMLWriter::Element libraryAnimationsElement(writer, "library_animations"); - - int animationEntryCount = int(animations.size()); - float animationEntryProgressSlice = (1.0f / (animationEntryCount ? float(animationEntryCount) : 1.0f)); - for (int animationEntryIndex = 0; animationEntryIndex < animationEntryCount; ++animationEntryIndex) - { - float FPS = source->GetDCCFrameRate(); - ProgressRange animationEntryProgressRange(progressRange, animationEntryProgressSlice); - - AnimationEntry& entry = animations[animationEntryIndex]; - - if (skeletonData.empty()) // Non-skeletal mesh - { - IAnimationData* animationData = NULL; - { - ProgressRange readAnimProgressRange(animationEntryProgressRange, 0.5f); - animationData = source->ReadAnimation(context, &geometryFileData, &modelData[0], -1, NULL, animationEntryIndex, FPS); - } - - if (animationData) - { - WriteAnimationTags(animationEntryProgressRange, entry, animationData, writer, NULL, &modelData[0]); - delete animationData; - } - } - else // Skeletal mesh - { - // Read the animation data. - SkeletonDataMap::const_iterator skeletonDataPos = skeletonData.find(std::make_pair(entry.geometryFileIndex, entry.modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - IAnimationData* animationData = NULL; - const SkeletonData& skeletonDataInstance = (*skeletonDataPos).second; - { - ProgressRange readAnimProgressRange(animationEntryProgressRange, 0.5f); - - animationData = source->ReadAnimation(context, &geometryFileData, &modelData[entry.modelIndex], entry.modelIndex, &skeletonDataInstance, entry.animationIndex, FPS); - } - - // Look up the bone entries for this model. - BoneDataMap::const_iterator boneDataPos = boneDataMap.find(std::make_pair(entry.geometryFileIndex, entry.modelIndex)); - const std::vector& bones = (*boneDataPos).second; - - if (animationData) - { - WriteAnimationTags(animationEntryProgressRange, entry, animationData, writer, &bones, NULL); - delete animationData; - } - } - } - } - } - - void WriteEffects(XMLWriter& writer, std::vector& effects, ProgressRange& progressRange) - { - XMLWriter::Element libraryEffectsElement(writer, "library_effects"); - for (int effectIndex = 0, effectCount = int(effects.size()); effectIndex < effectCount; ++effectIndex) - { - XMLWriter::Element effectElement(writer, "effect"); - effectElement.Attribute("id", effects[effectIndex].name); - - // Write out dummy effects values. - XMLWriter::Element profileElement(writer, "profile_COMMON"); - XMLWriter::Element techniqueElement(writer, "technique"); - techniqueElement.Attribute("sid", "default"); - XMLWriter::Element phongElement(writer, "phong"); - { - XMLWriter::Element emissionElement(writer, "emission"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "emission"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element ambientElement(writer, "ambient"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "ambient"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element diffuseElement(writer, "diffuse"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "diffuse"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element specularElement(writer, "specular"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "specular"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element shininessElement(writer, "shininess"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "shininess"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element reflectiveElement(writer, "reflective"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "reflective"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(1.0f); - } - { - XMLWriter::Element reflectivityElement(writer, "reflectivity"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "reflectivity"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element transparentElement(writer, "transparent"); - transparentElement.Attribute("opaque", "RGB_ZERO"); - XMLWriter::Element colorElement(writer, "color"); - colorElement.Attribute("sid", "transparent"); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - colorElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element transparencyElement(writer, "transparency"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "transparency"); - floatElement.ContentArrayElement(0.0f); - } - { - XMLWriter::Element refractionElement(writer, "index_of_refraction"); - XMLWriter::Element floatElement(writer, "float"); - floatElement.Attribute("sid", "index_of_refraction"); - floatElement.ContentArrayElement(0.0f); - } - } - } - - void WriteControllers( - XMLWriter& writer, - IExportContext* context, - IExportSource* exportSource, - std::vector& skinControllers, - std::vector& morphControllers, - std::map, int> modelMorphControllerMap, - GeometryFileData& geometryFileData, - const std::vector& modelData, - SkeletonDataMap& skeletonData, - MorphDataMap& morphData, - std::vector& morphGeometries, - std::map, int>, int>& morphGeometryMap, - std::vector& geometries, - std::map, int>& modelGeometryMap, - const BoneDataMap& boneDataMap, - ProgressRange& progressRange) - { - // - XMLWriter::Element libraryControllersElement(writer, "library_controllers"); - for (int controllerIndex = 0, controllerCount = int(skinControllers.size()); controllerIndex < controllerCount; ++controllerIndex) - { - SkinControllerEntry& controller = skinControllers[controllerIndex]; - SkeletonDataMap::iterator skeletonDataPos = skeletonData.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - if (skeletonDataPos == skeletonData.end()) - { - continue; - } - - SkeletonData skeleton = (*skeletonDataPos).second; - - // - XMLWriter::Element controllerElement(writer, "controller"); - controllerElement.Attribute("id", controller.name); - - // - std::string geometryName; - bool sourceFound = false; - { - std::map, int>::const_iterator modelMorphControllerMapPos = modelMorphControllerMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - int morphControllerIndex = (modelMorphControllerMapPos != modelMorphControllerMap.end() ? (*modelMorphControllerMapPos).second : -1); - geometryName = (morphControllerIndex >= 0 ? morphControllers[morphControllerIndex].name : "MISSING MORPH CONTROLLER NAME"); - sourceFound = (morphControllerIndex >= 0); - } - if (!sourceFound) - { - std::map, int>::const_iterator geometryMapPos = modelGeometryMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - int geometryIndex = (geometryMapPos != modelGeometryMap.end() ? (*geometryMapPos).second : -1); - geometryName = (geometryIndex >= 0 ? geometries[geometryIndex].name : "MISSING GEOMETRY NAME"); - sourceFound = (geometryIndex >= 0); - } - XMLWriter::Element skinElement(writer, "skin"); - skinElement.Attribute("source", "#" + geometryName); - - // - // 1.000000 0.000000 0.000000 0.000000 - // 0.000000 1.000000 0.000000 0.000000 - // 0.000000 0.000000 1.000000 0.000000 - // 0.000000 0.000000 0.000000 1.000000 - // - { - XMLWriter::Element bindMatrixElement(writer, "bind_shape_matrix"); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(0.0f); - bindMatrixElement.ContentArrayElement(1.0f); - } - - // - std::string jointsSourceName = controller.name + "_joints"; - { - XMLWriter::Element jointsSourceElement(writer, "source"); - jointsSourceElement.Attribute("id", jointsSourceName); - - // - const std::vector& bones = (*boneDataMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex))).second; - std::string arrayName = jointsSourceName + "_array"; - { - XMLWriter::Element idArrayElement(writer, "IDREF_array"); - idArrayElement.Attribute("id", arrayName); - idArrayElement.Attribute("count", skeleton.GetBoneCount()); - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - idArrayElement.ContentArrayElement(bones[boneIndex].name); - } - } - - // - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", skeleton.GetBoneCount()); - accessorElement.Attribute("stride", 1); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", std::string("IDREF")); - // - // - // - } - } - - // - std::string matricesSourceName = controller.name + "_matrices"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", matricesSourceName); - - // - std::string arrayName = matricesSourceName + "_array"; - { - XMLWriter::Element arrayElement(writer, "float_array"); - arrayElement.Attribute("id", arrayName); - arrayElement.Attribute("count", skeleton.GetBoneCount() * 16); - arrayElement.ContentLine(""); - for (int boneIndex = 0, boneCount = skeleton.GetBoneCount(); boneIndex < boneCount; ++boneIndex) - { - Vec3 scaleParams; - skeleton.GetScale((float*)&scaleParams, boneIndex); - Matrix44 scale = Matrix33::CreateScale(scaleParams); - - Ang3 rotationParams; - skeleton.GetRotation((float*)&rotationParams, boneIndex); - Matrix44 rotation = Matrix33::CreateRotationXYZ(rotationParams); - - Vec3 translationParams; - skeleton.GetTranslation((float*)&translationParams, boneIndex); - Matrix44 translation(IDENTITY); - translation.SetTranslation(translationParams); - - Matrix44 transform = translation * (rotation * scale); - transform.Invert(); - for (int i = 0; i < 4; ++i) - { - for (int j = 0; j < 4; ++j) - { - arrayElement.ContentArrayElement(transform(i, j)); - } - arrayElement.ContentLine(""); - } - } - } - - // - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", skeleton.GetBoneCount()); - accessorElement.Attribute("stride", 16); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", std::string("float4x4")); - - // - // - // - } - - // Read in the skinning info. - SkinningData skinningData; - exportSource->ReadSkinning(context, &skinningData, &modelData[controller.geometryFileIndex], controller.modelIndex, &skeleton); - - // Build a single array of weights. - std::vector weightsArray; - std::vector > weightIndexArray; - int vertexCount = skinningData.GetVertexCount(); - weightIndexArray.resize(vertexCount); - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - int linkCount = skinningData.GetBoneLinkCount(vertexIndex); - weightIndexArray[vertexIndex].resize(linkCount); - for (int linkIndex = 0; linkIndex < linkCount; ++linkIndex) - { - int weightIndex = int(weightsArray.size()); - weightsArray.push_back(skinningData.GetWeight(vertexIndex, linkIndex)); - weightIndexArray[vertexIndex][linkIndex] = weightIndex; - } - } - - // - std::string weightsSourceName = controller.name + "_weights"; - { - XMLWriter::Element weightsSourceElement(writer, "source"); - weightsSourceElement.Attribute("id", weightsSourceName); - - // - int weightCount = int(weightsArray.size()); - std::string arrayName = weightsSourceName + "_array"; - { - XMLWriter::Element floatArrayElement(writer, "float_array"); - floatArrayElement.Attribute("count", weightCount); - floatArrayElement.Attribute("id", arrayName); - - for (int weightIndex = 0; weightIndex < weightCount; ++weightIndex) - { - floatArrayElement.ContentArrayElement(weightsArray[weightIndex]); - } - } - - // - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - - // - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("count", weightCount); - accessorElement.Attribute("stride", 1); - accessorElement.Attribute("source", "#" + arrayName); - - // - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("type", "float"); - - // - // - // - } - - { - // - XMLWriter::Element jointsElement(writer, "joints"); - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "JOINT"); - inputElement.Attribute("source", "#" + jointsSourceName); - } - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "INV_BIND_MATRIX"); - inputElement.Attribute("source", "#" + matricesSourceName); - } - - // - } - - { - // - XMLWriter::Element vertexWeightsElement(writer, "vertex_weights"); - int vertexCount = skinningData.GetVertexCount(); - vertexWeightsElement.Attribute("count", vertexCount); - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "JOINT"); - inputElement.Attribute("offset", 0); - inputElement.Attribute("source", "#" + jointsSourceName); - } - - // - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "WEIGHT"); - inputElement.Attribute("offset", 1); - inputElement.Attribute("source", "#" + weightsSourceName); - } - - // - { - XMLWriter::Element vcountElement(writer, "vcount"); - - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - vcountElement.ContentArrayElement(int(weightIndexArray[vertexIndex].size())); - } - } - - // - { - XMLWriter::Element vElement(writer, "v"); - vElement.ContentLine(""); - - for (int vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex) - { - for (int linkIndex = 0, linkCount = int(weightIndexArray[vertexIndex].size()); linkIndex < linkCount; ++linkIndex) - { - vElement.ContentArrayElement(skinningData.GetBoneIndex(vertexIndex, linkIndex)); - vElement.ContentArrayElement(weightIndexArray[vertexIndex][linkIndex]); - } - vElement.ContentLine(""); - } - - // - } - // - } - - // - // - // - } - - // Write out the morph controllers. - for (int controllerIndex = 0, controllerCount = int(morphControllers.size()); controllerIndex < controllerCount; ++controllerIndex) - { - MorphControllerEntry& controller = morphControllers[controllerIndex]; - - // Find the geometry and morphs for the model. - std::map, int>::const_iterator modelGeometryMapPos = modelGeometryMap.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - MorphDataMap::const_iterator modelMorphDataPos = morphData.find(std::make_pair(controller.geometryFileIndex, controller.modelIndex)); - - if (modelGeometryMapPos != modelGeometryMap.end() && modelMorphDataPos != morphData.end()) - { - GeometryEntry& geometry = geometries[(*modelGeometryMapPos).second]; - const MorphData& modelMorphData = (*modelMorphDataPos).second; - - XMLWriter::Element controllerElement(writer, "controller"); - controllerElement.Attribute("id", controller.name); - XMLWriter::Element morphElement(writer, "morph"); - morphElement.Attribute("source", "#" + geometry.name); - - std::string targetsSourceID = controller.name + "-source_targets"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", targetsSourceID); - std::string arrayID = targetsSourceID + "-array"; - { - XMLWriter::Element idrefArrayElement(writer, "IDREF_array"); - idrefArrayElement.Attribute("id", arrayID); - idrefArrayElement.Attribute("count", modelMorphData.GetMorphCount()); - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - // Look up the geometry for this morph. - //std::vector& morphGeometries - std::map, int>, int>::const_iterator morphGeometryMapPos = morphGeometryMap.find(std::make_pair(std::make_pair(controller.geometryFileIndex, controller.modelIndex), morphIndex)); - int morphGeometryIndex = (morphGeometryMapPos != morphGeometryMap.end() ? (*morphGeometryMapPos).second : -1); - if (morphGeometryIndex >= -1) - { - const MorphGeometryEntry& morphGeometry = morphGeometries[morphGeometryIndex]; - idrefArrayElement.ContentArrayElement(morphGeometry.name); - } - } - } - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", "#" + arrayID); - accessorElement.Attribute("count", modelMorphData.GetMorphCount()); - accessorElement.Attribute("offset", 0); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "MORPH_TARGET"); - paramElement.Attribute("type", "IDREF"); - } - } - std::string weightsSourceID = controller.name + "-source_weights"; - { - XMLWriter::Element sourceElement(writer, "source"); - sourceElement.Attribute("id", weightsSourceID); - std::string arrayID = weightsSourceID + "-array"; - { - XMLWriter::Element floatArrayElement(writer, "float_array"); - floatArrayElement.Attribute("id", arrayID); - floatArrayElement.Attribute("count", modelMorphData.GetMorphCount()); - for (int morphIndex = 0, morphCount = modelMorphData.GetMorphCount(); morphIndex < morphCount; ++morphIndex) - { - // Look up the geometry for this morph. - //std::vector& morphGeometries - std::map, int>, int>::const_iterator morphGeometryMapPos = morphGeometryMap.find(std::make_pair(std::make_pair(controller.geometryFileIndex, controller.modelIndex), morphIndex)); - int morphGeometryIndex = (morphGeometryMapPos != morphGeometryMap.end() ? (*morphGeometryMapPos).second : -1); - if (morphGeometryIndex >= -1) - { - const MorphGeometryEntry& morphGeometry = morphGeometries[morphGeometryIndex]; - floatArrayElement.ContentArrayElement(0); - } - } - } - { - XMLWriter::Element techniqueCommonElement(writer, "technique_common"); - XMLWriter::Element accessorElement(writer, "accessor"); - accessorElement.Attribute("source", "#" + arrayID); - accessorElement.Attribute("count", modelMorphData.GetMorphCount()); - accessorElement.Attribute("offset", 0); - accessorElement.Attribute("stride", 1); - XMLWriter::Element paramElement(writer, "param"); - paramElement.Attribute("name", "MORPH_WEIGHT"); - paramElement.Attribute("type", "float"); - } - } - XMLWriter::Element targestElement(writer, "targets"); - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "MORPH_TARGET"); - inputElement.Attribute("source", "#" + targetsSourceID); - } - { - XMLWriter::Element inputElement(writer, "input"); - inputElement.Attribute("semantic", "MORPH_WEIGHT"); - inputElement.Attribute("source", "#" + weightsSourceID); - } - } - } - } - - void WriteImages(XMLWriter& writer, ProgressRange& progressRange) - { - XMLWriter::Element libraryImagesElement(writer, "library_images"); - } - - void WriteMaterials(XMLWriter& writer, MaterialData& materialData, std::map& materialFXMap, std::vector& effects, std::map& materialMaterialMap, std::vector& materials, ProgressRange& progressRange) - { - XMLWriter::Element libraryMaterialsElement(writer, "library_materials"); - - for (int materialIndex = 0, materialCount = materialData.GetMaterialCount(); materialIndex < materialCount; ++materialIndex) - { - std::map::iterator materialMapPos = materialMaterialMap.find(materialIndex); - int entryIndex = (materialMapPos != materialMaterialMap.end() ? (*materialMapPos).second : -1); - std::map::iterator effectMapPos = materialFXMap.find(materialIndex); - int effectIndex = (effectMapPos != materialFXMap.end() ? (*effectMapPos).second : -1); - - if (entryIndex >= 0) - { - std::string name = materials[entryIndex].name; - XMLWriter::Element materialElement(writer, "material"); - materialElement.Attribute("id", name); - if (effectIndex >= 0) - { - XMLWriter::Element effectElement(writer, "instance_effect"); - effectElement.Attribute("url", "#" + effects[effectIndex].name); - } - } - } - } - - void WriteScene(XMLWriter& writer, ProgressRange& progressRange) - { - XMLWriter::Element sceneElement(writer, "scene"); - XMLWriter::Element instanceElement(writer, "instance_visual_scene"); - instanceElement.Attribute("url", "#visual_scene_0"); - } -} - -bool ColladaWriter::Write(IExportSource* source, IExportContext* context, IXMLSink* sink, ProgressRange& progressRange) -{ - if (FloatingPointHasPrecisionIssues()) - { - // If you hit this point, please change floating point settings in your VS project (and recompile it): - // ConfigurationProperties -> C/C++ -> CodeGeneration -> FloatingPointModel: "/fp:strict". - // Note: using "/fp:precise" doesn't help. - assert(0); - context->Log(ILogger::eSeverity_Error, "Cannot write Collada file, because the writer has precision issues. Contact Crytek tools programmers."); - return false; - } - - // Temporarily change the current locale so that floats get written out using periods rather than commas. - LocaleChanger localeChangeToStandard(LC_NUMERIC, "C"); - - // Create an object to format the xml. - XMLWriter writer(sink); - - // Export the animations to the file. - { - XMLWriter::Element colladaElement(writer, "COLLADA"); - colladaElement.Attribute("xmlns", "http://www.collada.org/2005/11/COLLADASchema"); - colladaElement.Attribute("version", "1.4.1"); - - // Write out the document metadata. - WriteMetaData(source, writer, ProgressRange(progressRange, 0.01f)); - - // Read the skeleton. - GeometryFileData geometryFileData; - MaterialData materialData; - std::vector modelData; - SkeletonDataMap skeletonData; - MorphDataMap morphData; - { - ProgressRange subProgressRange(progressRange, 0.1f); - - source->ReadGeometryFiles(context, &geometryFileData); - - bool ok = source->ReadMaterials(context, &geometryFileData, &materialData); - if (!ok) - { - return false; - } - - modelData.resize(geometryFileData.GetGeometryFileCount()); - - for (int geometryFileIndex = 0, geometryFileCount = geometryFileData.GetGeometryFileCount(); geometryFileIndex < geometryFileCount; ++geometryFileIndex) - { - source->ReadModels(&geometryFileData, geometryFileIndex, &modelData[geometryFileIndex]); - - for (int modelIndex = 0, modelCount = modelData[geometryFileIndex].GetModelCount(); modelIndex < modelCount; ++modelIndex) - { - MorphDataMap::iterator morphDataPos = morphData.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), MorphData())).first; - source->ReadMorphs(context, &(*morphDataPos).second, &modelData[geometryFileIndex], modelIndex); - if ((*morphDataPos).second.GetMorphCount() == 0) - { - morphData.erase(morphDataPos); - } - - SkeletonDataMap::iterator skeletonDataPos = skeletonData.insert(std::make_pair(std::make_pair(geometryFileIndex, modelIndex), SkeletonData())).first; - if (!source->ReadSkeleton(&geometryFileData, geometryFileIndex, &modelData[geometryFileIndex], modelIndex, &materialData, &(*skeletonDataPos).second)) - { - skeletonData.erase(skeletonDataPos); - } - -#if !defined(HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT) -# define HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT 0 -#endif //!defined(HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT) - - skeletonDataPos = skeletonData.find(std::make_pair(geometryFileIndex, modelIndex)); - if (skeletonDataPos != skeletonData.end()) - { - SkeletonData newData, & oldData = (*skeletonDataPos).second; - int pelvisIndex = -1; - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - pelvisIndex = ((_stricmp(oldData.GetName(i).c_str(), "Bip01 Pelvis") == 0) ? i : pelvisIndex); - } - if (pelvisIndex >= 0) - { - if (pelvisIndex != 1) - { - context->Log(ILogger::eSeverity_Warning, "`Bip01 Pelvis` should be the second bone."); - } -#if HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT == 1 - std::vector oldToNewMap(oldData.GetBoneCount()); - std::vector newToOldMap(oldData.GetBoneCount()); - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - oldToNewMap[i] = i, newToOldMap[i] = i; - } - std::swap(oldToNewMap[pelvisIndex], oldToNewMap[1]); - std::swap(newToOldMap[pelvisIndex], newToOldMap[1]); - for (int i = 0, count = oldData.GetBoneCount(); i < count; ++i) - { - int oldIndex = newToOldMap[i]; - void* handle = oldData.GetBoneHandle(oldIndex); - std::string name = oldData.GetName(oldIndex); - int oldParentIndex = oldData.GetParentIndex(oldIndex); - int parentIndex = (oldParentIndex >= 0 ? oldToNewMap[oldParentIndex] : -1); - float translation[3], rotation[3], scale[3]; - oldData.GetTranslation(translation, oldIndex); - oldData.GetRotation(rotation, oldIndex); - oldData.GetScale(scale, oldIndex); - - int boneIndex = newData.AddBone(handle, name.c_str(), parentIndex); - newData.SetTranslation(boneIndex, translation); - newData.SetRotation(boneIndex, rotation); - newData.SetScale(boneIndex, scale); - - newData.SetHasGeometry(boneIndex, oldData.HasGeometry(oldIndex)); - - if (oldData.HasParentFrame(oldIndex)) - { - float parentFrameTranslation[3], parentFrameRotation[3], parentFrameScale[3]; - oldData.GetParentFrameTranslation(oldIndex, parentFrameTranslation); - oldData.GetParentFrameRotation(oldIndex, parentFrameRotation); - oldData.GetParentFrameScale(oldIndex, parentFrameScale); - newData.SetParentFrameTranslation(boneIndex, parentFrameTranslation); - newData.SetParentFrameRotation(boneIndex, parentFrameRotation); - newData.SetParentFrameScale(boneIndex, parentFrameScale); - } - for (int axisIndex = 0; axisIndex < 3; ++axisIndex) - { - ISkeletonData::Axis axis = ISkeletonData::Axis(axisIndex); - if (oldData.HasLimit(oldIndex, axis, ISkeletonData::LimitMin)) - { - newData.SetLimit(boneIndex, axis, ISkeletonData::LimitMin, oldData.GetLimit(oldIndex, axis, ISkeletonData::LimitMin)); - } - if (oldData.HasLimit(oldIndex, axis, ISkeletonData::LimitMax)) - { - newData.SetLimit(boneIndex, axis, ISkeletonData::LimitMax, oldData.GetLimit(oldIndex, axis, ISkeletonData::LimitMax)); - } - if (oldData.HasSpringTension(oldIndex, axis)) - { - newData.SetSpringTension(boneIndex, axis, oldData.GetSpringTension(oldIndex, axis)); - } - if (oldData.HasSpringAngle(oldIndex, axis)) - { - newData.SetSpringAngle(boneIndex, axis, oldData.GetSpringAngle(oldIndex, axis)); - } - if (oldData.HasAxisDamping(oldIndex, axis)) - { - newData.SetAxisDamping(boneIndex, axis, oldData.GetAxisDamping(oldIndex, axis)); - } - newData.SetPhysicalized(boneIndex, oldData.GetPhysicalized(oldIndex)); - } - } - (*skeletonDataPos).second = newData; -#endif //HACK_HACK_FORCE_PELVIS_TO_BE_BONE_1_BECAUSE_LOADING_CODE_EXPECTS_IT == 1 - } - } - } - } - } - - // Generate a list of fx to export. - std::map materialFXMap; - std::vector effects; - GenerateEffectsList(context, materialFXMap, effects, materialData); - - // Generate a list of geometry to export. - std::map, int> modelGeometryMap; - std::vector geometries; - GenerateGeometryList(context, modelGeometryMap, geometries, geometryFileData, modelData); - - // Generate a list of bone geometries to export. - std::map, int>, int> boneGeometryMap; - std::vector boneGeometries; - GenerateBoneGeometryList(context, boneGeometryMap, boneGeometries, geometryFileData, modelData, skeletonData); - - // Generate a list of morph geometries to export. - std::map, int>, int> morphGeometryMap; - std::vector morphGeometries; - GenerateMorphGeometryList(context, morphGeometryMap, morphGeometries, geometryFileData, modelData, morphData); - - BoneDataMap boneDataMap; - GenerateBoneList(context, boneDataMap, skeletonData, modelData); - - // Generate a list of animations to export. - std::vector animations; - GenerateAnimationList(context, animations, geometryFileData, modelData, skeletonData, source, ProgressRange(progressRange, 0.025f)); - - // Generate a list of morph controllers to export. - std::vector morphControllers; - std::map, int> modelMorphControllerMap; - GenerateMorphControllerList(context, morphControllers, modelMorphControllerMap, morphData, geometryFileData, modelData, modelGeometryMap, geometries, ProgressRange(progressRange, 0.0125f)); - - // Generate a list of skin controllers to export. - std::vector controllers; - std::map, int> modelControllerMap; - GenerateSkinControllerList(context, controllers, modelControllerMap, skeletonData, geometryFileData, modelData, modelGeometryMap, geometries, ProgressRange(progressRange, 0.0125f)); - - // Write out all the animations. - WriteAnimationList(writer, animations, ProgressRange(progressRange, 0.025f)); - WriteAnimationData(context, writer, animations, geometryFileData, modelData, skeletonData, boneDataMap, source, ProgressRange(progressRange, 0.475f)); - - // Write out all the effects. - WriteEffects(writer, effects, ProgressRange(progressRange, 0.01f)); - - // Write out the materials. - std::map materialMaterialMap; - std::vector materials; - GenerateMaterialList(context, materialMaterialMap, materialFXMap, effects, materials, materialData); - WriteMaterials(writer, materialData, materialFXMap, effects, materialMaterialMap, materials, ProgressRange(progressRange, 0.005f)); - - // Write out all the geometries. - bool ok = WriteGeometries(context, writer, geometries, geometryFileData, modelData, morphData, materialData, materials, materialMaterialMap, skeletonData, boneGeometries, boneGeometryMap, morphGeometryMap, morphGeometries, source, ProgressRange(progressRange, 0.2f)); - if (!ok) - { - return false; - } - - // Write out all the controllers. - WriteControllers(writer, context, source, controllers, morphControllers, modelMorphControllerMap, geometryFileData, modelData, skeletonData, morphData, morphGeometries, morphGeometryMap, geometries, modelGeometryMap, boneDataMap, ProgressRange(progressRange, 0.005f)); - - // Write out the list of models. - WriteHierarchy(writer, context, geometryFileData, materialData, materialMaterialMap, materials, modelData, skeletonData, modelGeometryMap, geometries, modelControllerMap, controllers, boneDataMap, boneGeometryMap, boneGeometries, modelMorphControllerMap, morphControllers, source, ProgressRange(progressRange, 0.1f)); - - // Write out all the other libraries. - WriteImages(writer, ProgressRange(progressRange, 0.01f)); - WriteScene(writer, ProgressRange(progressRange, 0.01f)); - } - - return true; -} diff --git a/Code/Tools/CryCommonTools/Export/ColladaWriter.h b/Code/Tools/CryCommonTools/Export/ColladaWriter.h deleted file mode 100644 index f880e8ce1b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ColladaWriter.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H -#pragma once - - -#include - -class IExportSource; -class IExportContext; -class ProgressRange; -class IXMLSink; - -class ColladaWriter -{ -public: - static bool Write(IExportSource* source, IExportContext* context, IXMLSink* sink, ProgressRange& progressRange); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_COLLADAWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/ExportFileType.cpp b/Code/Tools/CryCommonTools/Export/ExportFileType.cpp deleted file mode 100644 index 8e552f361b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportFileType.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ExportFileType.h" -#include "StringHelpers.h" - - -struct SFileTypeInfo -{ - int type; - const char* name; -}; - -SFileTypeInfo s_fileTypes[] = -{ - { CRY_FILE_TYPE_CGF, "cgf" }, - { CRY_FILE_TYPE_CGA, "cga" }, - { CRY_FILE_TYPE_CHR, "chr" }, - { CRY_FILE_TYPE_CAF, "caf" }, - { CRY_FILE_TYPE_ANM, "anm" }, - { CRY_FILE_TYPE_CHR | CRY_FILE_TYPE_CAF, "chrcaf" }, - { CRY_FILE_TYPE_CGA | CRY_FILE_TYPE_ANM, "cgaanm" }, - { CRY_FILE_TYPE_SKIN, "skin" }, - { CRY_FILE_TYPE_INTERMEDIATE_CAF, "i_caf" }, -}; - -static const int s_fileTypeCount = (sizeof(s_fileTypes) / sizeof(s_fileTypes[0])); - - -const char* ExportFileTypeHelpers::CryFileTypeToString(int const cryFileType) -{ - for (int i = 0; i < s_fileTypeCount; ++i) - { - if (s_fileTypes[i].type == cryFileType) - { - return s_fileTypes[i].name; - } - } - return "unknown"; -} - -int ExportFileTypeHelpers::StringToCryFileType(const char* str) -{ - if (str) - { - for (int i = 0; i < s_fileTypeCount; ++i) - { - if (_stricmp(str, s_fileTypes[i].name) == 0) - { - return s_fileTypes[i].type; - } - } - } - return CRY_FILE_TYPE_NONE; -} diff --git a/Code/Tools/CryCommonTools/Export/ExportFileType.h b/Code/Tools/CryCommonTools/Export/ExportFileType.h deleted file mode 100644 index 11d68f699b..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportFileType.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H -#pragma once - - -enum CryFileType -{ - CRY_FILE_TYPE_NONE = 0x0000, - CRY_FILE_TYPE_CGF = 0x0001, - CRY_FILE_TYPE_CGA = 0x0002, - CRY_FILE_TYPE_CHR = 0x0004, - CRY_FILE_TYPE_CAF = 0x0008, - CRY_FILE_TYPE_ANM = 0x0010, - CRY_FILE_TYPE_SKIN = 0x0020, - CRY_FILE_TYPE_INTERMEDIATE_CAF = 0x0040, - //START: Add Skinned Geometry (.CGF) export type (for touch bending vegetation) - CRY_FILE_TYPE_SKIN_CGF = 0x0080, - //END: Add Skinned Geometry (.CGF) export type (for touch bending vegetation) -}; - -namespace ExportFileTypeHelpers -{ - const char* CryFileTypeToString(int cryFileType); - int StringToCryFileType(const char* str); -}; - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTFILETYPE_H - diff --git a/Code/Tools/CryCommonTools/Export/ExportHelpers.h b/Code/Tools/CryCommonTools/Export/ExportHelpers.h deleted file mode 100644 index 00780696fe..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportHelpers.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H -#pragma once - - -#include - -namespace ExportHelpers -{ - inline void GenerateTextureCoordinates(float* const res_s, float* const res_t, const float x, const float y, const float z) - { - const float ax = ::fabs(x); - const float ay = ::fabs(y); - const float az = ::fabs(z); - - float s = 0.0f; - float t = 0.0f; - - if (ax > 1e-3f || ay > 1e-3f || az > 1e-3f) - { - if (ax > ay) - { - if (ax > az) - { - // X rules - s = y / ax; - t = z / ax; - } - else - { - // Z rules - s = x / az; - t = y / az; - } - } - else - { - // ax <= ay - if (ay > az) - { - // Y rules - s = x / ay; - t = z / ay; - } - else - { - // Z rules - s = x / az; - t = y / az; - } - } - } - - // Now the texture coordinates are in the range [-1,1]. - // We want normalized [0,1] texture coordinates. - s = (s + 1) * 0.5f; - t = (t + 1) * 0.5f; - - if (res_s) - { - *res_s = s; - } - if (res_t) - { - *res_t = t; - } - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp b/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp deleted file mode 100644 index 5fd0cb855f..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ExportSourceDecoratorBase.h" - -ExportSourceDecoratorBase::ExportSourceDecoratorBase(IExportSource* source) - : source(source) -{ -} - -void ExportSourceDecoratorBase::GetMetaData(SExportMetaData& metaData) const -{ - this->source->GetMetaData(metaData); -} - -std::string ExportSourceDecoratorBase::GetDCCFileName() const -{ - return this->source->GetDCCFileName(); -} - -std::string ExportSourceDecoratorBase::GetExportDirectory() const -{ - return this->source->GetExportDirectory(); -} - -void ExportSourceDecoratorBase::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - this->source->ReadGeometryFiles(context, geometryFileData); -} - -bool ExportSourceDecoratorBase::ReadMaterials(IExportContext* context, const IGeometryFileData* const geometryFileData, IMaterialData* materialData) -{ - return this->source->ReadMaterials(context, geometryFileData, materialData); -} - -void ExportSourceDecoratorBase::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - this->source->ReadModels(geometryFileData, geometryFileIndex, modelData); -} - -void ExportSourceDecoratorBase::ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* const modelData, int modelIndex, ISkeletonData* skeletonData) -{ - this->source->ReadSkinning(context, skinningData, modelData, modelIndex, skeletonData); -} - -bool ExportSourceDecoratorBase::ReadSkeleton(const IGeometryFileData* const geometryFileData, int geometryFileIndex, const IModelData* const modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - return this->source->ReadSkeleton(geometryFileData, geometryFileIndex, modelData, modelIndex, materialData, skeletonData); -} - -int ExportSourceDecoratorBase::GetAnimationCount() const -{ - return this->source->GetAnimationCount(); -} - -std::string ExportSourceDecoratorBase::GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const -{ - return this->source->GetAnimationName(geometryFileData, geometryFileIndex, animationIndex); -} - -void ExportSourceDecoratorBase::GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const -{ - this->source->GetAnimationTimeSpan(start, stop, animationIndex); -} - -void ExportSourceDecoratorBase::ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const -{ - this->source->ReadAnimationFlags(context, animationData, geometryFileData, modelData, modelIndex, skeletonData, animationIndex); -} - -IAnimationData* ExportSourceDecoratorBase::ReadAnimation(IExportContext* context, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const -{ - return this->source->ReadAnimation(context, geometryFileData, modelData, modelIndex, skeletonData, animationIndex, fps); -} - -bool ExportSourceDecoratorBase::ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* const modelData, const IMaterialData* const materialData, int modelIndex) -{ - return this->source->ReadGeometry(context, geometry, modelData, materialData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* const modelData, const IMaterialData* const materialData, int modelIndex) const -{ - return this->source->ReadGeometryMaterialData(context, geometryMaterialData, modelData, materialData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* const materialData) -{ - return this->source->ReadBoneGeometry(context, geometry, skeletonData, boneIndex, materialData); -} - -bool ExportSourceDecoratorBase::ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* const materialData) const -{ - return this->source->ReadBoneGeometryMaterialData(context, geometryMaterialData, skeletonData, boneIndex, materialData); -} - -void ExportSourceDecoratorBase::ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* const modelData, int modelIndex) -{ - this->source->ReadMorphs(context, morphData, modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* const modelData, int modelIndex, const IMorphData* const morphData, int morphIndex, const IMaterialData* materialData) -{ - return this->source->ReadMorphGeometry(context, geometry, modelData, modelIndex, morphData, morphIndex, materialData); -} - -bool ExportSourceDecoratorBase::HasValidPosController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidPosController(modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::HasValidRotController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidRotController(modelData, modelIndex); -} - -bool ExportSourceDecoratorBase::HasValidSclController(const IModelData* modelData, int modelIndex) const -{ - return this->source->HasValidSclController(modelData, modelIndex); -} diff --git a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h b/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h deleted file mode 100644 index df5bea80ee..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportSourceDecoratorBase.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H -#pragma once - - -#include "IExportSource.h" - -class ExportSourceDecoratorBase - : public IExportSource -{ -public: - ExportSourceDecoratorBase(IExportSource* source); - - virtual std::string GetResourceCompilerPath() const { return std::string(""); }; - virtual void GetMetaData(SExportMetaData& metaData) const; - virtual std::string GetDCCFileName() const; - virtual std::string GetExportDirectory() const; - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual bool ReadMaterials(IExportContext* context, const IGeometryFileData* geometryFileData, IMaterialData* materialData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - virtual int GetAnimationCount() const; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const; - virtual bool ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, const IMaterialData* materialData, int modelIndex); - virtual bool ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) const; - virtual bool ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData); - virtual bool ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) const; - virtual void ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* modelData, int modelIndex); - virtual bool ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, int modelIndex, const IMorphData* morphData, int morphIndex, const IMaterialData* materialData); - virtual bool HasValidPosController(const IModelData* modelData, int modelIndex) const; - virtual bool HasValidRotController(const IModelData* modelData, int modelIndex) const; - virtual bool HasValidSclController(const IModelData* modelData, int modelIndex) const; -protected: - IExportSource* source; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSOURCEDECORATORBASE_H diff --git a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp b/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp deleted file mode 100644 index bc10a107e7..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ExportStatusWindow.h" -#include "UI/Win32GUI.h" -#include "StringHelpers.h" -#include -#include - -enum -{ - WM_USER_TASK_FINISHED = WM_USER + 53, - WM_USER_ACCEPTED -}; - -struct ThreadData -{ - ExportStatusWindow* statusWindow; - void (ExportStatusWindow::* initialize)(int width, int height, const std::vector >& tasks); - void (ExportStatusWindow::* run)(); - int width; - int height; - const std::vector >* tasks; - HANDLE initializedSemaphore; -}; -unsigned int __stdcall ThreadFunc(void* threadDataMemory) -{ - ThreadData* data = static_cast(threadDataMemory); - ExportStatusWindow* statusWindow = data->statusWindow; - void (ExportStatusWindow::* initialize)(int width, int height, const std::vector >& tasks) = data->initialize; - void (ExportStatusWindow::* run)() = data->run; - int width = data->width; - int height = data->height; - const std::vector >& tasks = *data->tasks; - HANDLE initializedSemaphore = data->initializedSemaphore; - - // Initialize the data. - (statusWindow->*initialize)(width, height, tasks); - - // Let the creating thread know that we have read the data - it is - // now safe for it to clear it. - ReleaseSemaphore(initializedSemaphore, 1, 0); - - // Perform the main thread processing. - (statusWindow->*run)(); - return 0; -} - -#pragma warning(push) -#pragma warning(disable: 4355) // 'this' : used in base member initializer list -ExportStatusWindow::ExportStatusWindow(int width, int height, const std::vector >& tasks) - : m_threadHandle(0) - , m_warningsEncountered(false) - , m_errorsEncountered(false) - , m_waitState(WaitState_WarningsAndErrors) - , m_okButtonSpacer(0, 0, 2000, 0) - , m_okButton(_T("OK"), this, &ExportStatusWindow::OkPressed) - , m_okButtonLayout(Layout::DirectionHorizontal) -{ - OutputDebugString(_T("Showing status window.\n")); - - Win32GUI::Initialize(); - - HANDLE initializedSemaphore = CreateSemaphore(0, 0, 1, 0); - - // Create a thread to handle the message pump for the window. - ThreadData threadData; - threadData.statusWindow = this; - threadData.initialize = &ExportStatusWindow::Initialize; - threadData.run = &ExportStatusWindow::Run; - threadData.width = width; - threadData.height = height; - threadData.tasks = &tasks; - threadData.initializedSemaphore = initializedSemaphore; - m_threadHandle = (HANDLE)_beginthreadex( - 0, //void *security, - 0, //unsigned stack_size, - ThreadFunc, //unsigned ( *start_address )( void * ), - &threadData, //void *arglist, - 0, //unsigned initflag, - 0); //unsigned *thrdaddr - - // Wait until the thread has read the data, since once we return the data will be lost. - WaitForSingleObject(initializedSemaphore, INFINITE); - CloseHandle(initializedSemaphore); -} -#pragma warning(pop) - -ExportStatusWindow::~ExportStatusWindow() -{ - OutputDebugString(_T("Hiding status window.\n")); - - // Tell the thread to exit and then wait for it to do so. - if (HWND hwnd = (HWND)m_frameWindow.GetHWND()) - { - PostMessage(hwnd, WM_USER_TASK_FINISHED, 0, 0); - m_okButton.Enable(true); - WaitForSingleObject((HANDLE)m_threadHandle, INFINITE); - } -} - -void ExportStatusWindow::Initialize(int width, int height, const std::vector >& tasks) -{ - OutputDebugString(_T("Beginning status window thread.\n")); - - for (int taskIndex = 0, taskCount = int(tasks.size()); taskIndex < taskCount; ++taskIndex) - { - m_taskList.AddTask(tasks[taskIndex].first, tasks[taskIndex].second); - } - - m_okButtonLayout.AddComponent(&m_okButtonSpacer); - m_okButtonLayout.AddComponent(&m_okButton); - m_okButton.Enable(false); - - m_frameWindow.AddComponent(&m_taskList); - m_frameWindow.AddComponent(&m_progressBar); - m_frameWindow.AddComponent(&m_logWindow); - m_frameWindow.AddComponent(&m_okButtonLayout); - m_frameWindow.Show(true, width, height); -} - -void ExportStatusWindow::Run() -{ - MSG msg; - BOOL status; - bool waitingAcceptance = false; - while ((status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - break; - } - else if (msg.message == WM_USER_TASK_FINISHED) - { - if (m_waitState == WaitState_Always || - (m_waitState == WaitState_WarningsAndErrors && m_warningsEncountered || m_errorsEncountered) || - (m_waitState == WaitState_ErrorsOnly && m_errorsEncountered)) - { - waitingAcceptance = true; - } - else - { - break; - } - } - else if (waitingAcceptance && msg.message == WM_USER_ACCEPTED) - { - break; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - m_frameWindow.Show(false, 0, 0); - OutputDebugString(_T("Ending status window thread.\n")); -} - -void ExportStatusWindow::OkPressed() -{ - if (HWND hwnd = (HWND)m_frameWindow.GetHWND()) - { - PostMessage(hwnd, WM_USER_ACCEPTED, 0, 0); - } -} - -void ExportStatusWindow::SetWaitState(WaitState state) -{ - m_waitState = state; -} - -void ExportStatusWindow::AddTask(const std::string& id, const std::string& description) -{ - m_taskList.AddTask(id, description); -} - -void ExportStatusWindow::SetCurrentTask(const std::string& id) -{ - m_taskList.SetCurrentTask(id); -} - -void ExportStatusWindow::SetProgress(float progress) -{ - TCHAR buffer[2048]; - _sntprintf_s(buffer, sizeof(buffer), _TRUNCATE, _T("%.1f%% complete - exporting scene."), progress * 100); - m_frameWindow.SetCaption(buffer); - m_progressBar.SetProgress(progress); -} - -void ExportStatusWindow::Log(ILogger::ESeverity eSeverity, const char* message) -{ - if (eSeverity == ILogger::eSeverity_Error) - { - m_errorsEncountered = true; - } - else if (eSeverity == ILogger::eSeverity_Warning) - { - m_warningsEncountered = true; - } - - m_logWindow.Log(eSeverity, StringHelpers::ConvertString(message).c_str()); -} diff --git a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h b/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h deleted file mode 100644 index d82869ae96..0000000000 --- a/Code/Tools/CryCommonTools/Export/ExportStatusWindow.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H -#pragma once - - -#include "UI/FrameWindow.h" -#include "UI/ProgressBar.h" -#include "UI/TaskList.h" -#include "UI/LogWindow.h" -#include "UI/Spacer.h" -#include "UI/Layout.h" -#include "UI/PushButton.h" -#include "ILogger.h" - -class ExportStatusWindow -{ -public: - enum WaitState - { - WaitState_WarningsAndErrors, - WaitState_ErrorsOnly, - WaitState_Always, - WaitState_Never, - }; - - ExportStatusWindow(int width, int height, const std::vector >& tasks); - ~ExportStatusWindow(); - - void SetWaitState(WaitState state); - - void AddTask(const std::string& id, const std::string& description); - void SetCurrentTask(const std::string& id); - void SetProgress(float progress); - void Log(ILogger::ESeverity eSeverity, const char* message); - -private: - void Initialize(int width, int height, const std::vector >& tasks); - void Run(); - void OkPressed(); - - FrameWindow m_frameWindow; - TaskList m_taskList; - ProgressBar m_progressBar; - Spacer m_okButtonSpacer; - PushButton m_okButton; - Layout m_okButtonLayout; - LogWindow m_logWindow; - void* m_threadHandle; - bool m_warningsEncountered; - bool m_errorsEncountered; - WaitState m_waitState; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_EXPORTSTATUSWINDOW_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryData.cpp b/Code/Tools/CryCommonTools/Export/GeometryData.cpp deleted file mode 100644 index dd82d90181..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryData.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryData.h" - -GeometryData::GeometryData() -{ -} - -int GeometryData::AddPosition(float x, float y, float z) -{ - int positionIndex = int(this->positions.size()); - this->positions.push_back(Vector(x, y, z)); - return positionIndex; -} - -int GeometryData::AddNormal(float x, float y, float z) -{ - int normalIndex = int(this->normals.size()); - this->normals.push_back(Vector(x, y, z)); - return normalIndex; -} - -int GeometryData::AddTextureCoordinate(float u, float v) -{ - int textureCoordinateIndex = int(this->textureCoordinates.size()); - this->textureCoordinates.push_back(TextureCoordinate(u, v)); - return textureCoordinateIndex; -} - -int GeometryData::AddVertexColor(float r, float g, float b, float a) -{ - int vertexColorIndex = int(this->vertexColors.size()); - this->vertexColors.push_back(VertexColor(r, g, b, a)); - return vertexColorIndex; -} - -int GeometryData::AddPolygon(const int* indices, int mtlID) -{ - int polygonIndex = int(this->polygons.size()); - this->polygons.push_back(Polygon(mtlID, - Polygon::Vertex(indices[0], indices[1], indices[2], indices[3]), - Polygon::Vertex(indices[4], indices[5], indices[6], indices[7]), - Polygon::Vertex(indices[8], indices[9], indices[10], indices[11]))); - return polygonIndex; -} - -int GeometryData::GetNumberOfPositions() const -{ - return (int)this->positions.size(); -} - -int GeometryData::GetNumberOfNormals() const -{ - return (int)this->normals.size(); -} - -int GeometryData::GetNumberOfTextureCoordinates() const -{ - return (int)this->textureCoordinates.size(); -} - -int GeometryData::GetNumberOfVertexColors() const -{ - return (int)this->vertexColors.size(); -} - -int GeometryData::GetNumberOfPolygons() const -{ - return (int)this->polygons.size(); -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryData.h b/Code/Tools/CryCommonTools/Export/GeometryData.h deleted file mode 100644 index aa42925128..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryData.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H -#pragma once - - -#include "IGeometryData.h" -#include - -class GeometryData - : public IGeometryData -{ -public: - GeometryData(); - - // IGeometryData - virtual int AddPosition(float x, float y, float z); - virtual int AddNormal(float x, float y, float z); - virtual int AddTextureCoordinate(float u, float v); - virtual int AddVertexColor(float r, float g, float b, float a); - - virtual int AddPolygon(const int* indices, int mtlID); - - virtual int GetNumberOfPositions() const; - virtual int GetNumberOfNormals() const; - virtual int GetNumberOfTextureCoordinates() const; - virtual int GetNumberOfVertexColors() const; - - virtual int GetNumberOfPolygons() const; - - struct Vector - { - Vector(float x, float y, float z) - : x(x) - , y(y) - , z(z) {} - float x, y, z; - }; - - struct TextureCoordinate - { - TextureCoordinate(float u, float v) - : u(u) - , v(v) {} - float u, v; - }; - - struct VertexColor - { - VertexColor(float r, float g, float b, float a) - : r(r) - , g(g) - , b(b) - , a(a) {} - float r, g, b, a; - }; - - struct Polygon - { - struct Vertex - { - Vertex() {} - Vertex(int positionIndex, int normalIndex, int textureCoordinateIndex, int vertexColorIndex) - : positionIndex(positionIndex) - , normalIndex(normalIndex) - , textureCoordinateIndex(textureCoordinateIndex) - , vertexColorIndex(vertexColorIndex) {} - int positionIndex, normalIndex, textureCoordinateIndex, vertexColorIndex; - }; - - Polygon(int mtlID, const Vertex& v0, const Vertex& v1, const Vertex& v2) - : mtlID(mtlID) - { - v[0] = v0; - v[1] = v1; - v[2] = v2; - } - - int mtlID; - Vertex v[3]; - }; - - std::vector positions; - std::vector normals; - std::vector textureCoordinates; - std::vector vertexColors; - std::vector polygons; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYDATA_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp b/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp deleted file mode 100644 index 3333e12ca6..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryExportSourceAdapter.h" -#include "IGeometryFileData.h" -#include - -GeometryExportSourceAdapter::GeometryExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, const std::vector& geometryFileIndices) - : ExportSourceDecoratorBase(source) - , m_geometryFileData(geometryFileData) - , m_geometryFileIndices(geometryFileIndices) -{ - assert(m_geometryFileIndices.size() <= m_geometryFileData->GetGeometryFileCount()); - for (size_t i = 0; i < m_geometryFileIndices.size(); ++i) - { - int const geometryFileIndex = m_geometryFileIndices[i]; - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileData->GetGeometryFileCount()); - } -} - -void GeometryExportSourceAdapter::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - for (size_t i = 0; i < m_geometryFileIndices.size(); ++i) - { - int const geometryFileIndex = m_geometryFileIndices[i]; - int const newGeometryFileIndex = geometryFileData->AddGeometryFile( - m_geometryFileData->GetGeometryFileHandle(geometryFileIndex), - m_geometryFileData->GetGeometryFileName(geometryFileIndex), - m_geometryFileData->GetProperties(geometryFileIndex)); - } -} - -void GeometryExportSourceAdapter::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileIndices.size()); - this->source->ReadModels(m_geometryFileData, m_geometryFileIndices[geometryFileIndex], modelData); -} - -bool GeometryExportSourceAdapter::ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - assert(geometryFileIndex >= 0 && geometryFileIndex < m_geometryFileIndices.size()); - return this->source->ReadSkeleton(m_geometryFileData, m_geometryFileIndices[geometryFileIndex], modelData, modelIndex, materialData, skeletonData); -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h b/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h deleted file mode 100644 index 7fb6ee081d..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryExportSourceAdapter.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H -#pragma once - - -#include "ExportSourceDecoratorBase.h" - -class GeometryExportSourceAdapter - : public ExportSourceDecoratorBase -{ -public: - GeometryExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, const std::vector& geometryFileIndices); - - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - -private: - IGeometryFileData* m_geometryFileData; - std::vector m_geometryFileIndices; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYEXPORTSOURCEADAPTER_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp b/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp deleted file mode 100644 index f67c0905dd..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryFileData.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryFileData.h" - -int GeometryFileData::AddGeometryFile(const void* handle, const char* name, const SProperties& properties) -{ - const int geometryFileIndex = int(m_geometryFiles.size()); - m_geometryFiles.push_back(GeometryFileEntry(handle, name, properties)); - return geometryFileIndex; -} - -int GeometryFileData::GetGeometryFileCount() const -{ - return int(m_geometryFiles.size()); -} - -const void* GeometryFileData::GetGeometryFileHandle(int geometryFileIndex) const -{ - return m_geometryFiles[geometryFileIndex].handle; -} - -const char* GeometryFileData::GetGeometryFileName(int geometryFileIndex) const -{ - return m_geometryFiles[geometryFileIndex].name.c_str(); -} - -////////////////////////////////////////////////////////////////////////// -const IGeometryFileData::SProperties& GeometryFileData::GetProperties(int geometryFileIndex) const -{ - if (size_t(geometryFileIndex) >= m_geometryFiles.size()) - { - assert(0); - static SProperties badValue; - return badValue; - } - return m_geometryFiles[geometryFileIndex].properties; -} - -void GeometryFileData::SetProperties(int geometryFileIndex, const IGeometryFileData::SProperties& properties) -{ - if (size_t(geometryFileIndex) >= m_geometryFiles.size()) - { - assert(0); - return; - } - m_geometryFiles[geometryFileIndex].properties = properties; -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryFileData.h b/Code/Tools/CryCommonTools/Export/GeometryFileData.h deleted file mode 100644 index 975a9cc5f7..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryFileData.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H -#pragma once - - -#include "IGeometryFileData.h" -#include "STLHelpers.h" - -class GeometryFileData - : public IGeometryFileData -{ -public: - // IGeometryFileData - virtual int AddGeometryFile(const void* handle, const char* name, const SProperties& properties); - virtual const SProperties& GetProperties(int geometryFileIndex) const; - virtual void SetProperties(int geometryFileIndex, const SProperties& properties); - virtual int GetGeometryFileCount() const; - virtual const void* GetGeometryFileHandle(int geometryFileIndex) const; - virtual const char* GetGeometryFileName(int geometryFileIndex) const; - -private: - struct GeometryFileEntry - { - GeometryFileEntry(const void* a_handle, const char* a_name, const SProperties& a_properties) - : handle(a_handle) - , name(a_name) - , properties(a_properties) - { - } - - const void* handle; - std::string name; - SProperties properties; - }; - - std::vector m_geometryFiles; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYFILEDATA_H diff --git a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp b/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp deleted file mode 100644 index ddc27daf52..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "GeometryMaterialData.h" - -void GeometryMaterialData::AddUsedMaterialIndex(int materialIndex) -{ - std::map::iterator usedMaterialPos = m_usedMaterialIndexIndexMap.find(materialIndex); - if (usedMaterialPos == m_usedMaterialIndexIndexMap.end()) - { - int materialIndexIndex = int(m_usedMaterialIndices.size()); - m_usedMaterialIndices.push_back(materialIndex); - m_usedMaterialIndexIndexMap.insert(std::make_pair(materialIndex, materialIndexIndex)); - } -} - -int GeometryMaterialData::GetUsedMaterialCount() const -{ - return int(m_usedMaterialIndices.size()); -} - -int GeometryMaterialData::GetUsedMaterialIndex(int usedMaterialIndex) const -{ - return m_usedMaterialIndices[usedMaterialIndex]; -} diff --git a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h b/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h deleted file mode 100644 index b2fb5deb30..0000000000 --- a/Code/Tools/CryCommonTools/Export/GeometryMaterialData.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H -#pragma once - - -#include "IGeometryMaterialData.h" - -class GeometryMaterialData - : public IGeometryMaterialData -{ -public: - // IGeometryMaterialData - virtual void AddUsedMaterialIndex(int materialIndex); - virtual int GetUsedMaterialCount() const; - virtual int GetUsedMaterialIndex(int usedMaterialIndex) const; - -private: - std::vector m_usedMaterialIndices; - std::map m_usedMaterialIndexIndexMap; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_GEOMETRYMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/HelperData.h b/Code/Tools/CryCommonTools/Export/HelperData.h deleted file mode 100644 index adede42194..0000000000 --- a/Code/Tools/CryCommonTools/Export/HelperData.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H -#pragma once - - -struct SHelperData -{ -public: - enum EHelperType - { - eHelperType_UNKNOWN, - eHelperType_Point, - eHelperType_Dummy - }; - -public: - SHelperData() - : m_eHelperType(eHelperType_UNKNOWN) - { - } - -public: - EHelperType m_eHelperType; - float m_boundBoxMin[3]; // used for eHelperType_Dummy only - float m_boundBoxMax[3]; // used for eHelperType_Dummy only -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_HELPERDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IAnimationData.h b/Code/Tools/CryCommonTools/Export/IAnimationData.h deleted file mode 100644 index 4ac11abbb5..0000000000 --- a/Code/Tools/CryCommonTools/Export/IAnimationData.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H -#pragma once - - -class IAnimationData -{ -public: - virtual ~IAnimationData() {} - - virtual void SetFrameData(int modelIndex, int frameIndex, float translation[3], float rotation[3], float scale[3]) = 0; - virtual void SetFrameCount(int frameCount) = 0; - - virtual void SetFrameTimePos(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataPos(int modelIndex, int frameIndex, float translation[3]) = 0; - virtual void SetFrameCountPos(int modelIndex, int frameCount) = 0; - virtual void SetFrameTimeRot(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataRot(int modelIndex, int frameIndex, float rotation[3]) = 0; - virtual void SetFrameCountRot(int modelIndex, int frameCount) = 0; - virtual void SetFrameTimeScl(int modelIndex, int frameIndex, float time) = 0; - virtual void SetFrameDataScl(int modelIndex, int frameIndex, float scale[3]) = 0; - virtual void SetFrameCountScl(int modelIndex, int frameCount) = 0; - - // For TCB & Ease-In/-Out support - struct TCB - { - float tension; - float continuity; - float bias; - - TCB() - : tension(0) - , continuity(0) - , bias(0) {} - }; - struct Ease - { - float in; - float out; - - Ease() - : in(0) - , out(0) {} - }; - virtual void SetFrameTCBPos(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameTCBRot(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameTCBScl(int modelIndex, int frameIndex, TCB tcb) = 0; - virtual void SetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease ease) = 0; - virtual void SetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease ease) = 0; - virtual void SetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease ease) = 0; - - enum ModelFlags - { - ModelFlags_NoExport = 1 << 0 - }; - - virtual void SetModelFlags(int modelIndex, unsigned modelFlags) = 0; - - virtual void GetFrameData(int modelIndex, int frameIndex, const float*& translation, const float*& rotation, const float*& scale) const = 0; - virtual int GetFrameCount() const = 0; - - virtual float GetFrameTimePos(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataPos(int modelIndex, int frameIndex, const float*& translation) const = 0; - virtual int GetFrameCountPos(int modelIndex) const = 0; - virtual float GetFrameTimeRot(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataRot(int modelIndex, int frameIndex, const float*& rotation) const = 0; - virtual int GetFrameCountRot(int modelIndex) const = 0; - virtual float GetFrameTimeScl(int modelIndex, int frameIndex) const = 0; - virtual void GetFrameDataScl(int modelIndex, int frameIndex, const float*& scale) const = 0; - virtual int GetFrameCountScl(int modelIndex) const = 0; - - // For TCB & Ease-In/-Out support - virtual void GetFrameTCBPos(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameTCBRot(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameTCBScl(int modelIndex, int frameIndex, TCB& tcb) const = 0; - virtual void GetFrameEaseInOutPos(int modelIndex, int frameIndex, Ease& ease) const = 0; - virtual void GetFrameEaseInOutRot(int modelIndex, int frameIndex, Ease& ease) const = 0; - virtual void GetFrameEaseInOutScl(int modelIndex, int frameIndex, Ease& ease) const = 0; - - virtual unsigned GetModelFlags(int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IANIMATIONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IExportContext.h b/Code/Tools/CryCommonTools/Export/IExportContext.h deleted file mode 100644 index b2da053e6f..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportContext.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H -#pragma once - - -#include -#include "Exceptions.h" -#include "ILogger.h" - -struct IPakSystem; -class ISettings; - -class IExportContext - : public ILogger -{ -public: - // Declare an exception type to report the case where the scene must be saved before exporting. - struct NeedSaveErrorTag {}; - typedef Exception NeedSaveError; - struct PakSystemErrorTag {}; - typedef Exception PakSystemError; - - virtual void SetProgress(float progress) = 0; - virtual void SetCurrentTask(const std::string& id) = 0; - virtual IPakSystem* GetPakSystem() = 0; - virtual ISettings* GetSettings() = 0; - virtual void GetRootPath(char* buffer, int bufferSizeInBytes) = 0; - -protected: - // ILogger - virtual void LogImpl(ILogger::ESeverity eSeverity, const char* message) = 0; -}; - -struct CurrentTaskScope -{ - CurrentTaskScope(IExportContext* context, const std::string& id) - : context(context) {context->SetCurrentTask(id); } - ~CurrentTaskScope() {context->SetCurrentTask(""); } - IExportContext* context; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTCONTEXT_H diff --git a/Code/Tools/CryCommonTools/Export/IExportSource.h b/Code/Tools/CryCommonTools/Export/IExportSource.h deleted file mode 100644 index 61051d6a2a..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportSource.h +++ /dev/null @@ -1,98 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H -#pragma once - - -#include "Exceptions.h" - -class ISkeletonData; -class IAnimationData; -class IExportContext; -class IModelData; -class IGeometryFileData; -class IGeometryData; -class IMaterialData; -class ISkinningData; -class IMorphData; -class IGeometryMaterialData; - -namespace ExportGlobal -{ - const float g_defaultFrameRate = 30.f; -}; - -struct SExportMetaData -{ - enum EAxisUp - { - X_UP, - Y_UP, - Z_UP - }; - - char authoring_tool[128]; - char source_data[1024]; // Filename of the source. - char author[128]; // Name of the author. - char revision[64]; - EAxisUp up_axis; - float fMeterUnit; - float fFramesPerSecond; - - SExportMetaData() - { - fMeterUnit = 1.0f; - up_axis = Z_UP; - fFramesPerSecond = ExportGlobal::g_defaultFrameRate; - strcpy(authoring_tool, "CryENGINE Collada Exporter"); - strcpy(source_data, ""); - strcpy(author, ""); - strcpy(revision, "1.4.1"); - } -}; - -class IExportSource -{ -public: - virtual ~IExportSource() - { - } - virtual std::string GetResourceCompilerPath() const = 0; - virtual void GetMetaData(SExportMetaData& metaData) const = 0; - virtual std::string GetDCCFileName() const = 0; - virtual float GetDCCFrameRate() const{ return ExportGlobal::g_defaultFrameRate; } - virtual std::string GetExportDirectory() const = 0; - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) = 0; - virtual bool ReadMaterials(IExportContext* context, const IGeometryFileData* geometryFileData, IMaterialData* materialData) = 0; - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) = 0; - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData) = 0; - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) = 0; - virtual int GetAnimationCount() const = 0; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const = 0; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const = 0; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const = 0; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const = 0; - virtual bool ReadGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) = 0; - virtual bool ReadGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, const IModelData* modelData, const IMaterialData* materialData, int modelIndex) const = 0; - virtual bool ReadBoneGeometry(IExportContext* context, IGeometryData* geometry, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) = 0; - virtual bool ReadBoneGeometryMaterialData(IExportContext* context, IGeometryMaterialData* geometryMaterialData, ISkeletonData* skeletonData, int boneIndex, const IMaterialData* materialData) const = 0; - virtual void ReadMorphs(IExportContext* context, IMorphData* morphData, const IModelData* modelData, int modelIndex) = 0; - virtual bool ReadMorphGeometry(IExportContext* context, IGeometryData* geometry, const IModelData* modelData, int modelIndex, const IMorphData* morphData, int morphIndex, const IMaterialData* materialData) = 0; - virtual bool HasValidPosController(const IModelData* modelData, int modelIndex) const = 0; - virtual bool HasValidRotController(const IModelData* modelData, int modelIndex) const = 0; - virtual bool HasValidSclController(const IModelData* modelData, int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTSOURCE_H diff --git a/Code/Tools/CryCommonTools/Export/IExportWriter.h b/Code/Tools/CryCommonTools/Export/IExportWriter.h deleted file mode 100644 index 5f53f01049..0000000000 --- a/Code/Tools/CryCommonTools/Export/IExportWriter.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H -#pragma once - - -class IExportSource; -class IExportContext; - -class IExportWriter -{ -public: - virtual void Export(IExportSource* source, IExportContext* context) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IEXPORTWRITER_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryData.h b/Code/Tools/CryCommonTools/Export/IGeometryData.h deleted file mode 100644 index 0869c97421..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryData.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H -#pragma once - - -class IGeometryData -{ -public: - virtual int AddPosition(float x, float y, float z) = 0; - virtual int AddNormal(float x, float y, float z) = 0; - virtual int AddTextureCoordinate(float u, float v) = 0; - virtual int AddVertexColor(float r, float g, float b, float a) = 0; - virtual int AddPolygon(const int* indices, int mtlID) = 0; - - virtual int GetNumberOfPositions() const = 0; - virtual int GetNumberOfNormals() const = 0; - virtual int GetNumberOfTextureCoordinates() const = 0; - virtual int GetNumberOfVertexColors() const = 0; - virtual int GetNumberOfPolygons() const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryFileData.h b/Code/Tools/CryCommonTools/Export/IGeometryFileData.h deleted file mode 100644 index bc81366ab2..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryFileData.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H -#pragma once - - -#include "ExportFileType.h" -#include - -class IGeometryFileData -{ -public: - struct SProperties - { - int filetypeInt; // combination of flags from CryFileType - bool bDoNotMerge; - bool bUseCustomNormals; - bool bUseF32VertexFormat; - bool b8WeightsPerVertex; - std::string customExportPath; - - SProperties() - : filetypeInt(CRY_FILE_TYPE_NONE) - , bDoNotMerge(false) - , bUseCustomNormals(false) - , bUseF32VertexFormat(false) - , b8WeightsPerVertex(false) - { - } - }; -public: - virtual int AddGeometryFile(const void* handle, const char* name, const SProperties& properties) = 0; - virtual const SProperties& GetProperties(int geometryFileIndex) const = 0; - virtual int GetGeometryFileCount() const = 0; - - // return an implementation-specific handle (for example a maya Dag Path string, or a MAX node name or whatever) - // its opaque to the exporter, but you can cast it yourself. - virtual const void* GetGeometryFileHandle(int geometryFileIndex) const = 0; - virtual const char* GetGeometryFileName(int geometryFileIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYFILEDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h b/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h deleted file mode 100644 index 1c4eca55bf..0000000000 --- a/Code/Tools/CryCommonTools/Export/IGeometryMaterialData.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H -#pragma once - - -class IGeometryMaterialData -{ -public: - virtual void AddUsedMaterialIndex(int materialIndex) = 0; - virtual int GetUsedMaterialCount() const = 0; - virtual int GetUsedMaterialIndex(int usedMaterialIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IGEOMETRYMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IMaterialData.h b/Code/Tools/CryCommonTools/Export/IMaterialData.h deleted file mode 100644 index 82102eb3ce..0000000000 --- a/Code/Tools/CryCommonTools/Export/IMaterialData.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H -#pragma once - - -class IMaterialData -{ -public: - // the handle represents an implementation specific underlying handle (like a maya pointer to a string dag name). - virtual int AddMaterial(const char* name, int id, const void* handle, const char* properties) = 0; - virtual int AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties) = 0; - virtual int GetMaterialCount() const = 0; - virtual const char* GetName(int materialIndex) const = 0; - virtual int GetID(int materialIndex) const = 0; - virtual const char* GetSubMatName(int materialIndex) const = 0; - virtual const void* GetHandle(int materialIndex) const = 0; - virtual const char* GetProperties(int materialIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IModelData.h b/Code/Tools/CryCommonTools/Export/IModelData.h deleted file mode 100644 index 26ea7ed385..0000000000 --- a/Code/Tools/CryCommonTools/Export/IModelData.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H -#pragma once - - -#include "HelperData.h" -#include - -class IModelData -{ -public: - virtual int AddModel(const void* handle, const char* modelName, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString) = 0; - virtual int GetModelCount() const = 0; - virtual const void* GetModelHandle(int modelIndex) const = 0; - virtual const char* GetModelName(int modelIndex) const = 0; - virtual void SetTranslationRotationScale(int modelIndex, const float* translation, const float* rotation, const float* scale) = 0; - virtual void GetTranslationRotationScale(int modelIndex, float* translation, float* rotation, float* scale) const = 0; - virtual const SHelperData& GetHelperData(int modelIndex) const = 0; - virtual const std::string& GetProperties(int modelIndex) const = 0; - virtual bool IsRoot(int modelIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMODELDATA_H diff --git a/Code/Tools/CryCommonTools/Export/IMorphData.h b/Code/Tools/CryCommonTools/Export/IMorphData.h deleted file mode 100644 index 26c4f05e71..0000000000 --- a/Code/Tools/CryCommonTools/Export/IMorphData.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H -#pragma once - - -class IMorphData -{ -public: - virtual void SetHandle(const void* handle) = 0; - virtual void AddMorph(const void* handle, const char* name, const char* fullName = NULL) = 0; - virtual const void* GetHandle() const = 0; - virtual int GetMorphCount() const = 0; - virtual const void* GetMorphHandle(int morphIndex) const = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_IMORPHDATA_H diff --git a/Code/Tools/CryCommonTools/Export/ISkeletonData.h b/Code/Tools/CryCommonTools/Export/ISkeletonData.h deleted file mode 100644 index 75f3317343..0000000000 --- a/Code/Tools/CryCommonTools/Export/ISkeletonData.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H -#pragma once - - -class ISkeletonData -{ -public: - enum Axis - { - AxisX, - AxisY, - AxisZ - }; - enum Limit - { - LimitMin, - LimitMax - }; - - virtual int AddBone(const void* handle, const char* name, int parentIndex) = 0; - virtual int FindBone(const char* name) const = 0; - virtual const void* GetBoneHandle(int boneIndex) const = 0; - virtual int GetBoneParentIndex(int boneIndex) const = 0; - virtual int GetBoneCount() const = 0; - virtual void SetTranslation(int boneIndex, const float* vec) = 0; - virtual void SetRotation(int boneIndex, const float* vec) = 0; - virtual void SetScale(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameTranslation(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameRotation(int boneIndex, const float* vec) = 0; - virtual void SetParentFrameScale(int boneIndex, const float* vec) = 0; - virtual void SetPhysicalized(int boneIndex, bool physicalized) = 0; - virtual void SetHasGeometry(int boneIndex, bool hasGeometry) = 0; - virtual void SetBoneProperties(int boneIndex, const char* propertiesString) = 0; - virtual void SetBoneGeomProperties(int boneIndex, const char* propertiesString) = 0; - - virtual void SetLimit(int boneIndex, Axis axis, Limit extreme, float limit) = 0; - virtual void SetSpringTension(int boneIndex, Axis axis, float springTension) = 0; - virtual void SetSpringAngle(int boneIndex, Axis axis, float springAngle) = 0; - virtual void SetAxisDamping(int boneIndex, Axis axis, float damping) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKELETONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/ISkinningData.h b/Code/Tools/CryCommonTools/Export/ISkinningData.h deleted file mode 100644 index d20a3ad301..0000000000 --- a/Code/Tools/CryCommonTools/Export/ISkinningData.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H -#pragma once - - -class ISkinningData -{ -public: - virtual void SetVertexCount(int vertexCount) = 0; - virtual void AddWeight(int vertexIndex, int boneIndex, float weight) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_ISKINNINGDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MaterialData.cpp b/Code/Tools/CryCommonTools/Export/MaterialData.cpp deleted file mode 100644 index 243a0dcd93..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialData.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "MaterialData.h" - -int MaterialData::AddMaterial(const char* name, int id, const void* handle, const char* properties) -{ - const int materialIndex = int(m_materials.size()); - m_materials.push_back(MaterialEntry(name, id, "submat", handle, properties)); - return materialIndex; -} - -int MaterialData::AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties) -{ - const int materialIndex = int(m_materials.size()); - m_materials.push_back(MaterialEntry(name, id, subMatName, handle, properties)); - return materialIndex; -} - -int MaterialData::GetMaterialCount() const -{ - return int(m_materials.size()); -} - -const char* MaterialData::GetName(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].name.c_str(); -} - -int MaterialData::GetID(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].id; -} - -const char* MaterialData::GetSubMatName(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].subMatName.c_str(); -} - -const void* MaterialData::GetHandle(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].handle; -} - -const char* MaterialData::GetProperties(int materialIndex) const -{ - assert(materialIndex >= 0); - assert(materialIndex < int(m_materials.size())); - return m_materials[materialIndex].properties.c_str(); -} diff --git a/Code/Tools/CryCommonTools/Export/MaterialData.h b/Code/Tools/CryCommonTools/Export/MaterialData.h deleted file mode 100644 index 5916f56f9b..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialData.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H -#pragma once - - -#include "IMaterialData.h" - -class MaterialData - : public IMaterialData -{ -public: - virtual int AddMaterial(const char* name, int id, const void* handle, const char* properties); - virtual int AddMaterial(const char* name, int id, const char* subMatName, const void* handle, const char* properties); - virtual int GetMaterialCount() const; - virtual const char* GetName(int materialIndex) const; - virtual int GetID(int materialIndex) const; - virtual const char* GetSubMatName(int materialIndex) const; - virtual const void* GetHandle(int materialIndex) const; - virtual const char* GetProperties(int materialIndex) const; - -private: - struct MaterialEntry - { - MaterialEntry(const char* a_name, int a_id, const char* a_subMatName, const void* a_handle, const char* a_properties) - : name(a_name) - , id(a_id) - , subMatName(a_subMatName) - , handle(a_handle) - , properties(a_properties ? a_properties : "") - { - } - - string name; - int id; - string subMatName; - const void* handle; - string properties; - }; - - std::vector m_materials; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp b/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp deleted file mode 100644 index 82b9d1b88d..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialHelpers.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "MaterialHelpers.h" -#include "StringHelpers.h" -#include "PathHelpers.h" -#include "properties.h" - -MaterialHelpers::MaterialInfo::MaterialInfo() -{ - this->id = -1; - this->name = ""; - this->physicalize = "None"; - this->diffuseTexture = ""; - this->diffuseColor[0] = this->diffuseColor[1] = this->diffuseColor[2] = 1.0f; - this->specularColor[0] = this->specularColor[1] = this->specularColor[2] = 1.0f; - this->emissiveColor[0] = this->emissiveColor[1] = this->emissiveColor[2] = 0.0f; -} - -std::string MaterialHelpers::PhysicsIDToString(const int physicsID) -{ - switch (physicsID) - { - case 1: - return "Default"; - break; - case 2: - return "ProxyNoDraw"; - break; - case 3: - return "NoCollide"; - break; - case 4: - return "Obstruct"; - break; - default: - return "None"; - break; - } -} - -bool MaterialHelpers::WriteMaterials(const std::string& filename, const std::vector& materialList) -{ - FILE* materialFile = fopen(filename.c_str(), "w"); - if (materialFile) - { - fprintf(materialFile, "\n"); - fprintf(materialFile, " \n"); - for (int i = 0; i < materialList.size(); i++) - { - const MaterialInfo& material = materialList[i]; - - fprintf(materialFile, " \n"); - - fprintf(materialFile, " \n"); - - // Write out diffuse texture. - if (material.diffuseTexture.length() > 0) - { - //fprintf( materialFile, " \n", ProcessTexturePath( material.diffuseTexture ).c_str() ); - fprintf(materialFile, " \n", material.diffuseTexture.c_str()); - fprintf(materialFile, " \n"); - fprintf(materialFile, " \n"); - } - - fprintf(materialFile, " \n"); - fprintf(materialFile, " \n"); - } - fprintf(materialFile, " \n"); - fprintf(materialFile, "\n"); - fclose(materialFile); - - return true; - } - else - { - return false; - } -} diff --git a/Code/Tools/CryCommonTools/Export/MaterialHelpers.h b/Code/Tools/CryCommonTools/Export/MaterialHelpers.h deleted file mode 100644 index 0afe9de48c..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaterialHelpers.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H -#pragma once - - -namespace MaterialHelpers -{ - struct MaterialInfo - { - MaterialInfo();// : id(-1) { } - - std::string name; - std::string physicalize; - int id; - - float diffuseColor[3]; - float specularColor[3]; - float emissiveColor[3]; - std::string diffuseTexture; - }; - - std::string PhysicsIDToString(const int physicsID); - bool WriteMaterials(const std::string& filename, const std::vector& materialList); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MATERIALHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MaxHelpers.h b/Code/Tools/CryCommonTools/Export/MaxHelpers.h deleted file mode 100644 index bbb1cf17b7..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxHelpers.h +++ /dev/null @@ -1,138 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H -#pragma once - - -#include "CompileTimeAssert.h" -#include "PathHelpers.h" -#include "StringHelpers.h" - - -namespace MaxHelpers -{ - enum - { - kBadChar = '_' - }; - -#if !defined(MAX_PRODUCT_VERSION_MAJOR) - #error MAX_PRODUCT_VERSION_MAJOR is undefined -#elif (MAX_PRODUCT_VERSION_MAJOR >= 15) - COMPILE_TIME_ASSERT(sizeof(MCHAR) == 2); - #define MAX_MCHAR_SIZE 2 - typedef wstring MaxCompatibleString; -#elif (MAX_PRODUCT_VERSION_MAJOR >= 12) - COMPILE_TIME_ASSERT(sizeof(MCHAR) == 1); - #define MAX_MCHAR_SIZE 1 - typedef string MaxCompatibleString; -#else - #error 3dsMax 2009 and older are not supported anymore -#endif - - inline string CreateAsciiString(const char* s_ansi) - { - return StringHelpers::ConvertAnsiToAscii(s_ansi, kBadChar); - } - - - inline string CreateAsciiString(const wchar_t* s_utf16) - { - const string s_ansi = StringHelpers::ConvertUtf16ToAnsi(s_utf16, kBadChar); - return CreateAsciiString(s_ansi.c_str()); - } - - - inline string CreateUtf8String(const char* s_ansi) - { - return StringHelpers::ConvertAnsiToUtf8(s_ansi); - } - - - inline string CreateUtf8String(const wchar_t* s_utf16) - { - return StringHelpers::ConvertUtf16ToUtf8(s_utf16); - } - - - inline string CreateTidyAsciiNodeName(const char* s_ansi) - { - const size_t len = strlen(s_ansi); - - string res; - res.reserve(len); - - for (size_t i = 0; i < len; ++i) - { - char c = s_ansi[i]; - if (c < ' ' || c >= 127) - { - c = kBadChar; - } - res.append(1, c); - } - return res; - } - - - inline string CreateTidyAsciiNodeName(const wchar_t* s_utf16) - { - const string s_ansi = StringHelpers::ConvertUtf16ToAnsi(s_utf16, kBadChar); - return CreateTidyAsciiNodeName(s_ansi.c_str()); - ; - } - - - inline MSTR CreateMaxStringFromAscii(const char* s_ascii) - { -#if (MAX_MCHAR_SIZE == 2) - return MSTR(StringHelpers::ConvertAsciiToUtf16(s_ascii).c_str()); -#else - return MSTR(s_ascii); -#endif - } - - - inline MaxCompatibleString CreateMaxCompatibleStringFromAscii(const char* s_ascii) - { -#if (MAX_MCHAR_SIZE == 2) - return StringHelpers::ConvertAsciiToUtf16(s_ascii); -#else - return MaxCompatibleString(s_ascii); -#endif - } - - - inline string GetAbsoluteAsciiPath(const char* s_ansi) - { - if (!s_ansi || !s_ansi[0]) - { - return string(); - } - return PathHelpers::GetAbsoluteAsciiPath(StringHelpers::ConvertAnsiToUtf16(s_ansi).c_str()); - } - - - inline string GetAbsoluteAsciiPath(const wchar_t* s_utf16) - { - if (!s_utf16 || !s_utf16[0]) - { - return string(); - } - return PathHelpers::GetAbsoluteAsciiPath(s_utf16); - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp b/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp deleted file mode 100644 index 2afe2ca0b0..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "MaxUserPropertyHelpers.h" -#include "StringHelpers.h" -#include "MaxHelpers.h" - - -std::string MaxUserPropertyHelpers::GetNodeProperties(INode* node) -{ - if (node == 0) - { - return std::string(); - } - - MSTR buf; - node->GetUserPropBuffer(buf); - - return MaxHelpers::CreateAsciiString(buf); -} - - -std::string MaxUserPropertyHelpers::GetStringNodeProperty(INode* node, const char* name, const char* defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - MSTR val; - if (!node->GetUserPropString(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return MaxHelpers::CreateAsciiString(val); -} - - -float MaxUserPropertyHelpers::GetFloatNodeProperty(INode* node, const char* name, float defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - float val; - if (!node->GetUserPropFloat(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return val; -} - - -int MaxUserPropertyHelpers::GetIntNodeProperty(INode* node, const char* name, int defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - int val; - if (!node->GetUserPropInt(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return val; -} - - -bool MaxUserPropertyHelpers::GetBoolNodeProperty(INode* node, const char* name, bool defaultValue) -{ - if (node == 0) - { - return defaultValue; - } - - BOOL val; - if (!node->GetUserPropBool(MaxHelpers::CreateMaxStringFromAscii(name), val)) - { - return defaultValue; - } - - return (val != 0); -} diff --git a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h b/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h deleted file mode 100644 index efef23e167..0000000000 --- a/Code/Tools/CryCommonTools/Export/MaxUserPropertyHelpers.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H -#pragma once - - -#include - -class INode; - -namespace MaxUserPropertyHelpers -{ - std::string GetNodeProperties(INode* node); - std::string GetStringNodeProperty(INode* node, const char* name, const char* defaultValue); - float GetFloatNodeProperty(INode* node, const char* name, float defaultValue); - int GetIntNodeProperty(INode* node, const char* name, int defaultValue); - bool GetBoolNodeProperty(INode* node, const char* name, bool defaultValue); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MAXUSERPROPERTYHELPERS_H diff --git a/Code/Tools/CryCommonTools/Export/MeshUtils.h b/Code/Tools/CryCommonTools/Export/MeshUtils.h deleted file mode 100644 index 81b456bffb..0000000000 --- a/Code/Tools/CryCommonTools/Export/MeshUtils.h +++ /dev/null @@ -1,914 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H -#pragma once - - -#include "BaseTypes.h" // uint8 -#include "Cry_Vector3.h" // Vec3 -#include "IIndexedMesh.h" // CMesh -namespace MeshUtils -{ - struct Face - { - int vertexIndex[3]; - }; - - struct Color - { - uint8 r; - uint8 g; - uint8 b; - }; - - // Stores linking of a vertex to bone(s) - class VertexLinks - { - public: - struct Link - { - int boneId; - float weight; - Vec3 offset; - - Link() - : boneId(-1) - , weight(-1.0f) - , offset(0.0f, 0.0f, 0.0f) - { - } - }; - - enum ESort - { - eSort_ByWeight, - eSort_ByBoneId, - }; - - public: - std::vector links; - - public: - // minWeightToDelete: links with weights <= minWeightToDelete will be deleted - const char* Normalize(ESort eSort, const float minWeightToDelete, const int maxLinkCount) - { - if (minWeightToDelete < 0 || minWeightToDelete >= 1) - { - return "Bad minWeightToDelete passed"; - } - if (maxLinkCount <= 0) - { - return "Bad maxLinkCount passed"; - } - - // Merging links with matching bone ids - { - DeleteByWeight(0.0f); - - if (links.empty()) - { - return "All bone links of a vertex have zero weight"; - } - - std::sort(links.begin(), links.end(), CompareLinksByBoneId); - - size_t dst = 0; - for (size_t i = 1; i < links.size(); ++i) - { - if (links[i].boneId == links[dst].boneId) - { - const float w0 = links[dst].weight; - const float w1 = links[i].weight; - const float a = w0 / (w0 + w1); - links[dst].offset = links[dst].offset * a + links[i].offset * (1 - a); - links[dst].weight = w0 + w1; - } - else - { - links[++dst] = links[i]; - } - } - - links.resize(dst + 1); - } - - // Deleting links, normalizing link weights. - // - // Note: we produce meaningful results even in cases like this: - // input weights are { 0.03, 0.01 }, minWeightTodelete is 0.2. - // Output weights produced are { 0.75, 0.25 }. - { - std::sort(links.begin(), links.end(), CompareLinksByWeight); - - if (links.size() > maxLinkCount) - { - links.resize(maxLinkCount); - } - - NormalizeWeights(); - - const size_t oldSize = links.size(); - - DeleteByWeight(minWeightToDelete); - - if (links.empty()) - { - return "All bone links of a vertex are deleted (minWeightToDelete is too big)"; - } - - if (links.size() != oldSize) - { - NormalizeWeights(); - } - } - - switch (eSort) - { - case eSort_ByWeight: - // Do nothing because we already sorted links by weight (see above) - break; - case eSort_ByBoneId: - std::sort(links.begin(), links.end(), CompareLinksByBoneId); - break; - default: - assert(0); - break; - } - - return 0; - } - - private: - void DeleteByWeight(float minWeightToDelete) - { - for (size_t i = 0; i < links.size(); ++i) - { - if (links[i].weight <= minWeightToDelete) - { - if (i < links.size() - 1) - { - links[i] = links[links.size() - 1]; - } - links.resize(links.size() - 1); - --i; - } - } - } - - void NormalizeWeights() - { - assert(!links.empty() && links[0].weight > 0); - - float w = 0; - - for (size_t i = 0; i < links.size(); ++i) - { - w += links[i].weight; - } - - w = 1 / w; - - for (size_t i = 0; i < links.size(); ++i) - { - links[i].weight *= w; - } - } - - static bool CompareLinksByBoneId(const Link& left, const Link& right) - { - if (left.boneId != right.boneId) - { - return left.boneId < right.boneId; - } - if (left.weight != right.weight) - { - return left.weight < right.weight; - } - return memcmp(&left.offset, &right.offset, sizeof(left.offset)) < 0; - } - - static bool CompareLinksByWeight(const Link& left, const Link& right) - { - if (left.weight != right.weight) - { - return left.weight > right.weight; - } - if (left.boneId != right.boneId) - { - return left.boneId < right.boneId; - } - return memcmp(&left.offset, &right.offset, sizeof(left.offset)) < 0; - } - }; - - - class Mesh - { - public: - // Vertex data - std::vector m_positions; - std::vector m_topologyIds; - std::vector m_normals; - std::vector> m_texCoords; - std::vector m_colors; - std::vector m_alphas; - std::vector m_links; - std::vector m_vertexMatIds; - size_t m_auxSizeof; - std::vector m_aux; - - // Face data - std::vector m_faces; - std::vector m_faceMatIds; - - // Mappings computed and filled by ComputeVertexRemapping() - std::vector m_vertexOldToNew; - std::vector m_vertexNewToOld; - - public: - Mesh() - : m_auxSizeof(0) - { - } - - int GetVertexCount() const - { - return m_positions.size(); - } - - int GetFaceCount() const - { - return m_faces.size(); - } - - ////////////////////////////////////////////////////////////////////////// - // Setters - - void Clear() - { - m_positions.clear(); - m_topologyIds.clear(); - m_normals.clear(); - m_texCoords.clear(); - m_colors.clear(); - m_alphas.clear(); - m_links.clear(); - m_vertexMatIds.clear(); - m_aux.clear(); - - m_faces.clear(); - m_faceMatIds.clear(); - - m_vertexOldToNew.clear(); - m_vertexNewToOld.clear(); - } - - const char* SetPositions(const float* pVec3, int count, int stride, const float scale) - { - if (count <= 0) - { - return "bad position count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(Vec3))) - { - return "bad position stride"; - } - - m_positions.resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec3) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1]) || !_finite(p[2])) - { - m_positions.clear(); - return "Illegal (NAN) vertex position. Fix the 3d Model."; - } - m_positions[i].x = p[0] * scale; - m_positions[i].y = p[1] * scale; - m_positions[i].z = p[2] * scale; - } - - return 0; - } - - const char* SetTopologyIds(const int* pTopo, int count, int stride) - { - if (count <= 0) - { - return "bad topologyId count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(int))) - { - return "bad topologyId stride"; - } - - m_topologyIds.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pTopo) + ((size_t)i * stride)); - m_topologyIds[i] = p[0]; - } - - return 0; - } - - const char* SetNormals(const float* pVec3, int count, int stride) - { - if (count <= 0) - { - return "bad normal count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(Vec3))) - { - return "bad normal stride"; - } - - m_normals.resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec3) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1]) || !_finite(p[2])) - { - m_normals.clear(); - return "Illegal (NAN) vertex normal. Fix the 3d Model."; - } - m_normals[i].x = p[0]; - m_normals[i].y = p[1]; - m_normals[i].z = p[2]; - m_normals[i] = m_normals[i].GetNormalizedSafe(Vec3_OneZ); - } - - return 0; - } - - const char* SetTexCoords(const float* pVec2, int count, int stride, bool bFlipT, uint streamIndex) - { - if (count <= 0) - { - return "bad texCoord count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(float) * 2)) - { - return "bad texCoord stride"; - } - if (m_texCoords.size() <= streamIndex) - { - m_texCoords.resize(streamIndex + 1); - } - - m_texCoords[streamIndex].resize(count); - - for (int i = 0; i < count; ++i) - { - const float* const p = (const float*)(((const char*)pVec2) + ((size_t)i * stride)); - if (!_finite(p[0]) || !_finite(p[1])) - { - m_texCoords[streamIndex].clear(); - return "Illegal (NAN) texture coordinate. Fix the 3d Model."; - } - m_texCoords[streamIndex][i].x = p[0]; - m_texCoords[streamIndex][i].y = bFlipT ? 1 - p[1] : p[1]; - } - - return 0; - } - - const char* SetColors(const uint8* pRgb, int count, int stride) - { - if (count <= 0) - { - return "bad color count"; - } - if (stride < 0 || (stride > 0 && stride < 3)) - { - return "bad color stride"; - } - - m_colors.resize(count); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pRgb) + ((size_t)i * stride)); - m_colors[i].r = p[0]; - m_colors[i].g = p[1]; - m_colors[i].b = p[2]; - } - - return 0; - } - - const char* SetAlphas(const uint8* pAlpha, int count, int stride) - { - if (count <= 0) - { - return "bad alpha count"; - } - if (stride < 0) - { - return "bad alpha stride"; - } - - m_alphas.resize(count); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pAlpha) + ((size_t)i * stride)); - m_alphas[i] = p[0]; - } - - return 0; - } - - const char* SetFaces(const int* pVertIdx3, int count, int stride) - { - if (count <= 0) - { - return "bad face count"; - } - if (stride < 0 || (stride > 0 && stride < 3 * sizeof(int))) - { - return "bad face stride"; - } - - m_faces.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pVertIdx3) + ((size_t)i * stride)); - for (int j = 0; j < 3; ++j) - { - if (p[j] < 0 || p[j] >= m_positions.size()) - { - return "bad vertex index found in a face"; - } - m_faces[i].vertexIndex[j] = p[j]; - } - } - - return 0; - } - - const char* SetFaceMatIds(const int* pMatIds, int count, int stride, int maxMaterialId) - { - if (count <= 0) - { - return "bad face materialId count"; - } - if (stride < 0 || (stride > 0 && stride < sizeof(int))) - { - return "bad face materialIdstride"; - } - - m_faceMatIds.resize(count); - - for (int i = 0; i < count; ++i) - { - const int* const p = (const int*)(((const char*)pMatIds) + ((size_t)i * stride)); - if (p[0] < 0) - { - return "negative material ID found in a face"; - } - if (p[0] >= maxMaterialId) - { - return "material ID found in a face is outside of allowed ranges"; - } - m_faceMatIds[i] = p[0]; - } - - return 0; - } - - const char* SetAux(size_t auxSizeof, const void* pData, int count, int stride) - { - if (auxSizeof <= 0) - { - return "bad aux sizeof"; - } - if (count <= 0) - { - return "bad aux count"; - } - if (stride < 0 || (stride > 0 && stride < auxSizeof)) - { - return "bad aux stride"; - } - - m_auxSizeof = auxSizeof; - - m_aux.resize(count * m_auxSizeof); - - for (int i = 0; i < count; ++i) - { - const uint8* const p = (((const uint8*)pData) + ((size_t)i * stride)); - memcpy(&m_aux[i * m_auxSizeof], p, m_auxSizeof); - } - - return 0; - } - - ////////////////////////////////////////////////////////////////////////// - // Validation - - // Returns 0 if ok, or pointer to the error text - const char* Validate() const - { - const int nVerts = (int)m_positions.size(); - if (nVerts <= 0) - { - return "No vertices"; - } - - const int nFaces = (int)m_faces.size(); - if (nFaces <= 0) - { - return "No faces"; - } - - if (!m_topologyIds.empty() && nVerts != (int)m_topologyIds.size()) - { - return "Mismatch in the number of topology IDs"; - } - - if (!m_normals.empty() && nVerts != (int)m_normals.size()) - { - return "Mismatch in the number of normals"; - } - - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - if (!m_texCoords[streamIndex].empty() && nVerts != (int)m_texCoords[streamIndex].size()) - { - return "Mismatch in the number of texture coordinates"; - } - } - - if (!m_colors.empty() && nVerts != (int)m_colors.size()) - { - return "Mismatch in the number of colors"; - } - - if (!m_alphas.empty() && nVerts != (int)m_alphas.size()) - { - return "Mismatch in the number of alphas"; - } - - if (!m_links.empty() && nVerts != (int)m_links.size()) - { - return "Mismatch in the number of vertex-bone links"; - } - - for (size_t i = 0; i < m_links.size(); ++i) - { - if (m_links[i].links.empty()) - { - return "Found a vertex without bone linking"; - } - } - - if (!m_vertexMatIds.empty() && nVerts != (int)m_vertexMatIds.size()) - { - return "Mismatch in the number of vertex materials"; - } - - if (!m_aux.empty() && nVerts != (int)(m_aux.size() / m_auxSizeof)) - { - return "Mismatch in the number of auxiliary elements"; - } - - if (!m_faceMatIds.empty() && nFaces != (int)m_faceMatIds.size()) - { - return "Mismatch in the number of face materials"; - } - - return 0; - } - - ////////////////////////////////////////////////////////////////////////// - // Computation - - void RemoveDegenerateFaces() - { - int writePos = 0; - for (int readPos = 0; readPos < (int)m_faces.size(); ++readPos) - { - const Face& face = m_faces[readPos]; - if (face.vertexIndex[0] != face.vertexIndex[1] && - face.vertexIndex[1] != face.vertexIndex[2] && - face.vertexIndex[0] != face.vertexIndex[2]) - { - m_faces[writePos] = m_faces[readPos]; - if (!m_faceMatIds.empty()) - { - m_faceMatIds[writePos] = m_faceMatIds[readPos]; - } - ++writePos; - } - } - m_faces.resize(writePos); - if (!m_faceMatIds.empty()) - { - m_faceMatIds.resize(writePos); - } - } - - int AddVertexCopy(int sourceVertexIndex) - { - if (sourceVertexIndex < 0 || sourceVertexIndex >= m_positions.size()) - { - assert(0); - return -1; - } - - m_positions.push_back(m_positions[sourceVertexIndex]); - if (!m_topologyIds.empty()) - { - m_topologyIds.push_back(m_topologyIds[sourceVertexIndex]); - } - if (!m_normals.empty()) - { - m_normals.push_back(m_normals[sourceVertexIndex]); - } - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - if (!m_texCoords[streamIndex].empty()) - { - m_texCoords[streamIndex].push_back(m_texCoords[streamIndex][sourceVertexIndex]); - } - } - if (!m_colors.empty()) - { - m_colors.push_back(m_colors[sourceVertexIndex]); - } - if (!m_alphas.empty()) - { - m_alphas.push_back(m_alphas[sourceVertexIndex]); - } - if (!m_links.empty()) - { - m_links.push_back(m_links[sourceVertexIndex]); - } - if (!m_vertexMatIds.empty()) - { - m_vertexMatIds.push_back(m_vertexMatIds[sourceVertexIndex]); - } - if (!m_aux.empty()) - { - m_aux.resize(m_aux.size() + m_auxSizeof); - memcpy(&m_aux[m_aux.size() - m_auxSizeof], &m_aux[sourceVertexIndex * m_auxSizeof], m_auxSizeof); - } - return (int)m_positions.size() - 1; - } - - // Note: might create new vertices and modify vertex indices in faces - void SetVertexMaterialIdsFromFaceMaterialIds() - { - m_vertexMatIds.clear(); - if (m_faceMatIds.empty()) - { - return; - } - m_vertexMatIds.resize(m_positions.size(), -1); - - for (size_t i = 0; i < m_faces.size(); ++i) - { - const int faceMatId = m_faceMatIds[i]; - for (int j = 0; j < 3; ++j) - { - int v = m_faces[i].vertexIndex[j]; - if (m_vertexMatIds[v] >= 0 && m_vertexMatIds[v] != faceMatId) - { - v = AddVertexCopy(v); - m_faces[i].vertexIndex[j] = v; - } - m_vertexMatIds[v] = faceMatId; - } - } - } - - // Computes m_vertexOldToNew and m_vertexNewToOld by detecting duplicate vertices - void ComputeVertexRemapping() - { - const size_t nVerts = m_positions.size(); - - m_vertexNewToOld.resize(nVerts); - for (size_t i = 0; i < nVerts; ++i) - { - m_vertexNewToOld[i] = i; - } - - VertexLess less(*this); - std::sort(m_vertexNewToOld.begin(), m_vertexNewToOld.end(), less); - - m_vertexOldToNew.resize(nVerts); - - int nVertsNew = 0; - for (size_t i = 0; i < nVerts; ++i) - { - if (i == 0 || less(m_vertexNewToOld[i - 1], m_vertexNewToOld[i])) - { - m_vertexNewToOld[nVertsNew++] = m_vertexNewToOld[i]; - } - m_vertexOldToNew[m_vertexNewToOld[i]] = nVertsNew - 1; - } - m_vertexNewToOld.resize(nVertsNew); - } - - // Changes order of vertices, number of vertices, vertex indices in faces - void RemoveVerticesByUsingComputedRemapping() - { - CompactVertices(m_positions, m_vertexNewToOld); - CompactVertices(m_topologyIds, m_vertexNewToOld); - CompactVertices(m_normals, m_vertexNewToOld); - for (uint streamIndex = 0; streamIndex < m_texCoords.size(); ++streamIndex) - { - CompactVertices(m_texCoords[streamIndex], m_vertexNewToOld); - } - CompactVertices(m_colors, m_vertexNewToOld); - CompactVertices(m_alphas, m_vertexNewToOld); - CompactVertices(m_links, m_vertexNewToOld); - CompactVertices(m_vertexMatIds, m_vertexNewToOld); - CompactVerticesRaw(m_aux, m_auxSizeof, m_vertexNewToOld); - - for (size_t i = 0, count = m_faces.size(); i < count; ++i) - { - for (int j = 0; j < 3; ++j) - { - const int oldVertedIdx = m_faces[i].vertexIndex[j]; - assert(oldVertedIdx >= 0 && (size_t)oldVertedIdx < m_vertexOldToNew.size()); - const int newVertexIndex = m_vertexOldToNew[oldVertedIdx]; - m_faces[i].vertexIndex[j] = newVertexIndex; - } - } - } - - // Deleting degraded faces (faces with two or more vertices - // sharing same position in space) - void RemoveDegradedFaces() - { - size_t j = 0; - - for (size_t i = 0, count = m_faces.size(); i < count; ++i) - { - const Vec3& p0 = m_positions[m_faces[i].vertexIndex[0]]; - const Vec3& p1 = m_positions[m_faces[i].vertexIndex[1]]; - const Vec3& p2 = m_positions[m_faces[i].vertexIndex[2]]; - if (p0 != p1 && p1 != p2 && p2 != p0) - { - m_faces[j] = m_faces[i]; - if (!m_faceMatIds.empty()) - { - m_faceMatIds[j] = m_faceMatIds[i]; - } - ++j; - } - } - - m_faces.resize(j); - if (!m_faceMatIds.empty()) - { - m_faceMatIds.resize(j); - } - } - - private: - ////////////////////////////////////////////////////////////////////////// - // Internal helpers - - template - static void CompactVertices(std::vector& arr, const std::vector& newToOld) - { - if (arr.empty()) - { - return; - } - - const size_t newCount = newToOld.size(); - - std::vector tmp; - tmp.reserve(newCount); - - for (size_t i = 0; i < newCount; ++i) - { - tmp.push_back(arr[newToOld[i]]); - } - - arr.swap(tmp); - } - - static void CompactVerticesRaw(std::vector& arr, size_t elemSizeof, const std::vector& newToOld) - { - if (arr.empty()) - { - return; - } - - const size_t newCount = newToOld.size(); - - std::vector tmp; - tmp.resize(newCount * elemSizeof); - - for (size_t i = 0; i < newCount; ++i) - { - memcpy(&tmp[i * elemSizeof], &arr[newToOld[i] * elemSizeof], elemSizeof); - } - - arr.swap(tmp); - } - - struct VertexLess - { - const Mesh& m; - - VertexLess(const Mesh& mesh) - : m(mesh) - { - } - - bool operator()(int a, int b) const - { - if (!m.m_topologyIds.empty()) - { - const int res = m.m_topologyIds[a] - m.m_topologyIds[b]; - if (res != 0) - { - return res < 0; - } - } - - { - const int res = memcmp(&m.m_positions[a], &m.m_positions[b], sizeof(m.m_positions[0])); - if (res != 0) - { - return res < 0; - } - } - - int res = 0; - - if (res == 0 && !m.m_normals.empty()) - { - res = memcmp(&m.m_normals[a], &m.m_normals[b], sizeof(m.m_normals[0])); - } - - for (uint streamIndex = 0; streamIndex < m.m_texCoords.size(); ++streamIndex) - { - if (res == 0 && !m.m_texCoords[streamIndex].empty()) - { - res = memcmp(&m.m_texCoords[streamIndex][a], &m.m_texCoords[streamIndex][b], sizeof(m.m_texCoords[streamIndex][0])); - } - } - - if (res == 0 && !m.m_colors.empty()) - { - res = memcmp(&m.m_colors[a], &m.m_colors[b], sizeof(m.m_colors[0])); - } - - if (res == 0 && !m.m_alphas.empty()) - { - res = (int)m.m_alphas[a] - (int)m.m_alphas[b]; - } - - if (res == 0 && !m.m_links.empty()) - { - if (m.m_links[a].links.size() != m.m_links[b].links.size()) - { - res = (m.m_links[a].links.size() < m.m_links[b].links.size()) ? -1 : +1; - } - else - { - res = memcmp(&m.m_links[a].links[0], &m.m_links[b].links[0], sizeof(m.m_links[a].links[0]) * m.m_links[a].links.size()); - } - } - - if (res == 0 && !m.m_vertexMatIds.empty()) - { - res = m.m_vertexMatIds[a] - m.m_vertexMatIds[b]; - } - - if (res == 0 && !m.m_aux.empty()) - { - res = memcmp(&m.m_aux[a * m.m_auxSizeof], &m.m_aux[b * m.m_auxSizeof], m.m_auxSizeof); - } - - return res < 0; - } - }; - }; -} // namespace MeshUtils - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MESHUTILS_H diff --git a/Code/Tools/CryCommonTools/Export/ModelData.cpp b/Code/Tools/CryCommonTools/Export/ModelData.cpp deleted file mode 100644 index 5a6baf170c..0000000000 --- a/Code/Tools/CryCommonTools/Export/ModelData.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ModelData.h" - -int ModelData::AddModel(const void* handle, const char* modelName, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString) -{ - int modelIndex = int(m_models.size()); - m_models.push_back(ModelEntry(handle, modelName, parentModelIndex, geometry, helperData, propertiesString)); - if (parentModelIndex >= 0) - { - m_models[parentModelIndex].children.push_back(modelIndex); - } - else - { - m_roots.push_back(modelIndex); - } - return modelIndex; -} - -const void* ModelData::GetModelHandle(int modelIndex) const -{ - return m_models[modelIndex].handle; -} - -const char* ModelData::GetModelName(int modelIndex) const -{ - return m_models[modelIndex].name.c_str(); -} - -void ModelData::SetTranslationRotationScale(int const modelIndex, const float* const translation, const float* const rotation, const float* const scale) -{ - for (int i = 0; i < 3; ++i) - { - m_models[modelIndex].translation[i] = translation[i]; - m_models[modelIndex].rotation[i] = rotation[i]; - m_models[modelIndex].scale[i] = scale[i]; - } -} - -void ModelData::GetTranslationRotationScale(int const modelIndex, float* const translation, float* const rotation, float* const scale) const -{ - for (int i = 0; i < 3; ++i) - { - translation[i] = m_models[modelIndex].translation[i]; - rotation[i] = m_models[modelIndex].rotation[i]; - scale[i] = m_models[modelIndex].scale[i]; - } -} - -const SHelperData& ModelData::GetHelperData(int modelIndex) const -{ - return m_models[modelIndex].helperData; -} - -const std::string& ModelData::GetProperties(int modelIndex) const -{ - return m_models[modelIndex].propertiesString; -} - -bool ModelData::IsRoot(int modelIndex) const -{ - return (m_models[modelIndex].parentIndex < 0); -} - -int ModelData::GetModelCount() const -{ - return int(m_models.size()); -} - -int ModelData::GetRootCount() const -{ - return int(m_roots.size()); -} - -int ModelData::GetRootIndex(int rootIndex) const -{ - return m_roots[rootIndex]; -} - -int ModelData::GetChildCount(int modelIndex) const -{ - return int(m_models[modelIndex].children.size()); -} - -int ModelData::GetChildIndex(int modelIndex, int childIndexIndex) const -{ - return m_models[modelIndex].children[childIndexIndex]; -} - -bool ModelData::HasGeometry(int modelIndex) const -{ - return m_models[modelIndex].geometry; -} - -ModelData::ModelEntry::ModelEntry(const void* a_handle, const std::string& a_name, int a_parentIndex, bool a_geometry, const SHelperData& a_helperData, const std::string& a_propertiesString) - : handle(a_handle) - , name(a_name) - , parentIndex(a_parentIndex) - , geometry(a_geometry) - , helperData(a_helperData) - , propertiesString(a_propertiesString) -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} diff --git a/Code/Tools/CryCommonTools/Export/ModelData.h b/Code/Tools/CryCommonTools/Export/ModelData.h deleted file mode 100644 index f6dcb1a921..0000000000 --- a/Code/Tools/CryCommonTools/Export/ModelData.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H -#pragma once - - -#include "IModelData.h" - -class ModelData - : public IModelData -{ -public: - // IModelData - virtual int AddModel(const void* handle, const char* name, int parentModelIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString); - virtual int GetModelCount() const; - virtual const void* GetModelHandle(int modelIndex) const; - virtual const char* GetModelName(int modelIndex) const; - virtual void SetTranslationRotationScale(int modelIndex, const float* translation, const float* rotation, const float* scale); - virtual void GetTranslationRotationScale(int modelIndex, float* translation, float* rotation, float* scale) const; - virtual const SHelperData& GetHelperData(int modelIndex) const; - virtual const std::string& GetProperties(int modelIndex) const; - virtual bool IsRoot(int modelIndex) const; - - int GetRootCount() const; - int GetRootIndex(int rootIndex) const; - int GetChildCount(int modelIndex) const; - int GetChildIndex(int modelIndex, int childIndexIndex) const; - bool HasGeometry(int modelIndex) const; - -private: - struct ModelEntry - { - ModelEntry(const void* handle, const std::string& name, int parentIndex, bool geometry, const SHelperData& helperData, const std::string& propertiesString); - - const void* handle; - std::string name; - int parentIndex; - bool geometry; - std::vector children; - float translation[3]; - float rotation[3]; - float scale[3]; - SHelperData helperData; - std::string propertiesString; - }; - - std::vector m_models; - std::vector m_roots; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MODELDATA_H diff --git a/Code/Tools/CryCommonTools/Export/MorphData.cpp b/Code/Tools/CryCommonTools/Export/MorphData.cpp deleted file mode 100644 index feadb87a33..0000000000 --- a/Code/Tools/CryCommonTools/Export/MorphData.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "MorphData.h" - -MorphData::MorphData() - : m_handle(0) -{ -} - -void MorphData::SetHandle(const void* handle) -{ - m_handle = handle; -} - -void MorphData::AddMorph(const void* handle, const char* name, const char* fullname) -{ - m_morphs.push_back(Entry(handle, name, fullname ? fullname : "")); -} - -const void* MorphData::GetHandle() const -{ - return m_handle; -} - -int MorphData::GetMorphCount() const -{ - return int(m_morphs.size()); -} - -std::string MorphData::GetMorphName(int morphIndex) const -{ - return m_morphs[morphIndex].name; -} - -std::string MorphData::GetMorphFullName(int morphIndex) const -{ - return m_morphs[morphIndex].fullname.length() > 0 ? m_morphs[morphIndex].fullname : m_morphs[morphIndex].name; -} - -const void* MorphData::GetMorphHandle(int morphIndex) const -{ - return m_morphs[morphIndex].handle; -} diff --git a/Code/Tools/CryCommonTools/Export/MorphData.h b/Code/Tools/CryCommonTools/Export/MorphData.h deleted file mode 100644 index c9c942905a..0000000000 --- a/Code/Tools/CryCommonTools/Export/MorphData.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H -#pragma once - - -#include "IMorphData.h" - -class MorphData - : public IMorphData -{ -public: - MorphData(); - - virtual void SetHandle(const void* handle); - virtual void AddMorph(const void* handle, const char* name, const char* fullname); - virtual const void* GetHandle() const; - virtual int GetMorphCount() const; - virtual const void* GetMorphHandle(int morphIndex) const; - - std::string GetMorphName(int morphIndex) const; - std::string GetMorphFullName(int morphIndex) const; - -private: - struct Entry - { - Entry(const void* handle, const std::string& name, const std::string& fullname) - : handle(handle) - , name(name) - , fullname(fullname) {} - const void* handle; - std::string name; - std::string fullname; - }; - - const void* m_handle; - std::vector m_morphs; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_MORPHDATA_H diff --git a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp b/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp deleted file mode 100644 index be924eedf3..0000000000 --- a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "SingleAnimationExportSourceAdapter.h" -#include "IGeometryFileData.h" -#include - -SingleAnimationExportSourceAdapter::SingleAnimationExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) - : ExportSourceDecoratorBase(source) - , animationIndex(animationIndex) - , geometryFileData(geometryFileData) - , geometryFileIndex(geometryFileIndex) -{ - assert(this->animationIndex < this->source->GetAnimationCount()); -} - -float SingleAnimationExportSourceAdapter::GetDCCFrameRate() const -{ - return this->source->GetDCCFrameRate(); -} - -void SingleAnimationExportSourceAdapter::ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData) -{ - const int geometryFileIndex = geometryFileData->AddGeometryFile( - this->geometryFileData->GetGeometryFileHandle(this->geometryFileIndex), - this->geometryFileData->GetGeometryFileName(this->geometryFileIndex), - this->geometryFileData->GetProperties(this->geometryFileIndex)); -} - -void SingleAnimationExportSourceAdapter::ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData) -{ - assert(geometryFileIndex == 0); - this->source->ReadModels(this->geometryFileData, this->geometryFileIndex, modelData); -} - -void SingleAnimationExportSourceAdapter::ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* const modelData, int modelIndex, ISkeletonData* skeletonData) -{ - this->source->ReadSkinning(context, skinningData, modelData, modelIndex, skeletonData); -} - -bool SingleAnimationExportSourceAdapter::ReadSkeleton(const IGeometryFileData* const geometryFileData, int geometryFileIndex, const IModelData* const modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData) -{ - assert(geometryFileIndex == 0); - return this->source->ReadSkeleton(this->geometryFileData, this->geometryFileIndex, modelData, modelIndex, materialData, skeletonData); -} - -int SingleAnimationExportSourceAdapter::GetAnimationCount() const -{ - return 1; -} - -std::string SingleAnimationExportSourceAdapter::GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const -{ - assert(geometryFileIndex == 0); - assert(animationIndex == 0); - return this->source->GetAnimationName(this->geometryFileData, this->geometryFileIndex, this->animationIndex); -} - -void SingleAnimationExportSourceAdapter::GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const -{ - assert(animationIndex == 0); - this->source->GetAnimationTimeSpan(start, stop, this->animationIndex); -} - -void SingleAnimationExportSourceAdapter::ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const -{ - assert(animationIndex == 0); - this->source->ReadAnimationFlags(context, animationData, geometryFileData, modelData, modelIndex, skeletonData, this->animationIndex); -} - -IAnimationData* SingleAnimationExportSourceAdapter::ReadAnimation(IExportContext* context, const IGeometryFileData* const geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const -{ - assert(animationIndex == 0); - return this->source->ReadAnimation(context, geometryFileData, modelData, modelIndex, skeletonData, this->animationIndex, fps); -} diff --git a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h b/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h deleted file mode 100644 index 13da9b47a0..0000000000 --- a/Code/Tools/CryCommonTools/Export/SingleAnimationExportSourceAdapter.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H -#pragma once - - -#include "ExportSourceDecoratorBase.h" - -class SingleAnimationExportSourceAdapter - : public ExportSourceDecoratorBase -{ -public: - SingleAnimationExportSourceAdapter(IExportSource* source, IGeometryFileData* geometryData, int geometryFileIndex, int animationIndex); - - virtual float GetDCCFrameRate() const; - - virtual void ReadGeometryFiles(IExportContext* context, IGeometryFileData* geometryFileData); - virtual void ReadModels(const IGeometryFileData* geometryFileData, int geometryFileIndex, IModelData* modelData); - virtual void ReadSkinning(IExportContext* context, ISkinningData* skinningData, const IModelData* modelData, int modelIndex, ISkeletonData* skeletonData); - virtual bool ReadSkeleton(const IGeometryFileData* geometryFileData, int geometryFileIndex, const IModelData* modelData, int modelIndex, const IMaterialData* materialData, ISkeletonData* skeletonData); - virtual int GetAnimationCount() const; - virtual std::string GetAnimationName(const IGeometryFileData* geometryFileData, int geometryFileIndex, int animationIndex) const; - virtual void GetAnimationTimeSpan(float& start, float& stop, int animationIndex) const; - virtual void ReadAnimationFlags(IExportContext* context, IAnimationData* animationData, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex) const; - virtual IAnimationData* ReadAnimation(IExportContext* context, const IGeometryFileData* geometryFileData, const IModelData* modelData, int modelIndex, const ISkeletonData* skeletonData, int animationIndex, float fps) const; - -private: - int animationIndex; - IGeometryFileData* geometryFileData; - int geometryFileIndex; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SINGLEANIMATIONEXPORTSOURCEADAPTER_H diff --git a/Code/Tools/CryCommonTools/Export/SkeletonData.cpp b/Code/Tools/CryCommonTools/Export/SkeletonData.cpp deleted file mode 100644 index 13d38678b2..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkeletonData.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "SkeletonData.h" -#include - -int SkeletonData::AddBone(const void* handle, const char* name, int parentIndex) -{ - int modelIndex = int(m_bones.size()); - m_bones.push_back(BoneEntry(handle, name, parentIndex)); - m_nameBoneIndexMap.insert(std::make_pair(name, modelIndex)); - if (parentIndex >= 0) - { - m_bones[parentIndex].children.push_back(modelIndex); - } - else - { - m_roots.push_back(modelIndex); - } - return modelIndex; -} - -int SkeletonData::FindBone(const char* name) const -{ - std::map::const_iterator modelPos = m_nameBoneIndexMap.find(name); - return (modelPos != m_nameBoneIndexMap.end() ? (*modelPos).second : -1); -} - -const void* SkeletonData::GetBoneHandle(int boneIndex) const -{ - return m_bones[boneIndex].handle; -} - -int SkeletonData::GetBoneParentIndex(int boneIndex) const -{ - return m_bones[boneIndex].parentIndex; -} - -int SkeletonData::GetBoneCount() const -{ - return int(m_bones.size()); -} - -void SkeletonData::SetTranslation(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].translation[i] = vec[i]; - } -} - -void SkeletonData::SetRotation(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].rotation[i] = vec[i]; - } -} - -void SkeletonData::SetScale(int modelIndex, const float* vec) -{ - for (int i = 0; i < 3; ++i) - { - m_bones[modelIndex].scale[i] = vec[i]; - } -} - -void SkeletonData::SetParentFrameTranslation(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameTranslation); -} - -void SkeletonData::SetParentFrameRotation(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameRotation); -} - -void SkeletonData::SetParentFrameScale(int boneIndex, const float* vec) -{ - EnsureParentFrameExists(boneIndex); - std::copy(vec, vec + 3, m_bones[boneIndex].parentFrameScale); -} - -void SkeletonData::SetLimit(int boneIndex, Axis axis, Limit extreme, float limit) -{ - m_bones[boneIndex].limits.insert(std::make_pair(AxisLimit(axis, extreme), limit)); -} - -void SkeletonData::SetSpringTension(int boneIndex, Axis axis, float springTension) -{ - m_bones[boneIndex].springTensions.insert(std::make_pair(axis, springTension)); -} - -void SkeletonData::SetSpringAngle(int boneIndex, Axis axis, float springAngle) -{ - m_bones[boneIndex].springAngles.insert(std::make_pair(axis, springAngle)); -} - -void SkeletonData::SetAxisDamping(int boneIndex, Axis axis, float damping) -{ - m_bones[boneIndex].dampings.insert(std::make_pair(axis, damping)); -} - -void SkeletonData::SetPhysicalized(int boneIndex, bool physicalized) -{ - m_bones[boneIndex].physicalized = physicalized; -} - -void SkeletonData::SetHasGeometry(int boneIndex, bool hasGeometry) -{ - m_bones[boneIndex].hasGeometry = hasGeometry; -} - -void SkeletonData::SetBoneProperties(int boneIndex, const char* propertiesString) -{ - m_bones[boneIndex].propertiesString = propertiesString; -} - -void SkeletonData::SetBoneGeomProperties(int boneIndex, const char* propertiesString) -{ - m_bones[boneIndex].geomPropertiesString = propertiesString; -} - -bool SkeletonData::HasParentFrame(int boneIndex) const -{ - return m_bones[boneIndex].hasParentFrame; -} - -void SkeletonData::GetParentFrameTranslation(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameTranslation, m_bones[boneIndex].parentFrameTranslation + 3, vec); -} - -void SkeletonData::GetParentFrameRotation(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameRotation, m_bones[boneIndex].parentFrameRotation + 3, vec); -} - -void SkeletonData::GetParentFrameScale(int boneIndex, float* vec) const -{ - std::copy(m_bones[boneIndex].parentFrameScale, m_bones[boneIndex].parentFrameScale + 3, vec); -} - -bool SkeletonData::HasLimit(int boneIndex, Axis axis, Limit extreme) const -{ - return m_bones[boneIndex].limits.find(AxisLimit(axis, extreme)) != m_bones[boneIndex].limits.end(); -} - -float SkeletonData::GetLimit(int boneIndex, Axis axis, Limit extreme) const -{ - return (*m_bones[boneIndex].limits.find(AxisLimit(axis, extreme))).second; -} - -bool SkeletonData::HasSpringTension(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].springTensions.find(axis) != m_bones[boneIndex].springTensions.end(); -} - -float SkeletonData::GetSpringTension(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].springTensions.find(axis)).second; -} - -bool SkeletonData::HasSpringAngle(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].springAngles.find(axis) != m_bones[boneIndex].springAngles.end(); -} - -float SkeletonData::GetSpringAngle(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].springAngles.find(axis)).second; -} - -bool SkeletonData::HasAxisDamping(int boneIndex, Axis axis) const -{ - return m_bones[boneIndex].dampings.find(axis) != m_bones[boneIndex].dampings.end(); -} - -float SkeletonData::GetAxisDamping(int boneIndex, Axis axis) const -{ - return (*m_bones[boneIndex].dampings.find(axis)).second; -} - -bool SkeletonData::GetPhysicalized(int boneIndex) const -{ - return m_bones[boneIndex].physicalized; -} - -bool SkeletonData::HasGeometry(int boneIndex) const -{ - return m_bones[boneIndex].hasGeometry; -} - -int SkeletonData::GetRootCount() const -{ - return int(m_roots.size()); -} - -int SkeletonData::GetRootIndex(int rootIndex) const -{ - return m_roots[rootIndex]; -} - -int SkeletonData::GetParentIndex(int modelIndex) const -{ - return m_bones[modelIndex].parentIndex; -} - -const std::string SkeletonData::GetName(int modelIndex) const -{ - std::string copy(m_bones[modelIndex].name); - for (int i = 0, count = int(copy.size()); i < count; ++i) - { - if (!std::isalnum(copy[i]) && copy[i] != ' ') - { - copy[i] = '_'; - } - } - return copy; -} - - -const std::string SkeletonData::GetSafeName(int modelIndex) const -{ - std::string name = GetName(modelIndex); - std::replace_if(name.begin(), name.end(), std::isspace, '_'); - return name; -} - -int SkeletonData::GetChildCount(int modelIndex) const -{ - return int(m_bones[modelIndex].children.size()); -} - -int SkeletonData::GetChildIndex(int modelIndex, int childIndexIndex) const -{ - return m_bones[modelIndex].children[childIndexIndex]; -} - -void SkeletonData::GetTranslation(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].translation[i]; - } -} - -void SkeletonData::GetRotation(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].rotation[i]; - } -} - -void SkeletonData::GetScale(float* vec, int modelIndex) const -{ - for (int i = 0; i < 3; ++i) - { - vec[i] = m_bones[modelIndex].scale[i]; - } -} - -const std::string SkeletonData::GetBoneProperties(int boneIndex) const -{ - return m_bones[boneIndex].propertiesString; -} - -const std::string SkeletonData::GetBoneGeomProperties(int boneIndex) const -{ - return m_bones[boneIndex].geomPropertiesString; -} - -void SkeletonData::EnsureParentFrameExists(int boneIndex) -{ - if (!m_bones[boneIndex].hasParentFrame) - { - std::fill(m_bones[boneIndex].parentFrameTranslation, m_bones[boneIndex].parentFrameTranslation + 3, 0.0f); - std::fill(m_bones[boneIndex].parentFrameRotation, m_bones[boneIndex].parentFrameRotation + 3, 0.0f); - std::fill(m_bones[boneIndex].parentFrameScale, m_bones[boneIndex].parentFrameScale + 3, 0.0f); - m_bones[boneIndex].hasParentFrame = true; - } -} - -SkeletonData::BoneEntry::BoneEntry(const void* handle, const std::string& name, int parentIndex) - : handle(handle) - , name(name) - , parentIndex(parentIndex) - , hasParentFrame(false) - , physicalized(false) - , hasGeometry(hasGeometry) -{ - translation[0] = translation[1] = translation[2] = 0.0f; - rotation[0] = rotation[1] = rotation[2] = 0.0f; - scale[0] = scale[1] = scale[2] = 1.0f; -} diff --git a/Code/Tools/CryCommonTools/Export/SkeletonData.h b/Code/Tools/CryCommonTools/Export/SkeletonData.h deleted file mode 100644 index 60bd8274b7..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkeletonData.h +++ /dev/null @@ -1,116 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H -#pragma once - - -#include "ISkeletonData.h" -#include -#include -#include - -class SkeletonData - : public ISkeletonData -{ -public: - // ISkeletonData - virtual int AddBone(const void* handle, const char* name, int parentIndex); - virtual int FindBone(const char* name) const; - virtual const void* GetBoneHandle(int boneIndex) const; - virtual int GetBoneParentIndex(int boneIndex) const; - virtual int GetBoneCount() const; - virtual void SetTranslation(int boneIndex, const float* vec); - virtual void SetRotation(int boneIndex, const float* vec); - virtual void SetScale(int boneIndex, const float* vec); - virtual void SetParentFrameTranslation(int boneIndex, const float* vec); - virtual void SetParentFrameRotation(int boneIndex, const float* vec); - virtual void SetParentFrameScale(int boneIndex, const float* vec); - virtual void SetLimit(int boneIndex, Axis axis, Limit extreme, float limit); - virtual void SetSpringTension(int boneIndex, Axis axis, float springTension); - virtual void SetSpringAngle(int boneIndex, Axis axis, float springAngle); - virtual void SetAxisDamping(int boneIndex, Axis axis, float damping); - virtual void SetPhysicalized(int boneIndex, bool physicalized); - virtual void SetHasGeometry(int boneIndex, bool hasGeometry); - virtual void SetBoneProperties(int boneIndex, const char* propertiesString); - virtual void SetBoneGeomProperties(int boneIndex, const char* propertiesString); - - bool HasParentFrame(int boneIndex) const; - void GetParentFrameTranslation(int boneIndex, float* vec) const; - void GetParentFrameRotation(int boneIndex, float* vec) const; - void GetParentFrameScale(int boneIndex, float* vec) const; - bool HasLimit(int boneIndex, Axis axis, Limit extreme) const; - float GetLimit(int boneIndex, Axis axis, Limit extreme) const; - bool HasSpringTension(int boneIndex, Axis axis) const; - float GetSpringTension(int boneIndex, Axis axis) const; - bool HasSpringAngle(int boneIndex, Axis axis) const; - float GetSpringAngle(int boneIndex, Axis axis) const; - bool HasAxisDamping(int boneIndex, Axis axis) const; - float GetAxisDamping(int boneIndex, Axis axis) const; - bool GetPhysicalized(int boneIndex) const; - bool HasGeometry(int boneIndex) const; - - int GetRootCount() const; - int GetRootIndex(int rootIndex) const; - int GetParentIndex(int boneIndex) const; - const std::string GetName(int boneIndex) const; - const std::string GetSafeName(int boneIndex) const; - int GetChildCount(int boneIndex) const; - int GetChildIndex(int boneIndex, int childIndexIndex) const; - void GetTranslation(float* vec, int boneIndex) const; - void GetRotation(float* vec, int boneIndex) const; - void GetScale(float* vec, int boneIndex) const; - const std::string GetBoneProperties(int boneIndex) const; - const std::string GetBoneGeomProperties(int boneIndex) const; - -private: - void EnsureParentFrameExists(int boneIndex); - - typedef std::pair AxisLimit; - typedef std::map AxisLimitLimitMap; - typedef std::map AxisSpringTensionMap; - typedef std::map AxisSpringAngleMap; - typedef std::map AxisDampingMap; - - struct BoneEntry - { - public: - BoneEntry(const void* handle, const std::string& name, int parentIndex); - const void* handle; - std::string name; - int parentIndex; - AxisLimitLimitMap limits; - AxisSpringTensionMap springTensions; - AxisSpringAngleMap springAngles; - AxisDampingMap dampings; - bool hasParentFrame; - float parentFrameTranslation[3]; - float parentFrameRotation[3]; - float parentFrameScale[3]; - bool physicalized; - std::vector children; - float translation[3]; - float rotation[3]; - float scale[3]; - bool hasGeometry; - std::string propertiesString; - std::string geomPropertiesString; - }; - - std::vector m_bones; - std::vector m_roots; - std::map m_nameBoneIndexMap; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKELETONDATA_H diff --git a/Code/Tools/CryCommonTools/Export/SkinningData.cpp b/Code/Tools/CryCommonTools/Export/SkinningData.cpp deleted file mode 100644 index eeef150cad..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkinningData.cpp +++ /dev/null @@ -1,45 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "SkinningData.h" - -void SkinningData::SetVertexCount(int vertexCount) -{ - m_weights.resize(vertexCount); -} - -void SkinningData::AddWeight(int vertexIndex, int boneIndex, float weight) -{ - m_weights[vertexIndex].push_back(BoneWeight(boneIndex, weight)); -} - -int SkinningData::GetVertexCount() const -{ - return int(m_weights.size()); -} - -int SkinningData::GetBoneLinkCount(int vertexIndex) const -{ - return int(m_weights[vertexIndex].size()); -} - -int SkinningData::GetBoneIndex(int vertexIndex, int linkIndex) const -{ - return m_weights[vertexIndex][linkIndex].boneIndex; -} - -float SkinningData::GetWeight(int vertexIndex, int linkIndex) const -{ - return m_weights[vertexIndex][linkIndex].weight; -} diff --git a/Code/Tools/CryCommonTools/Export/SkinningData.h b/Code/Tools/CryCommonTools/Export/SkinningData.h deleted file mode 100644 index 6e3a9a6712..0000000000 --- a/Code/Tools/CryCommonTools/Export/SkinningData.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H -#pragma once - - -#include "ISkinningData.h" - -class SkinningData - : public ISkinningData -{ -public: - virtual void SetVertexCount(int vertexCount); - virtual void AddWeight(int vertexIndex, int boneIndex, float weight); - - int GetVertexCount() const; - int GetBoneLinkCount(int vertexIndex) const; - int GetBoneIndex(int vertexIndex, int linkIndex) const; - float GetWeight(int vertexIndex, int linkIndex) const; - -private: - struct BoneWeight - { - BoneWeight(int boneIndex, float weight) - : boneIndex(boneIndex) - , weight(weight) {} - int boneIndex; - float weight; - }; - - std::vector > m_weights; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_SKINNINGDATA_H diff --git a/Code/Tools/CryCommonTools/Export/TransformHelpers.h b/Code/Tools/CryCommonTools/Export/TransformHelpers.h deleted file mode 100644 index cdddd78337..0000000000 --- a/Code/Tools/CryCommonTools/Export/TransformHelpers.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H -#pragma once - - -#include "Cry_Math.h" - - -namespace TransformHelpers -{ - // Format of forwardUpAxes: "". - // Example of forwardUpAxes: "-Y+Z". - // Returns 0 if successful, or returns a pointer to an error message in case of an error. - // In case of success: X axis in res represents "forward" direction, - // Y axis represents "up" direction. - inline const char* GetForwardUpAxesMatrix(Matrix33& res, const char* forwardUpAxes) - { - Vec3 axisX(ZERO); - Vec3 axisY(ZERO); - - for (int i = 0; i < 2; ++i) - { - Vec3& v = (i == 0) ? axisX : axisY; - - const float val = forwardUpAxes[i * 2 + 0] == '-' ? -1.0f : +1.0f; - - switch (forwardUpAxes[i * 2 + 1]) - { - case 'X': - case 'x': - v.x = val; - break; - case 'Y': - case 'y': - v.y = val; - break; - case 'Z': - case 'z': - v.z = val; - break; - default: - assert(0); - return "Found a bad axis character in forwardUpAxes string"; - } - } - - if (axisX == axisY) - { - assert(0); - return "Forward and up axes are equal in forwardUpAxes string"; - } - - const Vec3 axisZ = axisX.cross(axisY); - - res.SetFromVectors(axisX, axisY, axisZ); - - return 0; - } - - - // Computes transform matrix that converts everything from forwardUpAxesSrc - // coordinate system to forwardUpAxesDst coordinate system. - // Format of forwardUpAxesXXX: "". - // Example of forwardUpAxesXXX: "-Y+Z". - // Returns 0 if successful, or returns a pointer to an error message in case of an error. - // In case of success puts computed transform into res. - // See comments to GetForwardUpAxesMatrix(). - inline const char* ComputeForwardUpAxesTransform(Matrix34& res, const char* forwardUpAxesSrc, const char* forwardUpAxesDst) - { - Matrix33 srcToWorld; - Matrix33 dstToWorld; - - const char* const err0 = GetForwardUpAxesMatrix(srcToWorld, forwardUpAxesSrc); - const char* const err1 = GetForwardUpAxesMatrix(dstToWorld, forwardUpAxesDst); - - if (err0 || err1) - { - return err0 ? err0 : err1; - } - - res = Matrix34(dstToWorld * srcToWorld.GetTransposed()); - - return 0; - } - - - inline Matrix34 ComputeOrthonormalMatrix(const Matrix34& m) - { - Vec3 x = m.GetColumn0(); - x.Normalize(); - - Vec3 y = m.GetColumn1(); - - Vec3 z = x.cross(y); - z.Normalize(); - - y = z.cross(x); - - Matrix34 result; - result.SetFromVectors(x, y, z, m.GetTranslation()); - - return result; - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXPORT_TRANSFORMHELPERS_H diff --git a/Code/Tools/CryCommonTools/UI/EULADialog.cpp b/Code/Tools/CryCommonTools/UI/EULADialog.cpp deleted file mode 100644 index a4b8696eea..0000000000 --- a/Code/Tools/CryCommonTools/UI/EULADialog.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "EULADialog.h" -#include "Win32GUI.h" -#include "ModuleHelpers.h" -#include "Richedit.h" -#include - -EULADialog::EULADialog() - : m_frameWindow() - , m_cancelButton(_T("Cancel"), this, &EULADialog::CancelPressed) - , m_buttonSpacer(0, 0, 2000, 0) - , m_acceptButton(_T("Accept"), this, &EULADialog::AcceptPressed) - , m_buttonLayout(Layout::DirectionHorizontal) - , m_edit() -{ - Win32GUI::Initialize(); - - m_buttonLayout.AddComponent(&m_buttonSpacer); - m_buttonLayout.AddComponent(&m_cancelButton); - m_buttonLayout.AddComponent(&m_acceptButton); - - m_frameWindow.AddComponent(&m_edit); - m_frameWindow.AddComponent(&m_buttonLayout); -} - -namespace -{ - class EditStreamCallbackObject - { - public: - EditStreamCallbackObject(const char* data, int size) - : data(data) - , position(0) - , size(size) {} - static DWORD WINAPI EditStreamCallback(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb) - { - return ((EditStreamCallbackObject*)dwCookie)->EditStreamCallback_Member(dwCookie, pbBuff, cb, pcb); - } - - private: - DWORD EditStreamCallback_Member(DWORD_PTR dwCookie, LPBYTE pbBuff, LONG cb, LONG* pcb) - { - int bytesToRead = (std::min)(this->size - this->position, (int)cb); - std::memcpy(pbBuff, this->data + this->position, bytesToRead); - this->position += bytesToRead; - if (pcb) - { - *pcb = bytesToRead; - } - return 0; - } - - const char* data; - int position; - int size; - }; -} - -EULADialog::UserResponse EULADialog::Run(int width, int height, TCHAR* resourceID) -{ - m_frameWindow.Show(true, width, height); - - // Attempt to load the resource. - HINSTANCE module = ModuleHelpers::GetCurrentModule(ModuleHelpers::CurrentModuleSpecifier_Library); - HRSRC resource = (resourceID ? FindResource(module, resourceID, RT_RCDATA) : 0); - int resourceLength = (resource ? SizeofResource(module, resource) : 0); - HGLOBAL resourceGlobal = (resource ? LoadResource(module, resource) : 0); - void* resourceData = (resourceGlobal ? LockResource(resourceGlobal) : 0); - // No need to unlock/delete data. - - m_userResponse = UserResponseNone; - - // Load the text. - if (resourceData && resourceLength > 0) - { - EditStreamCallbackObject callbackObject((const char*)resourceData, resourceLength); - EDITSTREAM editStream; - std::memset(&editStream, 0, sizeof(editStream)); - editStream.dwCookie = (DWORD_PTR)&callbackObject; - editStream.pfnCallback = &EditStreamCallbackObject::EditStreamCallback; - SendMessage((HWND)m_edit.m_edit, EM_STREAMIN, SF_RTF, (LPARAM)&editStream); - } - - MSG msg; - BOOL status; - bool waitingAcceptance = false; - while (m_userResponse == UserResponseNone && (status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - break; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - m_frameWindow.Show(false, 0, 0); - - return m_userResponse; -} - -void EULADialog::CancelPressed() -{ - m_userResponse = UserResponseCancel; -} - -void EULADialog::AcceptPressed() -{ - m_userResponse = UserResponseAccept; -} - -EULADialog::UserResponse EULADialog::Show(int width, int height, TCHAR* resourceID) -{ - EULADialog dlg; - return dlg.Run(width, height, resourceID); -} diff --git a/Code/Tools/CryCommonTools/UI/EULADialog.h b/Code/Tools/CryCommonTools/UI/EULADialog.h deleted file mode 100644 index 4af9bde758..0000000000 --- a/Code/Tools/CryCommonTools/UI/EULADialog.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_EULADIALOG_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_EULADIALOG_H -#pragma once - - -#include "FrameWindow.h" -#include "EditControl.h" -#include "Spacer.h" -#include "Layout.h" -#include "PushButton.h" - -class EULADialog -{ -public: - enum UserResponse - { - UserResponseNone, - UserResponseCancel, - UserResponseAccept - }; - - static UserResponse Show(int width, int height, TCHAR* resourceID); - -private: - EULADialog(); - - UserResponse Run(int width, int height, TCHAR* resourceID); - - void CancelPressed(); - void AcceptPressed(); - - FrameWindow m_frameWindow; - PushButton m_cancelButton; - Spacer m_buttonSpacer; - PushButton m_acceptButton; - Layout m_buttonLayout; - EditControl m_edit; - - UserResponse m_userResponse; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_EULADIALOG_H diff --git a/Code/Tools/CryCommonTools/UI/EditControl.cpp b/Code/Tools/CryCommonTools/UI/EditControl.cpp deleted file mode 100644 index 61ac51f41d..0000000000 --- a/Code/Tools/CryCommonTools/UI/EditControl.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "EditControl.h" -#include "Win32GUI.h" -#include -#include -#include - -EditControl::EditControl() - : m_edit(0) -{ -} - -void EditControl::CreateUI(void* window, int left, int top, int width, int height) -{ - m_edit = Win32GUI::CreateControl(RICHEDIT_CLASS, ES_MULTILINE /*| ES_READONLY*/, (HWND)window, left, top, width, height); -} - -void EditControl::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_edit, left, top, width, height, true); -} - -void EditControl::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_edit); - m_edit = 0; -} - -void EditControl::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 20; - maxWidth = 2000; - minHeight = 20; - maxHeight = 2000; -} diff --git a/Code/Tools/CryCommonTools/UI/EditControl.h b/Code/Tools/CryCommonTools/UI/EditControl.h deleted file mode 100644 index da00059e94..0000000000 --- a/Code/Tools/CryCommonTools/UI/EditControl.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H -#pragma once - - -#include "IUIComponent.h" - -class EditControl - : public IUIComponent -{ -public: - EditControl(); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - - void* m_edit; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_EDITCONTROL_H diff --git a/Code/Tools/CryCommonTools/UI/FrameWindow.cpp b/Code/Tools/CryCommonTools/UI/FrameWindow.cpp deleted file mode 100644 index feaa7ab293..0000000000 --- a/Code/Tools/CryCommonTools/UI/FrameWindow.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "FrameWindow.h" -#include "Win32GUI.h" -#include "IUIComponent.h" -#include -#include - -FrameWindow::FrameWindow() - : m_hwnd(0) - , m_layout(Layout::DirectionVertical) -{ -} - -FrameWindow::~FrameWindow() -{ - if (m_hwnd) - { - Show(false, 0, 0); - } -} - -void FrameWindow::AddComponent(IUIComponent* component) -{ - assert(m_hwnd == 0); - m_layout.AddComponent(component); -} - -void FrameWindow::Show(bool show, int width, int height) -{ - if (show) - { - assert(m_hwnd == 0); - TCHAR* className = _T("CustomFrameWindowClass212"); - Win32GUI::RegisterFrameClass(className); - m_hwnd = Win32GUI::CreateFrame(className, WS_MINIMIZEBOX | WS_OVERLAPPED | WS_THICKFRAME | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX, width, height); - Win32GUI::SetCallback((HWND)m_hwnd, this, &FrameWindow::CalculateExtremeDimensions); - Win32GUI::SetCallback((HWND)m_hwnd, this, &FrameWindow::OnSizeChanged); - std::pair size = InitializeSize(); - m_layout.CreateUI(m_hwnd, 0, 0, size.first, size.second); - ShowWindow((HWND)m_hwnd, SW_SHOWDEFAULT); - } - else - { - m_layout.DestroyUI(m_hwnd); - assert(m_hwnd != 0); - DestroyWindow((HWND)m_hwnd); - m_hwnd = 0; - } -} - -void FrameWindow::SetCaption(const TCHAR* caption) -{ - SendMessage((HWND)m_hwnd, WM_SETTEXT, 0, (LPARAM)caption); -} - -void* FrameWindow::GetHWND() -{ - return m_hwnd; -} - -std::pair FrameWindow::InitializeSize() -{ - int minW, maxW, minH, maxH; - CalculateExtremeDimensions(minW, maxW, minH, maxH); - RECT rect; - GetWindowRect((HWND)m_hwnd, &rect); - int width = int((std::min)(maxW, (std::max)(minW, int(rect.right - rect.left)))); - int height = int((std::min)(maxH, (std::max)(minH, int(rect.bottom - rect.top)))); - MoveWindow((HWND)m_hwnd, rect.left, rect.top, width, height, false); - return std::make_pair(width, height); -} - -void FrameWindow::CalculateExtremeDimensions(int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - int minW = 0; - int maxW = 0; - int minH = 0; - int maxH = 0; - m_layout.GetExtremeDimensions(m_hwnd, minW, maxW, minH, maxH); - - // Add the space required for the window decorations. - RECT rect; - rect.left = 0, rect.top = 0, rect.right = minW, rect.bottom = minH; - unsigned style = GetWindowLong((HWND)m_hwnd, GWL_STYLE); - AdjustWindowRect(&rect, style, false); - minW = rect.right - rect.left; - minH = rect.bottom - rect.top; - - rect.left = 0, rect.top = 0, rect.right = maxW, rect.bottom = maxH; - AdjustWindowRect(&rect, style, false); - maxW = rect.right - rect.left; - maxH = rect.bottom - rect.top; - - minWidth = minW; - maxWidth = maxW; - minHeight = minH; - maxHeight = maxH; -} - -void FrameWindow::OnSizeChanged(int width, int height) -{ - m_layout.Resize(m_hwnd, 0, 0, width, height); -} diff --git a/Code/Tools/CryCommonTools/UI/FrameWindow.h b/Code/Tools/CryCommonTools/UI/FrameWindow.h deleted file mode 100644 index ff1bba893d..0000000000 --- a/Code/Tools/CryCommonTools/UI/FrameWindow.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H -#pragma once - - -#include -#include "Layout.h" - -class IUIComponent; - -class FrameWindow -{ -public: - FrameWindow(); - ~FrameWindow(); - void AddComponent(IUIComponent* component); - void Show(bool show, int width, int height); - void SetCaption(const TCHAR* caption); - void* GetHWND(); - -private: - void UpdateComponentUI(bool create); - std::pair InitializeSize(); - void CalculateExtremeDimensions(int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - void OnSizeChanged(int width, int height); - - void* m_hwnd; - Layout m_layout; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_FRAMEWINDOW_H diff --git a/Code/Tools/CryCommonTools/UI/IUIComponent.h b/Code/Tools/CryCommonTools/UI/IUIComponent.h deleted file mode 100644 index 08b06c424b..0000000000 --- a/Code/Tools/CryCommonTools/UI/IUIComponent.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H -#pragma once - - -class IUIComponent -{ -public: - virtual void CreateUI(void* window, int left, int top, int width, int height) = 0; - virtual void Resize(void* window, int left, int top, int width, int height) = 0; - virtual void DestroyUI(void* window) = 0; - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_IUICOMPONENT_H diff --git a/Code/Tools/CryCommonTools/UI/Layout.cpp b/Code/Tools/CryCommonTools/UI/Layout.cpp deleted file mode 100644 index 3225544be2..0000000000 --- a/Code/Tools/CryCommonTools/UI/Layout.cpp +++ /dev/null @@ -1,233 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "Layout.h" -#include -#include - -Layout::Layout(Direction direction) - : m_direction(direction) -{ -} - -void Layout::AddComponent(IUIComponent* component) -{ - m_components.push_back(ComponentEntry(component)); -} - -void Layout::CreateUI(void* window, int left, int top, int width, int height) -{ - UpdateLayout(window, left, top, width, height); - - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->CreateUI(window, m_components[componentIndex].left, m_components[componentIndex].top, m_components[componentIndex].width, m_components[componentIndex].height); - } -} - -void Layout::Resize(void* window, int left, int top, int width, int height) -{ - UpdateLayout(window, left, top, width, height); - - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->Resize(window, m_components[componentIndex].left, m_components[componentIndex].top, m_components[componentIndex].width, m_components[componentIndex].height); - } -} - -void Layout::DestroyUI(void* window) -{ - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - component->DestroyUI(window); - } -} - -void Layout::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - int minW = 0; - int maxW = 0; - int minH = 0; - int maxH = 0; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - switch (m_direction) - { - case DirectionVertical: - minW = (minW > compMinW ? minW : compMinW); - maxW = (maxW > compMaxW ? maxW : compMaxW); // Deliberately take the larger maximum. - minH += compMinH; - maxH += compMaxH; - break; - case DirectionHorizontal: - minW += compMinW; - maxW += compMaxW; - minH = (minH > compMinH ? minH : compMinH); - maxH = (maxH > compMaxH ? maxH : compMaxH); // Deliberately take the larger maximum. - break; - } - } - - // Make sure the window is at least a certain size; - minW = (minW >= 10 ? minW : 10); - maxW = (maxW >= minW ? maxW : minW); - minH = (minH >= 10 ? minH : 10); - maxH = (maxH >= minH ? maxH : minH); - - minWidth = minW; - maxWidth = maxW; - minHeight = minH; - maxHeight = maxH; -} - -void Layout::UpdateLayout(void* window, int left, int top, int width, int height) -{ - assert(window); - - int remainingToAllocate; - switch (m_direction) - { - case DirectionVertical: - remainingToAllocate = height; - break; - case DirectionHorizontal: - remainingToAllocate = width; - break; - } - - int smallestAllocationAmount = INT_MAX; - int canBeExtendedCount = 0; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - - switch (m_direction) - { - case DirectionVertical: - { - int allocationAmount = compMaxH - compMinH; - if (allocationAmount > 0) - { - ++canBeExtendedCount; - smallestAllocationAmount = (smallestAllocationAmount < allocationAmount ? smallestAllocationAmount : allocationAmount); - } - m_components[componentIndex].height = compMinH; - m_components[componentIndex].width = (width > compMaxW ? compMaxW : width); - remainingToAllocate -= m_components[componentIndex].height; - } - break; - - case DirectionHorizontal: - { - int allocationAmount = compMaxW - compMinW; - if (allocationAmount > 0) - { - ++canBeExtendedCount; - smallestAllocationAmount = (smallestAllocationAmount < allocationAmount ? smallestAllocationAmount : allocationAmount); - } - m_components[componentIndex].width = compMinW; - m_components[componentIndex].height = (height > compMaxH ? compMaxH : height); - remainingToAllocate -= m_components[componentIndex].width; - } - break; - } - } - - while (remainingToAllocate > 0 && canBeExtendedCount > 0) - { - int equitablePerCompAllocation = remainingToAllocate / canBeExtendedCount; - int compAllocation = (equitablePerCompAllocation < smallestAllocationAmount ? equitablePerCompAllocation : smallestAllocationAmount); - compAllocation = (compAllocation > 0 ? compAllocation : 1); - canBeExtendedCount = 0; - smallestAllocationAmount = INT_MAX; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - IUIComponent* component = m_components[componentIndex].component; - int compMinW, compMaxW, compMinH, compMaxH; - component->GetExtremeDimensions(window, compMinW, compMaxW, compMinH, compMaxH); - switch (m_direction) - { - case DirectionVertical: - { - int componentExpandAmount = compMaxH - m_components[componentIndex].height; - if (componentExpandAmount > 0) - { - m_components[componentIndex].height += compAllocation; - assert(m_components[componentIndex].height <= compMaxH); - componentExpandAmount -= compAllocation; - remainingToAllocate -= compAllocation; - if (componentExpandAmount > 0) - { - smallestAllocationAmount = (smallestAllocationAmount < componentExpandAmount ? smallestAllocationAmount : componentExpandAmount); - ++canBeExtendedCount; - } - } - } - break; - - case DirectionHorizontal: - { - int componentExpandAmount = compMaxW - m_components[componentIndex].width; - if (componentExpandAmount > 0) - { - m_components[componentIndex].width += compAllocation; - assert(m_components[componentIndex].width <= compMaxW); - componentExpandAmount -= compAllocation; - remainingToAllocate -= compAllocation; - if (componentExpandAmount > 0) - { - smallestAllocationAmount = (smallestAllocationAmount < componentExpandAmount ? smallestAllocationAmount : componentExpandAmount); - ++canBeExtendedCount; - } - } - } - break; - } - } - } - - switch (m_direction) - { - case DirectionVertical: - { - int posY = top; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - m_components[componentIndex].left = left; - m_components[componentIndex].top = posY; - posY += m_components[componentIndex].height; - } - } - break; - case DirectionHorizontal: - { - int posX = left; - for (int componentIndex = 0, componentCount = int(m_components.size()); componentIndex < componentCount; ++componentIndex) - { - m_components[componentIndex].top = top; - m_components[componentIndex].left = posX; - posX += m_components[componentIndex].width; - } - } - break; - } -} diff --git a/Code/Tools/CryCommonTools/UI/Layout.h b/Code/Tools/CryCommonTools/UI/Layout.h deleted file mode 100644 index a2de6c4f69..0000000000 --- a/Code/Tools/CryCommonTools/UI/Layout.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_LAYOUT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LAYOUT_H -#pragma once - - -#include "IUIComponent.h" -#include - -class Layout - : public IUIComponent -{ -public: - enum Direction - { - DirectionHorizontal, - DirectionVertical - }; - Layout(Direction direction); - void AddComponent(IUIComponent* component); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void UpdateLayout(void* window, int left, int top, int width, int height); - - struct ComponentEntry - { - explicit ComponentEntry(IUIComponent* component) - : component(component) - , left(0) - , top(0) - , width(0) - , height(0) {} - IUIComponent* component; - int left; - int top; - int width; - int height; - }; - std::vector m_components; - Direction m_direction; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LAYOUT_H diff --git a/Code/Tools/CryCommonTools/UI/ListView.cpp b/Code/Tools/CryCommonTools/UI/ListView.cpp deleted file mode 100644 index dc43d41fc8..0000000000 --- a/Code/Tools/CryCommonTools/UI/ListView.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ListView.h" -#include "Win32GUI.h" -#include "resource.h" -#include "ModuleHelpers.h" -#include -#include -#include - -ListView::ListView() - : m_list(0) -{ -} - -void ListView::Add(int imageIndex, const TCHAR* message) -{ - int itemCount = int(SendMessage((HWND)m_list, LVM_GETITEMCOUNT, 0, 0)); - - LVITEM item; - std::memset(&item, 0, sizeof(item)); - item.mask = LVIF_TEXT | LVIF_IMAGE; - item.iItem = itemCount; - item.iSubItem = 0; - item.pszText = (TCHAR*)message; - item.iImage = imageIndex; - - SendMessage((HWND)m_list, LVM_INSERTITEM, 0, (LPARAM)&item); -} - -void ListView::Clear() -{ - SendMessage((HWND)m_list, LVM_DELETEALLITEMS, 0, 0); -} - -void ListView::CreateUI(void* window, int left, int top, int width, int height) -{ - m_list = Win32GUI::CreateControl(WC_LISTVIEW, LVS_REPORT | LVS_NOCOLUMNHEADER, (HWND)window, left, top, width, height); - - LVCOLUMN column; - std::memset(&column, 0, sizeof(column)); - column.mask = LVCF_TEXT | LVCF_WIDTH; - column.pszText = _T("Message"); - column.cx = width; - SendMessage((HWND)m_list, LVM_INSERTCOLUMN, 0, (LPARAM)&column); - - HIMAGELIST imageList = (HIMAGELIST)CreateImageList(); - SendMessage((HWND)m_list, LVM_SETIMAGELIST, LVSIL_SMALL, (LPARAM)imageList); -} - -void ListView::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_list, left, top, width, height, true); - SendMessage((HWND)m_list, LVM_SETCOLUMNWIDTH, 0, width); -} - -void ListView::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_list); - m_list = 0; -} - -void ListView::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 20; - maxWidth = 2000; - minHeight = 20; - maxHeight = 2000; -} - -void* ListView::CreateImageList() -{ - HINSTANCE instance = ModuleHelpers::GetCurrentModule(ModuleHelpers::CurrentModuleSpecifier_Library); - - HBITMAP image = (HBITMAP)LoadImage(instance, MAKEINTRESOURCE(IDB_LOG_ICONS), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION); - DIBSECTION dibSection; - GetObject(image, sizeof(dibSection), &dibSection); - int height = dibSection.dsBmih.biHeight; - int width = height; - int count = dibSection.dsBmih.biWidth / width; - HIMAGELIST imageList = ImageList_Create(16, 16, ILC_COLOR32, count, 0); - ImageList_Add(imageList, image, 0); - return imageList; -} diff --git a/Code/Tools/CryCommonTools/UI/ListView.h b/Code/Tools/CryCommonTools/UI/ListView.h deleted file mode 100644 index 60531dd13d..0000000000 --- a/Code/Tools/CryCommonTools/UI/ListView.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H -#pragma once - - -#include "IUIComponent.h" - -class ListView - : public IUIComponent -{ -public: - ListView(); - - void Add(int imageIndex, const TCHAR* message); - void Clear(); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void* CreateImageList(); - - void* m_list; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LISTVIEW_H diff --git a/Code/Tools/CryCommonTools/UI/LogWindow.cpp b/Code/Tools/CryCommonTools/UI/LogWindow.cpp deleted file mode 100644 index af96a389e1..0000000000 --- a/Code/Tools/CryCommonTools/UI/LogWindow.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "LogWindow.h" - -LogWindow::LogWindow() - : m_mainLayout(Layout::DirectionVertical) - , m_toolbarLayout(Layout::DirectionHorizontal) - , m_filterFlags(0) -{ - m_buttons.push_back(new ToggleButton(_T("Debug"), this, &LogWindow::DebugToggled)); - m_buttons.push_back(new ToggleButton(_T("Info"), this, &LogWindow::InfoToggled)); - m_buttons.push_back(new ToggleButton(_T("Warnings"), this, &LogWindow::WarningsToggled)); - m_buttons.push_back(new ToggleButton(_T("Errors"), this, &LogWindow::ErrorsToggled)); - - SetFilter(ILogger::eSeverity_Error, true); - SetFilter(ILogger::eSeverity_Warning, true); - SetFilter(ILogger::eSeverity_Info, true); - SetFilter(ILogger::eSeverity_Debug, false); - - m_toolbarLayout.AddComponent(m_buttons[3]); - m_toolbarLayout.AddComponent(m_buttons[2]); - m_toolbarLayout.AddComponent(m_buttons[1]); - m_toolbarLayout.AddComponent(m_buttons[0]); - - m_mainLayout.AddComponent(&m_toolbarLayout); - m_mainLayout.AddComponent(&m_list); -} - -LogWindow::~LogWindow() -{ - for (std::vector::iterator button = m_buttons.begin(), end = m_buttons.end(); button != end; ++button) - { - delete *button; - } -} - -void LogWindow::Log(ILogger::ESeverity eSeverity, const TCHAR* message) -{ - m_messages.push_back(LogMessage(eSeverity, message)); - - if (m_filterFlags & (1 << GetSeverityIndex(eSeverity))) - { - m_list.Add(GetImageIndex(eSeverity), message); - } -} - -void LogWindow::SetFilter(ILogger::ESeverity eSeverity, bool visible) -{ - int index = GetSeverityIndex(eSeverity); - if (visible) - { - m_filterFlags |= (1 << index); - } - else - { - m_filterFlags &= ~(1 << index); - } - m_buttons[index]->SetState(visible); - RefillList(); -} - -void LogWindow::CreateUI(void* window, int left, int top, int width, int height) -{ - m_mainLayout.CreateUI(window, left, top, width, height); -} - -void LogWindow::Resize(void* window, int left, int top, int width, int height) -{ - m_mainLayout.Resize(window, left, top, width, height); -} - -void LogWindow::DestroyUI(void* window) -{ - m_mainLayout.DestroyUI(window); -} - -void LogWindow::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - m_mainLayout.GetExtremeDimensions(window, minWidth, maxWidth, minHeight, maxHeight); -} - -void LogWindow::ErrorsToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Error, value); -} - -void LogWindow::WarningsToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Warning, value); -} - -void LogWindow::InfoToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Info, value); -} - -void LogWindow::DebugToggled(bool value) -{ - SetFilter(ILogger::eSeverity_Debug, value); -} - -void LogWindow::RefillList() -{ - m_list.Clear(); - for (int messageIndex = 0, messageCount = int(m_messages.size()); messageIndex < messageCount; ++messageIndex) - { - if (m_filterFlags & (1 << m_messages[messageIndex].severity)) - { - m_list.Add(GetImageIndex(m_messages[messageIndex].severity), m_messages[messageIndex].message.c_str()); - } - } -} - -int LogWindow::GetImageIndex(ILogger::ESeverity eSeverity) -{ - switch (eSeverity) - { - case ILogger::eSeverity_Debug: - return 2; - case ILogger::eSeverity_Info: - return -1; - case ILogger::eSeverity_Warning: - return 1; - case ILogger::eSeverity_Error: - return 0; - default: - return 0; - } -} - -int LogWindow::GetSeverityIndex(ILogger::ESeverity eSeverity) -{ - switch (eSeverity) - { - case ILogger::eSeverity_Debug: - return 0; - case ILogger::eSeverity_Info: - return 1; - case ILogger::eSeverity_Warning: - return 2; - case ILogger::eSeverity_Error: - return 3; - default: - return 3; - } -} diff --git a/Code/Tools/CryCommonTools/UI/LogWindow.h b/Code/Tools/CryCommonTools/UI/LogWindow.h deleted file mode 100644 index 13afeac57c..0000000000 --- a/Code/Tools/CryCommonTools/UI/LogWindow.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H -#pragma once - - -#include "IUIComponent.h" -#include "Layout.h" -#include "ListView.h" -#include "ToggleButton.h" -#include -#include "ILogger.h" - -class LogWindow - : public IUIComponent -{ -public: - LogWindow(); - ~LogWindow(); - - void Log(ILogger::ESeverity eSeverity, const TCHAR* message); - void SetFilter(ILogger::ESeverity eSeverity, bool visible); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - struct LogMessage - { - LogMessage(ILogger::ESeverity severity, tstring message) - : severity(severity) - , message(message) - { - } - ILogger::ESeverity severity; - tstring message; - }; - - void ErrorsToggled(bool value); - void WarningsToggled(bool value); - void InfoToggled(bool value); - void DebugToggled(bool value); - void RefillList(); - static int GetImageIndex(ILogger::ESeverity eSeverity); - static int GetSeverityIndex(ILogger::ESeverity eSeverity); - - Layout m_mainLayout; - Layout m_toolbarLayout; - ListView m_list; - std::vector m_buttons; - std::vector m_messages; - - unsigned m_filterFlags; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_LOGWINDOW_H diff --git a/Code/Tools/CryCommonTools/UI/ProgressBar.cpp b/Code/Tools/CryCommonTools/UI/ProgressBar.cpp deleted file mode 100644 index d83c8bf3ad..0000000000 --- a/Code/Tools/CryCommonTools/UI/ProgressBar.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ProgressBar.h" -#include -#include - -ProgressBar::ProgressBar() - : m_progressBar(0) -{ -} - -void ProgressBar::CreateUI(void* window, int left, int top, int width, int height) -{ - m_progressBar = CreateWindowEx( - 0, - PROGRESS_CLASS, - 0, - WS_CHILD | WS_VISIBLE, - left, - top, - width, - height, - (HWND)window, - (HMENU)0, - GetModuleHandle(0), - 0); - SendMessage((HWND)m_progressBar, PBM_SETRANGE, 0, MAKELPARAM(0, 1000)); - SendMessage((HWND)m_progressBar, PBM_SETSTEP, (WPARAM) 1, 0); -} - -void ProgressBar::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_progressBar, left, top, width, height, true); -} - -void ProgressBar::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_progressBar); -} - -void ProgressBar::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 200; - maxWidth = 2000; - minHeight = 30; - maxHeight = 30; -} - -void ProgressBar::SetProgress(float progress) -{ - int newPos = int(progress * 1000.0f); - SendMessage((HWND)m_progressBar, PBM_SETPOS, newPos, 0); -} diff --git a/Code/Tools/CryCommonTools/UI/ProgressBar.h b/Code/Tools/CryCommonTools/UI/ProgressBar.h deleted file mode 100644 index 16ce456abe..0000000000 --- a/Code/Tools/CryCommonTools/UI/ProgressBar.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_PROGRESSBAR_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_PROGRESSBAR_H -#pragma once - - -#include "IUIComponent.h" - -class ProgressBar - : public IUIComponent -{ -public: - ProgressBar(); - - void SetProgress(float progress); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void* m_progressBar; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_PROGRESSBAR_H diff --git a/Code/Tools/CryCommonTools/UI/PushButton.cpp b/Code/Tools/CryCommonTools/UI/PushButton.cpp deleted file mode 100644 index e1458db0d6..0000000000 --- a/Code/Tools/CryCommonTools/UI/PushButton.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "PushButton.h" -#include "Win32GUI.h" - -PushButton::~PushButton() -{ - m_callback->Release(); -} - -void PushButton::Enable(bool enabled) -{ - m_enabled = enabled; - EnableWindow((HWND)m_button, m_enabled); -} - -void PushButton::CreateUI(void* window, int left, int top, int width, int height) -{ - m_button = Win32GUI::CreateControl(_T("BUTTON"), WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON, (HWND)window, left, top, 40, 20); - m_font = Win32GUI::CreateFont(); - SendMessage((HWND)m_button, WM_SETFONT, (WPARAM)m_font, 0); - SendMessage((HWND)m_button, WM_SETTEXT, 0, (LPARAM)m_text.c_str()); - EnableWindow((HWND)m_button, m_enabled); - - Win32GUI::SetCallback((HWND)m_button, this, &PushButton::OnPushed); -} - -void PushButton::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_button, left, top, width, height, true); -} - -void PushButton::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_button); - m_button = 0; - DeleteObject(m_font); - m_font = 0; -} - -void PushButton::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 50; - maxWidth = 50; - minHeight = 20; - maxHeight = 20; -} - -void PushButton::OnPushed() -{ - m_callback->Call(); -} diff --git a/Code/Tools/CryCommonTools/UI/PushButton.h b/Code/Tools/CryCommonTools/UI/PushButton.h deleted file mode 100644 index a6199208d5..0000000000 --- a/Code/Tools/CryCommonTools/UI/PushButton.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H -#pragma once - - -#include "IUIComponent.h" -#include - -class PushButton - : public IUIComponent -{ -public: - template - PushButton(const TCHAR* text, T* object, void (T::* method)()); - ~PushButton(); - - void Enable(bool enabled); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - PushButton(const PushButton&); - PushButton& operator=(const PushButton&); - - struct ICallback - { - virtual void Release() = 0; - virtual void Call() = 0; - }; - - template - struct Callback - : public ICallback - { - Callback(T* object, void (T::* method)()) - : object(object) - , method(method) {} - virtual void Release() {delete this; } - virtual void Call() {(object->*method)(); } - T* object; - void (T::* method)(); - }; - - void OnPushed(); - - std::basic_string m_text; - void* m_button; - void* m_font; - ICallback* m_callback; - bool m_enabled; -}; - -template -PushButton::PushButton(const TCHAR* text, T* object, void (T::* method)()) - : m_text(text) - , m_callback(new Callback(object, method)) - , m_enabled(true) -{ -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_PUSHBUTTON_H diff --git a/Code/Tools/CryCommonTools/UI/Spacer.cpp b/Code/Tools/CryCommonTools/UI/Spacer.cpp deleted file mode 100644 index 822831116e..0000000000 --- a/Code/Tools/CryCommonTools/UI/Spacer.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "Spacer.h" - -Spacer::Spacer(int minWidth, int minHeight, int maxWidth, int maxHeight) - : m_minWidth(minWidth) - , m_minHeight(minHeight) - , m_maxWidth(maxWidth) - , m_maxHeight(maxHeight) -{ -} - -void Spacer::CreateUI(void* window, int left, int top, int width, int height) -{ -} - -void Spacer::Resize(void* window, int left, int top, int width, int height) -{ -} - -void Spacer::DestroyUI(void* window) -{ -} - -void Spacer::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = m_minWidth; - maxWidth = m_maxWidth; - minHeight = m_minHeight; - maxHeight = m_maxHeight; -} diff --git a/Code/Tools/CryCommonTools/UI/Spacer.h b/Code/Tools/CryCommonTools/UI/Spacer.h deleted file mode 100644 index 173fb7ab13..0000000000 --- a/Code/Tools/CryCommonTools/UI/Spacer.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_SPACER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_SPACER_H -#pragma once - - -#include "IUIComponent.h" - -class Spacer - : public IUIComponent -{ -public: - Spacer(int minWidth, int minHeight, int maxWidth, int maxHeight); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - int m_minWidth; - int m_minHeight; - int m_maxWidth; - int m_maxHeight; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_SPACER_H diff --git a/Code/Tools/CryCommonTools/UI/TaskList.cpp b/Code/Tools/CryCommonTools/UI/TaskList.cpp deleted file mode 100644 index 477041fd59..0000000000 --- a/Code/Tools/CryCommonTools/UI/TaskList.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "TaskList.h" -#include "Win32GUI.h" -#include -#include -#include -#include - -TaskList::TaskList() - : m_edit(0) -{ -} - -void TaskList::AddTask(const std::string& id, const std::string description) -{ - int taskIndex = int(m_tasks.size()); - m_tasks.push_back(std::make_pair(id, description)); - m_idTaskMap.insert(std::make_pair(id, taskIndex)); -} - -void TaskList::SetCurrentTask(const std::string& id) -{ - SetText(id); -} - -void TaskList::SetColor() -{ - SendMessage((HWND)m_edit, EM_SETBKGNDCOLOR, 0, GetSysColor(COLOR_3DFACE)); -} - -void TaskList::SetText(const std::string& highlightedTask) -{ - PARAFORMAT2 paragraphFormat; - std::memset(¶graphFormat, 0, sizeof(paragraphFormat)); - paragraphFormat.cbSize = sizeof(paragraphFormat); - paragraphFormat.dwMask = PFM_LINESPACING | PFM_SPACEBEFORE; - paragraphFormat.bLineSpacingRule = 5; // Specify spacing in 20ths of a line. - paragraphFormat.dyLineSpacing = 22; - paragraphFormat.dySpaceBefore = 70; - SendMessage((HWND)m_edit, EM_SETPARAFORMAT, 0, (LPARAM)¶graphFormat); - - CHARFORMAT format; - std::memset(&format, 0, sizeof(format)); - format.cbSize = sizeof(format); - format.dwMask = CFM_BOLD; - format.dwEffects = 0; - SendMessage((HWND)m_edit, EM_SETCHARFORMAT, 0, (LPARAM)&format); - - SETTEXTEX textEx; - std::memset(&textEx, 0, sizeof(textEx)); - textEx.flags = ST_DEFAULT; - textEx.codepage = CP_ACP; - SendMessage((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)_T("")); - int highlightedLineStart = 0; - int highlightedLineEnd = 0; - - for (std::vector >::const_iterator taskPos = m_tasks.begin(), taskEnd = m_tasks.end(); taskPos != taskEnd; ++taskPos) - { - textEx.flags = ST_SELECTION; - const std::string& id = (*taskPos).first; - const std::string& description = (*taskPos).second; - const char* margin = " "; - if (highlightedTask == id) - { - margin = "* "; - CHARRANGE range; - SendMessage((HWND)m_edit, EM_EXGETSEL, 0, (LPARAM)&range); - highlightedLineStart = range.cpMin; - } - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)margin); - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)description.c_str()); - SendMessageA((HWND)m_edit, EM_SETTEXTEX, (WPARAM)&textEx, (LPARAM)"\n"); - if (highlightedTask == id) - { - CHARRANGE range; - SendMessage((HWND)m_edit, EM_EXGETSEL, 0, (LPARAM)&range); - highlightedLineEnd = range.cpMin; - } - } - - CHARRANGE range = {highlightedLineStart, highlightedLineEnd}; - SendMessage((HWND)m_edit, EM_EXSETSEL, 0, (LPARAM)&range); - - format.dwEffects = CFE_BOLD; - SendMessage((HWND)m_edit, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format); - - range.cpMin = 0; - range.cpMax = 0; - SendMessage((HWND)m_edit, EM_EXSETSEL, 0, (LPARAM)&range); -} - -void TaskList::CreateUI(void* window, int left, int top, int width, int height) -{ - // Create the window. - LoadLibrary(_T("Riched20.dll")); - m_edit = CreateWindowEx( - 0, //DWORD dwExStyle, - RICHEDIT_CLASS, //LPCTSTR lpClassName, - 0, //LPCTSTR lpWindowName, - WS_CHILD | WS_VISIBLE | ES_LEFT | ES_MULTILINE | ES_READONLY, //DWORD dwStyle, - left, //int x, - top, //int y, - width, //int nWidth, - height, //int nHeight, - (HWND)window, //HWND hWndParent, - 0, //HMENU hMenu, - GetModuleHandle(0), //HINSTANCE hInstance, - 0); //LPVOID lpParam); - HFONT font = Win32GUI::CreateFont(); - SendMessage((HWND)m_edit, WM_SETFONT, (WPARAM)font, 0); - DeleteObject(font); - SetColor(); - - SetText(""); -} - -void TaskList::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_edit, left, top, width, height, true); -} - -void TaskList::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_edit); - m_edit = 0; -} - -void TaskList::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 10; - maxWidth = 2000; - int height = 25 * int(m_tasks.size()); - minHeight = height; - maxHeight = height; -} diff --git a/Code/Tools/CryCommonTools/UI/TaskList.h b/Code/Tools/CryCommonTools/UI/TaskList.h deleted file mode 100644 index 54f825a5b5..0000000000 --- a/Code/Tools/CryCommonTools/UI/TaskList.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_TASKLIST_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_TASKLIST_H -#pragma once - - -#include "IUIComponent.h" -#include -#include -#include - -class TaskList - : public IUIComponent -{ -public: - TaskList(); - - void AddTask(const std::string& id, const std::string description); - void SetCurrentTask(const std::string& id); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - void SetColor(); - void SetText(const std::string& highlightedTask); - - std::map m_idTaskMap; - std::vector > m_tasks; - void* m_edit; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_TASKLIST_H diff --git a/Code/Tools/CryCommonTools/UI/ToggleButton.cpp b/Code/Tools/CryCommonTools/UI/ToggleButton.cpp deleted file mode 100644 index 6f93a9c303..0000000000 --- a/Code/Tools/CryCommonTools/UI/ToggleButton.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "ToggleButton.h" -#include "Win32GUI.h" - -ToggleButton::~ToggleButton() -{ - m_callback->Release(); -} - -void ToggleButton::SetState(bool state) -{ - m_state = state; - SendMessage((HWND)m_button, BM_SETCHECK, m_state, 0); -} - -void ToggleButton::CreateUI(void* window, int left, int top, int width, int height) -{ - m_button = Win32GUI::CreateControl(_T("BUTTON"), WS_VISIBLE | WS_CHILD | BS_AUTOCHECKBOX | BS_NOTIFY | BS_PUSHLIKE, (HWND)window, left, top, 40, 20); - m_font = Win32GUI::CreateFont(); - SendMessage((HWND)m_button, WM_SETFONT, (WPARAM)m_font, 0); - SendMessage((HWND)m_button, WM_SETTEXT, 0, (LPARAM)m_text.c_str()); - SendMessage((HWND)m_button, BM_SETCHECK, m_state, 0); - - Win32GUI::SetCallback((HWND)m_button, this, &ToggleButton::OnChecked); -} - -void ToggleButton::Resize(void* window, int left, int top, int width, int height) -{ - MoveWindow((HWND)m_button, left, top, width, height, true); -} - -void ToggleButton::DestroyUI(void* window) -{ - DestroyWindow((HWND)m_button); - m_button = 0; - DeleteObject(m_font); - m_font = 0; -} - -void ToggleButton::GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight) -{ - minWidth = 50; - maxWidth = 50; - minHeight = 20; - maxHeight = 20; -} - -void ToggleButton::OnChecked(bool checked) -{ - m_state = checked; - m_callback->Call(checked); -} diff --git a/Code/Tools/CryCommonTools/UI/ToggleButton.h b/Code/Tools/CryCommonTools/UI/ToggleButton.h deleted file mode 100644 index 27eec0906c..0000000000 --- a/Code/Tools/CryCommonTools/UI/ToggleButton.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H -#pragma once - - -#include "IUIComponent.h" -#include - -class ToggleButton - : public IUIComponent -{ -public: - template - ToggleButton(const TCHAR* text, T* object, void (T::* method)(bool value)); - ~ToggleButton(); - - void SetState(bool value); - - // IUIComponent - virtual void CreateUI(void* window, int left, int top, int width, int height); - virtual void Resize(void* window, int left, int top, int width, int height); - virtual void DestroyUI(void* window); - virtual void GetExtremeDimensions(void* window, int& minWidth, int& maxWidth, int& minHeight, int& maxHeight); - -private: - ToggleButton(const ToggleButton&); - ToggleButton& operator=(const ToggleButton); - - struct ICallback - { - virtual void Release() = 0; - virtual void Call(bool value) = 0; - }; - - template - struct Callback - : public ICallback - { - Callback(T* object, void (T::* method)(bool value)) - : object(object) - , method(method) {} - virtual void Release() {delete this; } - virtual void Call(bool value) {(object->*method)(value); } - T* object; - void (T::* method)(bool value); - }; - - void OnChecked(bool checked); - - tstring m_text; - void* m_button; - void* m_font; - bool m_state; - ICallback* m_callback; -}; - -template -ToggleButton::ToggleButton(const TCHAR* text, T* object, void (T::* method)(bool value)) - : m_text(text) - , m_state(false) - , m_callback(new Callback(object, method)) -{ -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_TOGGLEBUTTON_H diff --git a/Code/Tools/CryCommonTools/UI/Win32GUI.cpp b/Code/Tools/CryCommonTools/UI/Win32GUI.cpp deleted file mode 100644 index e34348271d..0000000000 --- a/Code/Tools/CryCommonTools/UI/Win32GUI.cpp +++ /dev/null @@ -1,390 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "StdAfx.h" -#include "Win32GUI.h" -#include -#include -#include -#include -#include "commctrl.h" -#include "StringHelpers.h" - -namespace Win32GUI -{ - const int WM_REFLECT_BASE = WM_USER + 0x1c00; - const int WM_COMMAND_REFLECT = WM_REFLECT_BASE + WM_COMMAND; - const int WM_NOTIFY_REFLECT = WM_REFLECT_BASE + WM_NOTIFY; - - class Window - { - public: - typedef LRESULT (Window::* WindowProcMethod)(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - Window(WindowProcMethod windowProc); - ~Window(); - static LRESULT CALLBACK StaticWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - LRESULT WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - LRESULT FrameWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); - - void Subclass(HWND window); - void Unsubclass(HWND window); - - WNDPROC m_oldWndProc; - WindowProcMethod m_windowProc; - typedef std::multimap CallbackMap; - CallbackMap m_callbackMap; - }; -} - -void Win32GUI::Initialize() -{ - InitCommonControls(); - LoadLibrary(_T("riched20.dll")); -} - -void Win32GUI::RegisterFrameClass(const TCHAR* name) -{ - WNDCLASS cls; - std::memset(&cls, 0, sizeof(cls)); - cls.style = 0; - cls.lpfnWndProc = &Window::StaticWindowProc; - cls.cbClsExtra = 0; - cls.cbWndExtra = 0; - cls.hInstance = GetModuleHandle(0); - cls.hIcon = 0; - cls.hCursor = LoadCursor(0, IDC_ARROW); - cls.hbrBackground = GetSysColorBrush(COLOR_BTNFACE); - cls.lpszMenuName = 0; - cls.lpszClassName = name; - - RegisterClass(&cls); -} - -HWND Win32GUI::CreateFrame(const TCHAR* className, unsigned style, int width, int height) -{ - Window* window = new Window(&Window::FrameWindowProc); - - HWND hwnd = CreateWindow( - className, // LPCTSTR lpClassName, - TEXT(""), // LPCTSTR lpWindowName, - style, // DWORD dwStyle, - CW_USEDEFAULT, // int x, - CW_USEDEFAULT, // int y, - width, // int nWidth, - height, // int nHeight, - 0, // HWND hWndParent, - 0, // HMENU hMenu, - GetModuleHandle(0), // HINSTANCE hInstance, - window); // LPVOID lpParam - - return hwnd; -} - -HWND Win32GUI::CreateControl(const TCHAR* className, unsigned style, HWND parent, int left, int top, int width, int height) -{ - Window* window = new Window(&Window::WindowProc); - - HWND hwnd = CreateWindow( - className, // LPCTSTR lpClassName, - 0, // LPCTSTR lpWindowName, - style | WS_CHILD | WS_VISIBLE, // DWORD dwStyle, - left, // int x, - top, // int y, - width, // int nWidth, - height, // int nHeight, - parent, // HWND hWndParent, - 0, // HMENU hMenu, - GetModuleHandle(0), // HINSTANCE hInstance, - 0); // LPVOID lpParam - - window->Subclass(hwnd); - - return hwnd; -} - -int Win32GUI::Run() -{ - MSG msg; - BOOL status; - while ((status = GetMessage(&msg, HWND(0), UINT(0), UINT(0))) != 0) - { - if (status == -1) - { - return -1; - } - else - { - TranslateMessage(&msg); - DispatchMessage(&msg); - } - } - - return (int)msg.wParam; -} - -Win32GUI::Window::Window(WindowProcMethod windowProc) - : m_windowProc(windowProc) - , m_oldWndProc(0) -{ -} - -Win32GUI::Window::~Window() -{ - for (CallbackMap::iterator callbackPos = m_callbackMap.begin(); callbackPos != m_callbackMap.end(); ++callbackPos) - { - (*callbackPos).second->Release(); - } -} - -LRESULT CALLBACK Win32GUI::Window::StaticWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - Window* window = 0; - { - if (uMsg == WM_CREATE) - { - CREATESTRUCT* create_struct = (CREATESTRUCT*)lParam; - window = (Window*)create_struct->lpCreateParams; -#if defined(_WIN64) - SetWindowLongPtr(hwnd, GWLP_USERDATA, LONG_PTR(window)); -#else //defined(_WIN64) - SetWindowLong(hwnd, GWL_USERDATA, PtrToLong(window)); -#endif //defined(_WIN64) - } - else - { -#if defined(_WIN64) - window = (Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA); -#else //defined(_WIN64) - window = (Window*)LongToPtr(GetWindowLong(hwnd, GWL_USERDATA)); -#endif //defined(_WIN64) - } - } - - LRESULT result = 0; - if (window) - { - result = (window->*(window->m_windowProc))(hwnd, uMsg, wParam, lParam); - } - else - { - result = DefWindowProc(hwnd, uMsg, wParam, lParam); - } - - if (uMsg == WM_DESTROY) - { - delete window; -#if defined(_WIN64) - SetWindowLongPtr(hwnd, GWLP_USERDATA, 0); -#else //defined(_WIN64) - SetWindowLong(hwnd, GWL_USERDATA, 0); -#endif //defined(_WIN64) - } - - return result; -} - -LRESULT Win32GUI::Window::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - switch (uMsg) - { - case WM_COMMAND: - { - HWND control = (HWND)lParam; - if (control) - { - SendMessage(control, WM_COMMAND_REFLECT, wParam, lParam); - } - } - break; - - case WM_NOTIFY: - { - NMHDR* notify_header = reinterpret_cast(lParam); - if (notify_header->hwndFrom) - { - SendMessage(notify_header->hwndFrom, WM_NOTIFY_REFLECT, wParam, lParam); - } - } - break; - - case WM_COMMAND_REFLECT: - switch (HIWORD(wParam)) - { - case EN_CHANGE: - { - std::string text = GetWindowString(hwnd); - - std::pair range = m_callbackMap.equal_range(EventCallbacks::TextChanged::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IStringCallback* callback = static_cast((*callbackPos).second); - callback->Call(text); - } - } - break; - - case BN_CLICKED: - { - if (GetWindowLong(hwnd, GWL_STYLE) & BS_CHECKBOX) - { - bool checked = (0 != SendMessage(hwnd, BM_GETCHECK, 0, 0)); - std::pair range = m_callbackMap.equal_range(EventCallbacks::Checked::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IBoolCallback* callback = static_cast((*callbackPos).second); - callback->Call(checked); - } - } - else - { - std::pair range = m_callbackMap.equal_range(EventCallbacks::Pushed::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IVoidCallback* callback = static_cast((*callbackPos).second); - callback->Call(); - } - } - } - break; - } - break; - - case WM_GETMINMAXINFO: - { - int minW = 0, maxW = 0, minH = 100000, maxH = 100000; - - std::pair range = m_callbackMap.equal_range(EventCallbacks::GetDimensions::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::IGetDimensionsCallback* callback = static_cast((*callbackPos).second); - callback->Call(minW, maxW, minH, maxH); - } - - MINMAXINFO* minMaxInfo = (MINMAXINFO*)lParam; - minMaxInfo->ptMinTrackSize.x = minW; - minMaxInfo->ptMaxTrackSize.x = maxW; - minMaxInfo->ptMinTrackSize.y = minH; - minMaxInfo->ptMaxTrackSize.y = maxH; - } - break; - - case WM_SIZE: - { - int width = LOWORD(lParam); - int height = HIWORD(lParam); - std::pair range = m_callbackMap.equal_range(EventCallbacks::SizeChanged::ID); - for (CallbackMap::iterator callbackPos = range.first; callbackPos != range.second; ++callbackPos) - { - EventCallbacks::ISizeCallback* callback = static_cast((*callbackPos).second); - callback->Call(width, height); - } - } - break; - - case WM_NOTIFY_REFLECT: - break; - } - - LRESULT result = 0; - if (m_oldWndProc) - { - result = CallWindowProc(m_oldWndProc, hwnd, uMsg, wParam, lParam); - } - else - { - result = DefWindowProc(hwnd, uMsg, wParam, lParam); - } - - return result; -} - -LRESULT Win32GUI::Window::FrameWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) -{ - switch (uMsg) - { - case WM_CLOSE: - PostQuitMessage(0); - break; - } - - return WindowProc(hwnd, uMsg, wParam, lParam); -} - -void Win32GUI::Window::Subclass(HWND window) -{ -#if defined(_WIN64) - SetWindowLongPtr(window, GWLP_USERDATA, LONG_PTR(this)); - m_oldWndProc = (WNDPROC)GetWindowLongPtr(window, GWLP_WNDPROC); - SetWindowLongPtr(window, GWLP_WNDPROC, LONG_PTR(&Window::StaticWindowProc)); -#else //defined(_WIN64) - SetWindowLong(window, GWL_USERDATA, PtrToLong(this)); - m_oldWndProc = (WNDPROC)LongToPtr(GetWindowLong(window, GWL_WNDPROC)); - SetWindowLong(window, GWL_WNDPROC, PtrToLong(&Window::StaticWindowProc)); -#endif //defined(_WIN64) -} - -void Win32GUI::Window::Unsubclass(HWND window) -{ -#if defined(_WIN64) - SetWindowLongPtr(window, GWLP_USERDATA, 0); - SetWindowLongPtr(window, GWLP_WNDPROC, LONG_PTR(m_oldWndProc)); -#else //defined(_WIN64) - SetWindowLongPtr(window, GWL_USERDATA, 0); - SetWindowLong(window, GWLP_WNDPROC, PtrToLong(m_oldWndProc)); -#endif //defined(_WIN64) - m_oldWndProc = 0; -} - -std::string Win32GUI::GetWindowString(HWND hwnd) -{ - LRESULT length = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0); - std::wstring wtext(length, 0); - SendMessageW(hwnd, WM_GETTEXT, length + 1, (LPARAM)&wtext[0]); - return StringHelpers::ConvertUtf16ToAnsi(wtext.c_str(), '?'); -} - -void Win32GUI::SetWindowString(HWND hwnd, const std::string& text) -{ - std::wstring wtext = StringHelpers::ConvertAnsiToUtf16(text.c_str()); - SendMessageW(hwnd, WM_SETTEXT, 0, (LPARAM)&wtext[0]); -} - -HFONT Win32GUI::CreateFont() -{ - HFONT hFont = 0; - HFONT hGuiFont = static_cast(::GetStockObject(DEFAULT_GUI_FONT)); - - LOGFONT lfGuiFont = { 0 }; - if (::GetObject(hGuiFont, sizeof(LOGFONT), &lfGuiFont) == sizeof(LOGFONT)) - { - _tcsncpy(lfGuiFont.lfFaceName, _T("MS Shell Dlg 2"), sizeof(lfGuiFont.lfFaceName) / sizeof(TCHAR)); - lfGuiFont.lfFaceName[(sizeof(lfGuiFont.lfFaceName) / sizeof(TCHAR)) - 1] = '\0'; - - hFont = ::CreateFontIndirect(&lfGuiFont); - - return hFont; - } - return 0; -} - -void Win32GUI::SetCallbackObject(HWND hwnd, unsigned eventID, EventCallbacks::ICallback* callback) -{ -#if defined(_WIN64) - Window* window = (Window*)GetWindowLongPtr(hwnd, GWLP_USERDATA); -#else //defined(_WIN64) - Window* window = (Window*)LongToPtr(GetWindowLong(hwnd, GWL_USERDATA)); -#endif //defined(_WIN64) - - window->m_callbackMap.insert(std::make_pair(eventID, callback)); -} diff --git a/Code/Tools/CryCommonTools/UI/Win32GUI.h b/Code/Tools/CryCommonTools/UI/Win32GUI.h deleted file mode 100644 index 60b91ece9f..0000000000 --- a/Code/Tools/CryCommonTools/UI/Win32GUI.h +++ /dev/null @@ -1,216 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_UI_WIN32GUI_H -#define CRYINCLUDE_CRYCOMMONTOOLS_UI_WIN32GUI_H -#pragma once - - -#include -#include - -namespace Win32GUI -{ - void Initialize(); - void RegisterFrameClass(const TCHAR* name); - HWND CreateFrame(const TCHAR* className, unsigned style, int width, int height); - HWND CreateControl(const TCHAR* className, unsigned style, HWND parent, int left, int top, int width, int height); - int Run(); - std::string GetWindowString(HWND hwnd); - void SetWindowString(HWND hwnd, const std::string& text); - HFONT CreateFont(); - - namespace EventCallbacks - { - class ICallback - { - public: - virtual ~ICallback() {} - virtual void Release() = 0; - }; - - struct IVoidCallback - : public ICallback - { - virtual void Call() = 0; - }; - - struct VoidCallback - { - template - struct Callback - : public IVoidCallback - { - typedef void (O::* Signature)(); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call() {(m_object->*m_method)(); } - O* m_object; - Signature m_method; - }; - }; - - struct IStringCallback - : public ICallback - { - virtual void Call(const std::string& text) = 0; - }; - - struct StringCallback - { - template - struct Callback - : public IStringCallback - { - typedef void (O::* Signature)(const std::string& text); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(const std::string& text) {(m_object->*m_method)(text); } - O* m_object; - Signature m_method; - }; - }; - - struct IGetDimensionsCallback - : public ICallback - { - virtual void Call(int& minW, int& maxW, int& minH, int& maxH) = 0; - }; - - struct GetDimensionsCallback - { - template - struct Callback - : public IGetDimensionsCallback - { - typedef void (O::* Signature)(int& minW, int& maxW, int& minH, int& maxH); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(int& minW, int& maxW, int& minH, int& maxH) {(m_object->*m_method)(minW, maxW, minH, maxH); } - O* m_object; - Signature m_method; - }; - }; - - struct ISizeCallback - : public ICallback - { - virtual void Call(int width, int height) = 0; - }; - - struct SizeCallback - { - template - struct Callback - : public ISizeCallback - { - typedef void (O::* Signature)(int width, int height); - - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(int width, int height) {(m_object->*m_method)(width, height); } - O* m_object; - Signature m_method; - }; - }; - - struct IBoolCallback - : public ICallback - { - virtual void Call(bool value) = 0; - }; - - struct BoolCallback - { - template - struct Callback - : public IBoolCallback - { - typedef void (O::* Signature)(bool callback); - Callback(O* object, Signature method) - : m_object(object) - , m_method(method) {} - virtual void Release() {delete this; } - virtual void Call(bool value) {(m_object->*m_method)(value); } - O* m_object; - Signature m_method; - }; - }; - - struct TextChanged - : public StringCallback - { - enum - { - ID = 0x00005001 - }; - }; - struct GetDimensions - : public GetDimensionsCallback - { - enum - { - ID = 0x00005002 - }; - }; - struct SizeChanged - : public SizeCallback - { - enum - { - ID = 0x00005003 - }; - }; - struct Pushed - : public VoidCallback - { - enum - { - ID = 0x00005004 - }; - }; - struct Checked - : public BoolCallback - { - enum - { - ID = 0x00005005 - }; - }; - }; - - void SetCallbackObject(HWND hwnd, unsigned eventID, EventCallbacks::ICallback* callback); - template - inline void SetCallback(HWND hwnd, O* object, typename T::template Callback::Signature method); -} - -template -inline void Win32GUI::SetCallback(HWND hwnd, O* object, typename T::template Callback::Signature method) -{ - typedef T::template Callback Callback; - Callback* callback = new Callback(object, method); - SetCallbackObject(hwnd, T::ID, callback); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_UI_WIN32GUI_H diff --git a/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp b/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp index 20721d4624..5123d120d5 100644 --- a/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp +++ b/Gems/LyShine/Code/Editor/PropertyHandlerSprite.cpp @@ -27,8 +27,6 @@ #include "SpriteBorderEditorCommon.h" -#include - #include #include From 33f7da764e16ad7ee5026aa4ac4c2c8a39a01e41 Mon Sep 17 00:00:00 2001 From: Shirang Jia Date: Wed, 12 May 2021 10:05:42 -0700 Subject: [PATCH 22/47] Remove unneeded scripts that have internal service references (#683) --- scripts/build/tools/alert_build_failures.py | 76 ------------ scripts/build/tools/email_to_lionbridge.py | 128 -------------------- 2 files changed, 204 deletions(-) delete mode 100755 scripts/build/tools/alert_build_failures.py delete mode 100755 scripts/build/tools/email_to_lionbridge.py diff --git a/scripts/build/tools/alert_build_failures.py b/scripts/build/tools/alert_build_failures.py deleted file mode 100755 index 486d84123d..0000000000 --- a/scripts/build/tools/alert_build_failures.py +++ /dev/null @@ -1,76 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -import os -from incremental_build_util import get_iam_role_credentials -try: - import requests -except ImportError: - import pip - pip.main(['install', 'requests', '--ignore-installed', '-q']) - import requests -try: - from requests_aws4auth import AWS4Auth -except ImportError: - import pip - pip.main(['install', 'requests_aws4auth', '--ignore-installed', '-q']) - from requests_aws4auth import AWS4Auth - -IAM_ROLE_NAME = 'ec2-jenkins-node' -TEAM = 'lumberyard-build' -CHIME_ROOM_WEB_HOOK = "https://hooks.chime.aws/incomingwebhooks/2a6018c9-3bf5-4e03-851c-32ba82c7c4e2?token=YWhTVXZsWVJ8MXxaLTg5RkVZNlA5Q1NiMVdfQndGeS1TSHNnYW5VREVha3pjX1pUUEd5b1JF" - - -def find_curr_oncalls_for_team(team): - host = "who-is-oncall-pdx.corp.amazon.com" - service_name = "who-is-oncall" - aws_region = "us-west-2" - headers = {"content-type": "application/json", "host": host} - - credentials = get_iam_role_credentials(IAM_ROLE_NAME) - try: - aws_access_key_id = credentials['AccessKeyId'] - aws_secret_access_key = credentials['SecretAccessKey'] - aws_session_token = credentials['Token'] - except Exception as e: - print(f'ERROR: Cannot get AWS credentials.\n{e}') - return ['All'] - - auth = AWS4Auth(aws_access_key_id, aws_secret_access_key, aws_region, service_name, session_token=aws_session_token) - r = requests.get(f"https://who-is-oncall-pdx.corp.amazon.com/teams/{team}", headers=headers, auth=auth, verify=False) - if r.ok: - res = r.json() - try: - return res['currOncalls'] - except KeyError: - return ['All'] - return ['All'] - - -def send_alert_to_chime_room(web_hook, content): - data = '{"Content":"' + content + '"}' - headers = {'Content-Type': 'application/json'} - requests.post(web_hook, headers=headers, data=data) - - -def create_content(): - content = '' - oncalls = find_curr_oncalls_for_team(TEAM) - for oncall in oncalls: - content += f'@{oncall} ' - job_name = os.environ['JOB_NAME'] - build_url = os.environ['BUILD_URL'] - content += fr'\nJob {job_name} failed\nBuild URL: {build_url}\n' - return content - - -send_alert_to_chime_room(CHIME_ROOM_WEB_HOOK, create_content()) - diff --git a/scripts/build/tools/email_to_lionbridge.py b/scripts/build/tools/email_to_lionbridge.py deleted file mode 100755 index 7f522bb564..0000000000 --- a/scripts/build/tools/email_to_lionbridge.py +++ /dev/null @@ -1,128 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -""" -This script will be used in the Sandobx Jenkins job PACKAGE_COPY_S3 -PACKAGE_COPY_S3 is a downstream job of nightly packaging job, it copies the nightly packages from Infra S3 bucket to Lionbridge S3 bucket based on the INCLUDE_FILTER passed from packaging job -""" -import os -import re -import json -import requests -from requests.auth import HTTPBasicAuth -import boto3 -from util import error, warn - - -# Write EMAIL_TEMPLATE to a file and inject it into the email sent to Lionbridge -EMAIL_TEMPLATE = '''Packages are uploaded to S3 bucket {} -Package List: -{} - - -Changelists: -{} -''' - - -def get_jenkins_env(key): - try: - return os.environ[key] - except KeyError: - print('Error: Jenkins parameters {} is not set.'.format(key)) - return None - - -JENKINS_USERNAME = get_jenkins_env('JENKINS_USERNAME') -JENKINS_API_TOKEN = get_jenkins_env('JENKINS_API_TOKEN') -JENKINS_URL = get_jenkins_env('JENKINS_URL') -WORKSPACE = get_jenkins_env('WORKSPACE') -S3_TARGET = get_jenkins_env('S3_TARGET') -INCLUDE_FILTER = get_jenkins_env('INCLUDE_FILTER') -EMAIL_TEMPLATE_FILE = get_jenkins_env('EMAIL_TEMPLATE_FILE') -if None in [JENKINS_USERNAME, JENKINS_API_TOKEN, JENKINS_URL, WORKSPACE, S3_TARGET, INCLUDE_FILTER, EMAIL_TEMPLATE_FILE]: - error('Please make sure all Jenkins parameters are set correctly.') - - -def parse_include_filter(include_filter): - try: - res = re.search('^(\w*)-*lumberyard-(\d+)\.(\d+)-(\d+)-(\w+).*\*(\d+)\.\*', include_filter) - branch = res.group(1) - major_version = int(res.group(2)) - minor_version = int(res.group(3)) - changelist_number = res.group(4) - platform = res.group(5) - build_number = res.group(6) - return branch, major_version, minor_version, changelist_number, platform, build_number - except (AttributeError, IndexError): - error('Unable to parse INCLUDE_FILTER, please make sure the INCLUDE_FILTER is set correctly') - - -# Get the changelists that trigger the build -def get_changelists(job_name, build_number): - changelists = [] - headers = {'Content-type': 'application/json', 'Accept': 'application/json'} - try: - res = requests.get('{}/job/{}/{}/api/json'.format(JENKINS_URL, job_name, build_number), - auth=HTTPBasicAuth(JENKINS_USERNAME, JENKINS_API_TOKEN), headers=headers, verify=False) - res = json.loads(res.content) - changelists = res.get('changeSet').get('items') - return changelists - except: - warn('Error: Failed to get changes from build {} in job {}'.format(build_number, job_name)) - return [] - - -def get_packaging_job_name(branch, major_version, minor_version, platform): - if branch == '': - branch = 'ML' if major_version + minor_version == 0 else 'v{}_{}'.format(major_version, minor_version) - job_name = 'PKG_{}_{}'.format(branch, platform.capitalize()) - return job_name - - -# Get package names by looking up S3 bucket -def get_package_names(branch, major_version, minor_version, include_filter, build_number): - package_names = [] - prefix = include_filter[:include_filter.find('*')] - pattern = '.*{}.*{}..*'.format(prefix, build_number) - if branch == '': - bucket_name = 'ly-packages-mainline' if major_version + minor_version == 0 else 'ly-packages-release-candidate' - folder = 'lumberyard-packages' - else: - bucket_name = 'ly-packages-feature-branches' - folder = 'lumberyard-packages/{}'.format(branch) - s3 = boto3.resource('s3') - bucket = s3.Bucket(bucket_name) - for obj in bucket.objects.filter(Prefix='{}/{}'.format(folder, prefix)): - package_name = obj.key - if re.match(pattern, package_name): - package_names.append(package_name.replace('{}/'.format(folder), '')) - return package_names - - -if __name__ == "__main__": - branch, major_version, minor_version, changelist_number, platform, build_number = parse_include_filter(INCLUDE_FILTER) - packaging_job_name = get_packaging_job_name(branch, major_version, minor_version, platform) - changelists = get_changelists(packaging_job_name, build_number) - package_names = get_package_names(branch, major_version, minor_version, INCLUDE_FILTER, build_number) - with open(os.path.join(WORKSPACE, EMAIL_TEMPLATE_FILE), 'w+') as output: - if len(package_names) > 0: - package_list_str = '\n'.join(package_names) - changelists_str = '' - for item in changelists: - changelists_str += '---------------------------------------------------------------------------------------------\n' - try: - changelists_str += 'CL{} by {} on {}\n{}\n'.format(item['changeNumber'], item['author']['fullName'], item['changeTime'], item['msg'].encode('utf-8', 'ignore')) - except KeyError: - error('Internal error, check the output of Jenkins API.') - output.write(EMAIL_TEMPLATE.format(S3_TARGET, package_list_str, changelists_str)) - - From 3383cfc95a33145114893ba6dd98cc9775a90ab5 Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Wed, 12 May 2021 10:20:03 -0700 Subject: [PATCH 23/47] Fix Jenkins failure during engine registration for iOS --- scripts/build/Platform/iOS/build_config.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/build/Platform/iOS/build_config.json b/scripts/build/Platform/iOS/build_config.json index 4566d243ee..bb5f2d2fe6 100644 --- a/scripts/build/Platform/iOS/build_config.json +++ b/scripts/build/Platform/iOS/build_config.json @@ -27,7 +27,7 @@ "PARAMETERS": { "CONFIGURATION": "debug", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -44,7 +44,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -60,7 +60,7 @@ "PARAMETERS": { "CONFIGURATION": "profile", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=FALSE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=FALSE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" @@ -94,7 +94,7 @@ "PARAMETERS": { "CONFIGURATION": "release", "OUTPUT_DIRECTORY": "build/ios", - "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"!WORKSPACE!/home\" -DO3DE_REGISTER_ENGINE_PATH=\"!WORKSPACE!/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", + "CMAKE_OPTIONS": "-G Xcode -DCMAKE_TOOLCHAIN_FILE=cmake/Platform/iOS/Toolchain_ios.cmake -DLY_MONOLITHIC_GAME=TRUE -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=FALSE -DLY_IOS_CODE_SIGNING_IDENTITY=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGN_ENTITLEMENTS=\"\" -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_ALLOWED=FALSE -DLY_UNITY_BUILD=TRUE -DO3DE_HOME_PATH=\"${WORKSPACE}/home\" -DO3DE_REGISTER_ENGINE_PATH=\"${WORKSPACE}/o3de\" -DO3DE_REGISTER_THIS_ENGINE=TRUE", "CMAKE_LY_PROJECTS": "AutomatedTesting", "CMAKE_TARGET": "ALL_BUILD", "CMAKE_NATIVE_BUILD_ARGS": "-destination generic/platform=iOS" From 3569ac9b873f1a996d306eb06646195574710095 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Wed, 12 May 2021 13:13:28 -0500 Subject: [PATCH 24/47] Bringing back RHI modules to tools deps --- .../Source/Platform/Linux/additional_linux_tool_deps.cmake | 3 +++ .../Code/Source/Platform/Mac/additional_mac_tool_deps.cmake | 3 +++ .../Source/Platform/Windows/additional_windows_tool_deps.cmake | 3 +++ 3 files changed, 9 insertions(+) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake index 908417b1f8..c76527afa0 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Linux/additional_linux_tool_deps.cmake @@ -10,6 +10,9 @@ # set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Metal.Private Gem::Atom_RHI_Vulkan.Builders Gem::Atom_RHI_DX12.Builders Gem::Atom_RHI_Metal.Builders diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake index 445a416a68..81046d3071 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Mac/additional_mac_tool_deps.cmake @@ -10,6 +10,9 @@ # set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Metal.Private + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private Gem::Atom_RHI_Metal.Builders Gem::Atom_RHI_Vulkan.Builders Gem::Atom_RHI_DX12.Builders diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake index 908417b1f8..c76527afa0 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Platform/Windows/additional_windows_tool_deps.cmake @@ -10,6 +10,9 @@ # set(LY_RUNTIME_DEPENDENCIES + Gem::Atom_RHI_Vulkan.Private + Gem::Atom_RHI_DX12.Private + Gem::Atom_RHI_Metal.Private Gem::Atom_RHI_Vulkan.Builders Gem::Atom_RHI_DX12.Builders Gem::Atom_RHI_Metal.Builders From b5d7ae829a4c44a9d89bb104b55135ffc9059d19 Mon Sep 17 00:00:00 2001 From: zsolleci Date: Wed, 12 May 2021 14:10:54 -0500 Subject: [PATCH 25/47] addressed internal review feedback --- .../scripting/Node_HappyPath_DuplicateNode.py | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py index 9d8cccd027..77d3b2fcde 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Node_HappyPath_DuplicateNode.py @@ -12,9 +12,7 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # fmt: off class Tests(): - open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") - node_added = ("Successfully added node to graph", "Failed to add node to graph") - node_duplicated = ("Successfully duplicated node", "Failed to duplicate the node") + node_duplicated = ("Successfully duplicated node", "Failed to duplicate the node") # fmt: on @@ -30,9 +28,8 @@ def Node_HappyPath_DuplicateNode(): 1) Open Script Canvas window (Tools > Script Canvas) 2) Open a new graph 3) Add node to graph - 4) Select node in graph to verify existence - 5) Mock Ctrl+D to duplicate node - 6) Verify the node was duplicated + 4) Duplicate node + 5) Verify the node was duplicated6) Verify the node was duplicated Note: - This test file must be called from the Open 3D Engine Editor command terminal @@ -68,11 +65,9 @@ def Node_HappyPath_DuplicateNode(): def grab_title_text(): scroll_area = node_inspector.findChild(QtWidgets.QScrollArea, "") QtTest.QTest.keyClick(graph, "a", Qt.ControlModifier, WAIT_FRAMES) - general.idle_wait(1.0) background = scroll_area.findChild(QtWidgets.QFrame, "Background") title = background.findChild(QtWidgets.QLabel, "Title") text = title.findChild(QtWidgets.QLabel, "Title") - print(text.text()) return text.text() # 1) Open Script Canvas window (Tools > Script Canvas) @@ -80,29 +75,35 @@ def Node_HappyPath_DuplicateNode(): general.open_pane("Script Canvas") helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) - # # 2) Open a new graph + # 2) Open a new graph editor_window = pyside_utils.get_editor_main_window() sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") sc_main = sc.findChild(QtWidgets.QMainWindow) create_new_graph = pyside_utils.find_child_by_pattern( sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} ) + if sc.findChild(QtWidgets.QDockWidget, "NodeInspector") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Inspector", "type": QtWidgets.QAction}) + action.trigger() node_inspector = sc.findChild(QtWidgets.QDockWidget, "NodeInspector") create_new_graph.trigger() # 3) Add node command_line_input("add_node Print") - # 4) Select node in graph to verify existence + # 4) Duplicate node graph_view = sc.findChild(QtWidgets.QFrame, "graphicsViewFrame") graph = graph_view.findChild(QtWidgets.QWidget, "") - - # 5) Duplicate node + # There are currently no utilities available to directly duplicate the node, + # therefore the node is selected using CTRL+A on the graph to select + # it and then CTRL+D to duplicate sc_main.activateWindow() QtTest.QTest.keyClick(graph, "a", Qt.ControlModifier, WAIT_FRAMES) QtTest.QTest.keyClick(graph, "d", Qt.ControlModifier, WAIT_FRAMES) - # 6) Verify the node was duplicated + # 5) Verify the node was duplicated + # As direct interaction with node is not available the text on the label + # inside the Node Inspector is validated showing two nodes exist after_dup = grab_title_text() Report.result(Tests.node_duplicated, after_dup == EXPECTED_STRING) From 98a579abefc0ac64e6ee4ae021c7e8e824dafaa5 Mon Sep 17 00:00:00 2001 From: srikappa Date: Wed, 12 May 2021 12:17:36 -0700 Subject: [PATCH 26/47] Added a comment --- .../AzToolsFramework/Prefab/PrefabPublicHandler.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 3214905721..9649818ed9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -149,6 +149,7 @@ namespace AzToolsFramework undoBatch.GetUndoBatch(), containerEntityId, false); }); + // Create a link between the templates of the newly created instance and the instance it's being parented under. CreateLink( topLevelEntities, instanceToCreate->get(), commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch(), commonRootEntityId); From 2787e5053d8514afd470df38881da916d231bb39 Mon Sep 17 00:00:00 2001 From: catdo Date: Wed, 12 May 2021 13:18:32 -0700 Subject: [PATCH 27/47] addressed some nits and added comments --- .../prefab/PrefabLevel_OpensLevelWithEntities.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py index ca59bbc2f8..3401c6a0a9 100644 --- a/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py +++ b/AutomatedTesting/Gem/PythonTests/prefab/PrefabLevel_OpensLevelWithEntities.py @@ -14,7 +14,7 @@ class Tests(): find_empty_entity = ("Entity: 'EmptyEntity' found", "Entity: 'EmptyEntity' *not* found in level") empty_entity_pos = ("'EmptyEntity' position is at the expected position", "'EmptyEntity' position is *not* at the expected position") find_pxentity = ("Entity: 'EntityWithPxCollider' found", "Entity: 'EntityWithPxCollider' *not* found in level") - pxentity_component = ("Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' has *not* a Physx Collider") + pxentity_component = ("Entity: 'EntityWithPxCollider' has a Physx Collider", "Entity: 'EntityWithPxCollider' does *not* have a Physx Collider") # fmt:on @@ -50,17 +50,19 @@ def PrefabLevel_OpensLevelWithEntities(): if entityIds[0].IsValid(): return entityIds[0] return None - +#Checks for an entity called "EmptyEntity" helper.wait_for_condition(lambda: find_entity("EmptyEntity").IsValid(), 5.0) empty_entity_id = find_entity("EmptyEntity") Report.result(Tests.find_empty_entity, empty_entity_id.IsValid()) +# Checks if the EmptyEntity is in the correct position and if it fails, it will provide the expected postion and the actual postion of the entity in the Editor log empty_entity_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", empty_entity_id) is_at_position = empty_entity_pos.IsClose(EXPECTED_EMPTY_ENTITY_POS) Report.result(Tests.empty_entity_pos, is_at_position) if not is_at_position: Report.info(f'Expected position: {EXPECTED_EMPTY_ENTITY_POS.ToString()}, actual position: {empty_entity_pos.ToString()}') +#Checks for an entity called "EntityWithPxCollider" and if it has the PhysX Collider component pxentity = find_entity("EntityWithPxCollider") Report.result(Tests.find_pxentity, pxentity.IsValid()) From 059f69e5e639a006b3cefaaa64b7055770d5c93a Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 12 May 2021 21:20:23 +0100 Subject: [PATCH 28/47] tidy up NonUniformScaleService compatibility --- .../Components/NonUniformScaleComponent.cpp | 23 ------------------- .../EditorNonUniformScaleComponent.cpp | 23 ------------------- .../Code/Source/DebugDrawObbComponent.cpp | 2 +- .../Integration/Components/ActorComponent.h | 1 + .../Components/SimpleMotionComponent.h | 1 + .../Components/GradientTransformComponent.cpp | 1 + .../Source/Shape/CapsuleShapeComponent.cpp | 1 + .../Source/Shape/CompoundShapeComponent.h | 1 + .../Source/Shape/CylinderShapeComponent.cpp | 1 + .../Code/Source/Shape/DiskShapeComponent.cpp | 1 + .../Shape/EditorCapsuleShapeComponent.cpp | 6 +++++ .../Shape/EditorCapsuleShapeComponent.h | 2 ++ .../Shape/EditorCompoundShapeComponent.cpp | 6 +++++ .../Shape/EditorCompoundShapeComponent.h | 2 ++ .../Shape/EditorCylinderShapeComponent.cpp | 6 +++++ .../Shape/EditorCylinderShapeComponent.h | 2 ++ .../Source/Shape/EditorDiskShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorDiskShapeComponent.h | 1 + .../Shape/EditorSphereShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorSphereShapeComponent.h | 2 ++ .../Source/Shape/EditorSplineComponent.cpp | 1 + .../Source/Shape/EditorTubeShapeComponent.cpp | 6 +++++ .../Source/Shape/EditorTubeShapeComponent.h | 1 + .../Source/Shape/SphereShapeComponent.cpp | 1 + .../Code/Source/Shape/SplineComponent.h | 1 + .../Code/Source/Shape/TubeShapeComponent.cpp | 1 + .../Components/EditorSequenceComponent.h | 1 + .../Source/Components/SequenceComponent.cpp | 5 ++++ .../Source/Components/SequenceComponent.h | 2 ++ .../Code/Source/Components/ClothComponent.cpp | 5 ++++ .../Code/Source/Components/ClothComponent.h | 1 + .../Components/EditorClothComponent.cpp | 5 ++++ .../Source/Components/EditorClothComponent.h | 1 + .../Code/Source/EditorBallJointComponent.cpp | 5 ++++ .../Code/Source/EditorBallJointComponent.h | 1 + .../Code/Source/EditorFixedJointComponent.cpp | 5 ++++ .../Code/Source/EditorFixedJointComponent.h | 1 + .../Code/Source/EditorHingeJointComponent.cpp | 5 ++++ .../Code/Source/EditorHingeJointComponent.h | 1 + .../Components/CharacterControllerComponent.h | 1 + .../Components/CharacterGameplayComponent.cpp | 1 + .../EditorCharacterControllerComponent.h | 1 + .../EditorCharacterGameplayComponent.cpp | 1 + .../Components/RagdollComponent.h | 1 + .../EditorWhiteBoxColliderComponent.cpp | 5 ++++ .../EditorWhiteBoxColliderComponent.h | 1 + .../Components/WhiteBoxColliderComponent.cpp | 5 ++++ .../Components/WhiteBoxColliderComponent.h | 1 + .../Code/Source/EditorWhiteBoxComponent.cpp | 5 ++++ .../Code/Source/EditorWhiteBoxComponent.h | 1 + 50 files changed, 119 insertions(+), 47 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp index 57f14ddb38..d51f3645d3 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp @@ -37,29 +37,6 @@ namespace AzFramework void NonUniformScaleComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); - - incompatible.push_back(AZ_CRC_CE("DebugDrawObbService")); - incompatible.push_back(AZ_CRC_CE("DebugDrawService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXActorService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXSimpleMotionService")); - incompatible.push_back(AZ_CRC_CE("GradientTransformService")); - incompatible.push_back(AZ_CRC_CE("LegacyMeshService")); - incompatible.push_back(AZ_CRC_CE("LookAtService")); - incompatible.push_back(AZ_CRC_CE("SequenceService")); - incompatible.push_back(AZ_CRC_CE("ClothMeshService")); - incompatible.push_back(AZ_CRC_CE("PhysXJointService")); - incompatible.push_back(AZ_CRC_CE("PhysXCharacterControllerService")); - incompatible.push_back(AZ_CRC_CE("PhysXRagdollService")); - incompatible.push_back(AZ_CRC_CE("WhiteBoxService")); - incompatible.push_back(AZ_CRC_CE("NavigationAreaService")); - incompatible.push_back(AZ_CRC_CE("GeometryService")); - incompatible.push_back(AZ_CRC_CE("CapsuleShapeService")); - incompatible.push_back(AZ_CRC_CE("CompoundShapeService")); - incompatible.push_back(AZ_CRC_CE("CylinderShapeService")); - incompatible.push_back(AZ_CRC_CE("DiskShapeService")); - incompatible.push_back(AZ_CRC_CE("SphereShapeService")); - incompatible.push_back(AZ_CRC_CE("SplineService")); - incompatible.push_back(AZ_CRC_CE("TubeShapeService")); } void NonUniformScaleComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp index 989398f196..a61f042049 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp @@ -63,29 +63,6 @@ namespace AzToolsFramework void EditorNonUniformScaleComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); - - incompatible.push_back(AZ_CRC_CE("DebugDrawObbService")); - incompatible.push_back(AZ_CRC_CE("DebugDrawService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXActorService")); - incompatible.push_back(AZ_CRC_CE("EMotionFXSimpleMotionService")); - incompatible.push_back(AZ_CRC_CE("GradientTransformService")); - incompatible.push_back(AZ_CRC_CE("LegacyMeshService")); - incompatible.push_back(AZ_CRC_CE("LookAtService")); - incompatible.push_back(AZ_CRC_CE("SequenceService")); - incompatible.push_back(AZ_CRC_CE("ClothMeshService")); - incompatible.push_back(AZ_CRC_CE("PhysXJointService")); - incompatible.push_back(AZ_CRC_CE("PhysXCharacterControllerService")); - incompatible.push_back(AZ_CRC_CE("PhysXRagdollService")); - incompatible.push_back(AZ_CRC_CE("WhiteBoxService")); - incompatible.push_back(AZ_CRC_CE("NavigationAreaService")); - incompatible.push_back(AZ_CRC_CE("GeometryService")); - incompatible.push_back(AZ_CRC_CE("CapsuleShapeService")); - incompatible.push_back(AZ_CRC_CE("CompoundShapeService")); - incompatible.push_back(AZ_CRC_CE("CylinderShapeService")); - incompatible.push_back(AZ_CRC_CE("DiskShapeService")); - incompatible.push_back(AZ_CRC_CE("SphereShapeService")); - incompatible.push_back(AZ_CRC_CE("SplineService")); - incompatible.push_back(AZ_CRC_CE("TubeShapeService")); } void EditorNonUniformScaleComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) diff --git a/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp b/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp index df13bb56ce..72bbaba2b7 100644 --- a/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp +++ b/Gems/DebugDraw/Code/Source/DebugDrawObbComponent.cpp @@ -71,7 +71,7 @@ namespace DebugDraw void DebugDrawObbComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { - (void)incompatible; + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DebugDrawObbComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 416705bff4..8188da19b4 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h @@ -136,6 +136,7 @@ namespace EMotionFX { incompatible.push_back(AZ_CRC("EMotionFXActorService", 0xd6e8f48d)); incompatible.push_back(AZ_CRC("MeshService", 0x71d8a455)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h index 5f5066b9bb..6820bfe33f 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.h @@ -87,6 +87,7 @@ namespace EMotionFX { incompatible.push_back(AZ_CRC("EMotionFXAnimGraphService", 0x9ec3c819)); incompatible.push_back(AZ_CRC("EMotionFXSimpleMotionService", 0xea7a05d8)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void Reflect(AZ::ReflectContext* /*context*/); diff --git a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp index 0b967a6957..f99a8a8dfb 100644 --- a/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/GradientTransformComponent.cpp @@ -200,6 +200,7 @@ namespace GradientSignal void GradientTransformComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services) { services.push_back(AZ_CRC("GradientTransformService", 0x8c8c5ecc)); + services.push_back(AZ_CRC_CE("NonUniformScaleService")); } void GradientTransformComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services) diff --git a/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp index 46eb69dbd8..2341f93dbb 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/CapsuleShapeComponent.cpp @@ -32,6 +32,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CapsuleShapeService", 0x9bc1122c)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CapsuleShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h index 25204cd4c0..1000609cf3 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/CompoundShapeComponent.h @@ -76,6 +76,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CompoundShapeService", 0x4f7c640a)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void Reflect(AZ::ReflectContext* context); diff --git a/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp index 493cdef3e8..ff4ae9a9c5 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/CylinderShapeComponent.cpp @@ -31,6 +31,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("CylinderShapeService", 0x507c688e)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CylinderShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp index 2d0673f299..f4a0f778c5 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/DiskShapeComponent.cpp @@ -28,6 +28,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("DiskShapeService", 0xd90c482b)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DiskShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp index 93fdfae29f..6c37d2f1ec 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.cpp @@ -78,6 +78,12 @@ namespace LmbrCentral EditorBaseShapeComponent::Deactivate(); } + void EditorCapsuleShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCapsuleShapeComponent::DisplayEntityViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h index 6bb34b1b9e..3accb8f29d 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCapsuleShapeComponent.h @@ -40,6 +40,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CapsuleShapeService", 0x9bc1122c)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // EditorComponentBase void BuildGameEntity(AZ::Entity* gameEntity) override; diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp index c61f54ab08..18957fae36 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.cpp @@ -59,6 +59,12 @@ namespace LmbrCentral } } + void EditorCompoundShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCompoundShapeComponent::Init() { // setup the contained runtime component so that it can manage the child entities in the editor. diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h index 24f06ee336..c725c2ef34 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCompoundShapeComponent.h @@ -41,6 +41,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CompoundShapeService", 0x4f7c640a)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + AZ::u32 ConfigurationChanged(); private: diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp index 89de8410f5..fe5a525fa8 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.cpp @@ -55,6 +55,12 @@ namespace LmbrCentral } } + void EditorCylinderShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorCylinderShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h index a34ec6f548..3bbcf3286b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorCylinderShapeComponent.h @@ -40,6 +40,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("CylinderShapeService", 0x507c688e)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // EditorComponentBase void BuildGameEntity(AZ::Entity* gameEntity) override; diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp index 3d6181cde6..c1bfc04e7d 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.cpp @@ -55,6 +55,12 @@ namespace LmbrCentral provided.push_back(AZ_CRC("DiskShapeService", 0xd90c482b)); } + void EditorDiskShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorDiskShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h index 1d20f2a338..d936a4a9ec 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorDiskShapeComponent.h @@ -39,6 +39,7 @@ namespace LmbrCentral protected: static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); private: AZ_DISABLE_COPY_MOVE(EditorDiskShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp index 0d9885191d..0323ec2dfe 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.cpp @@ -60,6 +60,12 @@ namespace LmbrCentral } } + void EditorSphereShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorSphereShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h index f4a80d91ed..48f1d6cb2e 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSphereShapeComponent.h @@ -44,6 +44,8 @@ namespace LmbrCentral provided.push_back(AZ_CRC("SphereShapeService", 0x90c8dc80)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + private: AZ_DISABLE_COPY_MOVE(EditorSphereShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp index 144713c8ec..212ec49c93 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorSplineComponent.cpp @@ -44,6 +44,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("VariableVertexContainerService", 0x70c58740)); incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void EditorSplineComponent::Reflect(AZ::ReflectContext* context) diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp index c8c03e2811..6ffb9e3308 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.cpp @@ -59,6 +59,12 @@ namespace LmbrCentral } } + void EditorTubeShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorTubeShapeComponent::Init() { EditorBaseShapeComponent::Init(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h index b7b57310e5..6ffe7e9b73 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorTubeShapeComponent.h @@ -57,6 +57,7 @@ namespace LmbrCentral required.push_back(AZ_CRC("SplineService", 0x2b674d3c)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); private: AZ_DISABLE_COPY_MOVE(EditorTubeShapeComponent) diff --git a/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp index 3bddc9b695..7faa455398 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/SphereShapeComponent.cpp @@ -29,6 +29,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("SphereShapeService", 0x90c8dc80)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void SphereShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h b/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h index eaa3fde457..f4cd73574b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/SplineComponent.h @@ -103,6 +103,7 @@ namespace LmbrCentral incompatible.push_back(AZ_CRC("SplineService", 0x2b674d3c)); incompatible.push_back(AZ_CRC("VariableVertexContainerService", 0x70c58740)); incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp index f757da2107..014612daa1 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/TubeShapeComponent.cpp @@ -28,6 +28,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC("ShapeService", 0xe86aa5fe)); incompatible.push_back(AZ_CRC("TubeShapeService", 0x3fe791b4)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void TubeShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h index 294f7b4370..f5689f3f65 100644 --- a/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h +++ b/Gems/Maestro/Code/Source/Components/EditorSequenceComponent.h @@ -98,6 +98,7 @@ namespace Maestro { // This guarantees that only one SequenceComponent will ever be on an entity incompatible.push_back(AZ_CRC("SequenceService", 0x7cbe5938)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } // Required Reflect function. diff --git a/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp b/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp index c1470ccf15..f1951c12a3 100644 --- a/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp +++ b/Gems/Maestro/Code/Source/Components/SequenceComponent.cpp @@ -139,6 +139,11 @@ namespace Maestro } } + void SequenceComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void SequenceComponent::ReflectCinematicsLib(AZ::ReflectContext* context) { // The Movie System itself diff --git a/Gems/Maestro/Code/Source/Components/SequenceComponent.h b/Gems/Maestro/Code/Source/Components/SequenceComponent.h index 20e7d22fe3..48cd7f25c9 100644 --- a/Gems/Maestro/Code/Source/Components/SequenceComponent.h +++ b/Gems/Maestro/Code/Source/Components/SequenceComponent.h @@ -97,6 +97,8 @@ namespace Maestro provided.push_back(AZ_CRC("SequenceService", 0x7cbe5938)); } + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // Required Reflect function. static void Reflect(AZ::ReflectContext* context); private: diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp index ddd2d6fa36..912255c798 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponent.cpp @@ -47,6 +47,11 @@ namespace NvCloth required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); } + void ClothComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void ClothComponent::Activate() { // Cloth components do not run on dedicated servers. diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponent.h b/Gems/NvCloth/Code/Source/Components/ClothComponent.h index 9b8458d276..bb7a645b61 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponent.h +++ b/Gems/NvCloth/Code/Source/Components/ClothComponent.h @@ -38,6 +38,7 @@ namespace NvCloth static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); const ClothComponentMesh* GetClothComponentMesh() const { return m_clothComponentMesh.get(); } diff --git a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp index 4705a9f2c2..1254a13cb2 100644 --- a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp +++ b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.cpp @@ -415,6 +415,11 @@ namespace NvCloth required.push_back(AZ_CRC("MeshService", 0x71d8a455)); } + void EditorClothComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + const MeshNodeList& EditorClothComponent::GetMeshNodeList() const { return m_meshNodeList; diff --git a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h index 9727895a43..2ef3123942 100644 --- a/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h +++ b/Gems/NvCloth/Code/Source/Components/EditorClothComponent.h @@ -39,6 +39,7 @@ namespace NvCloth static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); const MeshNodeList& GetMeshNodeList() const; const AZStd::unordered_set& GetMeshNodesWithBackstopData() const; diff --git a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp index f3bdb83325..deb1d0d231 100644 --- a/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorBallJointComponent.cpp @@ -63,6 +63,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorBallJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorBallJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorBallJointComponent.h b/Gems/PhysX/Code/Source/EditorBallJointComponent.h index fbff44b38e..44f96b3fa8 100644 --- a/Gems/PhysX/Code/Source/EditorBallJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorBallJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp b/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp index a2b496672c..1645d8c932 100644 --- a/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorFixedJointComponent.cpp @@ -60,6 +60,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorFixedJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorFixedJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorFixedJointComponent.h b/Gems/PhysX/Code/Source/EditorFixedJointComponent.h index c66ba661be..8642f83472 100644 --- a/Gems/PhysX/Code/Source/EditorFixedJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorFixedJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp index fde1ff980b..6d136e898b 100644 --- a/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorHingeJointComponent.cpp @@ -63,6 +63,11 @@ namespace PhysX required.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); } + void EditorHingeJointComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorHingeJointComponent::Activate() { EditorJointComponent::Activate(); diff --git a/Gems/PhysX/Code/Source/EditorHingeJointComponent.h b/Gems/PhysX/Code/Source/EditorHingeJointComponent.h index 3b3182068b..ef555d145e 100644 --- a/Gems/PhysX/Code/Source/EditorHingeJointComponent.h +++ b/Gems/PhysX/Code/Source/EditorHingeJointComponent.h @@ -33,6 +33,7 @@ namespace PhysX static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component void Activate() override; diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h index 31f5051ac4..a7a1a92ad2 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterControllerComponent.h @@ -59,6 +59,7 @@ namespace PhysX static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterControllerService", 0x428de4fa)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp index 70373f8db2..d557919627 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/CharacterGameplayComponent.cpp @@ -51,6 +51,7 @@ namespace PhysX void CharacterGameplayComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterGameplayService", 0xfacd7876)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CharacterGameplayComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h index d42c1c9537..cc2a93d0b8 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterControllerComponent.h @@ -64,6 +64,7 @@ namespace PhysX incompatible.push_back(AZ_CRC("PhysXCharacterControllerService", 0x428de4fa)); incompatible.push_back(AZ_CRC("LegacyCryPhysicsService", 0xbb370351)); incompatible.push_back(AZ_CRC("PhysXRigidBodyService", 0x1d4c64a8)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp index 03ff0e0aea..dc67870fb2 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/EditorCharacterGameplayComponent.cpp @@ -23,6 +23,7 @@ namespace PhysX void EditorCharacterGameplayComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("PhysXCharacterGameplayService", 0xfacd7876)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void EditorCharacterGameplayComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h index e7397af877..a02e9c47fb 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h +++ b/Gems/PhysX/Code/Source/PhysXCharacters/Components/RagdollComponent.h @@ -49,6 +49,7 @@ namespace PhysX { incompatible.push_back(AZ_CRC("PhysXRagdollService", 0x6d889c70)); incompatible.push_back(AZ_CRC("LegacyCryPhysicsService", 0xbb370351)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp index 6e2e4be0a2..97bce7631d 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp @@ -75,6 +75,11 @@ namespace WhiteBox required.push_back(AZ_CRC("WhiteBoxService", 0x2f2f42b8)); } + void EditorWhiteBoxColliderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void EditorWhiteBoxColliderComponent::Activate() { AzToolsFramework::Components::EditorComponentBase::Activate(); diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h index 5b46d0b99e..635abbb1bd 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.h @@ -46,6 +46,7 @@ namespace WhiteBox private: static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component ... void Activate() override; diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp index 3179a2cd72..117b175cda 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp @@ -44,6 +44,11 @@ namespace WhiteBox required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); } + void WhiteBoxColliderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + WhiteBoxColliderComponent::WhiteBoxColliderComponent( const Physics::CookedMeshShapeConfiguration& shapeConfiguration, const Physics::ColliderConfiguration& physicsColliderConfiguration, diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h index 1ad773652d..0b50c834d8 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.h @@ -41,6 +41,7 @@ namespace WhiteBox private: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // AZ::Component ... void Activate() override; diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp index d4ab543404..e8e03556e2 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.cpp @@ -265,6 +265,11 @@ namespace WhiteBox provided.push_back(AZ_CRC("WhiteBoxService", 0x2f2f42b8)); } + void EditorWhiteBoxComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + EditorWhiteBoxComponent::EditorWhiteBoxComponent() = default; EditorWhiteBoxComponent::~EditorWhiteBoxComponent() diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h index 02b50a9407..c4dd6c2b0b 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponent.h @@ -89,6 +89,7 @@ namespace WhiteBox private: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // EditorComponentBase overrides ... void BuildGameEntity(AZ::Entity* gameEntity) override; From d0b006c209573e0be961b6bc27fd3bde1cbaf3ad Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 13:41:18 -0700 Subject: [PATCH 29/47] Some cleanup to better support backward reconciliation as well as dynamic player spawning on connect --- Code/CryEngine/CrySystem/SystemInit.cpp | 2 +- Gems/Multiplayer/Code/Include/IMultiplayer.h | 79 +++++++++++++++++-- .../Code/Include/INetworkEntityManager.h | 42 +++++----- Gems/Multiplayer/Code/Include/INetworkTime.h | 34 ++------ .../AutoGen/AutoComponentTypes_Source.jinja | 2 +- .../Source/AutoGen/AutoComponent_Source.jinja | 23 ++++-- .../LocalPredictionPlayerInputComponent.cpp | 6 +- .../Source/MultiplayerSystemComponent.cpp | 73 ++++++++++++----- .../Code/Source/MultiplayerSystemComponent.h | 5 ++ .../EntityReplicationManager.cpp | 2 +- .../EntityReplication/EntityReplicator.cpp | 4 +- .../NetworkEntity/NetworkEntityManager.cpp | 29 +++++-- .../NetworkEntity/NetworkEntityManager.h | 19 +++-- .../Source/NetworkInput/NetworkInputChild.cpp | 2 +- .../NetworkInputMigrationVector.cpp | 2 +- .../Code/Source/NetworkTime/NetworkTime.cpp | 52 ++++++++---- .../Code/Source/NetworkTime/NetworkTime.h | 7 +- .../Source/NetworkTime/RewindableObject.inl | 4 +- .../ServerToClientReplicationWindow.cpp | 2 +- .../ServerToClientReplicationWindow.h | 2 +- 20 files changed, 262 insertions(+), 129 deletions(-) diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 8bf2fb8930..6181fde615 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -1247,7 +1247,7 @@ bool CSystem::InitShine([[maybe_unused]] const SSystemInitParams& initParams) if (!m_env.pLyShine) { - AZ_Error(AZ_TRACE_SYSTEM_WINDOW, false, "LYShine System did not initialize correctly. Please check that the LyShine gem is enabled for this project in ProjectConfigurator."); + AZ_Error(AZ_TRACE_SYSTEM_WINDOW, false, "LYShine System did not initialize correctly. Please check that the LyShine gem is enabled for this project in *_dependencies.cmake."); return false; } return true; diff --git a/Gems/Multiplayer/Code/Include/IMultiplayer.h b/Gems/Multiplayer/Code/Include/IMultiplayer.h index 039b86b2a6..80bdaa68eb 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/IMultiplayer.h @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -46,6 +47,7 @@ namespace Multiplayer using ConnectionAcquiredEvent = AZ::Event; using SessionInitEvent = AZ::Event; using SessionShutdownEvent = AZ::Event; + using OnConnectFunctor = AZStd::function; //! IMultiplayer provides insight into the Multiplayer session and its Agents class IMultiplayer @@ -55,26 +57,30 @@ namespace Multiplayer virtual ~IMultiplayer() = default; - //! Gets the type of Agent this IMultiplayer impl represents + //! Gets the type of Agent this IMultiplayer impl represents. //! @return The type of agents represented virtual MultiplayerAgentType GetAgentType() const = 0; - //! Sets the type of this Multiplayer connection and calls any related callback + //! Sets the type of this Multiplayer connection and calls any related callback. //! @param state The state of this connection virtual void InitializeMultiplayer(MultiplayerAgentType state) = 0; - //! Adds a ConnectionAcquiredEvent Handler which is invoked when a new endpoint connects to the session + //! Adds a ConnectionAcquiredEvent Handler which is invoked when a new endpoint connects to the session. //! @param handler The SessionInitEvent Handler to add virtual void AddConnectionAcquiredHandler(ConnectionAcquiredEvent::Handler& handler) = 0; - //! Adds a SessionInitEvent Handler which is invoked when a new network session starts + //! Adds a SessionInitEvent Handler which is invoked when a new network session starts. //! @param handler The SessionInitEvent Handler to add virtual void AddSessionInitHandler(SessionInitEvent::Handler& handler) = 0; - //! Adds a SessionShutdownEvent Handler which is invoked when the current network session ends + //! Adds a SessionShutdownEvent Handler which is invoked when the current network session ends. //! @param handler The SessionShutdownEvent handler to add virtual void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) = 0; + //! Overrides the default connect behaviour with the provided functor. + //! @param functor the function to invoke during a new connection event + virtual void SetOnConnectFunctor(const OnConnectFunctor& functor) = 0; + //! Sends a packet telling if entity update messages can be sent //! @param readyForEntityUpdates Ready for entity updates or not virtual void SendReadyForEntityUpdates(bool readyForEntityUpdates) = 0; @@ -87,6 +93,14 @@ namespace Multiplayer //! @return the current server time in milliseconds virtual AZ::TimeMs GetCurrentHostTimeMs() const = 0; + //! Returns the network time instance bound to this multiplayer instance. + //! @return pointer to the network time instance bound to this multiplayer instance + virtual INetworkTime* GetNetworkTime() = 0; + + //! Returns the network entity manager instance bound to this multiplayer instance. + //! @return pointer to the network entity manager instance bound to this multiplayer instance + virtual INetworkEntityManager* GetNetworkEntityManager() = 0; + //! Returns the gem name associated with the provided component index. //! @param netComponentId the componentId to return the gem name of //! @return the name of the gem that contains the requested component @@ -117,6 +131,61 @@ namespace Multiplayer MultiplayerStats m_stats; }; + // Convenience helpers + inline IMultiplayer* GetMultiplayer() + { + return AZ::Interface::Get(); + } + + inline INetworkTime* GetNetworkTime() + { + return GetMultiplayer()->GetNetworkTime(); + } + + inline INetworkEntityManager* GetNetworkEntityManager() + { + return GetMultiplayer()->GetNetworkEntityManager(); + } + + inline NetworkEntityTracker* GetNetworkEntityTracker() + { + return GetNetworkEntityManager()->GetNetworkEntityTracker(); + } + + inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() + { + return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); + } + + inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() + { + return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); + } + + //! @class ScopedAlterTime + //! @brief This is a wrapper that temporarily adjusts global program time for backward reconciliation purposes. + class ScopedAlterTime final + { + public: + inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId connectionId) + { + INetworkTime* time = GetNetworkTime(); + m_previousHostFrameId = time->GetHostFrameId(); + m_previousHostTimeMs = time->GetHostTimeMs(); + m_previousRewindConnectionId = time->GetRewindingConnectionId(); + time->AlterTime(frameId, timeMs, connectionId); + } + inline ~ScopedAlterTime() + { + INetworkTime* time = GetNetworkTime(); + time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); + } + private: + HostFrameId m_previousHostFrameId = InvalidHostFrameId; + AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; + AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; + }; + inline const char* GetEnumString(MultiplayerAgentType value) { switch (value) diff --git a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h b/Gems/Multiplayer/Code/Include/INetworkEntityManager.h index d9b611ece0..ebb95e2281 100644 --- a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Include/INetworkEntityManager.h @@ -59,9 +59,24 @@ namespace Multiplayer //! Creates new entities of the given archetype //! @param prefabEntryId the name of the spawnable to spawn - virtual EntityList CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, AutoActivate autoActivate, - const AZ::Transform& transform) = 0; + virtual EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) = 0; + + //! Creates new entities of the given archetype + //! This interface is internally used to spawn replicated entities + //! @param prefabEntryId the name of the spawnable to spawn + virtual EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) = 0; //! Returns an ConstEntityPtr for the provided entityId. //! @param netEntityId the netEntityId to get an ConstEntityPtr for @@ -134,25 +149,4 @@ namespace Multiplayer //! @param entityRpcMessage the local rpc message to handle virtual void HandleLocalRpcMessage(NetworkEntityRpcMessage& message) = 0; }; - - // Convenience helpers - inline INetworkEntityManager* GetNetworkEntityManager() - { - return AZ::Interface::Get(); - } - - inline NetworkEntityTracker* GetNetworkEntityTracker() - { - return GetNetworkEntityManager()->GetNetworkEntityTracker(); - } - - inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() - { - return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); - } - - inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() - { - return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); - } } diff --git a/Gems/Multiplayer/Code/Include/INetworkTime.h b/Gems/Multiplayer/Code/Include/INetworkTime.h index 5346a0e0d0..1ccf08bbdc 100644 --- a/Gems/Multiplayer/Code/Include/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/INetworkTime.h @@ -47,9 +47,6 @@ namespace Multiplayer //! @return the hosts current timeMs virtual AZ::TimeMs GetHostTimeMs() const = 0; - //! Synchronizes rewindable entity state for the current application time. - virtual void SyncRewindableEntityState() = 0; - //! Get the controlling connection that may be currently altering global game time. //! Note this abstraction is required at a relatively high level to allow for 'don't rewind the shooter' semantics //! @return the ConnectionId of the connection requesting the rewind operation @@ -67,6 +64,13 @@ namespace Multiplayer //! @param rewindConnectionId the rewinding ConnectionId virtual void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) = 0; + //! Syncs all entities contained within a volume to the current rewind state. + //! @param rewindVolume the volume to rewind entities within (needed for physics entities) + virtual void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) = 0; + + //! Restores all rewound entities to the current application time. + virtual void ClearRewoundEntities() = 0; + AZ_DISABLE_COPY_MOVE(INetworkTime); }; @@ -79,28 +83,4 @@ namespace Multiplayer static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; }; using INetworkTimeRequestBus = AZ::EBus; - - //! @class ScopedAlterTime - //! @brief This is a wrapper that temporarily adjusts global program time for backward reconciliation purposes. - class ScopedAlterTime final - { - public: - inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId connectionId) - { - INetworkTime* time = AZ::Interface::Get(); - m_previousHostFrameId = time->GetHostFrameId(); - m_previousHostTimeMs = time->GetHostTimeMs(); - m_previousRewindConnectionId = time->GetRewindingConnectionId(); - time->AlterTime(frameId, timeMs, connectionId); - } - inline ~ScopedAlterTime() - { - INetworkTime* time = AZ::Interface::Get(); - time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); - } - private: - HostFrameId m_previousHostFrameId = InvalidHostFrameId; - AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; - AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; - }; } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja index 2bae618d94..2acc252729 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja @@ -22,7 +22,7 @@ namespace {{ Namespace }} void RegisterMultiplayerComponents() { Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = GetMultiplayerComponentRegistry(); - Multiplayer::MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + Multiplayer::MultiplayerStats& stats = GetMultiplayer()->GetStats(); {% for Component in dataFiles %} {% set ComponentName = Component.attrib['Name'] %} {% set ComponentBaseName = ComponentName %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 6e54ec3d58..d719cbe47b 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -476,7 +476,7 @@ bool {{ ClassName }}::Serialize{{ AutoComponentMacros.GetNetPropertiesSetName(Re {%- if networkPropertyCount.update({'value': networkPropertyCount.value + 1}) %}{% endif -%} {% endcall %} {% if networkPropertyCount.value > 0 %} - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = GetMultiplayer()->GetStats(); // We modify the record if we are writing an update so that we don't notify for a change that really didn't change the value (just a duplicated send from the server) [[maybe_unused]] bool modifyRecord = serializer.GetSerializerMode() == AzNetworking::SerializerMode::WriteToObject; {% call(Property) AutoComponentMacros.ParseNetworkProperties(Component, ReplicateFrom, ReplicateTo) %} @@ -1141,16 +1141,23 @@ namespace {{ Component.attrib['Namespace'] }} AZ::EditContext* editContext = serializeContext->GetEditContext(); if (editContext) { - editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") + editContext->Class<{{ ComponentBaseName }}>("{{ ComponentBaseName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) - {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Client', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Autonomous', ComponentName)|indent(20) -}} -{{ DefineNetworkPropertyEditReflection(Component, 'Autonomous', 'Authority', ComponentName)|indent(20) }} - {{ DefineArchetypePropertyEditReflection(Component, ComponentName)|indent(20) }}; + {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Client', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Autonomous', ComponentBaseName)|indent(20) -}} +{{ DefineNetworkPropertyEditReflection(Component, 'Autonomous', 'Authority', ComponentBaseName)|indent(20) }} + {{ DefineArchetypePropertyEditReflection(Component, ComponentBaseName)|indent(20) }}; +{% if ComponentDerived %} + + editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")); +{% endif %} } } } diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 90b590d99d..b57c465df2 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -94,7 +94,7 @@ namespace Multiplayer if (entityIsMigrating == EntityIsMigrating::True) { m_allowMigrateClientInput = true; - m_serverMigrateFrameId = AZ::Interface::Get()->GetHostFrameId(); + m_serverMigrateFrameId = GetNetworkTime()->GetHostFrameId(); } } @@ -492,8 +492,8 @@ namespace Multiplayer const uint32_t maxClientInputs = inputRate > 0.0 ? static_cast(maxRewindHistory / inputRate) : 0; - INetworkTime* networkTime = AZ::Interface::Get(); - IMultiplayer* multiplayer = AZ::Interface::Get(); + IMultiplayer* multiplayer = GetMultiplayer(); + INetworkTime* networkTime = GetNetworkTime(); while (m_moveAccumulator >= inputRate) { m_moveAccumulator -= inputRate; diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index e6fb77eca7..590faa6bad 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -23,6 +23,9 @@ #include #include #include +#include +#include +#include namespace AZ::ConsoleTypeHelpers { @@ -69,6 +72,7 @@ namespace Multiplayer AZ_CVAR(ProtocolType, sv_protocol, ProtocolType::Udp, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "This flag controls whether we use TCP or UDP for game networking"); AZ_CVAR(bool, sv_isDedicated, true, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Whether the host command creates an independent or client hosted server"); AZ_CVAR(AZ::TimeMs, cl_defaultNetworkEntityActivationTimeSliceMs, AZ::TimeMs{ 0 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Max Ms to use to activate entities coming from the network, 0 means instantiate everything"); + AZ_CVAR(AZ::CVarFixedString, sv_defaultPlayerSpawnAsset, "prefabs/player.network.spawnable", nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "The default spawnable to use when a new player connects"); void MultiplayerSystemComponent::Reflect(AZ::ReflectContext* context) { @@ -411,6 +415,11 @@ namespace Multiplayer void MultiplayerSystemComponent::OnConnect(AzNetworking::IConnection* connection) { + MultiplayerAgentDatum datum; + datum.m_id = connection->GetConnectionId(); + datum.m_isInvited = false; + datum.m_agentType = MultiplayerAgentType::Client; + if (connection->GetConnectionRole() == ConnectionRole::Connector) { AZLOG_INFO("New outgoing connection to remote address: %s", connection->GetRemoteAddress().GetString().c_str()); @@ -419,36 +428,45 @@ namespace Multiplayer else { AZLOG_INFO("New incoming connection from remote address: %s", connection->GetRemoteAddress().GetString().c_str()); - MultiplayerAgentDatum datum; - datum.m_id = connection->GetConnectionId(); - datum.m_isInvited = false; - datum.m_agentType = MultiplayerAgentType::Client; m_connAcquiredEvent.Signal(datum); } - if (GetAgentType() == MultiplayerAgentType::ClientServer - || GetAgentType() == MultiplayerAgentType::DedicatedServer) + if (m_onConnectFunctor) { - // TODO: This needs to be set to the players autonomous proxy ------------v - NetworkEntityHandle controlledEntity = GetNetworkEntityTracker()->Get(NetEntityId{ 0 }); - if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so - { - connection->SetUserData(new ServerToClientConnectionData(connection, *this, controlledEntity)); - } - - AZStd::unique_ptr window = AZStd::make_unique(controlledEntity, connection); - reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetReplicationWindow(AZStd::move(window)); } else { - if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + if (GetAgentType() == MultiplayerAgentType::ClientServer + || GetAgentType() == MultiplayerAgentType::DedicatedServer) { - connection->SetUserData(new ClientToServerConnectionData(connection, *this)); - } + PrefabEntityId playerPrefabEntityId(AZ::Name(static_cast(sv_defaultPlayerSpawnAsset).c_str()), 1); + INetworkEntityManager::EntityList entityList = m_networkEntityManager.CreateEntitiesImmediate(playerPrefabEntityId, NetEntityRole::Authority, AZ::Transform::CreateIdentity()); - AZStd::unique_ptr window = AZStd::make_unique(); - reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetEntityActivationTimeSliceMs(cl_defaultNetworkEntityActivationTimeSliceMs); + NetworkEntityHandle controlledEntity; + if (entityList.size() > 0) + { + controlledEntity = entityList[0]; + } + + if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + { + connection->SetUserData(new ServerToClientConnectionData(connection, *this, controlledEntity)); + } + + AZStd::unique_ptr window = AZStd::make_unique(controlledEntity, connection); + reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetReplicationWindow(AZStd::move(window)); + } + else + { + if (connection->GetUserData() == nullptr) // Only add user data if the connect event handler has not already done so + { + connection->SetUserData(new ClientToServerConnectionData(connection, *this)); + } + + AZStd::unique_ptr window = AZStd::make_unique(); + reinterpret_cast(connection->GetUserData())->GetReplicationManager().SetEntityActivationTimeSliceMs(cl_defaultNetworkEntityActivationTimeSliceMs); + } } } @@ -521,6 +539,11 @@ namespace Multiplayer handler.Connect(m_shutdownEvent); } + void MultiplayerSystemComponent::SetOnConnectFunctor(const OnConnectFunctor& functor) + { + m_onConnectFunctor = functor; + } + void MultiplayerSystemComponent::SendReadyForEntityUpdates(bool readyForEntityUpdates) { IConnectionSet& connectionSet = m_networkInterface->GetConnectionSet(); @@ -542,6 +565,16 @@ namespace Multiplayer } } + INetworkTime* MultiplayerSystemComponent::GetNetworkTime() + { + return &m_networkTime; + } + + INetworkEntityManager* MultiplayerSystemComponent::GetNetworkEntityManager() + { + return &m_networkEntityManager; + } + const char* MultiplayerSystemComponent::GetComponentGemName(NetComponentId netComponentId) const { return GetMultiplayerComponentRegistry()->GetComponentGemName(netComponentId); diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index 477745e6b5..1de8fccb50 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -89,8 +89,11 @@ namespace Multiplayer void AddConnectionAcquiredHandler(ConnectionAcquiredEvent::Handler& handler) override; void AddSessionInitHandler(SessionInitEvent::Handler& handler) override; void AddSessionShutdownHandler(SessionShutdownEvent::Handler& handler) override; + void SetOnConnectFunctor(const OnConnectFunctor& functor) override; void SendReadyForEntityUpdates(bool readyForEntityUpdates) override; AZ::TimeMs GetCurrentHostTimeMs() const override; + INetworkTime* GetNetworkTime() override; + INetworkEntityManager* GetNetworkEntityManager() override; const char* GetComponentGemName(NetComponentId netComponentId) const override; const char* GetComponentName(NetComponentId netComponentId) const override; const char* GetComponentPropertyName(NetComponentId netComponentId, PropertyIndex propertyIndex) const override; @@ -121,6 +124,8 @@ namespace Multiplayer SessionShutdownEvent m_shutdownEvent; ConnectionAcquiredEvent m_connAcquiredEvent; + OnConnectFunctor m_onConnectFunctor = nullptr; + AZ::TimeMs m_lastReplicatedHostTimeMs = AZ::TimeMs{ 0 }; HostFrameId m_lastReplicatedHostFrameId = InvalidHostFrameId; }; diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 1e7649f561..65df4f1464 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -824,7 +824,7 @@ namespace Multiplayer { if (entityReplicator == nullptr) { - IMultiplayer* multiplayer = AZ::Interface::Get(); + IMultiplayer* multiplayer = GetMultiplayer(); AZLOG_INFO ( "EntityReplicationManager: Dropping remote RPC message for component %s of rpc index %s, entityId %u has already been deleted", diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 7431b95a22..197d83a48c 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -448,7 +448,7 @@ namespace Multiplayer void EntityReplicator::DeferRpcMessage(NetworkEntityRpcMessage& entityRpcMessage) { // Received rpc metrics, log rpc sent, number of bytes, and the componentId/rpcId for bandwidth metrics - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = GetMultiplayer()->GetStats(); stats.RecordRpcSent(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); m_replicationManager.AddDeferredRpcMessage(entityRpcMessage); @@ -631,7 +631,7 @@ namespace Multiplayer bool EntityReplicator::HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetworkEntityRpcMessage& entityRpcMessage) { // Received rpc metrics, log rpc received, time spent, number of bytes, and the componentId/rpcId for bandwidth metrics - MultiplayerStats& stats = AZ::Interface::Get()->GetStats(); + MultiplayerStats& stats = GetMultiplayer()->GetStats(); stats.RecordRpcReceived(entityRpcMessage.GetComponentId(), entityRpcMessage.GetRpcIndex(), entityRpcMessage.GetEstimatedSerializeSize()); if (!m_netBindComponent) diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 1c7fb5f7af..7ee4d45e93 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -38,7 +38,6 @@ namespace Multiplayer , m_onSpawnedHandler([this](AZ::Data::Asset spawnable) { this->OnSpawned(spawnable); }) , m_onDespawnedHandler([this](AZ::Data::Asset spawnable) { this->OnDespawned(spawnable); }) { - AZ::Interface::Register(this); AzFramework::RootSpawnableNotificationBus::Handler::BusConnect(); AzFramework::SpawnableEntitiesInterface::Get()->AddOnSpawnedHandler(m_onSpawnedHandler); @@ -48,7 +47,6 @@ namespace Multiplayer NetworkEntityManager::~NetworkEntityManager() { AzFramework::RootSpawnableNotificationBus::Handler::BusDisconnect(); - AZ::Interface::Unregister(this); } void NetworkEntityManager::Initialize(HostId hostId, AZStd::unique_ptr entityDomain) @@ -365,9 +363,24 @@ namespace Multiplayer return returnList; } - INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, - AutoActivate autoActivate, const AZ::Transform& transform) + INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) + { + return CreateEntitiesImmediate(prefabEntryId, NextId(), netEntityRole, AutoActivate::Activate, transform); + } + + INetworkEntityManager::EntityList NetworkEntityManager::CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) { INetworkEntityManager::EntityList returnList; @@ -436,7 +449,7 @@ namespace Multiplayer void NetworkEntityManager::OnRootSpawnableAssigned( [[maybe_unused]] AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) { - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); if (agentType == MultiplayerAgentType::Client) @@ -448,7 +461,7 @@ namespace Multiplayer void NetworkEntityManager::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation) { // TODO: Do we need to clear all entities here? - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); if (agentType == MultiplayerAgentType::Client) @@ -494,7 +507,7 @@ namespace Multiplayer return; } - auto* multiplayer = AZ::Interface::Get(); + auto* multiplayer = GetMultiplayer(); const auto agentType = multiplayer->GetAgentType(); const bool spawnImmediately = diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index ae2cb0dd9e..ba71eaf780 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -47,10 +47,20 @@ namespace Multiplayer ConstNetworkEntityHandle GetEntity(NetEntityId netEntityId) const override; EntityList CreateEntitiesImmediate(const AzFramework::Spawnable& spawnable, NetEntityRole netEntityRole); - - EntityList CreateEntitiesImmediate( - const PrefabEntityId& prefabEntryId, NetEntityId netEntityId, NetEntityRole netEntityRole, - AutoActivate autoActivate, const AZ::Transform& transform) override; + EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityRole netEntityRole, + const AZ::Transform& transform + ) override; + EntityList CreateEntitiesImmediate + ( + const PrefabEntityId& prefabEntryId, + NetEntityId netEntityId, + NetEntityRole netEntityRole, + AutoActivate autoActivate, + const AZ::Transform& transform + ) override; uint32_t GetEntityCount() const override; NetworkEntityHandle AddEntityToEntityMap(NetEntityId netEntityId, AZ::Entity* entity) override; @@ -81,7 +91,6 @@ namespace Multiplayer private: void RemoveEntities(); - NetEntityId NextId(); void OnSpawned(AZ::Data::Asset spawnable); diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp index 8f70f7e1fa..114c3e3b43 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp index dee72156ed..c6eed626a9 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index 9a0e784d36..c0200c9e6d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -11,19 +11,12 @@ */ #include +#include +#include +#include namespace Multiplayer { - NetworkTime::NetworkTime() - { - AZ::Interface::Register(this); - } - - NetworkTime::~NetworkTime() - { - AZ::Interface::Unregister(this); - } - bool NetworkTime::IsTimeRewound() const { return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; @@ -51,11 +44,6 @@ namespace Multiplayer return m_hostTimeMs; } - void NetworkTime::SyncRewindableEntityState() - { - - } - AzNetworking::ConnectionId NetworkTime::GetRewindingConnectionId() const { return m_rewindingConnectionId; @@ -72,4 +60,38 @@ namespace Multiplayer m_hostTimeMs = timeMs; m_rewindingConnectionId = rewindConnectionId; } + + void NetworkTime::SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) + { + // TODO: extrude rewind volume for initial gather + AZStd::vector gatheredEntries; + AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(rewindVolume, [&gatheredEntries](const AzFramework::IVisibilityScene::NodeData& nodeData) + { + gatheredEntries.reserve(gatheredEntries.size() + nodeData.m_entries.size()); + for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) + { + if (visEntry->m_typeFlags & AzFramework::VisibilityEntry::TypeFlags::TYPE_Entity) + { + // TODO: offset aabb for exact rewound position and check against the non-extruded rewind volume + gatheredEntries.push_back(visEntry); + } + } + }); + + for (AzFramework::VisibilityEntry* visEntry : gatheredEntries) + { + AZ::Entity* entity = static_cast(visEntry->m_userData); + [[maybe_unused]] NetBindComponent* entryNetBindComponent = entity->template FindComponent(); + if (entryNetBindComponent != nullptr) + { + // TODO: invoke the sync to rewind event on the netBindComponent and add the entity to the rewound entity set + } + } + } + + void NetworkTime::ClearRewoundEntities() + { + AZ_Assert(!IsTimeRewound(), "Cannot clear rewound entity state while still within scoped rewind"); + // TODO: iterate all rewound entities, signal them to sync rewind state, and clear the rewound entity set + } } diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 06e758b349..47f557a11f 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -23,8 +23,8 @@ namespace Multiplayer : public INetworkTime { public: - NetworkTime(); - virtual ~NetworkTime(); + NetworkTime() = default; + virtual ~NetworkTime() = default; //! INetworkTime overrides. //! @{ @@ -33,10 +33,11 @@ namespace Multiplayer HostFrameId GetUnalteredHostFrameId() const override; void IncrementHostFrameId() override; AZ::TimeMs GetHostTimeMs() const override; - void SyncRewindableEntityState() override; AzNetworking::ConnectionId GetRewindingConnectionId() const override; HostFrameId GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const override; void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) override; + void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) override; + void ClearRewoundEntities() override; //! @} private: diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl index 0835421ebd..2e67d42ede 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl @@ -47,7 +47,7 @@ namespace Multiplayer template inline RewindableObject &RewindableObject::operator =(const RewindableObject& rhs) { - INetworkTime* networkTime = AZ::Interface::Get(); + INetworkTime* networkTime = GetNetworkTime(); SetValueForTime(rhs.GetValueForTime(networkTime->GetHostFrameId()), GetCurrentTimeForProperty()); return *this; } @@ -115,7 +115,7 @@ namespace Multiplayer template inline HostFrameId RewindableObject::GetCurrentTimeForProperty() const { - INetworkTime* networkTime = AZ::Interface::Get(); + INetworkTime* networkTime = GetNetworkTime(); return networkTime->GetHostFrameIdForRewindingConnection(m_owningConnectionId); } diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp index c54a610de2..a51bdc4acc 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp @@ -65,7 +65,7 @@ namespace Multiplayer { AZ::Entity* entity = m_controlledEntity.GetEntity(); AZ_Assert(entity, "Invalid controlled entity provided to replication window"); - m_controlledEntityTransform = entity->GetTransform(); + m_controlledEntityTransform = entity ? entity->GetTransform() : nullptr; AZ_Assert(m_controlledEntityTransform, "Controlled player entity must have a transform"); //// this one is optional diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h index 55a6a4b56e..b4e4427945 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include From 293e0057f4c0a74642e331dd052b3ae0d0468264 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 13:58:53 -0700 Subject: [PATCH 30/47] Actually invoke the override OnConnect handler --- Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 590faa6bad..15b6b48631 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -433,7 +433,8 @@ namespace Multiplayer if (m_onConnectFunctor) { - + // Default OnConnect behaviour has been overridden, + m_onConnectFunctor(connection, datum); } else { From 655d71e0ddfd69834537da5e2febd1f8a40fc59f Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 12 May 2021 22:16:14 +0100 Subject: [PATCH 31/47] update compatibility of atom components with NonUniformScaleService --- .../Atom/Component/DebugCamera/CameraControllerComponent.h | 3 ++- .../Component/DebugCamera/Code/Source/CameraComponent.cpp | 1 + .../DebugCamera/Code/Source/CameraControllerComponent.cpp | 7 ++++++- .../AtomBridge/Code/Source/FlyCameraInputComponent.cpp | 6 ++++++ .../AtomBridge/Code/Source/FlyCameraInputComponent.h | 1 + .../Code/Source/Animation/AttachmentComponent.h | 1 + .../CoreLights/DirectionalLightComponentController.cpp | 1 + .../DiffuseProbeGridComponentController.cpp | 1 + .../ReflectionProbe/ReflectionProbeComponentController.cpp | 1 + .../Code/Source/SkyBox/HDRiSkyboxComponentController.cpp | 1 + .../Code/Source/SkyBox/PhysicalSkyComponentController.cpp | 1 + 11 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h b/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h index 4b2b19cff0..225952302a 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h +++ b/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraControllerComponent.h @@ -41,7 +41,8 @@ namespace AZ static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + // CameraControllerRequestBus::Handler overrides void Enable(TypeId typeId) override final; void Reset() override final; diff --git a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp index fbda0924e6..cbaa70929c 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp +++ b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp @@ -69,6 +69,7 @@ namespace AZ void CameraComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("CameraService", 0x1dd1caa4)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void CameraComponent::Activate() diff --git a/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp b/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp index 69e8469a56..e5a88dd409 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp +++ b/Gems/Atom/Component/DebugCamera/Code/Source/CameraControllerComponent.cpp @@ -32,12 +32,17 @@ namespace AZ required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); required.push_back(AZ_CRC("CameraService", 0x1dd1caa4)); } - + void CameraControllerComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) { provided.push_back(AZ_CRC("CameraControllerService", 0xc35788f9)); } + void CameraControllerComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + void CameraControllerComponent::Enable(TypeId typeId) { // Enable this controller if type id matches, otherwise disable this controller diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp index 54e3a6ce59..3ad8bbae99 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp @@ -78,6 +78,12 @@ void FlyCameraInputComponent::GetProvidedServices(AZ::ComponentDescriptor::Depen provided.push_back(AZ_CRC("InputService", 0xd41af40c)); } +////////////////////////////////////////////////////////////////////////////// +void FlyCameraInputComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) +{ + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); +} + ////////////////////////////////////////////////////////////////////////////// void FlyCameraInputComponent::Reflect(AZ::ReflectContext* reflection) { diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h index 03fb3c421e..6c0232f358 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.h @@ -30,6 +30,7 @@ namespace AZ public: static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); static void Reflect(AZ::ReflectContext* reflection); AZ_COMPONENT(FlyCameraInputComponent, "{7AE0D6AD-691C-41B6-9DD5-F23F78B1A02E}"); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h index ac03663f22..855c5494b3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h @@ -163,6 +163,7 @@ namespace AZ static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("AttachmentService", 0x5aaa7b63)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp index 310e6e6eca..6bff558268 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp @@ -121,6 +121,7 @@ namespace AZ void DirectionalLightComponentController::GetIncompatibleServices(ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("DirectionalLightService", 0x5270619f)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleComponent")); } void DirectionalLightComponentController::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp index 8a0bd86965..0ddace1f87 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/DiffuseProbeGrid/DiffuseProbeGridComponentController.cpp @@ -73,6 +73,7 @@ namespace AZ void DiffuseProbeGridComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("DiffuseProbeGridService", 0x63d32042)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void DiffuseProbeGridComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp index 91040885f1..9b0ff29bb8 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp @@ -80,6 +80,7 @@ namespace AZ void ReflectionProbeComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("ReflectionProbeService", 0xa5b919ce)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void ReflectionProbeComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp index f343a68f79..2c44124564 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/HDRiSkyboxComponentController.cpp @@ -51,6 +51,7 @@ namespace AZ void HDRiSkyboxComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("SkyBoxService", 0x8169a709)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void HDRiSkyboxComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp index 867a81eefe..4a6b1608a4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/SkyBox/PhysicalSkyComponentController.cpp @@ -58,6 +58,7 @@ namespace AZ void PhysicalSkyComponentController::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { incompatible.push_back(AZ_CRC("SkyBoxService", 0x8169a709)); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void PhysicalSkyComponentController::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) From 50abafbab1bc0033395654c7491bfd3c2720d441 Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Wed, 12 May 2021 14:31:39 -0700 Subject: [PATCH 32/47] Add orchestrating script to install ubuntu packages for O3DE on Linux (#721) SPEC-3510: Linux environment setup scripts * Add orchestrating script to install ubuntu packages for O3DE on Linux * Fix issue parsing package content file for build-tools --- .../Platform/Linux/install-ubuntu-awscli.sh | 2 +- .../Linux/install-ubuntu-build-tools.sh | 21 ++++---- .../Platform/Linux/install-ubuntu-git.sh | 8 ++-- .../Platform/Linux/install-ubuntu.sh | 48 +++++++++++++++++++ 4 files changed, 64 insertions(+), 15 deletions(-) create mode 100755 scripts/build/build_node/Platform/Linux/install-ubuntu.sh diff --git a/scripts/build/build_node/Platform/Linux/install-ubuntu-awscli.sh b/scripts/build/build_node/Platform/Linux/install-ubuntu-awscli.sh index 4c2f350859..8649f61fd1 100755 --- a/scripts/build/build_node/Platform/Linux/install-ubuntu-awscli.sh +++ b/scripts/build/build_node/Platform/Linux/install-ubuntu-awscli.sh @@ -38,7 +38,7 @@ then ./aws/install rm -rf ./aws else - AWS_CLI_VERSION=`aws --version | awk '{print $1}' | awk -F/ '{print $2}'` + AWS_CLI_VERSION=$(aws --version | awk '{print $1}' | awk -F/ '{print $2}') echo AWS CLI \(version $AWS_CLI_VERSION\) already installed fi diff --git a/scripts/build/build_node/Platform/Linux/install-ubuntu-build-tools.sh b/scripts/build/build_node/Platform/Linux/install-ubuntu-build-tools.sh index fd7b59592a..6fea3b03fa 100755 --- a/scripts/build/build_node/Platform/Linux/install-ubuntu-build-tools.sh +++ b/scripts/build/build_node/Platform/Linux/install-ubuntu-build-tools.sh @@ -26,7 +26,7 @@ then exit 1 fi -UBUNTU_DISTRO="`lsb_release -c | awk '{print $2}'`" +UBUNTU_DISTRO="$(lsb_release -c | awk '{print $2}')" if [ "$UBUNTU_DISTRO" == "bionic" ] then echo "Setup for Ubuntu 18.04 LTS ($UBUNTU_DISTRO)" @@ -53,7 +53,7 @@ fi # will install it from the bionic distro manually into focal. This is needed since Ubuntu 20.04 supports # python 3.8 out of the box, but we are using 3.7 # -LIBFFI6_COUNT=`apt list --installed 2>/dev/null | grep libffi6 | wc -l` +LIBFFI6_COUNT=$(apt list --installed 2>/dev/null | grep libffi6 | wc -l) if [ "$UBUNTU_DISTRO" == "focal" ] && [ $LIBFFI6_COUNT -eq 0 ] then echo "Installing libffi for Ubuntu 20.04" @@ -90,7 +90,7 @@ fi # Add the kitware repository for cmake if necessary # -KITWARE_REPO_COUNT=`cat /etc/apt/sources.list | grep ^deb | grep https://apt.kitware.com/ubuntu/ | wc -l` +KITWARE_REPO_COUNT=$(cat /etc/apt/sources.list | grep ^deb | grep https://apt.kitware.com/ubuntu/ | wc -l) if [ $KITWARE_REPO_COUNT -eq 0 ] then @@ -121,33 +121,34 @@ PACKAGE_FILE_LIST=package-list.ubuntu-$UBUNTU_DISTRO.txt echo Reading package list $PACKAGE_FILE_LIST # Read each line (strip out comment tags) -for LINE in `cat $PACKAGE_FILE_LIST | sed 's/#.*$//g'` +for PREPROC_LINE in $(cat $PACKAGE_FILE_LIST | sed 's/#.*$//g') do - PACKAGE=`echo $LINE | awk -F / '{print $1}'` + LINE=$(echo $PREPROC_LINE | tr -d '\r\n') + PACKAGE=$(echo $LINE | awk -F / '{$1=$1;print $1}') if [ "$PACKAGE" != "" ] # Skip blank lines then - PACKAGE_VER=`echo $LINE | awk -F / '{print $2}'` + PACKAGE_VER=$(echo $LINE | awk -F / '{$2=$2;print $2}') if [ "$PACKAGE_VER" == "" ] then # Process non-versioned packages - INSTALLED_COUNT=`apt list --installed 2>/dev/null | grep ^$PACKAGE/ | wc -l` + INSTALLED_COUNT=$(apt list --installed 2>/dev/null | grep ^$PACKAGE/ | wc -l) if [ $INSTALLED_COUNT -eq 0 ] then echo Installing $PACKAGE apt-get install $PACKAGE -y else - INSTALLED_VERSION=`apt list --installed 2>/dev/null | grep ^$PACKAGE/ | awk '{print $2}'` + INSTALLED_VERSION=$(apt list --installed 2>/dev/null | grep ^$PACKAGE/ | awk '{print $2}') echo $PACKAGE already installed \(version $INSTALLED_VERSION\) fi else # Process versioned packages - INSTALLED_COUNT=`apt list --installed 2>/dev/null | grep ^$PACKAGE/ | wc -l` + INSTALLED_COUNT=$(apt list --installed 2>/dev/null | grep ^$PACKAGE/ | wc -l) if [ $INSTALLED_COUNT -eq 0 ] then echo Installing $PACKAGE \( $PACKAGE_VER \) apt-get install $PACKAGE=$PACKAGE_VER -y else - INSTALLED_VERSION=`apt list --installed 2>/dev/null | grep ^$PACKAGE/ | awk '{print $2}'` + INSTALLED_VERSION=$(apt list --installed 2>/dev/null | grep ^$PACKAGE/ | awk '{print $2}') if [ "$INSTALLED_VERSION" != "$PACKAGE_VER" ] then echo $PACKAGE already installed but with the wrong version. Purging the package diff --git a/scripts/build/build_node/Platform/Linux/install-ubuntu-git.sh b/scripts/build/build_node/Platform/Linux/install-ubuntu-git.sh index 53554f4175..028b0082d7 100755 --- a/scripts/build/build_node/Platform/Linux/install-ubuntu-git.sh +++ b/scripts/build/build_node/Platform/Linux/install-ubuntu-git.sh @@ -26,7 +26,7 @@ then exit 1 fi -UBUNTU_DISTRO="`lsb_release -c | awk '{print $2}'`" +UBUNTU_DISTRO="$(lsb_release -c | awk '{print $2}')" if [ "$UBUNTU_DISTRO" == "bionic" ] then echo "Setup for Ubuntu 18.04 LTS ($UBUNTU_DISTRO)" @@ -49,14 +49,14 @@ then apt-get update apt-get install git -y else - GIT_VERSION=`git --version | awk '{print $3}'` + GIT_VERSION=$(git --version | awk '{print $3}') echo Git $GIT_VERSION already Installed. Skipping Git installation fi # # Setup Git-LFS if needed # -GIT_LFS_PACKAGE_COUNT=`apt list --installed 2>/dev/null | grep git-lfs/ | wc -l` +GIT_LFS_PACKAGE_COUNT=$(apt list --installed 2>/dev/null | grep git-lfs/ | wc -l) if [ $GIT_LFS_PACKAGE_COUNT -eq 0 ] then echo Setting up Git-LFS @@ -87,7 +87,7 @@ then dpkg -i $GCM_PACKAGE_NAME popd else - GCM_VERSION=`git-credential-manager-core --version` + GCM_VERSION=$(git-credential-manager-core --version) echo Git Credential Manager \(GCM\) version $GCM_VERSION already installed. Skipping GCM installation fi diff --git a/scripts/build/build_node/Platform/Linux/install-ubuntu.sh b/scripts/build/build_node/Platform/Linux/install-ubuntu.sh new file mode 100755 index 0000000000..9cdc94fa9e --- /dev/null +++ b/scripts/build/build_node/Platform/Linux/install-ubuntu.sh @@ -0,0 +1,48 @@ +#!/bin/bash + +# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +# its licensors. +# +# For complete copyright and license terms please see the LICENSE at the root of this +# distribution (the "License"). All use of this software is governed by the License, +# or, if provided, by the license below or the license accompanying this file. Do not +# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +# This script must be run as root +if [[ $EUID -ne 0 ]] +then + echo "This script must be run as root (sudo)" + exit 1 +fi + +echo Installing packages and tools for O3DE development + +# Install awscli +./install-ubuntu-awscli.sh +if [ $? -ne 0 ] +then + echo Error installing AWSCLI + exit 1 +fi + + +# Install git +./install-ubuntu-git.sh +if [ $? -ne 0 ] +then + echo Error installing Git + exit 1 +fi + +# Install the necessary build tools +./install-ubuntu-build-tools.sh +if [ $? -ne 0 ] +then + echo Error installing ubuntu tools + exit 1 +fi + + +echo Packages and tools for O3DE setup complete +exit 0 From 9b1f4c04e65e8ae29053d1070eacc67a18be7768 Mon Sep 17 00:00:00 2001 From: mriegger Date: Wed, 12 May 2021 14:54:33 -0700 Subject: [PATCH 33/47] Removing the old hack code --- .../Code/Source/Decals/AsyncLoadTracker.h | 18 ++++++++++-------- .../DecalTextureArrayFeatureProcessor.cpp | 18 +++++------------- .../Decals/DecalTextureArrayFeatureProcessor.h | 3 --- 3 files changed, 15 insertions(+), 24 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h b/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h index ec35c4b51f..a3fff7b91e 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/AsyncLoadTracker.h @@ -23,7 +23,9 @@ namespace AZ { public: - void TrackAssetLoad(const FeatureProcessorHandle handle, const AZ::Data::AssetId asset) + using MaterialAssetPtr = AZ::Data::Asset; + + void TrackAssetLoad(const FeatureProcessorHandle handle, const MaterialAssetPtr asset) { if (IsAssetLoading(handle)) { @@ -77,12 +79,12 @@ namespace AZ { const auto asset = EraseFromInFlightHandles(handle); - AZ_Assert(m_inFlightHandlesByAsset.count(asset) > 0, "AsyncLoadTracker in a bad state"); - auto& handleList = m_inFlightHandlesByAsset[asset]; + AZ_Assert(m_inFlightHandlesByAsset.count(asset.GetId()) > 0, "AsyncLoadTracker in a bad state"); + auto& handleList = m_inFlightHandlesByAsset[asset.GetId()]; EraseFromVector(handleList, handle); if (handleList.empty()) { - m_inFlightHandlesByAsset.erase(asset); + m_inFlightHandlesByAsset.erase(asset.GetId()); } } @@ -104,14 +106,14 @@ namespace AZ vec.pop_back(); } - void Add(const FeatureProcessorHandle handle, const AZ::Data::AssetId asset) + void Add(const FeatureProcessorHandle handle, const MaterialAssetPtr asset) { AZ_Assert(m_inFlightHandles.count(handle) == 0, "AsyncLoadTracker::Add() - told to add a handle that was already being tracked."); - m_inFlightHandlesByAsset[asset].push_back(handle); + m_inFlightHandlesByAsset[asset.GetId()].push_back(handle); m_inFlightHandles[handle] = asset; } - AZ::Data::AssetId EraseFromInFlightHandles(const FeatureProcessorHandle handle) + MaterialAssetPtr EraseFromInFlightHandles(const FeatureProcessorHandle handle) { const auto iter = m_inFlightHandles.find(handle); AZ_Assert(iter != m_inFlightHandles.end(), "Told to remove handle that was not present"); @@ -125,7 +127,7 @@ namespace AZ // Hash table that tracks the reverse of the m_inFlightHandlesByAsset hash table. // i.e. for each object, it stores what asset that it needs. - AZStd::unordered_map m_inFlightHandles; + AZStd::unordered_map m_inFlightHandles; }; } } diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp index 4000df646d..24857f8d65 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp @@ -85,7 +85,6 @@ namespace AZ m_decalData.Clear(); m_decalBufferHandler.Release(); - m_materialAssets.clear(); } DecalTextureArrayFeatureProcessor::DecalHandle DecalTextureArrayFeatureProcessor::AcquireDecal() @@ -410,7 +409,7 @@ namespace AZ int iter = m_textureArrayList.begin(); while (iter != -1) { - const auto packedTexture = m_textureArrayList[iter].second.GetPackedTexture(); + const auto& packedTexture = m_textureArrayList[iter].second.GetPackedTexture(); view->GetShaderResourceGroup()->SetImage(m_decalTextureArrayIndices[iter], packedTexture); iter = m_textureArrayList.next(iter); } @@ -482,22 +481,15 @@ namespace AZ return material; } - void DecalTextureArrayFeatureProcessor::QueueMaterialLoadForDecal(const AZ::Data::AssetId material, const DecalHandle handle) + void DecalTextureArrayFeatureProcessor::QueueMaterialLoadForDecal(const AZ::Data::AssetId materialId, const DecalHandle handle) { - // Note that another decal might have already queued this material for loading - if (m_materialLoadTracker.IsAssetLoading(material)) - { - m_materialLoadTracker.TrackAssetLoad(handle, material); - return; - } + const auto materialAsset = QueueMaterialAssetLoad(materialId); - const auto materialAsset = QueueMaterialAssetLoad(material); - m_materialAssets.emplace(material, materialAsset); - m_materialLoadTracker.TrackAssetLoad(handle, material); + m_materialLoadTracker.TrackAssetLoad(handle, materialAsset); if (materialAsset.IsLoading()) { - AZ::Data::AssetBus::MultiHandler::BusConnect(material); + AZ::Data::AssetBus::MultiHandler::BusConnect(materialId); } else if (materialAsset.IsReady()) { diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h index 825e461fc2..5301fcc61b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h @@ -136,11 +136,8 @@ namespace AZ GpuBufferHandler m_decalBufferHandler; AsyncLoadTracker m_materialLoadTracker; - AZStd::unordered_map< AZ::Data::AssetId, DecalLocationAndUseCount> m_materialToTextureArrayLookupTable; - AZStd::unordered_map> m_materialAssets; - bool m_deviceBufferNeedsUpdate = false; }; } // namespace Render From 254ad165c15b3d433b852cb05a06f563ccb4fff4 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 16:01:59 -0700 Subject: [PATCH 34/47] A bunch of work to get external multiplayer components to actually work --- .../{ => Multiplayer}/IConnectionData.h | 2 +- .../Include/{ => Multiplayer}/IEntityDomain.h | 2 +- .../Include/{ => Multiplayer}/IMultiplayer.h | 6 +-- .../IMultiplayerComponentInput.h | 2 +- .../{ => Multiplayer}/INetworkEntityManager.h | 4 +- .../Multiplayer/INetworkPlayerSpawner.h | 0 .../Include/{ => Multiplayer}/INetworkTime.h | 2 +- .../{ => Multiplayer}/IReplicationWindow.h | 4 +- .../Multiplayer}/MultiplayerComponent.h | 6 +-- .../MultiplayerComponentRegistry.h | 2 +- .../Multiplayer}/MultiplayerController.h | 8 +--- .../{ => Multiplayer}/MultiplayerStats.cpp | 2 +- .../{ => Multiplayer}/MultiplayerStats.h | 2 +- .../{ => Multiplayer}/MultiplayerTypes.h | 0 .../Multiplayer}/NetBindComponent.h | 11 ++--- .../{ => Multiplayer}/NetworkEntityHandle.h | 4 +- .../{ => Multiplayer}/NetworkEntityHandle.inl | 0 .../Multiplayer}/NetworkEntityRpcMessage.h | 2 +- .../Multiplayer}/NetworkEntityUpdateMessage.h | 2 +- .../Multiplayer}/NetworkInput.h | 6 +-- .../Multiplayer}/ReplicationRecord.h | 2 +- .../Multiplayer}/RewindableObject.h | 4 +- .../Multiplayer}/RewindableObject.inl | 0 .../AutoGen/AutoComponentTypes_Header.jinja | 2 +- .../AutoGen/AutoComponentTypes_Source.jinja | 8 ++-- .../Source/AutoGen/AutoComponent_Header.jinja | 26 +++++------ .../Source/AutoGen/AutoComponent_Source.jinja | 10 ++-- ...tionPlayerInputComponent.AutoComponent.xml | 4 +- .../AutoGen/Multiplayer.AutoPackets.xml | 8 ++-- ...etworkTransformComponent.AutoComponent.xml | 2 +- .../LocalPredictionPlayerInputComponent.h | 2 +- .../Components/MultiplayerComponent.cpp | 4 +- .../MultiplayerComponentRegistry.cpp | 2 +- .../Components/MultiplayerController.cpp | 6 +-- .../Source/Components/NetBindComponent.cpp | 29 +++--------- .../ClientToServerConnectionData.h | 2 +- .../ServerToClientConnectionData.h | 2 +- .../EntityDomains/FullOwnershipEntityDomain.h | 2 +- .../Code/Source/MultiplayerGem.cpp | 2 +- .../Source/MultiplayerSystemComponent.cpp | 2 +- .../Code/Source/MultiplayerSystemComponent.h | 2 +- .../EntityReplicationManager.cpp | 14 +++--- .../EntityReplicationManager.h | 10 ++-- .../EntityReplication/EntityReplicator.cpp | 6 +-- .../EntityReplication/EntityReplicator.h | 4 +- .../EntityReplication/PropertyPublisher.h | 2 +- .../EntityReplication/PropertySubscriber.cpp | 2 +- .../EntityReplication/ReplicationRecord.cpp | 2 +- .../NetworkEntityAuthorityTracker.cpp | 4 +- .../NetworkEntity/NetworkEntityHandle.cpp | 8 ++-- .../NetworkEntity/NetworkEntityManager.cpp | 5 +- .../NetworkEntity/NetworkEntityManager.h | 8 ++-- .../NetworkEntity/NetworkEntityRpcMessage.cpp | 2 +- .../NetworkEntity/NetworkEntityTracker.cpp | 2 +- .../NetworkEntity/NetworkEntityTracker.h | 4 +- .../NetworkEntityUpdateMessage.cpp | 2 +- .../Code/Source/NetworkInput/NetworkInput.cpp | 4 +- .../Source/NetworkInput/NetworkInputArray.cpp | 2 +- .../Source/NetworkInput/NetworkInputArray.h | 4 +- .../Source/NetworkInput/NetworkInputChild.cpp | 2 +- .../Source/NetworkInput/NetworkInputChild.h | 2 +- .../Source/NetworkInput/NetworkInputHistory.h | 2 +- .../NetworkInputMigrationVector.cpp | 2 +- .../NetworkInputMigrationVector.h | 4 +- .../Code/Source/NetworkTime/NetworkTime.cpp | 4 +- .../Code/Source/NetworkTime/NetworkTime.h | 2 +- .../NullReplicationWindow.h | 2 +- .../ServerToClientReplicationWindow.cpp | 2 +- .../ServerToClientReplicationWindow.h | 6 +-- Gems/Multiplayer/Code/multiplayer_files.cmake | 46 +++++++++---------- 70 files changed, 162 insertions(+), 185 deletions(-) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IConnectionData.h (97%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IEntityDomain.h (97%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IMultiplayer.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IMultiplayerComponentInput.h (96%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/INetworkEntityManager.h (98%) create mode 100644 Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/INetworkTime.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/IReplicationWindow.h (94%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerComponent.h (97%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerComponentRegistry.h (98%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/MultiplayerController.h (90%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerStats.cpp (99%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerStats.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/MultiplayerTypes.h (100%) rename Gems/Multiplayer/Code/{Source/Components => Include/Multiplayer}/NetBindComponent.h (95%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/NetworkEntityHandle.h (98%) rename Gems/Multiplayer/Code/Include/{ => Multiplayer}/NetworkEntityHandle.inl (100%) rename Gems/Multiplayer/Code/{Source/NetworkEntity => Include/Multiplayer}/NetworkEntityRpcMessage.h (99%) rename Gems/Multiplayer/Code/{Source/NetworkEntity => Include/Multiplayer}/NetworkEntityUpdateMessage.h (99%) rename Gems/Multiplayer/Code/{Source/NetworkInput => Include/Multiplayer}/NetworkInput.h (95%) rename Gems/Multiplayer/Code/{Source/NetworkEntity/EntityReplication => Include/Multiplayer}/ReplicationRecord.h (98%) rename Gems/Multiplayer/Code/{Source/NetworkTime => Include/Multiplayer}/RewindableObject.h (98%) rename Gems/Multiplayer/Code/{Source/NetworkTime => Include/Multiplayer}/RewindableObject.inl (100%) diff --git a/Gems/Multiplayer/Code/Include/IConnectionData.h b/Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h similarity index 97% rename from Gems/Multiplayer/Code/Include/IConnectionData.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h index dcc2c940ef..39fdb61435 100644 --- a/Gems/Multiplayer/Code/Include/IConnectionData.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Include/IEntityDomain.h b/Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h similarity index 97% rename from Gems/Multiplayer/Code/Include/IEntityDomain.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h index 6571797d05..70215612b0 100644 --- a/Gems/Multiplayer/Code/Include/IEntityDomain.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IEntityDomain.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h similarity index 98% rename from Gems/Multiplayer/Code/Include/IMultiplayer.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index 80bdaa68eb..665661b55b 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -15,9 +15,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h similarity index 96% rename from Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h index b5df01a1a8..b26feadc4f 100644 --- a/Gems/Multiplayer/Code/Include/IMultiplayerComponentInput.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayerComponentInput.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h similarity index 98% rename from Gems/Multiplayer/Code/Include/INetworkEntityManager.h rename to Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h index ebb95e2281..17224e64cb 100644 --- a/Gems/Multiplayer/Code/Include/INetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkEntityManager.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Gems/Multiplayer/Code/Include/INetworkTime.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h similarity index 98% rename from Gems/Multiplayer/Code/Include/INetworkTime.h rename to Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h index 1ccf08bbdc..c228e135ee 100644 --- a/Gems/Multiplayer/Code/Include/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/IReplicationWindow.h b/Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h similarity index 94% rename from Gems/Multiplayer/Code/Include/IReplicationWindow.h rename to Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h index eb34a2f87d..d0192e8aa4 100644 --- a/Gems/Multiplayer/Code/Include/IReplicationWindow.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IReplicationWindow.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h similarity index 97% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h index 0f64221dde..29348a698a 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponent.h @@ -15,9 +15,9 @@ #include #include #include -#include -#include -#include +#include +#include +#include //! Macro to declare bindings for a multiplayer component inheriting from MultiplayerComponent #define AZ_MULTIPLAYER_COMPONENT(ComponentClass, Guid, Base) \ diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h similarity index 98% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h index e16f942100..d06362ed4b 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerComponentRegistry.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h similarity index 90% rename from Gems/Multiplayer/Code/Source/Components/MultiplayerController.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h index de07e39e66..89c47c40d4 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerController.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer @@ -84,12 +84,6 @@ namespace Multiplayer //! Returns the input priority ordering for determining the order of ProcessInput or CreateInput functions. virtual InputPriorityOrder GetInputOrder() const = 0; - //! Queries the rewind system to determine what volume is relevent for a given input, this is very important for performance at scale. - //! @param networkInput input structure to process - //! @param deltaTime amount of time the provided input would be integrated over - //! @return a world-space aabb representing the volume relevent to the provided input - virtual AZ::Aabb GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const = 0; - //! Base execution for ProcessInput packet, do not call directly. //! @param networkInput input structure to process //! @param deltaTime amount of time to integrate the provided inputs over diff --git a/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp similarity index 99% rename from Gems/Multiplayer/Code/Include/MultiplayerStats.cpp rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp index 7672997ad5..1f063b749d 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerStats.cpp +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Include/MultiplayerStats.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h similarity index 98% rename from Gems/Multiplayer/Code/Include/MultiplayerStats.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h index dc266a14bf..5d00c4d205 100644 --- a/Gems/Multiplayer/Code/Include/MultiplayerStats.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Include/MultiplayerTypes.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h similarity index 100% rename from Gems/Multiplayer/Code/Include/MultiplayerTypes.h rename to Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h similarity index 95% rename from Gems/Multiplayer/Code/Source/Components/NetBindComponent.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h index 0885e44aa4..464333e3b2 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetBindComponent.h @@ -20,11 +20,11 @@ #include #include #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include namespace Multiplayer @@ -73,7 +73,6 @@ namespace Multiplayer bool IsProcessingInput() const; void CreateInput(NetworkInput& networkInput, float deltaTime); void ProcessInput(NetworkInput& networkInput, float deltaTime); - AZ::Aabb GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const; bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole remoteRole, NetworkEntityRpcMessage& message); bool HandlePropertyChangeMessage(AzNetworking::ISerializer& serializer, bool notifyChanges = true); diff --git a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h similarity index 98% rename from Gems/Multiplayer/Code/Include/NetworkEntityHandle.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h index 9b8546ef2c..813589fac6 100644 --- a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include namespace Multiplayer { @@ -138,4 +138,4 @@ namespace Multiplayer }; } -#include +#include diff --git a/Gems/Multiplayer/Code/Include/NetworkEntityHandle.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.inl similarity index 100% rename from Gems/Multiplayer/Code/Include/NetworkEntityHandle.inl rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityHandle.inl diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h similarity index 99% rename from Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h index 08b1960172..f6a7ff2c65 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityRpcMessage.h @@ -14,7 +14,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h similarity index 99% rename from Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h index 9ca539d75d..e96191262a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntityUpdateMessage.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h similarity index 95% rename from Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h rename to Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h index b2b0fa12c6..9c6d2ce66a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput.h @@ -12,9 +12,9 @@ #pragma once -#include -#include -#include +#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h b/Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h similarity index 98% rename from Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h rename to Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h index 83721a5539..f6eb93c4ba 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/ReplicationRecord.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h similarity index 98% rename from Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h rename to Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h index 4e830d4480..9e1655aec7 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include #include @@ -115,4 +115,4 @@ namespace AZ AZ_TYPE_INFO_TEMPLATE(Multiplayer::RewindableObject, "{B2937B44-FEE1-4277-B1E0-863DE76D363F}", AZ_TYPE_INFO_TYPENAME, AZ_TYPE_INFO_AUTO); } -#include +#include diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl similarity index 100% rename from Gems/Multiplayer/Code/Source/NetworkTime/RewindableObject.inl rename to Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja index fc2860ebe7..849b4245e2 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Header.jinja @@ -1,7 +1,7 @@ #pragma once #include -#include +#include namespace AZ { diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja index 2acc252729..453d74c907 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponentTypes_Source.jinja @@ -1,6 +1,6 @@ #include -#include -#include +#include +#include {% for Component in dataFiles %} {% set ComponentDerived = Component.attrib['OverrideComponent']|booleanTrue %} {% set ControllerDerived = Component.attrib['OverrideController']|booleanTrue %} @@ -21,8 +21,8 @@ namespace {{ Namespace }} { void RegisterMultiplayerComponents() { - Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = GetMultiplayerComponentRegistry(); - Multiplayer::MultiplayerStats& stats = GetMultiplayer()->GetStats(); + Multiplayer::MultiplayerComponentRegistry* multiplayerComponentRegistry = Multiplayer::GetMultiplayerComponentRegistry(); + Multiplayer::MultiplayerStats& stats = Multiplayer::GetMultiplayer()->GetStats(); {% for Component in dataFiles %} {% set ComponentName = Component.attrib['Name'] %} {% set ComponentBaseName = ComponentName %} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index faaa009e34..c22945c983 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -221,13 +221,14 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] } #include #include #include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include {% call(Include) AutoComponentMacros.ParseIncludes(Component) %} #include <{{ Include.attrib['File'] }}> {% endcall %} @@ -359,7 +360,6 @@ namespace {{ Component.attrib['Namespace'] }} //! MultiplayerController interface //! @{ Multiplayer::MultiplayerController::InputPriorityOrder GetInputOrder() const override { return Multiplayer::MultiplayerController::InputPriorityOrder::Default; } - AZ::Aabb GetRewindBoundsForInput([[maybe_unused]] const NetworkInput& networkInput, [[maybe_unused]] float deltaTime) const override { return AZ::Aabb::CreateNull(); } void CreateInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) override {} void ProcessInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) override {} //! @} @@ -434,12 +434,12 @@ namespace {{ Component.attrib['Namespace'] }} //! MultiplayerComponent interface //! @{ - NetComponentId GetNetComponentId() const override; + Multiplayer::NetComponentId GetNetComponentId() const override; bool HandleRpcMessage(AzNetworking::IConnection* invokingConnection, Multiplayer::NetEntityRole remoteRole, Multiplayer::NetworkEntityRpcMessage& rpcMessage) override; bool SerializeStateDeltaMessage(Multiplayer::ReplicationRecord& replicationRecord, AzNetworking::ISerializer& serializer) override; void NotifyStateDeltaChanges(Multiplayer::ReplicationRecord& replicationRecord) override; bool HasController() const override; - MultiplayerController* GetController() override; + Multiplayer::MultiplayerController* GetController() override; protected: void ConstructController() override; @@ -484,8 +484,8 @@ namespace {{ Component.attrib['Namespace'] }} void NotifyChangesAutonomousToAuthorityProperties(const {{ RecordName }}& replicationRecord) const; //! Debug name helpers - static const char* GetNetworkPropertyName(PropertyIndex propertyIndex); - static const char* GetRpcName(RpcIndex rpcIndex); + static const char* GetNetworkPropertyName(Multiplayer::PropertyIndex propertyIndex); + static const char* GetRpcName(Multiplayer::RpcIndex rpcIndex); AZStd::unique_ptr<{{ RecordName }}> m_currentRecord; AZStd::unique_ptr<{{ ControllerName }}> m_controller; @@ -517,7 +517,7 @@ namespace {{ Component.attrib['Namespace'] }} {{ Type }}* {{ Name }} = nullptr; {% endcall %} - static NetComponentId s_netComponentId; + static Multiplayer::NetComponentId s_netComponentId; friend void RegisterMultiplayerComponents(); }; } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index d719cbe47b..1bc6dc3994 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -902,8 +902,8 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N #include #include #include -#include -#include +#include +#include {% if ComponentDerived or ControllerDerived %} #include <{{ Component.attrib['OverrideInclude'] }}> {% endif %} @@ -915,7 +915,7 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N namespace {{ Component.attrib['Namespace'] }} { - NetComponentId {{ UpperFirst(ComponentBaseName) }}::s_netComponentId = InvalidNetComponentId; + Multiplayer::NetComponentId {{ UpperFirst(ComponentBaseName) }}::s_netComponentId = Multiplayer::InvalidNetComponentId; namespace {{ UpperFirst(Component.attrib['Name']) }}Internal { @@ -1408,7 +1408,7 @@ namespace {{ Component.attrib['Namespace'] }} } {% endif %} - const char* {{ ComponentBaseName }}::GetNetworkPropertyName([[maybe_unused]] PropertyIndex propertyIndex) + const char* {{ ComponentBaseName }}::GetNetworkPropertyName([[maybe_unused]] Multiplayer::PropertyIndex propertyIndex) { {% if NetworkPropertyCount > 0 %} const {{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties propertyId = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::NetworkProperties>(propertyIndex); @@ -1423,7 +1423,7 @@ namespace {{ Component.attrib['Namespace'] }} return "Unknown network property"; } - const char* {{ ComponentBaseName }}::GetRpcName([[maybe_unused]] RpcIndex rpcIndex) + const char* {{ ComponentBaseName }}::GetRpcName([[maybe_unused]] Multiplayer::RpcIndex rpcIndex) { {% if RpcCount > 0 %} const {{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure rpcId = static_cast<{{ UpperFirst(Component.attrib['Name']) }}Internal::RemoteProcedure>(rpcIndex); diff --git a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml index 44edcaf505..a5a7e8decd 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/LocalPredictionPlayerInputComponent.AutoComponent.xml @@ -10,8 +10,8 @@ - - + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml index daf55c3d92..1260075cba 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/Multiplayer.AutoPackets.xml @@ -2,10 +2,10 @@ - - - - + + + + diff --git a/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml b/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml index 46065b386f..e76ac75edc 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml +++ b/Gems/Multiplayer/Code/Source/AutoGen/NetworkTransformComponent.AutoComponent.xml @@ -10,7 +10,7 @@ - + diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h index 15a4f3a048..924fd78391 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.h @@ -13,7 +13,7 @@ #pragma once #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp index fcdad87416..ae6fc50f5a 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponent.cpp @@ -10,8 +10,8 @@ * */ -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp index de1782cc59..648b28633e 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerComponentRegistry.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp b/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp index 737ecc10cc..9b8f41d5bc 100644 --- a/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp +++ b/Gems/Multiplayer/Code/Source/Components/MultiplayerController.cpp @@ -10,9 +10,9 @@ * */ -#include -#include -#include +#include +#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index eba09734a9..6dc661415e 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -10,13 +10,13 @@ * */ -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -177,21 +177,6 @@ namespace Multiplayer } } - AZ::Aabb NetBindComponent::GetRewindBoundsForInput(const NetworkInput& networkInput, float deltaTime) const - { - AZ_Assert(m_netEntityRole == NetEntityRole::Authority, "Incorrect network role for computing rewind bounds"); - AZ::Aabb bounds = AZ::Aabb::CreateNull(); - for (MultiplayerComponent* multiplayerComponent : m_multiplayerInputComponentVector) - { - const AZ::Aabb componentBounds = multiplayerComponent->GetController()->GetRewindBoundsForInput(networkInput, deltaTime); - if (componentBounds.IsValid()) - { - bounds.AddAabb(componentBounds); - } - } - return bounds; - } - bool NetBindComponent::HandleRpcMessage(AzNetworking::IConnection* invokingConnection, NetEntityRole remoteRole, NetworkEntityRpcMessage& message) { auto findIt = m_multiplayerComponentMap.find(message.GetComponentId()); diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h index b72a6aad2b..449ffafe45 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h index b02e6de9aa..6274a6ba31 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ServerToClientConnectionData.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h b/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h index c1abbe74cd..3bf6eb554f 100644 --- a/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h +++ b/Gems/Multiplayer/Code/Source/EntityDomains/FullOwnershipEntityDomain.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp b/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp index cafdbf2a09..aef3e546ad 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerGem.cpp @@ -13,10 +13,10 @@ #include #include #include -#include #include #include #include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 15b6b48631..715d9a8527 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -11,13 +11,13 @@ */ #include -#include #include #include #include #include #include #include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index 1de8fccb50..ba59a82eae 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -19,7 +19,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 65df4f1464..6eefeaf5fe 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -14,14 +14,14 @@ #include #include #include -#include -#include -#include #include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h index 4fc14e210f..50a4ad43d4 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.h @@ -13,11 +13,11 @@ #pragma once #include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 197d83a48c..15293d518d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -16,11 +16,11 @@ #include #include #include -#include -#include #include #include -#include +#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h index 93494ab07c..3587c28975 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.h @@ -18,8 +18,8 @@ #include #include #include -#include -#include +#include +#include namespace AzNetworking { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h index 238e665a00..be8ac1b65b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertyPublisher.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace AzNetworking diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp index 7b8c3e6094..4994884364 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp @@ -12,7 +12,7 @@ #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp index 5f8dae8ff4..6aa6c10b11 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp @@ -10,7 +10,7 @@ * */ -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp index 797d67e3ef..ecfd416380 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp @@ -11,8 +11,8 @@ */ #include -#include -#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp index ca0275d20b..0dd7292d25 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityHandle.cpp @@ -10,11 +10,11 @@ * */ -#include +#include +#include +#include +#include #include -#include -#include -#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 7ee4d45e93..28b72abf25 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -11,7 +11,6 @@ */ #include - #include #include #include @@ -22,9 +21,9 @@ #include #include #include -#include +#include +#include #include -#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index ba71eaf780..e763e7ebca 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -17,11 +17,11 @@ #include #include #include -#include -#include -#include #include -#include +#include +#include +#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp index 4bfc753f75..d58c192162 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityRpcMessage.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp index 69f715317a..42104e79fd 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h index 4cfb242154..34f5d03f2f 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityTracker.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp index 27c39ea135..5ece0c7157 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityUpdateMessage.cpp @@ -10,7 +10,7 @@ * */ -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp index 0ab1d5ffcc..eafd4375e7 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp @@ -10,8 +10,8 @@ * */ -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp index 0f5a0d7c0c..82e5cea0c4 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h index 504992fecb..d5cbcbbed3 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputArray.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp index 114c3e3b43..c6b8e8d7ef 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h index 18b518f19f..fa4ab1e4e9 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputChild.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h index ad406ffd8b..c5f0a70fd3 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputHistory.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp index c6eed626a9..4395ff5b7d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h index c6ea425fec..454cef4e0a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInputMigrationVector.h @@ -12,8 +12,8 @@ #pragma once -#include -#include +#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index c0200c9e6d..ab5988444b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -11,8 +11,8 @@ */ #include -#include -#include +#include +#include #include namespace Multiplayer diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 47f557a11f..18adc00140 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -12,7 +12,7 @@ #pragma once -#include +#include #include #include diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h index 1922e65941..5cb9c0de70 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/NullReplicationWindow.h @@ -12,7 +12,7 @@ #pragma once -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp index a51bdc4acc..bf370c1952 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.cpp @@ -11,7 +11,7 @@ */ #include -#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h index b4e4427945..25fbfd481d 100644 --- a/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h +++ b/Gems/Multiplayer/Code/Source/ReplicationWindows/ServerToClientReplicationWindow.h @@ -12,9 +12,9 @@ #pragma once -#include -#include -#include +#include +#include +#include #include #include #include diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 1f4e57ae43..bea88af10c 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -10,18 +10,28 @@ # set(FILES - Include/IConnectionData.h - Include/IEntityDomain.h - Include/IMultiplayer.h - Include/IMultiplayerComponentInput.h - Include/INetworkEntityManager.h - Include/INetworkTime.h - Include/IReplicationWindow.h - Include/MultiplayerStats.cpp - Include/MultiplayerStats.h - Include/MultiplayerTypes.h - Include/NetworkEntityHandle.h - Include/NetworkEntityHandle.inl + Include/Multiplayer/IConnectionData.h + Include/Multiplayer/IEntityDomain.h + Include/Multiplayer/IMultiplayer.h + Include/Multiplayer/IMultiplayerComponentInput.h + Include/Multiplayer/INetworkEntityManager.h + Include/Multiplayer/INetworkTime.h + Include/Multiplayer/IReplicationWindow.h + Include/Multiplayer/MultiplayerComponent.h + Include/Multiplayer/MultiplayerController.h + Include/Multiplayer/MultiplayerComponentRegistry.h + Include/Multiplayer/MultiplayerStats.cpp + Include/Multiplayer/MultiplayerStats.h + Include/Multiplayer/MultiplayerTypes.h + Include/Multiplayer/NetBindComponent.h + Include/Multiplayer/NetworkEntityRpcMessage.h + Include/Multiplayer/NetworkEntityUpdateMessage.h + Include/Multiplayer/NetworkEntityHandle.h + Include/Multiplayer/NetworkEntityHandle.inl + Include/Multiplayer/NetworkInput.h + Include/Multiplayer/ReplicationRecord.h + Include/Multiplayer/RewindableObject.h + Include/Multiplayer/RewindableObject.inl Source/Multiplayer_precompiled.cpp Source/Multiplayer_precompiled.h Source/MultiplayerSystemComponent.cpp @@ -36,14 +46,10 @@ set(FILES Source/AutoGen/NetworkTransformComponent.AutoComponent.xml Source/Components/LocalPredictionPlayerInputComponent.cpp Source/Components/LocalPredictionPlayerInputComponent.h - Source/Components/MultiplayerComponentRegistry.cpp - Source/Components/MultiplayerComponentRegistry.h Source/Components/MultiplayerComponent.cpp - Source/Components/MultiplayerComponent.h Source/Components/MultiplayerController.cpp - Source/Components/MultiplayerController.h + Source/Components/MultiplayerComponentRegistry.cpp Source/Components/NetBindComponent.cpp - Source/Components/NetBindComponent.h Source/Components/NetworkTransformComponent.cpp Source/Components/NetworkTransformComponent.h Source/ConnectionData/ClientToServerConnectionData.cpp @@ -64,7 +70,6 @@ set(FILES Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp Source/NetworkEntity/EntityReplication/PropertySubscriber.h Source/NetworkEntity/EntityReplication/ReplicationRecord.cpp - Source/NetworkEntity/EntityReplication/ReplicationRecord.h Source/NetworkEntity/NetworkEntityAuthorityTracker.cpp Source/NetworkEntity/NetworkEntityAuthorityTracker.h Source/NetworkEntity/NetworkEntityHandle.cpp @@ -73,14 +78,11 @@ set(FILES Source/NetworkEntity/NetworkSpawnableLibrary.cpp Source/NetworkEntity/NetworkSpawnableLibrary.h Source/NetworkEntity/NetworkEntityRpcMessage.cpp - Source/NetworkEntity/NetworkEntityRpcMessage.h Source/NetworkEntity/NetworkEntityTracker.cpp Source/NetworkEntity/NetworkEntityTracker.h Source/NetworkEntity/NetworkEntityTracker.inl Source/NetworkEntity/NetworkEntityUpdateMessage.cpp - Source/NetworkEntity/NetworkEntityUpdateMessage.h Source/NetworkInput/NetworkInput.cpp - Source/NetworkInput/NetworkInput.h Source/NetworkInput/NetworkInputArray.cpp Source/NetworkInput/NetworkInputArray.h Source/NetworkInput/NetworkInputChild.cpp @@ -91,8 +93,6 @@ set(FILES Source/NetworkInput/NetworkInputMigrationVector.h Source/NetworkTime/NetworkTime.cpp Source/NetworkTime/NetworkTime.h - Source/NetworkTime/RewindableObject.h - Source/NetworkTime/RewindableObject.inl Source/Pipeline/NetBindMarkerComponent.cpp Source/Pipeline/NetBindMarkerComponent.h Source/Pipeline/NetworkSpawnableHolderComponent.cpp From 8bb425709b38d2f574de0eafe842f3a0cffea8dc Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 16:04:44 -0700 Subject: [PATCH 35/47] unit test fix --- Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index 367b7ee0de..9f1b879856 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -10,7 +10,8 @@ * */ -#include +#include +#include #include #include #include From 67c3801d73fbcf67e93f9d42c3548923a580bf5d Mon Sep 17 00:00:00 2001 From: SSpalding <57235700+AMZN-scspaldi@users.noreply.github.com> Date: Wed, 12 May 2021 16:15:18 -0700 Subject: [PATCH 36/47] Log monitor encoding fix (#729) Fixed log monitor encoding bug. --- Tools/LyTestTools/ly_test_tools/log/log_monitor.py | 4 ++-- Tools/LyTestTools/tests/unit/test_log_monitor.py | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Tools/LyTestTools/ly_test_tools/log/log_monitor.py b/Tools/LyTestTools/ly_test_tools/log/log_monitor.py index ca3cd24303..ea3991342a 100755 --- a/Tools/LyTestTools/ly_test_tools/log/log_monitor.py +++ b/Tools/LyTestTools/ly_test_tools/log/log_monitor.py @@ -44,7 +44,7 @@ def check_exact_match(line, expected_line): # Look for either start of line or whitespace, then the expected_line, then either end of the line or whitespace. # This way we don't partial match inside of a string. So for example, 'foo' matches 'foo bar' but not 'foobar' - regex_pattern = re.compile("(^|\\s){}($|\\s)".format(re.escape(expected_line))) + regex_pattern = re.compile("(^|\\s){}($|\\s)".format(re.escape(expected_line)), re.UNICODE) if regex_pattern.search(line) is not None: return expected_line @@ -125,7 +125,7 @@ class LogMonitor(object): self.py_log = "" try: logger.debug("Monitoring log file in '{}' ".format(self.log_file_path)) - with open(self.log_file_path, mode='r') as log: + with open(self.log_file_path, mode='r', encoding='utf-8') as log: logger.info( "Monitoring log file '{}' for '{}' seconds".format(self.log_file_path, timeout)) diff --git a/Tools/LyTestTools/tests/unit/test_log_monitor.py b/Tools/LyTestTools/tests/unit/test_log_monitor.py index 5be2b48d8b..2dd588f9ff 100755 --- a/Tools/LyTestTools/tests/unit/test_log_monitor.py +++ b/Tools/LyTestTools/tests/unit/test_log_monitor.py @@ -98,6 +98,16 @@ class TestLogMonitor(object): under_test = ly_test_tools.log.log_monitor.check_exact_match(line, expected_line) assert under_test == expected_line + @mock.patch('os.path.exists', mock.MagicMock(return_value=True)) + def test_Monitor_UTF8StringsPresentAndExpected_Success(self): + mock_file = io.StringIO('gr\xc3\xb6\xc3\x9feren pr\xc3\xbcfung \xd1\x82\xd0\xb5\xd1\x81\xd1\x82\xd1\x83\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xbd\xd1\x8f\n\xc3\x80\xc3\x88\xc3\x8c\xc3\x92\xc3\x99\n\xc3\x85lpha\xc3\x9fravo\xc3\xa7harlie\n') + mock_launcher.is_alive.side_effect = [True, True, True, False] + + with mock.patch('ly_test_tools.log.log_monitor.open', return_value=mock_file, create=True): + mock_log_monitor().monitor_log_for_lines(['gr\xc3\xb6\xc3\x9feren pr\xc3\xbcfung \xd1\x82\xd0\xb5\xd1\x81\xd1\x82\xd1\x83\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xbd\xd1\x8f', + '\xc3\x80\xc3\x88\xc3\x8c\xc3\x92\xc3\x99', + '\xc3\x85lpha\xc3\x9fravo\xc3\xa7harlie']) + @mock.patch('os.path.exists', mock.MagicMock(return_value=True)) def test_Monitor_AllLinesFound_Success(self): mock_file = io.StringIO(u'a\nb\nc\n') From 7633ec9a83035d9bc543070f055840a086180d02 Mon Sep 17 00:00:00 2001 From: catdo Date: Wed, 12 May 2021 16:27:51 -0700 Subject: [PATCH 37/47] removed spacings in CMakeList and removed the tags.txt file in the prefab level --- .../Gem/PythonTests/CMakeLists.txt | 26 +++++++++---------- .../tags.txt | 12 --------- 2 files changed, 13 insertions(+), 25 deletions(-) delete mode 100644 AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 86bcb967ab..3f0827f995 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -124,19 +124,19 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) endif() ## Prefab ## - if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) - ly_add_pytest( - NAME AutomatedTesting::PrefabTests - TEST_SUITE main - TEST_SERIAL - PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Main.py - TIMEOUT 1500 - RUNTIME_DEPENDENCIES - Legacy::Editor - AZ::AssetProcessor - AutomatedTesting.Assets - ) - endif() +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_pytest( + NAME AutomatedTesting::PrefabTests + TEST_SUITE main + TEST_SERIAL + PATH ${CMAKE_CURRENT_LIST_DIR}/prefab/TestSuite_Main.py + TIMEOUT 1500 + RUNTIME_DEPENDENCIES + Legacy::Editor + AZ::AssetProcessor + AutomatedTesting.Assets + ) +endif() ## Editor Python Bindings ## if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) diff --git a/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt b/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt deleted file mode 100644 index 0d6c1880e7..0000000000 --- a/AutomatedTesting/Levels/Prefab/PrefabLevel_OpensLevelWithEntities/tags.txt +++ /dev/null @@ -1,12 +0,0 @@ -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 -0,0,0,0,0,0 From e7722658718b4c705b688ca88c54cb17c603b417 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:09:27 -0700 Subject: [PATCH 38/47] Build fixes for gem reorganization --- .../Code/Source/Debug/MultiplayerDebugSystemComponent.cpp | 2 +- .../Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp index aec8d8520e..1ae4bffd07 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugSystemComponent.cpp @@ -13,7 +13,7 @@ #include #include #include -#include +#include namespace Multiplayer { diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index 4962d16fb4..805a982506 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -18,7 +18,7 @@ #include #include #include -#include +#include #include #include From eea0660d2140c1e84f63b484f2e89e87a9ec4930 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:26:08 -0700 Subject: [PATCH 39/47] A couple more fixes --- .../Code/Include/Multiplayer/RewindableObject.inl | 4 ++-- .../Code/Source/AutoGen/AutoComponent_Source.jinja | 4 ++-- Gems/Multiplayer/Code/multiplayer_files.cmake | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl index 2e67d42ede..20f52ffcb0 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/RewindableObject.inl @@ -47,7 +47,7 @@ namespace Multiplayer template inline RewindableObject &RewindableObject::operator =(const RewindableObject& rhs) { - INetworkTime* networkTime = GetNetworkTime(); + INetworkTime* networkTime = Multiplayer::GetNetworkTime(); SetValueForTime(rhs.GetValueForTime(networkTime->GetHostFrameId()), GetCurrentTimeForProperty()); return *this; } @@ -115,7 +115,7 @@ namespace Multiplayer template inline HostFrameId RewindableObject::GetCurrentTimeForProperty() const { - INetworkTime* networkTime = GetNetworkTime(); + INetworkTime* networkTime = Multiplayer::GetNetworkTime(); return networkTime->GetHostFrameIdForRewindingConnection(m_owningConnectionId); } diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index 1bc6dc3994..200d38910b 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -1143,7 +1143,7 @@ namespace {{ Component.attrib['Namespace'] }} { editContext->Class<{{ ComponentBaseName }}>("{{ ComponentBaseName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::Category, "{{ Component.attrib['Namespace'] }}") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Authority', ComponentBaseName)|indent(20) -}} {{ DefineNetworkPropertyEditReflection(Component, 'Authority', 'Server', ComponentBaseName)|indent(20) -}} @@ -1155,7 +1155,7 @@ namespace {{ Component.attrib['Namespace'] }} editContext->Class<{{ ComponentName }}>("{{ ComponentName }}", "{{ Component.attrib['Description'] }}") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Multiplayer") + ->Attribute(AZ::Edit::Attributes::Category, "{{ Component.attrib['Namespace'] }}") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")); {% endif %} } diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index bea88af10c..5eba7dd144 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -24,12 +24,12 @@ set(FILES Include/Multiplayer/MultiplayerStats.h Include/Multiplayer/MultiplayerTypes.h Include/Multiplayer/NetBindComponent.h - Include/Multiplayer/NetworkEntityRpcMessage.h + Include/Multiplayer/NetworkEntityRpcMessage.h Include/Multiplayer/NetworkEntityUpdateMessage.h Include/Multiplayer/NetworkEntityHandle.h Include/Multiplayer/NetworkEntityHandle.inl Include/Multiplayer/NetworkInput.h - Include/Multiplayer/ReplicationRecord.h + Include/Multiplayer/ReplicationRecord.h Include/Multiplayer/RewindableObject.h Include/Multiplayer/RewindableObject.inl Source/Multiplayer_precompiled.cpp @@ -48,7 +48,7 @@ set(FILES Source/Components/LocalPredictionPlayerInputComponent.h Source/Components/MultiplayerComponent.cpp Source/Components/MultiplayerController.cpp - Source/Components/MultiplayerComponentRegistry.cpp + Source/Components/MultiplayerComponentRegistry.cpp Source/Components/NetBindComponent.cpp Source/Components/NetworkTransformComponent.cpp Source/Components/NetworkTransformComponent.h From 601dd30452f9f052bf93fc48413e831259e2297d Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:41:53 -0700 Subject: [PATCH 40/47] Various build and test fixes --- .../Code/Include/Multiplayer/IMultiplayer.h | 14 +++++++++----- .../EntityReplication/EntityReplicationManager.cpp | 6 +++++- .../Code/Source/NetworkTime/NetworkTime.cpp | 10 ++++++++++ .../Code/Source/NetworkTime/NetworkTime.h | 4 ++-- .../Code/Tests/RewindableObjectTests.cpp | 6 +++--- 5 files changed, 29 insertions(+), 11 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index 665661b55b..eda5b71b52 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -139,27 +139,31 @@ namespace Multiplayer inline INetworkTime* GetNetworkTime() { - return GetMultiplayer()->GetNetworkTime(); + return AZ::Interface::Get(); } inline INetworkEntityManager* GetNetworkEntityManager() { - return GetMultiplayer()->GetNetworkEntityManager(); + IMultiplayer* multiplayer = GetMultiplayer(); + return (multiplayer != nullptr) ? multiplayer->GetNetworkEntityManager() : nullptr; } inline NetworkEntityTracker* GetNetworkEntityTracker() { - return GetNetworkEntityManager()->GetNetworkEntityTracker(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetNetworkEntityTracker() : nullptr; } inline NetworkEntityAuthorityTracker* GetNetworkEntityAuthorityTracker() { - return GetNetworkEntityManager()->GetNetworkEntityAuthorityTracker(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetNetworkEntityAuthorityTracker() : nullptr; } inline MultiplayerComponentRegistry* GetMultiplayerComponentRegistry() { - return GetNetworkEntityManager()->GetMultiplayerComponentRegistry(); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + return (networkEntityManager != nullptr) ? networkEntityManager->GetMultiplayerComponentRegistry() : nullptr; } //! @class ScopedAlterTime diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 6eefeaf5fe..286090ca74 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -60,7 +60,11 @@ namespace Multiplayer // Start window update events m_updateWindow.Enqueue(AZ::TimeMs{ 0 }, true); - GetNetworkEntityManager()->AddEntityExitDomainHandler(m_entityExitDomainEventHandler); + INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); + if (networkEntityManager != nullptr) + { + networkEntityManager->AddEntityExitDomainHandler(m_entityExitDomainEventHandler); + } } void EntityReplicationManager::SetRemoteHostId(HostId hostId) diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index ab5988444b..d991e59d05 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -17,6 +17,16 @@ namespace Multiplayer { + NetworkTime::NetworkTime() + { + AZ::Interface::Register(this); + } + + NetworkTime::~NetworkTime() + { + AZ::Interface::Unregister(this); + } + bool NetworkTime::IsTimeRewound() const { return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 18adc00140..ff2da0f759 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -23,8 +23,8 @@ namespace Multiplayer : public INetworkTime { public: - NetworkTime() = default; - virtual ~NetworkTime() = default; + NetworkTime(); + virtual ~NetworkTime(); //! INetworkTime overrides. //! @{ diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index 9f1b879856..f614dc2690 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -38,7 +38,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } for (uint32_t i = 0; i < 16; ++i) @@ -51,7 +51,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } for (uint32_t i = 16; i < 48; ++i) @@ -69,7 +69,7 @@ namespace UnitTest { test = i; EXPECT_EQ(i, test); - AZ::Interface::Get()->IncrementHostFrameId(); + Multiplayer::GetNetworkTime()->IncrementHostFrameId(); } { From cb8016bde5f7c63c3054b4992705b9011fce502e Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:52:02 -0700 Subject: [PATCH 41/47] Fix for validator failing on empty files --- .../Multiplayer/INetworkPlayerSpawner.h | 18 ++++++++++++++++++ .../Code/Source/MultiplayerSystemComponent.cpp | 2 +- Gems/Multiplayer/Code/multiplayer_files.cmake | 1 + 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h index e69de29bb2..f50d60e82d 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkPlayerSpawner.h @@ -0,0 +1,18 @@ +/* +* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +* its licensors. +* +* For complete copyright and license terms please see the LICENSE at the root of this +* distribution (the "License"). All use of this software is governed by the License, +* or, if provided, by the license below or the license accompanying this file. Do not +* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* +*/ + +#pragma once + +namespace Multiplayer +{ + +} diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 715d9a8527..80a09d7d48 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -433,7 +433,7 @@ namespace Multiplayer if (m_onConnectFunctor) { - // Default OnConnect behaviour has been overridden, + // Default OnConnect behaviour has been overridden m_onConnectFunctor(connection, datum); } else diff --git a/Gems/Multiplayer/Code/multiplayer_files.cmake b/Gems/Multiplayer/Code/multiplayer_files.cmake index 5eba7dd144..26909cbfd3 100644 --- a/Gems/Multiplayer/Code/multiplayer_files.cmake +++ b/Gems/Multiplayer/Code/multiplayer_files.cmake @@ -15,6 +15,7 @@ set(FILES Include/Multiplayer/IMultiplayer.h Include/Multiplayer/IMultiplayerComponentInput.h Include/Multiplayer/INetworkEntityManager.h + Include/Multiplayer/INetworkPlayerSpawner.h Include/Multiplayer/INetworkTime.h Include/Multiplayer/IReplicationWindow.h Include/Multiplayer/MultiplayerComponent.h From c0d9a3c423b61747656842a931f9c127dceba8d7 Mon Sep 17 00:00:00 2001 From: karlberg Date: Wed, 12 May 2021 20:55:03 -0700 Subject: [PATCH 42/47] Fix for clang not being lazy about template expansion --- Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h | 5 ----- Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h | 6 ++++++ 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index eda5b71b52..4931fb167f 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -137,11 +137,6 @@ namespace Multiplayer return AZ::Interface::Get(); } - inline INetworkTime* GetNetworkTime() - { - return AZ::Interface::Get(); - } - inline INetworkEntityManager* GetNetworkEntityManager() { IMultiplayer* multiplayer = GetMultiplayer(); diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h index c228e135ee..240eed270a 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/INetworkTime.h @@ -83,4 +83,10 @@ namespace Multiplayer static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; }; using INetworkTimeRequestBus = AZ::EBus; + + // Convenience helpers + inline INetworkTime* GetNetworkTime() + { + return AZ::Interface::Get(); + } } From d690c3fee4810a49da588a71da4a95ab603918c9 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Thu, 13 May 2021 11:59:22 +0100 Subject: [PATCH 43/47] static rigid body and rigid body component use Handles instead of pointers (#662) --- .../Configuration/RigidBodyConfiguration.cpp | 8 +- .../Configuration/RigidBodyConfiguration.h | 1 - .../Physics/SimulatedBodies/RigidBody.h | 2 +- .../Code/Source/Family/BlastFamilyImpl.cpp | 2 +- Gems/Blast/Code/Tests/Mocks/BlastMocks.h | 2 +- .../Code/Source/EditorRigidBodyComponent.cpp | 98 +++--- .../Code/Source/EditorRigidBodyComponent.h | 7 +- Gems/PhysX/Code/Source/RigidBody.cpp | 8 +- Gems/PhysX/Code/Source/RigidBody.h | 2 +- Gems/PhysX/Code/Source/RigidBodyComponent.cpp | 278 ++++++++++++++---- Gems/PhysX/Code/Source/RigidBodyComponent.h | 3 +- Gems/PhysX/Code/Source/Scene/PhysXScene.cpp | 18 +- .../Code/Source/StaticRigidBodyComponent.cpp | 42 ++- .../Code/Source/StaticRigidBodyComponent.h | 1 - Gems/PhysX/Code/Source/System/PhysXSystem.cpp | 3 + Gems/PhysX/Code/Tests/PhysXTestCommon.cpp | 12 + 16 files changed, 358 insertions(+), 129 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp index 80434e5dee..0d5d5ca841 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.cpp @@ -99,6 +99,11 @@ namespace AzPhysics classElement.RemoveElementByName(AZ_CRC_CE("Property Visibility Flags")); } + if (classElement.GetVersion() <= 4) + { + classElement.RemoveElementByName(AZ_CRC_CE("Simulated")); + } + return true; } } @@ -110,7 +115,7 @@ namespace AzPhysics if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(4, &Internal::RigidBodyVersionConverter) + ->Version(5, &Internal::RigidBodyVersionConverter) ->Field("Initial linear velocity", &RigidBodyConfiguration::m_initialLinearVelocity) ->Field("Initial angular velocity", &RigidBodyConfiguration::m_initialAngularVelocity) ->Field("Linear damping", &RigidBodyConfiguration::m_linearDamping) @@ -119,7 +124,6 @@ namespace AzPhysics ->Field("Start Asleep", &RigidBodyConfiguration::m_startAsleep) ->Field("Interpolate Motion", &RigidBodyConfiguration::m_interpolateMotion) ->Field("Gravity Enabled", &RigidBodyConfiguration::m_gravityEnabled) - ->Field("Simulated", &RigidBodyConfiguration::m_simulated) ->Field("Kinematic", &RigidBodyConfiguration::m_kinematic) ->Field("CCD Enabled", &RigidBodyConfiguration::m_ccdEnabled) ->Field("Compute Mass", &RigidBodyConfiguration::m_computeMass) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h index 5c43118f3d..ecf7e023c5 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/Configuration/RigidBodyConfiguration.h @@ -57,7 +57,6 @@ namespace AzPhysics bool m_startAsleep = false; bool m_interpolateMotion = false; bool m_gravityEnabled = true; - bool m_simulated = true; bool m_kinematic = false; bool m_ccdEnabled = false; //!< Whether continuous collision detection is enabled. float m_ccdMinAdvanceCoefficient = 0.15f; //!< Coefficient affecting how granularly time is subdivided in CCD. diff --git a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h index 5b18887d43..0f43aaaf4a 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/SimulatedBodies/RigidBody.h @@ -62,7 +62,7 @@ namespace AzPhysics virtual void SetLinearVelocity(const AZ::Vector3& velocity) = 0; virtual AZ::Vector3 GetAngularVelocity() const = 0; virtual void SetAngularVelocity(const AZ::Vector3& angularVelocity) = 0; - virtual AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) = 0; + virtual AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const = 0; virtual void ApplyLinearImpulse(const AZ::Vector3& impulse) = 0; virtual void ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldPoint) = 0; virtual void ApplyAngularImpulse(const AZ::Vector3& angularImpulse) = 0; diff --git a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp index d276486548..87865d0e08 100644 --- a/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp +++ b/Gems/Blast/Code/Source/Family/BlastFamilyImpl.cpp @@ -241,7 +241,7 @@ namespace Blast configuration.m_orientation = transform.GetRotation(); configuration.m_scale = transform.GetScale(); configuration.m_ccdEnabled = m_actorConfiguration.m_isCcdEnabled; - configuration.m_simulated = m_actorConfiguration.m_isSimulated; + configuration.m_startSimulationEnabled = m_actorConfiguration.m_isSimulated; configuration.m_initialAngularVelocity = AZ::Vector3::CreateZero(); BlastActorDesc actorDesc; diff --git a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h index a1e57a6917..1ae87e2282 100644 --- a/Gems/Blast/Code/Tests/Mocks/BlastMocks.h +++ b/Gems/Blast/Code/Tests/Mocks/BlastMocks.h @@ -424,7 +424,7 @@ namespace Blast void SetAngularVelocity([[maybe_unused]] const AZ::Vector3& angularVelocity) override {} - AZ::Vector3 GetLinearVelocityAtWorldPoint([[maybe_unused]] const AZ::Vector3& worldPoint) override + AZ::Vector3 GetLinearVelocityAtWorldPoint([[maybe_unused]] const AZ::Vector3& worldPoint) const override { return {}; } diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp index b6517b0499..f97e7c6cbd 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp @@ -282,9 +282,8 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { - sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_editorBody = nullptr; + sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); + m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -342,12 +341,15 @@ namespace PhysX [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - if (m_editorBody && m_config.m_centerOfMassDebugDraw) + if (m_config.m_centerOfMassDebugDraw) { - debugDisplay.DepthTestOff(); - debugDisplay.SetColor(m_centerOfMassDebugColor); - debugDisplay.DrawBall(m_editorBody->GetCenterOfMassWorld(), m_centerOfMassDebugSize); - debugDisplay.DepthTestOn(); + if (const AzPhysics::RigidBody* body = GetRigidBody()) + { + debugDisplay.DepthTestOff(); + debugDisplay.SetColor(m_centerOfMassDebugColor); + debugDisplay.DrawBall(body->GetCenterOfMassWorld(), m_centerOfMassDebugSize); + debugDisplay.DepthTestOn(); + } } } @@ -366,29 +368,30 @@ namespace PhysX AZ::Transform colliderTransform = GetWorldTM(); colliderTransform.ExtractScale(); - AzPhysics::RigidBodyConfiguration configuration; + AzPhysics::RigidBodyConfiguration configuration = m_config; configuration.m_orientation = colliderTransform.GetRotation(); configuration.m_position = colliderTransform.GetTranslation(); configuration.m_entityId = GetEntityId(); configuration.m_debugName = GetEntity()->GetName(); - configuration.m_centerOfMassOffset = m_config.m_centerOfMassOffset; - configuration.m_computeCenterOfMass = m_config.m_computeCenterOfMass; - configuration.m_computeInertiaTensor = m_config.m_computeInertiaTensor; - configuration.m_inertiaTensor = m_config.m_inertiaTensor; - configuration.m_simulated = false; - configuration.m_kinematic = m_config.m_kinematic; + configuration.m_startSimulationEnabled = false; configuration.m_colliderAndShapeData = Internal::GetCollisionShapes(GetEntity()); + if (auto* sceneInterface = AZ::Interface::Get()) { - m_rigidBodyHandle = sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); - m_editorBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_rigidBodyHandle)); + m_editorRigidBodyHandle = sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); + if (auto* body = azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle) + )) + { + // AddSimulatedBody may update mass / CoM / Inertia tensor based on the config, so grab the updated values. + m_config.m_mass = body->GetMass(); + m_config.m_centerOfMassOffset = body->GetCenterOfMassLocal(); + m_config.m_inertiaTensor = body->GetInverseInertiaLocal(); + } } - - m_editorBody->UpdateMassProperties(m_config.GetMassComputeFlags(), &m_config.m_centerOfMassOffset, &m_config.m_inertiaTensor, &m_config.m_mass); - m_config.m_mass = m_editorBody->GetMass(); - m_config.m_centerOfMassOffset = m_editorBody->GetCenterOfMassLocal(); - m_config.m_inertiaTensor = m_editorBody->GetInverseInertiaLocal(); + AZ_Error("EditorRigidBodyComponent", + m_editorRigidBodyHandle != AzPhysics::InvalidSimulatedBodyHandle, "Failed to create editor rigid body"); } void EditorRigidBodyComponent::OnColliderChanged() @@ -424,9 +427,8 @@ namespace PhysX { if (auto* sceneInterface = AZ::Interface::Get()) { - sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_editorBody = nullptr; + sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); + m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; CreateEditorWorldRigidBody(); } @@ -436,46 +438,65 @@ namespace PhysX void EditorRigidBodyComponent::EnablePhysics() { - if (!IsPhysicsEnabled()) + if (auto* sceneInterface = AZ::Interface::Get()) { - m_editorBody->SetSimulationEnabled(true); + sceneInterface->EnableSimulationOfBody(m_editorSceneHandle, m_editorRigidBodyHandle); } } void EditorRigidBodyComponent::DisablePhysics() { - m_editorBody->SetSimulationEnabled(false); + if (auto* sceneInterface = AZ::Interface::Get()) + { + sceneInterface->DisableSimulationOfBody(m_editorSceneHandle, m_editorRigidBodyHandle); + } } bool EditorRigidBodyComponent::IsPhysicsEnabled() const { - return m_editorBody && m_editorBody->m_simulating; + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)) + { + return body->m_simulating; + } + } + return false; } AZ::Aabb EditorRigidBodyComponent::GetAabb() const { - if (m_editorBody) + if (auto* sceneInterface = AZ::Interface::Get()) { - return m_editorBody->GetAabb(); + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)) + { + return body->GetAabb(); + } } return AZ::Aabb::CreateNull(); } AzPhysics::SimulatedBody* EditorRigidBodyComponent::GetSimulatedBody() { - return m_editorBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle); + } + return nullptr; } AzPhysics::SimulatedBodyHandle EditorRigidBodyComponent::GetSimulatedBodyHandle() const { - return m_rigidBodyHandle; + return m_editorRigidBodyHandle; } AzPhysics::SceneQueryHit EditorRigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_editorBody) + if (AzPhysics::SimulatedBody* body = GetSimulatedBody()) { - return m_editorBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } @@ -488,7 +509,12 @@ namespace PhysX const AzPhysics::RigidBody* EditorRigidBodyComponent::GetRigidBody() const { - return m_editorBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_editorRigidBodyHandle)); + } + return nullptr; } void EditorRigidBodyComponent::SetShouldBeRecreated() diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h index b2b199e6be..72d34bb0d0 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.h @@ -33,8 +33,8 @@ namespace PhysX struct EditorRigidBodyConfiguration : public AzPhysics::RigidBodyConfiguration { - AZ_CLASS_ALLOCATOR(EditorRigidBodyConfiguration, AZ::SystemAllocator, 0); - AZ_RTTI(EditorRigidBodyConfiguration, "{27297024-5A99-4C58-8614-4EF18137CE69}", AzPhysics::RigidBodyConfiguration); + AZ_CLASS_ALLOCATOR(PhysX::EditorRigidBodyConfiguration, AZ::SystemAllocator, 0); + AZ_RTTI(PhysX::EditorRigidBodyConfiguration, "{27297024-5A99-4C58-8614-4EF18137CE69}", AzPhysics::RigidBodyConfiguration); static void Reflect(AZ::ReflectContext* context); @@ -127,8 +127,7 @@ namespace PhysX Debug::DebugDisplayDataChangedEvent::Handler m_debugDisplayDataChangeHandler; EditorRigidBodyConfiguration m_config; - AzPhysics::SimulatedBodyHandle m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - AzPhysics::RigidBody* m_editorBody = nullptr; + AzPhysics::SimulatedBodyHandle m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; AzPhysics::SceneHandle m_editorSceneHandle = AzPhysics::InvalidSceneHandle; AZ::Color m_centerOfMassDebugColor = AZ::Colors::White; diff --git a/Gems/PhysX/Code/Source/RigidBody.cpp b/Gems/PhysX/Code/Source/RigidBody.cpp index 6d1ece6a82..7fda0a1912 100644 --- a/Gems/PhysX/Code/Source/RigidBody.cpp +++ b/Gems/PhysX/Code/Source/RigidBody.cpp @@ -82,12 +82,8 @@ namespace PhysX SetName(configuration.m_debugName); SetGravityEnabled(configuration.m_gravityEnabled); - SetSimulationEnabled(configuration.m_simulated); SetCCDEnabled(configuration.m_ccdEnabled); - - AzPhysics::MassComputeFlags flags = configuration.GetMassComputeFlags(); - UpdateMassProperties(flags, &configuration.m_centerOfMassOffset, &configuration.m_inertiaTensor, - &configuration.m_mass); + SetKinematic(configuration.m_kinematic); if (configuration.m_customUserData) { @@ -459,7 +455,7 @@ namespace PhysX } } - AZ::Vector3 RigidBody::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) + AZ::Vector3 RigidBody::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const { return m_pxRigidActor ? GetLinearVelocity() + GetAngularVelocity().Cross(worldPoint - GetCenterOfMassWorld()) : diff --git a/Gems/PhysX/Code/Source/RigidBody.h b/Gems/PhysX/Code/Source/RigidBody.h index c9f171b261..07df60d649 100644 --- a/Gems/PhysX/Code/Source/RigidBody.h +++ b/Gems/PhysX/Code/Source/RigidBody.h @@ -63,7 +63,7 @@ namespace PhysX void SetLinearVelocity(const AZ::Vector3& velocity) override; AZ::Vector3 GetAngularVelocity() const override; void SetAngularVelocity(const AZ::Vector3& angularVelocity) override; - AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) override; + AZ::Vector3 GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const override; void ApplyLinearImpulse(const AZ::Vector3& impulse) override; void ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldPoint) override; void ApplyAngularImpulse(const AZ::Vector3& angularImpulse) override; diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp index cf2e306cc7..58b0749d0f 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp @@ -185,7 +185,6 @@ namespace PhysX { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_rigidBodyHandle); m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - m_rigidBody = nullptr; } Physics::RigidBodyRequestBus::Handler::BusDisconnect(); @@ -232,20 +231,33 @@ namespace PhysX // User sets kinematic Target ---> Update transform // User sets transform ---> Update kinematic target - if (!IsPhysicsEnabled() || (m_rigidBody->IsKinematic() && !m_isLastMovementFromKinematicSource)) + if (!IsPhysicsEnabled() || (IsKinematic() && !m_isLastMovementFromKinematicSource)) { return; } + auto* sceneInterface = AZ::Interface::Get(); + if (sceneInterface == nullptr) + { + AZ_Error("RigidBodyComponent", false, "PostPhysicsTick, SceneInterface is null"); + return; + } + + AzPhysics::SimulatedBody* rigidBody = + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle); + if (rigidBody == nullptr) + { + AZ_Error("RigidBodyComponent", false, "Unable to retrieve simulated rigid body"); + return; + } + + AZ::Transform transform = rigidBody->GetTransform(); if (m_configuration.m_interpolateMotion) { - AZ::Transform transform = m_rigidBody->GetTransform(); - m_interpolator->SetTarget(transform.GetTranslation(), m_rigidBody->GetOrientation(), fixedDeltaTime); + m_interpolator->SetTarget(transform.GetTranslation(), rigidBody->GetOrientation(), fixedDeltaTime); } else { - AZ::Transform transform = m_rigidBody->GetTransform(); - // Maintain scale (this must be precise). AZ::Transform entityTransform = AZ::Transform::Identity(); AZ::TransformBus::EventResult(entityTransform, GetEntityId(), &AZ::TransformInterface::GetWorldTM); @@ -261,13 +273,17 @@ namespace PhysX // Note: OnTransformChanged is not safe at the moment due to TransformComponent design flaw. // It is called when the parent entity is activated after the children causing rigid body // to move through the level instantly. - if (IsPhysicsEnabled() && (m_rigidBody->IsKinematic() && !m_isLastMovementFromKinematicSource)) + if (AzPhysics::RigidBody* body = GetRigidBody()) { - m_rigidBody->SetKinematicTarget(world); - } - else if (!IsPhysicsEnabled()) - { - m_rigidBodyTransformNeedsUpdateOnPhysReEnable = true; + if (body->m_simulating && + (body->IsKinematic() && !m_isLastMovementFromKinematicSource)) + { + body->SetKinematicTarget(world); + } + else if (!body->m_simulating) + { + m_rigidBodyTransformNeedsUpdateOnPhysReEnable = true; + } } } @@ -290,16 +306,9 @@ namespace PhysX auto* sceneInterface = AZ::Interface::Get(); if (sceneInterface != nullptr) { + m_configuration.m_startSimulationEnabled = false; //enable physics will enable this when called. m_rigidBodyHandle = sceneInterface->AddSimulatedBody(m_attachedSceneHandle, &m_configuration); - m_rigidBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)); - //disable simulating the body until EnablePhysics is called. - sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); } - m_rigidBody->SetKinematic(m_configuration.m_kinematic); - - AzPhysics::MassComputeFlags flags = m_configuration.GetMassComputeFlags(); - m_rigidBody->UpdateMassProperties(flags, &m_configuration.m_centerOfMassOffset, &m_configuration.m_inertiaTensor, - &m_configuration.m_mass); // Listen to the PhysX system for events concerning this entity. if (sceneInterface != nullptr) @@ -319,16 +328,23 @@ namespace PhysX return; } - if (auto* sceneInterface = AZ::Interface::Get()) + auto* sceneInterface = AZ::Interface::Get(); + if (sceneInterface == nullptr) { - sceneInterface->EnableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + AZ_Error("RigidBodyComponent", false, "Unable to enable physics, SceneInterface is null"); + return; } + SetSimulationEnabled(true); AZ::Transform transform = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(transform, GetEntityId(), &AZ::TransformInterface::GetWorldTM); if (m_rigidBodyTransformNeedsUpdateOnPhysReEnable) { - m_rigidBody->SetTransform(transform); + if (AzPhysics::SimulatedBody* body = + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)) + { + body->SetTransform(transform); + } m_rigidBodyTransformNeedsUpdateOnPhysReEnable = false; } @@ -345,188 +361,322 @@ namespace PhysX void RigidBodyComponent::DisablePhysics() { - if (auto* sceneInterface = AZ::Interface::Get()) - { - sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); - } + SetSimulationEnabled(false); Physics::RigidBodyNotificationBus::Event(GetEntityId(), &Physics::RigidBodyNotificationBus::Events::OnPhysicsDisabled); } bool RigidBodyComponent::IsPhysicsEnabled() const { - return m_rigidBody != nullptr && m_rigidBody->m_simulating; + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->m_simulating; + } + return false; } void RigidBodyComponent::ApplyLinearImpulse(const AZ::Vector3& impulse) { - m_rigidBody->ApplyLinearImpulse(impulse); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyLinearImpulse(impulse); + } } void RigidBodyComponent::ApplyLinearImpulseAtWorldPoint(const AZ::Vector3& impulse, const AZ::Vector3& worldSpacePoint) { - m_rigidBody->ApplyLinearImpulseAtWorldPoint(impulse, worldSpacePoint); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyLinearImpulseAtWorldPoint(impulse, worldSpacePoint); + } } void RigidBodyComponent::ApplyAngularImpulse(const AZ::Vector3& impulse) { - m_rigidBody->ApplyAngularImpulse(impulse); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ApplyAngularImpulse(impulse); + } } AZ::Vector3 RigidBodyComponent::GetLinearVelocity() const { - return m_rigidBody->GetLinearVelocity(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearVelocity(); + } + return AZ::Vector3::CreateZero(); } void RigidBodyComponent::SetLinearVelocity(const AZ::Vector3& velocity) { - m_rigidBody->SetLinearVelocity(velocity); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetLinearVelocity(velocity); + } } AZ::Vector3 RigidBodyComponent::GetAngularVelocity() const { - return m_rigidBody->GetAngularVelocity(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAngularVelocity(); + } + return AZ::Vector3::CreateZero(); } void RigidBodyComponent::SetAngularVelocity(const AZ::Vector3& angularVelocity) { - m_rigidBody->SetAngularVelocity(angularVelocity); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetAngularVelocity(angularVelocity); + } } AZ::Vector3 RigidBodyComponent::GetLinearVelocityAtWorldPoint(const AZ::Vector3& worldPoint) const { - return m_rigidBody->GetLinearVelocityAtWorldPoint(worldPoint); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearVelocityAtWorldPoint(worldPoint); + } + return AZ::Vector3::CreateZero(); } AZ::Vector3 RigidBodyComponent::GetCenterOfMassWorld() const { - return m_rigidBody->GetCenterOfMassWorld(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetCenterOfMassWorld(); + } + return AZ::Vector3::CreateZero(); } AZ::Vector3 RigidBodyComponent::GetCenterOfMassLocal() const { - return m_rigidBody->GetCenterOfMassLocal(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetCenterOfMassLocal(); + } + return AZ::Vector3::CreateZero(); } AZ::Matrix3x3 RigidBodyComponent::GetInverseInertiaWorld() const { - return m_rigidBody->GetInverseInertiaWorld(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseInertiaWorld(); + } + return AZ::Matrix3x3::CreateZero(); } AZ::Matrix3x3 RigidBodyComponent::GetInverseInertiaLocal() const { - return m_rigidBody->GetInverseInertiaLocal(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseInertiaLocal(); + } + return AZ::Matrix3x3::CreateZero(); } float RigidBodyComponent::GetMass() const { - return m_rigidBody->GetMass(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetMass(); + } + return 0.0f; } float RigidBodyComponent::GetInverseMass() const { - return m_rigidBody->GetInverseMass(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetInverseMass(); + } + return 0.0f; } void RigidBodyComponent::SetMass(float mass) { - m_rigidBody->SetMass(mass); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetMass(mass); + } } void RigidBodyComponent::SetCenterOfMassOffset(const AZ::Vector3& comOffset) { - m_rigidBody->SetCenterOfMassOffset(comOffset); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetCenterOfMassOffset(comOffset); + } } float RigidBodyComponent::GetLinearDamping() const { - return m_rigidBody->GetLinearDamping(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetLinearDamping(); + } + return 0.0f; } void RigidBodyComponent::SetLinearDamping(float damping) { - m_rigidBody->SetLinearDamping(damping); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetLinearDamping(damping); + } } float RigidBodyComponent::GetAngularDamping() const { - return m_rigidBody->GetAngularDamping(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAngularDamping(); + } + return 0.0f; } void RigidBodyComponent::SetAngularDamping(float damping) { - m_rigidBody->SetAngularDamping(damping); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetAngularDamping(damping); + } } bool RigidBodyComponent::IsAwake() const { - return m_rigidBody->IsAwake(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsAwake(); + } + return false; } void RigidBodyComponent::ForceAsleep() { - m_rigidBody->ForceAsleep(); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ForceAsleep(); + } } void RigidBodyComponent::ForceAwake() { - m_rigidBody->ForceAwake(); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->ForceAwake(); + } } bool RigidBodyComponent::IsKinematic() const { - return m_rigidBody->IsKinematic(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsKinematic(); + } + return false; } void RigidBodyComponent::SetKinematic(bool kinematic) { - m_rigidBody->SetKinematic(kinematic); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetKinematic(kinematic); + } } void RigidBodyComponent::SetKinematicTarget(const AZ::Transform& targetPosition) { m_isLastMovementFromKinematicSource = true; - m_rigidBody->SetKinematicTarget(targetPosition); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetKinematicTarget(targetPosition); + } } bool RigidBodyComponent::IsGravityEnabled() const { - return m_rigidBody->IsGravityEnabled(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->IsGravityEnabled(); + } + return false; } void RigidBodyComponent::SetGravityEnabled(bool enabled) { - m_rigidBody->SetGravityEnabled(enabled); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetGravityEnabled(enabled); + } } void RigidBodyComponent::SetSimulationEnabled(bool enabled) { - m_rigidBody->SetSimulationEnabled(enabled); + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (enabled) + { + sceneInterface->EnableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + } + else + { + sceneInterface->DisableSimulationOfBody(m_attachedSceneHandle, m_rigidBodyHandle); + } + } } float RigidBodyComponent::GetSleepThreshold() const { - return m_rigidBody->GetSleepThreshold(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetSleepThreshold(); + } + return 0.0f; } void RigidBodyComponent::SetSleepThreshold(float threshold) { - m_rigidBody->SetSleepThreshold(threshold); + if (AzPhysics::RigidBody* body = GetRigidBody()) + { + body->SetSleepThreshold(threshold); + } } AZ::Aabb RigidBodyComponent::GetAabb() const { - return m_rigidBody->GetAabb(); + if (const AzPhysics::RigidBody* body = GetRigidBodyConst()) + { + return body->GetAabb(); + } + return AZ::Aabb::CreateNull(); } AzPhysics::RigidBody* RigidBodyComponent::GetRigidBody() { - return m_rigidBody; + return azdynamic_cast(GetSimulatedBody()); } AzPhysics::SimulatedBody* RigidBodyComponent::GetSimulatedBody() { - return m_rigidBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle); + } + return nullptr; + } + + const AzPhysics::RigidBody* RigidBodyComponent::GetRigidBodyConst() const + { + if (auto* sceneInterface = AZ::Interface::Get()) + { + return azdynamic_cast( + sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_rigidBodyHandle)); + } + return nullptr; } AzPhysics::SimulatedBodyHandle RigidBodyComponent::GetSimulatedBodyHandle() const @@ -536,9 +686,9 @@ namespace PhysX AzPhysics::SceneQueryHit RigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_rigidBody) + if (AzPhysics::RigidBody* body = GetRigidBody()) { - return m_rigidBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.h b/Gems/PhysX/Code/Source/RigidBodyComponent.h index 12c4d3f5ff..7b2a34cf37 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.h @@ -153,11 +153,12 @@ namespace PhysX void InitPhysicsTickHandler(); void PostPhysicsTick(float fixedDeltaTime); + const AzPhysics::RigidBody* GetRigidBodyConst() const; + std::unique_ptr m_interpolator; AzPhysics::RigidBodyConfiguration m_configuration; AzPhysics::SimulatedBodyHandle m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - AzPhysics::RigidBody* m_rigidBody = nullptr; AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; AZ::Vector3 m_initialScale = AZ::Vector3::CreateOne(); diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp index 03bbac9fd4..96e2d8a9bb 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp @@ -189,6 +189,22 @@ namespace PhysX return newBody; } + AzPhysics::SimulatedBody* CreateRigidBody(const AzPhysics::RigidBodyConfiguration* configuration, AZ::Crc32& crc) + { + RigidBody* newBody = aznew RigidBody(*configuration); + if (!AZStd::holds_alternative(configuration->m_colliderAndShapeData)) + { + const bool shapeAdded = AddShape(newBody, configuration->m_colliderAndShapeData); + AZ_Warning("PhysXScene", shapeAdded, "No Collider or Shape information found when creating Rigid body [%s]", configuration->m_debugName.c_str()); + } + const AzPhysics::MassComputeFlags& flags = configuration->GetMassComputeFlags(); + newBody->UpdateMassProperties(flags, &configuration->m_centerOfMassOffset, + &configuration->m_inertiaTensor, &configuration->m_mass); + + crc = AZ::Crc32(newBody, sizeof(*newBody)); + return newBody; + } + AzPhysics::SimulatedBody* CreateCharacterBody(PhysXScene* scene, const Physics::CharacterConfiguration* characterConfig) { @@ -617,7 +633,7 @@ namespace PhysX AZ::Crc32 newBodyCrc; if (azrtti_istypeof(simulatedBodyConfig)) { - newBody = Internal::CreateSimulatedBody( + newBody = Internal::CreateRigidBody( azdynamic_cast(simulatedBodyConfig), newBodyCrc); } else if (azrtti_istypeof(simulatedBodyConfig)) diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp index 79e5ea8204..881fb29750 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp @@ -100,7 +100,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { m_staticRigidBodyHandle = sceneInterface->AddSimulatedBody(m_attachedSceneHandle, &configuration); - m_staticRigidBody = azdynamic_cast(sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)); } } @@ -119,16 +118,18 @@ namespace PhysX { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_staticRigidBodyHandle); m_staticRigidBodyHandle = AzPhysics::InvalidSceneHandle; - m_staticRigidBody = nullptr; } AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusDisconnect(); AZ::TransformNotificationBus::Handler::BusDisconnect(); } - void StaticRigidBodyComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) + void StaticRigidBodyComponent::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) { - m_staticRigidBody->SetTransform(world); + if (AzPhysics::SimulatedBody* body = GetSimulatedBody()) + { + body->SetTransform(world); + } } void StaticRigidBodyComponent::EnablePhysics() @@ -153,12 +154,31 @@ namespace PhysX bool StaticRigidBodyComponent::IsPhysicsEnabled() const { - return m_staticRigidBody != nullptr && m_staticRigidBody->m_simulating; + if (m_staticRigidBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) + { + if (auto* sceneInterface = AZ::Interface::Get(); + sceneInterface != nullptr && + sceneInterface->IsEnabled(m_attachedSceneHandle))//check if the scene is enabled + { + if (AzPhysics::SimulatedBody* body = sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)) + { + return body->m_simulating; + } + } + } + return false; } AZ::Aabb StaticRigidBodyComponent::GetAabb() const { - return m_staticRigidBody->GetAabb(); + if (auto* sceneInterface = AZ::Interface::Get()) + { + if (AzPhysics::SimulatedBody* body = sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle)) + { + return body->GetAabb(); + } + } + return AZ::Aabb::CreateNull(); } AzPhysics::SimulatedBodyHandle StaticRigidBodyComponent::GetSimulatedBodyHandle() const @@ -168,14 +188,18 @@ namespace PhysX AzPhysics::SimulatedBody* StaticRigidBodyComponent::GetSimulatedBody() { - return m_staticRigidBody; + if (auto* sceneInterface = AZ::Interface::Get()) + { + return sceneInterface->GetSimulatedBodyFromHandle(m_attachedSceneHandle, m_staticRigidBodyHandle); + } + return nullptr; } AzPhysics::SceneQueryHit StaticRigidBodyComponent::RayCast(const AzPhysics::RayCastRequest& request) { - if (m_staticRigidBody) + if (auto* body = azdynamic_cast(GetSimulatedBody())) { - return m_staticRigidBody->RayCast(request); + return body->RayCast(request); } return AzPhysics::SceneQueryHit(); } diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h index 660521ab7a..0f5bf1a4b2 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.h @@ -65,7 +65,6 @@ namespace PhysX void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; AzPhysics::SimulatedBodyHandle m_staticRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; - PhysX::StaticRigidBody* m_staticRigidBody = nullptr; AzPhysics::SceneHandle m_attachedSceneHandle = AzPhysics::InvalidSceneHandle; }; } // namespace PhysX diff --git a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp index 1d925570c5..1622d04aae 100644 --- a/Gems/PhysX/Code/Source/System/PhysXSystem.cpp +++ b/Gems/PhysX/Code/Source/System/PhysXSystem.cpp @@ -140,6 +140,9 @@ namespace PhysX } }; + AZ_Warning("PhysXSystem", deltaTime <= m_systemConfig.m_maxTimestep, + "Frame delta time of [%.6f seconds] exceeds Physics max frame timestep, physics timestep will be clamped to [%.6f seconds].", + deltaTime, m_systemConfig.m_maxTimestep); deltaTime = AZ::GetClamp(deltaTime, 0.0f, m_systemConfig.m_maxTimestep); AZ_Assert(m_systemConfig.m_fixedTimestep >= 0.0f, "PhysXSystem - fixed timestep is negitive."); diff --git a/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp b/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp index 2404a60e0d..93ad7704c9 100644 --- a/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp +++ b/Gems/PhysX/Code/Tests/PhysXTestCommon.cpp @@ -415,6 +415,10 @@ namespace PhysX Physics::SphereShapeConfiguration shapeConfiguration; shapeConfiguration.m_radius = radius; AzPhysics::RigidBodyConfiguration rigidBodySettings; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; rigidBodySettings.m_position = position; rigidBodySettings.m_linearDamping = 0.0f; rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfiguration); @@ -437,6 +441,10 @@ namespace PhysX Physics::CapsuleShapeConfiguration shapeConfig(height, radius); rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfig); rigidBodySettings.m_position = position; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; if (auto* sceneInterface = AZ::Interface::Get()) { @@ -455,6 +463,10 @@ namespace PhysX shapeConfiguration.m_dimensions = dimensions; AzPhysics::RigidBodyConfiguration rigidBodySettings; + rigidBodySettings.m_computeMass = false; + rigidBodySettings.m_computeInertiaTensor = false; + rigidBodySettings.m_computeCenterOfMass = false; + rigidBodySettings.m_mass = 1.0f; rigidBodySettings.m_position = position; rigidBodySettings.m_linearDamping = 0.0f; rigidBodySettings.m_colliderAndShapeData = AZStd::make_pair(&colliderConfig, &shapeConfiguration); From a13c9e8d531c25d2c490e127f63d2964b3ba9c08 Mon Sep 17 00:00:00 2001 From: Hasareej <82398396+Hasareej@users.noreply.github.com> Date: Thu, 13 May 2021 14:23:31 +0100 Subject: [PATCH 44/47] Hasareej lyn 2301 cluster space (#717) ViewportUi widget anchoring & alignment update. --- .../EditorTransformComponentSelection.cpp | 2 +- .../ViewportUi/ViewportUiDisplay.cpp | 30 ++++++++++++++++--- .../ViewportUi/ViewportUiDisplay.h | 4 +-- .../ViewportUi/ViewportUiManager.cpp | 8 ++--- .../ViewportUi/ViewportUiManager.h | 4 +-- .../ViewportUi/ViewportUiRequestBus.h | 15 ++++++++-- .../Tests/Viewport/ViewportUiDisplayTests.cpp | 10 +++---- .../Tests/Viewport/ViewportUiManagerTests.cpp | 12 ++++---- .../Code/Editor/ColliderComponentMode.cpp | 2 +- .../Source/EditorWhiteBoxComponentMode.cpp | 2 +- 10 files changed, 61 insertions(+), 28 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index c6450d03c7..1766e65276 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -2526,7 +2526,7 @@ namespace AzToolsFramework // create the cluster for changing transform mode ViewportUi::ViewportUiRequestBus::EventResult( m_transformModeClusterId, ViewportUi::DefaultViewportId, - &ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &ViewportUi::ViewportUiRequestBus::Events::CreateCluster, ViewportUi::Alignment::TopLeft); // create and register the buttons (strings correspond to icons even if the values appear different) m_translateButtonId = RegisterClusterButton(m_transformModeClusterId, "Move"); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp index e67ac46f62..e9e7dcc1cc 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.cpp @@ -41,6 +41,28 @@ namespace AzToolsFramework::ViewportUi::Internal } } + static Qt::Alignment GetQtAlignment(Alignment align) + { + switch (align) + { + case Alignment::TopRight: + return Qt::AlignTop | Qt::AlignRight; + case Alignment::TopLeft: + return Qt::AlignTop | Qt::AlignLeft; + case Alignment::BottomRight: + return Qt::AlignBottom | Qt::AlignRight; + case Alignment::BottomLeft: + return Qt::AlignBottom | Qt::AlignLeft; + case Alignment::Top: + return Qt::AlignTop; + case Alignment::Bottom: + return Qt::AlignBottom; + } + + AZ_Assert(false, "ViewportUI", "Unhandled ViewportUI Alignment %d", static_cast(align)); + return Qt::AlignTop; + } + ViewportUiDisplay::ViewportUiDisplay(QWidget* parent, QWidget* renderOverlay) : m_renderOverlay(renderOverlay) , m_uiMainWindow(parent) @@ -56,7 +78,7 @@ namespace AzToolsFramework::ViewportUi::Internal UnparentWidgets(m_viewportUiElements); } - void ViewportUiDisplay::AddCluster(AZStd::shared_ptr buttonGroup) + void ViewportUiDisplay::AddCluster(AZStd::shared_ptr buttonGroup, const Alignment align) { if (!buttonGroup.get()) { @@ -66,7 +88,7 @@ namespace AzToolsFramework::ViewportUi::Internal auto viewportUiCluster = AZStd::make_shared(buttonGroup); auto id = AddViewportUiElement(viewportUiCluster); buttonGroup->SetViewportUiElementId(id); - PositionViewportUiElementAnchored(id, Qt::AlignTop | Qt::AlignLeft); + PositionViewportUiElementAnchored(id, GetQtAlignment(align)); } void ViewportUiDisplay::AddClusterButton( @@ -94,7 +116,7 @@ namespace AzToolsFramework::ViewportUi::Internal } } - void ViewportUiDisplay::AddSwitcher(AZStd::shared_ptr buttonGroup) + void ViewportUiDisplay::AddSwitcher(AZStd::shared_ptr buttonGroup, const Alignment align) { if (!buttonGroup.get()) { @@ -104,7 +126,7 @@ namespace AzToolsFramework::ViewportUi::Internal auto viewportUiSwitcher = AZStd::make_shared(buttonGroup); auto id = AddViewportUiElement(viewportUiSwitcher); buttonGroup->SetViewportUiElementId(id); - PositionViewportUiElementAnchored(id, Qt::AlignTop | Qt::AlignLeft); + PositionViewportUiElementAnchored(id, GetQtAlignment(align)); } void ViewportUiDisplay::AddSwitcherButton(const ViewportUiElementId clusterId, Button* button) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h index 7ef81986c0..d46e01c978 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiDisplay.h @@ -56,12 +56,12 @@ namespace AzToolsFramework::ViewportUi::Internal ViewportUiDisplay(QWidget* parent, QWidget* renderOverlay); ~ViewportUiDisplay(); - void AddCluster(AZStd::shared_ptr buttonGroup); + void AddCluster(AZStd::shared_ptr buttonGroup, Alignment align); void AddClusterButton(ViewportUiElementId clusterId, Button* button); void RemoveClusterButton(ViewportUiElementId clusterId, ButtonId buttonId); void UpdateCluster(const ViewportUiElementId clusterId); - void AddSwitcher(AZStd::shared_ptr buttonGroup); + void AddSwitcher(AZStd::shared_ptr buttonGroup, Alignment align); void AddSwitcherButton(ViewportUiElementId switcherId, Button* button); void RemoveSwitcherButton(ViewportUiElementId switcherId, ButtonId buttonId); void UpdateSwitcher(ViewportUiElementId switcherId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp index 6eb97adb93..12c3b5c9bb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.cpp @@ -30,18 +30,18 @@ namespace AzToolsFramework::ViewportUi ViewportUiRequestBus::Handler::BusDisconnect(); } - const ClusterId ViewportUiManager::CreateCluster() + const ClusterId ViewportUiManager::CreateCluster(const Alignment align) { auto buttonGroup = AZStd::make_shared(); - m_viewportUi->AddCluster(buttonGroup); + m_viewportUi->AddCluster(buttonGroup, align); return RegisterNewCluster(buttonGroup); } - const SwitcherId ViewportUiManager::CreateSwitcher() + const SwitcherId ViewportUiManager::CreateSwitcher(const Alignment align) { auto buttonGroup = AZStd::make_shared(); - m_viewportUi->AddSwitcher(buttonGroup); + m_viewportUi->AddSwitcher(buttonGroup, align); return RegisterNewSwitcher(buttonGroup); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h index 1b350bbd64..04a58cef65 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiManager.h @@ -31,8 +31,8 @@ namespace AzToolsFramework::ViewportUi ~ViewportUiManager() = default; // ViewportUiRequestBus ... - const ClusterId CreateCluster() override; - const SwitcherId CreateSwitcher() override; + const ClusterId CreateCluster(Alignment align) override; + const SwitcherId CreateSwitcher(Alignment align) override; void SetClusterActiveButton(ClusterId clusterId, ButtonId buttonId) override; void SetSwitcherActiveButton(SwitcherId switcherId, ButtonId buttonId) override; const ButtonId CreateClusterButton(ClusterId clusterId, const AZStd::string& icon) override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h index 5041f28656..3879817ccb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportUi/ViewportUiRequestBus.h @@ -41,15 +41,26 @@ namespace AzToolsFramework::ViewportUi String }; + //! Used to anchor widgets to a specific side of the viewport. + enum class Alignment + { + TopRight, + TopLeft, + BottomRight, + BottomLeft, + Top, + Bottom + }; + //! Viewport requests to interact with the Viewport UI. Viewport UI refers to the entire UI overlay (one per viewport). //! Each widget on the Viewport UI is referred to as an element. class ViewportUiRequests { public: //! Creates and registers a cluster with the Viewport UI system. - virtual const ClusterId CreateCluster() = 0; + virtual const ClusterId CreateCluster(Alignment align) = 0; //! Creates and registers a switcher with the Viewport UI system. - virtual const SwitcherId CreateSwitcher() = 0; + virtual const SwitcherId CreateSwitcher(Alignment align) = 0; //! Sets the active button of the cluster. This is the button which will display as highlighted. virtual void SetClusterActiveButton(ClusterId clusterId, ButtonId buttonId) = 0; //! Sets the active button of the switcher. This is the button which has a text label. diff --git a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp index a1ce868569..5fd102b450 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiDisplayTests.cpp @@ -72,7 +72,7 @@ namespace UnitTest TEST_F(ViewportUiDisplayTestFixture, RemoveViewportUiElementRemovesElementFromViewportUi) { ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); auto widget = viewportUi.GetViewportUiElement(m_buttonGroup->GetViewportUiElementId()); EXPECT_TRUE(widget.get() != nullptr); @@ -89,7 +89,7 @@ namespace UnitTest ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); viewportUi.ShowViewportUiElement(m_buttonGroup->GetViewportUiElementId()); @@ -102,7 +102,7 @@ namespace UnitTest ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.HideViewportUiElement(m_buttonGroup->GetViewportUiElementId()); EXPECT_FALSE(viewportUi.IsViewportUiElementVisible(m_buttonGroup->GetViewportUiElementId())); @@ -112,7 +112,7 @@ namespace UnitTest { ViewportUiDisplay viewportUi(m_parentWidget, m_mockRenderOverlay); viewportUi.InitializeUiOverlay(); - viewportUi.AddCluster(m_buttonGroup); + viewportUi.AddCluster(m_buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); auto widget = viewportUi.GetViewportUiElement(m_buttonGroup->GetViewportUiElementId()); @@ -129,7 +129,7 @@ namespace UnitTest auto buttonGroup = AZStd::make_shared(); buttonGroup->AddButton(""); - viewportUi.AddCluster(buttonGroup); + viewportUi.AddCluster(buttonGroup, AzToolsFramework::ViewportUi::Alignment::TopLeft); viewportUi.Update(); EXPECT_TRUE(viewportUi.GetUiMainWindow()->isVisible()); diff --git a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp index 396bde3fdd..9babd0fe6d 100644 --- a/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Viewport/ViewportUiManagerTests.cpp @@ -101,7 +101,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, CreateClusterAddsNewClusterAndReturnsId) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); EXPECT_TRUE(clusterEntry != m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().end()); @@ -110,7 +110,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, CreateClusterButtonAddsNewButtonAndReturnsId) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -120,7 +120,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, SetClusterActiveButtonSetsButtonStateToActive) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -133,7 +133,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, RegisterClusterEventHandlerConnectsHandlerToClusterEvent) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); // create a handler which will be triggered by the cluster @@ -159,7 +159,7 @@ namespace UnitTest TEST_F(ViewportUiManagerTestFixture, RemoveClusterRemovesClusterFromViewportUi) { - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); m_viewportManagerWrapper.GetViewportManager()->RemoveCluster(clusterId); auto clusterEntry = m_viewportManagerWrapper.GetViewportManager()->GetClusterMap().find(clusterId); @@ -171,7 +171,7 @@ namespace UnitTest { m_viewportManagerWrapper.GetMockRenderOverlay()->setVisible(true); - auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(); + auto clusterId = m_viewportManagerWrapper.GetViewportManager()->CreateCluster(AzToolsFramework::ViewportUi::Alignment::TopLeft); auto buttonId = m_viewportManagerWrapper.GetViewportManager()->CreateClusterButton(clusterId, ""); m_viewportManagerWrapper.GetViewportManager()->Update(); diff --git a/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp b/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp index 9aece90d90..7caa497344 100644 --- a/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderComponentMode.cpp @@ -240,7 +240,7 @@ namespace PhysX // create the cluster for changing transform mode AzToolsFramework::ViewportUi::ViewportUiRequestBus::EventResult( m_modeSelectionClusterId, AzToolsFramework::ViewportUi::DefaultViewportId, - &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster, AzToolsFramework::ViewportUi::Alignment::TopLeft); // create and register the buttons m_dimensionsModeButtonId = RegisterClusterButton(m_modeSelectionClusterId, "Scale"); diff --git a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp index 7677ee69f4..0772851cba 100644 --- a/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp +++ b/Gems/WhiteBox/Code/Source/EditorWhiteBoxComponentMode.cpp @@ -482,7 +482,7 @@ namespace WhiteBox // create the cluster for changing transform mode AzToolsFramework::ViewportUi::ViewportUiRequestBus::EventResult( m_modeSelectionClusterId, AzToolsFramework::ViewportUi::DefaultViewportId, - &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster); + &AzToolsFramework::ViewportUi::ViewportUiRequestBus::Events::CreateCluster, AzToolsFramework::ViewportUi::Alignment::TopLeft); // create and register the buttons m_defaultModeButtonId = RegisterClusterButton(m_modeSelectionClusterId, "SketchMode"); From 7f79cc879698118c05dba138270e5e36955c94c2 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Thu, 13 May 2021 15:04:00 +0100 Subject: [PATCH 45/47] RemoveSimulatedBody automatically updates the requested handle to be invalid once removed. (#740) --- .../AzFramework/Physics/PhysicsScene.h | 16 ++++++++-------- Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h | 4 ++-- .../Code/Source/EditorColliderComponent.cpp | 4 ---- .../Code/Source/EditorRigidBodyComponent.cpp | 2 -- .../Code/Source/EditorShapeColliderComponent.cpp | 2 -- .../PhysXCharacters/API/CharacterController.cpp | 1 - .../Source/PhysXCharacters/API/RagdollNode.cpp | 1 - Gems/PhysX/Code/Source/RigidBodyComponent.cpp | 1 - Gems/PhysX/Code/Source/Scene/PhysXScene.cpp | 6 ++++-- Gems/PhysX/Code/Source/Scene/PhysXScene.h | 4 ++-- .../Code/Source/Scene/PhysXSceneInterface.cpp | 4 ++-- .../Code/Source/Scene/PhysXSceneInterface.h | 4 ++-- .../Code/Source/StaticRigidBodyComponent.cpp | 1 - .../Benchmarks/PhysXBenchmarkWashingMachine.cpp | 2 -- .../Tests/Benchmarks/PhysXJointBenchmarks.cpp | 5 +---- .../Benchmarks/PhysXRigidBodyBenchmarks.cpp | 15 +++------------ Gems/PhysX/Code/Tests/PhysXSceneTests.cpp | 9 +++++++-- Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp | 1 - .../Code/Tests/ScriptCanvasPhysicsTest.cpp | 4 ++-- .../EditorWhiteBoxColliderComponent.cpp | 1 - .../Components/WhiteBoxColliderComponent.cpp | 1 - 21 files changed, 33 insertions(+), 55 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h b/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h index db3ec15c83..58e53b0b0d 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h +++ b/Code/Framework/AzFramework/AzFramework/Physics/PhysicsScene.h @@ -88,13 +88,13 @@ namespace AzPhysics //! Remove a simulated body from the Scene.z //! @param sceneHandle A handle to the scene to remove the requested simulated body. - //! @param bodyHandle A handle to the simulated body being removed. - virtual void RemoveSimulatedBody(SceneHandle sceneHandle, SimulatedBodyHandle bodyHandle) = 0; + //! @param bodyHandle A handle to the simulated body being removed. This will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBody(SceneHandle sceneHandle, SimulatedBodyHandle& bodyHandle) = 0; //! Remove a list of simulated bodies from the Scene. //! @param sceneHandle A handle to the scene to remove the simulated bodies from. - //! @param bodyHandles A list of simulated body handles to be removed. - virtual void RemoveSimulatedBodies(SceneHandle sceneHandle, const SimulatedBodyHandleList& bodyHandles) = 0; + //! @param bodyHandles A list of simulated body handles to be removed. All handles will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBodies(SceneHandle sceneHandle, SimulatedBodyHandleList& bodyHandles) = 0; //! Enable / Disable simulation of the requested body. By default all bodies added are enabled. //! Disabling simulation the body will no longer be affected by any forces, collisions, or found with scene queries. @@ -286,12 +286,12 @@ namespace AzPhysics virtual SimulatedBodyList GetSimulatedBodiesFromHandle(const SimulatedBodyHandleList& bodyHandles) = 0; //! Remove a simulated body from the Scene. - //! @param bodyHandle A handle to the simulated body being removed. - virtual void RemoveSimulatedBody(SimulatedBodyHandle bodyHandle) = 0; + //! @param bodyHandle A handle to the simulated body being removed. This will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBody(SimulatedBodyHandle& bodyHandle) = 0; //! Remove a list of simulated bodies from the Scene. - //! @param bodyHandles A list of simulated body handles to be removed. - virtual void RemoveSimulatedBodies(const SimulatedBodyHandleList& bodyHandles) = 0; + //! @param bodyHandles A list of simulated body handles to be removed. All handles will be set to AzPhysics::InvalidSimulatedBodyHandle as they're no longer valid. + virtual void RemoveSimulatedBodies(SimulatedBodyHandleList& bodyHandles) = 0; //! Enable / Disable simulation of the requested body. By default all bodies added are enabled. //! Disabling simulation the body will no longer be affected by any forces, collisions, or found with scene queries. diff --git a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h index 1219e34448..22102fd38a 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/PhysicsSystem.h @@ -92,10 +92,10 @@ namespace Physics [[maybe_unused]] bool enable) override {} void RemoveSimulatedBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandle& bodyHandle) override {} void RemoveSimulatedBodies( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] const AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} void EnableSimulationOfBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 2cf5835a1f..18bb06ba74 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -405,7 +405,6 @@ namespace PhysX if (m_sceneInterface) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -579,7 +578,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } return; } @@ -634,7 +632,6 @@ namespace PhysX if (m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } m_editorBodyHandle = m_sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); @@ -1051,7 +1048,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp index f97e7c6cbd..efd65181da 100644 --- a/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorRigidBodyComponent.cpp @@ -283,7 +283,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); - m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } @@ -428,7 +427,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorRigidBodyHandle); - m_editorRigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; CreateEditorWorldRigidBody(); } diff --git a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp index b71bd47288..58b8995281 100644 --- a/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorShapeColliderComponent.cpp @@ -271,7 +271,6 @@ namespace PhysX if (m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } m_editorBodyHandle = m_sceneInterface->AddSimulatedBody(m_editorSceneHandle, &configuration); @@ -681,7 +680,6 @@ namespace PhysX if (m_sceneInterface && m_editorBodyHandle != AzPhysics::InvalidSimulatedBodyHandle) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_editorBodyHandle); - m_editorBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp index 9e5f92aa72..08df8c0601 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/CharacterController.cpp @@ -343,7 +343,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_sceneOwner, m_shadowBodyHandle); - m_shadowBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; m_shadowBody = nullptr; } } diff --git a/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp b/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp index 6e3b97212b..0f9c7644cd 100644 --- a/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp +++ b/Gems/PhysX/Code/Source/PhysXCharacters/API/RagdollNode.cpp @@ -163,7 +163,6 @@ namespace PhysX sceneInterface->RemoveSimulatedBody(m_sceneOwner, m_rigidBodyHandle); } m_rigidBody = nullptr; - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; m_sceneOwner = AzPhysics::InvalidSceneHandle; } } diff --git a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp index 58b0749d0f..f770f8408c 100644 --- a/Gems/PhysX/Code/Source/RigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/RigidBodyComponent.cpp @@ -184,7 +184,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } Physics::RigidBodyRequestBus::Handler::BusDisconnect(); diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp index 96e2d8a9bb..79aa767959 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.cpp @@ -729,7 +729,7 @@ namespace PhysX return results; } - void PhysXScene::RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle bodyHandle) + void PhysXScene::RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle& bodyHandle) { if (bodyHandle == AzPhysics::InvalidSimulatedBodyHandle) { @@ -751,10 +751,12 @@ namespace PhysX m_deferredDeletions.push_back(m_simulatedBodies[index].second); m_simulatedBodies[index] = AZStd::make_pair(AZ::Crc32(), nullptr); m_freeSceneSlots.push(index); + + bodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } - void PhysXScene::RemoveSimulatedBodies(const AzPhysics::SimulatedBodyHandleList& bodyHandles) + void PhysXScene::RemoveSimulatedBodies(AzPhysics::SimulatedBodyHandleList& bodyHandles) { for (auto& handle: bodyHandles) { diff --git a/Gems/PhysX/Code/Source/Scene/PhysXScene.h b/Gems/PhysX/Code/Source/Scene/PhysXScene.h index 8bf20fca55..2e257283f0 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXScene.h +++ b/Gems/PhysX/Code/Source/Scene/PhysXScene.h @@ -48,8 +48,8 @@ namespace PhysX AzPhysics::SimulatedBodyHandleList AddSimulatedBodies(const AzPhysics::SimulatedBodyConfigurationList& simulatedBodyConfigs) override; AzPhysics::SimulatedBody* GetSimulatedBodyFromHandle(AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SimulatedBodyList GetSimulatedBodiesFromHandle(const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; - void RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; - void RemoveSimulatedBodies(const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; + void RemoveSimulatedBody(AzPhysics::SimulatedBodyHandle& bodyHandle) override; + void RemoveSimulatedBodies(AzPhysics::SimulatedBodyHandleList& bodyHandles) override; void EnableSimulationOfBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; void DisableSimulationOfBody(AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SceneQueryHits QueryScene(const AzPhysics::SceneQueryRequest* request) override; diff --git a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp index 948529a5c8..3b3ab2f0f8 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.cpp @@ -112,7 +112,7 @@ namespace PhysX return {}; //return an empty list } - void PhysXSceneInterface::RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) + void PhysXSceneInterface::RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle& bodyHandle) { if (AzPhysics::Scene* scene = m_physxSystem->GetScene(sceneHandle)) { @@ -120,7 +120,7 @@ namespace PhysX } } - void PhysXSceneInterface::RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) + void PhysXSceneInterface::RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandleList& bodyHandles) { if (AzPhysics::Scene* scene = m_physxSystem->GetScene(sceneHandle)) { diff --git a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h index 3bc08d641c..2edfbd8457 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h +++ b/Gems/PhysX/Code/Source/Scene/PhysXSceneInterface.h @@ -40,8 +40,8 @@ namespace PhysX AzPhysics::SimulatedBodyHandleList AddSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyConfigurationList& simulatedBodyConfigs) override; AzPhysics::SimulatedBody* GetSimulatedBodyFromHandle(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SimulatedBodyList GetSimulatedBodiesFromHandle(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; - void RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; - void RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SimulatedBodyHandleList& bodyHandles) override; + void RemoveSimulatedBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle& bodyHandle) override; + void RemoveSimulatedBodies(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandleList& bodyHandles) override; void EnableSimulationOfBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; void DisableSimulationOfBody(AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle) override; AzPhysics::SceneQueryHits QueryScene(AzPhysics::SceneHandle sceneHandle, const AzPhysics::SceneQueryRequest* request) override; diff --git a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp index 881fb29750..bb1dfc4293 100644 --- a/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp +++ b/Gems/PhysX/Code/Source/StaticRigidBodyComponent.cpp @@ -117,7 +117,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_attachedSceneHandle, m_staticRigidBodyHandle); - m_staticRigidBodyHandle = AzPhysics::InvalidSceneHandle; } AzPhysics::SimulatedBodyComponentRequestsBus::Handler::BusDisconnect(); diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp index 463aea2f71..adc910e8c8 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXBenchmarkWashingMachine.cpp @@ -129,10 +129,8 @@ namespace PhysX::Benchmarks for (int i = 0; i < NumCylinderSide; i++) { sceneInterface->RemoveSimulatedBody(m_sceneHandle, m_cylinder[i]); - m_cylinder[i] = AzPhysics::InvalidSimulatedBodyHandle; } sceneInterface->RemoveSimulatedBody(m_sceneHandle, m_blade); - m_blade = AzPhysics::InvalidSimulatedBodyHandle; } m_sceneHandle = AzPhysics::InvalidSceneHandle; } diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp index 7143f08626..7d650d6bef 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp @@ -404,10 +404,7 @@ namespace PhysX::Benchmarks } subTickTracker.Stop(); - for (auto handle : snakeRigidBodyHandles) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(snakeRigidBodyHandles); snakeRigidBodyHandles.clear(); //sort the frame times and get the P50, P90, P99 percentiles diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp index 54f7d2219c..e295916554 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp @@ -233,10 +233,7 @@ namespace PhysX::Benchmarks subTickTracker.Stop(); //object clean up - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles @@ -310,10 +307,7 @@ namespace PhysX::Benchmarks //object clean up washingMachine.TearDownWashingMachine(); - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles @@ -465,10 +459,7 @@ namespace PhysX::Benchmarks //object clean up collisionHandlers.clear(); washingMachine.TearDownWashingMachine(); - for (auto handle : rigidBodies) - { - m_defaultScene->RemoveSimulatedBody(handle); - } + m_defaultScene->RemoveSimulatedBodies(rigidBodies); rigidBodies.clear(); //sort the frame times and get the P50, P90, P99 percentiles diff --git a/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp b/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp index 2a30fad32d..2a38e1b867 100644 --- a/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXSceneTests.cpp @@ -237,13 +237,17 @@ namespace PhysX //select 1 to remove AzPhysics::SimulatedBodyHandle removedSelection = simBodyHandles[simBodyHandles.size() / 2]; + const AzPhysics::SimulatedBodyIndex removedIndex = AZStd::get(removedSelection); sceneInterface->RemoveSimulatedBody(m_testSceneHandle, removedSelection); + // The removedSelection handle should be set to invalid in RemoveSimulatedBody + EXPECT_EQ(removedSelection, AzPhysics::InvalidSimulatedBodyHandle); + //add a new one. AzPhysics::SimulatedBodyHandle newSimBodyHandle = sceneInterface->AddSimulatedBody(m_testSceneHandle, &config); //The old and new handle should share an index as the freed slot will be used - EXPECT_EQ(AZStd::get(removedSelection), + EXPECT_EQ(removedIndex, AZStd::get(newSimBodyHandle)); } @@ -287,9 +291,10 @@ namespace PhysX EXPECT_EQ(simBodyHandle, addEventSimBodyHandle); //remove the body + const AzPhysics::SimulatedBodyHandle removedHandle = simBodyHandle; //copy the handle as RemoveSimulatedBody will mark it invalid. sceneInterface->RemoveSimulatedBody(m_testSceneHandle, simBodyHandle); EXPECT_TRUE(removedTriggered); - EXPECT_EQ(simBodyHandle, removeEventSimBodyHandle); + EXPECT_EQ(removedHandle, removeEventSimBodyHandle); } TEST_F(PhysXSceneFixture, StartFinishSimulationEvents_triggerAsExpected) diff --git a/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp b/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp index 8e4da0fe4b..74c88d0b46 100644 --- a/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp +++ b/Gems/PhysX/Code/Tests/PhysXSpecificTest.cpp @@ -882,7 +882,6 @@ namespace PhysX if (auto* sceneInterface = AZ::Interface::Get()) { sceneInterface->RemoveSimulatedBody(m_testSceneHandle, rigidBodyHandle); - rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } rigidBody = nullptr; } diff --git a/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp b/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp index c74030d6df..4b04434e13 100644 --- a/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp +++ b/Gems/ScriptCanvasPhysics/Code/Tests/ScriptCanvasPhysicsTest.cpp @@ -90,10 +90,10 @@ namespace ScriptCanvasPhysicsTests [[maybe_unused]] bool enable) override {} void RemoveSimulatedBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandle& bodyHandle) override {} void RemoveSimulatedBodies( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, - [[maybe_unused]] const AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} + [[maybe_unused]] AzPhysics::SimulatedBodyHandleList& bodyHandles) override {} void EnableSimulationOfBody( [[maybe_unused]] AzPhysics::SceneHandle sceneHandle, [[maybe_unused]] AzPhysics::SimulatedBodyHandle bodyHandle) override {} diff --git a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp index 97bce7631d..c8b189942e 100644 --- a/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/EditorWhiteBoxColliderComponent.cpp @@ -163,7 +163,6 @@ namespace WhiteBox if (m_sceneInterface) { m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle); - m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } } diff --git a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp index 117b175cda..41d0a4c5e3 100644 --- a/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp +++ b/Gems/WhiteBox/Code/Source/Components/WhiteBoxColliderComponent.cpp @@ -132,7 +132,6 @@ namespace WhiteBox sceneInterface->RemoveSimulatedBody(defaultScene, m_simulatedBodyHandle); } } - m_simulatedBodyHandle = AzPhysics::InvalidSimulatedBodyHandle; } void WhiteBoxColliderComponent::OnTransformChanged( From 4aff32e719c604b59ccdef7e21ce3dcd9923a8dc Mon Sep 17 00:00:00 2001 From: bosnichd Date: Thu, 13 May 2021 08:55:36 -0600 Subject: [PATCH 46/47] More red code (#732) Remove: - Code/CryEngine/CryCommon/Platform - Some unused Code/CryEngine/CryCommon/Mock files - Code/Tools/CryXML and almost all of Code/Tools/CryCommonTools - Code/Tools/TestBed/ResourceCompilerImage - Tools/DeepBandwidthToExcel - Various .p4ignore files --- Code/.p4ignore | 6 - Code/CryEngine/CryCommon/CMakeLists.txt | 8 - .../CryCommon/Mocks/IMemoryManagerMock.h | 43 - Code/CryEngine/CryCommon/Mocks/INetworkMock.h | 47 - .../CryCommon/Mocks/MockCGFContent.h | 29 - .../Platform/Android/crycommon_android.cmake | 11 - .../Android/crycommon_android_files.cmake | 14 - ...ycommon_enginesettings_android_files.cmake | 13 - .../Platform/AppleTV/crycommon_appletv.cmake | 11 - ...crycommon_enginesettings_linux_files.cmake | 13 - .../Platform/Linux/crycommon_linux.cmake | 11 - .../Linux/crycommon_linux_files.cmake | 14 - .../Platform/Mac/crycommon_mac.cmake | 11 - .../Platform/Mac/crycommon_mac_files.cmake | 14 - .../Platform/Windows/crycommon_windows.cmake | 11 - .../Windows/crycommon_windows_files.cmake | 13 - .../crycommon_enginesettings_ios_files.cmake | 13 - .../Platform/iOS/crycommon_ios.cmake | 11 - .../Platform/iOS/crycommon_ios_files.cmake | 14 - .../CryCommon/Terrain/Bus/HeightmapDataBus.h | 102 - .../CryCommon/Terrain/Bus/TerrainBus.h | 56 - .../Terrain/Bus/TerrainProviderBus.h | 82 - .../Terrain/Bus/TerrainRendererBus.h | 37 - .../Terrain/Bus/WorldMaterialRequestsBus.h | 122 - Code/CryEngine/CryCommon/WinBase.cpp | 3 + .../CryEngine/CryCommon/crycommon_files.cmake | 7 +- .../CryCommon/crycommon_linux_files.cmake | 13 - .../CryCommon/crycommon_testing_files.cmake | 2 - .../CryEngine/CryCommon/stl/STLAlignedAlloc.h | 115 - .../CrySystem/Tests/Test_CryPrimitives.cpp | 16 - Code/Framework/AtomCore/.p4ignore | 1 - Code/Framework/AzCore/.p4ignore | 1 - Code/Sandbox/.p4ignore | 5 - Code/Tools/CMakeLists.txt | 1 - Code/Tools/CryCommonTools/CMakeLists.txt | 26 - Code/Tools/CryCommonTools/ColladaShared.h | 18 - Code/Tools/CryCommonTools/Decompose.cpp | 514 ---- Code/Tools/CryCommonTools/Decompose.h | 30 - Code/Tools/CryCommonTools/Exceptions.h | 43 - Code/Tools/CryCommonTools/FileUtil.cpp | 175 -- Code/Tools/CryCommonTools/FileUtil.h | 311 --- .../CryCommonTools/FileXmlBufferSource.h | 48 - Code/Tools/CryCommonTools/ILogger.h | 53 - Code/Tools/CryCommonTools/IPakSystem.h | 49 - Code/Tools/CryCommonTools/ISettings.h | 57 - Code/Tools/CryCommonTools/LocaleChanger.cpp | 27 - Code/Tools/CryCommonTools/LocaleChanger.h | 30 - Code/Tools/CryCommonTools/LogFile.cpp | 79 - Code/Tools/CryCommonTools/LogFile.h | 40 - Code/Tools/CryCommonTools/MathHelpers.h | 72 - Code/Tools/CryCommonTools/ModuleHelpers.cpp | 44 - Code/Tools/CryCommonTools/ModuleHelpers.h | 31 - Code/Tools/CryCommonTools/PakSystem.cpp | 380 --- Code/Tools/CryCommonTools/PakSystem.h | 69 - .../CryCommonTools/PakXmlFileBufferSource.h | 74 - Code/Tools/CryCommonTools/PathHelpers.cpp | 621 ----- Code/Tools/CryCommonTools/PathHelpers.h | 110 - .../UnixLike/ZipDir/ZipDir_Traits_UnixLike.h | 15 - .../Linux/ZipDir/ZipDir_Traits_Linux.h | 16 - .../Linux/ZipDir/ZipDir_Traits_Platform.h | 15 - .../Platform/Linux/platform_linux_files.cmake | 16 - .../Platform/Mac/ZipDir/ZipDir_Traits_Mac.h | 16 - .../Mac/ZipDir/ZipDir_Traits_Platform.h | 14 - .../Platform/Mac/platform_mac_files.cmake | 16 - .../Windows/ZipDir/ZipDir_Traits_Platform.h | 14 - .../Windows/ZipDir/ZipDir_Traits_Windows.h | 16 - .../Windows/platform_windows_files.cmake | 15 - Code/Tools/CryCommonTools/ProgressRange.h | 89 - Code/Tools/CryCommonTools/PropertyHelpers.cpp | 125 - Code/Tools/CryCommonTools/PropertyHelpers.h | 28 - Code/Tools/CryCommonTools/STLHelpers.cpp | 14 - Code/Tools/CryCommonTools/STLHelpers.h | 54 - Code/Tools/CryCommonTools/SimpleBitmap.h | 508 ---- Code/Tools/CryCommonTools/SimpleStringPool.h | 249 -- .../CryCommonTools/StealingThreadPool.cpp | 580 ----- .../Tools/CryCommonTools/StealingThreadPool.h | 123 - Code/Tools/CryCommonTools/SuffixUtil.h | 59 - .../CryCommonTools/SummedAreaFilterKernel.cpp | 442 ---- .../CryCommonTools/SummedAreaFilterKernel.h | 112 - .../CryCommonTools/TempFilePakExtraction.cpp | 129 - .../CryCommonTools/TempFilePakExtraction.h | 50 - Code/Tools/CryCommonTools/ThreadUtils.cpp | 171 -- Code/Tools/CryCommonTools/ThreadUtils.h | 288 --- Code/Tools/CryCommonTools/UI/log_icons.bmp | 3 - .../UnitTests/PathHelpersUnitTests.cpp | 807 ------- .../UnitTests/StringHelpersUnitTests.cpp | 1056 --------- Code/Tools/CryCommonTools/WeightFilterSet.cpp | 36 - Code/Tools/CryCommonTools/WeightFilterSet.h | 96 - Code/Tools/CryCommonTools/XMLPakFileSink.cpp | 55 - Code/Tools/CryCommonTools/XMLPakFileSink.h | 39 - Code/Tools/CryCommonTools/XMLWriter.cpp | 261 -- Code/Tools/CryCommonTools/XMLWriter.h | 185 -- Code/Tools/CryCommonTools/ZipDir/ZipDir.h | 30 - .../CryCommonTools/ZipDir/ZipDirCache.cpp | 298 --- .../Tools/CryCommonTools/ZipDir/ZipDirCache.h | 140 -- .../ZipDir/ZipDirCacheFactory.cpp | 804 ------- .../ZipDir/ZipDirCacheFactory.h | 143 -- .../CryCommonTools/ZipDir/ZipDirCacheRW.cpp | 2100 ----------------- .../CryCommonTools/ZipDir/ZipDirCacheRW.h | 283 --- .../CryCommonTools/ZipDir/ZipDirFind.cpp | 246 -- Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h | 109 - .../CryCommonTools/ZipDir/ZipDirFindRW.cpp | 253 -- .../CryCommonTools/ZipDir/ZipDirFindRW.h | 110 - .../CryCommonTools/ZipDir/ZipDirList.cpp | 174 -- Code/Tools/CryCommonTools/ZipDir/ZipDirList.h | 138 -- .../ZipDir/ZipDirStructures.cpp | 670 ------ .../CryCommonTools/ZipDir/ZipDirTree.cpp | 356 --- Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h | 103 - Code/Tools/CryCommonTools/ZipDir/ZipFile.h | 19 - .../CryCommonTools/ZipDir/ZipFileFormat.h | 388 --- .../ZipDir/ZipFileFormat_info.h | 112 - .../CryCommonTools/ZipDir/zipdirstructures.h | 426 ---- .../CryCommonTools/crycommontools_files.cmake | 39 - .../crycommontools_tests_files.cmake | 15 - Code/Tools/CryCommonTools/zlibstatd64.lib | 3 - Code/Tools/CryXML/CMakeLists.txt | 32 - Code/Tools/CryXML/CryXML.cpp | 105 - Code/Tools/CryXML/CryXML.def | 3 - Code/Tools/CryXML/CryXML_precompiled.cpp | 14 - Code/Tools/CryXML/CryXML_precompiled.h | 32 - Code/Tools/CryXML/ICryXML.h | 34 - Code/Tools/CryXML/IXMLSerializer.h | 68 - Code/Tools/CryXML/XML/xml.cpp | 1400 ----------- Code/Tools/CryXML/XML/xml.h | 471 ---- Code/Tools/CryXML/XMLSerializer.cpp | 40 - Code/Tools/CryXML/XMLSerializer.h | 31 - Code/Tools/CryXML/cryxml_files.cmake | 22 - .../Input/Bump2NormalHighQ.tif.exportsettings | 1 - ...usehighQWithAlpha256512.tif.exportsettings | 1 - ...usehighQWithAlpha512256.tif.exportsettings | 1 - .../Input/LuminanceOnly.tif.exportsettings | 1 - .../Input/NoPreset3DC_ddn.tif.exportsettings | 1 - .../Input/NoPresetX8R8G8B8.tif.exportsettings | 1 - ...PresetX8R8G8B8WithAlpha.tif.exportsettings | 1 - .../NoPresetX8R8G8B8_bump.tif.exportsettings | 1 - .../NoPresetX8R8G8B8_ddn.tif.exportsettings | 1 - .../Input/NoTIFSettings.tif.exportsettings | 1 - .../NoTIFSettings300400.tif.exportsettings | 1 - ...oTIFSettingsGrey_DDNDIF.tif.exportsettings | 1 - .../NoTIFSettings_DDNDIF.tif.exportsettings | 1 - .../Input/NormalmapLowQ.tif.exportsettings | 1 - ...ormalmapLowQReduce1_ddn.tif.exportsettings | 1 - .../NormalmapLowQ_ddn.tif.exportsettings | 1 - .../TestColorChart_cch.tif.exportsettings | 1 - .../diamand_plate_ddn.tif.exportsettings | 1 - Gems/Blast/Assets/.p4ignore | 1 - Tools/AnimationTest/assetImportTest.bat | 31 - Tools/DeepBandwidthToExcel/7z.exe | 3 - .../DeepBandwidthToExcel.exe | 3 - .../Template/[Content_Types].xml | 2 - .../DeepBandwidthToExcel/Template/_rels/.rels | 2 - .../Template/docProps/app.xml | 2 - .../Template/docProps/core.xml | 2 - .../Template/xl/_rels/workbook.xml.rels | 2 - .../Template/xl/calcChain.xml | 2 - .../Template/xl/charts/chart1.xml | 2 - .../Template/xl/charts/chart2.xml | 2 - .../Template/xl/charts/chart3.xml | 2 - .../Template/xl/charts/chart4.xml | 2 - .../Template/xl/charts/chart5.xml | 93 - .../Template/xl/charts/chart6.xml | 78 - .../Template/xl/charts/chart7.xml | 84 - .../Template/xl/charts/chart8.xml | 83 - .../xl/drawings/_rels/drawing1.xml.rels | 2 - .../xl/drawings/_rels/drawing2.xml.rels | 2 - .../xl/drawings/_rels/drawing3.xml.rels | 2 - .../xl/drawings/_rels/drawing4.xml.rels | 2 - .../xl/drawings/_rels/drawing5.xml.rels | 2 - .../xl/drawings/_rels/drawing6.xml.rels | 2 - .../xl/drawings/_rels/drawing7.xml.rels | 2 - .../xl/drawings/_rels/drawing8.xml.rels | 2 - .../Template/xl/drawings/drawing1.xml | 2 - .../Template/xl/drawings/drawing2.xml | 2 - .../Template/xl/drawings/drawing3.xml | 2 - .../Template/xl/drawings/drawing4.xml | 2 - .../Template/xl/drawings/drawing5.xml | 2 - .../Template/xl/drawings/drawing6.xml | 2 - .../Template/xl/drawings/drawing7.xml | 2 - .../Template/xl/drawings/drawing8.xml | 2 - .../Template/xl/sharedStrings.xml | 2 - .../Template/xl/styles.xml | 2 - .../Template/xl/theme/theme1.xml | 2 - .../Template/xl/workbook.xml | 2 - .../xl/worksheets/_rels/sheet1.xml.rels | 2 - .../xl/worksheets/_rels/sheet2.xml.rels | 2 - .../xl/worksheets/_rels/sheet3.xml.rels | 2 - .../xl/worksheets/_rels/sheet4.xml.rels | 2 - .../xl/worksheets/_rels/sheet5.xml.rels | 2 - .../xl/worksheets/_rels/sheet6.xml.rels | 2 - .../xl/worksheets/_rels/sheet7.xml.rels | 2 - .../xl/worksheets/_rels/sheet8.xml.rels | 2 - .../Template/xl/worksheets/sheet1.xml | 2 - .../Template/xl/worksheets/sheet2.xml | 2 - .../Template/xl/worksheets/sheet3.xml | 2 - .../Template/xl/worksheets/sheet4.xml | 19 - .../Template/xl/worksheets/sheet5.xml | 17 - .../Template/xl/worksheets/sheet6.xml | 18 - .../Template/xl/worksheets/sheet7.xml | 18 - .../Template/xl/worksheets/sheet8.xml | 18 - .../Template/xl/worksheets/sheet9.xml | 16 - .../Windows/package_filelists/atom.json | 11 - 201 files changed, 4 insertions(+), 19283 deletions(-) delete mode 100644 Code/.p4ignore delete mode 100644 Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h delete mode 100644 Code/CryEngine/CryCommon/Mocks/INetworkMock.h delete mode 100644 Code/CryEngine/CryCommon/Mocks/MockCGFContent.h delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake delete mode 100644 Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h delete mode 100644 Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h delete mode 100644 Code/CryEngine/CryCommon/crycommon_linux_files.cmake delete mode 100644 Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h delete mode 100644 Code/Framework/AtomCore/.p4ignore delete mode 100644 Code/Framework/AzCore/.p4ignore delete mode 100644 Code/Sandbox/.p4ignore delete mode 100644 Code/Tools/CryCommonTools/ColladaShared.h delete mode 100644 Code/Tools/CryCommonTools/Decompose.cpp delete mode 100644 Code/Tools/CryCommonTools/Decompose.h delete mode 100644 Code/Tools/CryCommonTools/Exceptions.h delete mode 100644 Code/Tools/CryCommonTools/FileUtil.cpp delete mode 100644 Code/Tools/CryCommonTools/FileUtil.h delete mode 100644 Code/Tools/CryCommonTools/FileXmlBufferSource.h delete mode 100644 Code/Tools/CryCommonTools/ILogger.h delete mode 100644 Code/Tools/CryCommonTools/IPakSystem.h delete mode 100644 Code/Tools/CryCommonTools/ISettings.h delete mode 100644 Code/Tools/CryCommonTools/LocaleChanger.cpp delete mode 100644 Code/Tools/CryCommonTools/LocaleChanger.h delete mode 100644 Code/Tools/CryCommonTools/LogFile.cpp delete mode 100644 Code/Tools/CryCommonTools/LogFile.h delete mode 100644 Code/Tools/CryCommonTools/MathHelpers.h delete mode 100644 Code/Tools/CryCommonTools/ModuleHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/ModuleHelpers.h delete mode 100644 Code/Tools/CryCommonTools/PakSystem.cpp delete mode 100644 Code/Tools/CryCommonTools/PakSystem.h delete mode 100644 Code/Tools/CryCommonTools/PakXmlFileBufferSource.h delete mode 100644 Code/Tools/CryCommonTools/PathHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/PathHelpers.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h delete mode 100644 Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake delete mode 100644 Code/Tools/CryCommonTools/ProgressRange.h delete mode 100644 Code/Tools/CryCommonTools/PropertyHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/PropertyHelpers.h delete mode 100644 Code/Tools/CryCommonTools/STLHelpers.cpp delete mode 100644 Code/Tools/CryCommonTools/STLHelpers.h delete mode 100644 Code/Tools/CryCommonTools/SimpleBitmap.h delete mode 100644 Code/Tools/CryCommonTools/SimpleStringPool.h delete mode 100644 Code/Tools/CryCommonTools/StealingThreadPool.cpp delete mode 100644 Code/Tools/CryCommonTools/StealingThreadPool.h delete mode 100644 Code/Tools/CryCommonTools/SuffixUtil.h delete mode 100644 Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp delete mode 100644 Code/Tools/CryCommonTools/SummedAreaFilterKernel.h delete mode 100644 Code/Tools/CryCommonTools/TempFilePakExtraction.cpp delete mode 100644 Code/Tools/CryCommonTools/TempFilePakExtraction.h delete mode 100644 Code/Tools/CryCommonTools/ThreadUtils.cpp delete mode 100644 Code/Tools/CryCommonTools/ThreadUtils.h delete mode 100644 Code/Tools/CryCommonTools/UI/log_icons.bmp delete mode 100644 Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp delete mode 100644 Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp delete mode 100644 Code/Tools/CryCommonTools/WeightFilterSet.cpp delete mode 100644 Code/Tools/CryCommonTools/WeightFilterSet.h delete mode 100644 Code/Tools/CryCommonTools/XMLPakFileSink.cpp delete mode 100644 Code/Tools/CryCommonTools/XMLPakFileSink.h delete mode 100644 Code/Tools/CryCommonTools/XMLWriter.cpp delete mode 100644 Code/Tools/CryCommonTools/XMLWriter.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDir.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirList.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFile.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h delete mode 100644 Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h delete mode 100644 Code/Tools/CryCommonTools/crycommontools_tests_files.cmake delete mode 100644 Code/Tools/CryCommonTools/zlibstatd64.lib delete mode 100644 Code/Tools/CryXML/CMakeLists.txt delete mode 100644 Code/Tools/CryXML/CryXML.cpp delete mode 100644 Code/Tools/CryXML/CryXML.def delete mode 100644 Code/Tools/CryXML/CryXML_precompiled.cpp delete mode 100644 Code/Tools/CryXML/CryXML_precompiled.h delete mode 100644 Code/Tools/CryXML/ICryXML.h delete mode 100644 Code/Tools/CryXML/IXMLSerializer.h delete mode 100644 Code/Tools/CryXML/XML/xml.cpp delete mode 100644 Code/Tools/CryXML/XML/xml.h delete mode 100644 Code/Tools/CryXML/XMLSerializer.cpp delete mode 100644 Code/Tools/CryXML/XMLSerializer.h delete mode 100644 Code/Tools/CryXML/cryxml_files.cmake delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings delete mode 100644 Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings delete mode 100644 Gems/Blast/Assets/.p4ignore delete mode 100644 Tools/AnimationTest/assetImportTest.bat delete mode 100644 Tools/DeepBandwidthToExcel/7z.exe delete mode 100644 Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe delete mode 100644 Tools/DeepBandwidthToExcel/Template/[Content_Types].xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/_rels/.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/docProps/app.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/docProps/core.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/styles.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/workbook.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml delete mode 100644 Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml diff --git a/Code/.p4ignore b/Code/.p4ignore deleted file mode 100644 index f0b9f1ea6b..0000000000 --- a/Code/.p4ignore +++ /dev/null @@ -1,6 +0,0 @@ -#Ignore these directories -SDKs - -#ColinB (8/26)- I know there are depot files that this will ignore... But these files should not be -#here, they should all be in 3rdParty... so we will ignore them until I can move them, it should -#be OK for now because they shouldn't change at all anyway. diff --git a/Code/CryEngine/CryCommon/CMakeLists.txt b/Code/CryEngine/CryCommon/CMakeLists.txt index 5105ff1a5b..3a1eb90d9d 100644 --- a/Code/CryEngine/CryCommon/CMakeLists.txt +++ b/Code/CryEngine/CryCommon/CMakeLists.txt @@ -9,23 +9,15 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) -ly_get_pal_tool_dirs(pal_tool_dirs ${CMAKE_CURRENT_LIST_DIR}/Platform) - ly_add_target( NAME CryCommon STATIC NAMESPACE Legacy FILES_CMAKE crycommon_files.cmake - ${pal_dir}/crycommon_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake - PLATFORM_INCLUDE_FILES - ${pal_dir}/crycommon_${PAL_PLATFORM_NAME_LOWERCASE}.cmake INCLUDE_DIRECTORIES PUBLIC . # Lots of code without CryCommon/ .. # Dangerous since exports CryEngine's path (client code can do CrySystem/ without depending on that target) - ${pal_dir} - ${pal_tool_dirs} BUILD_DEPENDENCIES PUBLIC AZ::AzCore diff --git a/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h b/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h deleted file mode 100644 index 63df006e14..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/IMemoryManagerMock.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once -#include - -class MemoryManagerMock - : public IMemoryManager -{ -public: - MOCK_METHOD1(GetProcessMemInfo, - bool(SProcessMemInfo& minfo)); - MOCK_METHOD3(TraceDefineHeap, - HeapHandle(const char* heapName, size_t size, const void* pBase)); - MOCK_METHOD6(TraceHeapAlloc, - void(HeapHandle heap, void* mem, size_t size, size_t blockSize, const char* sUsage, const char* sNameHint)); - MOCK_METHOD3(TraceHeapFree, - void(HeapHandle heap, void* mem, size_t blockSize)); - MOCK_METHOD1(TraceHeapSetColor, - void(uint32 color)); - MOCK_METHOD0(TraceHeapGetColor, - uint32()); - MOCK_METHOD1(TraceHeapSetLabel, - void(const char* sLabel)); - MOCK_METHOD1(CreateCustomMemoryHeapInstance, - ICustomMemoryHeap* const (EAllocPolicy const eAllocPolicy)); - MOCK_METHOD3(CreateGeneralExpandingMemoryHeap, - IGeneralMemoryHeap* (size_t upperLimit, size_t reserveSize, const char* sUsage)); - MOCK_METHOD3(CreateGeneralMemoryHeap, - IGeneralMemoryHeap* (void* base, size_t sz, const char* sUsage)); - MOCK_METHOD2(ReserveAddressRange, - IMemoryAddressRange* (size_t capacity, const char* sName)); - MOCK_METHOD2(CreatePageMappingHeap, - IPageMappingHeap* (size_t addressSpace, const char* sName)); -}; diff --git a/Code/CryEngine/CryCommon/Mocks/INetworkMock.h b/Code/CryEngine/CryCommon/Mocks/INetworkMock.h deleted file mode 100644 index b627f927bc..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/INetworkMock.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -struct NetworkMock : public INetwork -{ - NetworkMock() : m_gridMate(nullptr) - { - } - GridMate::IGridMate* m_gridMate; - - void Release() override {} - void GetMemoryStatistics([[maybe_unused]] ICrySizer* pSizer) override {} - void GetBandwidthStatistics([[maybe_unused]] SBandwidthStats* const pStats) override {} - void GetPerformanceStatistics([[maybe_unused]] SNetworkPerformance* pSizer) override {} - void GetProfilingStatistics([[maybe_unused]] SNetworkProfilingStats* const pStats) override {} - void SyncWithGame([[maybe_unused]] ENetworkGameSync syncType) override {} - const char* GetHostName() override { return "testhostname"; } - GridMate::IGridMate* GetGridMate() override - { - return m_gridMate; - } - ChannelId GetChannelIdForSessionMember([[maybe_unused]] GridMate::GridMember* member) const override { return ChannelId(); } - ChannelId GetServerChannelId() const override { return ChannelId(); } - ChannelId GetLocalChannelId() const override { return ChannelId(); } - CTimeValue GetSessionTime() override { return CTimeValue(); } - void ChangedAspects([[maybe_unused]] EntityId id, [[maybe_unused]] NetworkAspectType aspectBits) override {} - void SetDelegatableAspectMask([[maybe_unused]] NetworkAspectType aspectBits) override {} - void SetObjectDelegatedAspectMask([[maybe_unused]] EntityId entityId, [[maybe_unused]] NetworkAspectType aspects, [[maybe_unused]] bool set) override {} - void DelegateAuthorityToClient([[maybe_unused]] EntityId entityId, [[maybe_unused]] ChannelId clientChannelId) override {} - void InvokeActorRMI([[maybe_unused]] EntityId entityId, [[maybe_unused]] uint8 actorExtensionId, [[maybe_unused]] ChannelId targetChannelFilter, [[maybe_unused]] IActorRMIRep& rep) override {} - void InvokeScriptRMI([[maybe_unused]] ISerializable* serializable, [[maybe_unused]] bool isServerRMI, [[maybe_unused]] ChannelId toChannelId = kInvalidChannelId, [[maybe_unused]] ChannelId avoidChannelId = kInvalidChannelId) override {} - void RegisterActorRMI([[maybe_unused]] IActorRMIRep* rep) override {} - void UnregisterActorRMI([[maybe_unused]] IActorRMIRep* rep) override {} - EntityId LocalEntityIdToServerEntityId([[maybe_unused]] EntityId localId) const override { return EntityId(); } - EntityId ServerEntityIdToLocalEntityId([[maybe_unused]] EntityId serverId, [[maybe_unused]] bool allowForcedEstablishment = false) const override { return EntityId(); } -}; diff --git a/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h b/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h deleted file mode 100644 index 8047a863f6..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/MockCGFContent.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include - -#include - -class MockIAssetWriter - : public IAssetWriter -{ -public: - ~MockIAssetWriter() override = default; - MOCK_METHOD1(WriteCGF, - bool(CContentCGF* content)); - MOCK_METHOD2(WriteCHR, - bool(CContentCGF* content, IConvertContext* convertContext)); - MOCK_METHOD3(WriteSKIN, - bool(CContentCGF* content, IConvertContext* convertContext, bool exportMorphTargets)); -}; diff --git a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_android_files.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake b/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Android/crycommon_enginesettings_android_files.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES -) diff --git a/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake b/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/AppleTV/crycommon_appletv.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_enginesettings_linux_files.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES -) diff --git a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake b/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Linux/crycommon_linux_files.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake b/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake b/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Mac/crycommon_mac_files.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake b/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - diff --git a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake b/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/Windows/crycommon_windows_files.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES -) diff --git a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_enginesettings_ios_files.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES -) diff --git a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake deleted file mode 100644 index f5b9ea77a2..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios.cmake +++ /dev/null @@ -1,11 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - diff --git a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake b/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake deleted file mode 100644 index 7b9245ae92..0000000000 --- a/Code/CryEngine/CryCommon/Platform/iOS/crycommon_ios_files.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../../WinBase.cpp -) diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h deleted file mode 100644 index 93065e1196..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/HeightmapDataBus.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include - -namespace Terrain -{ - class Viewport2D - { - public: - int m_topLeftX = 0; - int m_topLeftY = 0; - int m_width = 0; - int m_height = 0; - - Viewport2D() = default; - Viewport2D(const Viewport2D&) = default; - Viewport2D& operator=(const Viewport2D&) = default; - - Viewport2D(int topLeftX, int topLeftY, int width, int height) - : m_topLeftX(topLeftX) - , m_topLeftY(topLeftY) - , m_width(width) - , m_height(height) - { - } - }; - - // External height map data requests - class HeightmapDataRequestInfo - { - public: - HeightmapDataRequestInfo() = default; - HeightmapDataRequestInfo(const HeightmapDataRequestInfo& rhs) = default; - HeightmapDataRequestInfo& operator=(const HeightmapDataRequestInfo& rhs) = default; - - HeightmapDataRequestInfo(int viewportTopLeftX, int viewportTopLeftY, int viewportWidth, int viewportHeight, float metersPerPixel, AZ::Vector2 worldMin, AZ::Vector2 worldMax) - : m_viewport(viewportTopLeftX, viewportTopLeftY, viewportWidth, viewportHeight) - , m_metersPerPixel(metersPerPixel) - , m_worldMin(worldMin) - , m_worldMax(worldMax) - { - } - - float GetMetersPerPixel() const - { - return m_metersPerPixel; - } - - AZ::Vector2 GetWorldMin() const - { - return m_worldMin; - } - - AZ::Vector2 GetWorldMax() const - { - return m_worldMax; - } - - AZ::Vector2 GetWorldWidth() const - { - return (m_worldMax - m_worldMin); - } - - Viewport2D GetViewport() const - { - return m_viewport; - } - - private: - Viewport2D m_viewport; - AZ::Vector2 m_worldMin = AZ::Vector2(0.0f, 0.0f); - AZ::Vector2 m_worldMax = AZ::Vector2(0.0f, 0.0f); - float m_metersPerPixel = 1.0f; - }; - - class HeightmapDataNotifications - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - virtual void OnTerrainHeightDataChanged(const AZ::Aabb& dirtyRegion) = 0; - }; - using HeightmapDataNotificationBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h deleted file mode 100644 index 2cfb5134c9..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainBus.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include - -class CShader; - -namespace Terrain -{ - class TerrainDataRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - virtual float GetHeightSynchronous(float x, float y) = 0; - virtual AZ::Vector3 GetNormalSynchronous(float x, float y) = 0; - - virtual CShader* GetTerrainHeightGeneratorShader() const = 0; - virtual CShader* GetTerrainMaterialCompositingShader() const = 0; - }; - using TerrainDataRequestBus = AZ::EBus; - - class TerrainShaderRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - virtual void RefreshShader(const AZStd::string_view name, CShader* shader) = 0; - virtual void ReleaseShader(CShader* shader) const = 0; - }; - using TerrainShaderRequestBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h deleted file mode 100644 index 6c1aca6ea7..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainProviderBus.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include - -#include - -#include "HeightmapDataBus.h" - -class CShader; - -namespace Terrain -{ - // This interface defines how the renderer can access the terrain system to set up state and gather information before rendering height maps - class TerrainProviderRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - // world properties - virtual AZ::Vector3 GetWorldSize() = 0; - virtual AZ::Vector3 GetRegionSize() = 0; - virtual AZ::Vector3 GetWorldOrigin() = 0; - virtual AZ::Vector2 GetHeightRange() = 0; - - // utility - virtual void GetRegionIndex(const AZ::Vector2& worldMin, const AZ::Vector2& worldMax, int& regionIndexX, int& regionIndexY) = 0; - - virtual float GetHeightAtIndexedPosition([[maybe_unused]] int ix, [[maybe_unused]] int iy) { return 64.0f; } - virtual float GetHeightAtWorldPosition([[maybe_unused]] float fx, [[maybe_unused]] float fy) { return 64.0f; } - virtual unsigned char GetSurfaceTypeAtIndexedPosition([[maybe_unused]] int ix, [[maybe_unused]] int iy) { return 0; } - }; - using TerrainProviderRequestBus = AZ::EBus; - - // This class exists for the terrain system to inject data into the renderer for generating the GPU-side terrain height map - struct CRETerrainContext - { - // Tract map - virtual void OnTractVersionUpdate() = 0; - - CShader* m_currentShader = nullptr; - }; - - class TerrainProviderNotifications - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - ////////////////////////////////////////////////////////////////////////// - - // interface to be implemented by the game, invoked by the terrain render element - - // pull settings from the world cache, so the next accessors are accurate - virtual void SynchronizeSettings(CRETerrainContext* context) = 0; - }; - using TerrainProviderNotificationBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h deleted file mode 100644 index ea644f5653..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/TerrainRendererBus.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include - -namespace Terrain -{ - class TerrainRendererRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - - // Query state of the terrain renderer - // Returns true once the terrain renderer has fulfilled most data requests and is ready for rendering - virtual bool IsReady() = 0; - }; - using TerrainRendererRequestBus = AZ::EBus; -} diff --git a/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h b/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h deleted file mode 100644 index 3fb80f5f11..0000000000 --- a/Code/CryEngine/CryCommon/Terrain/Bus/WorldMaterialRequestsBus.h +++ /dev/null @@ -1,122 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -#include -#include -#include - -struct IMaterial; -class ITexture; - -namespace Terrain -{ - struct MacroMaterial - { - // Textures - _smart_ptr m_macroColorMap = nullptr; - _smart_ptr m_macroGlossMap = nullptr; - _smart_ptr m_macroNormalMap = nullptr; - - // Material Params - AZ::Color m_macroColorMapColor; - float m_macroGlossMapScale = 1.0f; - float m_macroNormalMapScale = 1.0f; - float m_macroSpecReflectance = 0.03f; - - void Clear() - { - m_macroColorMap = nullptr; - m_macroGlossMap = nullptr; - m_macroNormalMap = nullptr; - - m_macroColorMapColor = AZ::Color(1.0f); - m_macroGlossMapScale = 1.0f; - m_macroNormalMapScale = 1.0f; - m_macroSpecReflectance = 0.03f; - } - }; - - struct TerrainMaterialLayer - { - _smart_ptr m_material = nullptr; - _smart_ptr m_splatTexture = nullptr; - - TerrainMaterialLayer(_smart_ptr material, _smart_ptr splatTexture) - : m_material(material) - , m_splatTexture(splatTexture) - { - } - }; - - struct RegionMaterials - { - MacroMaterial m_macroMaterial; - - AZStd::vector m_materialLayers; - _smart_ptr m_defaultMaterial = nullptr; - - RegionMaterials& operator=(const RegionMaterials& rhs) = default; - - void Clear() - { - m_materialLayers.clear(); - m_defaultMaterial = nullptr; - m_macroMaterial.Clear(); - } - }; - - const AZ::u32 kMaxRegionsPerTerrainMaterialRequest = 16; - typedef AZStd::pair RegionIndex; - typedef AZStd::fixed_vector RegionIndexVector; - typedef AZStd::fixed_vector RegionMaterialVector; - - enum class RequestResult - { - NoAssetsForRegion, - Loading, - Success - }; - - class WorldMaterialRequests - : public AZ::EBusTraits - { - public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - //! allows multiple threads to call - using MutexType = AZStd::recursive_mutex; - - virtual void LoadWorld(const AZStd::string& worldName, int regionSize) = 0; - - virtual RequestResult RequestRegionMaterials(const RegionIndexVector& regions, RegionMaterialVector& outRegionMaterials) = 0; - - // Parameters: - // int tileX, tileY : Region tile indices - // Returns: - // bool : If true, region material data is loaded and exists. outMacroMaterial will be modified with the respective macro material data - // If false, no region material data has been loaded or exists for the given tile (may still have invalid material layers). - virtual RequestResult GetMacroMaterial(int tileX, int tileY, MacroMaterial& outMacroMaterial) = 0; - - virtual void GetTerrainPOMParameters(float& pomHeightBias, float& pomDisplacement, float& selfShadowStrength) = 0; - - //Get the surface type at a given position. If not loaded yet, returns "loadingMaterial". - virtual AZStd::string_view GetSurfaceTypeAtPosition(AZ::Vector2 position) = 0; - }; - using WorldMaterialRequestBus = AZ::EBus; -} // namespace Terrain - diff --git a/Code/CryEngine/CryCommon/WinBase.cpp b/Code/CryEngine/CryCommon/WinBase.cpp index e6ea1cd4a8..47cb943240 100644 --- a/Code/CryEngine/CryCommon/WinBase.cpp +++ b/Code/CryEngine/CryCommon/WinBase.cpp @@ -12,6 +12,7 @@ // Original file Copyright Crytek GMBH or its affiliates, used under license. // Description : Linux/Mac port support for Win32API calls +#if !defined(WIN32) #include "platform.h" // Note: This should be first to get consistent debugging definitions @@ -1667,3 +1668,5 @@ __finddata64_t::~__finddata64_t() } } #endif //defined(APPLE) || defined(LINUX) + +#endif // !defined(WIN32) diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index 77b51825f1..dff4ca66e7 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -249,7 +249,6 @@ set(FILES platform_impl.cpp Win32specific.h Win64specific.h - stl/STLAlignedAlloc.h LyShine/IDraw2d.h LyShine/ILyShine.h LyShine/ISprite.h @@ -341,11 +340,7 @@ set(FILES Maestro/Types/AssetBlendKey.h Maestro/Types/AssetBlends.h Maestro/Types/SequenceType.h - Terrain/Bus/WorldMaterialRequestsBus.h - Terrain/Bus/TerrainBus.h - Terrain/Bus/TerrainRendererBus.h - Terrain/Bus/HeightmapDataBus.h - Terrain/Bus/TerrainProviderBus.h StaticInstance.h Pak/CryPakUtils.h + WinBase.cpp ) diff --git a/Code/CryEngine/CryCommon/crycommon_linux_files.cmake b/Code/CryEngine/CryCommon/crycommon_linux_files.cmake deleted file mode 100644 index 5714be5dfb..0000000000 --- a/Code/CryEngine/CryCommon/crycommon_linux_files.cmake +++ /dev/null @@ -1,13 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES -) diff --git a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake index d20a33f791..b94be27c3b 100644 --- a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake @@ -14,12 +14,10 @@ set(FILES Mocks/IConsoleMock.h Mocks/ICryPakMock.h Mocks/ILogMock.h - Mocks/IMemoryManagerMock.h Mocks/ISystemMock.h Mocks/ITimerMock.h Mocks/ICVarMock.h Mocks/IRendererMock.h Mocks/ITextureMock.h Mocks/IRemoteConsoleMock.h - Mocks/MockCGFContent.h ) diff --git a/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h b/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h deleted file mode 100644 index dc21cead81..0000000000 --- a/Code/CryEngine/CryCommon/stl/STLAlignedAlloc.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Implements an aligned allocator for STL -// based on the Mallocator (http://blogs.msdn.com/b/vcblog/archive/2008/08/28/the-mallocator.aspx) - -#pragma once - -#include // Required for size_t and ptrdiff_t and NULL - -#include - -namespace stl -{ - template - class AlignedAllocator - : public AZ::SimpleSchemaAllocator> - { - public: - AZ_TYPE_INFO(AlignedAllocator, "{DF152D8A-36ED-4A2A-9FA6-734F212716C6}"); - using Base = AZ::SimpleSchemaAllocator>; - using Descriptor = Base::Descriptor; - using Schema = AZ::ChildAllocatorSchema; - - AlignedAllocator() - : Base("AlignedAllocator", "Legacy Cry Aligned Allocator") - { - } - - pointer_type Allocate(size_type byteSize, size_type /*alignment*/, int flags /* = 0 */, const char* name /* = 0 */, const char* fileName /* = 0 */, int lineNum /* = 0 */, unsigned int suppressStackRecord /* = 0 */) override - { - return Base::Allocate(byteSize, Alignment, flags, name, fileName, lineNum, suppressStackRecord); - } - - void DeAllocate(pointer_type ptr, size_type byteSize, [[maybe_unused]] size_type alignment) override - { - return Base::DeAllocate(ptr, byteSize, Alignment); - } - - pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type /*newAlignment*/) override - { - return Base::ReAllocate(ptr, newSize, Alignment); - } - }; - - template - using aligned_alloc = AZ::AZStdAlloc>; - - ////////////////////////////////////////////////////////////////////////// - // Defines aligned vector type - ////////////////////////////////////////////////////////////////////////// - template - class aligned_vector - : public AZStd::vector > - { - public: - typedef aligned_alloc MyAlloc; - typedef AZStd::vector MySuperClass; - typedef aligned_vector MySelf; - typedef size_t size_type; - - aligned_vector() {} - explicit aligned_vector(const MyAlloc& _Al) - : MySuperClass(_Al) {} - explicit aligned_vector(size_type _Count) - : MySuperClass(_Count) {}; - aligned_vector(size_type _Count, const T& _Val) - : MySuperClass(_Count, _Val) {} - aligned_vector(size_type _Count, const T& _Val, const MyAlloc& _Al) - : MySuperClass(_Count, _Val) {} - aligned_vector(const MySelf& _Right) - : MySuperClass(_Right) {}; - - - template - aligned_vector(_Iter _First, _Iter _Last) - : MySuperClass(_First, _Last) {}; - - template - aligned_vector(_Iter _First, _Iter _Last, const MyAlloc& _Al) - : MySuperClass(_First, _Last, _Al) {}; - }; - - template - inline size_t size_of_aligned_vector(const Vec& c) - { - if (!c.empty()) - { - // Not really correct as not taking alignment into the account - return c.capacity() * sizeof(typename Vec::value_type); - } - return 0; - } -} // namespace stl - -// Specialize for the AlignedAllocator to provide one per module that does not use the -// environment for its storage. Since this allocator just uses LegacyAllocator -// to do the real work, it's fine if there is one of these per cry module -namespace AZ -{ - template - class AllocatorInstance> : public Internal::AllocatorInstanceBase, AllocatorStorage::ModuleStoragePolicy>> - { - }; -} diff --git a/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp b/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp index 2e6e646548..26d12ffd8c 100644 --- a/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp +++ b/Code/CryEngine/CrySystem/Tests/Test_CryPrimitives.cpp @@ -12,7 +12,6 @@ #include "CrySystem_precompiled.h" #include #include -#include TEST(StringTests, CUT_Strings) { @@ -424,21 +423,6 @@ TEST_F(CryPrimitives, CUT_FixedString) EXPECT_EQ("0123", str5); } -////////////////////////////////////////////////////////////////////////// -// Unit Testing of aligned_vector -////////////////////////////////////////////////////////////////////////// -TEST_F(CryPrimitives, CUT_AlignedVector) -{ - stl::aligned_vector vec; - - vec.push_back(1); - vec.push_back(2); - vec.push_back(3); - - EXPECT_TRUE(vec.size() == 3); - EXPECT_TRUE(((INT_PTR)(&vec[0]) % 16) == 0); -} - TEST_F(CryPrimitives, CUT_DynArray) { LegacyDynArray a; diff --git a/Code/Framework/AtomCore/.p4ignore b/Code/Framework/AtomCore/.p4ignore deleted file mode 100644 index 6722cd96e7..0000000000 --- a/Code/Framework/AtomCore/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.xml diff --git a/Code/Framework/AzCore/.p4ignore b/Code/Framework/AzCore/.p4ignore deleted file mode 100644 index 6722cd96e7..0000000000 --- a/Code/Framework/AzCore/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.xml diff --git a/Code/Sandbox/.p4ignore b/Code/Sandbox/.p4ignore deleted file mode 100644 index 9c6b6fcd91..0000000000 --- a/Code/Sandbox/.p4ignore +++ /dev/null @@ -1,5 +0,0 @@ -#Ignore these directories -SDKs - -#ignore these files -*.user diff --git a/Code/Tools/CMakeLists.txt b/Code/Tools/CMakeLists.txt index db5476756b..278474819c 100644 --- a/Code/Tools/CMakeLists.txt +++ b/Code/Tools/CMakeLists.txt @@ -15,7 +15,6 @@ add_subdirectory(AWSNativeSDKInit) add_subdirectory(AzTestRunner) add_subdirectory(CrashHandler) add_subdirectory(CryCommonTools) -add_subdirectory(CryXML) add_subdirectory(News) add_subdirectory(PythonBindingsExample) add_subdirectory(RemoteConsole) diff --git a/Code/Tools/CryCommonTools/CMakeLists.txt b/Code/Tools/CryCommonTools/CMakeLists.txt index 0188506e97..63f535b1af 100644 --- a/Code/Tools/CryCommonTools/CMakeLists.txt +++ b/Code/Tools/CryCommonTools/CMakeLists.txt @@ -13,44 +13,18 @@ if (NOT PAL_TRAIT_BUILD_HOST_TOOLS) return() endif() -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) - ly_add_target( NAME CryCommonTools STATIC NAMESPACE Legacy FILES_CMAKE crycommontools_files.cmake - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake INCLUDE_DIRECTORIES PUBLIC . - ${pal_dir} BUILD_DEPENDENCIES PRIVATE - 3rdParty::lz4 - 3rdParty::zlib - 3rdParty::zstd AZ::AzCore PUBLIC Legacy::CryCommon AZ::AzFramework ) - -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - ly_add_target( - NAME CryCommonTools.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE Legacy - FILES_CMAKE - crycommontools_tests_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - UnitTests - BUILD_DEPENDENCIES - PRIVATE - Legacy::CryCommonTools - AZ::AzTest - ) - ly_add_googletest( - NAME Legacy::CryCommonTools.Tests - ) -endif() diff --git a/Code/Tools/CryCommonTools/ColladaShared.h b/Code/Tools/CryCommonTools/ColladaShared.h deleted file mode 100644 index edc8341fe1..0000000000 --- a/Code/Tools/CryCommonTools/ColladaShared.h +++ /dev/null @@ -1,18 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_COLLADASHARED_H -#define CRYINCLUDE_CRYCOMMONTOOLS_COLLADASHARED_H -#pragma once - -static const char* g_LumberyardExportNodeTag = "LumberyardExportNode"; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_COLLADASHARED_H diff --git a/Code/Tools/CryCommonTools/Decompose.cpp b/Code/Tools/CryCommonTools/Decompose.cpp deleted file mode 100644 index 3cf88db251..0000000000 --- a/Code/Tools/CryCommonTools/Decompose.cpp +++ /dev/null @@ -1,514 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include - -// Taken from http://tog.acm.org/GraphicsGems/gemsiv/polar_decomp/Decompose.c - -/**** Decompose.c ****/ -/* Ken Shoemake, 1993 */ -#include -#include "Decompose.h" - -#pragma warning(disable:4244) // conversion from 'double' to 'float', possible loss of data -#pragma warning(disable:4305) // 'initializing' : truncation from 'double' to 'float' - -namespace decomp { - - /******* Matrix Preliminaries *******/ - - /** Fill out 3x3 matrix to 4x4 **/ -#define mat_pad(A) (A[W][X]=A[X][W]=A[W][Y]=A[Y][W]=A[W][Z]=A[Z][W]=0,A[W][W]=1) - -/** Copy nxn matrix A to C using "gets" for assignment **/ -#define mat_copy(C,gets,A,n) {int i,j; for(i=0;i= 0.0) { - s = sqrt(tr + mat[W][W]); - qu.w = s * 0.5; - s = 0.5 / s; - qu.x = (mat[Z][Y] - mat[Y][Z]) * s; - qu.y = (mat[X][Z] - mat[Z][X]) * s; - qu.z = (mat[Y][X] - mat[X][Y]) * s; - } else { - int h = X; - if (mat[Y][Y] > mat[X][X]) h = Y; - if (mat[Z][Z] > mat[h][h]) h = Z; - switch (h) { -#define caseMacro(i,j,k,I,J,K) \ - case I:\ - s = sqrt( (mat[I][I] - (mat[J][J]+mat[K][K])) + mat[W][W] );\ - qu.i = s*0.5;\ - s = 0.5 / s;\ - qu.j = (mat[I][J] + mat[J][I]) * s;\ - qu.k = (mat[K][I] + mat[I][K]) * s;\ - qu.w = (mat[K][J] - mat[J][K]) * s;\ - break - caseMacro(x, y, z, X, Y, Z); - caseMacro(y, z, x, Y, Z, X); - caseMacro(z, x, y, Z, X, Y); - } - } - if (mat[W][W] != 1.0) qu = Qt_Scale(qu, 1 / sqrt(mat[W][W])); - return (qu); - } - /******* Decomp Auxiliaries *******/ - - static HMatrix mat_id = { {1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1} }; - - /** Compute either the 1 or infinity norm of M, depending on tpose **/ - float mat_norm(HMatrix M, int tpose) - { - int i; - float sum, max; - max = 0.0; - for (i = 0; i < 3; i++) { - if (tpose) sum = fabs(M[0][i]) + fabs(M[1][i]) + fabs(M[2][i]); - else sum = fabs(M[i][0]) + fabs(M[i][1]) + fabs(M[i][2]); - if (max < sum) max = sum; - } - return max; - } - - float norm_inf(HMatrix M) { return mat_norm(M, 0); } - float norm_one(HMatrix M) { return mat_norm(M, 1); } - - /** Return index of column of M containing maximum abs entry, or -1 if M=0 **/ - int find_max_col(HMatrix M) - { - float abs, max; - int i, j, col; - max = 0.0; col = -1; - for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { - abs = M[i][j]; if (abs < 0.0) abs = -abs; - if (abs > max) { max = abs; col = j; } - } - return col; - } - - /** Setup u for Household reflection to zero all v components but first **/ - void make_reflector(float* v, float* u) - { - float s = sqrt(vdot(v, v)); - u[0] = v[0]; u[1] = v[1]; - u[2] = v[2] + ((v[2] < 0.0) ? -s : s); - s = sqrt(2.0 / vdot(u, u)); - u[0] = u[0] * s; u[1] = u[1] * s; u[2] = u[2] * s; - } - - /** Apply Householder reflection represented by u to column vectors of M **/ - void reflect_cols(HMatrix M, float* u) - { - int i, j; - for (i = 0; i < 3; i++) { - float s = u[0] * M[0][i] + u[1] * M[1][i] + u[2] * M[2][i]; - for (j = 0; j < 3; j++) M[j][i] -= u[j] * s; - } - } - /** Apply Householder reflection represented by u to row vectors of M **/ - void reflect_rows(HMatrix M, float* u) - { - int i, j; - for (i = 0; i < 3; i++) { - float s = vdot(u, M[i]); - for (j = 0; j < 3; j++) M[i][j] -= u[j] * s; - } - } - - /** Find orthogonal factor Q of rank 1 (or less) M **/ - void do_rank1(HMatrix M, HMatrix Q) - { - float v1[3], v2[3], s; - int col; - mat_copy(Q, =, mat_id, 4); - /* If rank(M) is 1, we should find a non-zero column in M */ - col = find_max_col(M); - if (col < 0) return; /* Rank is 0 */ - v1[0] = M[0][col]; v1[1] = M[1][col]; v1[2] = M[2][col]; - make_reflector(v1, v1); reflect_cols(M, v1); - v2[0] = M[2][0]; v2[1] = M[2][1]; v2[2] = M[2][2]; - make_reflector(v2, v2); reflect_rows(M, v2); - s = M[2][2]; - if (s < 0.0) Q[2][2] = -1.0; - reflect_cols(Q, v1); reflect_rows(Q, v2); - } - - /** Find orthogonal factor Q of rank 2 (or less) M using adjoint transpose **/ - void do_rank2(HMatrix M, HMatrix MadjT, HMatrix Q) - { - float v1[3], v2[3]; - float w, x, y, z, c, s, d; - int col; - /* If rank(M) is 2, we should find a non-zero column in MadjT */ - col = find_max_col(MadjT); - if (col < 0) { do_rank1(M, Q); return; } /* Rank<2 */ - v1[0] = MadjT[0][col]; v1[1] = MadjT[1][col]; v1[2] = MadjT[2][col]; - make_reflector(v1, v1); reflect_cols(M, v1); - vcross(M[0], M[1], v2); - make_reflector(v2, v2); reflect_rows(M, v2); - w = M[0][0]; x = M[0][1]; y = M[1][0]; z = M[1][1]; - if (w * z > x* y) { - c = z + w; s = y - x; d = sqrt(c * c + s * s); c = c / d; s = s / d; - Q[0][0] = Q[1][1] = c; Q[0][1] = -(Q[1][0] = s); - } else { - c = z - w; s = y + x; d = sqrt(c * c + s * s); c = c / d; s = s / d; - Q[0][0] = -(Q[1][1] = c); Q[0][1] = Q[1][0] = s; - } - Q[0][2] = Q[2][0] = Q[1][2] = Q[2][1] = 0.0; Q[2][2] = 1.0; - reflect_cols(Q, v1); reflect_rows(Q, v2); - } - - - /******* Polar Decomposition *******/ - - /* Polar Decomposition of 3x3 matrix in 4x4, - * M = QS. See Nicholas Higham and Robert S. Schreiber, - * Fast Polar Decomposition of An Arbitrary Matrix, - * Technical Report 88-942, October 1988, - * Department of Computer Science, Cornell University. - */ - float polar_decomp(HMatrix M, HMatrix Q, HMatrix S) - { -#define TOL 1.0e-6 - HMatrix Mk, MadjTk, Ek; - float det, M_one, M_inf, MadjT_one, MadjT_inf, E_one, gamma, g1, g2; - int i, j; - mat_tpose(Mk, =, M, 3); - M_one = norm_one(Mk); M_inf = norm_inf(Mk); - do { - adjoint_transpose(Mk, MadjTk); - det = vdot(Mk[0], MadjTk[0]); - if (det == 0.0) { do_rank2(Mk, MadjTk, Mk); break; } - MadjT_one = norm_one(MadjTk); MadjT_inf = norm_inf(MadjTk); - gamma = sqrt(sqrt((MadjT_one * MadjT_inf) / (M_one * M_inf)) / fabs(det)); - g1 = gamma * 0.5; - g2 = 0.5 / (gamma * det); - mat_copy(Ek, =, Mk, 3); - mat_binop(Mk, =, g1 * Mk, +, g2 * MadjTk, 3); - mat_copy(Ek, -=, Mk, 3); - E_one = norm_one(Ek); - M_one = norm_one(Mk); M_inf = norm_inf(Mk); - } while (E_one > (M_one * TOL)); - mat_tpose(Q, =, Mk, 3); mat_pad(Q); - mat_mult(Mk, M, S); mat_pad(S); - for (i = 0; i < 3; i++) for (j = i; j < 3; j++) - S[i][j] = S[j][i] = 0.5 * (S[i][j] + S[j][i]); - return (det); - } - - - - - - - - - - - - - - - - - - /******* Spectral Decomposition *******/ - - /* Compute the spectral decomposition of symmetric positive semi-definite S. - * Returns rotation in U and scale factors in result, so that if K is a diagonal - * matrix of the scale factors, then S = U K (U transpose). Uses Jacobi method. - * See Gene H. Golub and Charles F. Van Loan. Matrix Computations. Hopkins 1983. - */ - HVect spect_decomp(HMatrix S, HMatrix U) - { - HVect kv; - double Diag[3], OffD[3]; /* OffD is off-diag (by omitted index) */ - double g, h, fabsh, fabsOffDi, t, theta, c, s, tau, ta, OffDq, a, b; - static char nxt[] = { Y,Z,X }; - int sweep, i, j; - mat_copy(U, =, mat_id, 4); - Diag[X] = S[X][X]; Diag[Y] = S[Y][Y]; Diag[Z] = S[Z][Z]; - OffD[X] = S[Y][Z]; OffD[Y] = S[Z][X]; OffD[Z] = S[X][Y]; - for (sweep = 20; sweep > 0; sweep--) { - float sm = fabs(OffD[X]) + fabs(OffD[Y]) + fabs(OffD[Z]); - if (sm == 0.0) break; - for (i = Z; i >= X; i--) { - int p = nxt[i]; int q = nxt[p]; - fabsOffDi = fabs(OffD[i]); - g = 100.0 * fabsOffDi; - if (fabsOffDi > 0.0) { - h = Diag[q] - Diag[p]; - fabsh = fabs(h); - if (fabsh + g == fabsh) { - t = OffD[i] / h; - } else { - theta = 0.5 * h / OffD[i]; - t = 1.0 / (fabs(theta) + sqrt(theta * theta + 1.0)); - if (theta < 0.0) t = -t; - } - c = 1.0 / sqrt(t * t + 1.0); s = t * c; - tau = s / (c + 1.0); - ta = t * OffD[i]; OffD[i] = 0.0; - Diag[p] -= ta; Diag[q] += ta; - OffDq = OffD[q]; - OffD[q] -= s * (OffD[p] + tau * OffD[q]); - OffD[p] += s * (OffDq - tau * OffD[p]); - for (j = Z; j >= X; j--) { - a = U[j][p]; b = U[j][q]; - U[j][p] -= s * (b + tau * a); - U[j][q] += s * (a - tau * b); - } - } - } - } - kv.x = Diag[X]; kv.y = Diag[Y]; kv.z = Diag[Z]; kv.w = 1.0; - return (kv); - } - - /******* Spectral Axis Adjustment *******/ - - /* Given a unit quaternion, q, and a scale vector, k, find a unit quaternion, p, - * which permutes the axes and turns freely in the plane of duplicate scale - * factors, such that q p has the largest possible w component, i.e. the - * smallest possible angle. Permutes k's components to go with q p instead of q. - * See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition. - * Proceedings of Graphics Interface 1992. Details on p. 262-263. - */ - Quat snuggle(Quat q, HVect* k) - { -#define SQRTHALF (0.7071067811865475244f) -#define sgn(n,v) ((n)?-(v):(v)) -#define swap(a,i,j) {a[3]=a[i]; a[i]=a[j]; a[j]=a[3];} -#define cycle(a,p) if (p) {a[3]=a[0]; a[0]=a[1]; a[1]=a[2]; a[2]=a[3];}\ - else {a[3]=a[2]; a[2]=a[1]; a[1]=a[0]; a[0]=a[3];} - Quat p; - float ka[4]; - int i, turn = -1; - ka[X] = k->x; ka[Y] = k->y; ka[Z] = k->z; - if (ka[X] == ka[Y]) { if (ka[X] == ka[Z]) turn = W; else turn = Z; } - else { if (ka[X] == ka[Z]) turn = Y; else if (ka[Y] == ka[Z]) turn = X; } - if (turn >= 0) { - Quat qtoz, qp; - unsigned neg[3], win; - double mag[3], t; - static Quat qxtoz = { 0,SQRTHALF,0,SQRTHALF }; - static Quat qytoz = { SQRTHALF,0,0,SQRTHALF }; - static Quat qppmm = { 0.5, 0.5,-0.5,-0.5 }; - static Quat qpppp = { 0.5, 0.5, 0.5, 0.5 }; - static Quat qmpmm = { -0.5, 0.5,-0.5,-0.5 }; - static Quat qpppm = { 0.5, 0.5, 0.5,-0.5 }; - static Quat q0001 = { 0.0, 0.0, 0.0, 1.0 }; - static Quat q1000 = { 1.0, 0.0, 0.0, 0.0 }; - switch (turn) { - default: return (Qt_Conj(q)); - case X: q = Qt_Mul(q, qtoz = qxtoz); swap(ka, X, Z) break; - case Y: q = Qt_Mul(q, qtoz = qytoz); swap(ka, Y, Z) break; - case Z: qtoz = q0001; break; - } - q = Qt_Conj(q); - mag[0] = (double)q.z * q.z + (double)q.w * q.w - 0.5; - mag[1] = (double)q.x * q.z - (double)q.y * q.w; - mag[2] = (double)q.y * q.z + (double)q.x * q.w; - for (i = 0; i < 3; i++) if (neg[i] = (mag[i] < 0.0)) mag[i] = -mag[i]; - if (mag[0] > mag[1]) { if (mag[0] > mag[2]) win = 0; else win = 2; } - else { if (mag[1] > mag[2]) win = 1; else win = 2; } - switch (win) { - case 0: if (neg[0]) p = q1000; else p = q0001; break; - case 1: if (neg[1]) p = qppmm; else p = qpppp; cycle(ka, 0) break; - case 2: if (neg[2]) p = qmpmm; else p = qpppm; cycle(ka, 1) break; - } - qp = Qt_Mul(q, p); - t = sqrt(mag[win] + 0.5); - p = Qt_Mul(p, Qt_(0.0, 0.0, -qp.z / t, qp.w / t)); - p = Qt_Mul(qtoz, Qt_Conj(p)); - } else { - float qa[4], pa[4]; - unsigned lo, hi, neg[4], par = 0; - double all, big, two; - qa[0] = q.x; qa[1] = q.y; qa[2] = q.z; qa[3] = q.w; - for (i = 0; i < 4; i++) { - pa[i] = 0.0; - if (neg[i] = (qa[i] < 0.0)) qa[i] = -qa[i]; - par ^= neg[i]; - } - /* Find two largest components, indices in hi and lo */ - if (qa[0] > qa[1]) lo = 0; else lo = 1; - if (qa[2] > qa[3]) hi = 2; else hi = 3; - if (qa[lo] > qa[hi]) { - if (qa[lo ^ 1] > qa[hi]) { hi = lo; lo ^= 1; } - else { hi ^= lo; lo ^= hi; hi ^= lo; } - } else {if (qa[hi^1]>qa[lo]) lo = hi^1;} - all = (qa[0] + qa[1] + qa[2] + qa[3]) * 0.5; - two = (qa[hi] + qa[lo]) * SQRTHALF; - big = qa[hi]; - if (all > two) { - if (all > big) {/*all*/ - {int i; for (i = 0; i < 4; i++) pa[i] = sgn(neg[i], 0.5); } - cycle(ka, par) - } else {/*big*/ pa[hi] = sgn(neg[hi],1.0);} - } else { - if (two > big) {/*two*/ - pa[hi] = sgn(neg[hi], SQRTHALF); pa[lo] = sgn(neg[lo], SQRTHALF); - if (lo > hi) { hi ^= lo; lo ^= hi; hi ^= lo; } - if (hi == W) { hi = "\001\002\000"[lo]; lo = 3 - hi - lo; } - swap(ka, hi, lo) - } else {/*big*/ pa[hi] = sgn(neg[hi],1.0);} - } - p.x = -pa[0]; p.y = -pa[1]; p.z = -pa[2]; p.w = pa[3]; - } - k->x = ka[X]; k->y = ka[Y]; k->z = ka[Z]; - return (p); - } - - - - - - - - - - - - /******* Decompose Affine Matrix *******/ - - /* Decompose 4x4 affine matrix A as TFRUK(U transpose), where t contains the - * translation components, q contains the rotation R, u contains U, k contains - * scale factors, and f contains the sign of the determinant. - * Assumes A transforms column vectors in right-handed coordinates. - * See Ken Shoemake and Tom Duff. Matrix Animation and Polar Decomposition. - * Proceedings of Graphics Interface 1992. - */ - void decomp_affine(HMatrix A, AffineParts* parts) - { - HMatrix Q, S, U; - Quat p; - float det; - parts->t = Qt_(A[X][W], A[Y][W], A[Z][W], 0); - det = polar_decomp(A, Q, S); - if (det < 0.0) { - mat_copy(Q, =, -Q, 3); - parts->f = -1; - } else parts->f = 1; - parts->q = Qt_FromMatrix(Q); - parts->k = spect_decomp(S, U); - parts->u = Qt_FromMatrix(U); - p = snuggle(parts->u, &parts->k); - parts->u = Qt_Mul(parts->u, p); - } - - /******* Invert Affine Decomposition *******/ - - /* Compute inverse of affine decomposition. - */ - void invert_affine(AffineParts* parts, AffineParts* inverse) - { - Quat t, p; - inverse->f = parts->f; - inverse->q = Qt_Conj(parts->q); - inverse->u = Qt_Mul(parts->q, parts->u); - inverse->k.x = (parts->k.x == 0.0) ? 0.0 : 1.0 / parts->k.x; - inverse->k.y = (parts->k.y == 0.0) ? 0.0 : 1.0 / parts->k.y; - inverse->k.z = (parts->k.z == 0.0) ? 0.0 : 1.0 / parts->k.z; - inverse->k.w = parts->k.w; - t = Qt_(-parts->t.x, -parts->t.y, -parts->t.z, 0); - t = Qt_Mul(Qt_Conj(inverse->u), Qt_Mul(t, inverse->u)); - t = Qt_(inverse->k.x * t.x, inverse->k.y * t.y, inverse->k.z * t.z, 0); - p = Qt_Mul(inverse->q, inverse->u); - t = Qt_Mul(p, Qt_Mul(t, Qt_Conj(p))); - inverse->t = (inverse->f > 0.0) ? t : Qt_(-t.x, -t.y, -t.z, 0); - } - -} diff --git a/Code/Tools/CryCommonTools/Decompose.h b/Code/Tools/CryCommonTools/Decompose.h deleted file mode 100644 index 88e04737b6..0000000000 --- a/Code/Tools/CryCommonTools/Decompose.h +++ /dev/null @@ -1,30 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -namespace decomp { -// Taken from http://tog.acm.org/GraphicsGems/gemsiv/polar_decomp/Decompose.h - -/**** Decompose.h - Basic declarations ****/ -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H -#pragma once - -typedef struct {float x, y, z, w;} Quat; /* Quaternion */ -enum QuatPart {X, Y, Z, W}; -typedef Quat HVect; /* Homogeneous 3D vector */ -typedef float HMatrix[4][4]; /* Right-handed, for column vectors */ -typedef struct { - HVect t; /* Translation components */ - Quat q; /* Essential rotation */ - Quat u; /* Stretch rotation */ - HVect k; /* Stretch factors */ - float f; /* Sign of determinant */ -} AffineParts; -float polar_decomp(HMatrix M, HMatrix Q, HMatrix S); -HVect spect_decomp(HMatrix S, HMatrix U); -Quat snuggle(Quat q, HVect *k); -void decomp_affine(HMatrix A, AffineParts *parts); -void invert_affine(AffineParts *parts, AffineParts *inverse); - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_DECOMPOSE_H - -} diff --git a/Code/Tools/CryCommonTools/Exceptions.h b/Code/Tools/CryCommonTools/Exceptions.h deleted file mode 100644 index cc8830f0dd..0000000000 --- a/Code/Tools/CryCommonTools/Exceptions.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H -#pragma once - - -#include -#include - -class BaseException - : public std::exception -{ -public: - BaseException(const string& msg) - : msg(msg) {} - virtual const char* what() const throw () {return msg.c_str(); } - -private: - string msg; -}; - -template -class Exception - : public BaseException -{ -public: - Exception(const string& msg) - : BaseException(msg) {} -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_EXCEPTIONS_H diff --git a/Code/Tools/CryCommonTools/FileUtil.cpp b/Code/Tools/CryCommonTools/FileUtil.cpp deleted file mode 100644 index d42a60bcc2..0000000000 --- a/Code/Tools/CryCommonTools/FileUtil.cpp +++ /dev/null @@ -1,175 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "FileUtil.h" -#include "PathHelpers.h" -#include "StringHelpers.h" - -#include -#include - - -////////////////////////////////////////////////////////////////////////// -// returns true if 'dir' is a subdirectory of 'baseDir' or same directory as 'baseDir' -// note: returns false in case of wrong names passed -static bool IsSubdirOrSameDir(const char* dir, const char* baseDir) -{ - - AZ::IO::LocalFileIO localFileIO; - - char szFullPathDir[AZ_MAX_PATH_LEN]; - if(!localFileIO.ConvertToAbsolutePath(dir, szFullPathDir, sizeof(szFullPathDir))) - { - return false; - } - - char szFullPathBaseDir[2 * 1024]; - if(!localFileIO.ConvertToAbsolutePath(baseDir, szFullPathBaseDir, sizeof(szFullPathBaseDir))) - { - return false; - } - - const char* p = szFullPathDir; - const char* q = szFullPathBaseDir; - for (;; ++p, ++q) - { - if (tolower(*p) == tolower(*q)) - { - if (*p == 0) - { - // dir is exactly same as baseDir - return true; - } - continue; - } - - if ((*p == '/' || *p == '\\') && (*q == '/' || *q == '\\')) - { - continue; - } - - if (*p == 0) - { - // dir length is shorter than baseDir length. so it's not a subdir - return false; - } - - if (*q == 0) - { - // baseDir is shorter than dir. so may be it's a subdir. - const bool isSubdir = (*p == '/' || *p == '\\'); - return isSubdir; - } - - return false; - } -} - -////////////////////////////////////////////////////////////////////////// -// the paths must have trailing slash -static bool ScanDirectoryRecursive(const string& root, const string& path, const string& file, std::vector& files, bool recursive, const string& dirToIgnore) -{ - bool anyFound = false; - if (!dirToIgnore.empty()) - { - if (IsSubdirOrSameDir(root.c_str(), dirToIgnore.c_str())) - { - return anyFound; - } - } - - AZ::IO::LocalFileIO localFileIO; - localFileIO.FindFiles(root.c_str(), file.c_str(), [&](const char* filePath) -> bool - { - bool isDir = localFileIO.IsDirectory(filePath); - if (!isDir) - { - const string foundFilename(filePath); - if (StringHelpers::MatchesWildcardsIgnoreCase(foundFilename, file)) - { - anyFound = true; - files.push_back(PathHelpers::Join(path, PathHelpers::GetFilename(filePath))); - } - } - - return true; // Keep iterating - }); - - if (recursive) - { - localFileIO.FindFiles(root.c_str(), "*", [&](const char* filePath) -> bool - { - bool isDir = localFileIO.IsDirectory(filePath); - // If recursive. - if (isDir && strcmp(filePath, ".") && strcmp(filePath, "..")) - { - if (ScanDirectoryRecursive(filePath, PathHelpers::Join(path, PathHelpers::GetFilename(filePath)), file, files, recursive, dirToIgnore)) - { - anyFound = true; - } - } - return true; // Keep iterating - }); - } - - return anyFound; -} - -////////////////////////////////////////////////////////////////////////// - -bool FileUtil::ScanDirectory(const string& path, const string& file, std::vector& files, bool recursive, const string& dirToIgnore) -{ - return ScanDirectoryRecursive(path, "", file, files, recursive, dirToIgnore); -} - - -bool FileUtil::EnsureDirectoryExists(const char* szPathIn) -{ - if (!szPathIn || !szPathIn[0]) - { - return true; - } - - if (DirectoryExists(szPathIn)) - { - return true; - } - - std::vector path(szPathIn, szPathIn + strlen(szPathIn) + 1); - char* p = &path[0]; - - // Skip '/' and '//' in the beginning - while (*p == '/' || *p == '\\') - { - ++p; - } - - for (;; ) - { - while (*p != '/' && *p != '\\' && *p) - { - ++p; - } - const char saved = *p; - *p = 0; - AZ::IO::LocalFileIO().CreatePath(&path[0]); - *p++ = saved; - if (saved == 0) - { - break; - } - } - - return DirectoryExists(szPathIn); -} diff --git a/Code/Tools/CryCommonTools/FileUtil.h b/Code/Tools/CryCommonTools/FileUtil.h deleted file mode 100644 index cf258c074b..0000000000 --- a/Code/Tools/CryCommonTools/FileUtil.h +++ /dev/null @@ -1,311 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H -#pragma once - -#include -#include - -#include - -#if AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) -#include -#endif -#if defined(AZ_PLATFORM_LINUX) -#include "Linux64Specific.h" -#endif // defined(AZ_PLATFORM_LINUX) - -#include -#include - -namespace FileUtil -{ - // Magic number explanation: - // Both epochs are Gregorian. 1970 - 1601 = 369. Assuming a leap - // year every four years, 369 / 4 = 92. However, 1700, 1800, and 1900 - // were NOT leap years, so 89 leap years, 280 non-leap years. - // 89 * 366 + 280 * 365 = 134744 days between epochs. Of course - // 60 * 60 * 24 = 86400 seconds per day, so 134744 * 86400 = - // 11644473600 = SECS_BETWEEN_EPOCHS. - // - // This result is also confirmed in the MSDN documentation on how - // to convert a time_t value to a win32 FILETIME. - #define SECS_BETWEEN_EPOCHS 11644473600ll - /* 10^7 */ - #define SECS_TO_100NS 10000000ll - - // Find all files matching filespec. - bool ScanDirectory(const string& path, const string& filespec, std::vector& files, bool recursive, const string& dirToIgnore); - - // Ensures that directory specified by szPathIn exists by creating all needed (sub-)directories. - // Returns false in case of a failure. - // Example: "c:\temp\test" ("c:\temp\test\" also works) - ensures that "c:\temp\test" exists. - bool EnsureDirectoryExists(const char* szPathIn); - - // converts the FILETIME to the C Timestamp (compatible with dbghelp.dll) - inline DWORD FiletimeToUnixTime(const FILETIME& ft) - { - return (DWORD)((((int64&)ft) / SECS_TO_100NS) - SECS_BETWEEN_EPOCHS); - } - - // converts the FILETIME to 64bit C timestamp - inline AZ::u64 FiletimeTo64BitUnixTime(const FILETIME& fileTime) - { - const AZ::u64 time = static_cast(fileTime.dwHighDateTime) << 32 | fileTime.dwLowDateTime; - return ((time / SECS_TO_100NS) - SECS_BETWEEN_EPOCHS); - } - - // converts the C Timestamp (compatible with dbghelp.dll) to FILETIME - inline FILETIME UnixTimeToFiletime(DWORD nCTime) - { - const int64 time = (nCTime + SECS_BETWEEN_EPOCHS) * SECS_TO_100NS; - return (FILETIME&)time; - } - - //converts the 64 bit C Timestamp to FILETIME - inline void UnixTime64BitToFiletime(AZ::u64 nCTime, FILETIME& fileTime) - { - const AZ::u64 time = (nCTime + SECS_BETWEEN_EPOCHS) * SECS_TO_100NS; - fileTime.dwLowDateTime = static_cast(time); - fileTime.dwHighDateTime = static_cast(time >> 32); - } - - inline FILETIME GetInvalidFileTime() - { - FILETIME fileTime; - fileTime.dwLowDateTime = 0; - fileTime.dwHighDateTime = 0; - return fileTime; - } - - // returns file time stamps -#if defined(AZ_PLATFORM_WINDOWS) - inline bool GetFileTimes(const char* filename, FILETIME* ftimeCreate = nullptr, FILETIME* ftimeAccess = nullptr, FILETIME* ftimeModify = nullptr) - { - WIN32_FIND_DATAA FindFileData; - const HANDLE hFind = FindFirstFileA(filename, &FindFileData); - if (hFind == INVALID_HANDLE_VALUE) - { - return false; - } - - if (ftimeModify == nullptr && ftimeCreate == nullptr && ftimeAccess == nullptr) - { - FindClose(hFind); - return true; - } - - FindClose(hFind); - if (ftimeCreate) - { - ftimeCreate->dwLowDateTime = FindFileData.ftCreationTime.dwLowDateTime; - ftimeCreate->dwHighDateTime = FindFileData.ftCreationTime.dwHighDateTime; - } - if (ftimeModify) - { - ftimeModify->dwLowDateTime = FindFileData.ftLastWriteTime.dwLowDateTime; - ftimeModify->dwHighDateTime = FindFileData.ftLastWriteTime.dwHighDateTime; - } - if (ftimeAccess) - { - ftimeAccess->dwLowDateTime = FindFileData.ftLastAccessTime.dwLowDateTime; - ftimeAccess->dwHighDateTime = FindFileData.ftCreationTime.dwHighDateTime; - } - return true; - } -#else - inline bool GetFileTimes(const char* filename, AZ::u64* timeCreate = nullptr, AZ::u64* timeAccess = nullptr, AZ::u64* timeModify = nullptr) - { - - struct stat statResult; - if (stat(filename, &statResult) != 0) - { - return false; - } - - if (timeCreate) - { - *timeCreate =static_cast(statResult.st_ctime); - } - if (timeModify) - { - *timeModify =static_cast(statResult.st_mtime); - } - if (timeAccess) - { - *timeAccess =static_cast(statResult.st_atime); - } - return true; - } -#endif - - - - inline FILETIME GetLastWriteFileTime(const char* filename) - { - FILETIME timeModify = GetInvalidFileTime(); -#if defined(AZ_PLATFORM_WINDOWS) - GetFileTimes(filename, nullptr, nullptr, &timeModify); -#else - AZ::u64 modTime = 0; - GetFileTimes(filename, nullptr, nullptr, &modTime); - if(modTime != 0) - { - UnixTime64BitToFiletime(modTime, timeModify); - } -#endif - return timeModify; - } - - inline bool FileTimesAreEqual(const FILETIME& fileTime0, const FILETIME& fileTime1) - { - return - (fileTime0.dwLowDateTime == fileTime1.dwLowDateTime) && - (fileTime0.dwHighDateTime == fileTime1.dwHighDateTime); - } - - inline bool FileTimesAreEqual(const char* const srcfilename, const char* const targetfilename) - { - FILETIME ftSource = FileUtil::GetLastWriteFileTime(srcfilename); - FILETIME ftTarget = FileUtil::GetLastWriteFileTime(targetfilename); - return FileTimesAreEqual(ftSource, ftTarget); - } - - inline bool FileTimeIsValid(const FILETIME& fileTime) - { - return !FileTimesAreEqual(GetInvalidFileTime(), fileTime); - } - - inline bool SetFileTimes(const char* const filename, const FILETIME& creationFileTime, const FILETIME& accessFileTime, const FILETIME& modifcationFileTime) - { -#if defined(AZ_PLATFORM_WINDOWS) - const HANDLE hf = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } -#else - AZ::u64 creationTime = FiletimeTo64BitUnixTime(creationFileTime); - AZ::u64 modificationTime = FiletimeTo64BitUnixTime(modifcationFileTime); - - struct utimbuf puttime; - puttime.modtime = modificationTime; - puttime.actime = creationTime; - - if (utime(filename, &puttime) == 0) - { - return true; - } - -#endif - return false; - } - - inline bool SetFileTimes(const char* const filename, const FILETIME& fileTime) - { -#if defined(AZ_PLATFORM_WINDOWS) - const HANDLE hf = CreateFileA(filename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &fileTime, &fileTime, &fileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } -#else - - AZ::u64 newTime = FiletimeTo64BitUnixTime(fileTime); - - struct utimbuf puttime; - puttime.modtime = newTime; - puttime.actime = newTime; - - if (utime(filename, &puttime) == 0) - { - return true; - } -#endif - return false; - } - - inline bool SetFileTimes(const char* const srcfilename, const char* const targetfilename) - { -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME creationFileTime, accessFileTime, modifcationFileTime; - if (GetFileTimes(srcfilename, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - const HANDLE hf = CreateFileA(targetfilename, FILE_WRITE_ATTRIBUTES, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); - if (hf != INVALID_HANDLE_VALUE) - { - if (SetFileTime(hf, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - if (CloseHandle(hf)) - { - return true; - } - } - - CloseHandle(hf); - } - } -#else - AZ::u64 creationFileTime, accessFileTime, modifcationFileTime; - if (GetFileTimes(srcfilename, &creationFileTime, &accessFileTime, &modifcationFileTime)) - { - struct utimbuf puttime; - puttime.modtime = modifcationFileTime; - puttime.actime = accessFileTime; - - if (utime(targetfilename, &puttime) == 0) - { - return true; - } - } -#endif - return false; - } - - inline uint64 GetFileSize(const char* const filename) - { - AZ::u64 fileSize = AZ::IO::SystemFile::Length(filename); - return fileSize >= 0? fileSize : -1; - - } - - inline bool FileExists(const char* szPath) - { - return AZ::IO::LocalFileIO().Exists(szPath); - } - - inline bool DirectoryExists(const char* szPath) - { - return AZ::IO::LocalFileIO().IsDirectory(szPath); - } -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_FILEUTIL_H diff --git a/Code/Tools/CryCommonTools/FileXmlBufferSource.h b/Code/Tools/CryCommonTools/FileXmlBufferSource.h deleted file mode 100644 index de802a3311..0000000000 --- a/Code/Tools/CryCommonTools/FileXmlBufferSource.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H -#pragma once - - -class FileXmlBufferSource - : public IXmlBufferSource -{ -public: - FileXmlBufferSource(const char* path) - { - file = std::fopen(path, "r"); - } - ~FileXmlBufferSource() - { - if (file) - { - std::fclose(file); - } - } - - virtual int Read(void* buffer, int size) const - { - if (!file) - { - return 0; - } - return std::fread(buffer, 1, size, file); - } - -private: - mutable std::FILE* file; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_FILEXMLBUFFERSOURCE_H diff --git a/Code/Tools/CryCommonTools/ILogger.h b/Code/Tools/CryCommonTools/ILogger.h deleted file mode 100644 index cbcbae3094..0000000000 --- a/Code/Tools/CryCommonTools/ILogger.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H -#pragma once - - -#include -#include - -class ILogger -{ -public: - enum ESeverity - { - eSeverity_Debug, - eSeverity_Info, - eSeverity_Warning, - eSeverity_Error - }; - - virtual ~ILogger() - { - } - - void Log(ESeverity eSeverity, const char* const format, ...) - { - char buffer[2048]; - { - va_list args; - va_start(args, format); - _vsnprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, format, args); - va_end(args); - } - LogImpl(eSeverity, buffer); - } - -protected: - virtual void LogImpl(ESeverity eSeverity, const char* text) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ILOGGER_H diff --git a/Code/Tools/CryCommonTools/IPakSystem.h b/Code/Tools/CryCommonTools/IPakSystem.h deleted file mode 100644 index d8646c3a2c..0000000000 --- a/Code/Tools/CryCommonTools/IPakSystem.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H -#define CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H -#pragma once - -#include - -struct PakSystemFile; -struct PakSystemArchive; -struct IPakSystem -{ - virtual PakSystemFile* Open(const char* filename, const char* mode) = 0; - virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0) = 0; - virtual void Close(PakSystemFile* file) = 0; - virtual int GetLength(PakSystemFile* file) const = 0; - virtual int Read(PakSystemFile* file, void* buffer, int size) = 0; - virtual bool EoF(PakSystemFile* file) = 0; - - virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment = 1, bool encrypted = false, const uint32 encryptionKey[4] = 0) = 0; - virtual void CloseArchive(PakSystemArchive* archive) = 0; - - // Summary: - // Adds a new file to the pak or update an existing one. - // Adds a directory (creates several nested directories if needed) - // Arguments: - // path - relative path inside archive - // data, size - file content - // modTime - modification timestamp of the file - // compressionLevel - level of compression (correnponds to zlib-levels): - // -1 or [0-9] where -1=default compression, 0=no compression, 9=best compression - virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel = -1) = 0; - - virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path) = 0; - virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime) = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_IPAKSYSTEM_H diff --git a/Code/Tools/CryCommonTools/ISettings.h b/Code/Tools/CryCommonTools/ISettings.h deleted file mode 100644 index bba3100215..0000000000 --- a/Code/Tools/CryCommonTools/ISettings.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H -#pragma once - - -class ISettings -{ -public: - virtual bool GetSettingString(char* buffer, int bufferSizeInBytes, const char* key) = 0; - virtual bool GetSettingInt(int& value, const char* key) = 0; -}; - -inline bool GetSettingByRef(ISettings* settings, const string& key, string& value) -{ - char buffer[1024]; - bool success = false; - if (settings) - { - success = settings->GetSettingString(buffer, sizeof(buffer), key.c_str()); - } - if (success) - { - value = buffer; - } - return success; -} - -inline bool GetSettingByRef(ISettings* settings, const string& key, int& value) -{ - return settings->GetSettingInt(value, key.c_str()); -} - -template -inline T GetSetting(ISettings* settings, const string& key, const T& dflt) -{ - T value; - if (!GetSettingByRef(settings, key, value)) - { - value = dflt; - } - return value; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ISETTINGS_H diff --git a/Code/Tools/CryCommonTools/LocaleChanger.cpp b/Code/Tools/CryCommonTools/LocaleChanger.cpp deleted file mode 100644 index 3a9edee30a..0000000000 --- a/Code/Tools/CryCommonTools/LocaleChanger.cpp +++ /dev/null @@ -1,27 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "LocaleChanger.h" -#include - -LocaleChanger::LocaleChanger(int category, const char* newLocale) -{ - m_category = category; - m_oldLocale = setlocale(category, newLocale); -} - -LocaleChanger::~LocaleChanger() -{ - setlocale(m_category, m_oldLocale.c_str()); -} diff --git a/Code/Tools/CryCommonTools/LocaleChanger.h b/Code/Tools/CryCommonTools/LocaleChanger.h deleted file mode 100644 index 3b85c462a2..0000000000 --- a/Code/Tools/CryCommonTools/LocaleChanger.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H -#pragma once - - -class LocaleChanger -{ -public: - LocaleChanger(int category, const char* newLocale); - ~LocaleChanger(); - -private: - int m_category; - string m_oldLocale; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_LOCALECHANGER_H diff --git a/Code/Tools/CryCommonTools/LogFile.cpp b/Code/Tools/CryCommonTools/LogFile.cpp deleted file mode 100644 index ef98be776b..0000000000 --- a/Code/Tools/CryCommonTools/LogFile.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "LogFile.h" - -LogFile::LogFile(const char* const filename) - : m_file(0) - , m_hasWarnings(false) - , m_hasErrors(false) -{ - m_file = std::fopen(filename, "w"); -} - -LogFile::~LogFile() -{ - if (m_file) - { - fclose(m_file); - } -} - -bool LogFile::IsOpen() const -{ - return m_file != 0; -} - -bool LogFile::HasWarningsOrErrors() const -{ - return m_hasWarnings || m_hasErrors; -} - -void LogFile::LogImpl(ESeverity eSeverity, const char* const text) -{ - const char* severityMessage = 0; - switch (eSeverity) - { - case eSeverity_Debug: - severityMessage = " "; - break; - case eSeverity_Info: - severityMessage = " "; - break; - case eSeverity_Warning: - severityMessage = "W: "; - break; - case eSeverity_Error: - severityMessage = "E: "; - break; - default: - severityMessage = "?: "; - break; - } - - if (eSeverity == eSeverity_Warning) - { - m_hasWarnings = true; - } - if (eSeverity == eSeverity_Error) - { - m_hasErrors = true; - } - - if (m_file) - { - fprintf(m_file, "%s%s\n", severityMessage, text); - fflush(m_file); - } -} diff --git a/Code/Tools/CryCommonTools/LogFile.h b/Code/Tools/CryCommonTools/LogFile.h deleted file mode 100644 index d26c457165..0000000000 --- a/Code/Tools/CryCommonTools/LogFile.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H -#pragma once - - -#include "ILogger.h" - -class LogFile - : public ILogger -{ -public: - LogFile(const char* filename); - ~LogFile(); - - bool IsOpen() const; - bool HasWarningsOrErrors() const; - - // ILogger - virtual void LogImpl(ESeverity eSeverity, const char* message); - -private: - std::FILE* m_file; - bool m_hasWarnings; - bool m_hasErrors; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_LOGFILE_H diff --git a/Code/Tools/CryCommonTools/MathHelpers.h b/Code/Tools/CryCommonTools/MathHelpers.h deleted file mode 100644 index d21c14aa6c..0000000000 --- a/Code/Tools/CryCommonTools/MathHelpers.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H -#pragma once - - -#include -#if (_M_IX86_FP > 0) -#include -#endif - -namespace MathHelpers -{ -#if (_M_IX86_FP > 0) - inline int FastRoundFloatTowardZero(float f) - { - return _mm_cvtt_ss2si(_mm_set_ss(f)); - } -#else - inline int FastRoundFloatTowardZero(float f) - { - return int(f); - } -#endif - -#if defined(AZ_PLATFORM_WINDOWS) - - inline unsigned int EnableFloatingPointExceptions(unsigned int mask) - { - _clearfp(); - unsigned int oldMask; - _controlfp_s(&oldMask, 0, 0); - unsigned int newMask; - _controlfp_s(&newMask, ~mask, _MCW_EM); - return ~oldMask; - } - - class AutoFloatingPointExceptions - { - public: - AutoFloatingPointExceptions(const unsigned int mask) - : m_mask(EnableFloatingPointExceptions(mask)) - { - } - - ~AutoFloatingPointExceptions() - { - EnableFloatingPointExceptions(m_mask); - } - - private: - unsigned int m_mask; - }; - -#endif //AZ_PLATFORM_WINDOWS -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_MATHHELPERS_H - - diff --git a/Code/Tools/CryCommonTools/ModuleHelpers.cpp b/Code/Tools/CryCommonTools/ModuleHelpers.cpp deleted file mode 100644 index 2ce5c2639a..0000000000 --- a/Code/Tools/CryCommonTools/ModuleHelpers.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "ModuleHelpers.h" - -HMODULE ModuleHelpers::GetCurrentModule(CurrentModuleSpecifier moduleSpecifier) -{ - switch (moduleSpecifier) - { - case CurrentModuleSpecifier_Executable: - return GetModuleHandle(0); - - case CurrentModuleSpecifier_Library: - MEMORY_BASIC_INFORMATION mbi; - static int dummy; - VirtualQuery(&dummy, &mbi, sizeof(mbi)); - HMODULE instance = reinterpret_cast(mbi.AllocationBase); - return instance; - } - - return 0; -} - -std::basic_string ModuleHelpers::GetCurrentModulePath(CurrentModuleSpecifier moduleSpecifier) -{ - // Here's a trick that will get you the handle of the module - // you're running in without any a-priori knowledge: - // http://www.dotnet247.com/247reference/msgs/13/65259.aspx - HMODULE instance = GetCurrentModule(moduleSpecifier); - TCHAR moduleNameBuffer[MAX_PATH]; - GetModuleFileName(instance, moduleNameBuffer, sizeof(moduleNameBuffer) / sizeof(moduleNameBuffer[0])); - return moduleNameBuffer; -} diff --git a/Code/Tools/CryCommonTools/ModuleHelpers.h b/Code/Tools/CryCommonTools/ModuleHelpers.h deleted file mode 100644 index cb9049e89b..0000000000 --- a/Code/Tools/CryCommonTools/ModuleHelpers.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_MODULEHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_MODULEHELPERS_H -#pragma once - - -namespace ModuleHelpers -{ - enum CurrentModuleSpecifier - { - CurrentModuleSpecifier_Executable, - CurrentModuleSpecifier_Library - }; - - HMODULE GetCurrentModule(CurrentModuleSpecifier moduleSpecifier); - std::basic_string GetCurrentModulePath(CurrentModuleSpecifier moduleSpecifier); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_MODULEHELPERS_H diff --git a/Code/Tools/CryCommonTools/PakSystem.cpp b/Code/Tools/CryCommonTools/PakSystem.cpp deleted file mode 100644 index 42a129c5e6..0000000000 --- a/Code/Tools/CryCommonTools/PakSystem.cpp +++ /dev/null @@ -1,380 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "PakSystem.h" -#include "PathHelpers.h" -#include "StringHelpers.h" -#include "ZipDir/ZipDir.h" - -#include -#include -#include - - - -PakSystemFile::PakSystemFile() -{ - type = PakSystemFileType_Unknown; - file = NULL; - zip = NULL; - fileEntry = NULL; - data = NULL; - dataPosition = 0; -} - -PakSystem::PakSystem() -{ -} - -PakSystemFile* PakSystem::Open(const char* a_path, const char* a_mode) -{ - string normalPath = a_path; - - string const zipExt = ".zip"; - bool bZip = StringHelpers::EndsWithIgnoreCase(normalPath, zipExt); - - if (bZip) - { - // If it's a .zip file, then we'll try to look for a file without .zip extension inside of the .zip file - normalPath.erase(normalPath.length() - zipExt.length(), zipExt.length()); - } - - string zipPath = normalPath + zipExt; - string filename = PathHelpers::GetFilename(normalPath); - - if (!normalPath.empty() && normalPath[0] == '@') - { - // File is inside pak file. - int splitter = normalPath.find_first_of("|;,"); - if (splitter >= 0) - { - zipPath = normalPath.substr(1, splitter - 1); - filename = StringHelpers::MakeLowerCase(normalPath.substr(splitter + 1)); - bZip = true; - } - else - { - return 0; - } - } - - if (!bZip) - { - // Try to open the file. - FILE* f = nullptr; - azfopen(&f, normalPath.c_str(), a_mode); - if (f) - { - std::unique_ptr file(new PakSystemFile()); - file->type = PakSystemFileType_File; - file->file = f; - - return file.release(); - } - } - - // if it's simple and read-only, it's assumed it's read-only - unsigned const nFactoryFlags = ZipDir::CacheFactory::FLAGS_DONT_COMPACT | ZipDir::CacheFactory::FLAGS_READ_ONLY; - - bool bFileExists = false; - const uint32* decryptionKey = 0; // use default one - - if (bZip) - { - // a caller asked to open a .zip file. check if the .zip file on disk exist - FILE* f = nullptr; - azfopen(&f, zipPath.c_str(), "rb"); - if (f) - { - fclose(f); - bFileExists = true; - } - } - else - { - // a caller specified normal file. we already failed to find it on disk, - // so the file could be within a .pak file. let's find all 'potential' - // pak files and look within these for a matching file - - std::vector foundFileCountainer; // pak files found - - for (string dirToSearch = normalPath;; ) - { - dirToSearch = PathHelpers::GetDirectory(dirToSearch); - - AZ::IO::LocalFileIO localFileIO; - localFileIO.FindFiles(dirToSearch.c_str(), "*.pak", [&](const char* filePath) -> bool - { - const string foundFilename(filePath); - if (StringHelpers::EqualsIgnoreCase(PathHelpers::FindExtension(foundFilename), "pak")) - { - foundFileCountainer.push_back(foundFilename); - } - return true; // continue iterating - }); - - if (PathHelpers::GetFilename(dirToSearch).empty()) - { - // We've reached the top of the path - break; - } - } - - // iterate through found containers and look for relevant files within them - for (int iFile = 0; iFile < foundFileCountainer.size(); ++iFile) - { - zipPath = foundFileCountainer[ iFile ]; - string pathToZip = PathHelpers::GetDirectory(zipPath); - - // construct filename by removing path to zip from path to filename - string pathToFile = PathHelpers::GetDirectory(string(normalPath)); - string pureFileName = PathHelpers::GetFilename(string(normalPath)); - if (pathToFile.length() != pathToZip.length() && pathToZip.length() > 0) - { - pathToFile = pathToFile.substr(pathToZip.length() + 1); - } - filename = pathToFile.empty() - ? pureFileName - : pathToFile + "\\" + pureFileName; - - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CachePtr testZip = factory.New(zipPath.c_str(), decryptionKey); - ZipDir::FileEntry* testFileEntry = (testZip ? testZip->FindFile(filename.c_str()) : 0); - - // break out if we have a testFileEntry, as we've found our first (and best) candidate. - if (testFileEntry) - { - bFileExists = true; - break; - } - } - } - - { - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CachePtr zip = (bFileExists ? factory.New(zipPath.c_str(), decryptionKey) : 0); - ZipDir::FileEntry* fileEntry = (zip ? zip->FindFile(filename.c_str()) : 0); - - if (fileEntry) - { - std::unique_ptr file(new PakSystemFile()); - file->type = PakSystemFileType_PakFile; - file->zip = zip; - file->fileEntry = fileEntry; - file->data = zip->AllocAndReadFile(file->fileEntry); - file->dataPosition = 0; - return file.release(); - } - } - - return 0; -} - - -//Extracts archived file to disk without overwriting any files -//returns true on success, false on failure (due to potential overwrite or no file -//in archive -bool PakSystem::ExtractNoOverwrite(const char* fileToExtract, const char* extractToFile) -{ - if (0 == extractToFile) - { - extractToFile = fileToExtract; - } - - //open file using pak system - PakSystemFile* fileZip = Open(fileToExtract, "r"); - if (!fileZip) - { - return false; - } - - // Try to open a writable file - FILE* fFileOnDisk = nullptr; - azfopen(&fFileOnDisk, extractToFile, "wb"); - if (!fFileOnDisk) - { - Close(fileZip); - return false; - } - - fwrite(fileZip->data, fileZip->fileEntry->desc.lSizeUncompressed, 1, fFileOnDisk); - fclose(fFileOnDisk); - - Close(fileZip); - - return true; -} - - -void PakSystem::Close(PakSystemFile* file) -{ - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - fclose(file->file); - break; - - case PakSystemFileType_PakFile: - file->zip->Free(file->data); - break; - } - delete file; - } -} - - -int PakSystem::GetLength(PakSystemFile* file) const -{ - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - if (file->file) - { - long pos = ftell(file->file); - fseek(file->file, 0, SEEK_END); - int result = ftell(file->file); - fseek(file->file, pos, SEEK_SET); - return result; - } - break; - } - case PakSystemFileType_PakFile: - { - if (file->fileEntry) - { - return file->fileEntry->desc.lSizeUncompressed; - } - break; - } - default: - { - break; - } - } - } - return 0; -} - - -int PakSystem::Read(PakSystemFile* file, void* buffer, int size) -{ - int readBytes = 0; - - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - readBytes = fread(buffer, 1, size, file->file); - } - break; - - case PakSystemFileType_PakFile: - { - int fileSize = file->fileEntry->desc.lSizeUncompressed; - readBytes = (fileSize - file->dataPosition > size ? size : fileSize - file->dataPosition); - memcpy(buffer, static_cast(file->data) + file->dataPosition, readBytes); - file->dataPosition += readBytes; - } - break; - } - } - - return readBytes; -} - -bool PakSystem::EoF(PakSystemFile* file) -{ - bool EoF = true; - if (file) - { - switch (file->type) - { - case PakSystemFileType_File: - { - EoF = (0 != feof(file->file)); - } - break; - - case PakSystemFileType_PakFile: - { - int fileSize = file->fileEntry->desc.lSizeUncompressed; - EoF = (file->dataPosition >= fileSize); - } - break; - } - } - - return EoF; -} - -PakSystemArchive* PakSystem::OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]) -{ - //unsigned nFactoryFlags = ZipDir::CacheFactory::FLAGS_DONT_COMPACT | ZipDir::CacheFactory::FLAGS_CREATE_NEW; - unsigned nFactoryFlags = 0; - ZipDir::CacheFactory factory(ZipDir::ZD_INIT_FAST, nFactoryFlags); - ZipDir::CacheRWPtr cache = factory.NewRW(path, fileAlignment, encrypted, encryptionKey); - PakSystemArchive* archive = (cache ? new PakSystemArchive() : 0); - if (archive) - { - archive->zip = cache; - } - return archive; -} - -void PakSystem::CloseArchive(PakSystemArchive* archive) -{ - if (archive) - { - archive->zip->Close(); - delete archive; - } -} - -void PakSystem::AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel) -{ - int compressionMethod = ZipFile::METHOD_DEFLATE; - if (compressionLevel == 0) - { - compressionMethod = ZipFile::METHOD_STORE; - } - archive->zip->UpdateFile(path, data, size, compressionMethod, compressionLevel, modTime); -} - -////////////////////////////////////////////////////////////////////////// -bool PakSystem::CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime) -{ - assert(archive); - - ZipDir::FileEntry* pFileEntry = archive->zip->FindFile(path); - if (pFileEntry) - { - return pFileEntry->CompareFileTimeNTFS(modTime); - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool PakSystem::DeleteFromArchive(PakSystemArchive* archive, const char* path) -{ - ZipDir::ErrorEnum err = archive->zip->RemoveFile(path); - return ZipDir::ZD_ERROR_SUCCESS == err; -} diff --git a/Code/Tools/CryCommonTools/PakSystem.h b/Code/Tools/CryCommonTools/PakSystem.h deleted file mode 100644 index ba57f26d4d..0000000000 --- a/Code/Tools/CryCommonTools/PakSystem.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H -#pragma once - - -#include "IPakSystem.h" -#include "ZipDir/ZipDir.h" // TODO: get rid of thid include - -enum PakSystemFileType -{ - PakSystemFileType_Unknown, - PakSystemFileType_File, - PakSystemFileType_PakFile -}; -struct PakSystemFile -{ - PakSystemFile(); - PakSystemFileType type; - - // PakSystemFileType_File - FILE* file; - - // PakSystemFileType_PakFile - ZipDir::CachePtr zip; - ZipDir::FileEntry* fileEntry; - void* data; - int dataPosition; -}; - -struct PakSystemArchive -{ - ZipDir::CacheRWPtr zip; -}; - -class PakSystem - : public IPakSystem -{ -public: - PakSystem(); - - // IPakSystem - virtual PakSystemFile* Open(const char* filename, const char* mode); - virtual bool ExtractNoOverwrite(const char* filename, const char* extractToFile = 0); - virtual void Close(PakSystemFile* file); - virtual int GetLength(PakSystemFile* file) const; - virtual int Read(PakSystemFile* file, void* buffer, int size); - virtual bool EoF(PakSystemFile* file); - - virtual PakSystemArchive* OpenArchive(const char* path, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]); - virtual void CloseArchive(PakSystemArchive* archive); - virtual void AddToArchive(PakSystemArchive* archive, const char* path, void* data, int size, int64 modTime, int compressionLevel); - virtual bool DeleteFromArchive(PakSystemArchive* archive, const char* path); - virtual bool CheckIfFileExist(PakSystemArchive* archive, const char* path, int64 modTime); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKSYSTEM_H diff --git a/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h b/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h deleted file mode 100644 index cd9aa9d211..0000000000 --- a/Code/Tools/CryCommonTools/PakXmlFileBufferSource.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H -#pragma once - - -#include "../CryXML/IXMLSerializer.h" -#include "IPakSystem.h" - -class PakXmlFileBufferSource - : public IXmlBufferSource -{ -public: - PakXmlFileBufferSource(IPakSystem* pakSystem, const char* path) - : pakSystem(pakSystem) - { - file = pakSystem->Open(path, "r"); - } - ~PakXmlFileBufferSource() - { - if (file) - { - pakSystem->Close(file); - } - } - - virtual int Read(void* buffer, int size) const - { - return pakSystem->Read(file, buffer, size); - }; - - IPakSystem* pakSystem; - PakSystemFile* file; -}; - -class PakXmlBufferSource - : public IXmlBufferSource -{ -public: - PakXmlBufferSource(const char* buffer, size_t length) - : position(buffer) - , end(buffer + length) - { - } - - virtual int Read(void* output, int size) const - { - size_t bytesLeft = end - position; - size_t bytesToCopy = size < bytesLeft ? size : bytesLeft; - if (bytesToCopy > 0) - { - memcpy(output, position, bytesToCopy); - position += bytesToCopy; - } - return bytesToCopy; - }; - - mutable const char* position; - const char* end; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PAKXMLFILEBUFFERSOURCE_H diff --git a/Code/Tools/CryCommonTools/PathHelpers.cpp b/Code/Tools/CryCommonTools/PathHelpers.cpp deleted file mode 100644 index 4abd28183e..0000000000 --- a/Code/Tools/CryCommonTools/PathHelpers.cpp +++ /dev/null @@ -1,621 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "PathHelpers.h" -#include "StringHelpers.h" -#include "Util.h" - -#include -#include -#include -#include -#include - - -// Returns position of last extension in last name (string::npos if not found) -// note: returns string::npos for names starting from '.' and having no -// '.' later (for example 'aaa/.ccc', 'a:.abc', '.rc') -template -static inline size_t findExtensionPosition_Tpl(const TS& path) -{ - const size_t dotPos = path.rfind('.'); - if (dotPos == TS::npos) - { - return TS::npos; - } - - static const typename TS::value_type separators[] = { '\\', '/', ':', 0 }; - const size_t separatorPos = path.find_last_of(separators); - if (separatorPos != TS::npos) - { - if (separatorPos + 1 >= dotPos) - { - return TS::npos; - } - } - else if (dotPos == 0) - { - return TS::npos; - } - - return dotPos + 1; -} - -static size_t findExtensionPosition(const string& path) -{ - return findExtensionPosition_Tpl(path); -} - -static size_t findExtensionPosition(const wstring& path) -{ - return findExtensionPosition_Tpl(path); -} - - -string PathHelpers::FindExtension(const string& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == string::npos) ? string() : path.substr(extPos, string::npos); -} - -wstring PathHelpers::FindExtension(const wstring& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == wstring::npos) ? wstring() : path.substr(extPos, wstring::npos); -} - - -template -static inline TS ReplaceExtension_Tpl(const TS& path, const TS& newExtension) -{ - if (path.empty()) - { - return TS(); - } - - if (newExtension.empty()) - { - return PathHelpers::RemoveExtension(path); - } - - const typename TS::value_type last = path[path.length() - 1]; - if ((last == '\\') || (last == '/') || (last == ':') || (last == '.')) - { - return path; - } - - const size_t extPos = findExtensionPosition(path); - static const typename TS::value_type dot[] = { '.', 0 }; - return ((extPos == TS::npos) ? path + dot : path.substr(0, extPos)) + newExtension; -} - -string PathHelpers::ReplaceExtension(const string& path, const string& newExtension) -{ - return ReplaceExtension_Tpl(path, newExtension); -} - -wstring PathHelpers::ReplaceExtension(const wstring& path, const wstring& newExtension) -{ - return ReplaceExtension_Tpl(path, newExtension); -} - - -string PathHelpers::RemoveExtension(const string& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == string::npos) ? path : path.substr(0, extPos - 1); -} - -wstring PathHelpers::RemoveExtension(const wstring& path) -{ - const size_t extPos = findExtensionPosition(path); - return (extPos == wstring::npos) ? path : path.substr(0, extPos - 1); -} - - -template -static inline TS GetDirectory_Tpl(const TS& path) -{ - static const typename TS::value_type separators[] = { '/', '\\', ':', 0 }; - const size_t pos = path.find_last_of(separators); - - if (pos == TS::npos) - { - return TS(); - } - - if (path[pos] == ':' || pos == 0 || path[pos - 1] == ':') - { - return path.substr(0, pos + 1); - } - - // Handle paths like "\\machine" - if (pos == 1 && (path[0] == '/' || path[0] == '\\')) - { - return path; - } - - return path.substr(0, pos); -} - -string PathHelpers::GetDirectory(const string& path) -{ - return GetDirectory_Tpl(path); -} - -wstring PathHelpers::GetDirectory(const wstring& path) -{ - return GetDirectory_Tpl(path); -} - - -template -static inline TS GetFilename_Tpl(const TS& path) -{ - static const typename TS::value_type separators[] = { '/', '\\', ':', 0 }; - const size_t pos = path.find_last_of(separators); - - if (pos == TS::npos) - { - return path; - } - - // Handle paths like "\\machine" - if (pos == 1 && (path[0] == '/' || path[0] == '\\')) - { - return TS(); - } - - return path.substr(pos + 1, TS::npos); -} - -string PathHelpers::GetFilename(const string& path) -{ - return GetFilename_Tpl(path); -} - -wstring PathHelpers::GetFilename(const wstring& path) -{ - return GetFilename_Tpl(path); -} - - -template -static inline TS AddSeparator_Tpl(const TS& path) -{ - if (path.empty()) - { - return TS(); - } - const typename TS::value_type last = path[path.length() - 1]; - if (last == '/' || last == '\\' || last == ':') - { - return path; - } -#if defined(AZ_PLATFORM_WINDOWS) - static const typename TS::value_type separator[] = { '\\', 0 }; -#else - static const typename TS::value_type separator[] = { '/', 0 }; -#endif - return path + separator; -} - -string PathHelpers::AddSeparator(const string& path) -{ - return AddSeparator_Tpl(path); -} - -wstring PathHelpers::AddSeparator(const wstring& path) -{ - return AddSeparator_Tpl(path); -} - - -template -static inline TS RemoveSeparator_Tpl(const TS& path) -{ - if (path.empty()) - { - return TS(); - } - const typename TS::value_type last = path[path.length() - 1]; - if ((last == '/' || last == '\\') && path.length() > 1 && path[path.length() - 2] != ':') - { - return path.substr(0, path.length() - 1); - } - return path; -} - -string PathHelpers::RemoveSeparator(const string& path) -{ - return RemoveSeparator_Tpl(path); -} - -wstring PathHelpers::RemoveSeparator(const wstring& path) -{ - return RemoveSeparator_Tpl(path); -} - - -template -static inline TS RemoveDuplicateSeparators_Tpl(const TS& path) -{ - if (path.length() <= 1) - { - return path; - } - - TS ret; - ret.reserve(path.length()); - - const typename TS::value_type* p = path.c_str(); - - // We start from the second char just to avoid damaging UNC paths with double backslash at the beginning (e.g. "\\Server04\file.txt") - ret += *p++; - - while (*p) - { - ret += *p++; - if (p[-1] == '\\' || p[-1] == '/') - { - while (*p == '\\' || *p == '/') - { - ++p; - } - } - } - - return ret; -} - -string PathHelpers::RemoveDuplicateSeparators(const string& path) -{ - return RemoveDuplicateSeparators_Tpl(path); -} - -wstring PathHelpers::RemoveDuplicateSeparators(const wstring& path) -{ - return RemoveDuplicateSeparators_Tpl(path); -} - - -template -static inline TS Join_Tpl(const TS& path1, const TS& path2) -{ - if (path1.empty()) - { - return path2; - } - if (path2.empty()) - { - return path1; - } - - if (!PathHelpers::IsRelative(path2)) - { - assert(0 && "Join(): path2 is not relative"); - return TS(); - } - - const typename TS::value_type last = path1[path1.length() - 1]; - if (last == '/' || last == '\\' || last == ':') - { - return path1 + path2; - } -#if defined(AZ_PLATFORM_WINDOWS) - static const typename TS::value_type separator[] = { '\\', 0 }; -#else - static const typename TS::value_type separator[] = { '/', 0 }; -#endif - return path1 + separator + path2; -} - - -string PathHelpers::Join(const string& path1, const string& path2) -{ - return Join_Tpl(path1, path2); -} - -wstring PathHelpers::Join(const wstring& path1, const wstring& path2) -{ - return Join_Tpl(path1, path2); -} - - -template -static inline bool IsRelative_Tpl(const TS& path) -{ - if (path.empty()) - { - return true; - } - return path[0] != '/' && path[0] != '\\' && path.find(':') == TS::npos; -} - -bool PathHelpers::IsRelative(const string& path) -{ - return IsRelative_Tpl(path); -} - -bool PathHelpers::IsRelative(const wstring& path) -{ - return IsRelative_Tpl(path); -} - - -string PathHelpers::ToUnixPath(const string& path) -{ - return StringHelpers::Replace(path, '\\', '/'); -} - -wstring PathHelpers::ToUnixPath(const wstring& path) -{ - wstring s(path); - std::replace(s.begin(), s.end(), L'\\', L'/'); - return s; -} - - -string PathHelpers::ToDosPath(const string& path) -{ - return StringHelpers::Replace(path, '/', '\\'); -} - -wstring PathHelpers::ToDosPath(const wstring& path) -{ - wstring s(path); - std::replace(s.begin(), s.end(), L'/', L'\\'); - return s; -} - -string PathHelpers::ToPlatformPath(const string& path) -{ -#if defined(AZ_PLATFORM_WINDOWS) - return ToDosPath(path); -#else - return ToUnixPath(path); -#endif -} - -wstring PathHelpers::ToPlatformPath(const wstring& path) -{ -#if defined(AZ_PLATFORM_WINDOWS) - return ToDosPath(path); -#else - return ToUnixPath(path); -#endif -} - - -string PathHelpers::GetAsciiPath(const char* pPath) -{ - AZStd::wstring wstr; - AZStd::to_wstring(wstr, pPath); - return GetAsciiPath(wstr.c_str()); -} - -string PathHelpers::GetAsciiPath(const wchar_t* pPath) -{ - if (!pPath[0]) - { - return string(); - } - - wstring w = ToPlatformPath(RemoveSeparator(wstring(pPath))); - - if (StringHelpers::Utf16ContainsAsciiOnly(w.c_str())) - { - return StringHelpers::ConvertAsciiUtf16ToAscii(w.c_str()); - } - - // The path is non-ASCII, so let's resort to using short - // filenames where needed (short names are always ASCII-only) - - // Long names components - std::vector p0; - StringHelpers::Split(w, wstring(L"\\"), true, p0); - - // find last component that is not in ASCII char set - int lastNonAscii; - for (lastNonAscii = (int)p0.size() - 1; lastNonAscii >= 0; --lastNonAscii) - { - if (!StringHelpers::Utf16ContainsAsciiOnly(p0[lastNonAscii].c_str())) - { - break; - } - } - assert(lastNonAscii >= 0); - - string res; - res.reserve(w.length()); - - w.clear(); - for (int i = 0; i <= lastNonAscii; ++i) - { - w.append(p0[i]); - if (i < lastNonAscii) - { - w.push_back('\\'); - } - } - - enum - { - kBufferLen = AZ_MAX_PATH_LEN - }; - wchar_t bufferWchars[kBufferLen]; - -#if defined(AZ_PLATFORM_WINDOWS) - const int charCount = GetShortPathNameW(w.c_str(), bufferWchars, kBufferLen); -#else - const int charCount = w.length(); - wcsncpy(bufferWchars, w.c_str(), kBufferLen); -#endif - if (charCount <= 0 || charCount >= kBufferLen) - { - return string(); - } -#if defined(AZ_PLATFORM_WINDOWS) - // Paranoid - if (!StringHelpers::Utf16ContainsAsciiOnly(bufferWchars)) - { - assert(0); - return string(); - } -#endif - - // Short names components - std::vector p1; - StringHelpers::Split(wstring(bufferWchars), wstring(L"\\"), true, p1); - - for (size_t i = 0; i < (int)p0.size(); ++i) - { - if (!p0[i].empty()) - { - const wstring& p = - (i > lastNonAscii || StringHelpers::Utf16ContainsAsciiOnly(p0[i].c_str())) - ? p0[i] - : p1[i]; - res.append(StringHelpers::ConvertAsciiUtf16ToAscii(p.c_str())); - } - if (i + 1 < (int)p0.size()) - { - res.push_back('\\'); - } - } - - return res; -} - - -string PathHelpers::GetAbsoluteAsciiPath(const char* pPath) -{ - char fullPath[AZ_MAX_PATH_LEN]; - AZ::IO::LocalFileIO localFileIO; - - AZStd::string normalizedPath(pPath); - AzFramework::StringFunc::Path::Normalize(normalizedPath); - - localFileIO.ConvertToAbsolutePath(normalizedPath.c_str(), fullPath, AZ_MAX_PATH_LEN); - fullPath[sizeof(fullPath) - 1] = '\0'; - - AZStd::wstring wstr; - AZStd::to_wstring(wstr, fullPath); - return GetAsciiPath(wstr.c_str()); -} - -string PathHelpers::GetAbsoluteAsciiPath(const wchar_t* pPath) -{ - AZStd::string str; - AZStd::to_string(str, pPath); - - AzFramework::StringFunc::Path::Normalize(str); - - char fullPath[AZ_MAX_PATH_LEN]; - AZ::IO::LocalFileIO localFileIO; - localFileIO.ConvertToAbsolutePath(str.c_str(), fullPath, AZ_MAX_PATH_LEN); - fullPath[sizeof(fullPath) - 1] = '\0'; - - AZStd::wstring wstr; - AZStd::to_wstring(wstr, fullPath); - return GetAsciiPath(wstr.c_str()); -} - - -string PathHelpers::GetShortestRelativeAsciiPath(const string& baseFolder, const string& dependentPath) -{ - const string d = GetAbsoluteAsciiPath(dependentPath.c_str()); - if (d.empty()) - { - return PathHelpers::CanonicalizePath(dependentPath); - } - - const string b = GetAbsoluteAsciiPath(baseFolder.c_str()); - if (b.empty()) - { - return PathHelpers::CanonicalizePath(dependentPath); - } - - const string b2 = AddSeparator(b); - if (StringHelpers::StartsWithIgnoreCase(d, b2)) - { - const size_t len = d.length() - b2.length(); - // note: len == 0 is possible in case of "C:\" and "C:\". - return (len == 0) ? string(".") : d.substr(b2.length(), len); - } - - std::vector p0; - StringHelpers::Split(b2, string("\\"), true, p0); - std::vector p1; - StringHelpers::Split(d, string("\\"), true, p1); - - if (!StringHelpers::EqualsIgnoreCase(p0[0], p1[0])) - { - // got different drive letters - return PathHelpers::CanonicalizePath(dependentPath); - } - - if (StringHelpers::EqualsIgnoreCase(d, b)) - { - // exactly same path - return string("."); - } - - // Search for first non-matching component - for (int i = 1; i < (int)p0.size(); ++i) - { - if (StringHelpers::EqualsIgnoreCase(p0[i], p1[i])) - { - continue; - } - - string s; - s.reserve(Util::getMax(d.length(), b.length())); - for (int j = i; j < (int)p0.size(); ++j) - { - if (!p0[j].empty()) - { - s.append("..\\"); - } - } - for (int j = i; j < (int)p1.size(); ++j) - { - s.append(p1[j]); - if (j + 1 < (int)p1.size()) - { - s.push_back('\\'); - } - } - return s; - } - - assert(0); - return string(); -} - - -string PathHelpers::CanonicalizePath(const string& path) -{ - string result = RemoveSeparator(path); - // remove .\ or ./ at the path beginning. - if (result.length() > 2) - { - if (result[0] == '.' && (result[1] == '\\' || result[1] == '/')) - { - result = result.substr(2); - } - } - - return result; -} diff --git a/Code/Tools/CryCommonTools/PathHelpers.h b/Code/Tools/CryCommonTools/PathHelpers.h deleted file mode 100644 index 4cf509d876..0000000000 --- a/Code/Tools/CryCommonTools/PathHelpers.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H -#pragma once - -#include - -namespace PathHelpers -{ - // checks to see what the extension is in a string path - // returns the extension if found or an empty string if not found - string FindExtension(const string& path); - wstring FindExtension(const wstring& path); - - // replace an extension of a string path with a new specified extension - // returns a string with the replaced extension or the original string if unable to replace the extension - string ReplaceExtension(const string& path, const string& newExtension); - wstring ReplaceExtension(const wstring& path, const wstring& newExtension); - - // removes the extension of a specified string path - // returns a string with the extension removed or the original string if no extension was found - string RemoveExtension(const string& path); - wstring RemoveExtension(const wstring& path); - - // "abc/def/ghi" -> "abc/def" - // "abc/def/ghi/" -> "abc/def/ghi" - // "/" -> "/" - // gets the directory path out of a specified string path - // returns a string of the directory path - string GetDirectory(const string& path); - wstring GetDirectory(const wstring& path); - - // gets the file name out of a specified string path - // returns a string of the file name - string GetFilename(const string& path); - wstring GetFilename(const wstring& path); - - // add a backslash to a specified path if it doesn't already have a separator - // returns a path with the appended backslash unless there was already a separator - string AddSeparator(const string& path); - wstring AddSeparator(const wstring& path); - - // removes a forward slash or backslash from the end of a specified string path if found - // returns a string with the separator removed - string RemoveSeparator(const string& path); - wstring RemoveSeparator(const wstring& path); - - // removes extra forward slashes and backslashes if they're contained within the string path - // returns a string with the extra forward slashes and backslashes removed - string RemoveDuplicateSeparators(const string& path); - wstring RemoveDuplicateSeparators(const wstring& path); - - // It's not allowed to pass an absolute path in path2. - // Join(GetDirectory(fname), GetFilename(fname)) returns fname. - // merges two string paths together into one - // returns the merged string paths - string Join(const string& path1, const string& path2); - wstring Join(const wstring& path1, const wstring& path2); - - // checks to see if the path is a relative path - // returns true if it is or false if it is not - bool IsRelative(const string& path); - bool IsRelative(const wstring& path); - - // converts a string path to a unix path format - // returns the path in unix format - string ToUnixPath(const string& path); - wstring ToUnixPath(const wstring& path); - - // converts a string path to a dos path format - // returns the path in dos format - string ToDosPath(const string& path); - wstring ToDosPath(const wstring& path); - - // converts a string to the platform's path format. - // returns the path in the platform's path format. - string ToPlatformPath(const string& path); - wstring ToPlatformPath(const wstring& path); - - // char* pPath: in ASCII or UTF-8 encoding - // wchar_t* pPath: in UTF-16 encoding - // Non-ASCII components of pPath (everything from &pPath[0] to last non-ASCII - // part, inclusively) should exist on disk, otherwise an empty string is returned. - string GetAsciiPath(const char* pPath); - string GetAsciiPath(const wchar_t* pPath); - - // pPath passed should be in ASCII or UTF-8 encoding - string GetAbsoluteAsciiPath(const char* pPath); - // pPath passed should be in UTF-16 encoding - string GetAbsoluteAsciiPath(const wchar_t* pPath); - - // baseFolder and dependentPath passed should be in ASCII or UTF-8 encoding - string GetShortestRelativeAsciiPath(const string& baseFolder, const string& dependentPath); - - string CanonicalizePath(const string& path); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PATHHELPERS_H diff --git a/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h b/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h deleted file mode 100644 index 03a0b4ff38..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h +++ /dev/null @@ -1,15 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#define AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(file, offset, s) fseek(file, offset, s) -#define AZ_TRAIT_CRYCOMMONTOOLS_FTELL(file) ftell(file) diff --git a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h b/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h deleted file mode 100644 index 81a38177c2..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Linux.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> - -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 0 diff --git a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index 6232c6462b..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/ZipDir/ZipDir_Traits_Platform.h +++ /dev/null @@ -1,15 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> -#include diff --git a/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake b/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake deleted file mode 100644 index 9c71b39bf1..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Linux/platform_linux_files.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Linux.h - ../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h -) diff --git a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h b/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h deleted file mode 100644 index 111a31dc55..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Mac.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include <../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h> - -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 1 diff --git a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index e601614c59..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/ZipDir/ZipDir_Traits_Platform.h +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include diff --git a/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake b/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake deleted file mode 100644 index b1fb3fa9a1..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Mac/platform_mac_files.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Mac.h - ../Common/UnixLike/ZipDir/ZipDir_Traits_UnixLike.h -) diff --git a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h b/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h deleted file mode 100644 index 1d177a5c8c..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Platform.h +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include diff --git a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h b/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h deleted file mode 100644 index 6d9c5314e4..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/ZipDir/ZipDir_Traits_Windows.h +++ /dev/null @@ -1,16 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#define AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(file, offset, s) _fseeki64(file, (__int64)offset, s) -#define AZ_TRAIT_CRYCOMMONTOOLS_FTELL(file) (size_t)_ftelli64(file) -#define AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 1 diff --git a/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake b/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake deleted file mode 100644 index 252842e917..0000000000 --- a/Code/Tools/CryCommonTools/Platform/Windows/platform_windows_files.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ZipDir/ZipDir_Traits_Platform.h - ZipDir/ZipDir_Traits_Windows.h -) diff --git a/Code/Tools/CryCommonTools/ProgressRange.h b/Code/Tools/CryCommonTools/ProgressRange.h deleted file mode 100644 index 297d862980..0000000000 --- a/Code/Tools/CryCommonTools/ProgressRange.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H -#pragma once - - -class ProgressRange -{ -public: - template - ProgressRange(T* object, void (T::* setter)(float progress)) - : m_target(new MethodTarget(object, setter)) - , m_progress(0.0f) - , m_start(0.0f) - , m_scale(1.0f) - { - m_target->Set(m_start); - } - - ProgressRange(ProgressRange& parent, float scale) - : m_target(new ParentRangeTarget(parent)) - , m_progress(0.0f) - , m_start(parent.m_progress) - , m_scale(scale) - { - m_target->Set(m_start); - } - - ~ProgressRange() - { - m_target->Set(m_start + m_scale); - delete m_target; - } - - void SetProgress(float progress) - { - assert(progress > -0.01f && progress < 1.1f); - m_progress = progress; - m_target->Set(m_start + m_scale * progress); - } - -private: - struct ITarget - { - virtual ~ITarget() {} - virtual void Set(float progress) = 0; - }; - - struct ParentRangeTarget - : public ITarget - { - ParentRangeTarget(ProgressRange& range) - : range(range) {} - virtual void Set(float progress) {range.SetProgress(progress); } - ProgressRange& range; - }; - - template - struct MethodTarget - : public ITarget - { - typedef void (T::* Setter)(float progress); - MethodTarget(T* object, Setter setter) - : object(object) - , setter(setter) {} - virtual void Set(float progress) {(object->*setter)(progress); } - T* object; - Setter setter; - }; - - ITarget* m_target; - float m_progress; - float m_start; - float m_scale; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PROGRESSRANGE_H diff --git a/Code/Tools/CryCommonTools/PropertyHelpers.cpp b/Code/Tools/CryCommonTools/PropertyHelpers.cpp deleted file mode 100644 index aaaa1df309..0000000000 --- a/Code/Tools/CryCommonTools/PropertyHelpers.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "PropertyHelpers.h" -#include "StringHelpers.h" - - -bool PropertyHelpers::GetPropertyValue(const string& a_propertiesString, const char* a_propertyName, string& a_value) -{ - if ((a_propertyName == 0) || (a_propertyName[0] == 0)) - { - return false; - } - - const char* lineStart = a_propertiesString.c_str(); - - while (*lineStart) - { - string key; - string value; - - const size_t lineEndPosition = strcspn(lineStart, "\n"); - const size_t equalPosition = strcspn(lineStart, "="); - - if (equalPosition < lineEndPosition) - { - key = string(lineStart, equalPosition); - value = string(lineStart + equalPosition + 1, lineEndPosition - equalPosition - 1); - } - else - { - key = string(lineStart, lineEndPosition); - value = ""; - } - - key = StringHelpers::Trim(key); - - if (_stricmp(key.c_str(), a_propertyName) == 0) - { - a_value = StringHelpers::Trim(value); - return true; - } - - lineStart += lineEndPosition; - if (*lineStart) - { - ++lineStart; - } - } - - return false; -} - -void PropertyHelpers::SetPropertyValue(string& a_propertiesString, const char* a_propertyName, const char* a_value) -{ - if ((a_propertyName == 0) || (a_propertyName[0] == 0)) - { - return; - } - - const string newValue = StringHelpers::Trim(string(a_value)); - - const char* lineStart = a_propertiesString.c_str(); - - while (*lineStart) - { - const size_t lineEndPosition = strcspn(lineStart, "\n"); - const size_t equalPosition = strcspn(lineStart, "="); - - const string key = StringHelpers::Trim(string(lineStart, ((equalPosition < lineEndPosition) ? equalPosition : lineEndPosition))); - - if (_stricmp(key.c_str(), a_propertyName) == 0) - { - const size_t prefixSz = lineStart - a_propertiesString.c_str(); - const size_t expressionSz = lineEndPosition; - - if (newValue.empty()) - { - a_propertiesString = a_propertiesString.substr(0, prefixSz) + string(a_propertyName) + a_propertiesString.substr(prefixSz + expressionSz, string::npos); - } - else - { - a_propertiesString = a_propertiesString.substr(0, prefixSz) + string(a_propertyName) + string("=") + newValue + a_propertiesString.substr(prefixSz + expressionSz, string::npos); - } - return; - } - - lineStart += lineEndPosition; - if (*lineStart) - { - ++lineStart; - } - } - - if (a_propertiesString.empty() || (a_propertiesString[a_propertiesString.size() - 1] != '\n')) - { - a_propertiesString += string("\r\n"); - } - - if (newValue.empty()) - { - a_propertiesString += string(a_propertyName); - } - else - { - a_propertiesString += string(a_propertyName) + string("=") + newValue; - } -} - -bool PropertyHelpers::HasProperty(const string& a_propertiesString, const char* a_propertyName) -{ - string value; - return PropertyHelpers::GetPropertyValue(a_propertiesString, a_propertyName, value); -} diff --git a/Code/Tools/CryCommonTools/PropertyHelpers.h b/Code/Tools/CryCommonTools/PropertyHelpers.h deleted file mode 100644 index 0a2f428cc8..0000000000 --- a/Code/Tools/CryCommonTools/PropertyHelpers.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H -#pragma once - - -namespace PropertyHelpers -{ - bool GetPropertyValue(const string& propertiesString, const char* propertyName, string& value); - void SetPropertyValue(string& a_propertiesString, const char* propertyName, const char* value); - bool HasProperty(const string& propertiesString, const char* propertyName); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_PROPERTYHELPERS_H - - diff --git a/Code/Tools/CryCommonTools/STLHelpers.cpp b/Code/Tools/CryCommonTools/STLHelpers.cpp deleted file mode 100644 index c1b65f25b2..0000000000 --- a/Code/Tools/CryCommonTools/STLHelpers.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include diff --git a/Code/Tools/CryCommonTools/STLHelpers.h b/Code/Tools/CryCommonTools/STLHelpers.h deleted file mode 100644 index 6fbf0c7d11..0000000000 --- a/Code/Tools/CryCommonTools/STLHelpers.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H -#pragma once - - -#include - -namespace STLHelpers -{ - template - inline const char* constchar_cast(const Type& type) - { - return type; - } - - template <> - inline const char* constchar_cast(const std::string& type) - { - return type.c_str(); - } - - template - struct less_strcmp - { - bool operator()(const Type& left, const Type& right) const - { - return strcmp(constchar_cast(left), constchar_cast(right)) < 0; - } - }; - - template - struct less_stricmp - { - bool operator()(const Type& left, const Type& right) const - { - return _stricmp(constchar_cast(left), constchar_cast(right)) < 0; - } - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_STLHELPERS_H diff --git a/Code/Tools/CryCommonTools/SimpleBitmap.h b/Code/Tools/CryCommonTools/SimpleBitmap.h deleted file mode 100644 index ce4e93c626..0000000000 --- a/Code/Tools/CryCommonTools/SimpleBitmap.h +++ /dev/null @@ -1,508 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H - -#include -#include // STL vector -#include "platform.h" // uint32 -#include "Cry_Math.h" // uint32 -#include "Util.h" // getMin() - -enum EImageFilteringMode -{ - eifm2DBorder = 0, - eifmCubemapFilter = 1, -}; - -namespace -{ - enum ECubeFace - { - ecfPosX = 0, - ecfNegX = 1, - ecfPosY = 2, - ecfNegY = 3, - ecfPosZ = 4, - ecfNegZ = 5, - ecfUnknown = -1, - }; - - struct JumpEntry - { - ECubeFace face; - int rot; - }; - - static const JumpEntry XJmpTable[] = - { - {ecfNegZ, 0}, {ecfPosZ, 2}, // ecfPosXa - {ecfPosZ, 0}, {ecfNegZ, 2}, // ecfNegXa - {ecfPosX, 1}, {ecfNegX, 3}, // ecfPosYa - {ecfPosX, 3}, {ecfNegX, 1}, // ecfNegYa - {ecfPosX, 0}, {ecfNegX, 0}, // ecfPosZa - {ecfPosX, 2}, {ecfNegX, 2} // ecfNegZa - }; - - static const JumpEntry YJmpTable[] = - { - {ecfPosY, 3}, {ecfNegY, 1}, // ecfPosXa - {ecfPosY, 1}, {ecfNegY, 3}, // ecfNegXa - {ecfNegZ, 2}, {ecfPosZ, 0}, // ecfPosYa - {ecfPosZ, 0}, {ecfNegZ, 2}, // ecfNegYa - {ecfNegY, 0}, {ecfPosY, 2}, // ecfPosZa - {ecfNegY, 2}, {ecfPosY, 0} // ecfNegZa - }; -} - -//! memory block used as bitmap -//! if you might need mipmaps please consider using ImageObject instead -template -class CSimpleBitmap -{ -public: - - CSimpleBitmap() - : m_dwWidth(0) - , m_dwHeight(0) - { - } - - ~CSimpleBitmap() - { - } - - // copy constructor - CSimpleBitmap(const CSimpleBitmap& rhs) - : m_dwWidth(0) - , m_dwHeight(0) - { - *this = rhs; // call assignment operator - } - - // assignment operator - CSimpleBitmap& operator=(const CSimpleBitmap& rhs) - { - if (&rhs != this) - { - m_data = rhs.m_data; - m_dwWidth = rhs.m_dwWidth; - m_dwHeight = rhs.m_dwHeight; - } - return *this; - } - - //! free all the memory resources - void FreeData() - { - m_data = std::vector(); - m_dwWidth = 0; - m_dwHeight = 0; - } - - //! /return true=success, false=failed because of low memory - bool SetSize(const uint32 indwWidth, const uint32 indwHeight) - { - if (m_dwWidth * m_dwHeight != indwWidth * indwHeight) - { - FreeData(); - m_data.resize(indwWidth * indwHeight); - m_dwWidth = indwWidth; - m_dwHeight = indwHeight; - } - return true; - } - -private: - ECubeFace JumpX(const ECubeFace srcFace, const bool isdXPos, int* rotCoords) const - { - int index = (int)srcFace * 2 + (isdXPos ? 0 : 1); - assert(index < sizeof(XJmpTable)); - const JumpEntry& jmp = XJmpTable[index]; - (*rotCoords) += jmp.rot; - return jmp.face; - } - - ECubeFace JumpY(const ECubeFace srcFace, const bool isdYPos, int* rotCoords) const - { - int index = (int)srcFace * 2 + (isdYPos ? 0 : 1); - assert(index < sizeof(YJmpTable)); - const JumpEntry& jmp = YJmpTable[index]; - (*rotCoords) += jmp.rot; - return jmp.face; - } - - // table that shows to which face we jump - ECubeFace JumpTable(const ECubeFace srcFace, int isdXPos, int isdYPos, int* rotCoords) const - { - if (isdXPos != 0) // recursive jump until dx==0 - { - int newSwap = 0; - ECubeFace newFace = JumpX(srcFace, isdXPos > 0, &newSwap); - (*rotCoords) += newSwap; - isdXPos -= ((isdXPos > 0) ? 1 : -1); - RotateCoord(&isdXPos, &isdYPos, newSwap); - return JumpTable(newFace, isdXPos, isdYPos, rotCoords); - } - if (isdYPos != 0) // recursive jump until dy==0 - { - int newSwap = 0; - ECubeFace newFace = JumpY(srcFace, isdYPos > 0, &newSwap); - (*rotCoords) += newSwap; - isdYPos -= ((isdYPos > 0) ? 1 : -1); - RotateCoord(&isdXPos, &isdYPos, newSwap); - return JumpTable(newFace, isdXPos, isdYPos, rotCoords); - } - assert(isdXPos == 0 && isdYPos == 0); - return srcFace; - } - - void RotateCoord(int* x, int* y, int mode) const - { - if (mode != 0) - { - if (mode == 2) // 180 degrees - { - (*x) = -(*x); - (*y) = -(*y); - } - else - { - if (mode == 1) // 90 dergees - { - int tmp = (*y); - (*y) = (*x); - (*x) = -tmp; - } - else // 270 degrees - { - assert(mode == 3); - int tmp = (*y); - (*y) = -(*x); - (*x) = tmp; - } - } - } - } - -public: - //! works only within the Bitmap for filter kernels - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to the raster element value if position was in the bitmap, NULL otherwise - const RasterElement* GetForFiltering_2D(const int inX, const int inY) const - { - return Get(inX, inY); - } - - //! works only within the Bitmap for filter kernels - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to the raster element value if position was in the bitmap, NULL otherwise - const RasterElement* GetForFiltering_Cubemap(const int inX, const int inY, const int srcX, const int srcY) const - { - if (m_data.empty()) - { - return false; - } - - assert(m_dwWidth == m_dwHeight * 6); - assert(srcX >= 0 && srcX < m_dwWidth); - assert(srcY >= 0 && srcY < m_dwHeight); - - const int sideSize = m_dwHeight; - - ECubeFace srcFace = (ECubeFace)(srcX / sideSize); - - if (inX >= 0 && inX < m_dwWidth && inY >= 0 && inY < m_dwHeight) // if we're inside the cubemap - { - ECubeFace destFace = (ECubeFace)(inX / sideSize); - if (destFace == srcFace) // we have the same face as src texel - { - return &m_data[inY * m_dwWidth + inX]; - } - } - const int halfSideSize = Util::getMax(1, sideSize / 2); - - // ternary logic - const int isdXPositive = int(floorf((float)inX / sideSize) - floorf((float)srcX / sideSize)); - const int isdYPositive = int(floorf((float)inY / sideSize) - floorf((float)srcY / sideSize)); - //if(isdXPositive==0&&isdYPositive<0&&srcFace==ecfPosY) - //{ - // int tmp = 0; - //} - assert(isdXPositive != 0 || isdYPositive != 0); - int rotCoords = 0; // quadrants to rotate coords - ECubeFace destFace = JumpTable(srcFace, isdXPositive, isdYPositive, &rotCoords); - rotCoords = ((rotCoords % 4) + 4) % 4; - int destX = inX - srcFace * sideSize; - int destY = inY; - - // rotate coords - destX -= halfSideSize; // center coords - destY -= halfSideSize; - RotateCoord(&destX, &destY, rotCoords); - destX += halfSideSize; // shift back - destY += halfSideSize; - - destX = ((destX + sideSize) % sideSize + sideSize) % sideSize; // tile in the face - destY = ((destY + sideSize) % sideSize + sideSize) % sideSize; - - destX = Util::getMin(destX, sideSize - 1); - destY = Util::getMin(destY, sideSize - 1); - destX += sideSize * destFace; - - assert(destX < m_dwWidth); - assert((ECubeFace)(destX / sideSize) == destFace); - - return &m_data[destY * m_dwWidth + destX]; - } - - const RasterElement* GetForFiltering(const Vec3& inDir) const - { - Vec3 vcAbsDir(fabsf(inDir.x), fabsf(inDir.y), fabsf(inDir.z)); - ECubeFace face; - int rotQuadrant = 0; - Vec2 texCoord; - if (vcAbsDir.x > vcAbsDir.y && vcAbsDir.x > vcAbsDir.z) - { - if (inDir.x > 0) - { - rotQuadrant = 3; - face = ecfPosX; - } - else - { - rotQuadrant = 1; - face = ecfNegX; - } - texCoord = Vec2(inDir.y, inDir.z) / vcAbsDir.x; - } - else if (vcAbsDir.y > vcAbsDir.x && vcAbsDir.y > vcAbsDir.z) - { - if (inDir.y > 0) - { - rotQuadrant = 2; - face = ecfPosY; - } - else - { - rotQuadrant = 0; - face = ecfNegY; - } - texCoord = Vec2(inDir.x, inDir.z) / vcAbsDir.y; - } - else - { - assert(vcAbsDir.z >= vcAbsDir.x && vcAbsDir.z >= vcAbsDir.y); - if (inDir.z > 0) - { - rotQuadrant = 1; - face = ecfPosZ; - } - else - { - rotQuadrant = 3; - face = ecfNegZ; - } - texCoord = Vec2(inDir.x, inDir.y) / vcAbsDir.z; - } - - texCoord = texCoord * .5f + Vec2(.5f, .5f); - assert(texCoord.x <= 1.f && texCoord.x >= 0); - assert(texCoord.y <= 1.f && texCoord.y >= 0); - - Vec2i texelPos(texCoord.x * (m_dwHeight - 1), texCoord.y * (m_dwHeight - 1)); - - texelPos.x += face * m_dwHeight; // plus face - return &m_data[texelPos.y * m_dwWidth + texelPos.x]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param outValue - //! /return pointer to raster element value if position was in the bitmap, NULL otherwise - const RasterElement* Get(const uint32 inX, const uint32 inY) const - { - if (m_data.empty()) - { - return 0; - } - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - - //! bilinear, works only well within 0..1 - bool GetFiltered(const float infX, const float infY, RasterElement& outValue) const - { - float fIX = floorf(infX), fIY = floorf(infY); - float fFX = infX - fIX, fFY = infY - fIY; - int iXa = (int)fIX, iYa = (int)fIY; - int iXb = iXa + 1, iYb = iYa + 1; - - if (iXb == m_dwWidth) - { - iXb = 0; - } - - if (iYb == m_dwHeight) - { - iYb = 0; - } - - const RasterElement* p[4]; - - if ((p[0] = Get(iXa, iYa)) && (p[1] = Get(iXb, iYa)) && (p[2] = Get(iXa, iYb)) && (p[3] = Get(iXb, iYb))) - { - outValue = - (*p[0]) * ((1.0f - fFX) * (1.0f - fFY)) + // left top - (*p[1]) * ((fFX) * (1.0f - fFY)) + // right top - (*p[2]) * ((1.0f - fFX) * (fFY)) + // left bottom - (*p[3]) * ((fFX) * (fFY)); // right bottom - - return true; - } - - return false; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - const RasterElement& GetRef(const uint32 inX, const uint32 inY) const - { - assert(!m_data.empty()); - assert(inX < m_dwWidth && inY < m_dwHeight); - return m_data[inY * m_dwWidth + inX]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - RasterElement& GetRef(const uint32 inX, const uint32 inY) - { - assert(!m_data.empty()); - assert(inX < m_dwWidth && inY < m_dwHeight); - return m_data[inY * m_dwWidth + inX]; - } - - //! works even outside of the Bitmap (tiled) - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - RasterElement& GetTiledRef(const uint32 inX, const uint32 inY) - { - assert(!m_data.empty()); - const uint32 x = inX % m_dwWidth; - const uint32 y = inY % m_dwHeight; - return m_data[y * m_dwWidth + x]; - } - - //! works only within the Bitmap - //! /param inX 0..m_dwWidth-1 or the method returns false - //! /param inY 0..m_dwHeight-1 or the method returns false - //! /param inValue - bool Set(const uint32 inX, const uint32 inY, const RasterElement& inValue) - { - if (m_data.empty()) - { - assert(!m_data.empty()); - return false; - } - - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return false; - } - - m_data[inY * m_dwWidth + inX] = inValue; - - return true; - } - - uint32 GetWidth() const - { - return m_dwWidth; - } - - uint32 GetHeight() const - { - return m_dwHeight; - } - - // Returns size of one line in bytes - size_t GetPitch() const - { - return m_dwWidth * sizeof(RasterElement); - } - - uint32 GetBitmapSizeInBytes() const - { - return m_dwWidth * m_dwHeight * sizeof(RasterElement); - } - - //! /return could be 0 if the pixel is outside the bitmap - const RasterElement* GetPointer(const uint32 inX = 0, const uint32 inY = 0) const - { - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - //! /return could be 0 if the pixel is outside the bitmap - RasterElement* GetPointer(const uint32 inX = 0, const uint32 inY = 0) - { - if (inX >= m_dwWidth || inY >= m_dwHeight) - { - return 0; - } - return &m_data[inY * m_dwWidth + inX]; - } - - void Fill(const RasterElement& inValue) - { - const uint32 n = m_dwHeight * m_dwWidth; - for (uint32 i = 0; i < n; ++i) - { - m_data[i] = inValue; - } - } - - bool IsValid() const - { - return !m_data.empty(); - } - -protected: // ------------------------------------------------------ - - std::vector m_data; //!< [m_dwWidth * m_dwHeight] - - uint32 m_dwWidth; - uint32 m_dwHeight; -}; - - - - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SIMPLEBITMAP_H diff --git a/Code/Tools/CryCommonTools/SimpleStringPool.h b/Code/Tools/CryCommonTools/SimpleStringPool.h deleted file mode 100644 index 4e65ce1be6..0000000000 --- a/Code/Tools/CryCommonTools/SimpleStringPool.h +++ /dev/null @@ -1,249 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H -#pragma once - -#include - -///////////////////////////////////////////////////////////////////// -// String pool implementation. -// Inspired by expat implementation. -///////////////////////////////////////////////////////////////////// -class CSimpleStringPool -{ -public: - enum - { - STD_BLOCK_SIZE = 4096 - }; - struct BLOCK - { - BLOCK* next; - int size; - char s[1]; - }; - unsigned int m_blockSize; - BLOCK* m_blocks; - BLOCK* m_free_blocks; - const char* m_end; - char* m_ptr; - char* m_start; - int nUsedSpace; - int nUsedBlocks; - - CSimpleStringPool() - { - m_blockSize = STD_BLOCK_SIZE; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - nUsedBlocks = 0; - m_free_blocks = 0; - } - ~CSimpleStringPool() - { - BLOCK* pBlock = m_blocks; - while (pBlock) - { - BLOCK* temp = pBlock->next; - //nFree++; - free(pBlock); - pBlock = temp; - } - pBlock = m_free_blocks; - while (pBlock) - { - BLOCK* temp = pBlock->next; - //nFree++; - free(pBlock); - pBlock = temp; - } - m_blocks = 0; - m_ptr = 0; - m_start = 0; - m_end = 0; - } - void SetBlockSize(unsigned int nBlockSize) - { - if (nBlockSize > 1024 * 1024) - { - nBlockSize = 1024 * 1024; - } - unsigned int size = 512; - while (size < nBlockSize) - { - size *= 2; - } - - m_blockSize = size - offsetof(BLOCK, s); - } - void Clear() - { - if (m_free_blocks) - { - BLOCK* pLast = m_blocks; - while (pLast) - { - BLOCK* temp = pLast->next; - if (!temp) - { - break; - } - pLast = temp; - } - if (pLast) - { - pLast->next = m_free_blocks; - } - } - m_free_blocks = m_blocks; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - } - char* Append(const char* ptr, int nStrLen) - { - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = (std::max)(nStrLen + 1, (int)m_blockSize); - AllocBlock(nNewBlockSize, nStrLen + 1); - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } - char* ReplaceString(const char* str1, const char* str2) - { - int nStrLen1 = check_cast(strlen(str1)); - int nStrLen2 = check_cast(strlen(str2)); - - // undo ptr1 add. - if (m_ptr != m_start) - { - m_ptr = m_ptr - nStrLen1 - 1; - } - - assert(m_ptr == str1); - - int nStrLen = nStrLen1 + nStrLen2; - - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = (std::max)(nStrLen + 1, check_cast(m_blockSize)); - if (m_ptr == m_start) - { - ReallocBlock(nNewBlockSize * 2); // Reallocate current block. - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - else - { - AllocBlock(nNewBlockSize, nStrLen + 1); - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } -private: - void AllocBlock(int blockSize, int nMinBlockSize) - { - if (m_free_blocks) - { - BLOCK* pBlock = m_free_blocks; - BLOCK* pPrev = 0; - while (pBlock) - { - if (pBlock->size >= nMinBlockSize) - { - // Reuse free block - if (pPrev) - { - pPrev->next = pBlock->next; - } - else - { - m_free_blocks = pBlock->next; - } - - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + pBlock->size; - return; - } - pPrev = pBlock; - pBlock = pBlock->next; - } - } - size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char); - //nMallocs++; - BLOCK* pBlock = (BLOCK*)malloc(nMallocSize); - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - nUsedBlocks++; - } - void ReallocBlock(int blockSize) - { - BLOCK* pThisBlock = m_blocks; - BLOCK* pPrevBlock = m_blocks->next; - m_blocks = pPrevBlock; - - size_t nMallocSize = offsetof(BLOCK, s) + blockSize * sizeof(char); - - //nMallocs++; - BLOCK* pBlock = (BLOCK*)realloc(pThisBlock, nMallocSize); - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - } -}; - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SIMPLESTRINGPOOL_H diff --git a/Code/Tools/CryCommonTools/StealingThreadPool.cpp b/Code/Tools/CryCommonTools/StealingThreadPool.cpp deleted file mode 100644 index e4a6f87243..0000000000 --- a/Code/Tools/CryCommonTools/StealingThreadPool.cpp +++ /dev/null @@ -1,580 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "StealingThreadPool.h" -#include "ThreadUtils.h" -#include -#include -#include - -namespace ThreadUtils { - class StealingWorker - { - public: - StealingWorker(StealingThreadPool* pool, int index, bool trace, AZStd::condition_variable& jobsCV) - : m_pool(pool) - , m_index(index) - , m_tracingEnabled(trace) - , m_lastStartTime(0) - , m_exitFlag(0) - , m_jobsCV(jobsCV) - { - } - - static unsigned int __stdcall ThreadFunc(void* param) - { - StealingWorker* self = (StealingWorker*)(param); - self->Work(); - return 0; - } - - void Start(int startTime) - { - m_lastStartTime = startTime; - - string threadName; - threadName.Format("StealingWorker %d", m_index); - - AZStd::thread_desc threadDesc; - threadDesc.m_name = threadName.c_str(); - m_thread = AZStd::thread(AZStd::bind(StealingWorker::ThreadFunc, (void*)this), &threadDesc); - - } - - bool GetJobLockless(Job& job) - { - if (m_jobs.empty()) - { - return false; - } - job = m_jobs.front(); - m_jobs.pop_front(); - - return true; - } - - bool GetJob(Job& job) - { - AZStd::lock_guard lock(m_lockJobs); - return GetJobLockless(job); - } - - void ExecuteJob(Job& job) - { - --m_pool->m_numJobsWaitingForExecution; - job.Run(); - - if (m_tracingEnabled) - { - int time = (int)GetTickCount(); - - JobTrace trace; - trace.m_job = job; - trace.m_duration = time - m_lastStartTime; - m_traces.push_back(trace); - - m_lastStartTime = time; - } - - --m_pool->m_numJobs; - m_pool->m_jobFinishedCV.notify_all(); - } - - bool TryToStealJob(Job& job) - { - while (true) - { - StealingWorker* victim = m_pool->FindBestVictim(m_index); - if (!victim) - { - return false; - } - if (StealJobs(job, victim)) - { - return true; - } - } - } - - void Work() - { - Job job; - - while (true) - { - AZStd::mutex loadMutex; - AZStd::unique_lock loadLock(loadMutex, AZStd::defer_lock_t()); - - while (m_pool->m_numJobsWaitingForExecution == 0) - { - - m_jobsCV.wait(loadLock); - - if (m_exitFlag == 1) - { - return; - } - } - - if (GetJob(job)) - { - ExecuteJob(job); - } - else if (TryToStealJob(job)) - { - ExecuteJob(job); - } - } - } - - // Called from different worker thread - bool StealJobs(Job& job, StealingWorker* victim) - { - if (victim == this) - { - assert(0 && "Trying to steal own jobs"); - return false; - } - - bool order = m_index < victim->m_index; - AZStd::lock_guard lock1(order ? m_lockJobs : victim->m_lockJobs); - AZStd::lock_guard lock2(order ? victim->m_lockJobs : m_lockJobs); - - if (victim->m_jobs.empty()) - { - return false; - } - - int numJobs = (int)victim->m_jobs.size(); - size_t stealUntil = numJobs - numJobs / 2; - Jobs::iterator begin = victim->m_jobs.begin(); - Jobs::iterator end = victim->m_jobs.begin() + stealUntil; - - m_jobs.insert(m_jobs.end(), begin, end); - victim->m_jobs.erase(begin, end); - - return GetJobLockless(job); - } - - // Called from any thread - void Submit(const Job& job) - { - AZStd::lock_guard lock(m_lockJobs); - - m_jobs.push_back(job); - m_jobs.back().m_debugInitialThread = m_index; - - m_jobsCV.notify_one(); - } - - // Called from any thread - void Submit(const Jobs& jobs) - { - const size_t numJobs = jobs.size(); - - AZStd::lock_guard lock(m_lockJobs); - - m_jobs.insert(m_jobs.begin(), jobs.begin(), jobs.end()); - for (size_t i = 0; i < numJobs; ++i) - { - m_jobs[i].m_debugInitialThread = m_index; - } - - m_jobsCV.notify_one(); - } - - long NumJobsPending() const - { - AZStd::lock_guard lock(m_lockJobs); - return m_jobs.size(); - } - - // Called from main thread - void SignalExit() - { - CryInterlockedCompareExchange(&m_exitFlag, 1, 0); - } - - void GetTraces(JobTraces& traces) - { - if (m_tracingEnabled) - { - m_traces.swap(traces); - } - } - - private: - StealingThreadPool* m_pool; - AZStd::thread m_thread; - int m_index; - bool m_tracingEnabled; - int m_lastStartTime; - JobTraces m_traces; - - Jobs m_jobs; - mutable AZStd::mutex m_lockJobs; - AZStd::condition_variable& m_jobsCV; - - LONG m_exitFlag; - friend class StealingThreadPool; - }; - - // --------------------------------------------------------------------------- - - StealingThreadPool::StealingThreadPool(int numThreads, bool enableTracing) - : m_numThreads(numThreads) - , m_numJobs(0) - , m_numJobsWaitingForExecution(0) - , m_enableTracing(enableTracing) - { - m_workers.resize(numThreads); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i] = new StealingWorker(this, i, m_enableTracing, m_jobsCV); - } - } - - StealingThreadPool::~StealingThreadPool() - { - WaitAllJobs(); - - size_t numThreads = m_workers.size(); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->SignalExit(); - } - m_jobsCV.notify_all(); - - m_threadTraces.resize(numThreads); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->GetTraces(m_threadTraces[i]); - } - } - - void StealingThreadPool::Start() - { - int startTime = (int)GetTickCount(); - size_t numThreads = m_workers.size(); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i]->Start(startTime); - } - } - - void StealingThreadPool::WaitAllJobs() - { - AZStd::mutex loadMutex; - AZStd::unique_lock loadLock(loadMutex, AZStd::defer_lock_t()); - - while (m_numJobs > 0) - { - m_jobsCV.wait(loadLock); - } - } - - // Called from any thread - void StealingThreadPool::Submit(const Job& job) - { - ++m_numJobs; - ++m_numJobsWaitingForExecution; - - if (StealingWorker* worker = FindWorstWorker()) - { - worker->Submit(job); - } - } - - // Called from any thread - void StealingThreadPool::Submit(const Jobs& jobs) - { - m_numJobs += jobs.size(); - m_numJobsWaitingForExecution += jobs.size(); - if (StealingWorker* worker = FindWorstWorker()) - { - worker->Submit(jobs); - } - } - - JobGroup* StealingThreadPool::CreateJobGroup(JobFunc func, void* data) - { - return new JobGroup(this, func, data); - } - - StealingWorker* StealingThreadPool::FindBestVictim(int exceptFor) const - { - int maxJobs = 0; - StealingWorker* bestVictim = 0; - for (size_t i = 0; i < m_workers.size(); ++i) - { - if (i == exceptFor) - { - continue; - } - StealingWorker* worker = m_workers[i]; - long numJobs = worker->NumJobsPending(); - if (numJobs > maxJobs) - { - maxJobs = numJobs; - bestVictim = worker; - } - } - return bestVictim; - } - - StealingWorker* StealingThreadPool::FindWorstWorker() const - { - if (m_workers.empty()) - { - return 0; - } - - int minJobs = INT_MAX; - StealingWorker* worstWorker = m_workers[0]; - for (size_t i = 0; i < m_workers.size(); ++i) - { - StealingWorker* worker = m_workers[i]; - long numJobs = worker->NumJobsPending(); - if (numJobs < minJobs) - { - minJobs = numJobs; - worstWorker = worker; - } - } - return worstWorker; - } - - static bool WriteString(FILE* f, const char* str) - { - return fwrite(str, strlen(str), 1, f) == 1; - } - - static int Interpolate(int a, int b, float phase) - { - return int(float(a) + float(b - a) * phase); - } - - static int InterpolateColor(int c1, int c2, float phase) - { - const int r1 = (c1 & 0x0000ff); - const int g1 = (c1 & 0x00ff00) >> 8; - const int b1 = (c1 & 0xff0000) >> 16; - const int r2 = (c2 & 0x0000ff); - const int g2 = (c2 & 0x00ff00) >> 8; - const int b2 = (c2 & 0xff0000) >> 16; - - const int r = min(255, max(0, Interpolate(r1, r2, phase))); - const int g = min(255, max(0, Interpolate(g1, g2, phase))); - const int b = min(255, max(0, Interpolate(b1, b2, phase))); - - return r + (g << 8) + (b << 16); - } - - static const int g_animColors[] = { - 0xff0000, 0x0000ff, 0x00ff00, - 0xffff00, 0xff00ff, 0x00ffff, - 0xff8080, 0x8080ff, 0x80ff80, - 0xffff80, 0xff80ff, 0x80ffff - }; - - static int ColorizeJobTrace(const ThreadUtils::JobTrace& trace) - { - const int numColors = sizeof(g_animColors) / sizeof(g_animColors[0]); - const int initialThread = trace.m_job.m_debugInitialThread; - const int index = initialThread % numColors; - const float brightness = aznumeric_cast(pow(0.5f, initialThread / numColors)); - return InterpolateColor(0, InterpolateColor(g_animColors[index], 0xffffff, 0.5f), brightness); - } - - bool StealingThreadPool::SaveTracesGraph(const char* filename) - { - if (!m_enableTracing) - { - return false; - } - - const float screenWidth = 1240.0f; - - float duration = 0; - for (size_t t = 0; t < m_threadTraces.size(); ++t) - { - float threadDuration = 0; - const JobTraces& traces = m_threadTraces[t]; - for (int i = 0; i < traces.size(); ++i) - { - threadDuration += traces[i].m_duration; - } - duration = max(threadDuration, duration); - } - - const float padding = 10.0f; - const float rowHeight = 60.0f; - const float xScale = fabsf(duration) > FLT_EPSILON ? (screenWidth - padding * 2.0f) / duration : 1.0f; - - const float width = screenWidth; - const float height = (m_threadTraces.size() + 0.5f) * rowHeight; - - FILE* f = nullptr; - azfopen(&f, filename, "wt"); - if (!f) - { - return false; - } - - char buf[4096]; - azsnprintf(buf, sizeof(buf), - "\n" - "\n", - width, height - ); - - if (!WriteString(f, buf)) - { - return false; - } - - for (size_t t = 0; t < m_threadTraces.size(); ++t) - { - float x = padding; - float y = rowHeight * 0.5f + rowHeight * t; - - azsnprintf(buf, sizeof(buf), - " Thread %i\n", - x, y, x, y, static_cast(t + 1)); - - if (!WriteString(f, buf)) - { - return false; - } - - - y += padding; - - const ThreadUtils::JobTraces& traces = m_threadTraces[t]; - for (int i = 0; i < traces.size(); ++i) - { - const float width2 = traces[i].m_duration * xScale; - const float height2 = rowHeight * 0.5f; - - const int color = ColorizeJobTrace(traces[i]); - const int strokeColor = 0; - azsnprintf(buf, sizeof(buf), - " \n", - color, strokeColor, width2, height2, x, y); - - if (!WriteString(f, buf)) - { - return false; - } - - x += width2; - } - - y += rowHeight; - } - - if (!WriteString(f, "\n\n")) - { - return false; - } - - fclose(f); - return true; - } - - // --------------------------------------------------------------------------- - - void JobGroup::Process(JobGroup::GroupInfo* info) - { - info->m_job.Run(); - - long jobsLeft = --info->m_group->m_numJobsRunning; - assert(jobsLeft >= 0); - if (jobsLeft == 0) - { - info->m_group->m_finishJob.Run(); - delete info->m_group; - } - } - - JobGroup::JobGroup(StealingThreadPool* pool, JobFunc func, void* data) - : m_pool(pool) - , m_numJobsRunning(0) - , m_finishJob(func, data) - , m_submited(false) - { - } - - void JobGroup::Submit() - { - if (m_submited) - { - assert(0); - return; - } - - if (m_numJobsRunning == 0) - { - m_pool->Submit(m_finishJob); - return; - } - - Jobs jobs; - jobs.resize(m_infos.size()); - for (size_t i = 0; i < m_infos.size(); ++i) - { - jobs[i] = Job((JobFunc) & JobGroup::Process, &m_infos[i]); - } - - m_pool->Submit(jobs); - } - - void JobGroup::Add(JobFunc func, void* data) - { - if (m_submited) - { - assert(0); - return; - } - - GroupInfo info; - info.m_job = Job(func, data); - info.m_group = this; - - m_infos.push_back(info); - ++m_numJobsRunning; - } -} diff --git a/Code/Tools/CryCommonTools/StealingThreadPool.h b/Code/Tools/CryCommonTools/StealingThreadPool.h deleted file mode 100644 index 8576ed0416..0000000000 --- a/Code/Tools/CryCommonTools/StealingThreadPool.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H -#pragma once - - -#include "ThreadUtils.h" -#include -#include -#include -#include -#if AZ_TRAIT_OS_PLATFORM_APPLE -#include "AppleSpecific.h" -#endif - -namespace ThreadUtils { - class StealingWorker; - class JobGroup; - - // Simple stealing thread pool - class StealingThreadPool - { - public: - explicit StealingThreadPool(int numThreads, bool enableTracing = false); - ~StealingThreadPool(); - - void Start(); - void WaitAllJobs(); - - const std::vector& Traces() const{ return m_threadTraces; } - bool SaveTracesGraph(const char* filename); - - // Submits single independent job - template - void Submit(void(* jobFunc)(T*), T* data) - { - Submit(Job((JobFunc)jobFunc, data)); - } - - // Create a group of jobs. A group of jobs can be followed by one "finishing" job. - // It is a way to express dependencies between jobs. - template - JobGroup* CreateJobGroup(void(* jobFunc)(T*), T* data) - { - return CreateJobGroup((JobFunc)jobFunc, (void*)data); - } - - uint GetNumThreads() const { return aznumeric_cast(m_numThreads); } - - private: - StealingWorker* FindBestVictim(int exceptFor) const; - StealingWorker* FindWorstWorker() const; - - void Submit(const Job& job); - void Submit(const Jobs& jobs); - JobGroup* CreateJobGroup(JobFunc, void* data); - - size_t m_numThreads; - typedef std::vector ThreadWorkers; - ThreadWorkers m_workers; - - bool m_enableTracing; - std::vector m_threadTraces; - - AZStd::atomic_long m_numJobsWaitingForExecution; - AZStd::atomic_long m_numJobs; - AZStd::condition_variable m_jobsCV; - AZStd::condition_variable m_jobFinishedCV; - - - friend class JobGroup; - friend class StealingWorker; - }; - - - // JobGroup represents a group of jobs that can be followed by one "finishing" - // job. This is a way to express dependencies between jobs. - class JobGroup - { - public: - template - void Add(void(* jobFunc)(T*), T* data) - { - Add((JobFunc)jobFunc, data); - } - - // Submits group to thread pool - void Submit(); - private: - struct GroupInfo - { - Job m_job; - JobGroup* m_group; - }; - typedef std::vector GroupInfos; - - JobGroup(StealingThreadPool* pool, JobFunc func, void* data); - - static void Process(JobGroup::GroupInfo* job); - void Add(JobFunc func, void* data); - - volatile LONG m_numJobsRunning; - StealingThreadPool* m_pool; - GroupInfos m_infos; - Job m_finishJob; - bool m_submited; - friend class StealingThreadPool; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_STEALINGTHREADPOOL_H diff --git a/Code/Tools/CryCommonTools/SuffixUtil.h b/Code/Tools/CryCommonTools/SuffixUtil.h deleted file mode 100644 index 632e86525f..0000000000 --- a/Code/Tools/CryCommonTools/SuffixUtil.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H -#pragma once - - -// convenience class to work with suffixes in filenames, like in like dirt_ddn.dds -class SuffixUtil -{ -public: - - // filename allowed to have many suffixes (e.g. "test_ddn_bump.dds" has "bump" and "ddn" - // as suffixes (assuming that suffixSeparator is '_'). - // suffixes in file extension are also considered (e.g. "test_abc.my_data" has "abc" and "data" as suffixes) - // suffixes in path part are also considered. if it's not what you want - remove path before calling this function. - // comparison is case insensitive - static bool HasSuffix(const char* const filename, const char suffixSeparator, const char* const suffix) - { - assert(filename); - assert(suffix && suffix[0]); - - const size_t suffixLen = strlen(suffix); - - for (const char* p = filename; *p; ++p) - { - if (p[0] != suffixSeparator) - { - continue; - } - - if (azmemicmp(&p[1], suffix, suffixLen) != 0) - { - continue; - } - - const char c = p[1 + suffixLen]; - if ((c == 0) || (c == suffixSeparator) || (c == '.')) - { - return true; - } - } - - return false; - } -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SUFFIXUTIL_H diff --git a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp b/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp deleted file mode 100644 index 3ee26df3bd..0000000000 --- a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.cpp +++ /dev/null @@ -1,442 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include -#include // assert() -#include // floorf() -#include "SummedAreaFilterKernel.h" // CSummedAreaFilterKernel - -CSummedAreaFilterKernel::CSummedAreaFilterKernel() -{ - m_eFilterType = eEmpty; - m_fCorrectionFactor = 0.0f; -} - -// http://www.sixsigma.de/english/sixsigma/6s_e_gauss.htm -bool CSummedAreaFilterKernel::CreateFromGauss(const unsigned long indwSize) -{ - assert(indwSize > 2); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - for (unsigned long y = 0; y < indwSize; y++) - { - for (unsigned long x = 0; x < indwSize; x++) - { - float fX = (float)(x) - (float)(indwSize) * 0.5f; - float fY = (float)(y) - (float)(indwSize) * 0.5f; - - double r1 = sqrt(fX * fX + fY * fY) / (indwSize * 0.5 - 2.0); - - if (r1 > 1) - { - m_pData[y * indwSize + x] = 0; - } - else - { - double fSigma = 1.0 / 3.0; // we aim for 6*sigma = 99,99996 of all values - - double fWeight = exp(-r1 * r1 / (2 * fSigma * fSigma)); - - fWeight -= (1.0 - 0.9999996); - - m_pData[y * indwSize + x] = (int)(255.0f * fWeight); - } - } - } - - m_eFilterType = eGaussBlur; - _SumUpTableAndNormalize(); - return true; -} - - -// create summed area table -void CSummedAreaFilterKernel::_SumUpTableAndNormalize() -{ - for (unsigned long y = 0; y < m_dwHeight; y++) - { - int iFromLeft = 0; - - for (unsigned long x = 0; x < m_dwWidth; x++) - { - iFromLeft += m_pData[y * m_dwWidth + x]; - - if (y != 0) - { - m_pData[y * m_dwWidth + x] = iFromLeft + m_pData[(y - 1) * m_dwWidth + x]; - } - else - { - m_pData[y * m_dwWidth + x] = iFromLeft; - } - } - } - - m_fCorrectionFactor = 1.0f / ((float)m_pData[m_dwHeight * m_dwWidth - 1]); -} - - -// windows size 16x16 = radius 8 -bool CSummedAreaFilterKernel::CreateFromSincCalc(const unsigned long indwSize) -{ - assert(indwSize > 2); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - for (unsigned long y = 0; y < indwSize; y++) - { - for (unsigned long x = 0; x < indwSize; x++) - { - float fX = (float)(x - indwSize * 0.5f); - float fY = (float)(y - indwSize * 0.5f); - - float r1 = sqrtf(fX * fX + fY * fY) / (indwSize * 0.5f - 2.0f); - - if (r1 > 1.0f) - { - m_pData[y * indwSize + x] = 0; - } - else - { - r1 *= 3.1415926535897932384626433832795f; - - float r2 = r1 * 8.0f; - - // http://home.no.net/dmaurer/~dersch/interpolator/interpolator.html - // weight = [ sin(x*pi) / (x*pi) ] * [ sin(x*pi / 8) / (x*pi/8) ] - - // http://www.binbooks.com/books/photo/i/l/57186AF8DE - // sinc(x) = sin(pi * x) / (pi * x) - // L8interp(x) = sinc(x) * sinc(x/8) if abs(x) <= 8 - // = 0 if abs(x) > 8 - - float fWeight = (sinf(r1) * sinf(r2)) / (r1 * r2); - - m_pData[y * indwSize + x] = (int)(255.0f * fWeight); - } - } - } - - m_eFilterType = eSinc; - _SumUpTableAndNormalize(); - - return true; -} - - - - - -bool CSummedAreaFilterKernel::CreateFromRAWFile(const char* filename, const unsigned long indwSize, const int iniMidValue) -{ - assert(iniMidValue >= 0 && iniMidValue < 255); - - int iInit = 0; - - if (!Alloc(indwSize, indwSize, &iInit)) - { - return false; - } - - FILE* in = fopen(filename, "rb"); - if (!in) - { - return false; - } - - for (unsigned long y = 0; y < m_dwHeight; y++) - { - for (unsigned long x = 0; x < m_dwWidth; x++) - { - unsigned char val; - - if (fread(&val, 1, 1, in) != 1) - { - fclose(in); - return false; - } - - m_pData[y * m_dwWidth + x] = (int)val - iniMidValue; - } - } - - fclose(in); - - m_eFilterType = eRAW; - _SumUpTableAndNormalize(); - - return true; -} - - -std::string CSummedAreaFilterKernel::GetInfoString(void) const -{ - std::string sRet = "FilterKernel("; - - switch (m_eFilterType) - { - case eEmpty: - sRet += "Empty"; - break; - case eSinc: - sRet += "Sinc16x16"; - break; - case eRAW: - sRet += "RAW"; - break; - case eGaussBlur: - sRet += "GaussBlur"; - break; - case eGaussSharp: - sRet += "GaussSharp"; - break; - default: - assert(0); - } - - sRet += ")"; - - return(sRet); -} - -float CSummedAreaFilterKernel::GetAreaNonAA(float infAx, float infAy, float infDx, float infDy) const -{ - assert(m_eFilterType != eEmpty); - - int ax = (int)floorf(infAx * 127.5f + 127.5f); - int ay = (int)floorf(infAy * 127.5f + 127.5f); - int dx = (int)floorf(infDx * 127.5f + 127.5f); - int dy = (int)floorf(infDy * 127.5f + 127.5f); - - if (ax < 0) - { - ax = 0; - } - else if (ax > 255) - { - ax = 255; - } - if (dx < 0) - { - dx = 0; - } - else if (dx > 255) - { - dx = 255; - } - if (ay < 0) - { - ay = 0; - } - else if (ay > 255) - { - ay = 255; - } - if (dy < 0) - { - dy = 0; - } - else if (dy > 255) - { - dy = 255; - } - - unsigned long area = m_pData[dy * m_dwWidth + dx] - m_pData[dy * m_dwWidth + ax] - m_pData[ay * m_dwWidth + dx] + m_pData[ay * m_dwWidth + ax]; - - return(m_fCorrectionFactor * (float)area); -} - - - -// optimizable -float CSummedAreaFilterKernel::GetAreaAA(float infAx, float infAy, float infDx, float infDy) const -{ - assert(m_eFilterType != eEmpty); - - infAx = infAx * 127.5f + 127.5f; - infAy = infAy * 127.5f + 127.5f; - infDx = infDx * 127.5f + 127.5f; - infDy = infDy * 127.5f + 127.5f; - - float fSum = _GetBilinearFiltered(infDx, infDy) - - _GetBilinearFiltered(infAx, infDy) - - _GetBilinearFiltered(infDx, infAy) - + _GetBilinearFiltered(infAx, infAy); - - return(fSum * m_fCorrectionFactor); -} - - -float CSummedAreaFilterKernel::_GetBilinearFiltered(const float infX, const float infY) const -{ - float fIX = floorf(infX), fIY = floorf(infY); - float fFX = infX - fIX, fFY = infY - fIY; - int iX = (int)fIX, iY = (int)fIY; - - if (iX < 0) - { - iX = 0; - } - else if (iX > 254) - { - iX = 254; - } - if (iY < 0) - { - iY = 0; - } - else if (iY > 254) - { - iY = 254; - } - - float fArea = m_pData[ iY * m_dwWidth + iX ] * ((1.0f - fFX) * (1.0f - fFY)) // left top - + m_pData[ iY * m_dwWidth + iX + 1 ] * ((fFX) * (1.0f - fFY)) // right top - + m_pData[(iY + 1) * m_dwWidth + iX ] * ((1.0f - fFX) * (fFY)) // left bottom - + m_pData[ iY * m_dwWidth + iX + 257] * ((fFX) * (fFY)); // right bottom - - return(fArea); -} - - - -bool CSummedAreaFilterKernel::CreateWeightFilter(CSimpleBitmap& outFilter, const float infX, const float infY, - const float infWeight, const float infR) const -{ - assert(infX >= 0.0f); - assert(infX < 1.0f); - assert(infY >= 0.0f); - assert(infY < 1.0f); - assert(infWeight >= 0.0f); - assert(infR > 0.0f); - - float fLeftTop = ceilf(infR); - int iSide = 2 * (int)fLeftTop + 1; - - float fInit = 0.0f; - - if (!outFilter.Alloc(iSide, iSide, &fInit)) - { - return false; - } - - AddWeights(outFilter, infX + fLeftTop, infY + fLeftTop, infWeight, infR); - - return true; -} - - -bool CSummedAreaFilterKernel::CreateWeightFilterBlock(CSimpleBitmap& outFilter, const unsigned long indwSideLength, - const float infR) const -{ - assert(indwSideLength >= 0); - assert(infR > 0.0f); - - float fLeftTop = ceilf(infR); - int iSide = 2 * (int)fLeftTop + 1; - - float fInit = 0.0f; - - if (!outFilter.Alloc(iSide, iSide, &fInit)) - { - return false; - } - - float fStep = 1.0f / (float)indwSideLength; - float fHalf = fStep * 0.5f; - - float fWeight = fStep * fStep; - - for (float y = fHalf; y < 1.0f; y += fStep) - { - for (float x = fHalf; x < 1.0f; x += fStep) - { - AddWeights(outFilter, x + fLeftTop, y + fLeftTop, fWeight, infR); - } - } - - // check -#ifdef _DEBUG - float fSum = 0.0f; - for (int y = 0; y < iSide; y++) - { - for (int x = 0; x < iSide; x++) - { - float f; - - outFilter.Get(x, y, f); - fSum += f; - } - } - assert(fSum >= 0.98f); - assert(fSum <= 1.02f); -#endif - - return true; -} - - -void CSummedAreaFilterKernel::AddWeights(CSimpleBitmap& inoutFilter, const float infX, const float infY, - const float infWeight, const float infR) const -{ - assert(infWeight >= 0.0f); - assert(infR > 0.0f); - - if (infWeight <= 0.0f) - { - return; - } - - float fInvR = 1.0f / infR; - float sx = floorf(infX - infR); - float sy = floorf(infY - infR); - - int iax = (int)sx; - int iay = (int)sy; - int iex = (int)ceilf(infX + infR); - int iey = (int)ceilf(infY + infR); - - float x, y; - int ix, iy; - - for (iy = iay, y = (sy - infY) * fInvR; iy <= iey; iy++, y += fInvR) - { - for (ix = iax, x = (sx - infX) * fInvR; ix <= iex; ix++, x += fInvR) - { - float fArea = GetAreaAA(x, y, x + fInvR, y + fInvR); // better quality - // float fArea=m_Filter.GetAreaNonAA(x,y,x+fInvR,y+fInvR); // faster - - // assert(fArea<=1.0f); // may be wrong if we use sharpening filter - - float fOldVal; - - inoutFilter.Get(ix, iy, fOldVal); - inoutFilter.Set(ix, iy, fOldVal + fArea * infWeight); - } - } -} - - - diff --git a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h b/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h deleted file mode 100644 index 55af94f12c..0000000000 --- a/Code/Tools/CryCommonTools/SummedAreaFilterKernel.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H -#define CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H - -#include // STL string -#include "SimpleBitmap.h" // SimpleBitmap<> - -// squared of any size (summed area tables limit the size and/or values) -// normalized(sum=1) - -// optimized for high quality, not speed -// for faster filter kernels extract the neccessary size and use this 1:1 - -// based on summed area tables - -class CSummedAreaFilterKernel - : public CSimpleBitmap -{ -public: - - //! constructor init is eEmpty - CSummedAreaFilterKernel(); - - //! load 8 bit photoshop 256x256 raw image - slow - //! typical filtersize for a gaussian filter kernel is 1.44 - //! /param iniMidValue [0..255[ this enables sharpening - sharpening may expand the result range - bool CreateFromRAWFile(const char* filename, const unsigned long indwSize = 256, const int iniMidValue = 0); - - //! sharpest possible result - filter diameter size has to be 16*pixelsize (256 samples per pixel) - //! theory: http://home.no.net/dmaurer/~dersch/interpolator/interpolator.html - //! /param indwSize >2 - bool CreateFromSincCalc(const unsigned long indwSize = 256); - - //! shttp://www.sixsigma.de/english/sixsigma/6s_e_gauss.htm - //! /param indwSize >2 - bool CreateFromGauss(const unsigned long indwSize = 256); - - //! optimizable O(k*1) with high k - //! bokeh is in the range ([-1..1],[-1..1]) - //! return normalized result - float GetAreaAA(float infAx, float infAy, float infDx, float infDy) const; - - //! O(k*1) with low k - //! bokeh is in the range ([-1..1],[-1..1]) - //! return normalized result - float GetAreaNonAA(float infAx, float infAy, float infDx, float infDy) const; - - //! - //! /return e.g. "FilterKernel(Sinc16x16)" - std::string GetInfoString(void) const; - - //! /param infX [0..1[ - //! /param infY [0..1[ - //! /param infWeight [0..[ - //! /param infR >0, radius - bool CreateWeightFilter(CSimpleBitmap& outFilter, const float infX, const float infY, - const float infWeight, const float infR) const; - - //! weight for the whole block is 1.0 - //! /param indwSideLength [1,..[ e.g. 3 for 3x3 block - //! /param infR >0, radius - bool CreateWeightFilterBlock(CSimpleBitmap& outFilter, const unsigned long indwSideLength, const float infR) const; - - //! with user filter kernel - //! /param infX - //! /param infY - //! /param infWeight [0..[ - //! /param infR >0, radius - void AddWeights(CSimpleBitmap& inoutFilter, const float infX, const float infY, - const float infWeight, const float infR) const; - -private: // -------------------------------------------------------------------- - - enum EFilterState - { - eEmpty, //!< after calling constructor - eSinc, //!< from CreateFromSincCalc - eRAW, //!< from CreateFromRAWFile - eGaussBlur, //!< from CreateFromGauss - eDisc, //!< not implemented - eGaussSharp //!< not implemented - }; - - EFilterState m_eFilterType; //!< for error checks and GetInfoString() - float m_fCorrectionFactor; //!< to get the normalized (whole kernel has sum of 1) result - - //! optimizable - //! bokeh is in the range ([0..255],[0..255]) - //! /param infX - //! /param infY - //! /return not normalized result - float _GetBilinearFiltered(const float infX, const float infY) const; - - //! sum the stored values in the bitmap together - //! calculate m_fCorrectionFactor - void _SumUpTableAndNormalize(void); -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_SUMMEDAREAFILTERKERNEL_H diff --git a/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp b/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp deleted file mode 100644 index 52aa6896d6..0000000000 --- a/Code/Tools/CryCommonTools/TempFilePakExtraction.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Opens a temporary file for read only access, where the file could be -// located in a zip or pak file. Note that if the file specified -// already exists it does not delete it when finished. - - -#include "TempFilePakExtraction.h" -#include "FileUtil.h" -#include "PathHelpers.h" -#include "IPakSystem.h" - - -TempFilePakExtraction::TempFilePakExtraction(const char* filename, const char* tempPath, IPakSystem* pPakSystem) - : m_strOriginalFileName(filename) - , m_strTempFileName(filename) -{ - if (!pPakSystem || !tempPath) - { - return; - } - - { - FILE* fileOnDisk = nullptr; - azfopen(&fileOnDisk, m_strOriginalFileName.c_str(), "rb"); - if (fileOnDisk) - { - fclose(fileOnDisk); - return; - } - } - - // Choose the name for the temporary file. - string tempFullFileName; - { - uint32 tempNumber = 0; - { - LARGE_INTEGER performanceCount; - if (QueryPerformanceCounter(&performanceCount)) - { - tempNumber = performanceCount.u.LowPart; - } - } - - string tempName; - { - // CryEngine's pak system supports filenames in format "@pakFilename|fileInPak", - // so let's handle such cases by using fileInPak part of the filename. - const size_t pos = m_strOriginalFileName.find_last_of('|'); - if (pos != string::npos) - { - tempName = m_strOriginalFileName.substr(pos + 1, string::npos); - if (tempName.empty()) - { - tempName = "BadFilenameSyntax"; - } - } - else - { - tempName = m_strOriginalFileName; - } - tempName = PathHelpers::GetFilename(tempName); - } - - int tryCount = 2000; - while (--tryCount >= 0) - { - tempFullFileName.Format("%sRC%04x_%s", tempPath, (tempNumber & 0xFFFF), tempName.c_str()); - - if (!FileUtil::FileExists(tempFullFileName.c_str())) - { - FILE* f = nullptr; - azfopen(&f, tempFullFileName.c_str(), "wb"); - if (f) - { - fclose(f); - break; - } - } - - tempFullFileName.clear(); - ++tempNumber; - } - - if (tempFullFileName.empty()) - { - return; - } - } - - if (pPakSystem->ExtractNoOverwrite(m_strOriginalFileName.c_str(), tempFullFileName.c_str())) - { - m_strTempFileName = tempFullFileName; - AZ::IO::SystemFile::SetWritable(m_strTempFileName.c_str(), false); - } - else - { - AZ::IO::LocalFileIO().Remove(tempFullFileName.c_str()); - } -} - - -TempFilePakExtraction::~TempFilePakExtraction() -{ - if (HasTempFile()) - { -#if defined(AZ_PLATFORM_WINDOWS) - SetFileAttributesA(m_strTempFileName.c_str(), FILE_ATTRIBUTE_ARCHIVE); -#endif - AZ::IO::LocalFileIO().Remove(m_strTempFileName.c_str()); - } -} - - -bool TempFilePakExtraction::HasTempFile() const -{ - return (m_strOriginalFileName != m_strTempFileName); -} diff --git a/Code/Tools/CryCommonTools/TempFilePakExtraction.h b/Code/Tools/CryCommonTools/TempFilePakExtraction.h deleted file mode 100644 index c0fbb44b8a..0000000000 --- a/Code/Tools/CryCommonTools/TempFilePakExtraction.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Opens a temporary file for read only access, where the file could be -// located in a zip or pak file. Note that if the file specified -// already exists it does not delete it when finished. - - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H -#define CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H -#pragma once - -#include - -struct IPakSystem; - -class TempFilePakExtraction -{ -public: - TempFilePakExtraction(const char* filename, const char* tempPath, IPakSystem* pPakSystem); - ~TempFilePakExtraction(); - - const string& GetTempName() const - { - return m_strTempFileName; - } - - const string& GetOriginalName() const - { - return m_strOriginalFileName; - } - - bool HasTempFile() const; - -private: - string m_strTempFileName; - string m_strOriginalFileName; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_TEMPFILEPAKEXTRACTION_H diff --git a/Code/Tools/CryCommonTools/ThreadUtils.cpp b/Code/Tools/CryCommonTools/ThreadUtils.cpp deleted file mode 100644 index b3dfcd6117..0000000000 --- a/Code/Tools/CryCommonTools/ThreadUtils.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "ThreadUtils.h" -#include -#include -#include -#include - -namespace ThreadUtils -{ - class SimpleWorker - { - public: - SimpleWorker(SimpleThreadPool* pool, int index, bool trace) - : m_pool(pool) - , m_index(index) - , m_trace(trace) - { - } - - void Start(int startTime) - { - m_lastStartTime = startTime; - m_handle = AZStd::thread(AZStd::bind(SimpleWorker::ThreadFunc, (void*)this)); - } - - static unsigned int __stdcall ThreadFunc(void* param) - { - SimpleWorker* self = (SimpleWorker*)(param); - self->Work(); - return 0; - } - - void ExecuteJob(Job& job) - { - job.Run(); - if (m_trace) - { - int time = (int)GetTickCount(); - - JobTrace trace; - trace.m_job = job; - trace.m_duration = time - m_lastStartTime; - m_traces.push_back(trace); - - m_lastStartTime = time; - } - } - - void Work() - { - Job job; - for (;; ) - { - if (m_pool->GetJob(job, m_index)) - { - ExecuteJob(job); - } - else - { - return; - } - } - } - - // Called from main thread - void Join(JobTraces& traces) - { - if(m_handle.joinable()) - { - m_handle.join(); - } - - if (m_trace) - { - m_traces.swap(traces); - } - } - - private: - SimpleThreadPool* m_pool; - AZStd::thread m_handle; - int m_index; - bool m_trace; - int m_lastStartTime; - JobTraces m_traces; - friend SimpleThreadPool; - }; - - // --------------------------------------------------------------------------- - - SimpleThreadPool::SimpleThreadPool(bool trace) - : m_trace(trace) - , m_started(false) - , m_numProcessedJobs(0) - { - } - - SimpleThreadPool::~SimpleThreadPool() - { - WaitAllJobs(); - } - - void SimpleThreadPool::Start(int numThreads) - { - m_workers.resize(numThreads); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i] = new SimpleWorker(this, i, m_trace); - } - - m_started = true; - - int startTime = (int)GetTickCount(); - for (int i = 0; i < numThreads; ++i) - { - m_workers[i]->Start(startTime); - } - } - - - void SimpleThreadPool::WaitAllJobs() - { - size_t numThreads = m_workers.size(); - m_threadTraces.resize(numThreads); - for (size_t i = 0; i < numThreads; ++i) - { - m_workers[i]->Join(m_threadTraces[i]); - } - - for (size_t i = 0; i < numThreads; ++i) - { - delete m_workers[i]; - } - m_workers.clear(); - - m_started = false; - } - - void SimpleThreadPool::Submit(const Job& job) - { - assert(!m_started); - m_jobs.push_back(job); - } - - bool SimpleThreadPool::GetJob(Job& job, [[maybe_unused]] int threadIndex) - { - AZStd::lock_guard lock(m_lockJobs); - - if (m_numProcessedJobs >= m_jobs.size()) - { - return false; - } - - job = m_jobs[m_numProcessedJobs]; - ++m_numProcessedJobs; - return true; - } -} diff --git a/Code/Tools/CryCommonTools/ThreadUtils.h b/Code/Tools/CryCommonTools/ThreadUtils.h deleted file mode 100644 index ac60a8420e..0000000000 --- a/Code/Tools/CryCommonTools/ThreadUtils.h +++ /dev/null @@ -1,288 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_THREADUTILS_H -#define CRYINCLUDE_CRYCOMMONTOOLS_THREADUTILS_H -#pragma once - -#include - -#if defined(AZ_PLATFORM_WINDOWS) -#define WIN32_LEAN_AND_MEAN -#include // CRITICAL_SECTION -#endif - -#include -#include - -namespace ThreadUtils -{ -#if defined(AZ_PLATFORM_WINDOWS) - class CriticalSection - { - friend class ConditionVariable; - - public: - CriticalSection() - { - memset(&m_cs, 0, sizeof(m_cs)); - InitializeCriticalSection(&m_cs); - } - - ~CriticalSection() - { - DeleteCriticalSection(&m_cs); - } - - void Lock() - { - EnterCriticalSection(&m_cs); - } - void Unlock() - { - LeaveCriticalSection(&m_cs); - } - bool TryLock() - { - return TryEnterCriticalSection(&m_cs) != FALSE; - } - -#if defined(AZ_DEBUG_BUILD) - bool IsLocked() - { - return m_cs.RecursionCount > 0 && m_cs.OwningThread == GetCurrentThread(); - } -#endif - - private: - // You are not allowed to copy or move a CRITICAL_SECTION - // handle, so make this class non-copyable - CriticalSection(const CriticalSection& cs); - CriticalSection& operator=(const CriticalSection& cs); - - CRITICAL_SECTION m_cs; - }; - - class ConditionVariable - { - public: - ConditionVariable() - { - InitializeConditionVariable(&m_cv); - } - - void Wake() - { - WakeConditionVariable(&m_cv); - } - - void WakeAll() - { - WakeAllConditionVariable(&m_cv); - } - - void Sleep(CriticalSection& cs, DWORD milliseconds = INFINITE) - { - SleepConditionVariableCS(&m_cv, &cs.m_cs, milliseconds); - } - - private: - // You are not allowed to copy or move a CONDITION_VARIABLE - // handle, so make this class non-copyable - ConditionVariable(const ConditionVariable& cs); - ConditionVariable& operator=(const ConditionVariable& cs); - - CONDITION_VARIABLE m_cv; - }; -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - class CriticalSection - { - public: - CriticalSection() - : m_locked(false) - { - } - - ~CriticalSection() - { - } - - void Lock() - { - m_cs.lock(); - m_locked = true; - } - void Unlock() - { - m_cs.unlock(); - m_locked = false; - } - bool TryLock() - { - m_locked = m_cs.try_lock(); - return m_locked; - } - -#if defined (AZ_DEBUG_BUILD) - bool IsLocked() - { - return m_locked; - } -#endif - - private: - // You are not allowed to copy or move a CRITICAL_SECTION - // handle, so make this class non-copyable - CriticalSection(const CriticalSection& cs); - CriticalSection& operator=(const CriticalSection& cs); - - bool m_locked; - AZStd::recursive_mutex m_cs; - }; -#endif - - class AutoLock - { - private: - CriticalSection& m_lock; - - AutoLock(); - AutoLock(const AutoLock&); - AutoLock& operator = (const AutoLock&); - - public: - AutoLock(CriticalSection& lock) - : m_lock(lock) - { - m_lock.Lock(); - } - ~AutoLock() - { - m_lock.Unlock(); - } - }; - - typedef void(* JobFunc)(void*); - - struct Job - { - JobFunc m_func; - void* m_data; - int m_debugInitialThread; - - Job() - : m_func(0) - , m_data(0) - , m_debugInitialThread(0) - { - } - - Job(JobFunc func, void* data) - : m_func(func) - , m_data(data) - , m_debugInitialThread(0) - { - } - - void Run() - { - m_func(m_data); - } - }; - typedef std::deque Jobs; - - struct JobTrace - { - Job m_job; - bool m_stolen; - int m_duration; - - JobTrace() - : m_duration(0) - , m_stolen(false) - { - } - }; - typedef std::vector JobTraces; - - class SimpleWorker; - - class SimpleThreadPool - { - public: - SimpleThreadPool(bool trace); - ~SimpleThreadPool(); - - bool GetJob(Job& job, int threadIndex); - - // Submits single independent job - template - void Submit(void(* jobFunc)(T*), T* data) - { - Submit(Job((JobFunc)jobFunc, data)); - } - - void Start(int numThreads); - void WaitAllJobs(); - - private: - void Submit(const Job& job); - - bool m_started; - bool m_trace; - - std::vector m_workers; - - std::vector m_threadTraces; - - int m_numProcessedJobs; - AZStd::mutex m_lockJobs; - std::vector m_jobs; - }; - -#if defined(AZ_PLATFORM_WINDOWS) -#pragma pack(push, 8) - struct ThreadNameInfo - { - DWORD dwType; // Must be 0x1000. - LPCSTR szName; // Pointer to name (in user addr space). - DWORD dwThreadID; // Thread ID (-1=caller thread). - DWORD dwFlags; // Reserved for future use, must be zero. - }; -#pragma pack(pop) - - // Usage: SetThreadName (-1, "MainThread"); - // From http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx - inline void SetThreadName([[maybe_unused]] DWORD dwThreadID, [[maybe_unused]] const char* threadName) - { -#ifdef _DEBUG - ThreadNameInfo info; - info.dwType = 0x1000; - info.szName = threadName; - info.dwThreadID = dwThreadID; - info.dwFlags = 0; - - __try - { - const DWORD exceptionCode = 0x406D1388; - RaiseException(exceptionCode, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - } -#endif - } -#endif -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_THREADUTILS_H diff --git a/Code/Tools/CryCommonTools/UI/log_icons.bmp b/Code/Tools/CryCommonTools/UI/log_icons.bmp deleted file mode 100644 index 4080bb98ea..0000000000 --- a/Code/Tools/CryCommonTools/UI/log_icons.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1fb280a5c873225c5f2b0518964c9b7947e81c6fdb4ec19374e02043a12dd295 -size 2358 diff --git a/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp b/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp deleted file mode 100644 index 0c44aabb86..0000000000 --- a/Code/Tools/CryCommonTools/UnitTests/PathHelpersUnitTests.cpp +++ /dev/null @@ -1,807 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - - -#include -#include "PathHelpers.h" -#include -#include -#include - -namespace PathHelpersTest -{ - class CryCommonToolsPathHelpersTest - : public UnitTest::AllocatorsTestFixture - { - public: - void SetUp() override - { - UnitTest::AllocatorsTestFixture::SetUp(); - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - } - - void TearDown() - { - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - UnitTest::AllocatorsTestFixture::TearDown(); - } - }; - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_StringPathNoExtension_ReturnsEmptyString) - { - const char* filePath = "ext"; - string result = PathHelpers::FindExtension(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_StringPath_ReturnsStringExtension) - { - const char* extension = "ext"; - const char* filePath = "foo.ext"; - string result = PathHelpers::FindExtension(filePath); - EXPECT_STREQ(extension, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_WStringPathNoExtension_ReturnsEmptyString) - { - const wchar_t filePath[] = L"ext"; - const wchar_t expectedResult[] = L""; - const wstring result = PathHelpers::FindExtension(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, FindExtension_WStringPath_ReturnsStringExtension) - { - const wchar_t extension[] = L"ext"; - const wchar_t filePath[] = L"foo.ext"; - const wstring result = PathHelpers::FindExtension(filePath); - EXPECT_TRUE(result == extension); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_EmptyStringPath_ReturnsEmptyString) - { - const char* filePath = ""; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringNoExtension_ReturnsStringNoExtension) - { - const char* filePath = "foo.ext"; - const char* newExtension = ""; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithDoubleBackSlash_ReturnsUnalteredString) - { - const char* filePath = "foo.ext\\"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithForwardSlash_ReturnsUnalteredString) - { - const char* filePath = "foo.ext/"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathWithColon_ReturnsUnalteredString) - { - const char* filePath = "foo.ext:"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringPathEndsWithPeriod_ReturnsUnalteredString) - { - const char* filePath = "foo.ext."; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_StringNewExtension_ReturnsStringWithNewExtension) - { - const char* filePath = "foo.ext"; - const char* newExtension = "new"; - string result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_STREQ("foo.new", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_EmptyWStringPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringNoExtension_ReturnsWStringNoExtension) - { - const wchar_t filePath[] = L"foo.ext"; - const wchar_t newExtension[] = L""; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithDoubleBackSlash_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext\\"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithForwardSlash_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext/"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathWithColon_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext:"; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringPathEndsWithPeriod_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo.ext."; - const wchar_t newExtension[] = L"new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, ReplaceExtension_WStringNewExtension_ReturnsWStringWithNewExtension) - { - const wchar_t filePath[] = L"foo.ext"; - const wchar_t newExtension[] = L"new"; - const wchar_t expectedResult[] = L"foo.new"; - wstring result = PathHelpers::ReplaceExtension(filePath, newExtension); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_StringPathNoExtension_ReturnsUnalteredString) - { - const char* filePath = "foo"; - string result = PathHelpers::RemoveExtension(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_StringPath_ReturnsStringWithoutExtension) - { - const char* filePath = "foo.bar"; - string result = PathHelpers::RemoveExtension(filePath); - EXPECT_STREQ("foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_WStringPathNoExtension_ReturnsUnalteredWString) - { - const wchar_t filePath[] = L"foo"; - wstring result = PathHelpers::RemoveExtension(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveExtension_WStringPath_ReturnsWStringWithoutExtension) - { - const wchar_t filePath[] = L"foo.bar"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveExtension(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithColon_RemovesCharactersAfterColon) - { - const char* filePath = "foo:bar"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foo:", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithColonAsCharacterBeforeLastSeparator_RemovesCharactersAfterLastSeparator) - { - const char* filePath = "foo:/bar"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foo:/", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathWithLastSeparatorAsFirstCharacter_ReturnsStringColon) - { - const char* filePath = ":foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(":", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathStartsWithForwardSlash_ReturnsFullString) - { - const char* filePath = "//foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPathStartsWithDoubleBackSlash_ReturnsFullString) - { - const char* filePath = "\\\\foo"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_StringPath_ReturnsOnlyStringPath) - { - const char* filePath = "foobar/"; - string result = PathHelpers::GetDirectory(filePath); - EXPECT_STREQ("foobar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithColon_RemovesCharactersAfterColon) - { - const wchar_t filePath[] = L"foo:bar"; - const wchar_t expectedResult[] = L"foo:"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithColonAsCharacterBeforeLastSeparator_RemovesCharactersAfterLastSeparator) - { - const wchar_t filePath[] = L"foo:/bar"; - const wchar_t expectedResult[] = L"foo:/"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathWithLastSeparatorAsFirstCharacter_ReturnsWStringColon) - { - const wchar_t filePath[] = L":foo"; - const wchar_t expectedResult[] = L":"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathStartsWithForwardSlash_ReturnsFullWString) - { - const wchar_t filePath[] = L"//foo"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPathStartsWithDoubleBackSlash_ReturnsFullWString) - { - const wchar_t filePath[] = L"\\\\foo"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetDirectory_WStringPath_ReturnsOnlyWStringPath) - { - const wchar_t filePath[] = L"foobar/"; - const wchar_t expectedResult[] = L"foobar"; - wstring result = PathHelpers::GetDirectory(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPathStartsWithForwardSlash_ReturnsEmptyString) - { - const char* filePath = "/:foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPathStartsWithDoubleBackSlash_ReturnsEmptyString) - { - const char* filePath = "\\:foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_StringPath_ReturnsStringFilename) - { - const char* filePath = "/foo/foo/foobar"; - string result = PathHelpers::GetFilename(filePath); - EXPECT_STREQ("foobar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPathStartsWithForwardSlash_ReturnsEmptyWString) - { - const wchar_t filePath[] = L"/:foobar"; - const wchar_t expectedResult[] = L""; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPathStartsWithDoubleBackSlash_ReturnsEmptyWString) - { - const wchar_t filePath[] = L"\\:foobar"; - const wchar_t expectedResult[] = L""; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetFilename_WStringPath_ReturnsWStringFilename) - { - const wchar_t filePath[] = L"/foo/foo/foobar"; - const wchar_t expectedResult[] = L"foobar"; - wstring result = PathHelpers::GetFilename(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_EmptyPath_ReturnsEmptyString) - { - const char* filePath = ""; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithForwardSlash_ReturnsStringPath) - { - const char* filePath = "foo/"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithDoubleBackSlash_ReturnsStringPath) - { - const char* filePath = "foo\\"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPathEndsWithColon_ReturnsStringPath) - { - const char* filePath = "foo:"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_StringPath_ReturnsStringWithDoubleBackSlashAdded) - { - const char* filePath = "foo"; - string result = PathHelpers::AddSeparator(filePath); - EXPECT_STREQ("foo\\", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_EmptyPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithForwardSlash_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo/"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithDoubleBackSlash_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo\\"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPathEndsWithColon_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo:"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, AddSeparator_WStringPath_ReturnsWStringWithDoubleBackSlashAdded) - { - const wchar_t filePath[] = L"foo"; - const wchar_t expectedResult[] = L"foo\\"; - wstring result = PathHelpers::AddSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_EmptyStringPath_ReturnsEmptyString) - { - const char* filePath = ""; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPathEndsWithForwardSlash_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "foo/"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPathEndsWithDoubleBackSlash_ReturnsStringWithoutDoubleBackSlash) - { - const char* filePath = "foo\\"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ("foo", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_StringPath_ReturnsStringPath) - { - const char* filePath = "foo"; - string result = PathHelpers::RemoveSeparator(filePath); - EXPECT_STREQ(filePath, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_EmptyWStringPath_ReturnsEmptyWString) - { - const wchar_t filePath[] = L""; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPathEndsWithForwardSlash_ReturnsWStringWithoutForwardSlash) - { - const wchar_t filePath[] = L"foo/"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPathEndsWithDoubleBackSlash_ReturnsWStringWithoutDoubleBackSlash) - { - const wchar_t filePath[] = L"foo\\"; - const wchar_t expectedResult[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveSeparator_WStringPath_ReturnsWStringPath) - { - const wchar_t filePath[] = L"foo"; - wstring result = PathHelpers::RemoveSeparator(filePath); - EXPECT_TRUE(result == filePath); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathLengthEqualOne_ReturnsStringPath) - { - const char* filePath = "f"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathWithDuplicateBackSlashes_ReturnsStringWithoutDoubleBackSlashes) - { - const char* filePath = "foo\\\\bar"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_StringPathWithDuplicateForwardSlashes_ReturnsStringWithoutForwardSlashes) - { - const char* filePath = "foo//bar"; - string result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_STREQ("foo/bar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathLengthEqualOne_ReturnsWStringPath) - { - const wchar_t filePath[] = L"f"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == filePath); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathWithDuplicateBackSlashes_ReturnsWStringWithoutDoubleBackSlashes) - { - const wchar_t filePath[] = L"foo\\\\bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, RemoveDuplicateSeparators_WStringPathWithDuplicateForwardSlashes_ReturnsWStringWithoutForwardSlashes) - { - const wchar_t filePath[] = L"foo//bar"; - const wchar_t expectedResult[] = L"foo/bar"; - wstring result = PathHelpers::RemoveDuplicateSeparators(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptySecondStringPath_ReturnsFirstString) - { - const char* filePath1 = "foo"; - const char* filePath2 = ""; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ(filePath1, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptyFirstStringPath_ReturnsSecondString) - { - const char* filePath1 = ""; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ(filePath2, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_StringPath_ReturnsStringAppendedWithDoubleBackSlashDivider) - { - const char* filePath1 = "foo"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithForwardSlash_ReturnsAppendedString) - { - const char* filePath1 = "foo/"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo/bar", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithDoubleBackSlash_ReturnsAppendedString) - { - const char* filePath1 = "foo\\"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstStringPathEndsWithColon_ReturnsAppendedString) - { - const char* filePath1 = "foo:"; - const char* filePath2 = "bar"; - string result = PathHelpers::Join(filePath1, filePath2); - EXPECT_STREQ("foo:bar", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptySecondWStringPath_ReturnsFirstWString) - { - const wchar_t filePath1[] = L"foo"; - const wchar_t filePath2[] = L""; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == filePath1); - } - - TEST_F(CryCommonToolsPathHelpersTest, Join_EmptyFirstWStringPath_ReturnsSecondWString) - { - const wchar_t filePath1[] = L""; - const wchar_t filePath2[] = L"bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == filePath2); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_WStringPath_ReturnsWStringAppendedWithDoubleBackSlashDivider) - { - const wchar_t filePath1[] = L"foo"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithForwardSlash_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo/"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo/bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithDoubleBackSlash_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo\\"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo\\bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, Join_FirstWStringPathEndsWithColon_ReturnsAppendedWString) - { - const wchar_t filePath1[] = L"foo:"; - const wchar_t filePath2[] = L"bar"; - const wchar_t expectedResult[] = L"foo:bar"; - wstring result = PathHelpers::Join(filePath1, filePath2); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_EmptyStringPath_ReturnsTrue) - { - const char* filePath = ""; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPath_ReturnsTrue) - { - const char* filePath = "foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithForwardSlash_ReturnsFalse) - { - const char* filePath = "/foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithDoubleBackSlash_ReturnsFalse) - { - const char* filePath = "\\foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE (result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_StringPathBeginsWithColon_ReturnsFalse) - { - const char* filePath = ":foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_EmptyWStringPath_ReturnsTrue) - { - const wchar_t filePath[] = L""; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPath_ReturnsTrue) - { - const wchar_t filePath[] = L"foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithForwardSlash_ReturnsFalse) - { - const wchar_t filePath[] = L"/foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithDoubleBackSlash_ReturnsFalse) - { - const wchar_t filePath[] = L"\\foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, IsRelative_WStringPathBeginsWithColon_ReturnsFalse) - { - const wchar_t filePath[] = L":foo"; - bool result = PathHelpers::IsRelative(filePath); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToUnixPath_StringPath_ReturnsStringWithForwardSlashes) - { - const char* filePath = "foo\\foo\\foo"; - string result = PathHelpers::ToUnixPath(filePath); - EXPECT_STREQ("foo/foo/foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToUnixPath_WStringPath_ReturnsWStringWithForwardSlashes) - { - const wchar_t filePath[] = L"foo\\foo\\foo"; - const wchar_t expectedResult[] = L"foo/foo/foo"; - wstring result = PathHelpers::ToUnixPath(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToDosPath_StringPath_ReturnsStringWithDoubleBackSlashes) - { - const char* filePath = "foo/foo/foo"; - string result = PathHelpers::ToDosPath(filePath); - EXPECT_STREQ("foo\\foo\\foo", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, ToDosPath_WStringPath_ReturnsStringWithDoubleBackSlashes) - { - const wchar_t filePath[] = L"foo/foo/foo"; - const wchar_t expectedResult[] = L"foo\\foo\\foo"; - wstring result = PathHelpers::ToDosPath(filePath); - EXPECT_TRUE(result == expectedResult); - } - - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_EmptyStringPath_ReturnsEmpty) - { - const char* filePath = ""; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ(filePath, result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_StringPath_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "foo/bar/"; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ("foo\\bar", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - - TEST_F(CryCommonToolsPathHelpersTest, GetAsciiPath_EmptyWStringPath_ReturnsEmpty) - { - const wchar_t filePath[] = L""; - string expectedResult = ""; - string result = PathHelpers::GetAsciiPath(filePath); - EXPECT_STREQ(expectedResult, result); - } - - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathLengthLessThanThree_ReturnsStringWithoutForwardSlash) - { - const char* filePath = "./"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ(".", result); - } - - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathStartsWithPeriodForwardSlash_ReturnsStringWithoutPeriodAndForwardSlash) - { - const char* filePath = "./foo"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ("foo", result); - } - -#if AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS - TEST_F(CryCommonToolsPathHelpersTest, CanonicalizePath_StringPathStartsWithPeriodDoubleBackSlash_ReturnsStringWithoutPeriodAndDoubleBackSlash) - { - const char* filePath = ".\\foo"; - string result = PathHelpers::CanonicalizePath(filePath); - EXPECT_STREQ("foo", result); - } -#endif // AZ_TRAIT_OS_USE_WINDOWS_FILE_PATHS -} - -AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp b/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp deleted file mode 100644 index 013f077528..0000000000 --- a/Code/Tools/CryCommonTools/UnitTests/StringHelpersUnitTests.cpp +++ /dev/null @@ -1,1056 +0,0 @@ -/* - * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or - * its licensors. - * - * For complete copyright and license terms please see the LICENSE at the root of this - * distribution (the "License"). All use of this software is governed by the License, - * or, if provided, by the license below or the license accompanying this file. Do not - * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * - */ - -#include -#include "StringHelpers.h" -#include -#include -#include - -namespace StringHelpersTest -{ - class CryCommonToolsStringHelpersTest - : public UnitTest::AllocatorsTestFixture - { - public: - void SetUp() override - { - UnitTest::AllocatorsTestFixture::SetUp(); - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - } - - void TearDown() - { - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - UnitTest::AllocatorsTestFixture::TearDown(); - } - }; - - TEST_F(CryCommonToolsStringHelpersTest, Compare_TwoMatchingStrings_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondStringLonger_ReturnsGreaterThanZero) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstStringLonger_ReturnsLessThanZero) - { - const char* string1 = "foobar"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstStringCapitalized_ReturnsGreaterThanZero) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondStringCapitalized_ReturnsLessThanZero) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_TwoMatchingWStrings_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondWStringLonger_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstWStringLonger_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foobar"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_FirstWStringCapitalized_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Compare_SecondWStringCapitalized_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - int result = StringHelpers::Compare(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_TwoMatchingStrings_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstStringCapitalized_ReturnsZero) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondStringCapitalized_ReturnsZero) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondStringLonger_ReturnsGreaterThanZero) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstStringLonger_ReturnsLessThanZero) - { - const char* string1 = "foobar"; - const char* string2 = "foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_TwoMatchingWStrings_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstWStringCapitalized_ReturnsZero) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondWStringCapitalized_ReturnsZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_EQ(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_SecondWStringLonger_ReturnsGreaterThanZero) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_GT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, CompareIgnoreCase_FirstWStringLonger_ReturnsLessThanZero) - { - const wchar_t string1[] = L"foobar"; - const wchar_t string2[] = L"foo"; - int result = StringHelpers::CompareIgnoreCase(string1, string2); - EXPECT_LT(0, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SameTwoStrings_ReturnsTrue) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SecondStringUpperCase_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_FirstStringUpperCase_ReturnsFalse) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_DifferentStrings_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SameTwoWStrings_ReturnsTrue) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_SecondWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_FirstWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Equals_DifferentWStrings_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - bool result = StringHelpers::Equals(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SameTwoStrings_ReturnsTrue) - { - const char* string1 = "foo"; - const char* string2 = "foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SecondStringUpperCase_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "FOO"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_FirstStringUpperCase_ReturnsFalse) - { - const char* string1 = "FOO"; - const char* string2 = "foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_DifferentStrings_ReturnsFalse) - { - const char* string1 = "foo"; - const char* string2 = "foobar"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SameTwoWStrings_ReturnsTrue) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_SecondWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"FOO"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_FirstWStringUpperCase_ReturnsFalse) - { - const wchar_t string1[] = L"FOO"; - const wchar_t string2[] = L"foo"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EqualsIgnoreCase_DifferentWStrings_ReturnsFalse) - { - const wchar_t string1[] = L"foo"; - const wchar_t string2[] = L"foobar"; - bool result = StringHelpers::EqualsIgnoreCase(string1, string2); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathsWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "FOO"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathsWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_PatternWstringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"FOO"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWith_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::StartsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathsWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "FOO"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathsWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"foo"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"FOO"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, StartsWithIgnoreCase_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::StartsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBAR"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobar"; - const char* pattern = "BAR"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::EndsWith(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWith_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "foobar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathCapitalized_ReturnsTrue) - { - const char* string = "FOOBAR"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foobar"; - const char* pattern = "BAR"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_StringPathAndNoMatchingPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"foobar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOOBAR"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foobar"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, EndsWithIgnoreCase_WStringPathAndNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::EndsWithIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "barbar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foobarfoo"; - const char* pattern = "BAR"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathCapitalized_ReturnsFalse) - { - const char* string = "FOOBARFOO"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_StringPathNoMatchingPattern_ReturnsFalse) - { - const char* string = "foofoofoo"; - const char* pattern = "bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"barbar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_PatternWStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOOBARFOO"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Contains_WStringPathNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foofoofoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::Contains(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathWithLongerPattern_ReturnsFalse) - { - const char* string = "foo"; - const char* pattern = "barbar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathAndPattern_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foobarfoo"; - const char* pattern = "BAR"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathCapitalized_ReturnsTrue) - { - const char* string = "FOOBARFOO"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_StringPathNoMatchingPattern_ReturnsFalse) - { - const char* string = "foofoofoo"; - const char* pattern = "bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathWithLongerPattern_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t pattern[] = L"barbar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathAndPattern_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathAndPattern2_ReturnsTrue) - { - const wchar_t string[] = L"foobfobaro"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foobarfoo"; - const wchar_t pattern[] = L"BAR"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOOBARFOO"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, ContainsIgnoreCase_WStringPathNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foofoofoo"; - const wchar_t pattern[] = L"bar"; - bool result = StringHelpers::ContainsIgnoreCase(string, pattern); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringMatchingPattern_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_PatternStringCapitalized_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "F*O"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringCapitalized_ReturnsFalse) - { - const char* string = "FOO"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "f*r"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_StringNoMatchingPattern_ReturnsFalse) - { - const char* string = "foobar"; - const char* wildcard = "foo"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringMatchingPattern_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WPatternStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"F*O"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringCapitalized_ReturnsFalse) - { - const wchar_t string[] = L"FOO"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*r"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcards_WStringNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t wildcard[] = L"foo"; - bool result = StringHelpers::MatchesWildcards(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringMatchingPattern_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_PatternStringCapitalized_ReturnsTrue) - { - const char* string = "foo"; - const char* wildcard = "F*O"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringCapitalized_ReturnsTrue) - { - const char* string = "FOO"; - const char* wildcard = "f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const char* string = "foo"; - const char* wildcard = "f*r"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_StringNoMatchingPattern_ReturnsFalse) - { - const char* string = "foobar"; - const char* wildcard = "foo"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringMatchingPattern_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_PatternWStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"F*O"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringCapitalized_ReturnsTrue) - { - const wchar_t string[] = L"FOO"; - const wchar_t wildcard[] = L"f*o"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_TRUE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringNoMatchingPatternWithAsterisk_ReturnsFalse) - { - const wchar_t string[] = L"foo"; - const wchar_t wildcard[] = L"f*r"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MatchesWildcardsIgnoreCase_WStringNoMatchingPattern_ReturnsFalse) - { - const wchar_t string[] = L"foobar"; - const wchar_t wildcard[] = L"foo"; - bool result = StringHelpers::MatchesWildcardsIgnoreCase(string, wildcard); - EXPECT_FALSE(result); - } - - TEST_F(CryCommonToolsStringHelpersTest, TrimLeft_StringWithoutReturnOrTab_ReturnsString) - { - const char* stringInput = "foo"; - string result = StringHelpers::TrimLeft(stringInput); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, TrimRight_StringWithoutReturnOrTab_ReturnsString) - { - const char* stringInput = "foo"; - string result = StringHelpers::TrimRight(stringInput); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeLowerCase_UpperCaseString_ReturnsLowerCaseString) - { - const char* stringInput = "FOO"; - string result = StringHelpers::MakeLowerCase(stringInput); - EXPECT_STREQ("foo", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeLowerCase_UpperCaseWString_ReturnsLowerCaseString) - { - const wchar_t stringInput[] = L"FOO"; - const wchar_t expectedString[] = L"foo"; - wstring result = StringHelpers::MakeLowerCase(stringInput); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeUpperCase_LowerCaseString_ReturnsUpperCaseString) - { - const char* stringInput = "foo"; - string result = StringHelpers::MakeUpperCase(stringInput); - EXPECT_STREQ("FOO", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, MakeUpperCase_LowerCaseWString_ReturnsUpperCaseString) - { - const wchar_t stringInput[] = L"foo"; - const wchar_t expectedString[] = L"FOO"; - wstring result = StringHelpers::MakeUpperCase(stringInput); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplace_ReturnsStringWithReplacedCharacters) - { - const char* stringInput = "foo"; - char oldChar = 'o'; - char newChar = 'i'; - string result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_STREQ("fii", result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplace_ReturnsWStringWithReplacedCharacters) - { - const wchar_t stringInput[] = L"foo"; - wchar_t oldChar = 'o'; - wchar_t newChar = 'i'; - const wchar_t expectedString[] = L"fii"; - wstring result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_TRUE(result == expectedString); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplaceNotInString_ReturnsOriginalString) - { - const char* stringInput = "foo"; - char oldChar = 'a'; - char newChar = 'i'; - string result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_STREQ(stringInput, result); - } - - TEST_F(CryCommonToolsStringHelpersTest, Replace_CharacterToReplaceNotInWString_ReturnsOriginalWString) - { - const wchar_t stringInput[] = L"foo"; - wchar_t oldChar = 'a'; - wchar_t newChar = 'i'; - wstring result = StringHelpers::Replace(stringInput, oldChar, newChar); - EXPECT_TRUE(result == stringInput); - } -} diff --git a/Code/Tools/CryCommonTools/WeightFilterSet.cpp b/Code/Tools/CryCommonTools/WeightFilterSet.cpp deleted file mode 100644 index dfc5ff24d0..0000000000 --- a/Code/Tools/CryCommonTools/WeightFilterSet.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include // assert() -#include "WeightFilterSet.h" // CWeightFilterSet - - - -void CWeightFilterSet::FreeData() -{ - m_FilterKernelBlock.FreeData(); -} - - -bool CWeightFilterSet::Create(const unsigned long indwSideLength, const CSummedAreaFilterKernel& inFilter, const float infR) -{ - assert(indwSideLength >= 1); - - FreeData(); - - // 32 Baustelle - inFilter.CreateWeightFilterBlock(m_FilterKernelBlock, 1, infR * indwSideLength); - return(true); -} - diff --git a/Code/Tools/CryCommonTools/WeightFilterSet.h b/Code/Tools/CryCommonTools/WeightFilterSet.h deleted file mode 100644 index 16c8c79acd..0000000000 --- a/Code/Tools/CryCommonTools/WeightFilterSet.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H -#define CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H - - -#include "SimpleBitmap.h" // SimpleBitmap<> -#include // STL vector<> -#include "SummedAreaFilterKernel.h" // CSummedAreaFilterKernel - -class CWeightFilterSet -{ -public: - - //! /param indwSideLength [1,..[ e.g. 3 for 3x3 block - bool Create(const unsigned long indwSideLength, const CSummedAreaFilterKernel& inFilter, const float infR); - - //! - void FreeData(); - - //! optimizable - //! weight is 1.0 - //! /param iniX x position in inoutDest - //! /param iniY y position in inoutDest - //! /param TInputImage typically CSimpleBitmap - //! /return weight - template - float GetBlockWithFilter(const TInputImage& inSrc, const int iniX, const int iniY, TElement& outResult) - { - float fWeightSum = 0.0f; - CSimpleBitmap& rBitmap = m_FilterKernelBlock; - - int W = (int)rBitmap.GetWidth(); - int H = (int)rBitmap.GetHeight(); - - int iSrcW = (int)inSrc.GetWidth(); - int iSrcH = (int)inSrc.GetHeight(); - - float* pfWeights = rBitmap.GetPointer(0, 0); - - for (int y = 0; y < H; y++) - { - int iDestY = y + iniY - H / 2; - - // optimizable (don't use the bottom border) - // if(iDestY==iSrcH){ pfWeights+=H;continue; } - - for (int x = 0; x < W; x++, pfWeights++) - { - int iDestX = x + iniX - W / 2; - - // optimizable (don't use the right border) - // if(iDestX==iSrcW) - // continue; - - TElement Value; - - // if(inSrc.Get(iDestX,iDestY,Value)) - if (inSrc.Get((iDestX + iSrcW * 2) % iSrcW, (iDestY + iSrcH * 2) % iSrcH, Value)) // tiled - { - float fWeight = *pfWeights; - - outResult += Value * fWeight; - fWeightSum += fWeight; - } - } - } - - return fWeightSum; - } - - int GetBorderSize() - { - int W = (int)m_FilterKernelBlock.GetWidth(); - - return (W - 1) / 2; - } - -private: // ------------------------------------------------------------- - - CSimpleBitmap m_FilterKernelBlock; //!< weight = 1 -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_WEIGHTFILTERSET_H diff --git a/Code/Tools/CryCommonTools/XMLPakFileSink.cpp b/Code/Tools/CryCommonTools/XMLPakFileSink.cpp deleted file mode 100644 index 9a9590687f..0000000000 --- a/Code/Tools/CryCommonTools/XMLPakFileSink.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "XMLPakFileSink.h" -#include "StringHelpers.h" - -XMLPakFileSink::XMLPakFileSink(IPakSystem* pakSystem, const string& archivePath, const string& filePath) - : pakSystem(pakSystem) - , filePath(filePath) -{ - archive = pakSystem->OpenArchive(archivePath.c_str()); -} - -XMLPakFileSink::~XMLPakFileSink() -{ - if (archive && pakSystem) - { - SYSTEMTIME st; - GetSystemTime(&st); - - FILETIME ft; - ZeroStruct(ft); - const BOOL ok = SystemTimeToFileTime(&st, &ft); - - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - - const __int64 modTime = lt.QuadPart; - ; - - pakSystem->AddToArchive(archive, filePath.c_str(), &data[0], int(data.size()), modTime); - pakSystem->CloseArchive(archive); - } -} - -void XMLPakFileSink::Write(const char* text) -{ - string asciiText = text; - int len = int(asciiText.size()); - int start = int(data.size()); - data.resize(data.size() + len); - memcpy(&data[start], asciiText.c_str(), len); -} diff --git a/Code/Tools/CryCommonTools/XMLPakFileSink.h b/Code/Tools/CryCommonTools/XMLPakFileSink.h deleted file mode 100644 index 973f9a05ca..0000000000 --- a/Code/Tools/CryCommonTools/XMLPakFileSink.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_XMLPAKFILESINK_H -#define CRYINCLUDE_CRYCOMMONTOOLS_XMLPAKFILESINK_H -#pragma once - - -#include "XMLWriter.h" -#include "IPakSystem.h" - -class XMLPakFileSink - : public IXMLSink -{ -public: - XMLPakFileSink(IPakSystem* pakSystem, const string& archivePath, const string& filePath); - ~XMLPakFileSink(); - - // IXMLSink - virtual void Write(const char* text); - -private: - IPakSystem* pakSystem; - PakSystemArchive* archive; - string filePath; - std::vector data; -}; - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_XMLPAKFILESINK_H diff --git a/Code/Tools/CryCommonTools/XMLWriter.cpp b/Code/Tools/CryCommonTools/XMLWriter.cpp deleted file mode 100644 index bfaf9df429..0000000000 --- a/Code/Tools/CryCommonTools/XMLWriter.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "XMLWriter.h" -#include "StringHelpers.h" -#include - -XMLWriter::XMLWriter(IXMLSink* sink) -{ - m_indentationSize = -1; - m_sink = sink; - - WriteText("\n"); -} - -void XMLWriter::BeginElement(const string& name) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("<%s", name.c_str()); - m_newLine = false; -} - -void XMLWriter::EndElement(const string& name) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("\n", name.c_str()); - m_newLine = true; -} - -void XMLWriter::CloseElement(const string& name, bool newLine) -{ - if (newLine) - { - WriteText(">\n"); - } - else - { - WriteText(">"); - } - m_newLine = newLine; -} - -void XMLWriter::CloseLeafElement(const string& name) -{ - WriteText(" />\n"); - m_newLine = true; -} - -void XMLWriter::IncreaseIndentation() -{ - ++m_indentationSize; -} - -void XMLWriter::DecreaseIndentation() -{ - --m_indentationSize; -} - -void XMLWriter::WriteAttribute(const string& name, const string& value) -{ - WriteText(" %s=\"%s\"", name.c_str(), value.c_str()); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, const string& value) -{ - // TODO: Escape string. - strcpy_s(buffer, bufferSize, value.c_str()); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, float value) -{ - sprintf_s(buffer, bufferSize, "%.10e", value); -} - -void XMLWriter::SerializeAttribute(char* buffer, size_t bufferSize, int value) -{ - sprintf_s(buffer, bufferSize, "%d", value); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, float value) -{ - sprintf_s(buffer, bufferSize, "%.10e", value); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, const string& value) -{ - strcpy(buffer, value.c_str()); -} - -void XMLWriter::SerializeArrayElement(char* buffer, size_t bufferSize, int value) -{ - sprintf_s(buffer, bufferSize, "%d", value); -} - -void XMLWriter::WriteContent(const string& text) -{ - WriteText("%s", text.c_str()); -} - -void XMLWriter::WriteContentLine(const string& text) -{ - // Write the indentation. - if (m_newLine) - { - for (int i = 0; i < m_indentationSize; ++i) - { - WriteText(" "); - } - } - - WriteText("%s\n", text.c_str()); - m_newLine = true; -} - -void XMLWriter::WriteText(const char* format, ...) -{ - va_list args; - va_start(args, format); - char buffer[40000]; - azvsnprintf(buffer, sizeof(buffer), format, args); - m_sink->Write(buffer); - va_end(args); -} - -XMLWriter::Element::Element(XMLWriter& writer, const string& name, bool output) - : m_writer(writer) - , m_name(name) - , m_output(output) - , isParent(false) -{ - if (!m_writer.m_elements.empty()) - { - Element* parent = m_writer.m_elements.back(); - if (!parent->isParent) - { - parent->isParent = true; - if (parent->m_output) - { - m_writer.CloseElement(m_name, true); - } - } - } - m_writer.m_elements.push_back(this); - if (m_output) - { - m_writer.IncreaseIndentation(); - } - if (m_output) - { - m_writer.BeginElement(m_name); - } -} - -XMLWriter::Element::~Element() -{ - if (m_output) - { - if (isParent) - { - m_writer.EndElement(m_name); - } - else - { - m_writer.CloseLeafElement(m_name); - } - } - m_writer.m_elements.pop_back(); - if (m_output) - { - m_writer.DecreaseIndentation(); - } -} - -void XMLWriter::Element::Child(const string& name, const string& value) -{ - Element child(m_writer, name); - child.Content(value); -} - -void XMLWriter::Element::Content(const string& text) -{ - if (m_output) - { - assert(!isParent); - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - m_writer.WriteContent(text); - } -} - -void XMLWriter::Element::ContentLine(const string& text) -{ - if (!isParent) - { - isParent = true; - if (m_output) - { - m_writer.CloseElement(m_name, true); - } - } - if (m_output) - { - m_writer.WriteContentLine(text); - } -} - -XMLFileSink::XMLFileSink(const string& filename) -{ - m_file = std::fopen(filename.c_str(), "w"); - if (!m_file) - { - throw OpenFailedError("Unable to open file."); - } -} - -XMLFileSink::~XMLFileSink() -{ - if (m_file) - { - fclose(m_file); - } -} - -void XMLFileSink::Write(const char* text) -{ - if (m_file) - { - string asciiText = StringHelpers::ConvertString(text); - fwrite(asciiText.c_str(), 1, asciiText.size(), m_file); - } -} diff --git a/Code/Tools/CryCommonTools/XMLWriter.h b/Code/Tools/CryCommonTools/XMLWriter.h deleted file mode 100644 index d98b9f3d56..0000000000 --- a/Code/Tools/CryCommonTools/XMLWriter.h +++ /dev/null @@ -1,185 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_XMLWRITER_H -#define CRYINCLUDE_CRYCOMMONTOOLS_XMLWRITER_H -#pragma once - - -#include "Exceptions.h" - -#include -#include -#include - -class IXMLSink -{ -public: - // Define an exception type to throw when file opening fails. - struct OpenFailedErrorTag {}; - typedef Exception OpenFailedError; - - virtual void Write(const char* text) = 0; -}; - -class XMLFileSink - : public IXMLSink -{ -public: - XMLFileSink(const string& name); - ~XMLFileSink(); - - virtual void Write(const char* text); - -private: - FILE* m_file; -}; - -class XMLWriter -{ -public: - XMLWriter(IXMLSink* sink); - - class Element - { - public: - Element(XMLWriter& writer, const string& name, bool output = true); - ~Element(); - - template - void Attribute(const string& name, const T& value); - void Child(const string& name, const string& value); - void Content(const string& text); - void ContentLine(const string& text); - template - void ContentArrayElement(const T& value); - void ContentArrayFloat24(const float floatBuffer[24], const int entryCount); - - void WriteDirectText(const char* text) - { - if (!isParent) - { - isParent = true; - if (m_output) - { - m_writer.CloseElement(m_name, false); - } - } - m_writer.WriteDirectText(text); - } - - private: - XMLWriter& m_writer; - string m_name; - bool isParent; - bool m_output; - }; - - void WriteDirectText(const char* text) - { - m_sink->Write(text); - } - -private: - void IncreaseIndentation(); - void DecreaseIndentation(); - - void BeginElement(const string& name); - void EndElement(const string& name); - void CloseElement(const string& name, bool newLine); - void CloseLeafElement(const string& name); - - void WriteAttribute(const string& name, const string& value); - static void SerializeAttribute(char* buffer, size_t bufferSize, const string& value); - static void SerializeAttribute(char* buffer, size_t bufferSize, float value); - static void SerializeAttribute(char* buffer, size_t bufferSize, int value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, float value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, const string& value); - static void SerializeArrayElement(char* buffer, size_t bufferSize, int value); - void WriteContent(const string& text); - void WriteContentLine(const string& text); - - void WriteText(const char* format, ...); - - IXMLSink* m_sink; - int m_indentationSize; - - std::vector m_elements; - bool m_newLine; -}; - -template -void XMLWriter::Element::Attribute(const string& name, const T& value) -{ - assert(!isParent); - char buffer[1024]; - XMLWriter::SerializeAttribute(buffer, sizeof(buffer), value); - if (m_output) - { - m_writer.WriteAttribute(name, buffer); - } -} - -template -void XMLWriter::Element::ContentArrayElement(const T& value) -{ - if (!m_output) - { - return; - } - - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - - char buffer[1024] = {' ', 0}; - XMLWriter::SerializeArrayElement(buffer + 1, sizeof(buffer) - 1, value); - - m_writer.WriteDirectText(buffer); -} - -inline void XMLWriter::Element::ContentArrayFloat24(const float floatBuffer[24], const int entryCount) -{ - if (!m_output) - { - return; - } - if (!isParent) - { - isParent = true; - m_writer.CloseElement(m_name, false); - } - - char buffer[2048]; - if (entryCount == 24) - { - sprintf_s(buffer, " %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e %.10e", - floatBuffer[0], floatBuffer[1], floatBuffer[2], floatBuffer[3], floatBuffer[4], floatBuffer[5], floatBuffer[6], floatBuffer[7], - floatBuffer[8], floatBuffer[9], floatBuffer[10], floatBuffer[11], floatBuffer[12], floatBuffer[13], floatBuffer[14], floatBuffer[15], - floatBuffer[16], floatBuffer[17], floatBuffer[18], floatBuffer[19], floatBuffer[20], floatBuffer[21], floatBuffer[22], floatBuffer[23]); - m_writer.WriteDirectText(buffer); - } - else - { - for (int i = 0; i < entryCount; i++) - { - char buffer[1024]; - sprintf_s(buffer, " %.10e", floatBuffer[i]); - m_writer.WriteDirectText(buffer); - } - } -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_XMLWRITER_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDir.h b/Code/Tools/CryCommonTools/ZipDir/ZipDir.h deleted file mode 100644 index c9954ce5dc..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDir.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H -#pragma once - -#include "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "smartptr.h" -#include "ZipDirTree.h" -#include "ZipDirList.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirFind.h" -#include "ZipDirFindRW.h" - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIR_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp deleted file mode 100644 index 1f5d4a9286..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#include -#include "FileUtil.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCache.h" -#include "ZipDirFind.h" -#include "ZipDirCacheFactory.h" -#include -#include -#include "PathHelpers.h" -#include - -using namespace ZipFile; - -// initializes the instance structure -void ZipDir::Cache::Construct(FILE* fNew, size_t nDataSizeIn, const EncryptionKey& key) -{ - m_nRefCount = 0; - m_pFile = fNew; - m_nDataSize = nDataSizeIn; - m_nZipPathOffset = nDataSizeIn; - m_bEncryptHeaders = false; - m_encryptionKey = key; -} - -// self-destruct when ref count drops to 0 -void ZipDir::Cache::Delete() -{ - if (m_pFile) - { - fclose (m_pFile); - } - free(this); -} - -// looks for the given file record in the Central Directory. If there's none, returns NULL. -// if there is some, returns the pointer to it. -// the Path must be the relative path to the file inside the Zip -// if the file handle is passed, it will be used to find the file data offset, if one hasn't been initialized yet -ZipDir::FileEntry* ZipDir::Cache::FindFile (const char* szPath, [[maybe_unused]] bool bRefresh) -{ - ZipDir::FindFile fd (this); - if (!fd.FindExact(szPath)) - { - assert (!fd.GetFileEntry()); - return NULL; - } - assert (fd.GetFileEntry()); - return fd.GetFileEntry(); -} - -// loads the given file into the pCompressed buffer (the actual compressed data) -// if the pUncompressed buffer is supplied, uncompresses the data there -// buffers must have enough memory allocated, according to the info in the FileEntry -// NOTE: there's no need to decompress if the method is 0 (store) -// returns 0 if successful or error code if couldn't do something -ZipDir::ErrorEnum ZipDir::Cache::ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->desc.lSizeUncompressed == 0) - { - assert (pFileEntry->desc.lSizeCompressed == 0); - return ZD_ERROR_SUCCESS; - } - - assert (pFileEntry->desc.lSizeCompressed > 0); - - ErrorEnum nError = Refresh(pFileEntry); - if (nError != ZD_ERROR_SUCCESS) - { - return nError; - } - - if (AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(m_pFile, pFileEntry->nFileDataOffset, SEEK_SET)) - { - return ZD_ERROR_IO_FAILED; - } - - SmartPtr pBufferDestroyer; - - void* pBuffer = pCompressed; // the buffer where the compressed data will go - - if (pFileEntry->nMethod == 0 && pUncompressed) - { - // we can directly read into the uncompress buffer - pBuffer = pUncompressed; - } - - if (!pBuffer) - { - if (!pUncompressed) - { - // what's the sense of it - no buffers at all? - return ZD_ERROR_INVALID_CALL; - } - - pBuffer = malloc(pFileEntry->desc.lSizeCompressed); - pBufferDestroyer.Attach(pBuffer); // we want it auto-freed once we return - } - - - if (fread (pBuffer, pFileEntry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return ZD_ERROR_IO_FAILED; - } - - if (pFileEntry->nMethod == METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pBuffer, pFileEntry->desc.lSizeCompressed, m_encryptionKey); - } - - // if there's a buffer for uncompressed data, uncompress it to that buffer - if (pUncompressed) - { - if (pFileEntry->nMethod == 0) - { - assert (pBuffer == pUncompressed); - //assert (pFileEntry->desc.lSizeCompressed == pFileEntry->nSizeUncompressed); - //memcpy (pUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed); - } - else - { - unsigned long nSizeUncompressed = pFileEntry->desc.lSizeUncompressed; - if (Z_OK != ZipRawUncompress(pUncompressed, &nSizeUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed)) - { - return ZD_ERROR_CORRUPTED_DATA; - } - } - } - - return ZD_ERROR_SUCCESS; -} - -// loads and unpacks the file into a newly created buffer (that must be subsequently freed with -// Free()) Returns NULL if failed -void* ZipDir::Cache::AllocAndReadFile (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return NULL; - } - - void* pData = malloc(pFileEntry->desc.lSizeUncompressed); - if (pData) - { - if (ZD_ERROR_SUCCESS != ReadFile (pFileEntry, NULL, pData)) - { - free(pData); - pData = NULL; - } - } - return pData; -} - -// frees the memory block that was previously allocated by AllocAndReadFile -void ZipDir::Cache::Free (void* pData) -{ - free(pData); -} - -// refreshes information about the given file entry into this file entry -ZipDir::ErrorEnum ZipDir::Cache::Refresh (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; // the data offset has been successfully read.. - } - - return ZipDir::Refresh(m_pFile, pFileEntry, m_bEncryptHeaders); -} - -////////////////////////////////////////////////////////////////////////// -uint32 ZipDir::Cache::GetFileDataOffset(FileEntry* pFileEntry) -{ - if (pFileEntry->nFileDataOffset == pFileEntry->INVALID_DATA_OFFSET) - { - ZipDir::Refresh (m_pFile, pFileEntry, m_bEncryptHeaders); - } - return pFileEntry->nFileDataOffset; -} - -// returns the size of memory occupied by the instance referred to by this cache -// must be exact, because it's used by CacheRW to reallocate this cache -size_t ZipDir::Cache::GetSize() const -{ - return m_nDataSize + sizeof(Cache) + strlen(GetFilePath()); -} - - -// QUICK check to determine whether the file entry belongs to this object -bool ZipDir::Cache::IsOwnerOf (const FileEntry* pFileEntry) const -{ - // just check whether the pointer is within the memory block of this cache instance - return ((ULONG_PTR)pFileEntry >= (ULONG_PTR)(GetRoot() + 1) - && (ULONG_PTR)pFileEntry <= ((ULONG_PTR)GetRoot()) + m_nDataSize - sizeof(FileEntry)); -} - -bool ZipDir::Cache::UnpakToDisk(const string& destFolder) -{ - return UnpakToDiskInternal(GetRoot(), destFolder); -} - -bool ZipDir::Cache::UnpakToDiskInternal(ZipDir::DirHeader* folder, const string& destFolder) -{ - if (!folder) - { - return false; - } - - if (!FileUtil::EnsureDirectoryExists(destFolder.c_str())) - { - return false; - } - - bool result = true; - for (ZipFile::ushort fileNum = 0; fileNum < folder->numFiles; ++fileNum) - { - ZipDir::FileEntry* fileEntry = folder->GetFileEntry(fileNum); - if (!fileEntry) - { - result = false; - continue; - } - - string filePath = PathHelpers::Join(destFolder, fileEntry->GetName(folder->GetNamePool())); - AZ::IO::SystemFile file; - if (!file.Open(filePath.c_str(), AZ::IO::SystemFile::SF_OPEN_READ_WRITE | AZ::IO::SystemFile::SF_OPEN_CREATE)) - { - result = false; - continue; - } - - if (!fileEntry->desc.lSizeUncompressed) - { - // Nothing to write. Just close the file. - file.Close(); - continue; - } - - AZStd::vector buffer(fileEntry->desc.lSizeUncompressed); - if (ReadFile(fileEntry, nullptr, buffer.data()) == ZD_ERROR_SUCCESS) - { - file.Write(buffer.data(), buffer.size()); - file.Close(); - } - else - { - file.Close(); - AZ::IO::SystemFile::Delete(filePath.c_str()); - result = false; - continue; - } - } - - for (ZipFile::ushort dirNum = 0; dirNum < folder->numDirs; ++dirNum) - { - ZipDir::DirEntry* entry = folder->GetSubdirEntry(dirNum); - if (!entry) - { - result = false; - continue; - } - - string newPath = PathHelpers::Join(destFolder, entry->GetName(folder->GetNamePool())); - if (!UnpakToDiskInternal(entry->GetDirectory(), newPath)) - { - result = false; - continue; - } - } - - return result; -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h deleted file mode 100644 index 958c77efc3..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCache.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Declarations of the class used to parse and cache Zipped directory. -// This class is actually an auto-pointer to the instance of the cache, so it can -// be easily passed by value. -// The cache instance contains the optimized for memory usage and fast search tree -// of the files/directories inside the zip; each file has a descriptor with the -// info about where its compressed data lies within the file - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H -#pragma once - - - -///////////////////////////////////////////////////////////// -// THe Zip Dir uses a special memory layout for keeping the structure of zip file. -// This layout is optimized for small memory footprint (for big zip files) -// and quick binary-search access to the individual files. -// -// The serialized layout consists of a number of directory records. -// Each directory record starts with the DirHeader structure, then -// it has an array of DirEntry structures (sorted by name), -// array of FileEntry structures (sorted by name) and then -// the pool of names, followed by pad bytes to align the whole directory -// record on 4-byte boundray. - -namespace ZipDir -{ - // this is the header of the instance data allocated dynamically - // it contains the FILE* : it owns it and closes upon destruction - struct Cache - { - void AddRef() { ++m_nRefCount; } - void Release() - { - if (--m_nRefCount <= 0) - { - Delete(); - } - } - int NumRefs() const { return m_nRefCount; } - - // looks for the given file record in the Central Directory. If there's none, returns NULL. - // if there is some, returns the pointer to it. - // the Path must be the relative path to the file inside the Zip - // if the file handle is passed, it will be used to find the file data offset, if one hasn't been initialized yet - // if bFull is true, then the full information about the file is returned (the offset to the data may be unknown at this point)- - // if needed, the file is accessed and the information is loaded - FileEntry* FindFile (const char* szPath, bool bFullInfo = false); - - // loads the given file into the pCompressed buffer (the actual compressed data) - // if the pUncompressed buffer is supplied, uncompresses the data there - // buffers must have enough memory allocated, according to the info in the FileEntry - // NOTE: there's no need to decompress if the method is 0 (store) - // returns 0 if successful or error code if couldn't do something - ErrorEnum ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed); - - // loads and unpacks the file into a newly created buffer (that must be subsequently freed with - // Free()) Returns NULL if failed - void* AllocAndReadFile (FileEntry* pFileEntry); - - // frees the memory block that was previously allocated by AllocAndReadFile - void Free (void*); - - // refreshes information about the given file entry into this file entry - ErrorEnum Refresh (FileEntry* pFileEntry); - - // Return FileEntity data offset inside zip file. - uint32 GetFileDataOffset(FileEntry* pFileEntry); - - - // returns the root directory record; - // through this directory record, user can traverse the whole tree - DirHeader* GetRoot() const - { - return (DirHeader*)(this + 1); - } - - // returns the size of memory occupied by the instance referred to by this cache - // must be exact, because it's used by CacheRW to reallocate this cache - size_t GetSize() const; - - // QUICK check to determine whether the file entry belongs to this object - bool IsOwnerOf (const FileEntry* pFileEntry) const; - - // returns the string - path to the zip file from which this object was constructed. - // this will be "" if the object was constructed with a factory that wasn't created with FLAGS_MEMORIZE_ZIP_PATH - const char* GetFilePath() const - { - return ((const char*)(this + 1)) + m_nZipPathOffset; - } - - // Unpak the file into a destination folder - bool UnpakToDisk(const string& destFolder); - - friend class CacheFactory; // the factory class creates instances of this class - friend class CacheRW; // the Read-Write 2-way cache can modify this cache directly during write operations - protected: - volatile signed int m_nRefCount; // the reference count - FILE* m_pFile; // the opened file - - // the size of the serialized data following this instance (not including the extra fields after the serialized tree data) - size_t m_nDataSize; - // the offset to the path/name of the zip file relative to (char*)(this+1) pointer in bytes - size_t m_nZipPathOffset; - - // tells if encryption used for zip-file - EncryptionKey m_encryptionKey; - bool m_bEncryptHeaders; - public: - // initializes the instance structure - void Construct(FILE* fNew, size_t nDataSize, const EncryptionKey& key); - void Delete(); - private: - bool ReadCompressedData(char* data, size_t size); - bool UnpakToDiskInternal(ZipDir::DirHeader* dirHeader, const string& destFolder); - - // the constructor/destructor cannot be called at all - everything will go through the factory class - Cache() { m_nRefCount = 0; } - ~Cache(){} - }; - - TYPEDEF_AUTOPTR(Cache); - - typedef Cache_AutoPtr CachePtr; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp deleted file mode 100644 index 9d64f60b63..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.cpp +++ /dev/null @@ -1,804 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirList.h" -#include - -static uint32 g_defaultEncryptionKey[4] = { 0xc968fb67, 0x8f9b4267, 0x85399e84, 0xf9b99dc4 }; - -ZipDir::CacheFactory::CacheFactory (InitMethodEnum nInitMethod, unsigned nFlags) -{ - m_nCDREndPos = 0; - m_f = NULL; - m_bBuildFileEntryMap = false; // we only need it for validation/debugging - m_bBuildFileEntryTree = true; // we need it to actually build the optimized structure of directories - m_bEncryptedHeaders = false; - - m_nInitMethod = nInitMethod; - m_nFlags = nFlags; -} - -ZipDir::CacheFactory::~CacheFactory() -{ - Clear(); -} - -ZipDir::CachePtr ZipDir::CacheFactory::New (const char* szFile, const uint32 key[4]) -{ - m_encryptionKey = EncryptionKey(g_defaultEncryptionKey); - if (key) - { - m_encryptionKey = EncryptionKey(key); - } - - Clear(); - m_f = nullptr; - azfopen(&m_f, szFile, "rb"); - if (m_f) - { - return MakeCache (szFile); - } - Clear(); - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot open file in binary mode for reading, probably missing file"); - return 0; - /* - if (!m_f) - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED,"Cannot open file in binary mode for reading, probably missing file"); - try - { - return MakeCache (szFile); - } - catch(Error) - { - Clear(); - throw; - } - */ -} - - -ZipDir::CacheRWPtr ZipDir::CacheFactory::NewRW(const char* szFileName, size_t fileAlignment, bool encrypted, const uint32* key) -{ - m_encryptionKey = EncryptionKey(g_defaultEncryptionKey); - if (key) - { - m_encryptionKey = EncryptionKey(key); - } - - CacheRWPtr pCache = new CacheRW(encrypted, m_encryptionKey); - - // opens the given zip file and connects to it. Creates a new file if no such file exists - // if successful, returns true. - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - pCache->m_strFilePath = szFileName; - } - - if (m_nFlags & FLAGS_DONT_COMPACT) - { - pCache->m_nFlags |= CacheRW::FLAGS_DONT_COMPACT; - } - - // first, try to open the file for reading or reading/writing - if (m_nFlags & FLAGS_READ_ONLY) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "rb"); - pCache->m_nFlags |= CacheRW::FLAGS_CDR_DIRTY | CacheRW::FLAGS_READ_ONLY; - - if (!m_f) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for reading"); - return 0; - } - } - else - { - m_f = NULL; - if (!(m_nFlags & FLAGS_CREATE_NEW)) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "r+b"); - } - - bool bOpenForWriting = true; - - if (m_f) - { - // get file size - fseek(m_f, 0, SEEK_END); - size_t nFileSize = AZ_TRAIT_CRYCOMMONTOOLS_FTELL(m_f); - fseek(m_f, 0, SEEK_SET); - - if (nFileSize) - { - if (!ReadCacheRW(*pCache)) - { - fclose(m_f); - m_f = NULL; - - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not read archive"); - return 0; - } - bOpenForWriting = false; - } - else - { - // if file has 0 bytes (e.g. crash during saving) we don't want to open it - assert(0); // you can ignore, the system shold handle this gracefully - } - } - - if (bOpenForWriting) - { - m_f = nullptr; - azfopen(&m_f, szFileName, "w+b"); - if (m_f) - { - // there's no such file, but we'll create one. We'll need to write out the CDR here - pCache->m_lCDROffset = 0; - pCache->m_nFlags |= CacheRW::FLAGS_CDR_DIRTY; - } - pCache->m_fileAlignment = fileAlignment; - } - - if (!m_f) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for appending (read/write)"); - return 0; - } - } - - - // give the cache the file handle: - pCache->m_pFile = m_f; - // the factory doesn't own it after that - m_f = NULL; - - return pCache; -} - -bool ZipDir::CacheFactory::ReadCacheRW (CacheRW& rwCache) -{ - m_bBuildFileEntryTree = true; - if (!Prepare()) - { - return false; - } - - // since it's open for R/W, we need to know exactly how much space - // we have for each file to use the gaps efficiently - FileEntryList Adjuster (&m_treeFileEntries, m_CDREnd.lCDROffset); - Adjuster.RefreshEOFOffsets(); - - m_treeFileEntries.Swap(rwCache.m_treeDir); - m_CDR_buffer.swap(rwCache.m_CDR_buffer); // CDR Buffer contain actually the string pool for the tree directory. - m_unifiedNameBuffer.swap(rwCache.m_unifiedNameBuffer); // string pool for unified names - - // very important: we need this offset to be able to add to the zip file - rwCache.m_lCDROffset = m_CDREnd.lCDROffset; - - if (m_bEncryptedHeaders != rwCache.m_bEncryptedHeaders) - { - // force to relink and update all headers on close - rwCache.m_nFlags |= ZipDir::CacheRW::FLAGS_UNCOMPACTED; - rwCache.m_bHeadersEncryptedOnClose = rwCache.m_bEncryptedHeaders; - rwCache.m_bEncryptedHeaders = m_bEncryptedHeaders; - } - return true; -} - -// reads everything and prepares the maps -bool ZipDir::CacheFactory::Prepare () -{ - if (!FindCDREnd()) - { - return false; - } - - m_bEncryptedHeaders = (m_CDREnd.nDisk & (1 << 15)) != 0; - m_CDREnd.nDisk = m_CDREnd.nDisk & 0x7fff; - - // we don't support multivolume archives - if (m_CDREnd.nDisk != 0 - || m_CDREnd.nCDRStartDisk != 0 - || m_CDREnd.numEntriesOnDisk != m_CDREnd.numEntriesTotal) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Multivolume archive detected. Current version of ZipDir does not support multivolume archives"); - return false; - } - - // if the central directory offset or size are out of range, - // the CDREnd record is probably corrupt - if (m_CDREnd.lCDROffset > m_nCDREndPos - || m_CDREnd.lCDRSize > m_nCDREndPos - || m_CDREnd.lCDROffset + m_CDREnd.lCDRSize > m_nCDREndPos) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_DATA_IS_CORRUPT, "The central directory offset or size are out of range, the pak is probably corrupt, try to repair or delete the file"); - return false; - } - - if (!BuildFileEntryMap()) - { - return false; - } - - // the number of parsed files MUST be the declared number of entries - // in the central directory - if (m_bBuildFileEntryMap && m_CDREnd.numEntriesTotal != m_mapFileEntries.size()) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "The number of parsed files does not match the declared number of entries in the central directory, the pak is probably corrupt, try to repair or delete the file"); - } - - const size_t numFilesFound = m_treeFileEntries.NumFilesTotal(); - if (m_bBuildFileEntryTree && m_CDREnd.numEntriesTotal != numFilesFound) - { - const size_t numDirsFound = m_treeFileEntries.NumDirsTotal(); - - // Other zip tools create entries for directories. - // These entires don't have representation in our tree. - // FIXME: Proper calculation of entry count should be implemented. - if (m_CDREnd.numEntriesTotal != numFilesFound + numDirsFound) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "The number of parsed files does not match the declared number of entries in the central directory. The pak does not appear to be corrupt, but perhaps there are some duplicated or missing file entries, try to repair the file"); - } - } - - return true; -} - -ZipDir::CachePtr ZipDir::CacheFactory::MakeCache (const char* szFile) -{ - if (!Prepare()) - { - return CachePtr(); - } - - // initializes this object from the given tree, which is a convenient representation of the file tree - size_t nSizeRequired = m_treeFileEntries.GetSizeSerialized(); - size_t nSizeZipPath = 1; // we need to remember the terminating 0 - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - nSizeZipPath += strlen(szFile); - } - // allocate and initialize the memory that'll be the root now - size_t nCacheInstanceSize = sizeof(Cache) + nSizeRequired + nSizeZipPath; - - Cache* pCacheInstance = (Cache*)malloc(nCacheInstanceSize); // Do not use pools for this allocation - pCacheInstance->Construct(m_f, nSizeRequired, m_encryptionKey); - CachePtr cache = pCacheInstance; - m_f = NULL; // we don't own the file anymore - it's in possession of the cache instance - - // try to serialize into the memory -#if !defined(NDEBUG) - size_t nSizeSerialized = -#endif - m_treeFileEntries.Serialize (cache->GetRoot()); - - assert (nSizeSerialized == nSizeRequired); - - char* pZipPath = ((char*)(pCacheInstance + 1)) + nSizeRequired; - - if (!(m_nFlags & FLAGS_DONT_MEMORIZE_ZIP_PATH)) - { - memcpy (pZipPath, szFile, nSizeZipPath); - } - else - { - pZipPath[0] = '\0'; - } - - Clear(); - - return cache; -} - -void ZipDir::CacheFactory::Clear() -{ - if (m_f) - { - fclose (m_f); - } - m_nCDREndPos = 0; - memset (&m_CDREnd, 0, sizeof(m_CDREnd)); - m_mapFileEntries.clear(); - m_treeFileEntries.Clear(); - m_bEncryptedHeaders = false; -} - - -////////////////////////////////////////////////////////////////////////// -// searches for CDREnd record in the given file -bool ZipDir::CacheFactory::FindCDREnd() -{ - // this buffer will be used to find the CDR End record - // the additional bytes are required to store the potential tail of the CDREnd structure - // when moving the window to the next position in the file - char pReservedBuffer[g_nCDRSearchWindowSize + sizeof(ZipFile::CDREnd) - 1]; - - Seek (0, SEEK_END); - unsigned long nFileSize = Tell(); - - if (nFileSize < sizeof(ZipFile::CDREnd)) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_CDR, "The file is too small, it doesn't even contain the CDREnd structure. Please check and delete the file. Truncated files are not deleted automatically"); - return false; - } - - // this will point to the place where the buffer was loaded - unsigned int nOldBufPos = nFileSize; - // start scanning well before the end of the file to avoid reading beyond the end - - unsigned int nScanPos = nFileSize - sizeof(ZipFile::CDREnd); - - m_CDREnd.lSignature = 0; // invalid signature as the flag of not-found CDR End structure - while (true) - { - unsigned int nNewBufPos; // the new buf pos - char* pWindow = pReservedBuffer; // the window pointer into which data will be read (takes into account the possible tail-of-CDREnd) - if (nOldBufPos <= g_nCDRSearchWindowSize) - { - // the old buffer position doesn't let us read the full search window size - // therefore the new buffer pos will be 0 (instead of negative beyond the start of the file) - // and the window pointer will be closer tot he end of the buffer because the end of the buffer - // contains the data from the previous iteration (possibly) - nNewBufPos = 0; - pWindow = pReservedBuffer + g_nCDRSearchWindowSize - (nOldBufPos - nNewBufPos); - } - else - { - nNewBufPos = nOldBufPos - g_nCDRSearchWindowSize; - assert (nNewBufPos > 0); - } - - // since dealing with 32bit unsigned, check that filesize is bigger than - // CDREnd plus comment before the following check occurs. - if (nFileSize > (sizeof(ZipFile::CDREnd) + 0xFFFF)) - { - // if the new buffer pos is beyond 64k limit for the comment size - if (nNewBufPos < (unsigned int)(nFileSize - sizeof(ZipFile::CDREnd) - 0xFFFF)) - { - nNewBufPos = nFileSize - sizeof(ZipFile::CDREnd) - 0xFFFF; - } - } - - // if there's nothing to search - if (nNewBufPos >= nOldBufPos) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_CDR, "Cannot find Central Directory Record in pak. This is either not a pak file, or a pak file without Central Directory. It does not mean that the data is permanently lost, but it may be severely damaged. Please repair the file with external tools, there may be enough information left to recover the file completely"); // we didn't find anything - return false; - } - - // seek to the start of the new window and read it - Seek (nNewBufPos); - Read (pWindow, nOldBufPos - nNewBufPos); - - while (nScanPos >= nNewBufPos) - { - ZipFile::CDREnd* pEnd = (ZipFile::CDREnd*)(pWindow + nScanPos - nNewBufPos); - if (pEnd->lSignature == pEnd->SIGNATURE) - { - if (pEnd->nCommentLength == nFileSize - nScanPos - sizeof(ZipFile::CDREnd)) - { - // the comment length is exactly what we expected - m_CDREnd = *pEnd; - m_nCDREndPos = nScanPos; - break; - } - else - { - THROW_ZIPDIR_ERROR (ZD_ERROR_DATA_IS_CORRUPT, "Central Directory Record is followed by a comment of inconsistent length. This might be a minor misconsistency, please try to repair the file. However, it is dangerous to open the file because I will have to guess some structure offsets, which can lead to permanent unrecoverable damage of the archive content"); - return false; - } - } - if (nScanPos == 0) - { - break; - } - --nScanPos; - } - - if (m_CDREnd.lSignature == m_CDREnd.SIGNATURE) - { - return true; // we've found it - } - - nOldBufPos = nNewBufPos; - memmove (pReservedBuffer + g_nCDRSearchWindowSize, pWindow, sizeof(ZipFile::CDREnd) - 1); - } - THROW_ZIPDIR_ERROR (ZD_ERROR_UNEXPECTED, "The program flow may not have possibly lead here. This error is unexplainable"); // we shouldn't be here - return false; -} - - -////////////////////////////////////////////////////////////////////////// -// uses the found CDREnd to scan the CDR and probably the Zip file itself -// builds up the m_mapFileEntries -bool ZipDir::CacheFactory::BuildFileEntryMap() -{ - Seek (m_CDREnd.lCDROffset); - - if (m_CDREnd.lCDRSize == 0) - { - return true; - } - - DynArray& pBuffer = m_CDR_buffer; // Use persistent buffer. - - pBuffer.resize(m_CDREnd.lCDRSize + 1); // Allocate one more because we use this memory as a strings pool. - - if (pBuffer.empty()) // couldn't allocate enough memory for temporary copy of CDR - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_MEMORY, "Not enough memory to cache Central Directory record for fast initialization. This error may not happen on non-console systems"); - return false; - } - - // Calculate buffer size for unified filenames - const size_t headersSize = sizeof(ZipFile::CDRFileHeader) * m_CDREnd.numEntriesTotal; - const size_t terminatingZeros = m_CDREnd.numEntriesTotal; - if (headersSize > m_CDREnd.lCDRSize + terminatingZeros) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CORRUPTED_DATA, "Number of entries in Central Directory seems to be wrong"); - return false; - } - const size_t nameBufferSize = m_CDREnd.lCDRSize + terminatingZeros - headersSize; // numEntriesTotal for terminating zeroes - - // Allocate buffer for unified filenames - m_unifiedNameBuffer.resize(nameBufferSize); - if (m_unifiedNameBuffer.empty() && nameBufferSize != 0) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_NO_MEMORY, "Not enough memory to allocate unified names buffer"); - return false; - } - char* pUnifiedName = m_unifiedNameBuffer.empty() ? 0 : &m_unifiedNameBuffer[0]; - const char* const pUnifiedNameEnd = pUnifiedName + m_unifiedNameBuffer.size(); - - ReadHeaderData(&pBuffer[0], m_CDREnd.lCDRSize); - - // now we've read the complete CDR - parse it. - ZipFile::CDRFileHeader* pFile = (ZipFile::CDRFileHeader*)(&pBuffer[0]); - const char* const pEndOfData = &pBuffer[0] + m_CDREnd.lCDRSize; - const char* const pEndOfBuffer = &pBuffer[0] + pBuffer.size(); - char* pFileName; - - // check signature of first entry - if ((const char*)(pFile + 1) <= pEndOfData) - { - if (pFile->lSignature != pFile->SIGNATURE) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, m_bEncryptedHeaders - ? "Signature of CDR entry is corrupt. Wrong decryption key was used or archive is corrupt." - : "Signature of CDR entry is corrupt. Archive is corrupt."); - return false; - } - } - - while ((pFileName = (char*)(pFile + 1)) <= pEndOfData) - { - // Hacky way to use CDR memory block as a string pool. - pFile->lSignature = 0; // Force signature to always be 0 (First byte of signature maybe a zero termination of the previous file filename). - - if (pFile->nVersionNeeded > 20) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_UNSUPPORTED, "Reading file header with unsupported version (nVersionNeeded > 20)."); - return false; - } - //if (pFile->lSignature != pFile->SIGNATURE) // Timur, Dont compare signatures as signatue in memory can be overwritten by the code below - //break; - // the end of this file record - const char* pEndOfRecord = (pFileName + pFile->nFileNameLength + pFile->nExtraFieldLength + pFile->nFileCommentLength); - // if the record overlaps with the End Of CDR structure, something is wrong - if (pEndOfRecord > pEndOfData) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "Central Directory record is either corrupt, or truncated, or missing. Cannot read the archive directory"); - return false; - } - - ////////////////////////////////////////////////////////////////////////// - // Analyze advanced section. - ////////////////////////////////////////////////////////////////////////// - SExtraZipFileData extra; - const char* pExtraField = (pFileName + pFile->nFileNameLength); - const char* pExtraEnd = pExtraField + pFile->nExtraFieldLength; - while (pExtraField < pExtraEnd) - { - const char* pAttrData = pExtraField + sizeof(ZipFile::ExtraFieldHeader); - ZipFile::ExtraFieldHeader& hdr = *(ZipFile::ExtraFieldHeader*)pExtraField; - switch (hdr.headerID) - { - case ZipFile::EXTRA_NTFS: - { - extra.nLastModifyTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader)); - //uint64 accTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader) + 8); - //uint64 crtTime = *(uint64*)(pAttrData + sizeof(ZipFile::ExtraNTFSHeader) + 16); - } - break; - } - pExtraField += sizeof(ZipFile::ExtraFieldHeader) + hdr.dataSize; - } - - bool bDirectory = false; - if (pFile->nFileNameLength > 0 && (pFileName[pFile->nFileNameLength - 1] == '/' || pFileName[pFile->nFileNameLength - 1] == '\\')) - { - bDirectory = true; - } - - if (!bDirectory) - { - const size_t fileNameLen = pFile->nFileNameLength; - pFileName[fileNameLen] = 0; // Not standard!, may overwrite signature of the next memory record data in zip. - - // generate unified name - if (pFileName + fileNameLen + 1 > pEndOfBuffer || - pUnifiedName + fileNameLen + 1 > pUnifiedNameEnd) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CORRUPTED_DATA, "Filename length exceeds estimated size. Try to repair the archive."); - return false; - } - - for (int i = 0; i < fileNameLen + 1; i++) - { - pUnifiedName[i] = ::tolower(pFileName[i]); - } - - // put this entry into the map - AddFileEntry (pFileName, pUnifiedName, pFile, extra); - - pUnifiedName += fileNameLen + 1; - } - - // move to the next file - pFile = (ZipFile::CDRFileHeader*)pEndOfRecord; - } - - // finished reading CDR - return true; -} - - -////////////////////////////////////////////////////////////////////////// -// give the CDR File Header entry, reads the local file header to validate -// and determine where the actual file lies -void ZipDir::CacheFactory::AddFileEntry (char* strFilePath, char* strUnifiedPath, const ZipFile::CDRFileHeader* pFileHeader, const SExtraZipFileData& extra) -{ - if (pFileHeader->lLocalHeaderOffset > m_CDREnd.lCDROffset) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_CDR_IS_CORRUPT, "Central Directory contains file descriptors pointing outside the archive file boundaries. The archive file is either truncated or damaged. Please try to repair the file"); // the file offset is beyond the CDR: impossible - return; - } - - if (pFileHeader->nMethod == ZipFile::METHOD_STORE && pFileHeader->desc.lSizeUncompressed != pFileHeader->desc.lSizeCompressed) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_VALIDATION_FAILED, "File with STORE compression method declares its compressed size not matching its uncompressed size. File descriptor is inconsistent, archive content may be damaged, please try to repair the archive"); - return; - } - - FileEntry fileEntry (*pFileHeader, extra); - - if ((m_bEncryptedHeaders || m_nInitMethod >= ZD_INIT_FULL) && pFileHeader->desc.lSizeCompressed) - { - InitDataOffset(fileEntry, pFileHeader); - } - - if (m_bBuildFileEntryMap) - { - m_mapFileEntries.insert (FileEntryMap::value_type(strFilePath, fileEntry)); - } - - if (m_bBuildFileEntryTree) - { - m_treeFileEntries.Add(strFilePath, strUnifiedPath, fileEntry); - } -} - - -////////////////////////////////////////////////////////////////////////// -// initializes the actual data offset in the file in the fileEntry structure -// searches to the local file header, reads it and calculates the actual offset in the file -void ZipDir::CacheFactory::InitDataOffset (FileEntry& fileEntry, const ZipFile::CDRFileHeader* pFileHeader) -{ - // make sure it's the same file and the fileEntry structure is properly initialized - assert (fileEntry.nFileHeaderOffset == pFileHeader->lLocalHeaderOffset); - - /* - // without validation, it would be like this: - ErrorEnum nError = Refresh(&fileEntry); - if (nError != ZD_ERROR_SUCCESS) - THROW_ZIPDIR_ERROR(nError,"Cannot refresh file entry. Probably corrupted file header inside zip file"); - */ - - - if (m_bEncryptedHeaders) - { - // ignore local header - fileEntry.nFileDataOffset = pFileHeader->lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + pFileHeader->nFileNameLength + pFileHeader->nExtraFieldLength; - } - else - { - Seek(pFileHeader->lLocalHeaderOffset); - // read the local file header and the name (for validation) into the buffer - DynArraypBuffer; - unsigned nBufferLength = sizeof(ZipFile::LocalFileHeader) + pFileHeader->nFileNameLength; - pBuffer.resize(nBufferLength); - Read (&pBuffer[0], nBufferLength); - - // validate the local file header (compare with the CDR file header - they should contain basically the same information) - const ZipFile::LocalFileHeader* pLocalFileHeader = (const ZipFile::LocalFileHeader*)&pBuffer[0]; - if (pFileHeader->desc != pLocalFileHeader->desc - || pFileHeader->nMethod != pLocalFileHeader->nMethod - || pFileHeader->nFileNameLength != pLocalFileHeader->nFileNameLength - // for a tough validation, we can compare the timestamps of the local and central directory entries - // but we won't do that for backward compatibility with ZipDir - //|| pFileHeader->nLastModDate != pLocalFileHeader->nLastModDate - //|| pFileHeader->nLastModTime != pLocalFileHeader->nLastModTime - ) - { - THROW_ZIPDIR_ERROR (ZD_ERROR_VALIDATION_FAILED, "The local file header descriptor doesn't match the basic parameters declared in the global file header in the file. The archive content is misconsistent and may be damaged. Please try to repair the archive"); - return; - } - - // now compare the local file name with the one recorded in CDR: they must match. - if (azmemicmp((const char*)&pBuffer[sizeof(ZipFile::LocalFileHeader)], (const char*)pFileHeader + 1, pFileHeader->nFileNameLength)) - { - // either file name, or the extra field do not match - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The local file header contains file name which does not match the file name of the global file header. The archive content is misconsistent with its directory. Please repair the archive"); - return; - } - - fileEntry.nFileDataOffset = pFileHeader->lLocalHeaderOffset + sizeof(ZipFile::LocalFileHeader) + pLocalFileHeader->nFileNameLength + pLocalFileHeader->nExtraFieldLength; - } - - if (fileEntry.nFileDataOffset >= m_nCDREndPos) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_VALIDATION_FAILED, "The global file header declares the file which crosses the boundaries of the archive. The archive is either corrupted or truncated, please try to repair it"); - return; - } - - if (m_nInitMethod >= ZD_INIT_VALIDATE) - { - Validate (fileEntry); - } -} - -////////////////////////////////////////////////////////////////////////// -// reads the file pointed by the given header and entry (they must be coherent) -// and decompresses it; then calculates and validates its CRC32 -void ZipDir::CacheFactory::Validate(const FileEntry& fileEntry) -{ - DynArray pBuffer; - // validate the file contents - // allocate memory for both the compressed data and uncompressed data - pBuffer.resize(fileEntry.desc.lSizeCompressed + fileEntry.desc.lSizeUncompressed); - char* pUncompressed = &pBuffer[fileEntry.desc.lSizeCompressed]; - char* pCompressed = &pBuffer[0]; - - assert (fileEntry.nFileDataOffset != FileEntry::INVALID_DATA_OFFSET); - Seek(fileEntry.nFileDataOffset); - - Read(pCompressed, fileEntry.desc.lSizeCompressed); - - if (fileEntry.nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt(pCompressed, fileEntry.desc.lSizeCompressed, m_encryptionKey); - } - - unsigned long nDestSize = fileEntry.desc.lSizeUncompressed; - int nError = Z_OK; - if (fileEntry.nMethod) - { - nError = ZipRawUncompress (pUncompressed, &nDestSize, pCompressed, fileEntry.desc.lSizeCompressed); - } - else - { - assert (fileEntry.desc.lSizeCompressed == fileEntry.desc.lSizeUncompressed); - memcpy (pUncompressed, pCompressed, fileEntry.desc.lSizeUncompressed); - } - switch (nError) - { - case Z_OK: - break; - case Z_MEM_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_NO_MEMORY, "ZLib reported out-of-memory error"); - return; - case Z_BUF_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_CORRUPTED_DATA, "ZLib reported compressed stream buffer error"); - return; - case Z_DATA_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_CORRUPTED_DATA, "ZLib reported compressed stream data error"); - return; - default: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_FAILED, "ZLib reported an unexpected unknown error"); - return; - } - - if (nDestSize != fileEntry.desc.lSizeUncompressed) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_CORRUPTED_DATA, "Uncompressed stream doesn't match the size of uncompressed file stored in the archive file headers"); - return; - } - - uLong uCRC32 = crc32(0L, Z_NULL, 0); - uCRC32 = crc32(uCRC32, (Bytef*)pUncompressed, nDestSize); - if (uCRC32 != fileEntry.desc.lCRC32) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_CRC32_CHECK, "Uncompressed stream CRC32 check failed"); - return; - } -} - - -////////////////////////////////////////////////////////////////////////// -// extracts the file path from the file header with subsequent information -// may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) -// it's the responsibility of the caller to ensure that the file name is in readable valid memory -char* ZipDir::CacheFactory::GetFilePath (const char* pFileName, ZipFile::ushort nFileNameLength) -{ - static char strResult[_MAX_PATH]; - assert(nFileNameLength < _MAX_PATH); - memcpy(strResult, pFileName, nFileNameLength); - strResult[nFileNameLength] = 0; - for (int i = 0; i < nFileNameLength; i++) - { - strResult[i] = ::tolower(strResult[i]); - } - - return strResult; -} - -// seeks in the file relative to the starting position -void ZipDir::CacheFactory::Seek (ZipFile::ulong nPos, int nOrigin) // throw -{ - if (AZ_TRAIT_CRYCOMMONTOOLS_FSEEK(m_f, nPos, nOrigin)) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fseek() to the new position in the file. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); - return; - } -} - -unsigned long ZipDir::CacheFactory::Tell () // throw -{ - AZ::s64 nPos = AZ_TRAIT_CRYCOMMONTOOLS_FTELL(m_f); - if (nPos == -1) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot ftell() position in the archive. This is unexpected error and should not happen under any circumstances. Perhaps some network or disk failure error has caused this"); - return 0; - } - return (unsigned long)nPos; -} - -void ZipDir::CacheFactory::Read (void* pDest, unsigned nSize) // throw -{ - if (fread (pDest, nSize, 1, m_f) != 1) - { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fread() a portion of data from archive"); - } -} - -void ZipDir::CacheFactory::ReadHeaderData (void* pDest, unsigned nSize) // throw -{ - Read(pDest, nSize); - - if (m_bEncryptedHeaders) - { - ZipDir::Decrypt((char*)pDest, nSize, m_encryptionKey); - } -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h deleted file mode 100644 index caf947e1af..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheFactory.h +++ /dev/null @@ -1,143 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// This is the class that can read the directory from Zip file, -// and store it into the directory cache - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H -#pragma once - - -namespace ZipDir -{ - class CacheRW; - TYPEDEF_AUTOPTR(CacheRW); - typedef CacheRW_AutoPtr CacheRWPtr; - - // an instance of this class is temporarily created on stack to initialize the CZipFile instance - class CacheFactory - { - public: - enum - { - // open RW cache in read-only mode - FLAGS_READ_ONLY = 1, - // do not compact RW-cached zip upon destruction - FLAGS_DONT_COMPACT = 1 << 1, - // if this is set, then the zip paths won't be memorized in the cache objects - FLAGS_DONT_MEMORIZE_ZIP_PATH = 1 << 2, - // if this is set, the archive will be created anew (the existing file will be overwritten) - FLAGS_CREATE_NEW = 1 << 3 - }; - - // initializes the internal structures - // nFlags can have FLAGS_READ_ONLY flag, in this case the object will be opened only for reading - CacheFactory (InitMethodEnum nInitMethod, unsigned nFlags = 0); - ~CacheFactory(); - - // the new function creates a new cache - CachePtr New(const char* szFileName, const uint32 decryptionKey[4]);// throw (ErrorEnum); - - CacheRWPtr NewRW(const char* szFileName, size_t fileAlignment, bool encrypted, const uint32 encryptionKey[4]); - - protected: - // reads the zip file into the file entry tree. - bool ReadCacheRW (CacheRW& rwCache); - - // creates from the m_f file - // reserves the given number of bytes for future expansion of the object - // upon return, pReserve contains the actual number of bytes that were allocated (more might have been allocated) - CachePtr MakeCache (const char* szFile); - - // this sets the window size of the blocks of data read from the end of the file to find the Central Directory Record - // since normally there are no - enum - { - g_nCDRSearchWindowSize = 0x100 - }; - - void Clear(); - - // reads everything and prepares the maps - bool Prepare(); - - // searches for CDREnd record in the given file - bool FindCDREnd();// throw(ErrorEnum); - - // uses the found CDREnd to scan the CDR and probably the Zip file itself - // builds up the m_mapFileEntries - bool BuildFileEntryMap();// throw (ErrorEnum); - - // give the CDR File Header entry, reads the local file header to validate and determine where - // the actual file lies - // This function can actually modify strFilePath and strUnifiedPath variables, make sure you use copies of real paths. - void AddFileEntry (char* strFilePath, char* strUnifiedPath, const ZipFile::CDRFileHeader* pFileHeader, const SExtraZipFileData& extra);// throw (ErrorEnum); - - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const ZipFile::CDRFileHeader* pFileHeader) - { - return GetFilePath((const char*)(pFileHeader + 1), pFileHeader->nFileNameLength); - } - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const ZipFile::LocalFileHeader* pFileHeader) - { - return GetFilePath((const char*)(pFileHeader + 1), pFileHeader->nFileNameLength); - } - // extracts the file path from the file header with subsequent information - // may, or may not, put all letters to lower-case (depending on whether the system is to be case-sensitive or not) - // it's the responsibility of the caller to ensure that the file name is in readable valid memory - char* GetFilePath (const char* pFileName, ZipFile::ushort nFileNameLength); - - // validates (if the init method has the corresponding value) the given file/header - void Validate(const FileEntry& fileEntry); - - // initializes the actual data offset in the file in the fileEntry structure - // searches to the local file header, reads it and calculates the actual offset in the file - void InitDataOffset (FileEntry& fileEntry, const ZipFile::CDRFileHeader* pFileHeader); - - // seeks in the file relative to the starting position - void Seek (ZipFile::ulong nPos, int nOrigin = SEEK_SET); // throw - unsigned long Tell (); // throw - void Read (void* pDest, unsigned nSize); // throw - void ReadHeaderData (void* pDest, unsigned nSize);// throw - protected: - - FILE* m_f; - InitMethodEnum m_nInitMethod; - unsigned m_nFlags; - ZipFile::CDREnd m_CDREnd; - - unsigned m_nCDREndPos; // position of the CDR End in the file - - // Map: Relative file path => file entry info - typedef std::map FileEntryMap; - FileEntryMap m_mapFileEntries; - - FileEntryTree m_treeFileEntries; - - DynArray m_CDR_buffer; - DynArray m_unifiedNameBuffer; - - EncryptionKey m_encryptionKey; - bool m_bEncryptedHeaders; - bool m_bBuildFileEntryMap; - bool m_bBuildFileEntryTree; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRCACHEFACTORY_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp deleted file mode 100644 index 6e47aec5d4..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.cpp +++ /dev/null @@ -1,2100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include -#include "Util.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirList.h" -#include "ZipDirCache.h" -#include "ZipDirCacheRW.h" -#include "ZipDirCacheFactory.h" -#include "ZipDirFindRW.h" - -#include "ThreadUtils.h" - -#include // declaration of Z_OK for ZipRawDecompress -#include -#include -#include -#include -#include -#include -#include -#include -#include - -enum PackFileStatus -{ - PACKFILE_COMPRESSED, - - PACKFILE_ADDED, - PACKFILE_UPTODATE, - PACKFILE_SKIPPED, - PACKFILE_MISSING, - PACKFILE_FAILED -}; - -enum PackFileCompressionPolicy -{ - PACKFILE_USE_REQUESTED_COMPRESSOR, - PACKFILE_USE_FASTEST_DECOMPRESSING_CODEC -}; - -class PackFilePool; -struct PackFileBatch -{ - PackFilePool* pool; - - int zipMaxSize; - int sourceMinSize; - int sourceMaxSize; - int compressionMethod; - int compressionLevel; - - PackFileBatch() - : pool(0) - , sourceMinSize(0) - , sourceMaxSize(0) - , zipMaxSize(0) - , compressionMethod(0) - , compressionLevel(0) - { - } -}; - -class PackFilePool; -struct PackFileJob -{ - int index; - int key; - PackFileBatch* batch; - const char* relativePathSrc; - const char* realFilename; - - unsigned int existingCRC; - - void* compressedData; - unsigned long compressedSize; - unsigned long compressedSizePreviously; - - void* uncompressedData; - unsigned long uncompressedSize; - unsigned long uncompressedSizePreviously; - - int64 modTime; - ZipDir::ErrorEnum zdError; - PackFileStatus status; - PackFileCompressionPolicy compressionPolicy; - - PackFileJob() - : index(0) - , key(0) - , batch(0) - , realFilename(0) - , relativePathSrc(0) - , existingCRC(0) - , compressedData(0) - , compressedSize(0) - , compressedSizePreviously(0) - , uncompressedData(0) - , uncompressedSize(0) - , uncompressedSizePreviously(0) - , modTime(0) - , zdError(ZipDir::ZD_ERROR_NOT_IMPLEMENTED) - , status(PACKFILE_FAILED) - , compressionPolicy(PACKFILE_USE_REQUESTED_COMPRESSOR) - { - } - - void DetachUncompressedData() - { - if (uncompressedData && uncompressedData == compressedData) - { - compressedData = 0; - compressedSize = 0; - } - - uncompressedData = 0; - uncompressedSize = 0; - } - - ~PackFileJob() - { - if (compressedData && compressedData != uncompressedData) - { - azfree(compressedData); - compressedData = 0; - } - - if (uncompressedData) - { - azfree(uncompressedData); - uncompressedData = 0; - } - } -}; - - -// --------------------------------------------------------------------------- -static void PackFileFromDisc(PackFileJob* job); -class PackFilePool -{ -public: - PackFilePool(int numFiles, size_t memoryLimit) - : m_pool(false) - , m_skip(false) - , m_awaitedFile(0) - , m_memoryLimit(memoryLimit) - , m_allocatedMemory(0) - { - m_files.reserve(numFiles); - } - - ~PackFilePool() - { - } - - void Submit(int key, const PackFileJob& job) - { - PackFileJob* newJob = new PackFileJob(job); - - // index in queue, and custom key for identification - newJob->index = int(m_files.size()); - newJob->key = key; - - m_files.push_back(newJob); - } - - PackFileJob* WaitForFile(int index) - { - while (true) - { - { - AZStd::lock_guard lock(m_filesLock); - m_awaitedFile = index; - if (size_t(index) >= m_files.size()) - { - return 0; - } - if (m_files[index]) - { - return m_files[index]; - } - } - Sleep(0); - } - - assert(0); - return 0; - } - - void Start(unsigned numExtraThreads) - { - if (numExtraThreads == 0) - { - for (PackFileJob* job : m_files) - { - PackFileFromDisc(job); - } - } - else - { - for (size_t i = 0; i < m_files.size(); ++i) - { - PackFileJob* job = m_files[i]; - m_files[i] = 0; - m_pool.Submit(&ProcessFile, job); - } - - m_pool.Start(numExtraThreads); - } - } - - size_t GetJobCount() const - { - return m_files.size(); - } - - void SkipPendingFiles() - { - m_skip = true; - } - - void ReleaseFile(int index) - { - assert(m_files[index] != 0); - if (m_files[index]) - { - if (m_memoryLimit != 0) - { - AZStd::lock_guard lock(m_filesLock); - - m_allocatedMemory -= m_files[index]->uncompressedSize; - m_allocatedMemory -= m_files[index]->compressedSize; - } - - delete m_files[index]; - m_files[index] = 0; - } - } - -private: - - // called from non-main thread - static void ProcessFile(PackFileJob* job) - { - PackFilePool* self = job->batch->pool; - - if (!self->m_skip) - { - if (self->m_memoryLimit != 0) - { - while (true) - { - size_t allocatedMemory = 0; - int awaitedFile = 0; - { - AZStd::lock_guard lock(self->m_filesLock); - allocatedMemory = self->m_allocatedMemory; - awaitedFile = self->m_awaitedFile; - } - - if (allocatedMemory > self->m_memoryLimit && job->index > awaitedFile + 1) - { - Sleep(10); // give time to main thread to write data to file - } - else - { - break; - } - } - } - - PackFileFromDisc(job); - } - - self->FileCompleted(job); - } - - // called from non-main thread - void FileCompleted(PackFileJob* job) - { - AZStd::lock_guard lock(m_filesLock); - - assert(job); - assert(job->index < m_files.size()); - assert(m_files[job->index] == 0); - m_files[job->index] = job; - - if (m_memoryLimit != 0) - { - m_allocatedMemory += job->uncompressedSize; - m_allocatedMemory += job->compressedSize; - } - } - - size_t m_memoryLimit; - - AZStd::mutex m_filesLock; - std::vector m_files; - int m_awaitedFile; - size_t m_allocatedMemory; - bool m_skip; - - ThreadUtils::SimpleThreadPool m_pool; -}; - -////////////////////////////////////////////////////////////////////////// -static size_t AlignTo(size_t offset, size_t alignment) -{ - const size_t remainder = offset % alignment; - return remainder ? offset + alignment - remainder : offset; -} -////////////////////////////////////////////////////////////////////////// -// Calculates new offset of the header to make sure that following data are -// aligned properly -static size_t CalculateAlignedHeaderOffset(const char* fileName, size_t currentOffset, size_t alignment) -{ - // Since file should start from header - if (currentOffset == 0) - { - return 0; - } - - // Local header is followed by filename - const size_t totalHeaderSize = sizeof(ZipFile::LocalFileHeader) + strlen(fileName); - - // Align end of the header - const size_t dataOffset = AlignTo(currentOffset + totalHeaderSize, alignment); - - return dataOffset - totalHeaderSize; -} - -////////////////////////////////////////////////////////////////////////// -ZipDir::CacheRW::CacheRW(bool encryptHeaders, const EncryptionKey& encryptionKey) - : m_pFile (NULL) - , m_nFlags (0) - , m_lCDROffset (0) - , m_fileAlignment (1) - , m_bEncryptedHeaders(encryptHeaders) - , m_bHeadersEncryptedOnClose(encryptHeaders) - , m_encryptionKey(encryptionKey) -{ - m_nRefCount = 0; -} -////////////////////////////////////////////////////////////////////////// -ZipDir::CacheRW::~CacheRW() -{ - Close(); -} -////////////////////////////////////////////////////////////////////////// -void ZipDir::CacheRW::AddRef() -{ - ++m_nRefCount; -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::CacheRW::Release() -{ - if (--m_nRefCount <= 0) - { - delete this; - } -} - -void ZipDir::CacheRW::Close() -{ - if (m_pFile) - { - if (!(m_nFlags & FLAGS_READ_ONLY)) - { - if ((m_nFlags & FLAGS_UNCOMPACTED) && !(m_nFlags & FLAGS_DONT_COMPACT)) - { - if (!RelinkZip()) - { - WriteCDR(); - } - } - else - if (m_nFlags & FLAGS_CDR_DIRTY) - { - WriteCDR(); - } - } - - if (m_pFile) // RelinkZip() might have closed the file - { - fclose (m_pFile); - } - - m_pFile = NULL; - } - m_treeDir.Clear(); -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::UnifyPath(char* const str, const char* pPath) -{ - assert(str); - const char* src = pPath; - char* trg = str; - while (*src) - { - if (*src != '/') - { - *trg++ = ::tolower(*src++); - } - else - { - *trg++ = '\\'; - src++; - } - } - *trg = 0; - return str; -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::ToUnixPath(char* const str, const char* pPath) -{ - assert(str); - const char* src = pPath; - char* trg = str; - while (*src) - { - if (*src != '/') - { - *trg++ = *src++; - } - else - { - *trg++ = '\\'; - src++; - } - } - *trg = 0; - return str; -} - -////////////////////////////////////////////////////////////////////////// -char* ZipDir::CacheRW::AllocPath(const char* pPath) -{ - char str[_MAX_PATH]; - char* temp = ToUnixPath(str, pPath); - temp = m_tempStringPool.Append(temp, strlen(temp)); - return temp; -} - -static bool UseZlibForFileType(const char* filename) -{ - AZStd::string f(filename); - - //some files types are forced to use zlib - bool found = AzFramework::StringFunc::Path::IsExtension(filename, ".dds") || f.find("cover.ctc") != string::npos || AzFramework::StringFunc::Path::IsExtension(filename, ".uicanvas"); - - return found; -} - -#ifdef AZ_DEBUG_BUILD -static const char* CodecAsString(CompressionCodec::Codec codec) -{ - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - return "ZLIB"; - case CompressionCodec::Codec::ZSTD: - return "ZSTD"; - case CompressionCodec::Codec::LZ4: - return "LZ4"; - } - return "ERROR"; -} -#endif - -static bool CompressData(PackFileJob *job) -{ - bool bUseZlib = UseZlibForFileType(job->relativePathSrc) || (job->compressionPolicy == PACKFILE_USE_REQUESTED_COMPRESSOR); - - bool compressionSuccessful = true; - - if (bUseZlib) - { - job->compressedSize = ZipDir::GetCompressedSizeEstimate(job->uncompressedSize,CompressionCodec::Codec::ZLIB); - job->compressedData = azmalloc(job->compressedSize); - int error = ZipDir::ZipRawCompress(job->uncompressedData, &job->compressedSize, job->compressedData, job->uncompressedSize, job->batch->compressionLevel); - if (error == Z_OK) - { - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - } - else - { - compressionSuccessful = false; - } - } - else - { - unsigned long compressedSize[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - void* compressedData[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - std::chrono::milliseconds decompressionTime[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - bool compressionCodecWasSuccessful[static_cast(CompressionCodec::Codec::NUM_CODECS)]; - - std::chrono::time_point start; - - //do compression - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - unsigned int index = static_cast(codec); - compressedSize[index] = ZipDir::GetCompressedSizeEstimate(job->uncompressedSize, codec); - compressedData[index] = azmalloc(compressedSize[index]); - AZStd::unique_ptr tempBuffer; - unsigned long tempSize = 0; - - //some files decompress so fast they are beyond our ability to measure so we need to do it a few times to get a reading - int numTimesToDecompress = 1 + ZipDir::TARGET_MIN_TEST_COMPRESS_BYTES / job->uncompressedSize; - - auto testDecompressionTime = [&tempSize, job, &tempBuffer, &start, &compressionCodecWasSuccessful, index, numTimesToDecompress, &compressedData, &compressedSize, &decompressionTime]() { - tempSize = job->uncompressedSize; - tempBuffer = AZStd::make_unique(tempSize); - start = std::chrono::high_resolution_clock::now(); - - //start by assuming the decompression test is never going to result in an error - compressionCodecWasSuccessful[index] = true; - - for (int i = 0; i < numTimesToDecompress; i++) - { - int zerror = ZipDir::ZipRawUncompress(tempBuffer.get(), &tempSize, compressedData[index], compressedSize[index]); - if (zerror != Z_OK) - { - compressionCodecWasSuccessful[index] = false; - break; - } - } - decompressionTime[index] = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - start); - }; - - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - if (ZipDir::ZipRawCompress(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, job->batch->compressionLevel) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - break; - - case CompressionCodec::Codec::ZSTD: - if (ZipDir::ZipRawCompressZSTD(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, 1) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - break; - - case CompressionCodec::Codec::LZ4: - if (ZipDir::ZipRawCompressLZ4(job->uncompressedData, &compressedSize[index], compressedData[index], job->uncompressedSize, job->batch->compressionLevel) == Z_OK) - { - testDecompressionTime(); - } - else - { - compressionCodecWasSuccessful[index] = false; - } - - break; - - default: - break; - } - } - - //check decompression speed - int bestTimeIndex = -1; - int numberOfSuccessfulCodecs = 0; - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - int index = static_cast(codec); - if (compressionCodecWasSuccessful[index]) - { - numberOfSuccessfulCodecs++; - if (bestTimeIndex == -1) - { - bestTimeIndex = index; - continue; - } - if ((decompressionTime[index] < decompressionTime[bestTimeIndex])) - { - bestTimeIndex = index; - } - } - } - - if (!numberOfSuccessfulCodecs) - { - AZ_Error("ZipDirCacheRW", false, "None of the available codecs were able to compress the file: %s", job->relativePathSrc); - compressionSuccessful = false; - } - else - { -#ifdef AZ_DEBUG_BUILD - AZ_Printf("ZipDirCacheRW", "Winner for %s is %s with: %d ms ", job->realFilename, CodecAsString(static_cast(bestTimeIndex)), decompressionTime[bestTimeIndex]); -#endif - } - - //get rid of losing data - for (CompressionCodec::Codec codec : CompressionCodec::s_AllCodecs) - { - int index = static_cast(codec); - if (index != bestTimeIndex) - { - azfree(compressedData[index]); - compressedData[index] = nullptr; - } - } - - if (compressionSuccessful) - { - job->compressedSize = compressedSize[bestTimeIndex]; - job->compressedData = compressedData[bestTimeIndex]; - } - } - - //if there was a problem with the compression so just store the file - if (!compressionSuccessful) - { - azfree(job->compressedData); - job->compressedData = job->uncompressedData; - job->compressedSize = job->uncompressedSize; - } - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return true; -} - -static void PackFileFromMemory(PackFileJob* job) -{ - if (job->existingCRC != 0) - { - unsigned int crcCode = (unsigned int)crc32(0, (unsigned char*)job->uncompressedData, job->uncompressedSize); - if (crcCode == job->existingCRC) - { - job->compressedData = 0; - job->compressedSize = 0; - job->status = PACKFILE_UPTODATE; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - // This file with same data already in pak, skip it. - return; - } - } - - switch (job->batch->compressionMethod) - { - case ZipFile::METHOD_DEFLATE_AND_ENCRYPT: - case ZipFile::METHOD_DEFLATE: - { - // allocate memory for compression. Min is nSize * 1.001 + 12 - if (job->uncompressedSize > 0) - { - CompressData(job); - } - else - { - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - - job->compressedSize = 0; - job->compressedData = 0; - } - break; - } - case ZipFile::METHOD_STORE: - job->compressedData = job->uncompressedData; - job->compressedSize = job->uncompressedSize; - job->status = PACKFILE_COMPRESSED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - break; - - default: - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_UNSUPPORTED; - break; - } -} - -bool ZipDir::CacheRW::WriteCompressedData(const char* data, size_t size, bool encrypt, FILE* file) -{ - if (size <= 0) - { - return true; - } - - std::vector buffer; - if (encrypt) - { - buffer.resize(size); - memcpy(&buffer[0], data, size); - ZipDir::Encrypt(&buffer[0], size, m_encryptionKey); - data = &buffer[0]; - } - - // Danny - writing a single large chunk (more than 6MB?) causes - // Windows fwrite to (silently?!) fail. So we're writing data - // in small chunks. - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, size_t(1024 * 1024)); - if (fwrite(data, sizeToWrite, 1, file) != 1) - { - return false; - } - data += sizeToWrite; - size -= sizeToWrite; - } - - return true; -} - -static bool WriteRandomData(FILE* file, size_t size) -{ - if (size <= 0) - { - return true; - } - - const size_t bufferSize = Util::getMin(size, size_t(1024 * 1024)); - std::vector buffer(bufferSize); - - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, bufferSize); - - for (size_t i = 0; i < sizeToWrite; ++i) - { - buffer[i] = rand() & 0xff; - } - - if (fwrite(&buffer[0], sizeToWrite, 1, file) != 1) - { - return false; - } - - size -= sizeToWrite; - } - - return true; -} - -bool ZipDir::CacheRW::WriteNullData(size_t size) -{ - if (size <= 0) - { - return true; - } - - const size_t bufferSize = Util::getMin(size, size_t(1024 * 1024)); - std::vector buffer(bufferSize, 0); - - while (size > 0) - { - const size_t sizeToWrite = Util::getMin(size, bufferSize); - - if (fwrite(&buffer[0], sizeToWrite, 1, m_pFile) != 1) - { - return false; - } - - size -= sizeToWrite; - } - - return true; -} - -void ZipDir::CacheRW::StorePackedFile(PackFileJob* job) -{ - if (job->batch->zipMaxSize > 0 && GetTotalFileSize() > job->batch->zipMaxSize) - { - job->status = PACKFILE_SKIPPED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return; - } - - job->status = PACKFILE_FAILED; - - char str[_MAX_PATH]; - char* relativePath = UnifyPath(str, job->relativePathSrc); - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(job->relativePathSrc), AllocPath(relativePath)); - - if (!pFileEntry) - { - job->zdError = ZipDir::ZD_ERROR_INVALID_PATH; - return; - } - - pFileEntry->OnNewFileData(job->uncompressedData, job->uncompressedSize, - job->compressedSize, job->batch->compressionMethod, false); - pFileEntry->SetFromFileTimeNTFS(job->modTime); - - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // the new CDR position, if the operation completes successfully - unsigned lNewCDROffset = m_lCDROffset; - - if (pFileEntry->IsInitialized()) - { - // this file entry is already allocated in CDR - - // check if the new compressed data fits into the old place - unsigned nFreeSpace = pFileEntry->nEOFOffset - pFileEntry->nFileHeaderOffset - (unsigned)sizeof(ZipFile::LocalFileHeader) - (unsigned)strlen(relativePath); - - if (nFreeSpace != job->compressedSize) - { - m_nFlags |= FLAGS_UNCOMPACTED; - } - - if (nFreeSpace >= job->compressedSize) - { - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - } - else - { - // we need to write the file anew - in place of current CDR - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(job->relativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - lNewCDROffset = pFileEntry->nEOFOffset; - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - } - } - else - { - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(job->relativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, job->relativePathSrc, m_bEncryptedHeaders); - if (e != ZipDir::ZD_ERROR_SUCCESS) - { - job->zdError = e; - return; - } - - lNewCDROffset = pFileEntry->nFileDataOffset + job->compressedSize; - - m_nFlags |= FLAGS_CDR_DIRTY; - } - - // now we have the fresh local header and data offset - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - job->zdError = ZD_ERROR_IO_FAILED; - return; - } - - const bool encrypt = pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - - if (!WriteCompressedData((char*)job->compressedData, job->compressedSize, encrypt, m_pFile)) - { - job->zdError = ZD_ERROR_IO_FAILED; - return; - } - - // since we wrote the file successfully, update the new CDR position - m_lCDROffset = lNewCDROffset; - pFileEntry.Commit(); - - job->status = PACKFILE_ADDED; - job->zdError = ZD_ERROR_SUCCESS; -} - -// Adds a new file to the zip or update an existing one -// adds a directory (creates several nested directories if needed) -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFile (const char* szRelativePathSrc, void* pUncompressed, unsigned nSize, - unsigned nCompressionMethod, int nCompressionLevel, int64 modTime) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - - PackFileBatch batch; - batch.compressionMethod = nCompressionMethod; - batch.compressionLevel = nCompressionLevel; - - PackFileJob job; - job.relativePathSrc = szRelativePathSrc; - job.modTime = modTime; - job.uncompressedData = pUncompressed; - job.uncompressedSize = nSize; - job.batch = &batch; - - // crc will be used to check if this file need to be updated at all - ZipDir::FileEntry* entry = FindFile(szRelativePath); - if (entry) - { - job.existingCRC = entry->desc.lCRC32; - } - - PackFileFromMemory(&job); - - switch (job.status) - { - case PACKFILE_SKIPPED: - case PACKFILE_MISSING: - case PACKFILE_FAILED: - return ZD_ERROR_IO_FAILED; - } - - StorePackedFile(&job); - job.DetachUncompressedData(); - return job.zdError; -} - -static FILETIME GetFileWriteTimeAndSize(uint64* fileSize, const char* filename) -{ - // Warning: FindFirstFile on NTFS may report file size that - // is not up-to-date with the actual file content. - // http://blogs.msdn.com/b/oldnewthing/archive/2011/12/26/10251026.aspx - - FILETIME fileTime; - -#if defined(AZ_PLATFORM_WINDOWS) - WIN32_FIND_DATAA FindFileData; - HANDLE hFind = FindFirstFileA(filename, &FindFileData); - - if (hFind == INVALID_HANDLE_VALUE) - { - fileTime.dwLowDateTime = 0; - fileTime.dwHighDateTime = 0; - if (fileSize) - { - *fileSize = 0; - } - } - else - { - fileTime.dwLowDateTime = FindFileData.ftLastWriteTime.dwLowDateTime; - fileTime.dwHighDateTime = FindFileData.ftLastWriteTime.dwHighDateTime; - if (fileSize) - { - *fileSize = (uint64(FindFileData.nFileSizeHigh) << 32) + FindFileData.nFileSizeLow; - } - FindClose(hFind); - } -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - //We cant use this implmentation for the windows version because ModificationTime - //returns the time filename was changed(ChangeTime) not last written into(LastWriteTime). - //If LocalFileIO ever adds support for LastWriteTime we can have a common implementation. - AZ::IO::LocalFileIO localFileIO; - AZ::u64 modTime = 0; - modTime = localFileIO.ModificationTime(filename); - if(modTime != 0) - { - fileTime.dwHighDateTime = modTime >> 32; - fileTime.dwLowDateTime = modTime & 0xFFFFFFFF; - if (fileSize) - { - localFileIO.Size(filename, *fileSize); - } - } -#else -#error Needs implmentation! -#endif - return fileTime; -} -static void PackFileFromDisc(PackFileJob* job) -{ - const FILETIME ft = GetFileWriteTimeAndSize(0, job->realFilename); - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - job->modTime = lt.QuadPart; - - FILE* f = nullptr; - azfopen(&f, job->realFilename, "rb"); - if (!f) - { - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_FILE_NOT_FOUND; - return; - } - - fseek(f, 0, SEEK_END); - size_t fileSize = (size_t)ftell(f); - - if ((fileSize < job->batch->sourceMinSize) || (job->batch->sourceMaxSize > 0 && fileSize > job->batch->sourceMaxSize)) - { - fclose(f); - - job->status = PACKFILE_SKIPPED; - job->zdError = ZipDir::ZD_ERROR_SUCCESS; - return; - } - - if (!fileSize) - { - //Allow 0-Bytes long files. - job->uncompressedData = nullptr; - } - else - { - job->uncompressedData = azmalloc(fileSize); - - fseek(f, 0, SEEK_SET); - if (fread(job->uncompressedData, 1, fileSize, f) != fileSize) - { - azfree(job->uncompressedData); - job->uncompressedData = 0; - fclose(f); - - job->status = PACKFILE_FAILED; - job->zdError = ZipDir::ZD_ERROR_IO_FAILED; - return; - } - } - fclose(f); - job->uncompressedSize = fileSize; - - PackFileFromMemory(job); -} - -bool ZipDir::CacheRW::UpdateMultipleFiles(const char** realFilenames, const char** filenamesInZip, size_t fileCount, - int compressionLevel, bool encryptContent, size_t zipMaxSize, int sourceMinSize, int sourceMaxSize, - unsigned numExtraThreads, ZipDir::IReporter* reporter, ZipDir::ISplitter* splitter, bool useFastestDecompressionCodec) -{ - int compressionMethod = ZipFile::METHOD_DEFLATE; - if (encryptContent) - { - compressionMethod = ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - } - else if (compressionLevel == 0) - { - compressionMethod = ZipFile::METHOD_STORE; - } - - uint64 totalSize = 0; - - clock_t startTime = clock(); - - PackFileBatch batch; - batch.compressionLevel = compressionLevel; - batch.compressionMethod = compressionMethod; - batch.sourceMinSize = sourceMinSize; - batch.sourceMaxSize = sourceMaxSize; - batch.zipMaxSize = zipMaxSize; - - const size_t memoryLimit = 1024 * 1024 * 1024; // prevents threads from generating more than 1GB of data - PackFilePool pool(fileCount, memoryLimit); - batch.pool = &pool; - - for (int i = 0; i < fileCount; ++i) - { - const char* realFilename = realFilenames[i]; - const char* filenameInZip = filenamesInZip[i]; - - PackFileJob job; - - job.relativePathSrc = filenameInZip; - job.realFilename = realFilename; - job.batch = &batch; - job.compressionPolicy = useFastestDecompressionCodec ? PACKFILE_USE_FASTEST_DECOMPRESSING_CODEC : PACKFILE_USE_REQUESTED_COMPRESSOR; - - { - // crc will be used to check if this file need to be updated at all - ZipDir::FileEntry* entry = FindFile(filenameInZip); - if (entry) - { - uint64 fileSize = 0; - - const FILETIME ft = GetFileWriteTimeAndSize(&fileSize, realFilename); - LARGE_INTEGER lt; - - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - job.modTime = lt.QuadPart; - job.existingCRC = entry->desc.lCRC32; - job.compressedSizePreviously = entry->desc.lSizeCompressed; - job.uncompressedSizePreviously = entry->desc.lSizeUncompressed; - - // Check if file with the same name, timestamp and size already exists in pak. - if (entry->CompareFileTimeNTFS(job.modTime) && fileSize == entry->desc.lSizeUncompressed) - { - if (reporter) - { - reporter->ReportUpToDate(filenameInZip); - } - continue; - } - } - } - - pool.Submit(i, job); - } - - // Get the number of submitted jobs, which is at most - // as large as the largest successfully submitted file-index. - // Any number of files can be skipped for submission. - const int jobCount = pool.GetJobCount(); - if (jobCount == 0) - { - return true; - } - - pool.Start(numExtraThreads); - - for (int i = 0; i < jobCount; ++i) - { - PackFileJob* job = pool.WaitForFile(i); - if (!job) - { - assert(job); - continue; - } - - if (job->status == PACKFILE_COMPRESSED) - { - if (splitter) - { - size_t dsk = GetTotalFileSizeOnDiskSoFar(); - size_t bse = 0; - size_t add = 0; - size_t sub = 0; - - bse += sizeof(ZipFile::CDRFileHeader) + strlen(job->relativePathSrc); - bse += sizeof(ZipFile::LocalFileHeader) + strlen(job->relativePathSrc); - - if (job->compressedSize) - { - add += bse + job->compressedSize; - } - if (job->compressedSizePreviously) - { - sub += bse + job->compressedSizePreviously; - } - - if (splitter->CheckWriteLimit(dsk, add, sub)) - { - splitter->SetLastFile(dsk, add, sub, job->key - 1); - - // deplete the pool before leaving the loop - pool.SkipPendingFiles(); - for (; i < jobCount; ++i) - { - pool.WaitForFile(i); - pool.ReleaseFile(i); - } - - break; - } - } - - StorePackedFile(job); - } - - switch (job->status) - { - case PACKFILE_ADDED: - if (reporter) - { - reporter->ReportAdded(job->relativePathSrc); - } - - totalSize += job->uncompressedSize; - break; - case PACKFILE_MISSING: - if (reporter) - { - reporter->ReportMissing(job->realFilename); - } - break; - case PACKFILE_UPTODATE: - if (reporter) - { - reporter->ReportUpToDate(job->realFilename); - } - break; - case PACKFILE_SKIPPED: - if (reporter) - { - reporter->ReportSkipped(job->realFilename); - } - break; - default: - if (reporter) - { - reporter->ReportFailed(job->realFilename, ""); // TODO reason - } - break; - } - - pool.ReleaseFile(i); - } - - clock_t endTime = clock(); - double timeSeconds = double(endTime - startTime) / CLOCKS_PER_SEC; - double speed = (endTime - startTime) == 0 ? 0.0 : double(totalSize) / timeSeconds; - - if (reporter) - { - reporter->ReportSpeed(speed); - } - - return true; -} - - -// Adds a new file to the zip or update an existing one if it is not compressed - just stored - start a big file -ZipDir::ErrorEnum ZipDir::CacheRW::StartContinuousFileUpdate(const char* szRelativePathSrc, unsigned nSize) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - pFileEntry->OnNewFileData (NULL, nSize, nSize, ZipFile::METHOD_STORE, false); - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // the new CDR position, if the operation completes successfully - unsigned lNewCDROffset = m_lCDROffset; - if (pFileEntry->IsInitialized()) - { - // check if the new compressed data fits into the old place - unsigned nFreeSpace = pFileEntry->nEOFOffset - pFileEntry->nFileHeaderOffset - (unsigned)sizeof(ZipFile::LocalFileHeader) - (unsigned)strlen(szRelativePath); - - if (nFreeSpace != nSize) - { - m_nFlags |= FLAGS_UNCOMPACTED; - } - - if (nFreeSpace >= nSize) - { - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - } - else - { - // we need to write the file anew - in place of current CDR - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(szRelativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - lNewCDROffset = pFileEntry->nEOFOffset; - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - } - } - else - { - pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset(szRelativePathSrc, m_lCDROffset, m_fileAlignment); - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePathSrc, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - lNewCDROffset = pFileEntry->nFileDataOffset + nSize; - - m_nFlags |= FLAGS_CDR_DIRTY; - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (!WriteNullData(nSize)) - { - return ZD_ERROR_IO_FAILED; - } - - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset; - - // since we wrote the file successfully, update the new CDR position - m_lCDROffset = lNewCDROffset; - pFileEntry.Commit(); - - return ZD_ERROR_SUCCESS; -} - -// Adds a new file to the zip or update an existing's segment if it is not compressed - just stored -// adds a directory (creates several nested directories if needed) -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFileContinuousSegment (const char* szRelativePathSrc, [[maybe_unused]] unsigned nSize, void* pUncompressed, unsigned nSegmentSize, unsigned nOverwriteSeekPos) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - pFileEntry->OnNewFileData (pUncompressed, nSegmentSize, nSegmentSize, ZipFile::METHOD_STORE, true); - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - // this file entry is already allocated in CDR - unsigned lSegmentOffset = pFileEntry->nEOFOffset; - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePath, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - if (nOverwriteSeekPos != 0xffffffff) - { - lSegmentOffset = pFileEntry->nFileDataOffset + nOverwriteSeekPos; - } - - // now we have the fresh local header and data offset -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)lSegmentOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, lSegmentOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - const bool encrypt = false; // encryption is not supported for continous updates - if (!WriteCompressedData((char*)pUncompressed, nSegmentSize, encrypt, m_pFile)) - { - return ZD_ERROR_IO_FAILED; - } - - if (nOverwriteSeekPos == 0xffffffff) - { - pFileEntry->nEOFOffset = lSegmentOffset + nSegmentSize; - } - - // since we wrote the file successfully, update CDR - pFileEntry.Commit(); - return ZD_ERROR_SUCCESS; -} - - -ZipDir::ErrorEnum ZipDir::CacheRW::UpdateFileCRC (const char* szRelativePathSrc, unsigned dwCRC32) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - SmartPtr pBufferDestroyer; - - // create or find the file entry.. this object will rollback (delete the object - // if the operation fails) if needed. - FileEntryTransactionAdd pFileEntry(this, AllocPath(szRelativePathSrc), AllocPath(szRelativePath)); - - if (!pFileEntry) - { - return ZD_ERROR_INVALID_PATH; - } - - // since we changed the time, we'll have to update CDR - m_nFlags |= FLAGS_CDR_DIRTY; - - pFileEntry->desc.lCRC32 = dwCRC32; - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, pFileEntry->nFileHeaderOffset, SEEK_SET) != 0) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - // and we can just override the compressed data in the file - ErrorEnum e = WriteLocalHeader(m_pFile, pFileEntry, szRelativePath, m_bEncryptedHeaders); - if (e != ZD_ERROR_SUCCESS) - { - return e; - } - - // since we wrote the file successfully, update - pFileEntry.Commit(); - return ZD_ERROR_SUCCESS; -} - - -// deletes the file from the archive -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveFile (const char* szRelativePathSrc) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - // find the last slash in the path - const char* pSlash = (std::max)(strrchr(szRelativePath, '/'), strrchr(szRelativePath, '\\')); - - const char* pFileName; // the name of the file to delete - - FileEntryTree* pDir; // the dir from which the subdir will be deleted - - if (pSlash) - { - FindDirRW fd (GetRoot()); - // the directory to remove - pDir = fd.FindExact(string (szRelativePath, pSlash - szRelativePath).c_str()); - if (!pDir) - { - return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory - } - pFileName = pSlash + 1; - } - else - { - pDir = GetRoot(); - pFileName = szRelativePath; - } - - ErrorEnum e = pDir->RemoveFile (pFileName); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - - -// deletes the directory, with all its descendants (files and subdirs) -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveDir (const char* szRelativePathSrc) -{ - char str[_MAX_PATH]; - char* szRelativePath = UnifyPath(str, szRelativePathSrc); - - // find the last slash in the path - const char* pSlash = (std::max)(strrchr(szRelativePath, '/'), strrchr(szRelativePath, '\\')); - - const char* pDirName; // the name of the dir to delete - - FileEntryTree* pDir; // the dir from which the subdir will be deleted - - if (pSlash) - { - FindDirRW fd (GetRoot()); - // the directory to remove - pDir = fd.FindExact(string (szRelativePath, pSlash - szRelativePath).c_str()); - if (!pDir) - { - return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory - } - pDirName = pSlash + 1; - } - else - { - pDir = GetRoot(); - pDirName = szRelativePath; - } - - ErrorEnum e = pDir->RemoveDir (pDirName); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - -// deletes all files and directories in this archive -ZipDir::ErrorEnum ZipDir::CacheRW::RemoveAll() -{ - ErrorEnum e = m_treeDir.RemoveAll(); - if (e == ZD_ERROR_SUCCESS) - { - m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; - } - return e; -} - -ZipDir::ErrorEnum ZipDir::CacheRW::ReadFile (FileEntry* pFileEntry, void* pCompressed, void* pUncompressed) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->desc.lSizeUncompressed == 0) - { - assert (pFileEntry->desc.lSizeCompressed == 0); - return ZD_ERROR_SUCCESS; - } - - assert (pFileEntry->desc.lSizeCompressed > 0); - - ErrorEnum nError = Refresh(pFileEntry); - if (nError != ZD_ERROR_SUCCESS) - { - return nError; - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)pFileEntry->nFileDataOffset, SEEK_SET)) -#else - if (fseek (m_pFile, pFileEntry->nFileDataOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - SmartPtr pBufferDestroyer; - - void* pBuffer = pCompressed; // the buffer where the compressed data will go - - if (pFileEntry->nMethod == 0 && pUncompressed) - { - // we can directly read into the uncompress buffer - pBuffer = pUncompressed; - } - - if (!pBuffer) - { - if (!pUncompressed) - { - // what's the sense of it - no buffers at all? - return ZD_ERROR_INVALID_CALL; - } - - pBuffer = azmalloc(pFileEntry->desc.lSizeCompressed); - pBufferDestroyer.Attach(pBuffer); // we want it auto-freed once we return - } - - if (fread((char*)pBuffer, pFileEntry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return ZD_ERROR_IO_FAILED; - } - - if (pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pBuffer, pFileEntry->desc.lSizeCompressed, m_encryptionKey); - } - - // if there's a buffer for uncompressed data, uncompress it to that buffer - if (pUncompressed) - { - if (pFileEntry->nMethod == 0) - { - assert (pBuffer == pUncompressed); - //assert (pFileEntry->nSizeCompressed == pFileEntry->nSizeUncompressed); - //memcpy (pUncompressed, pBuffer, pFileEntry->nSizeCompressed); - } - else - { - unsigned long nSizeUncompressed = pFileEntry->desc.lSizeUncompressed; - if (nSizeUncompressed > 0) - { - if (Z_OK != ZipRawUncompress(pUncompressed, &nSizeUncompressed, pBuffer, pFileEntry->desc.lSizeCompressed)) - { - return ZD_ERROR_CORRUPTED_DATA; - } - } - } - } - - return ZD_ERROR_SUCCESS; -} - - -////////////////////////////////////////////////////////////////////////// -// finds the file by exact path -ZipDir::FileEntry* ZipDir::CacheRW::FindFile (const char* szPathSrc, [[maybe_unused]] bool bFullInfo) -{ - char str[_MAX_PATH]; - char* szPath = UnifyPath(str, szPathSrc); - - ZipDir::FindFileRW fd (GetRoot()); - if (!fd.FindExact(szPath)) - { - assert (!fd.GetFileEntry()); - return NULL; - } - assert (fd.GetFileEntry()); - return fd.GetFileEntry(); -} - -// returns the size of memory occupied by the instance referred to by this cache -size_t ZipDir::CacheRW::GetSize() const -{ - return sizeof(*this) + m_strFilePath.capacity() + m_treeDir.GetSize() - sizeof(m_treeDir); -} - -// returns the compressed size of all the entries -size_t ZipDir::CacheRW::GetCompressedSize() const -{ - return m_treeDir.GetCompressedFileSize(); -} - -// returns the total size of memory occupied by the instance of this cache and all the compressed files -size_t ZipDir::CacheRW::GetTotalFileSize() const -{ - return GetSize() + GetCompressedSize(); -} - -// returns the total size of space occupied on disk by the instance of this cache and all the compressed files -size_t ZipDir::CacheRW::GetTotalFileSizeOnDiskSoFar() -{ - FileRecordList arrFiles(GetRoot()); - FileRecordList::ZipStats statFiles = arrFiles.GetStats(); - - return m_lCDROffset + statFiles.nSizeCDR; -} - -// refreshes information about the given file entry into this file entry -ZipDir::ErrorEnum ZipDir::CacheRW::Refresh (FileEntry* pFileEntry) -{ - if (!pFileEntry) - { - return ZD_ERROR_INVALID_CALL; - } - - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; // the data offset has been successfully read.. - } - - return ZipDir::Refresh(m_pFile, pFileEntry, m_bEncryptedHeaders); -} - - -// writes the CDR to the disk -bool ZipDir::CacheRW::WriteCDR(FILE* fTarget, bool encryptCDR) -{ - if (!fTarget) - { - return false; - } - -#ifdef WIN32 - if (_fseeki64(fTarget, (__int64)m_lCDROffset, SEEK_SET)) -#else - if (fseek(fTarget, m_lCDROffset, SEEK_SET)) -#endif - { - return false; - } - - FileRecordList arrFiles(GetRoot()); - //arrFiles.SortByFileOffset(); - size_t nSizeCDR = arrFiles.GetStats().nSizeCDR; - void* pCDR = malloc(nSizeCDR); -#if !defined(NDEBUG) - size_t nSizeCDRSerialized = -#endif - arrFiles.MakeZipCDR(m_lCDROffset, pCDR, encryptCDR); - assert (nSizeCDRSerialized == nSizeCDR); - - if (encryptCDR) - { - // We do not encrypt CDREnd, so we could find it by signature - ZipDir::Encrypt((char*)pCDR, nSizeCDR - sizeof(ZipFile::CDREnd), m_encryptionKey); - } - - size_t nWriteRes = fwrite (pCDR, nSizeCDR, 1, fTarget); - free(pCDR); - return nWriteRes == 1; -} - -// generates random file name -string ZipDir::CacheRW::GetRandomName(int nAttempt) -{ - if (nAttempt) - { - char szBuf[8]; - int i; - for (i = 0; i < sizeof(szBuf) - 1; ++i) - { - int r = rand() % (10 + 'z' - 'a' + 1); - szBuf[i] = r > 9 ? (r - 10) + 'a' : '0' + r; - } - szBuf[i] = '\0'; - return szBuf; - } - else - { - return string(); - } -} - -bool ZipDir::CacheRW::RelinkZip() -{ - AZ::IO::LocalFileIO localFileIO; - for (int nAttempt = 0; nAttempt < 32; ++nAttempt) - { - string strNewFilePath = m_strFilePath + "$" + GetRandomName(nAttempt); - - FILE* f = nullptr; - azfopen(&f, strNewFilePath.c_str(), "wb"); - if (f) - { - bool bOk = RelinkZip(f); - fclose (f); // we don't need the temporary file handle anyway - - if (!bOk) - { - // we don't need the temporary file - localFileIO.Remove(strNewFilePath.c_str()); - return false; - } - - // we successfully relinked, now copy the temporary file to the original file - fclose (m_pFile); - m_pFile = NULL; - - localFileIO.Remove(m_strFilePath.c_str()); - if (localFileIO.Rename(strNewFilePath.c_str(), m_strFilePath.c_str()) == 0) - { - // successfully renamed - reopen - m_pFile = nullptr; - azfopen(&m_pFile, m_strFilePath.c_str(), "r+b"); - return m_pFile == NULL; - } - else - { - // could not rename - - //m_pFile = fopen (strNewFilePath.c_str(), "r+b"); - return false; - } - } - } - - // couldn't open temp file - return false; -} - -bool ZipDir::CacheRW::RelinkZip(FILE* fTmp) -{ - FileRecordList arrFiles(GetRoot()); - arrFiles.SortByFileOffset(); - FileRecordList::ZipStats Stats = arrFiles.GetStats(); - - // we back up our file entries, because we'll need to restore them - // in case the operation fails - std::vector arrFileEntryBackup; - arrFiles.Backup (arrFileEntryBackup); - - // this is the set of files that are to be written out - compressed data and the file record iterator - std::vector queFiles; - queFiles.reserve (g_nMaxItemsRelinkBuffer); - - // the total size of data in the queue - unsigned nQueueSize = 0; - - for (FileRecordList::iterator it = arrFiles.begin(); it != arrFiles.end(); ++it) - { - FileEntry* entry = it->pFileEntry; - // find the file data offset - if (ZD_ERROR_SUCCESS != Refresh(entry)) - { - return false; - } - - // go to the file data -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - // allocate memory for the file compressed data - FileDataRecordPtr pFile = FileDataRecord::New (*it); - - if (!pFile) - { - return false; - } - - // read the compressed data - if (entry->desc.lSizeCompressed && fread (pFile->GetData(), entry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return false; - } - - if (entry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pFile->GetData(), entry->desc.lSizeCompressed, m_encryptionKey); - } - - // put the file into the queue for copying (writing) - queFiles.push_back(pFile); - nQueueSize += entry->desc.lSizeCompressed; - - // if the queue is big enough, write it out - if (nQueueSize > g_nSizeRelinkBuffer || queFiles.size() >= g_nMaxItemsRelinkBuffer) - { - nQueueSize = 0; - if (!WriteZipFiles(queFiles, fTmp)) - { - return false; - } - } - } - - if (!WriteZipFiles(queFiles, fTmp)) - { - return false; - } - - ZipFile::ulong lOldCDROffset = m_lCDROffset; - // the file data has now been written out. Now write the CDR -#ifdef WIN32 - m_lCDROffset = (ZipFile::ulong)_ftelli64(fTmp); -#else - m_lCDROffset = ftell(fTmp); -#endif - if (m_lCDROffset >= 0 && WriteCDR(fTmp, m_bHeadersEncryptedOnClose) && 0 == fflush (fTmp)) - { - // the new file positions are already there - just discard the backup and return - return true; - } - // recover from backup - arrFiles.Restore (arrFileEntryBackup); - m_lCDROffset = lOldCDROffset; - m_bEncryptedHeaders = m_bHeadersEncryptedOnClose; - return false; -} - -// writes out the file data in the queue into the given file. Empties the queue -bool ZipDir::CacheRW::WriteZipFiles(std::vector& queFiles, FILE* fTmp) -{ - for (std::vector::iterator it = queFiles.begin(); it != queFiles.end(); ++it) - { - // set the new header offset to the file entry - we won't need it -#ifdef WIN32 - const unsigned long currentPos = (unsigned long)_ftelli64 (fTmp); -#else - const unsigned long currentPos = ftell (fTmp); -#endif - (*it)->pFileEntry->nFileHeaderOffset = CalculateAlignedHeaderOffset((*it)->strPath.c_str(), currentPos, m_fileAlignment); - - // while writing the local header, the data offset will also be calculated - if (ZD_ERROR_SUCCESS != WriteLocalHeader(fTmp, (*it)->pFileEntry, (*it)->strPath.c_str(), m_bHeadersEncryptedOnClose)) - { - return false; - } - ; - - // write the compressed file data - const bool encrypt = (*it)->pFileEntry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - if (!WriteCompressedData((char*)(*it)->GetData(), (*it)->pFileEntry->desc.lSizeCompressed, encrypt, fTmp)) - { - return false; - } - -#ifdef WIN32 - assert ((*it)->pFileEntry->nEOFOffset == (unsigned long)_ftelli64 (fTmp)); -#else - assert ((*it)->pFileEntry->nEOFOffset == ftell (fTmp)); -#endif - } - queFiles.clear(); - queFiles.reserve (g_nMaxItemsRelinkBuffer); - return true; -} - -void TruncateFile(FILE* file, size_t newLength) -{ -#if defined(AZ_PLATFORM_WINDOWS) - int filedes = _fileno(file); - _chsize_s(filedes, newLength); -#elif AZ_TRAIT_OS_PLATFORM_APPLE || defined(AZ_PLATFORM_LINUX) - ftruncate(fileno(file), newLength); -#else -#error Not implemented! -#endif -} - -bool ZipDir::CacheRW::EncryptArchive(EncryptionChange change, IEncryptPredicate* encryptContentPredicate, int* numChanged, int* numSkipped) -{ - FileRecordList arrFiles(GetRoot()); - arrFiles.SortByFileOffset(); - - size_t unusedSpace = 0; - size_t lastDataEnd = 0; - - for (FileRecordList::iterator it = arrFiles.begin(); it != arrFiles.end(); ++it) - { - FileEntry* entry = it->pFileEntry; - - if (entry->nFileHeaderOffset > lastDataEnd) - { - fseek(m_pFile, lastDataEnd, SEEK_SET); - size_t gapLength = entry->nFileHeaderOffset - lastDataEnd; - unusedSpace += gapLength; - if (change == ENCRYPT) - { - if (!WriteRandomData(m_pFile, gapLength)) - { - return false; - } - } - else - { - if (!WriteNullData(gapLength)) - { - return false; - } - } - } - lastDataEnd = entry->nEOFOffset; - - if (numSkipped) - { - ++(*numSkipped); - } - - // find the file data offset - if (ZD_ERROR_SUCCESS != Refresh (entry)) - { - return false; - } - - ZipFile::ushort oldMethod = entry->nMethod; - ZipFile::ushort newMethod = oldMethod; - if (change == ENCRYPT) - { - if (entry->nMethod == ZipFile::METHOD_DEFLATE) - { - newMethod = ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - } - } - else - { - if (entry->nMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - newMethod = ZipFile::METHOD_DEFLATE; - } - } - - // allow encryption only for matching files - if (newMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT && - (!encryptContentPredicate || !encryptContentPredicate->Match(it->strPath.c_str()))) - { - newMethod = ZipFile::METHOD_DEFLATE; - } - - entry->nMethod = newMethod; - - const bool encryptHeaders = change == ENCRYPT; - // encryption is toggled or compression method changed... - if (newMethod != oldMethod || encryptHeaders != m_bEncryptedHeaders) - { - // ... update header - if (ZipDir::WriteLocalHeader(m_pFile, entry, it->strPath.c_str(), encryptHeaders) != ZD_ERROR_SUCCESS) - { - return false; - } - } - - if (newMethod == oldMethod) - { - // no need to update file content - continue; - } - - // go to the file data -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - // allocate memory for the file compressed data - FileDataRecordPtr pFile = FileDataRecord::New(*it); - if (!pFile) - { - return false; - } - - // read the compressed data - if (entry->desc.lSizeCompressed && fread (pFile->GetData(), entry->desc.lSizeCompressed, 1, m_pFile) != 1) - { - return false; - } - - if (oldMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT) - { - ZipDir::Decrypt((char*)pFile->GetData(), entry->desc.lSizeCompressed, m_encryptionKey); - } - -#ifdef WIN32 - if (_fseeki64 (m_pFile, (__int64)entry->nFileDataOffset, SEEK_SET) != 0) -#else - if (fseek (m_pFile, entry->nFileDataOffset, SEEK_SET) != 0) -#endif - { - return false; - } - - const bool encryptContent = newMethod == ZipFile::METHOD_DEFLATE_AND_ENCRYPT; - if (!WriteCompressedData((const char*)pFile->GetData(), entry->desc.lSizeCompressed, encryptContent, m_pFile)) - { - return false; - } - - if (numSkipped) - { - --(*numSkipped); - } - if (numChanged) - { - ++(*numChanged); - } - } - - m_bEncryptedHeaders = change == ENCRYPT; - m_bHeadersEncryptedOnClose = m_bEncryptedHeaders; - - if (!WriteCDR(m_pFile, m_bEncryptedHeaders)) - { - return false; - } - - if (fflush (m_pFile) != 0) - { - return false; - } - - size_t endOfCDR = (size_t)ftell(m_pFile); - - fseek(m_pFile, 0, SEEK_END); - size_t fileSize = (size_t)ftell(m_pFile); - - if (fileSize != endOfCDR) - { - TruncateFile(m_pFile, endOfCDR); - } - - fclose(m_pFile); - m_pFile = 0; - m_treeDir.Clear(); - return true; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h deleted file mode 100644 index 6c02d34bf3..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirCacheRW.h +++ /dev/null @@ -1,283 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -////////////////////////////////////////////////////////////////////////// -// Declaration of the class that will keep the ZipDir Cache object -// and will provide all its services to access Zip file, plus it will -// provide services to write to the zip file efficiently -// Time to time, the contained Cache object will be recreated during -// an archive add operation - -#pragma once - -#include "SimpleStringPool.h" -#include "StringUtils.h" - -struct PackFileJob; -namespace ZipDir -{ - struct FileDataRecord; - TYPEDEF_AUTOPTR(FileDataRecord); - typedef FileDataRecord_AutoPtr FileDataRecordPtr; - - static constexpr int TARGET_MIN_TEST_COMPRESS_BYTES = 128 * 1024; - - struct IReporter - { - virtual void ReportAdded(const char* filename) = 0; - virtual void ReportMissing(const char* filename) = 0; - virtual void ReportUpToDate(const char* filename) = 0; - virtual void ReportSkipped(const char* filename) = 0; - virtual void ReportFailed(const char* filename, const char* error) = 0; - virtual void ReportSpeed(double bytesPerSecond) = 0; - }; - - struct ISplitter - { - // Arguments: - // total - the current size of the pak - // add - the size of the file to add - // sub - the size of the old version of the file which will be removed from the pak - // Return: - // true if adding the current file to the current pak is still permitted. - virtual bool CheckWriteLimit(size_t total, size_t add, size_t sub) const = 0; - - // Arguments: - // total - the current size of the pak - // add - the size of the file to add - // sub - the size of the old version of the file which will be removed from the pak - // offset - the position of the first file which has not been added to the pak - // in the array passed to "UpdateMultipleFiles()" - virtual void SetLastFile(size_t total, size_t add, size_t sub, int offset) = 0; - }; - - struct IEncryptPredicate - { - virtual ~IEncryptPredicate() = default; - virtual bool Match(const char* filename) = 0; - }; - - class CacheRW - { - public: - enum EncryptionChange - { - ENCRYPT, - DECRYPT - }; - // the size of the buffer that's using during re-linking the zip file - enum - { - g_nSizeRelinkBuffer = 128 * 1024 * 1024, // 128 Mbytes - g_nMaxItemsRelinkBuffer = 1024 // max number of files to read before (without) writing - }; - - void AddRef(); - void Release(); - - - CacheRW(bool encryptHeaders, const EncryptionKey& encryptionKey); - ~CacheRW(); - - bool IsValid () const - { - return m_pFile != NULL; - } - - static char* UnifyPath(char* const str, const char* pPath); - static char* ToUnixPath(char* const str, const char* pPath); - char* AllocPath(const char* pPath); - - // opens the given zip file and connects to it. Creates a new file if no such file exists - // if successful, returns true. - //ErrorEnum Open (CMTSafeHeap* pHeap, InitMethodEnum nInitMethod, unsigned nFlags, const char* szFile); - - // Adds a new file to the zip or update an existing one - // adds a directory (creates several nested directories if needed) - ErrorEnum UpdateFile(const char* szRelativePath, void* pUncompressed, unsigned nSize, unsigned nCompressionMethod, int nCompressionLevel, int64 modTime); - - // Sets if Archive should be encrypted or decrypted on close. - bool EncryptArchive(EncryptionChange change, IEncryptPredicate* encryptContentPredicate, int* numChanged, int* numSkipped); - - // Adds or updates a bunch of files. Creates directories if needed. Multithreaded when numExtraThreads > 0 - bool UpdateMultipleFiles(const char** realFilenames, const char** filenamesInZip, size_t fileCount, - int compressionLevel, bool encryptContent, size_t zipMaxSize, int sourceMinSize, int sourceMaxSize, - unsigned numExtraThreads, ZipDir::IReporter* reporter, ZipDir::ISplitter* splitter = nullptr, bool useFastestDecompressionCodec = false); - - // Adds a new file to the zip or update an existing one if it is not compressed - just stored - start a big file - ErrorEnum StartContinuousFileUpdate(const char* szRelativePath, unsigned nSize); - - // Adds a new file to the zip or update an existing's segment if it is not compressed - just stored - // adds a directory (creates several nested directories if needed) - // Arguments: - // nOverwriteSeekPos - 0xffffffff means the seek pos should not be overwritten - ErrorEnum UpdateFileContinuousSegment (const char* szRelativePath, unsigned nSize, void* pUncompressed, unsigned nSegmentSize, unsigned nOverwriteSeekPos); - - ErrorEnum UpdateFileCRC(const char* szRelativePath, unsigned dwCRC32); - - // deletes the file from the archive - ErrorEnum RemoveFile(const char* szRelativePath); - - // deletes the directory, with all its descendants (files and subdirs) - ErrorEnum RemoveDir(const char* szRelativePath); - - // deletes all files and directories in this archive - ErrorEnum RemoveAll(); - - // closes the current zip file - void Close(); - - FileEntry* FindFile(const char* szPath, bool bFullInfo = false); - - ErrorEnum ReadFile(FileEntry* pFileEntry, void* pCompressed, void* pUncompressed); - - void* AllocAndReadFile (FileEntry* pFileEntry); - - void Free (void* p) - { - free(p); - } - - // refreshes information about the given file entry into this file entry - ErrorEnum Refresh (FileEntry* pFileEntry); - - // returns the size of memory occupied by the instance of this cache - size_t GetSize() const; - - // returns the compressed size of all the entries - size_t GetCompressedSize() const; - - // returns the total size of memory occupied by the instance of this cache and all the compressed files - size_t GetTotalFileSize() const; - - // returns the total size of space occupied on disk by the instance of this cache and all the compressed files - size_t GetTotalFileSizeOnDiskSoFar(); - - // QUICK check to determine whether the file entry belongs to this object - bool IsOwnerOf (const FileEntry* pFileEntry) const - { - return m_treeDir.IsOwnerOf(pFileEntry); - } - - // returns the string - path to the zip file from which this object was constructed. - // this will be "" if the object was constructed with a factory that wasn't created with FLAGS_MEMORIZE_ZIP_PATH - const char* GetFilePath() const - { - return m_strFilePath.c_str(); - } - - FileEntryTree* GetRoot() - { - return &m_treeDir; - } - - const FileEntryTree* GetRoot() const - { - return &m_treeDir; - } - - // writes the CDR to the disk - bool WriteCDR() {return WriteCDR(m_pFile, m_bEncryptedHeaders); } - bool WriteCDR(FILE* fTarget, bool encryptHeaders); - - bool RelinkZip(); - protected: - bool RelinkZip(FILE* fTmp); - // writes out the file data in the queue into the given file. Empties the queue - bool WriteZipFiles(std::vector& queFiles, FILE* fTmp); - // generates random file name - string GetRandomName(int nAttempt); - - bool ReadCompressedData(char* data, size_t size); - bool WriteCompressedData(const char* data, size_t size, bool encrypt, FILE* file); - bool WriteNullData(size_t size); - - void StorePackedFile(PackFileJob* job); - protected: - - friend class CacheFactory; - volatile signed int m_nRefCount; // the reference count - FileEntryTree m_treeDir; - FILE* m_pFile; - string m_strFilePath; - - // offset to the start of CDR in the file,even if there's no CDR there currently - // when a new file is added, it can start from here, but this value will need to be updated then - ZipFile::ulong m_lCDROffset; - - CSimpleStringPool m_tempStringPool; - - enum - { - // if this is set, the file needs to be compacted before it can be used by - // all standard zip tools, because gaps between file datas can be present - FLAGS_UNCOMPACTED = 1 << 0, - // if this is set, the CDR needs to be written to the file - FLAGS_CDR_DIRTY = 1 << 1, - // if this is set, the file is opened in read-only mode. no write operations are to be performed - FLAGS_READ_ONLY = 1 << 2, - // when this is set, compact operation is not performed - FLAGS_DONT_COMPACT = 1 << 3 - }; - unsigned m_nFlags; - size_t m_fileAlignment; - - // CDR buffer. - DynArray m_CDR_buffer; - // unified names buffer - DynArray m_unifiedNameBuffer; - - EncryptionKey m_encryptionKey; - bool m_bEncryptedHeaders; - bool m_bHeadersEncryptedOnClose; - }; - - TYPEDEF_AUTOPTR(CacheRW); - typedef CacheRW_AutoPtr CacheRWPtr; - - // creates and if needed automatically destroys the file entry - class FileEntryTransactionAdd - { - class CacheRW* m_pCache; - char m_szPath[_MAX_PATH]; - FileEntry* m_pFileEntry; - bool m_bComitted; - public: - operator FileEntry* () { - return m_pFileEntry; - } - operator bool() const{ - return m_pFileEntry != NULL; - } - FileEntry* operator -> () {return m_pFileEntry; } - FileEntryTransactionAdd(class CacheRW* pCache, char* szPath, char* szUnifiedPath) - : m_pCache(pCache) - , m_bComitted (false) - { - // we need to copy path, because original one will be destroyed by FileEntryTree::Add call - cry_strcpy(m_szPath, szUnifiedPath); - m_pFileEntry = m_pCache->GetRoot()->Add(szPath, szUnifiedPath); - } - ~FileEntryTransactionAdd() - { - if (m_pFileEntry && !m_bComitted) - { - m_pCache->RemoveFile(m_szPath); - } - } - void Commit() - { - m_bComitted = true; - } - }; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp deleted file mode 100644 index c62428f0b1..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#include "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirCache.h" -#include "ZipDirFind.h" -#include "StringHelpers.h" - -bool ZipDir::FindFile::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_nFileEntry = 0; - return SkipNonMatchingFiles(); -} - -bool ZipDir::FindDir::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_nDirEntry = 0; - return SkipNonMatchingDirs(); -} - -// matches the file wilcard in the m_szWildcard to the given file/dir name -// this takes into account the fact that xxx. is the alias name for xxx -bool ZipDir::FindData::MatchWildcard(const char* szName) -{ - if (StringHelpers::MatchesWildcards(szName, m_szWildcard)) - { - return true; - } - - // check if the file object name contains extension sign (.) - const char* p; - for (p = szName; *p && *p != '.'; ++p) - { - continue; - } - - if (*p) - { - // there's an extension sign in the object, but it wasn't matched.. - assert (*p == '.'); - return false; - } - - // no extension sign - add it - char szAlias[_MAX_PATH + 2]; - size_t nLength = p - szName; - if (nLength > _MAX_PATH) - { - nLength = _MAX_PATH; - } - memcpy (szAlias, szName, nLength); - szAlias[nLength] = '.'; // add the alias - szAlias[nLength + 1] = '\0'; // terminate the string - return StringHelpers::MatchesWildcards(szAlias, m_szWildcard); -} - - -ZipDir::FileEntry* ZipDir::FindFile::FindExact (const char* szPath) -{ - if (!PreFind (szPath)) - { - return NULL; - } - - FileEntry* pFileEntry = m_pDirHeader->FindFileEntry(m_szWildcard); - if (pFileEntry) - { - m_nFileEntry = (unsigned)(pFileEntry - m_pDirHeader->GetFileEntry(0)); - } - else - { - m_pDirHeader = NULL; // we didn't find it, fail the search - } - return pFileEntry; -} - -////////////////////////////////////////////////////////////////////////// -// after this call returns successfully (with true returned), the m_szWildcard -// contains the file name/wildcard and m_pDirHeader contains the directory where -// the file (s) are to be found -bool ZipDir::FindData::PreFind (const char* szWildcard) -{ - if (!m_pRoot) - { - return false; - } - - // start the search from the root - m_pDirHeader = m_pRoot; - - // for each path dir name, copy it into the buffer and try to find the subdirectory - const char* pPath = szWildcard; - for (;; ) - { - char* pName = m_szWildcard; - - // at first we'll use the wildcard memory to save the directory names - for (; *pPath && *pPath != '/' && *pPath != '\\' && pName < m_szWildcard + sizeof(m_szWildcard) - 1; ++pPath, ++pName) - { - *pName = ::tolower(*pPath); - } - *pName = '\0'; - - if (*pPath) - { - if (*pPath != '/' && *pPath != '\\') - { - return false;//ZD_ERROR_NAME_TOO_LONG; - } - // this is the name of the directory - DirEntry* pDirEntry = m_pDirHeader->FindSubdirEntry(m_szWildcard); - if (!pDirEntry) - { - m_pDirHeader = NULL; // finish the search - return false; - } - m_pDirHeader = pDirEntry->GetDirectory(); - ++pPath; - assert(m_pDirHeader); - } - else - { - // finally, this is the name of the file (or directory) - return true; - } - } -} - -// goes on to the next entry -bool ZipDir::FindFile::FindNext () -{ - if (m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles) - { - ++m_nFileEntry; - return SkipNonMatchingFiles(); - } - else - { - return false; - } -} - -// goes on to the next entry -bool ZipDir::FindDir::FindNext () -{ - if (m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs) - { - ++m_nDirEntry; - return SkipNonMatchingDirs(); - } - else - { - return false; - } -} - -bool ZipDir::FindFile::SkipNonMatchingFiles() -{ - assert(m_pDirHeader && m_nFileEntry <= m_pDirHeader->numFiles); - - for (; m_nFileEntry < m_pDirHeader->numFiles; ++m_nFileEntry) - { - if (MatchWildcard(GetFileName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - -bool ZipDir::FindDir::SkipNonMatchingDirs() -{ - assert(m_pDirHeader && m_nDirEntry <= m_pDirHeader->numDirs); - - for (; m_nDirEntry < m_pDirHeader->numDirs; ++m_nDirEntry) - { - if (MatchWildcard(GetDirName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - - -ZipDir::FileEntry* ZipDir::FindFile::GetFileEntry() -{ - return m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles ? m_pDirHeader->GetFileEntry(m_nFileEntry) : NULL; -} -ZipDir::DirEntry* ZipDir::FindDir::GetDirEntry() -{ - return m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs ? m_pDirHeader->GetSubdirEntry(m_nDirEntry) : NULL; -} - -const char* ZipDir::FindFile::GetFileName () -{ - if (m_pDirHeader && m_nFileEntry < m_pDirHeader->numFiles) - { - const char* pNamePool = m_pDirHeader->GetNamePool(); - return m_pDirHeader->GetFileEntry(m_nFileEntry)->GetName(pNamePool); - } - else - { - return ""; // default name - } -} - -const char* ZipDir::FindDir::GetDirName () -{ - if (m_pDirHeader && m_nDirEntry < m_pDirHeader->numDirs) - { - const char* pNamePool = m_pDirHeader->GetNamePool(); - return m_pDirHeader->GetSubdirEntry(m_nDirEntry)->GetName(pNamePool); - } - else - { - return ""; // default name - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h deleted file mode 100644 index 99e95607c1..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFind.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H -#pragma once - - -namespace ZipDir -{ - // create this structure and loop: - // FindData fd (pZip); - // for (fd.FindFirst("*.cgf"); fd.GetFileEntry(); fd.FindNext()) - // {} // inside the loop, use GetFileEntry() and GetFileName() to get the file entry and name records - class FindData - { - public: - - FindData (DirHeader* pRoot) - : m_pRoot (pRoot) - , m_pDirHeader (NULL) - { - } - - protected: - // initializes everything until the point where the file must be searched for - // after this call returns successfully (with true returned), the m_szWildcard - // contains the file name/wildcard and m_pDirHeader contains the directory where - // the file (s) are to be found - bool PreFind (const char* szWildcard); - - // matches the file wilcard in the m_szWildcard to the given file/dir name - // this takes into account the fact that xxx. is the alias name for xxx - bool MatchWildcard(const char* szName); - - DirHeader* m_pRoot; // the zip file inwhich the search is performed - DirHeader* m_pDirHeader; // the header of the directory in which the files reside - //unsigned m_nDirEntry; // the current directory entry inside the parent directory - - // the actual wildcard being used in the current scan - the file name wildcard only! - char m_szWildcard[_MAX_PATH]; - }; - - class FindFile - : public FindData - { - public: - FindFile (Cache* pCache) - : FindData(pCache->GetRoot()) - { - } - FindFile (DirHeader* pRoot) - : FindData(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntry* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntry* GetFileEntry(); - const char* GetFileName (); - - protected: - bool SkipNonMatchingFiles(); - unsigned m_nFileEntry; // the current file index inside the parent directory - }; - - class FindDir - : public FindData - { - public: - FindDir (Cache* pCache) - : FindData(pCache->GetRoot()) - { - } - FindDir (DirHeader* pRoot) - : FindData(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - // goes on to the next file entry - bool FindNext (); - - DirEntry* GetDirEntry(); - const char* GetDirName (); - - protected: - bool SkipNonMatchingDirs(); - unsigned m_nDirEntry; // the current dir index inside the parent directory - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFIND_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp deleted file mode 100644 index a44f8dd45e..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#include "smartptr.h" -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" -#include "ZipDirCacheRW.h" -#include "ZipDirFindRW.h" -#include "StringHelpers.h" - -bool ZipDir::FindFileRW::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_itFile = m_pDirHeader->GetFileBegin(); - return SkipNonMatchingFiles(); -} - -bool ZipDir::FindDirRW::FindFirst (const char* szWildcard) -{ - if (!PreFind (szWildcard)) - { - return false; - } - - // finally, this is the name of the file - m_itDir = m_pDirHeader->GetDirBegin(); - return SkipNonMatchingDirs(); -} - -// matches the file wilcard in the m_szWildcard to the given file/dir name -// this takes into account the fact that xxx. is the alias name for xxx -bool ZipDir::FindDataRW::MatchWildcard(const char* szName) -{ - if (StringHelpers::MatchesWildcards(szName, m_szWildcard)) - { - return true; - } - - // check if the file object name contains extension sign (.) - const char* p; - for (p = szName; *p && *p != '.'; ++p) - { - continue; - } - - if (*p) - { - // there's an extension sign in the object, but it wasn't matched.. - assert (*p == '.'); - return false; - } - - // no extension sign - add it - char szAlias[_MAX_PATH + 2]; - size_t nLength = p - szName; - if (nLength > _MAX_PATH) - { - nLength = _MAX_PATH; - } - memcpy (szAlias, szName, nLength); - szAlias[nLength] = '.'; // add the alias - szAlias[nLength + 1] = '\0'; // terminate the string - return StringHelpers::MatchesWildcards(szAlias, m_szWildcard); -} - - -ZipDir::FileEntry* ZipDir::FindFileRW::FindExact (const char* szPath) -{ - if (!PreFind (szPath)) - { - return NULL; - } - - FileEntryTree::FileMap::iterator itFile = m_pDirHeader->FindFile(m_szWildcard); - if (itFile != m_pDirHeader->GetFileEnd()) - { - m_itFile = itFile; - } - else - { - m_pDirHeader = NULL; // we didn't find it, fail the search - } - return m_pDirHeader ? m_pDirHeader->GetFileEntry(itFile) : NULL; -} - -ZipDir::FileEntryTree* ZipDir::FindDirRW::FindExact (const char* szPath) -{ - if (!PreFind(szPath)) - { - return NULL; - } - - // the wildcard will contain the target directory name - return m_pDirHeader->FindDir(m_szWildcard); -} - -////////////////////////////////////////////////////////////////////////// -// initializes everything until the point where the file must be searched for -// after this call returns successfully (with true returned), the m_szWildcard -// contains the file name/wildcard and m_pDirHeader contains the directory where -// the file (s) are to be found -bool ZipDir::FindDataRW::PreFind (const char* szWildcard) -{ - if (!m_pRoot) - { - return false; - } - - // start the search from the root - m_pDirHeader = m_pRoot; - - // for each path dir name, copy it into the buffer and try to find the subdirectory - const char* pPath = szWildcard; - for (;; ) - { - char* pName = m_szWildcard; - - // at first we'll use the wildcard memory to save the directory names - for (; *pPath && *pPath != '/' && *pPath != '\\' && pName < m_szWildcard + sizeof(m_szWildcard) - 1; ++pPath, ++pName) - { - *pName = ::tolower(*pPath); - } - *pName = '\0'; - - if (*pPath) - { - // this is the name of the directory - FileEntryTree* pDirEntry = m_pDirHeader->FindDir(m_szWildcard); - if (!pDirEntry) - { - m_pDirHeader = NULL; // finish the search - return false; - } - m_pDirHeader = pDirEntry->GetDirectory(); - ++pPath; - assert(m_pDirHeader); - } - else - { - // finally, this is the name of the file (or directory) - return true; - } - } -} - -// goes on to the next entry -bool ZipDir::FindFileRW::FindNext () -{ - if (m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd()) - { - ++m_itFile; - return SkipNonMatchingFiles(); - } - else - { - return false; - } -} - -// goes on to the next entry -bool ZipDir::FindDirRW::FindNext () -{ - if (m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd()) - { - ++m_itDir; - return SkipNonMatchingDirs(); - } - else - { - return false; - } -} - -bool ZipDir::FindFileRW::SkipNonMatchingFiles() -{ - assert(m_pDirHeader); - - for (; m_itFile != m_pDirHeader->GetFileEnd(); ++m_itFile) - { - if (MatchWildcard(GetFileName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - -bool ZipDir::FindDirRW::SkipNonMatchingDirs() -{ - assert(m_pDirHeader); - - for (; m_itDir != m_pDirHeader->GetDirEnd(); ++m_itDir) - { - if (MatchWildcard(GetDirName())) - { - return true; - } - } - // we didn't find anything other file else - return false; -} - - -ZipDir::FileEntry* ZipDir::FindFileRW::GetFileEntry() -{ - return m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd() ? m_pDirHeader->GetFileEntry(m_itFile) : NULL; -} -ZipDir::FileEntryTree* ZipDir::FindDirRW::GetDirEntry() -{ - return m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd() ? m_pDirHeader->GetDirEntry(m_itDir) : NULL; -} - -const char* ZipDir::FindFileRW::GetFileName () -{ - if (m_pDirHeader && m_itFile != m_pDirHeader->GetFileEnd()) - { - return m_pDirHeader->GetFileName(m_itFile); - } - else - { - return ""; // default name - } -} - -const char* ZipDir::FindDirRW::GetDirName () -{ - if (m_pDirHeader && m_itDir != m_pDirHeader->GetDirEnd()) - { - return m_pDirHeader->GetDirName(m_itDir); - } - else - { - return ""; // default name - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h deleted file mode 100644 index 3085b5f8ba..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirFindRW.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Declaration of the class that can be used to search for the entries -// in a zip dir cache - - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H -#pragma once - - -namespace ZipDir -{ - // create this structure and loop: - // FindData fd (pZip); - // for (fd.FindFirst("*.cgf"); fd.GetFileEntry(); fd.FindNext()) - // {} // inside the loop, use GetFileEntry() and GetFileName() to get the file entry and name records - class FindDataRW - { - public: - FindDataRW (FileEntryTree* pRoot) - : m_pRoot (pRoot) - , m_pDirHeader (NULL) - { - } - - // returns the directory to which the current object belongs - FileEntryTree* GetParentDir() {return m_pDirHeader; } - protected: - // initializes everything until the point where the file must be searched for - // after this call returns successfully (with true returned), the m_szWildcard - // contains the file name/wildcard and m_pDirHeader contains the directory where - // the file (s) are to be found - bool PreFind (const char* szWildcard); - - // matches the file wilcard in the m_szWildcard to the given file/dir name - // this takes into account the fact that xxx. is the alias name for xxx - bool MatchWildcard(const char* szName); - - // the directory inside which the current object (file or directory) is being searched - FileEntryTree* m_pDirHeader; - - FileEntryTree* m_pRoot; // the root of the zip file in which to search - - // the actual wildcard being used in the current scan - the file name wildcard only! - char m_szWildcard[_MAX_PATH]; - }; - - - class FindFileRW - : public FindDataRW - { - public: - FindFileRW (FileEntryTree* pRoot) - : FindDataRW(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntry* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntry* GetFileEntry(); - const char* GetFileName (); - - protected: - bool SkipNonMatchingFiles(); - FileEntryTree::FileMap::iterator m_itFile; // the current file iterator inside the parent directory - }; - - class FindDirRW - : public FindDataRW - { - public: - FindDirRW (FileEntryTree* pRoot) - : FindDataRW(pRoot) - { - } - // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst (const char* szWildcard); - - FileEntryTree* FindExact (const char* szPath); - - // goes on to the next file entry - bool FindNext (); - - FileEntryTree* GetDirEntry(); - const char* GetDirName (); - - protected: - bool SkipNonMatchingDirs(); - FileEntryTree::SubdirMap::iterator m_itDir; // the current dir index inside the parent directory - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRFINDRW_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp deleted file mode 100644 index 36b0dd6ba8..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.cpp +++ /dev/null @@ -1,174 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#undef max -#include -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirList.h" -#include "ZipDirTree.h" - -ZipDir::FileRecordList::FileRecordList(FileEntryTree* pTree) -{ - clear(); - reserve(pTree->NumFilesTotal()); - AddAllFiles(pTree); -} - -//recursively adds the files from this directory and subdirectories -// the strRoot contains the trailing slash -void ZipDir::FileRecordList::AddAllFiles(FileEntryTree* pTree, string strRoot) -{ - for (FileEntryTree::SubdirMap::iterator it = pTree->GetDirBegin(); it != pTree->GetDirEnd(); ++it) - { - AddAllFiles (it->second, strRoot + it->second->GetOriginalName() + "/"); - } - - for (FileEntryTree::FileMap::iterator it = pTree->GetFileBegin(); it != pTree->GetFileEnd(); ++it) - { - FileRecord rec; - rec.pFileEntry = pTree->GetFileEntry(it); - const char* filename = rec.pFileEntry->szOriginalFileName ? rec.pFileEntry->szOriginalFileName : it->first; - rec.strPath = strRoot + filename; - push_back(rec); - } -} - - -// sorts the files by the physical offset in the zip file -void ZipDir::FileRecordList::SortByFileOffset() -{ - std::sort (begin(), end(), FileRecordFileOffsetOrder()); -} - -// returns the size of CDR in the zip file -ZipDir::FileRecordList::ZipStats ZipDir::FileRecordList::GetStats() const -{ - ZipStats Stats; - Stats.nSizeCDR = sizeof(ZipFile::CDREnd); - Stats.nSizeCompactData = 0; - // for each file, we'll need to store only its CDR header and the name - for (const_iterator it = begin(); it != end(); ++it) - { - Stats.nSizeCDR += sizeof(ZipFile::CDRFileHeader) + it->strPath.length(); - Stats.nSizeCompactData += sizeof(ZipFile::LocalFileHeader) + it->strPath.length() + it->pFileEntry->desc.lSizeCompressed; - } - - return Stats; -} - -// puts the CDR into the given block of mem -size_t ZipDir::FileRecordList::MakeZipCDR(ZipFile::ulong lCDROffset, void* pBuffer, bool encryptedFlag) const -{ - const ZipFile::ushort nBaseVersion = std::max(encryptedFlag ? ZipFile::VERSION_ENCRYPTION_PKWARE : ZipFile::VERSION_DEFAULT, ZipFile::VERSION_COMPRESSION_DEFLATE); - - char* pCur = (char*)pBuffer; - for (const_iterator it = begin(); it != end(); ++it) - { - ZipFile::CDRFileHeader& h = *(ZipFile::CDRFileHeader*)pCur; - pCur = (char*)(&h + 1); - h.lSignature = h.SIGNATURE; - h.nVersionMadeBy = nBaseVersion + (ZipFile::CREATOR_MSDOS << 8); - h.nVersionNeeded = nBaseVersion; - h.nFlags = 0; - h.nMethod = it->pFileEntry->nMethod; - h.nLastModTime = it->pFileEntry->nLastModTime; - h.nLastModDate = it->pFileEntry->nLastModDate; - h.desc = it->pFileEntry->desc; - h.nFileNameLength = (ZipFile::ushort)it->strPath.length(); - h.nExtraFieldLength = 0; - h.nFileCommentLength = 0; - h.nDiskNumberStart = 0; - h.nAttrInternal = 0; - h.lAttrExternal = 0; - h.lLocalHeaderOffset = it->pFileEntry->nFileHeaderOffset; - - memcpy (pCur, it->strPath.c_str(), it->strPath.length()); - pCur += it->strPath.length(); - } - - ZipFile::CDREnd& e = *(ZipFile::CDREnd*)pCur; - e.lSignature = e.SIGNATURE; - e.nDisk = encryptedFlag ? (1 << 15) : 0; - e.nCDRStartDisk = 0; - e.numEntriesOnDisk = (ZipFile::ushort)this->size(); - e.numEntriesTotal = (ZipFile::ushort)this->size(); - e.lCDRSize = (ZipFile::ulong)(pCur - (char*)pBuffer); - e.lCDROffset = lCDROffset; - e.nCommentLength = 0; - - pCur = (char*)(&e + 1); - - return pCur - (char*)pBuffer; -} - - -ZipDir::FileEntryList::FileEntryList (FileEntryTree* pTree, unsigned lCDROffset) - : m_lCDROffset (lCDROffset) -{ - Add (pTree); -} - -void ZipDir::FileEntryList::Add(FileEntryTree* pTree) -{ - for (FileEntryTree::SubdirMap::iterator itDir = pTree->GetDirBegin(); itDir != pTree->GetDirEnd(); ++itDir) - { - Add(pTree->GetDirEntry(itDir)); - } - for (FileEntryTree::FileMap::iterator itFile = pTree->GetFileBegin(); itFile != pTree->GetFileEnd(); ++itFile) - { - insert(pTree->GetFileEntry(itFile)); - } -} - -// updates each file entry's info about the next file entry -void ZipDir::FileEntryList::RefreshEOFOffsets() -{ - iterator it, itNext = begin(); - - if (itNext != end()) - { - while ((it = itNext, ++itNext) != end()) - { - // start scan - (*it)->nEOFOffset = (*itNext)->nFileHeaderOffset; - } - // it is the last one.. - (*it)->nEOFOffset = m_lCDROffset; - } -} - - -void ZipDir::FileRecordList::Backup(std::vector& arrFiles) const -{ - arrFiles.resize (size()); - std::vector::iterator itTgt = arrFiles.begin(); - - for (const_iterator it = begin(); it != end(); ++it, ++itTgt) - { - *itTgt = *it->pFileEntry; - } -} - -void ZipDir::FileRecordList::Restore(const std::vector& arrFiles) -{ - if (arrFiles.size() == size()) - { - std::vector::const_iterator itTgt = arrFiles.begin(); - for (iterator it = begin(); it != end(); ++it, ++itTgt) - { - *it->pFileEntry = *itTgt; - } - } -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h deleted file mode 100644 index 58ce7312ae..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirList.h +++ /dev/null @@ -1,138 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H -#pragma once - -#include - -namespace ZipDir -{ - // this is the array of file entries that's convenient to use to construct CDR - struct FileRecord - { - string strPath; // relative path to the file inside zip - FileEntry* pFileEntry; // the file entry itself - - void ConstructFileRecord() - { - new (&strPath)string(); - } - }; - - struct FileDataRecord - : public FileRecord - { - FileDataRecord() { m_nRefCount = 0; } - void AddRef() { ++m_nRefCount; } - void Release() - { - if (--m_nRefCount <= 0) - { - Delete(); - } - } - - void Delete() - { - free (this); - } - - static FileDataRecord* New(const FileRecord& rThat) - { - FileDataRecord* pThis = (FileDataRecord*)malloc(sizeof(FileDataRecord) + rThat.pFileEntry->desc.lSizeCompressed); - - if (pThis) - { - pThis->m_nRefCount = 0; - pThis->ConstructFileRecord(); - *static_cast(pThis) = rThat; - } - return pThis; - } - - void* GetData() {return this + 1; } - - volatile signed int m_nRefCount; // the reference count - }; - - TYPEDEF_AUTOPTR(FileDataRecord); - typedef FileDataRecord_AutoPtr FileDataRecordPtr; - - struct FileRecordFileOffsetOrder - { - bool operator () (const FileRecord& left, const FileRecord& right) - { - return left.pFileEntry->nFileHeaderOffset < right.pFileEntry->nFileHeaderOffset; - } - }; - - // this is used for construction of CDR - class FileRecordList - : public std::vector - { - public: - FileRecordList(class FileEntryTree* pTree); - - struct ZipStats - { - // the size of the CDR in the file - size_t nSizeCDR; - // the size of the file data part (local file descriptors and file datas) - // if it's compacted - size_t nSizeCompactData; - }; - - // sorts the files by the physical offset in the zip file - void SortByFileOffset (); - - // returns the size of CDR in the zip file - ZipStats GetStats() const; - - // puts the CDR into the given block of mem - size_t MakeZipCDR(ZipFile::ulong lCDROffset, void* p, bool encryptedFlag) const; - - void Backup(std::vector& arrFiles) const; - void Restore(const std::vector& arrFiles); - - protected: - // recursively adds the files from this directory and subdirectories - // the strRoot contains the trailing slash - void AddAllFiles(class FileEntryTree* pTree, string strRoot = string()); - }; - - - struct FileEntryFileOffsetOrder - { - bool operator () (FileEntry* pLeft, FileEntry* pRight) const - { - return pLeft->nFileHeaderOffset < pRight->nFileHeaderOffset; - } - }; - - // this is used for refreshing EOFOffsets - class FileEntryList - : public std::set - { - public: - FileEntryList (class FileEntryTree* pTree, unsigned lCDROffset); - // updates each file entry's info about the next file entry - void RefreshEOFOffsets(); - protected: - void Add (class FileEntryTree* pTree); - unsigned m_lCDROffset; - }; -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRLIST_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp deleted file mode 100644 index 3d404ad62b..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirStructures.cpp +++ /dev/null @@ -1,670 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "smartptr.h" -#include -#include -#include -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include -#include -#include -#include - -using namespace ZipFile; - -ZipDir::FileEntry::FileEntry(const CDRFileHeader& header, const SExtraZipFileData& extra) -{ - this->desc = header.desc; - this->nFileHeaderOffset = header.lLocalHeaderOffset; - this->nFileDataOffset = INVALID_DATA_OFFSET; // we don't know yet - this->nMethod = header.nMethod; - this->nNameOffset = 0; // we don't know yet -#if defined(AZ_PLATFORM_WINDOWS) - this->nLastModTime = header.nLastModTime; - this->nLastModDate = header.nLastModDate; -#endif - this->nNTFS_LastModifyTime = extra.nLastModifyTime; - this->szOriginalFileName = 0; - - // make an estimation (at least this offset should be there), but we don't actually know yet - this->nEOFOffset = header.lLocalHeaderOffset + sizeof (ZipFile::LocalFileHeader) + header.nFileNameLength + header.desc.lSizeCompressed; -} - - - -// Uncompresses raw (without wrapping) data that is compressed with method 8 (deflated) in the Zip file -// returns one of the Z_* errors (Z_OK upon success) -// This function just mimics the standard uncompress (with modification taken from unzReadCurrentFile) -// with 2 differences: there are no 16-bit checks, and -// it initializes the inflation to start without waiting for compression method byte, as this is the -// way it's stored into zip file -int ZipDir::ZipRawUncompress (void* pUncompressed, unsigned long* pDestSize, const void* pCompressed, unsigned long nSrcSize) -{ - int nReturnCode = Z_OK; - - //check first 4 bytes to see what compression codec was used - if (CompressionCodec::TestForZSTDMagic(pCompressed)) - { - - size_t result = ZSTD_decompress(pUncompressed, *pDestSize, pCompressed, nSrcSize); - - if (ZSTD_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error decompressing using zstd: %s", ZSTD_getErrorName(result)); - nReturnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = result; - } - return nReturnCode; - } - else if (CompressionCodec::TestForLZ4Magic(pCompressed)) - { - size_t result; - LZ4F_decompressionContext_t dctx; - result = LZ4F_createDecompressionContext(&dctx, LZ4F_VERSION); - if (LZ4F_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error creating lz4 decompression context: %s", LZ4F_getErrorName(result)); - return Z_BUF_ERROR; - } - - size_t dstSize = (size_t)*pDestSize; - size_t srcSize = (size_t)nSrcSize; - result = LZ4F_decompress(dctx, pUncompressed, &dstSize, pCompressed, &srcSize, nullptr); - if (LZ4F_isError(result)) - { - AZ_Error("ZipDirStructures", false, "Error decompressing using lz4: %s", LZ4F_getErrorName(result)); - nReturnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = (long)dstSize; - } - - size_t freeCode = LZ4F_freeDecompressionContext(dctx); - if (LZ4F_isError(freeCode)) - { - //We are not changing the return code in this case, but it is good to record that releasing the - //decompression context failed. - AZ_Error("ZipDirStructures", false, "Error releasing lz4 decompression context: %s", LZ4F_getErrorName(freeCode)); - } - - return nReturnCode; - } - - - //Default to Zlib - z_stream stream; - stream.next_in = (Bytef*)pCompressed; - stream.avail_in = (uInt)nSrcSize; - - int err; - - stream.next_out = (Bytef*)pUncompressed; - stream.avail_out = (uInt) * pDestSize; - - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - - err = inflateInit2(&stream, -MAX_WBITS); - if (err != Z_OK) - { - return err; - } - - // for some strange reason, passing Z_FINISH doesn't work - - // it seems the stream isn't finished for some files and - // inflate returns an error due to stream-end-not-reached (though expected) problem - err = inflate(&stream, Z_SYNC_FLUSH); - if (err != Z_STREAM_END && err != Z_OK) - { - inflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - - *pDestSize = stream.total_out; - - err = inflateEnd(&stream); - return err; - -} - -// compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate) -// returns one of the Z_* errors (Z_OK upon success) -int ZipDir::ZipRawCompress(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel) -{ - z_stream stream; - int err; - - stream.next_out = reinterpret_cast(pCompressed); - - stream.next_in = const_cast(static_cast(pUncompressed)); - stream.avail_in = static_cast(nSrcSize); - - stream.avail_out = static_cast(*pDestSize); - - stream.zalloc = Z_NULL; - stream.zfree = Z_NULL; - stream.opaque = Z_NULL; - - err = deflateInit2 (&stream, nLevel, Z_DEFLATED, -MAX_WBITS, 9, Z_DEFAULT_STRATEGY); - if (err != Z_OK) - { - return err; - } - - err = deflate (&stream, Z_FINISH); - if (err != Z_STREAM_END) - { - deflateEnd(&stream); - return err == Z_OK ? Z_BUF_ERROR : err; - } - *pDestSize = stream.total_out; - - err = deflateEnd(&stream); - return err; -} - -int ZipDir::ZipRawCompressZSTD(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel) -{ - size_t result = ZSTD_compress(pCompressed, *pDestSize, pUncompressed, nSrcSize, nLevel); - - int err = Z_OK; - - if (ZSTD_isError(result)) - { - err = Z_BUF_ERROR; - } - else - { - *pDestSize = static_cast(result); - } - return err; -} - -int ZipDir::ZipRawCompressLZ4(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, [[maybe_unused]] int nLevel) -{ - int returnCode = Z_OK; - const size_t compressedBufferMaxSize = aznumeric_caster(*pDestSize); - size_t lz4_code = LZ4F_compressFrame(pCompressed, compressedBufferMaxSize, pUncompressed, aznumeric_caster(nSrcSize), nullptr); - - if (LZ4F_isError(lz4_code)) - { - returnCode = Z_BUF_ERROR; - } - else - { - *pDestSize = aznumeric_caster(lz4_code); - } - - return returnCode; -} - -int ZipDir::GetCompressedSizeEstimate(unsigned long uncompressedSize, CompressionCodec::Codec codec) -{ - switch (codec) - { - case CompressionCodec::Codec::ZLIB: - return (uncompressedSize + (uncompressedSize >> 3) + 32); - case CompressionCodec::Codec::ZSTD: - return ZSTD_compressBound(uncompressedSize); - case CompressionCodec::Codec::LZ4: - return LZ4F_compressFrameBound(uncompressedSize, nullptr); - default: - break; - } - return 0; -} - -ZipDir::ValidationResult ZipDir::ValidateZSTDCompressedDataWithOriginalData(const void* pUncompressed, unsigned long uncompressedSize, const void* pCompressed, unsigned long compressedSize) -{ - auto decompressedSize = ZSTD_getDecompressedSize(pCompressed, compressedSize); - ZipDir::ValidationResult testResult = ValidationResult::OK; - - if (decompressedSize != uncompressedSize) - { - testResult = ValidationResult::SIZE_MISMATCH; - } - else - { - void* decompressionBuffer = azmalloc(decompressedSize); - - size_t result = ZSTD_decompress(decompressionBuffer, decompressedSize, pCompressed, compressedSize); - - if (ZSTD_isError(result)) - { - AZ_Warning("Debug", false, "Error decompressing data with zstd: %s", ZSTD_getErrorName(result)); - testResult = ValidationResult::DATA_CORRUPTED; - } - else - { - if (memcmp(decompressionBuffer, pUncompressed, decompressedSize) != 0) - { - testResult = ValidationResult::DATA_NO_MATCH; - } - } - azfree(decompressionBuffer); - } - return testResult; -} - -// finds the subdirectory entry by the name, using the names from the name pool -// assumes: all directories are sorted in alphabetical order. -// case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) -ZipDir::DirEntry* ZipDir::DirHeader::FindSubdirEntry(const char* szName) -{ - if (this->numDirs) - { - const char* pNamePool = GetNamePool(); - DirEntrySortPred pred(pNamePool); - DirEntry* pBegin = GetSubdirEntry(0); - DirEntry* pEnd = pBegin + this->numDirs; - DirEntry* pEntry = std::lower_bound(pBegin, pEnd, szName, pred); -#if defined(LINUX) - if (pEntry != pEnd && !strcasecmp(szName, pEntry->GetName(pNamePool))) -#else - if (pEntry != pEnd && !strcmp(szName, pEntry->GetName(pNamePool))) -#endif - { - return pEntry; - } - } - return NULL; -} - -// finds the file entry by the name, using the names from the name pool -// assumes: all directories are sorted in alphabetical order. -// case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) -ZipDir::FileEntry* ZipDir::DirHeader::FindFileEntry(const char* szName) -{ - if (this->numFiles) - { - const char* pNamePool = GetNamePool(); - DirEntrySortPred pred(pNamePool); - FileEntry* pBegin = GetFileEntry(0); - FileEntry* pEnd = pBegin + this->numFiles; - FileEntry* pEntry = std::lower_bound(pBegin, pEnd, szName, pred); -#if defined(LINUX) - if (pEntry != pEnd && !strcasecmp(szName, pEntry->GetName(pNamePool))) -#else - if (pEntry != pEnd && !strcmp(szName, pEntry->GetName(pNamePool))) -#endif - { - return pEntry; - } - } - return NULL; -} - - -// tries to refresh the file entry from the given file (reads fromthere if needed) -// returns the error code if the operation was impossible to complete -ZipDir::ErrorEnum ZipDir::Refresh(FILE* f, FileEntry* pFileEntry, bool encryptedHeaders) -{ - if (pFileEntry->nFileDataOffset != pFileEntry->INVALID_DATA_OFFSET) - { - return ZD_ERROR_SUCCESS; - } - - if (pFileEntry->desc.lSizeCompressed == 0) - { - return ZD_ERROR_SUCCESS; - } - -#ifdef WIN32 - if (_fseeki64(f, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET)) -#else - if (fseek(f, pFileEntry->nFileHeaderOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (encryptedHeaders) - { - // with encrypted headers FileEntries should always be initialized from CDR. - return ZD_ERROR_IO_FAILED; - } - - // read the local file header and the name (for validation) into the buffer - LocalFileHeader fileHeader; - if (1 != fread (&fileHeader, sizeof(fileHeader), 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - - if (fileHeader.desc != pFileEntry->desc - || fileHeader.nMethod != pFileEntry->nMethod) - { - return ZD_ERROR_IO_FAILED; - } - - pFileEntry->nFileDataOffset = pFileEntry->nFileHeaderOffset + sizeof(LocalFileHeader) + fileHeader.nFileNameLength + fileHeader.nExtraFieldLength; - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset + pFileEntry->desc.lSizeCompressed; - return ZD_ERROR_SUCCESS; -} - -// writes into the file local header - without Extra data -// puts the new offset to the file data to the file entry -// in case of error can put INVALID_DATA_OFFSET into the data offset field of file entry -ZipDir::ErrorEnum ZipDir::WriteLocalHeader (FILE* f, FileEntry* pFileEntry, const char* szRelativePath, bool encrypt) -{ - size_t nFileNameLength = strlen(szRelativePath); - size_t nHeaderSize = sizeof(LocalFileHeader) + nFileNameLength; - - pFileEntry->nFileDataOffset = pFileEntry->nFileHeaderOffset + nHeaderSize; - pFileEntry->nEOFOffset = pFileEntry->nFileDataOffset + pFileEntry->desc.lSizeCompressed; - -#ifdef WIN32 - if (_fseeki64 (f, (__int64)pFileEntry->nFileHeaderOffset, SEEK_SET)) -#else - if (fseek (f, pFileEntry->nFileHeaderOffset, SEEK_SET)) -#endif - { - return ZD_ERROR_IO_FAILED; - } - - if (encrypt) - { - std::vector garbage; - garbage.resize(nHeaderSize); - for (size_t i = 0; i < nHeaderSize; ++i) - { - garbage[i] = rand() & 0xff; - } - - if (fwrite(&garbage[0], nHeaderSize, 1, f) != 1) - { - return ZD_ERROR_IO_FAILED; - } - } - else - { - LocalFileHeader h; - memset(&h, 0, sizeof(h)); - - h.lSignature = h.SIGNATURE; - h.nVersionNeeded = 10; - h.nFlags = 0; - h.nMethod = pFileEntry->nMethod; -#if defined(AZ_PLATFORM_WINDOWS) - h.nLastModDate = pFileEntry->nLastModDate; - h.nLastModTime = pFileEntry->nLastModTime; -#endif - h.desc = pFileEntry->desc; - h.nFileNameLength = (unsigned short)nFileNameLength; - h.nExtraFieldLength = 0; - - if (1 != fwrite(&h, sizeof(h), 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - - if (nFileNameLength > 0) - { - if (1 != fwrite (szRelativePath, nFileNameLength, 1, f)) - { - return ZD_ERROR_IO_FAILED; - } - } - } - - return ZD_ERROR_SUCCESS; -} - - -// conversion routines for the date/time fields used in Zip -ZipFile::ushort ZipDir::DOSDate(tm* t) -{ - return - ((t->tm_year - 80) << 9) - | (t->tm_mon << 5) - | t->tm_mday; -} - -ZipFile::ushort ZipDir::DOSTime(tm* t) -{ - return - ((t->tm_hour) << 11) - | ((t->tm_min) << 5) - | ((t->tm_sec) >> 1); -} - - - -// sets the current time to modification time -// calculates CRC32 for the new data -void ZipDir::FileEntry::OnNewFileData(void* pUncompressed, unsigned nSize, unsigned nCompressedSize, unsigned nCompressionMethod, bool bContinuous) -{ - time_t nTime; - time(&nTime); -#if defined(AZ_PLATFORM_WINDOWS) - tm t; - localtime_s(&t, &nTime); - this->nLastModTime = DOSTime(&t); - this->nLastModDate = DOSDate(&t); -#else - -#endif - this->nNTFS_LastModifyTime = AZStd::GetTimeUTCMilliSecond(); - - if (!bContinuous) - { - this->desc.lCRC32 = crc32(0L, Z_NULL, 0); - this->desc.lSizeCompressed = nCompressedSize; - this->desc.lSizeUncompressed = nSize; - } - - // we'll need CRC32 of the file to pack it - this->desc.lCRC32 = crc32(this->desc.lCRC32, (Bytef*)pUncompressed, nSize); - - this->nMethod = nCompressionMethod; -} - - -const char* ZipDir::DOSTimeCStr(ZipFile::ushort nTime) -{ - static char szBuf[16]; - azsprintf(szBuf, "%02d:%02d.%02d", (nTime >> 11), ((nTime & ((1 << 11) - 1)) >> 5), ((nTime & ((1 << 5) - 1)) << 1)); - return szBuf; -} - -const char* ZipDir::DOSDateCStr(ZipFile::ushort nTime) -{ - static char szBuf[32]; - azsprintf(szBuf, "%02d.%02d.%04d", (nTime & 0x1F), (nTime >> 5) & 0xF, (nTime >> 9) + 1980); - return szBuf; -} - -uint64 ZipDir::FileEntry::GetModificationTime() -{ - if (nNTFS_LastModifyTime != 0) - { - return nNTFS_LastModifyTime; - } - -#if defined(AZ_PLATFORM_WINDOWS) - // TODO/TIME: check and test - SYSTEMTIME st; - st.wYear = (nLastModDate >> 9) + 1980; - st.wMonth = ((nLastModDate >> 5) & 0xF); - st.wDay = (nLastModDate & 0x1F); - st.wHour = (nLastModTime >> 11); - st.wMinute = (nLastModTime >> 5) & 0x3F; - st.wSecond = (nLastModTime << 1) & 0x3F; - st.wMilliseconds = 0; - FILETIME ft; - SystemTimeToFileTime(&st, &ft); - LARGE_INTEGER lt; - lt.HighPart = ft.dwHighDateTime; - lt.LowPart = ft.dwLowDateTime; - return lt.QuadPart; -#else - return 0; -#endif -} - - -void ZipDir::FileEntry::SetFromFileTimeNTFS(int64 timestamp) -{ -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME ft; - ft.dwHighDateTime = timestamp >> 32; - ft.dwLowDateTime = timestamp & 0xFFFFFFFF; - - WORD dosTime, dosDate; - FileTimeToDosDateTime(&ft, &dosDate, &dosTime); - - nLastModDate = dosDate; - nLastModTime = dosTime; -#endif - nNTFS_LastModifyTime = timestamp; -} - -bool ZipDir::FileEntry::CompareFileTimeNTFS(int64 timestamp) -{ -#if defined(AZ_PLATFORM_WINDOWS) - FILETIME ft; - ft.dwHighDateTime = timestamp >> 32; - ft.dwLowDateTime = timestamp & 0xFFFFFFFF; - - WORD dosTime, dosDate; - FileTimeToDosDateTime(&ft, &dosDate, &dosTime); - - return (nLastModTime == dosTime && nLastModDate == dosDate); -#else - return (nNTFS_LastModifyTime == timestamp); -#endif -} - -const char* ZipDir::Error::getError() -{ - switch (this->nError) - { -#define DECLARE_ERROR(x) case ZD_ERROR_##x: \ - return #x; - DECLARE_ERROR(SUCCESS); - DECLARE_ERROR(IO_FAILED); - DECLARE_ERROR(UNEXPECTED); - DECLARE_ERROR(UNSUPPORTED); - DECLARE_ERROR(INVALID_SIGNATURE); - DECLARE_ERROR(ZIP_FILE_IS_CORRUPT); - DECLARE_ERROR(DATA_IS_CORRUPT); - DECLARE_ERROR(NO_CDR); - DECLARE_ERROR(CDR_IS_CORRUPT); - DECLARE_ERROR(NO_MEMORY); - DECLARE_ERROR(VALIDATION_FAILED); - DECLARE_ERROR(CRC32_CHECK); - DECLARE_ERROR(ZLIB_FAILED); - DECLARE_ERROR(ZLIB_CORRUPTED_DATA); - DECLARE_ERROR(ZLIB_NO_MEMORY); - DECLARE_ERROR(CORRUPTED_DATA); - DECLARE_ERROR(INVALID_CALL); - DECLARE_ERROR(NOT_IMPLEMENTED); - DECLARE_ERROR(FILE_NOT_FOUND); - DECLARE_ERROR(DIR_NOT_FOUND); - DECLARE_ERROR(NAME_TOO_LONG); - DECLARE_ERROR(INVALID_PATH); - DECLARE_ERROR(FILE_ALREADY_EXISTS); -#undef DECLARE_ERROR - default: - return "Unknown ZD_ERROR code"; - } -} - - -inline void btea(uint32* v, int n, uint32 const k[4]) -{ -#define TEA_DELTA 0x9e3779b9 -#define TEA_MX (((z >> 5 ^ y << 2) + (y >> 3 ^ z << 4)) ^ ((sum ^ y) + (k[(p & 3) ^ e] ^ z))) - uint32 y, z, sum; - unsigned p, rounds, e; - if (n > 1) /* Coding Part */ - { - rounds = 6 + 52 / n; - sum = 0; - z = v[n - 1]; - do - { - sum += TEA_DELTA; - e = (sum >> 2) & 3; - for (p = 0; p < n - 1; p++) - { - y = v[p + 1]; - z = v[p] += TEA_MX; - } - y = v[0]; - z = v[n - 1] += TEA_MX; - } while (--rounds); - } - else if (n < -1) /* Decoding Part */ - { - n = -n; - rounds = 6 + 52 / n; - sum = rounds * TEA_DELTA; - y = v[0]; - do - { - e = (sum >> 2) & 3; - for (p = n - 1; p > 0; p--) - { - z = v[p - 1]; - y = v[p] -= TEA_MX; - } - z = v[n - 1]; - y = v[0] -= TEA_MX; - } while ((sum -= TEA_DELTA) != 0); - } -#undef TEA_DELTA -#undef TEA_MX -} - -static inline void SwapByteOrder(uint32* values, size_t count) -{ - for (uint32* w = values, * e = values + count; w != e; ++w) - { - *w = (*w >> 24) + ((*w >> 8) & 0xff00) + ((*w & 0xff00) << 8) + (*w << 24); - } -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::Encrypt(char* buffer, size_t size, const EncryptionKey& key) -{ - uint32* intBuffer = (uint32*)buffer; - const int encryptedLen = size >> 2; - - SwapByteOrder(intBuffer, encryptedLen); - - btea(intBuffer, encryptedLen, key.key); - - SwapByteOrder(intBuffer, encryptedLen); -} - -////////////////////////////////////////////////////////////////////////// -void ZipDir::Decrypt(char* buffer, size_t size, const EncryptionKey& key) -{ - uint32* intBuffer = (uint32*)buffer; - const int encryptedLen = size >> 2; - - SwapByteOrder(intBuffer, encryptedLen); - - btea(intBuffer, -encryptedLen, key.key); - - SwapByteOrder(intBuffer, encryptedLen); -} - diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp b/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp deleted file mode 100644 index b35ae48b2a..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.cpp +++ /dev/null @@ -1,356 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "ZipFileFormat.h" -#include "zipdirstructures.h" -#include "ZipDirTree.h" - - -// Adds or finds the file. Returns non-initialized structure if it was added, -// or an IsInitialized() structure if it was found -ZipDir::FileEntry* ZipDir::FileEntryTree::Add(char* szPath, char* szUnifiedPath) -{ - // find the slash; if we found it, it's a subdirectory - add a subdirectory and - // add the file to it. - // if we didn't find it, it's a file - add the file to this dir - - char* pSlash; - for (pSlash = szPath; *pSlash && *pSlash != '/' && *pSlash != '\\'; ++pSlash) - { - continue; // find the next slash - } - char* pUnifiedSlash = szUnifiedPath + (pSlash - szPath); - assert(*pUnifiedSlash == '\0' || *pUnifiedSlash == '\\' || *pUnifiedSlash == '/'); - - if (*pUnifiedSlash) - { - FileEntryTree* pSubdir; - // we have a subdirectory here - create the file in it - { - char* unifiedDir = szUnifiedPath; - *pUnifiedSlash = '\0'; - - char* dir = szPath; - *pSlash = '\0'; - - SubdirMap::iterator it = m_mapDirs.find (unifiedDir); - if (it == m_mapDirs.end()) - { - pSubdir = new FileEntryTree(dir); - m_mapDirs.insert (SubdirMap::value_type(unifiedDir, pSubdir)); - } - else - { - pSubdir = it->second; - } - } - - return pSubdir->Add(pSlash + 1, pUnifiedSlash + 1); - } - else - { - ZipDir::FileEntry* result = &m_mapFiles[szUnifiedPath]; - result->szOriginalFileName = szPath; - return result; - } -} - -// adds a file to this directory -ZipDir::ErrorEnum ZipDir::FileEntryTree::Add (char* szPath, char* szUnifiedPath, const FileEntry& file) -{ - FileEntry* pFile = Add (szPath, szUnifiedPath); - if (!pFile) - { - return ZD_ERROR_INVALID_PATH; - } - if (pFile->IsInitialized()) - { - return ZD_ERROR_FILE_ALREADY_EXISTS; - } - // preserve original filename - const char* szOriginalFileName = pFile->szOriginalFileName; - *pFile = file; - pFile->szOriginalFileName = szOriginalFileName; - return ZD_ERROR_SUCCESS; -} - -// returns the number of files in this tree, including this and sublevels -unsigned ZipDir::FileEntryTree::NumFilesTotal() const -{ - unsigned numFiles = (unsigned)m_mapFiles.size(); - for (SubdirMap::const_iterator it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - numFiles += it->second->NumFilesTotal(); - } - return numFiles; -} - -#ifdef _TEST_ -size_t g_nSF = 0, g_nSS = 0, g_nSN = 0, g_nSNa = 0, g_nSH; -size_t g_nGF = 0, g_nGS = 0, g_nGN = 0, g_nGNa = 0, g_nGH; -#endif - -// returns the size required to serialize the tree -size_t ZipDir::FileEntryTree::GetSizeSerialized() const -{ - // the total size of name pool gets aligned on 4-byte boundary - size_t nSizeOfNamePool = 0; - size_t nSizeOfFileEntries = 0, nSizeOfDirEntries = 0; - size_t nSizeOfSubdirs = 0; - - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSizeOfDirEntries += sizeof(DirEntry); - const char* dirname = itDir->first; - nSizeOfNamePool += strlen(dirname) + 1; - nSizeOfSubdirs += itDir->second->GetSizeSerialized(); - } - - // for each file, we need to have an entry in the name pool and in the file list - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSizeOfFileEntries += sizeof(FileEntry); - const char* fname = itFile->first; - nSizeOfNamePool += strlen(fname) + 1; - } - - if (nSizeOfNamePool > 0xFFFF) - { - // we don't support so long names/directories - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Name pool larger then 65536 bytes"); - } - -#ifdef _TEST_ - g_nGF += nSizeOfFileEntries; - g_nGS += nSizeOfDirEntries; - g_nGN += nSizeOfNamePool; - g_nGNa += ((nSizeOfNamePool + 3) & ~3); - g_nGH += sizeof(DirHeader); -#endif - - return sizeof(DirHeader) + ((nSizeOfNamePool + 3) & ~3) + nSizeOfDirEntries + nSizeOfFileEntries + nSizeOfSubdirs; -} - -// serializes into the memory -size_t ZipDir::FileEntryTree::Serialize (DirHeader* pDirHeader) const -{ - pDirHeader->numDirs = (ZipFile::ushort)m_mapDirs.size(); - pDirHeader->numFiles = (ZipFile::ushort)m_mapFiles.size(); - DirEntry* pDirEntries = (DirEntry*)(pDirHeader + 1); - FileEntry* pFileEntries = (FileEntry*)(pDirEntries + pDirHeader->numDirs); - char* pNamePool = (char*)(pFileEntries + pDirHeader->numFiles); - - char* pName = pNamePool; - DirEntry* pDirEntry = pDirEntries; - FileEntry* pFileEntry = pFileEntries; - - SubdirMap::const_iterator itDir; - for (itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - pDirEntry->nNameOffset = (ZipFile::ulong)(pName - pNamePool); - size_t nNameLen = strlen(itDir->first); - memcpy (pName, itDir->first, nNameLen + 1); - pName += nNameLen + 1; - ++pDirEntry; - } - - assert ((FileEntry*)pDirEntry == pFileEntry); - - // for each file, we need to have an entry in the name pool and in the file list - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - *pFileEntry = itFile->second; - const char* filename = itFile->first; - pFileEntry->nNameOffset = (ZipFile::ushort)(pName - pNamePool); - size_t nNameLen = strlen(filename); - memcpy (pName, filename, nNameLen + 1); - pName += nNameLen + 1; - ++pFileEntry; - } - assert ((const char*)pFileEntry == pNamePool); - - // now the name pool is full. Go on and fill the other directories - const char* pSubdirHeader = (const char*)(((UINT_PTR)(pName + 3)) & ~3); - -#ifdef _TEST_ - g_nSF += pDirHeader->numFiles * sizeof(FileEntry); - g_nSS += pDirHeader->numDirs * sizeof(DirEntry); - g_nSN += pName - pNamePool; - g_nSNa += pSubdirHeader - pNamePool; - g_nSH += sizeof(DirHeader); -#endif - - pDirEntry = pDirEntries; - for (itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - pDirEntry->nDirHeaderOffset = (ZipFile::ulong)(pSubdirHeader - (const char*)pDirEntry); - pSubdirHeader += itDir->second->Serialize ((DirHeader*)pSubdirHeader); - ++pDirEntry; - } - - - return pSubdirHeader - (const char*)pDirHeader; -} - - - -void ZipDir::FileEntryTree::Clear() -{ - for (SubdirMap::iterator it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - delete it->second; - } - m_mapDirs.clear(); - m_mapFiles.clear(); -} - - -size_t ZipDir::FileEntryTree::GetSize() const -{ - size_t nSize = sizeof(*this); - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += strlen(itDir->first) + sizeof(*itDir) + itDir->second->GetSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += strlen(itFile->first) + sizeof(*itFile); - } - return nSize; -} - -size_t ZipDir::FileEntryTree::GetCompressedFileSize() const -{ - size_t nSize = 0; - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += itDir->second->GetCompressedFileSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += itFile->second.desc.lSizeCompressed; - } - return nSize; -} - -size_t ZipDir::FileEntryTree::GetUncompressedFileSize() const -{ - size_t nSize = 0; - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - nSize += itDir->second->GetUncompressedFileSize(); - } - - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - nSize += itFile->second.desc.lSizeUncompressed; - } - return nSize; -} - -bool ZipDir::FileEntryTree::IsOwnerOf (const FileEntry* pFileEntry) const -{ - for (FileMap::const_iterator itFile = m_mapFiles.begin(); itFile != m_mapFiles.end(); ++itFile) - { - if (pFileEntry == &itFile->second) - { - return true; - } - } - - for (SubdirMap::const_iterator itDir = m_mapDirs.begin(); itDir != m_mapDirs.end(); ++itDir) - { - if (itDir->second->IsOwnerOf (pFileEntry)) - { - return true; - } - } - - return false; -} - -ZipDir::FileEntryTree* ZipDir::FileEntryTree::FindDir(const char* szDirName) -{ - SubdirMap::iterator it = m_mapDirs.find (szDirName); - if (it == m_mapDirs.end()) - { - return NULL; - } - else - { - return it->second; - } -} - -ZipDir::FileEntryTree::FileMap::iterator ZipDir::FileEntryTree::FindFile (const char* szFileName) -{ - return m_mapFiles.find (szFileName); -} - -ZipDir::FileEntry* ZipDir::FileEntryTree::GetFileEntry(FileMap::iterator it) -{ - return it == GetFileEnd() ? NULL : &it->second; -} - -ZipDir::FileEntryTree* ZipDir::FileEntryTree::GetDirEntry(SubdirMap::iterator it) -{ - return it == GetDirEnd() ? NULL : it->second; -} - -const ZipDir::FileEntry* ZipDir::FileEntryTree::GetFileEntry(FileMap::const_iterator it) const -{ - return it == GetFileEnd() ? NULL : &it->second; -} - -const ZipDir::FileEntryTree* ZipDir::FileEntryTree::GetDirEntry(SubdirMap::const_iterator it) const -{ - return it == GetDirEnd() ? NULL : it->second; -} - -ZipDir::ErrorEnum ZipDir::FileEntryTree::RemoveDir (const char* szDirName) -{ - SubdirMap::iterator itRemove = m_mapDirs.find (szDirName); - if (itRemove == m_mapDirs.end()) - { - return ZD_ERROR_FILE_NOT_FOUND; - } - - delete itRemove->second; - m_mapDirs.erase (itRemove); - return ZD_ERROR_SUCCESS; -} - -ZipDir::ErrorEnum ZipDir::FileEntryTree::RemoveFile (const char* szFileName) -{ - FileMap::iterator itRemove = m_mapFiles.find (szFileName); - if (itRemove == m_mapFiles.end()) - { - return ZD_ERROR_FILE_NOT_FOUND; - } - - m_mapFiles.erase (itRemove); - return ZD_ERROR_SUCCESS; -} - -size_t ZipDir::FileEntryTree::NumDirsTotal() const -{ - size_t result = m_mapDirs.size(); - SubdirMap::const_iterator it; - for (it = m_mapDirs.begin(); it != m_mapDirs.end(); ++it) - { - result += it->second->NumDirsTotal(); - } - return result; -} diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h b/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h deleted file mode 100644 index 0e8af76142..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipDirTree.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H -#pragma once - - -namespace ZipDir -{ - class FileEntryTree - { - public: - FileEntryTree() - : m_originalName(0) {} - FileEntryTree(const char* originalName) - : m_originalName(originalName) {} - ~FileEntryTree () {Clear(); } - - // adds a file to this directory - // Function can modify szPath input - ErrorEnum Add (char* szPath, char* szUnifiedPath, const FileEntry& file); - - // Adds or finds the file. Returns non-initialized structure if it was added, - // or an IsInitialized() structure if it was found - // Function can modify szPath input - FileEntry* Add (char* szPath, char* szUnifiedPath); - - // returns the number of files in this tree, including this and sublevels - unsigned NumFilesTotal() const; - - // returns the size required to serialize the tree - size_t GetSizeSerialized() const; - - // serializes into the memory - size_t Serialize (DirHeader* pDir) const; - - void Clear(); - - void Swap (FileEntryTree& rThat) - { - m_mapDirs.swap (rThat.m_mapDirs); - m_mapFiles.swap (rThat.m_mapFiles); - } - - size_t GetSize() const; - - size_t GetCompressedFileSize() const; - size_t GetUncompressedFileSize() const; - - bool IsOwnerOf (const FileEntry* pFileEntry) const; - - // subdirectories - typedef std::map > SubdirMap; - // file entries - typedef std::map > FileMap; - - FileEntryTree* FindDir(const char* szDirName); - ErrorEnum RemoveDir (const char* szDirName); - ErrorEnum RemoveAll (){Clear(); return ZD_ERROR_SUCCESS; } - FileEntry* FindFileEntry (const char* szFileName); - FileMap::iterator FindFile (const char* szFileName); - ErrorEnum RemoveFile (const char* szFileName); - FileEntryTree* GetDirectory(){return this; } // the FileENtryTree is simultaneously an entry in the dir list AND the directory header - - FileMap::iterator GetFileBegin() {return m_mapFiles.begin(); } - FileMap::iterator GetFileEnd() {return m_mapFiles.end(); } - FileMap::const_iterator GetFileBegin() const {return m_mapFiles.begin(); } - FileMap::const_iterator GetFileEnd() const {return m_mapFiles.end(); } - unsigned NumFiles() const {return (unsigned)m_mapFiles.size(); } - - SubdirMap::iterator GetDirBegin() {return m_mapDirs.begin(); } - SubdirMap::iterator GetDirEnd() {return m_mapDirs.end(); } - SubdirMap::const_iterator GetDirBegin() const {return m_mapDirs.begin(); } - SubdirMap::const_iterator GetDirEnd() const {return m_mapDirs.end(); } - size_t NumDirsTotal() const; - - const char* GetFileName(FileMap::iterator it) {return it->first; } - const char* GetDirName(SubdirMap::iterator it) {return it->first; } - const char* GetOriginalName() const{ return m_originalName; } - - FileEntry* GetFileEntry(FileMap::iterator it); - FileEntryTree* GetDirEntry(SubdirMap::iterator it); - const FileEntry* GetFileEntry(FileMap::const_iterator it) const; - const FileEntryTree* GetDirEntry(SubdirMap::const_iterator it) const; - - protected: - SubdirMap m_mapDirs; - FileMap m_mapFiles; - const char* m_originalName; - }; -} -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRTREE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFile.h b/Code/Tools/CryCommonTools/ZipDir/ZipFile.h deleted file mode 100644 index 5e1f78050c..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFile.h +++ /dev/null @@ -1,19 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H -#pragma once - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILE_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h b/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h deleted file mode 100644 index 3f2083de0f..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat.h +++ /dev/null @@ -1,388 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H -#pragma once - -#include -#include - -#if AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 -#pragma pack(push) -#pragma pack(1) -#define PACK_GCC -#else -#define PACK_GCC __PACKED -#endif - -namespace ZipFile -{ - typedef unsigned int ulong; - typedef unsigned short ushort; - - // General-purpose bit field flags - enum - { - GPF_ENCRYPTED = 1 << 0, // If set, indicates that the file is encrypted. - GPF_DATA_DESCRIPTOR = 1 << 3, // if set, the CRC32 and sizes aren't set in the file header, but only in the data descriptor following compressed data - GPF_RESERVED_8_ENHANCED_DEFLATING = 1 << 4, // Reserved for use with method 8, for enhanced deflating. - GPF_COMPRESSED_PATCHED = 1 << 5, // the file is compressed patched data - }; - - // compression methods - enum - { - METHOD_STORE = 0, // The file is stored (no compression) - METHOD_SHRINK = 1, // The file is Shrunk - METHOD_REDUCE_1 = 2, // The file is Reduced with compression factor 1 - METHOD_REDUCE_2 = 3, // The file is Reduced with compression factor 2 - METHOD_REDUCE_3 = 4, // The file is Reduced with compression factor 3 - METHOD_REDUCE_4 = 5, // The file is Reduced with compression factor 4 - METHOD_IMPLODE = 6, // The file is Imploded - METHOD_TOKENIZE = 7, // Reserved for Tokenizing compression algorithm - METHOD_DEFLATE = 8, // The file is Deflated - METHOD_DEFLATE64 = 9, // Enhanced Deflating using Deflate64(tm) - METHOD_IMPLODE_PKWARE = 10, // PKWARE Date Compression Library Imploding - METHOD_DEFLATE_AND_ENCRYPT = 11 // Deflate + Custom encryption - }; - - // version numbers - enum - { - VERSION_DEFAULT = 10, // Default value - - VERSION_TYPE_VOLUMELABEL = 11, // File is a volume label - VERSION_TYPE_FOLDER = 20, // File is a folder (directory) - VERSION_TYPE_PATCHDATASET = 27, // File is a patch data set - VERSION_TYPE_ZIP64 = 45, // File uses ZIP64 format extensions - - VERSION_COMPRESSION_DEFLATE = 20, // File is compressed using Deflate compression - VERSION_COMPRESSION_DEFLATE64 = 21, // File is compressed using Deflate64(tm) - VERSION_COMPRESSION_DCLIMPLODE = 25, // File is compressed using PKWARE DCL Implode - VERSION_COMPRESSION_BZIP2 = 46, // File is compressed using BZIP2 compression* - VERSION_COMPRESSION_LZMA = 63, // File is compressed using LZMA - VERSION_COMPRESSION_PPMD = 63, // File is compressed using PPMd+ - - VERSION_ENCRYPTION_PKWARE = 20, // File is encrypted using traditional PKWARE encryption - VERSION_ENCRYPTION_DES = 50, // File is encrypted using DES - VERSION_ENCRYPTION_3DES = 50, // File is encrypted using 3DES - VERSION_ENCRYPTION_RC2 = 50, // File is encrypted using original RC2 encryption - VERSION_ENCRYPTION_RC4 = 50, // File is encrypted using RC4 encryption - VERSION_ENCRYPTION_AES = 51, // File is encrypted using AES encryption - VERSION_ENCRYPTION_RC2C = 51, // File is encrypted using corrected RC2 encryption** - VERSION_ENCRYPTION_RC4C = 52, // File is encrypted using corrected RC2-64 encryption** - VERSION_ENCRYPTION_NOOAEP = 61, // File is encrypted using non-OAEP key wrapping*** - VERSION_ENCRYPTION_CDR = 62, // Central directory encryption - VERSION_ENCRYPTION_BLOWFISH = 63, // File is encrypted using Blowfish - VERSION_ENCRYPTION_TWOFISH = 63, // File is encrypted using Twofish - }; - - // creator numbers - enum - { - CREATOR_MSDOS = 0, // MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems) - CREATOR_AMIGA = 1, // Amiga - CREATOR_OpenVMS = 2, // OpenVMS - CREATOR_UNIX = 3, // UNIX - CREATOR_VM = 4, // VM/CMS - CREATOR_ATARI = 5, // Atari ST - CREATOR_OS2 = 6, // OS/2 H.P.F.S. - CREATOR_MACINTOSH = 7, // Macintosh - CREATOR_ZSYSTEM = 8, // Z-System - CREATOR_CPM = 9, // CP/M - CREATOR_WINDOWS = 10, // Windows NTFS - CREATOR_MVS = 11, // MVS (OS/390 - Z/OS) - CREATOR_VSE = 12, // VSE - CREATOR_ACORN = 13, // Acorn Risc - CREATOR_VFAT = 14, // VFAT - CREATOR_AMVS = 15, // alternate MVS - CREATOR_BEOS = 16, // BeOS - CREATOR_TANDEM = 17, // Tandem - CREATOR_OS400 = 18, // OS/400 - CREATOR_OSX = 19, // OS X (Darwin) - - CREATOR_UNUSED = 20, // 20 thru 255 - unused - }; - - enum - { - ZIP64_SEE_EXTENSION = -1 // If an archive is in ZIP64 format - // and a value in a field is 0xFFFFFFFF (or 0xFFFF), the size will be - // in the corresponding 8 byte (or 4 byte) ZIP64 extended information. - }; - - // end of Central Directory Record - // followed by the .zip file comment (variable size, can be empty, obtained from nCommentLength) - struct CDREnd - { - enum - { - SIGNATURE = 0x06054b50 - }; - ulong lSignature; // end of central dir signature 4 bytes (0x06054b50) - ushort nDisk; // number of this disk 2 bytes - ushort nCDRStartDisk; // number of the disk with the start of the central directory 2 bytes - ushort numEntriesOnDisk; // total number of entries in the central directory on this disk 2 bytes - ushort numEntriesTotal; // total number of entries in the central directory 2 bytes - ulong lCDRSize; // size of the central directory 4 bytes - ulong lCDROffset; // offset of start of central directory with respect to the starting disk number 4 bytes - ushort nCommentLength; // .ZIP file comment length 2 bytes - - AUTO_STRUCT_INFO - - // .ZIP file comment (variable size, can be empty) follows - } PACK_GCC; - - // end of Central Directory Record - // followed by the zip64 extensible data sector (variable size, can be empty, obtained from nExtDataLength) - struct CDREnd_ZIP64 - { - enum - { - SIGNATURE = 0x06064b50 - }; - ulong lSignature; // end of central dir signature 4 bytes (0x06064b50) - uint64 nExtDataLength; // The value stored into the "size of zip64 end of central directory record" should be the size of the remaining record and should not include the leading 12 bytes. 8 bytes - ushort nVersionMadeBy; // version made by 2 bytes - ushort nVersionNeeded; // version needed to extract 2 bytes - ulong nDisk; // number of this disk 4 bytes - ulong nCDRStartDisk; // number of the disk with the start of the central directory 4 bytes - uint64 numEntriesOnDisk; // total number of entries in the central directory on this disk 8 bytes - uint64 numEntriesTotal; // total number of entries in the central directory 8 bytes - uint64 lCDRSize; // size of the central directory 8 bytes - uint64 lCDROffset; // offset of start of central directory with respect to the starting disk number 8 bytes - - AUTO_STRUCT_INFO - - // zip64 extensible data sector (variable size, can be empty) follows - } PACK_GCC; - - // end of Central Directory Locator - struct CDRLocator_ZIP64 - { - enum - { - SIGNATURE = 0x07064b50 - }; - ulong lSignature; // end of central loc signature 4 bytes (0x07064b50) - ulong nCDR64StartDisk; // number of the disk with the start of the zip64 end of central directory 4 bytes - uint64 lCDR64EndOffset; // relative offset of the zip64 end of central directory record 8 bytes - ulong nDisks; // number of disks 4 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; - - // This descriptor exists only if bit 3 of the general - // purpose bit flag is set (see below). It is byte aligned - // and immediately follows the last byte of compressed data. - // This descriptor is used only when it was not possible to - // seek in the output .ZIP file, e.g., when the output .ZIP file - // was standard output or a non seekable device. For Zip64 format - // archives, the compressed and uncompressed sizes are 8 bytes each. - struct DataDescriptor - { - ulong lCRC32; // crc-32 4 bytes - ulong lSizeCompressed; // compressed size 4 bytes - ulong lSizeUncompressed; // uncompressed size 4 bytes - - bool operator == (const DataDescriptor& d) const - { - return lCRC32 == d.lCRC32 && lSizeCompressed == d.lSizeCompressed && lSizeUncompressed == d.lSizeUncompressed; - } - bool operator != (const DataDescriptor& d) const - { - return lCRC32 != d.lCRC32 || lSizeCompressed != d.lSizeCompressed || lSizeUncompressed != d.lSizeUncompressed; - } - - bool IsZIP64([[maybe_unused]] const DataDescriptor& d) const - { - return lSizeCompressed == (ulong)ZIP64_SEE_EXTENSION || lSizeUncompressed == (ulong)ZIP64_SEE_EXTENSION; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // When compressing files, compressed and uncompressed sizes - // should be stored in ZIP64 format (as 8 byte values) when a - // file's size exceeds 0xFFFFFFFF. However ZIP64 format may be - // used regardless of the size of a file. When extracting, if - // the zip64 extended information extra field is present for - // the file the compressed and uncompressed sizes will be 8 - // byte values. - struct DataDescriptor_ZIP64 - { - ulong lCRC32; // crc-32 4 bytes - uint64 lSizeCompressed; // compressed size 8 bytes - uint64 lSizeUncompressed; // uncompressed size 8 bytes - - bool operator == (const DataDescriptor& d) const - { - return lCRC32 == d.lCRC32 && lSizeCompressed == d.lSizeCompressed && lSizeUncompressed == d.lSizeUncompressed; - } - bool operator != (const DataDescriptor& d) const - { - return lCRC32 != d.lCRC32 || lSizeCompressed != d.lSizeCompressed || lSizeUncompressed != d.lSizeUncompressed; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // the File Header as it appears in the CDR - // followed by: - // file name (variable size) - // extra field (variable size) - // file comment (variable size) - struct CDRFileHeader - { - enum - { - SIGNATURE = 0x02014b50 - }; - ulong lSignature; // central file header signature 4 bytes (0x02014b50) - ushort nVersionMadeBy; // version made by 2 bytes - ushort nVersionNeeded; // version needed to extract 2 bytes - ushort nFlags; // general purpose bit flag 2 bytes - ushort nMethod; // compression method 2 bytes - ushort nLastModTime; // last mod file time 2 bytes - ushort nLastModDate; // last mod file date 2 bytes - DataDescriptor desc; - ushort nFileNameLength; // file name length 2 bytes - ushort nExtraFieldLength; // extra field length 2 bytes - ushort nFileCommentLength; // file comment length 2 bytes - ushort nDiskNumberStart; // disk number start 2 bytes - ushort nAttrInternal; // internal file attributes 2 bytes - ulong lAttrExternal; // external file attributes 4 bytes - - // This is the offset from the start of the first disk on - // which this file appears, to where the local header should - // be found. If an archive is in zip64 format and the value - // in this field is 0xFFFFFFFF, the size will be in the - // corresponding 8 byte zip64 extended information extra field. - enum - { - ZIP64_LOCAL_HEADER_OFFSET = 0xFFFFFFFF - }; - ulong lLocalHeaderOffset; // relative offset of local header 4 bytes - - bool IsZIP64([[maybe_unused]] const CDRFileHeader& d) const - { - return desc.IsZIP64(desc) || nDiskNumberStart == (ushort)ZIP64_SEE_EXTENSION || lLocalHeaderOffset == (ulong)ZIP64_SEE_EXTENSION; - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - - // this is the local file header that appears before the compressed data - // followed by: - // file name (variable size) - // extra field (variable size) - struct LocalFileHeader - { - enum - { - SIGNATURE = 0x04034b50 - }; - ulong lSignature; // local file header signature 4 bytes (0x04034b50) - ushort nVersionNeeded; // version needed to extract 2 bytes - ushort nFlags; // general purpose bit flag 2 bytes - ushort nMethod; // compression method 2 bytes - ushort nLastModTime; // last mod file time 2 bytes - ushort nLastModDate; // last mod file date 2 bytes - DataDescriptor desc; - ushort nFileNameLength; // file name length 2 bytes - ushort nExtraFieldLength; // extra field length 2 bytes - - bool IsZIP64([[maybe_unused]] const LocalFileHeader& d) const - { - return desc.IsZIP64(desc); - } - - AUTO_STRUCT_INFO - } PACK_GCC; - - // compression methods - enum EExtraHeaderID - { - EXTRA_ZIP64 = 0x0001, // ZIP64 extended information extra field - EXTRA_NTFS = 0x000a, // NTFS - EXTRA_UNIX = 0x000d, // UNIX - EXTRA_PATCH = 0x000f, // Patch Descriptor - }; - - ////////////////////////////////////////////////////////////////////////// - // header1+data1 + header2+data2 . . . - // Each header should consist of: - // Header ID - 2 bytes - // Data Size - 2 bytes - struct ExtraFieldHeader - { - ushort headerID; - ushort dataSize; - - AUTO_STRUCT_INFO - } PACK_GCC; - - struct ExtraNTFSHeader - { - ulong reserved; // 4 bytes. - ushort attrTag; // 2 bytes. - ushort attrSize; // 2 bytes. - - AUTO_STRUCT_INFO - } PACK_GCC; - - ////////////////////////////////////////////////////////////////////////// - // The following is the layout of the zip64 extended - // information "extra" block. If one of the size or - // offset fields in the Local or Central directory - // record is too small to hold the required data, - // a Zip64 extended information record is created. - // The order of the fields in the zip64 extended - // information record is fixed, but the fields MUST - // only appear if the corresponding Local or Central - // directory record field is set to 0xFFFF or 0xFFFFFFFF. - // - // The extended information in the Local header MUST include - // BOTH original and compressed file size fields. - - struct ExtraZIP64LocalFileHeader - { - // LocalFileHeader overrides - uint64 lSizeUncompressed; // uncompressed size 4->8 bytes - uint64 lSizeCompressed; // compressed size 4->8 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; - - struct ExtraZIP64CDRFileHeader - { - // CDRFileHeader overrides - uint64 lSizeUncompressed; // uncompressed size 4->8 bytes - uint64 lSizeCompressed; // compressed size 4->8 bytes - - uint64 lLocalHeaderOffset; // relative offset of local header 4->8 bytes - ulong nDiskNumberStart; // Number of the disk on which this file starts 2->4 bytes - - AUTO_STRUCT_INFO - } PACK_GCC; -} - -#undef PACK_GCC - -#if AZ_TRAIT_CRYCOMMONTOOLS_PACK_1 -#pragma pack(pop) -#endif - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_H diff --git a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h b/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h deleted file mode 100644 index 9f91eec49b..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/ZipFileFormat_info.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H -#pragma once - -#include "ZipFileFormat.h" - -STRUCT_INFO_BEGIN(ZipFile::CDREnd) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nCDRStartDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(numEntriesOnDisk, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(numEntriesTotal, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(lCDRSize, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lCDROffset, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCommentLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::CDREnd) - -STRUCT_INFO_BEGIN(ZipFile::CDREnd_ZIP64) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nExtDataLength, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nVersionMadeBy, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCDRStartDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(numEntriesOnDisk, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(numEntriesTotal, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lCDRSize, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lCDROffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_INFO_END(ZipFile::CDREnd_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::CDRLocator_ZIP64) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nCDR64StartDisk, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lCDR64EndOffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nDisks, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::CDRLocator_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::DataDescriptor) -STRUCT_VAR_INFO(lCRC32, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::DataDescriptor) - -STRUCT_INFO_BEGIN(ZipFile::DataDescriptor_ZIP64) -STRUCT_VAR_INFO(lCRC32, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_INFO_END(ZipFile::DataDescriptor_ZIP64) - -STRUCT_INFO_BEGIN(ZipFile::CDRFileHeader) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nVersionMadeBy, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nMethod, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModTime, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModDate, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(desc, TYPE_INFO(ZipFile::DataDescriptor)) -STRUCT_VAR_INFO(nFileNameLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nExtraFieldLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFileCommentLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nDiskNumberStart, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nAttrInternal, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(lAttrExternal, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(lLocalHeaderOffset, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::CDRFileHeader) - -STRUCT_INFO_BEGIN(ZipFile::LocalFileHeader) -STRUCT_VAR_INFO(lSignature, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(nVersionNeeded, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nMethod, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModTime, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nLastModDate, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(desc, TYPE_INFO(ZipFile::DataDescriptor)) -STRUCT_VAR_INFO(nFileNameLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(nExtraFieldLength, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::LocalFileHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraFieldHeader) -STRUCT_VAR_INFO(headerID, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(dataSize, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::ExtraFieldHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraNTFSHeader) -STRUCT_VAR_INFO(reserved, TYPE_INFO(ZipFile::ulong)) -STRUCT_VAR_INFO(attrTag, TYPE_INFO(ZipFile::ushort)) -STRUCT_VAR_INFO(attrSize, TYPE_INFO(ZipFile::ushort)) -STRUCT_INFO_END(ZipFile::ExtraNTFSHeader) - -STRUCT_INFO_BEGIN(ZipFile::ExtraZIP64Data) -STRUCT_VAR_INFO(lSizeUncompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lSizeCompressed, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(lLocalHeaderOffset, TYPE_INFO(ZipFile::uint64)) -STRUCT_VAR_INFO(nDiskNumberStart, TYPE_INFO(ZipFile::ulong)) -STRUCT_INFO_END(ZipFile::ExtraZIP64Data) - - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPFILEFORMAT_INFO_H diff --git a/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h b/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h deleted file mode 100644 index dac298c90c..0000000000 --- a/Code/Tools/CryCommonTools/ZipDir/zipdirstructures.h +++ /dev/null @@ -1,426 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// This file contains only the support definitions for CZipDir class -// implementation. This it to unload the ZipDir.h from secondary stuff. - -#ifndef CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H -#define CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H -#pragma once - -#include - -namespace ZipDir -{ - // possible errors occuring during the method execution - // to avoid clushing with the global Windows defines, we prefix these with ZD_ - enum ErrorEnum - { - ZD_ERROR_SUCCESS = 0, - ZD_ERROR_IO_FAILED, - ZD_ERROR_UNEXPECTED, - ZD_ERROR_UNSUPPORTED, - ZD_ERROR_INVALID_SIGNATURE, - ZD_ERROR_ZIP_FILE_IS_CORRUPT, - ZD_ERROR_DATA_IS_CORRUPT, - ZD_ERROR_NO_CDR, - ZD_ERROR_CDR_IS_CORRUPT, - ZD_ERROR_NO_MEMORY, - ZD_ERROR_VALIDATION_FAILED, - ZD_ERROR_CRC32_CHECK, - ZD_ERROR_ZLIB_FAILED, - ZD_ERROR_ZLIB_CORRUPTED_DATA, - ZD_ERROR_ZLIB_NO_MEMORY, - ZD_ERROR_CORRUPTED_DATA, - ZD_ERROR_INVALID_CALL, - ZD_ERROR_NOT_IMPLEMENTED, - ZD_ERROR_FILE_NOT_FOUND, - ZD_ERROR_DIR_NOT_FOUND, - ZD_ERROR_NAME_TOO_LONG, - ZD_ERROR_INVALID_PATH, - ZD_ERROR_FILE_ALREADY_EXISTS - }; - - // the error describes the reason of the error, as well as the error code, line of code where it happened etc. - struct Error - { - Error(ErrorEnum _nError, const char* _szDescription, const char* _szFunction, const char* _szFile, unsigned _nLine) - : nError(_nError) - , m_szDescription(_szDescription) - , szFunction(_szFunction) - , szFile(_szFile) - , nLine(_nLine) - { - } - - ErrorEnum nError; - const char* getError(); - - const char* getDescription() {return m_szDescription; } - const char* szFunction, * szFile; - unsigned nLine; - protected: - // the description of the error; if needed, will be made as a dynamic string - const char* m_szDescription; - }; - - //#define THROW_ZIPDIR_ERROR(ZD_ERR,DESC) throw Error (ZD_ERR, DESC, __FUNCTION__, __FILE__, __LINE__) - //#define THROW_ZIPDIR_ERROR(ZD_ERR,DESC) CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,DESC ) - -#define THROW_ZIPDIR_ERROR(ZD_ERR, DESC) - - struct EncryptionKey - { - uint32 key[4]; - - explicit EncryptionKey(const uint32 data[4]) - { - memcpy(key, data, sizeof(key)); - } - - EncryptionKey() - { - memset(key, 0, sizeof(key)); - } - }; - - // possible initialization methods - enum InitMethodEnum - { - // initialize as fast as possible, with minimal validation - ZD_INIT_FAST, - // after initialization, scan through all file headers, precache the actual file data offset values and validate the headers - ZD_INIT_FULL, - // scan all file headers and try to decompress the data, searching for corrupted files - ZD_INIT_VALIDATE, - // maximum level of validation, checks for integrity of the archive - ZD_INIT_VALIDATE_MAX = ZD_INIT_VALIDATE - }; - - typedef void* (* FnAlloc) (void* pUserData, unsigned nItems, unsigned nSize); - typedef void (* FnFree) (void* pUserData, void* pAddress); - - ////////////////////////////////////////////////////////////////////////// - // This structure contains the pointers to functions for memory management - // by default, it's initialized to default malloc/free -#if 0 - struct Allocator - { - FnAlloc fnAlloc; - FnFree fnFree; - void* pOpaque; - - static void* DefaultAlloc (void*, unsigned nItems, unsigned nSize) - { - return malloc (nItems * nSize); - } - - static void DefaultFree (void*, void* pAddress) - { - free (pAddress); - } - - void* Alloc (unsigned nItems, unsigned nSize) - { - return this->fnAlloc(this->pOpaque, nItems, nSize); - } - - void Free (void* pAddress) - { - this->fnFree (this->pOpaque, pAddress); - } - - // constructs the allocator object; by default, the stdlib functions are used - Allocator (FnAlloc fnAllocIn = DefaultAlloc, FnFree fnFreeIn = DefaultFree, void* pOpaqueIn = NULL) - : fnAlloc(fnAllocIn) - , fnFree (fnFreeIn) - , pOpaque(pOpaqueIn) - { - } - }; -#endif - // instance of this class just releases the memory when it's destructed - struct SmartHeapPtr - { - SmartHeapPtr() - : m_pAddress(NULL) - { - } - ~SmartHeapPtr() - { - Release(); - } - - void Attach (void* p) - { - Release(); - m_pAddress = p; - } - - void* Detach() - { - void* p = m_pAddress; - m_pAddress = NULL; - return p; - } - - void Release() - { - if (m_pAddress) - { - free(m_pAddress); - m_pAddress = NULL; - } - } - protected: - // the pointer to free - void* m_pAddress; - }; - - typedef SmartHeapPtr SmartPtr; - - // Uncompresses raw (without wrapping) data that is compressed with method 8 (deflated) in the Zip file - // returns one of the Z_* errors (Z_OK upon success) - extern int ZipRawUncompress (void* pUncompressed, unsigned long* pDestSize, const void* pCompressed, unsigned long nSrcSize); - - // compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate) - // returns one of the Z_* errors (Z_OK upon success), and the size in *pDestSize. the pCompressed buffer must be at least nSrcSize*1.001+12 size - - extern int ZipRawCompress (const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - extern int ZipRawCompressZSTD(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - extern int ZipRawCompressLZ4(const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel); - - //returns an estimate of the size of the data when compressed - extern int GetCompressedSizeEstimate(unsigned long uncompressedSize, CompressionCodec::Codec codec = CompressionCodec::Codec::ZLIB); - - enum class ValidationResult - { - OK = 0, - SIZE_MISMATCH, - DATA_CORRUPTED, - DATA_NO_MATCH - }; - //decompresses a zstd blob and compares with the original - returns true if original and uncompressed data match - ValidationResult ValidateZSTDCompressedDataWithOriginalData(const void* pUncompressed, unsigned long uncompressedSize, const void* pCompressed, unsigned long compressedSize); - - ////////////////////////////////////////////////////////////////////////// - struct SExtraZipFileData - { - SExtraZipFileData() - : nLastModifyTime(0) {} - - uint64 nLastModifyTime; - }; - - // this is the record about the file in the Zip file. - struct FileEntry - { - enum - { - INVALID_DATA_OFFSET = 0xFFFFFFFF - }; - - ZipFile::DataDescriptor desc; - ZipFile::ulong nFileHeaderOffset; // offset of the local file header - ZipFile::ulong nFileDataOffset; // offset of the packed info inside the file; NOTE: this can be INVALID_DATA_OFFSET, if not calculated yet! - ZipFile::ushort nMethod; // the method of compression (0 if no compression/store) - ZipFile::ushort nNameOffset; // offset of the file name in the name pool for the directory - - // the file modification times - ZipFile::ushort nLastModTime; - ZipFile::ushort nLastModDate; - - uint64 nNTFS_LastModifyTime; - - // the offset to the start of the next file's header - this - // can be used to calculate the available space in zip file - ZipFile::ulong nEOFOffset; - const char* szOriginalFileName; // original filename (for CacheRW) - - FileEntry() - : nFileHeaderOffset(INVALID_DATA_OFFSET) - , szOriginalFileName(0){} - FileEntry(const ZipFile::CDRFileHeader& header, const SExtraZipFileData& extra); - - bool IsInitialized () - { - // structure marked as non-initialized should have nFileHeaderOffset == INVALID_DATA_OFFSET - return nFileHeaderOffset != INVALID_DATA_OFFSET; - } - // returns the name of this file, given the pointer to the name pool - const char* GetName(const char* pNamePool) const - { - return pNamePool + nNameOffset; - } - - // sets the current time to modification time - // calculates CRC32 for the new data - void OnNewFileData(void* pUncompressed, unsigned nSize, unsigned nCompressedSize, unsigned nCompressionMethod, bool bContinuous); - - uint64 GetModificationTime(); - void SetFromFileTimeNTFS(int64 timestamp); - bool CompareFileTimeNTFS(int64 timestamp); - }; - - // tries to refresh the file entry from the given file (reads fromthere if needed) - // returns the error code if the operation was impossible to complete - extern ErrorEnum Refresh (FILE* f, FileEntry* pFileEntry, bool encrpytedHeaders); - - // writes into the file local header - without Extra data - // puts the new offset to the file data to the file entry - // in case of error can put INVALID_DATA_OFFSET into the data offset field of file entry - extern ErrorEnum WriteLocalHeader (FILE* f, FileEntry* pFileEntry, const char* szRelativePath, bool encrypt); - - // conversion routines for the date/time fields used in Zip - extern ZipFile::ushort DOSDate(tm*); - extern ZipFile::ushort DOSTime(tm*); - - extern const char* DOSTimeCStr(ZipFile::ushort nTime); - extern const char* DOSDateCStr(ZipFile::ushort nTime); - - struct DirHeader; - // this structure represents a subdirectory descriptor in the directory record. - // it points to the actual directory info (list of its subdirs and files), as well - // as on its name - struct DirEntry - { - ZipFile::ulong nDirHeaderOffset;// offset, in bytes, relative to this object, of the actual directory record header - ZipFile::ulong nNameOffset; // offset of the dir name in the name pool of the parent directory - // returns the name of this directory, given the pointer to the name pool of hte parent directory - const char* GetName(const char* pNamePool) const - { - return pNamePool + nNameOffset; - } - - // returns the pointer to the actual directory record. - // call this function only for the actual structure instance contained in a directory record and - // followed by the other directory records - const DirHeader* GetDirectory () const - { - return (const DirHeader*)(((const char*)this) + nDirHeaderOffset); - } - DirHeader* GetDirectory () - { - return (DirHeader*)(((char*)this) + nDirHeaderOffset); - } - }; - - // this is the head of the directory record - // the name pool follows straight the directory and file entries. - struct DirHeader - { - ZipFile::ushort numDirs; // number of directory entries - DirEntry structures - ZipFile::ushort numFiles; // number of file entries - FileEntry structures - - // returns the pointer to the name pool that follows this object - // you can only call this method for the structure instance actually followed by the dir record - const char* GetNamePool() const - { - return ((char*)(this + 1)) + (size_t)this->numDirs * sizeof(DirEntry) + (size_t)this->numFiles * sizeof(FileEntry); - } - char* GetNamePool() - { - return ((char*)(this + 1)) + (size_t)this->numDirs * sizeof(DirEntry) + (size_t)this->numFiles * sizeof(FileEntry); - } - - // returns the pointer to the i-th directory - // call this only for the actual instance of the structure at the head of dir record - const DirEntry* GetSubdirEntry(unsigned i) const - { - assert (i < numDirs); - return ((const DirEntry*)(this + 1)) + i; - } - DirEntry* GetSubdirEntry(unsigned i) - { - assert (i < numDirs); - return ((DirEntry*)(this + 1)) + i; - } - - // returns the pointer to the i-th file - // call this only for the actual instance of the structure at the head of dir record - const FileEntry* GetFileEntry (unsigned i) const - { - assert (i < numFiles); - return (const FileEntry*)(((const DirEntry*)(this + 1)) + numDirs) + i; - } - FileEntry* GetFileEntry (unsigned i) - { - assert (i < numFiles); - return (FileEntry*)(((DirEntry*)(this + 1)) + numDirs) + i; - } - - // finds the subdirectory entry by the name, using the names from the name pool - // assumes: all directories are sorted in alphabetical order. - // case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) - DirEntry* FindSubdirEntry(const char* szName); - - // finds the file entry by the name, using the names from the name pool - // assumes: all directories are sorted in alphabetical order. - // case-sensitive (must be lower-case if case-insensitive search in Win32 is performed) - FileEntry* FindFileEntry(const char* szName); - }; - - // this is the sorting predicate for directory entries - struct DirEntrySortPred - { - DirEntrySortPred (const char* pNamePool) - : m_pNamePool (pNamePool) - { - } - - bool operator () (const FileEntry& left, const FileEntry& right) const - { - return strcmp(left.GetName(m_pNamePool), right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const FileEntry& left, const char* szRight) const - { - return strcmp(left.GetName(m_pNamePool), szRight) < 0; - } - - bool operator () (const char* szLeft, const FileEntry& right) const - { - return strcmp(szLeft, right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const DirEntry& left, const DirEntry& right) const - { - return strcmp(left.GetName(m_pNamePool), right.GetName(m_pNamePool)) < 0; - } - - bool operator () (const DirEntry& left, const char* szName) const - { - return strcmp(left.GetName(m_pNamePool), szName) < 0; - } - - bool operator () (const char* szLeft, const DirEntry& right) const - { - return strcmp(szLeft, right.GetName(m_pNamePool)) < 0; - } - - const char* m_pNamePool; - }; - - inline void tolower (string& str) - { - for (size_t i = 0; i < str.length(); ++i) - { - const_cast(str[i]) = ::tolower(str[i]); - } - } - - void Encrypt(char* buffer, size_t size, const EncryptionKey& key); - void Decrypt(char* buffer, size_t size, const EncryptionKey& key); -} - -#endif // CRYINCLUDE_CRYCOMMONTOOLS_ZIPDIR_ZIPDIRSTRUCTURES_H diff --git a/Code/Tools/CryCommonTools/crycommontools_files.cmake b/Code/Tools/CryCommonTools/crycommontools_files.cmake index d68c49836a..204a65f907 100644 --- a/Code/Tools/CryCommonTools/crycommontools_files.cmake +++ b/Code/Tools/CryCommonTools/crycommontools_files.cmake @@ -10,45 +10,6 @@ # set(FILES - PakSystem.cpp - TempFilePakExtraction.cpp - IPakSystem.h - PakSystem.h - PakXmlFileBufferSource.h - TempFilePakExtraction.h - FileUtil.cpp - PathHelpers.cpp StringHelpers.cpp - FileUtil.h - MathHelpers.h - PathHelpers.h - PropertyHelpers.h - PropertyHelpers.cpp - SimpleStringPool.h - StealingThreadPool.cpp - StealingThreadPool.h StringHelpers.h - ThreadUtils.cpp - ZipDir/ZipDirCache.cpp - ZipDir/ZipDirCacheFactory.cpp - ZipDir/ZipDirCacheRW.cpp - ZipDir/ZipDirFind.cpp - ZipDir/ZipDirFindRW.cpp - ZipDir/ZipDirList.cpp - ZipDir/ZipDirStructures.cpp - ZipDir/ZipDirTree.cpp - ThreadUtils.h - ZipDir/ZipDir.h - ZipDir/ZipDirCache.h - ZipDir/ZipDirCacheFactory.h - ZipDir/ZipDirCacheRW.h - ZipDir/ZipDirFind.h - ZipDir/ZipDirFindRW.h - ZipDir/ZipDirList.h - ZipDir/zipdirstructures.h - ZipDir/ZipDirTree.h - ZipDir/ZipFile.h - ZipDir/ZipFileFormat.h - ZipDir/ZipFileFormat_info.h - SuffixUtil.h ) diff --git a/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake b/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake deleted file mode 100644 index 13f6d90d3c..0000000000 --- a/Code/Tools/CryCommonTools/crycommontools_tests_files.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - UnitTests/PathHelpersUnitTests.cpp - UnitTests/StringHelpersUnitTests.cpp -) diff --git a/Code/Tools/CryCommonTools/zlibstatd64.lib b/Code/Tools/CryCommonTools/zlibstatd64.lib deleted file mode 100644 index 779712e946..0000000000 --- a/Code/Tools/CryCommonTools/zlibstatd64.lib +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9d9f51c3e75a4e80f45ba176511a84257146d6bc7c61f0cd582343544fd30e7c -size 277480 diff --git a/Code/Tools/CryXML/CMakeLists.txt b/Code/Tools/CryXML/CMakeLists.txt deleted file mode 100644 index a154fb6bd5..0000000000 --- a/Code/Tools/CryXML/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -if (NOT PAL_TRAIT_BUILD_HOST_TOOLS) - return() -endif() -ly_add_target( - NAME CryXML MODULE - NAMESPACE Legacy - FILES_CMAKE - cryxml_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - . - COMPILE_DEFINITIONS - PRIVATE - CRYTOOLS - RESOURCE_COMPILER - BUILD_DEPENDENCIES - PRIVATE - 3rdParty::expat - Legacy::CryCommon - Legacy::CryCommonTools -) diff --git a/Code/Tools/CryXML/CryXML.cpp b/Code/Tools/CryXML/CryXML.cpp deleted file mode 100644 index 597c751b0d..0000000000 --- a/Code/Tools/CryXML/CryXML.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Defines the entry point for the DLL application. - - -#include "CryXML_precompiled.h" -#include "CryAssert_impl.h" -#include "ICryXML.h" -#include "XMLSerializer.h" -#include -#include - -class CryXML - : public ICryXML -{ -public: - CryXML(); - virtual void AddRef(); - virtual void Release(); - virtual IXMLSerializer* GetXMLSerializer(); - -private: - int nRefCount; - XMLSerializer serializer; -}; - -static CryXML* s_pCryXML = nullptr; - -#if defined(AZ_PLATFORM_WINDOWS) && !defined(AZ_MONOLITHIC_BUILD) -BOOL APIENTRY DllMain([[maybe_unused]] HANDLE hModule, [[maybe_unused]] DWORD ul_reason_for_call, [[maybe_unused]] LPVOID lpReserved) -{ - return TRUE; -} -#endif - -extern "C" DLL_EXPORT ICryXML * __stdcall GetICryXML() -{ - PREVENT_MODULE_AND_ENVIRONMENT_SYMBOL_STRIPPING - - if (!s_pCryXML) - { - s_pCryXML = new CryXML; - } - return s_pCryXML; -} - -CryXML::CryXML() - : nRefCount(0) -{ -} - -void CryXML::AddRef() -{ - ++this->nRefCount; -} - -void CryXML::Release() -{ - --this->nRefCount; - if (this->nRefCount == 0) - { - if (this == s_pCryXML) - { - s_pCryXML = nullptr; - } - delete this; - } -} - -IXMLSerializer* CryXML::GetXMLSerializer() -{ - return &this->serializer; -} - - -// STLPort requires folowing functions defined: - -// when using STL Port _STLP_DEBUG and _STLP_DEBUG_TERMINATE - avoid actually -// crashing (default terminator seems to kill the thread, which isn't nice). -#ifdef _STLP_DEBUG_TERMINATE -void __stl_debug_terminate(void) -{ - assert(0 && "STL Debug Error"); -} -#endif -#ifdef _STLP_DEBUG_MESSAGE -void __stl_debug_message(const char* format_str, ...) -{ - va_list __args; - va_start(__args, format_str); - vprintf(format_str, __args); - va_end(__args); -} -#endif //_STLP_DEBUG_MESSAGE diff --git a/Code/Tools/CryXML/CryXML.def b/Code/Tools/CryXML/CryXML.def deleted file mode 100644 index 6275474eab..0000000000 --- a/Code/Tools/CryXML/CryXML.def +++ /dev/null @@ -1,3 +0,0 @@ -LIBRARY CryXML -EXPORTS - GetICryXML @1 diff --git a/Code/Tools/CryXML/CryXML_precompiled.cpp b/Code/Tools/CryXML/CryXML_precompiled.cpp deleted file mode 100644 index 8bb231ffd1..0000000000 --- a/Code/Tools/CryXML/CryXML_precompiled.cpp +++ /dev/null @@ -1,14 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CryXML_precompiled.h" diff --git a/Code/Tools/CryXML/CryXML_precompiled.h b/Code/Tools/CryXML/CryXML_precompiled.h deleted file mode 100644 index b7f48067b1..0000000000 --- a/Code/Tools/CryXML/CryXML_precompiled.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// stdafx.h : include file for standard system include files, -// or project specific include files that are used frequently, but -// are changed infrequently -// -#pragma once - -#include - -#define CRY_ASSERT(condition) assert(condition) -#define CRY_ASSERT_TRACE(condition, message) assert(condition) -#define CRY_ASSERT_MESSAGE(condition, message) assert(condition) - -// Define this to prevent including CryAssert (there is no proper hook for turning this off, like the above). -#define CRYINCLUDE_CRYCOMMON_CRYASSERT_H - -#define CRY_STRING -#include - -#include "Cry_Math.h" diff --git a/Code/Tools/CryXML/ICryXML.h b/Code/Tools/CryXML/ICryXML.h deleted file mode 100644 index fddc95e60e..0000000000 --- a/Code/Tools/CryXML/ICryXML.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYXML_ICRYXML_H -#define CRYINCLUDE_CRYXML_ICRYXML_H -#pragma once - - -class IXMLSerializer; - -class ICryXML -{ -public: - virtual ~ICryXML() = default; - virtual void AddRef() = 0; - virtual void Release() = 0; - virtual IXMLSerializer* GetXMLSerializer() = 0; -}; - -// Prototype for the function that is exported by the DLL - use this function to -// get a pointer to an ICryXML object. The function is exported by name as GetICryXML(). -typedef ICryXML* (* FnGetICryXML)(); - -#endif // CRYINCLUDE_CRYXML_ICRYXML_H diff --git a/Code/Tools/CryXML/IXMLSerializer.h b/Code/Tools/CryXML/IXMLSerializer.h deleted file mode 100644 index 44347beb5b..0000000000 --- a/Code/Tools/CryXML/IXMLSerializer.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYXML_IXMLSERIALIZER_H -#define CRYINCLUDE_CRYXML_IXMLSERIALIZER_H -#pragma once - - -#include "IXml.h" -#include -class IXMLDataSink; -class IXMLDataSource; - -struct IXmlBufferSource -{ - virtual int Read(void* buffer, int size) const = 0; -}; - -class FileXmlBufferSource - : public IXmlBufferSource -{ -public: - FileXmlBufferSource(const char* path) - { - file = nullptr; - azfopen(&file, path, "r"); - } - ~FileXmlBufferSource() - { - if (file) - { - std::fclose(file); - } - } - - virtual int Read(void* buffer, int size) const - { - if (!file) - { - return 0; - } - return check_cast(std::fread(buffer, 1, size, file)); - } - -private: - mutable std::FILE* file; -}; - -class IXMLSerializer -{ -public: - virtual XmlNodeRef CreateNode(const char* tag) = 0; - virtual bool Write(XmlNodeRef root, const char* szFileName) = 0; - - virtual XmlNodeRef Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer) = 0; -}; - -#endif // CRYINCLUDE_CRYXML_IXMLSERIALIZER_H diff --git a/Code/Tools/CryXML/XML/xml.cpp b/Code/Tools/CryXML/XML/xml.cpp deleted file mode 100644 index 4c117b54c7..0000000000 --- a/Code/Tools/CryXML/XML/xml.cpp +++ /dev/null @@ -1,1400 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CryXML_precompiled.h" - -//#define _CRT_SECURE_NO_DEPRECATE 1 -//#define _CRT_NONSTDC_NO_DEPRECATE -#include - -#define XML_STATIC -#include -#include "xml.h" -#include "../IXMLSerializer.h" -#include "Util.h" -#include -#include -#include - -#include -#include -#include -#include - -///////////////////////////////////////////////////////////////////// -// String pool implementation (from expat). -///////////////////////////////////////////////////////////////////// -class CSimpleStringPool -{ -public: - enum - { - STD_BLOCK_SIZE = 4096 - }; - struct BLOCK - { - BLOCK* next; - int size; - char s[1]; - }; - unsigned int m_blockSize; - BLOCK* m_blocks; - const char* m_end; - char* m_ptr; - char* m_start; - int nUsedSpace; - int nUsedBlocks; - - CSimpleStringPool() - { - m_blockSize = STD_BLOCK_SIZE; - m_blocks = 0; - m_start = 0; - m_ptr = 0; - m_end = 0; - nUsedSpace = 0; - nUsedBlocks = 0; - } - ~CSimpleStringPool() - { - BLOCK* p = m_blocks; - while (p) - { - BLOCK* temp = p->next; - //nFree++; - CryModuleFree(p); - p = temp; - } - m_blocks = 0; - m_ptr = 0; - m_start = 0; - m_end = 0; - } - void SetBlockSize(unsigned int nBlockSize) - { - if (nBlockSize > 1024 * 1024) - { - nBlockSize = 1024 * 1024; - } - unsigned int size = 512; - while (size < nBlockSize) - { - size *= 2; - } - - m_blockSize = size; - } - char* Append(const char* ptr, int nStrLen) - { - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = Util::getMax(nStrLen + 1, (int)m_blockSize); - AllocBlock(nNewBlockSize); - memcpy(m_ptr, ptr, nStrLen); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } - char* ReplaceString(const char* str1, const char* str2) - { - int nStrLen1 = strlen(str1); - int nStrLen2 = strlen(str2); - - // undo ptr1 add. - if (m_ptr != m_start) - { - m_ptr = m_ptr - nStrLen1 - 1; - } - - assert(m_ptr == str1); - - int nStrLen = nStrLen1 + nStrLen2; - - char* ret = m_ptr; - if (m_ptr && nStrLen + 1 < (m_end - m_ptr)) - { - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - } - else - { - int nNewBlockSize = Util::getMax(nStrLen + 1, (int)m_blockSize); - if (m_ptr == m_start) - { - ReallocBlock(nNewBlockSize * 2); // Reallocate current block. - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - else - { - AllocBlock(nNewBlockSize); - memcpy(m_ptr, str1, nStrLen1); - memcpy(m_ptr + nStrLen1, str2, nStrLen2); - } - - m_ptr = m_ptr + nStrLen; - *m_ptr++ = 0; // add null termination. - ret = m_start; - } - nUsedSpace += nStrLen; - return ret; - } -private: - void AllocBlock(int blockSize) - { - //nMallocs++; - BLOCK* pBlock = (BLOCK*)CryModuleMalloc(offsetof(BLOCK, s) + blockSize * sizeof(char)); - if (!pBlock) - { - // no memory. - //CryError( "Out of memory" ); - m_ptr = 0; - m_start = 0; - m_end = 0; - return; - } - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - nUsedBlocks++; - } - void ReallocBlock(int blockSize) - { - BLOCK* pThisBlock = m_blocks; - BLOCK* pPrevBlock = m_blocks->next; - m_blocks = pPrevBlock; - //nMallocs++; - BLOCK* pBlock = (BLOCK*)CryModuleRealloc(pThisBlock, offsetof(BLOCK, s) + blockSize * sizeof(char)); - if (!pBlock) - { - // no memory. - //CryError( "Out of memory" ); - m_ptr = 0; - m_start = 0; - m_end = 0; - return; - } - pBlock->size = blockSize; - pBlock->next = m_blocks; - m_blocks = pBlock; - m_ptr = pBlock->s; - m_start = pBlock->s; - m_end = pBlock->s + blockSize; - } -}; - -////////////////////////////////////////////////////////////////////////// -static int __cdecl ascii_stricmp(const char* dst, const char* src) -{ - int f, l; - do - { - if (((f = (unsigned char)(*(dst++))) >= 'A') && (f <= 'Z')) - { - f -= 'A' - 'a'; - } - if (((l = (unsigned char)(*(src++))) >= 'A') && (l <= 'Z')) - { - l -= 'A' - 'a'; - } - } - while (f && (f == l)); - return(f - l); -} - -////////////////////////////////////////////////////////////////////////// -XmlStrCmpFunc g_pXmlStrCmp = &ascii_stricmp; - -////////////////////////////////////////////////////////////////////////// -class CXmlStringData - : public IXmlStringData -{ -public: - int m_nRefCount; - XmlString m_string; - - CXmlStringData() { m_nRefCount = 0; } - virtual void AddRef() { ++m_nRefCount; } - virtual void Release() - { - if (--m_nRefCount <= 0) - { - delete this; - } - } - - virtual const char* GetString() { return m_string.c_str(); }; - virtual size_t GetStringLength() { return m_string.size(); }; -}; - -class CXmlStringPool - : public IXmlStringPool -{ -public: - char* AddString(const char* str) { return m_stringPool.Append(str, (int)strlen(str)); } -private: - CSimpleStringPool m_stringPool; -}; - -/** -****************************************************************************** -* CXmlNode implementation. -****************************************************************************** -*/ - -void CXmlNode::DeleteThis() -{ - delete this; -} - -CXmlNode::~CXmlNode() -{ - // Clear parent pointer from childs. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - IXmlNode* node = *it; - ((CXmlNode*)node)->m_parent = 0; - } - m_pStringPool->Release(); -} - -CXmlNode::CXmlNode() -{ - m_tag = ""; - m_content = ""; - m_parent = 0; - m_nRefCount = 0; - m_pStringPool = 0; // must be changed later. -} - -CXmlNode::CXmlNode(const char* tag) -{ - m_content = ""; - m_parent = 0; - m_nRefCount = 0; - m_pStringPool = new CXmlStringPool; - m_pStringPool->AddRef(); - m_tag = m_pStringPool->AddString(tag); -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CXmlNode::createNode(const char* tag) -{ - CXmlNode* pNewNode = new CXmlNode; - pNewNode->m_pStringPool = m_pStringPool; - m_pStringPool->AddRef(); - pNewNode->m_tag = m_pStringPool->AddString(tag); - return XmlNodeRef(pNewNode); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setTag(const char* tag) -{ - m_tag = m_pStringPool->AddString(tag); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setContent(const char* str) -{ - m_content = str; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::isTag(const char* tag) const -{ - return g_pXmlStrCmp(tag, m_tag) == 0; -} - -const char* CXmlNode::getAttr(const char* key) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - return svalue; - } - return ""; -} - -bool CXmlNode::getAttr(const char* key, const char** value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - *value = svalue; - return true; - } - else - { - *value = ""; - return false; - } -} - -bool CXmlNode::haveAttr(const char* key) const -{ - XmlAttrConstIter it = GetAttrConstIterator(key); - if (it != m_attributes.end()) - { - return true; - } - return false; -} - -void CXmlNode::delAttr(const char* key) -{ - XmlAttrIter it = GetAttrIterator(key); - if (it != m_attributes.end()) - { - m_attributes.erase(it); - } -} - -void CXmlNode::removeAllAttributes() -{ - m_attributes.clear(); -} - -void CXmlNode::setAttr(const char* key, const char* value) -{ - XmlAttrIter it = GetAttrIterator(key); - if (it == m_attributes.end()) - { - XmlAttribute tempAttr; - tempAttr.key = m_pStringPool->AddString(key); - tempAttr.value = m_pStringPool->AddString(value); - m_attributes.push_back(tempAttr); - // Sort attributes. - //std::sort( m_attributes.begin(),m_attributes.end() ); - } - else - { - // If already exist, override this member. - it->value = m_pStringPool->AddString(value); - } -} - -void CXmlNode::setAttr(const char* key, int value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%d", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, unsigned int value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%d", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, float value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g", value); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, double value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g", value); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setAttr(const char* key, int64 value) -{ - char str[32]; - azsnprintf(str, sizeof(str), "%" PRId64, value); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::setAttr(const char* key, uint64 value, bool useHexFormat) -{ - char str[32]; - if (useHexFormat) - { - azsnprintf(str, sizeof(str), "%" PRIX64, value); - } - else - { - azsnprintf(str, sizeof(str), "%" PRIu64, value); - } - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Ang3& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec2& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g", value.x, value.y); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec2d& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g,%.17g", value.x, value.y); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec3& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec3d& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%.17g,%.17g,%.17g", value.x, value.y, value.z); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Vec4& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g,%g", value.x, value.y, value.z, value.w); - setAttr(key, str); -} - -void CXmlNode::setAttr(const char* key, const Quat& value) -{ - char str[128]; - azsnprintf(str, sizeof(str), "%g,%g,%g,%g", value.w, value.v.x, value.v.y, value.v.z); - setAttr(key, str); -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, int& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atoi(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, unsigned int& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = strtoul(svalue, NULL, 10); - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, int64& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - azsscanf(svalue, "%" PRId64, &value); - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, uint64& value, bool useHexFormat) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - if (useHexFormat) - { - azsscanf(svalue, "%" PRIX64, &value); - } - else - { - azsscanf(svalue, "%" PRIu64, &value); - } - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, bool& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atoi(svalue) != 0; - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, float& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = (float)atof(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, double& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - value = atof(svalue); - return true; - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Ang3& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z; - if (azsscanf(svalue, "%f,%f,%f", &x, &y, &z) == 3) - { - value(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec2& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y; - if (azsscanf(svalue, "%f,%f", &x, &y) == 2) - { - value = Vec2(x, y); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec2d& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - double x, y; - if (azsscanf(svalue, "%lf,%lf", &x, &y) == 2) - { - value = Vec2d(x, y); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec3& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z; - if (azsscanf(svalue, "%f,%f,%f", &x, &y, &z) == 3) - { - value(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec4& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float x, y, z, w; - if (azsscanf(svalue, "%f,%f,%f,%f", &x, &y, &z, &w) == 3) - { - value(x, y, z, w); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Vec3d& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - double x, y, z; - if (azsscanf(svalue, "%lf,%lf,%lf", &x, &y, &z) == 3) - { - value = Vec3d(x, y, z); - return true; - } - } - return false; -} - -bool CXmlNode::getAttr(const char* key, Quat& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - float w, x, y, z; - if (azsscanf(svalue, "%f,%f,%f,%f", &w, &x, &y, &z) == 4) - { - if (fabs(w) > VEC_EPSILON || fabs(x) > VEC_EPSILON || fabs(y) > VEC_EPSILON || fabs(z) > VEC_EPSILON) - { - //[AlexMcC|02.03.10] directly assign to members to avoid triggering the assert in Quat() with data from bad assets - value.w = w; - value.v = Vec3(x, y, z); - return value.IsValid(); - } - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttr(const char* key, ColorB& value) const -{ - const char* svalue = GetValue(key); - if (svalue) - { - unsigned int r, g, b, a = 255; - int numFound = azsscanf(svalue, "%u,%u,%u,%u", &r, &g, &b, &a); - if (numFound == 3 || numFound == 4) - { - // If we only found 3 values, a should be unchanged, and still be 255 - if (r < 256 && g < 256 && b < 256 && a < 256) - { - value = ColorB(r, g, b, a); - return true; - } - } - } - return false; -} - - -XmlNodeRef CXmlNode::findChild(const char* tag) const -{ - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - if ((*it)->isTag(tag)) - { - return *it; - } - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::deleteChild(const char* tag) -{ - for (XmlNodes::iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - if ((*it)->isTag(tag)) - { - m_childs.erase(it); - return; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::deleteChildAt(int nIndex) -{ - if (nIndex >= 0 && nIndex < (int)m_childs.size()) - { - m_childs.erase(m_childs.begin() + nIndex); - } -} - -//! Adds new child node. -void CXmlNode::addChild(const XmlNodeRef& node) -{ - assert(node != 0); - m_childs.push_back(node); - IXmlNode* n = node; - ((CXmlNode*)n)->m_parent = this; -}; - -void CXmlNode::setParent(const XmlNodeRef& inNewParent) -{ - // note, parent ptrs are not ref counted - IXmlNode* n = inNewParent; - m_parent = (CXmlNode*)n; -} - -void CXmlNode::insertChild(int inIndex, const XmlNodeRef& inNewChild) -{ - assert(inIndex >= 0 && inIndex <= getChildCount()); - assert(inNewChild != 0); - if (inIndex >= 0 && inIndex <= getChildCount() && inNewChild) - { - if (getChildCount() == 0) - { - addChild(inNewChild); - } - else - { - IXmlNode* pNode = ((IXmlNode*)inNewChild); - pNode->AddRef(); - m_childs.insert(m_childs.begin() + inIndex, pNode); - pNode->setParent(this); - } - } -} - -void CXmlNode::replaceChild(int inIndex, const XmlNodeRef& inNewChild) -{ - assert(inIndex >= 0 && inIndex < getChildCount()); - assert(inNewChild != 0); - if (inIndex >= 0 && inIndex < getChildCount() && inNewChild) - { - IXmlNode* wasChild = m_childs[inIndex]; - - if (wasChild->getParent() == this) - { - wasChild->setParent(XmlNodeRef()); // child is orphaned, will be freed by Release() below if this parent is last holding a reference to it - } - wasChild->Release(); - inNewChild->AddRef(); - m_childs[inIndex] = inNewChild; - inNewChild->setParent(this); - } -} - -XmlNodeRef CXmlNode::newChild(const char* tagName) -{ - XmlNodeRef node = createNode(tagName); - addChild(node); - return node; -} - -void CXmlNode::removeChild(const XmlNodeRef& node) -{ - XmlNodes::iterator it = std::find(m_childs.begin(), m_childs.end(), (IXmlNode*)node); - if (it != m_childs.end()) - { - m_childs.erase(it); - } -} - -void CXmlNode::removeAllChilds() -{ - m_childs.clear(); -} - -//! Get XML Node child nodes. -XmlNodeRef CXmlNode::getChild(int i) const -{ - assert(i >= 0 && i < (int)m_childs.size()); - return m_childs[i]; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::copyAttributes(XmlNodeRef fromNode) -{ - IXmlNode* inode = fromNode; - CXmlNode* n = (CXmlNode*)inode; - if (n->m_pStringPool == m_pStringPool) - { - m_attributes = n->m_attributes; - } - else - { - m_attributes.resize(n->m_attributes.size()); - for (int i = 0; i < (int)n->m_attributes.size(); i++) - { - m_attributes[i].key = m_pStringPool->AddString(n->m_attributes[i].key); - m_attributes[i].value = m_pStringPool->AddString(n->m_attributes[i].value); - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::getAttributeByIndex(int index, const char** key, const char** value) -{ - XmlAttributes::iterator it = m_attributes.begin(); - if (it != m_attributes.end()) - { - std::advance(it, index); - if (it != m_attributes.end()) - { - *key = it->key; - *value = it->value; - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CXmlNode::clone() -{ - CXmlNode* node = new CXmlNode; - node->m_pStringPool = m_pStringPool; - m_pStringPool->AddRef(); - node->m_tag = m_tag; - node->m_content = m_content; - // Clone attributes. - CXmlNode* n = (CXmlNode*)(IXmlNode*)node; - n->copyAttributes(this); - // Clone sub nodes. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - XmlNodeRef child = (*it)->clone(); - node->addChild(child); - } - - return node; -} - -////////////////////////////////////////////////////////////////////////// -static void AddTabsToString(XmlString& xml, int level) -{ - static const char* tabs[] = { - "", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - }; - // Add tabs. - if (level < sizeof(tabs) / sizeof(tabs[0])) - { - xml += tabs[level]; - } - else - { - for (int i = 0; i < level; i++) - { - xml += " "; - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CXmlNode::IsValidXmlString(const char* str) const -{ - if (strcspn(str, "\"\'&><") == strlen(str)) - { - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -XmlString CXmlNode::MakeValidXmlString(const XmlString& instr) const -{ - XmlString str = instr; - - // check if str contains any invalid characters - str.replace("&", "&"); - str.replace("\"", """); - str.replace("\'", "'"); - str.replace("<", "<"); - str.replace(">", ">"); - - return str; -} - -////////////////////////////////////////////////////////////////////////// -void CXmlNode::AddToXmlString(XmlString& xml, int level) const -{ - AddTabsToString(xml, level); - - // Begin Tag - if (m_attributes.empty()) - { - xml += "<"; - xml += m_tag; - if (*m_content == 0 && m_childs.empty()) - { - // Compact tag form. - xml += " />\n"; - return; - } - xml += ">"; - } - else - { - xml += "<"; - xml += m_tag; - xml += " "; - - // Put attributes. - for (XmlAttributes::const_iterator it = m_attributes.begin(); it != m_attributes.end(); ) - { - xml += it->key; - xml += "=\""; - if (IsValidXmlString(it->value)) - { - xml += it->value; - } - else - { - xml += MakeValidXmlString(it->value); - } - it++; - if (it != m_attributes.end()) - { - xml += "\" "; - } - else - { - xml += "\""; - } - } - if (*m_content == 0 && m_childs.empty()) - { - // Compact tag form. - xml += "/>\n"; - return; - } - xml += ">"; - } - - // Put node content. - if (IsValidXmlString(m_content)) - { - xml += m_content; - } - else - { - xml += MakeValidXmlString(m_content); - } - - if (m_childs.empty()) - { - xml += "\n"; - return; - } - - xml += "\n"; - - // Add sub nodes. - for (XmlNodes::const_iterator it = m_childs.begin(); it != m_childs.end(); ++it) - { - IXmlNode* node = *it; - ((CXmlNode*)node)->AddToXmlString(xml, level + 1); - } - - // Add tabs. - AddTabsToString(xml, level); - xml += "\n"; -} - -IXmlStringData* CXmlNode::getXMLData(int nReserveMem) const -{ - CXmlStringData* pStrData = new CXmlStringData; - pStrData->m_string.reserve(nReserveMem); - AddToXmlString(pStrData->m_string, 0); - return pStrData; -} - -XmlString CXmlNode::getXML(int level) const -{ - static XmlString xml; - xml = ""; - xml.reserve(6000000); - - AddToXmlString(xml, level); - return xml; -} - -bool CXmlNode::saveToFile(const char* fileName) -{ - XmlString xml = getXML(); - FILE* file = nullptr; - azfopen(&file, fileName, "wt"); - if (file) - { - const char* sxml = (const char*)xml; - fprintf(file, "%s", sxml); - fclose(file); - return true; - } - return false; -} - -/** -****************************************************************************** -* XmlParserImp class. -****************************************************************************** -*/ -class XmlParserImp - : public IXmlStringPool -{ -public: - explicit XmlParserImp(bool bRemoveNonessentialSpacesFromContent); - ~XmlParserImp(); - void beginParse(); - bool parse(const char* buffer, int bufLen); - XmlNodeRef endParse(XmlString& errorString); - - // Add new string to pool. - char* AddString(const char* str) { return m_stringPool.Append(str, (int)strlen(str)); } - //char* AddString( const char *str ) { return (char*)str; } - -protected: - void onStartElement(const char* tagName, const char** atts); - void onEndElement(const char* tagName); - void onRawData(const char* data); - - static void startElement(void* userData, const char* name, const char** atts) - { - ((XmlParserImp*)userData)->onStartElement(name, atts); - } - static void endElement(void* userData, const char* name) - { - ((XmlParserImp*)userData)->onEndElement(name); - } - static void characterData(void* userData, const char* s, int len) - { - char str[500000]; - if (len > sizeof(str) - 1) - { - assert(0); - len = sizeof(str) - 1; - } - memcpy(str, s, len); - str[len] = 0; - ((XmlParserImp*)userData)->onRawData(str); - } - - // First node will become root node. - std::vector nodeStack; - XmlNodeRef m_root; - - XML_Parser m_parser; - CSimpleStringPool m_stringPool; - bool m_bRemoveNonessentialSpacesFromContent; -}; - -/** -****************************************************************************** -* XmlParserImp -****************************************************************************** -*/ -void XmlParserImp::onStartElement(const char* tagName, const char** atts) -{ - XmlNodeRef parent; - CXmlNode* pCNode = new CXmlNode; - pCNode->m_pStringPool = this; - pCNode->m_pStringPool->AddRef(); - pCNode->m_tag = AddString(tagName); - - XmlNodeRef node = pCNode; - - if (!nodeStack.empty()) - { - parent = nodeStack.back(); - } - else - { - m_root = node; - } - nodeStack.push_back(node); - - if (parent) - { - parent->addChild(node); - } - - uint64 line = XML_GetCurrentLineNumber((XML_Parser)m_parser); - node->setLine(line > INT_MAX ? INT_MAX : (int)line); - - // Call start element callback. - int i = 0; - int numAttrs = 0; - while (atts[i] != 0) - { - numAttrs++; - i += 2; - } - if (numAttrs > 0) - { - i = 0; - pCNode->m_attributes.resize(numAttrs); - int nAttr = 0; - while (atts[i] != 0) - { - pCNode->m_attributes[nAttr].key = AddString(atts[i]); - pCNode->m_attributes[nAttr].value = AddString(atts[i + 1]); - nAttr++; - i += 2; - } - // Sort attributes. - //std::sort( pCNode->m_attributes.begin(),pCNode->m_attributes.end() ); - } -} - -void XmlParserImp::onEndElement([[maybe_unused]] const char* tagName) -{ - assert(!nodeStack.empty()); - if (!nodeStack.empty()) - { - nodeStack.pop_back(); - } -} - -void XmlParserImp::onRawData(const char* const data) -{ - if (data && data[0]) - { - CXmlNode* const node = (CXmlNode*)(IXmlNode*)nodeStack.back(); - - if (!m_bRemoveNonessentialSpacesFromContent) - { - // Implementation note: Skipping spaces in beginning (even although - // m_bRemoveNonessentialSpacesFromContent is false) allows us - // to avoid having lot of "space only" content nodes - if (node->m_content.empty()) - { - const size_t len = strlen(data); - const size_t spaceCount = strspn(data, "\r\n\t "); - - if (spaceCount < len) - { - node->m_content += &data[spaceCount]; - } - } - else - { - node->m_content += data; - } - } - else - { - const size_t len = strlen(data); - const size_t spaceCount = strspn(data, "\r\n\t "); - - if ((spaceCount > 0) && (!node->m_content.empty())) - { - node->m_content += " "; - } - - if (spaceCount < len) - { - node->m_content += &data[spaceCount]; - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -static void* custom_xml_malloc(size_t nSize) -{ - return CryModuleMalloc(nSize); -} -static void* custom_xml_realloc(void* p, size_t nSize) -{ - return CryModuleRealloc(p, nSize); -} -static void custom_xml_free(void* p) -{ - CryModuleFree(p); -} - -namespace CryXML_Internal -{ - XML_Memory_Handling_Suite memHandler; - XML_Memory_Handling_Suite* GetMemoryHandler() - { - memHandler.malloc_fcn = custom_xml_malloc; // CryModuleMalloc; - memHandler.realloc_fcn = custom_xml_realloc; // CryModuleRealloc; - memHandler.free_fcn = custom_xml_free; // CryModuleFree; - return &memHandler; - } -} - -XmlParserImp::XmlParserImp(bool bRemoveNonessentialSpacesFromContent) -{ - m_bRemoveNonessentialSpacesFromContent = bRemoveNonessentialSpacesFromContent; - - m_root = 0; - nodeStack.reserve(100); - - m_parser = XML_ParserCreate_MM(NULL, CryXML_Internal::GetMemoryHandler(), NULL); - - XML_SetUserData(m_parser, this); - XML_SetElementHandler(m_parser, startElement, endElement); - XML_SetCharacterDataHandler(m_parser, characterData); - XML_SetEncoding(m_parser, "utf-8"); -} - -XmlParserImp::~XmlParserImp() -{ - XML_ParserFree(m_parser); -} - -void XmlParserImp::beginParse() -{ - m_root = 0; - - m_stringPool.SetBlockSize(1 << 20); -} - -bool XmlParserImp::parse(const char* buffer, int bufLen) -{ - if (!XML_Parse(m_parser, buffer, (int)bufLen, 0)) - { - m_root = 0; - return false; - } - return true; -} - -XmlNodeRef XmlParserImp::endParse(XmlString& errorString) -{ - errorString = ""; - - if (!XML_Parse(m_parser, "", 0, 1)) - { - m_root = 0; - } - - if (!m_root) - { - const char* const errorText = XML_ErrorString(XML_GetErrorCode(m_parser)); - if (errorText) - { - errorString += "XML Error: "; - errorString += errorText; - // The following code is disabled by 'if (false)' because XML_GetCurrentLineNumber() - // XML_GetCurrentColumnNumber() return incorrect numbers. - // The issue (wrong numbers) might be fixed if/when we upgrade to a newer version - // of the Expat XML library (on 2014/02/26 CryEngine still uses expat version 1.95.2 - // from 2001/07/27, although the latest expat version is 2.1.0 from 2012/03/24). - if (false) - { - char s[64]; - azsprintf(s, " at line %d, column %d", (int)XML_GetCurrentLineNumber(m_parser), (int)XML_GetCurrentColumnNumber(m_parser)); - errorString += s; - } - } - } - - XmlNodeRef root = m_root; - m_root = 0; - return root; -} - -XmlParser::XmlParser(bool bRemoveNonessentialSpacesFromContent) -{ - m_pImpl = new XmlParserImp(bRemoveNonessentialSpacesFromContent); - m_pImpl->AddRef(); -} - -XmlParser::~XmlParser() -{ - m_pImpl->Release(); -} - -//! Parse xml file. -XmlNodeRef XmlParser::parse(const char* fileName) -{ - m_errorString = ""; - - std::vector buf; - auto pPak = GetISystem()->GetIPak(); - AZ::IO::HandleType file = pPak->FOpen(fileName, "rb"); - if (file) - { - pPak->FSeek(file, 0, SEEK_END); - int fileSize = pPak->FTell(file); - pPak->FSeek(file, 0, SEEK_SET); - buf.resize(fileSize); - pPak->FRead(&(buf[0]), fileSize, file); - pPak->FClose(file); - m_pImpl->parse(&buf[0], buf.size()); - return m_pImpl->endParse(m_errorString); - } - else - { - return XmlNodeRef(); - } -} - -//! Parse xml from memory buffer. -XmlNodeRef XmlParser::parseBuffer(const char* buffer) -{ - m_errorString = ""; - m_pImpl->beginParse(); - m_pImpl->parse(buffer, strlen(buffer)); - return m_pImpl->endParse(m_errorString); -} - -XmlNodeRef XmlParser::parseSource(const IXmlBufferSource* source) -{ - m_errorString = ""; - char buffer[40000]; - enum - { - bufferSize = sizeof(buffer) / sizeof(buffer[0]) - }; - m_pImpl->beginParse(); - int bytesRead = source->Read(buffer, bufferSize); - while (bytesRead) - { - if (!m_pImpl->parse(buffer, bytesRead)) - { - break; - } - bytesRead = source->Read(buffer, bufferSize); - } - return m_pImpl->endParse(m_errorString); -} diff --git a/Code/Tools/CryXML/XML/xml.h b/Code/Tools/CryXML/XML/xml.h deleted file mode 100644 index 8e9072acbf..0000000000 --- a/Code/Tools/CryXML/XML/xml.h +++ /dev/null @@ -1,471 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYXML_XML_XML_H -#define CRYINCLUDE_CRYXML_XML_XML_H -#pragma once - - -#include -#include -#include - -#include "IXml.h" - -struct IXmlBufferSource; - -struct IXmlStringPool -{ -public: - IXmlStringPool() { m_refCount = 0; } - virtual ~IXmlStringPool() {}; - void AddRef() { m_refCount++; }; - void Release() - { - if (--m_refCount <= 0) - { - delete this; - } - }; - virtual char* AddString(const char* str) = 0; -private: - int m_refCount; -}; - -/************************************************************************/ -/* XmlParser class, Parse xml and return root xml node if success. */ -/************************************************************************/ -class XmlParser -{ -public: - explicit XmlParser(bool bRemoveNonessentialSpacesFromContent); - ~XmlParser(); - - //! Parse xml file. - XmlNodeRef parse(const char* fileName); - - //! Parse xml from memory buffer. - XmlNodeRef parseBuffer(const char* buffer); - - XmlNodeRef parseSource(const IXmlBufferSource* source); - - const char* getErrorString() const { return m_errorString; } - -private: - XmlString m_errorString; - class XmlParserImp* m_pImpl; -}; - -// Compare function for string comparasion, can be strcmp or _stricmp -typedef int (__cdecl * XmlStrCmpFunc)(const char* str1, const char* str2); -extern XmlStrCmpFunc g_pXmlStrCmp; - -////////////////////////////////////////////////////////////////////////// -// XmlAttribute class -////////////////////////////////////////////////////////////////////////// -struct XmlAttribute -{ - const char* key; - const char* value; - - bool operator<(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) < 0; } - bool operator>(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) > 0; } - bool operator==(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) == 0; } - bool operator!=(const XmlAttribute& attr) const { return g_pXmlStrCmp(key, attr.key) != 0; } -}; - -//! Xml node attributes class. -typedef std::vector XmlAttributes; -typedef XmlAttributes::iterator XmlAttrIter; -typedef XmlAttributes::const_iterator XmlAttrConstIter; - -/** -****************************************************************************** -* CXmlNode class -* Never use CXmlNode directly instead use reference counted XmlNodeRef. -****************************************************************************** -*/ - -class CXmlNode - : public IXmlNode -{ -public: - //! Constructor. - CXmlNode(); - CXmlNode(const char* tag); - //! Destructor. - ~CXmlNode(); - - virtual void DeleteThis(); - - //! Create new XML node. - XmlNodeRef createNode(const char* tag); - - //! Get XML node tag. - const char* getTag() const { return m_tag; }; - void setTag(const char* tag); - - //! Return true if given tag equal to node tag. - bool isTag(const char* tag) const; - - //! Get XML Node attributes. - virtual int getNumAttributes() const { return (int)m_attributes.size(); }; - //! Return attribute key and value by attribute index. - virtual bool getAttributeByIndex(int index, const char** key, const char** value); - - virtual void copyAttributes(XmlNodeRef fromNode); - - //! Get XML Node attribute for specified key. - const char* getAttr(const char* key) const; - - //! Get XML Node attribute for specified key. - // Returns true if the attribute existes, alse otherwise. - bool getAttr(const char* key, const char** value) const; - - //! Check if attributes with specified key exist. - bool haveAttr(const char* key) const; - - //! Creates new xml node and add it to childs list. - XmlNodeRef newChild(const char* tagName); - - //! Adds new child node. - void addChild(const XmlNodeRef& node); - //! Remove child node. - void removeChild(const XmlNodeRef& node); - - void insertChild(int nIndex, const XmlNodeRef& node); - void replaceChild(int nIndex, const XmlNodeRef& node); - - //! Remove all child nodes. - void removeAllChilds(); - - //! Get number of child XML nodes. - int getChildCount() const { return (int)m_childs.size(); }; - - //! Get XML Node child nodes. - XmlNodeRef getChild(int i) const; - - //! Find node with specified tag. - XmlNodeRef findChild(const char* tag) const; - void deleteChild(const char* tag); - void deleteChildAt(int nIndex); - - //! Get parent XML node. - XmlNodeRef getParent() const { return m_parent; } - void setParent(const XmlNodeRef& inRef); - - //! Returns content of this node. - const char* getContent() const { return m_content.c_str(); }; - void setContent(const char* str); - - XmlNodeRef clone(); - - //! Returns line number for XML tag. - int getLine() const { return m_line; }; - //! Set line number in xml. - void setLine(int line) { m_line = line; }; - - //! Returns XML of this node and sub nodes. - virtual IXmlStringData* getXMLData(int nReserveMem = 0) const; - XmlString getXML(int level = 0) const; - bool saveToFile(const char* fileName) override; - - //! Set new XML Node attribute (or override attribute with same key). - void setAttr(const char* key, const char* value); - void setAttr(const char* key, int value); - void setAttr(const char* key, unsigned int value); - void setAttr(const char* key, int64 value); - void setAttr(const char* key, uint64 value, bool useHexFormat = true); - void setAttr(const char* key, float value); - void setAttr(const char* key, double value); - void setAttr(const char* key, const Vec2& value); - void setAttr(const char* key, const Vec2d& value); - void setAttr(const char* key, const Ang3& value); - void setAttr(const char* key, const Vec3& value); - void setAttr(const char* key, const Vec4& value); - void setAttr(const char* key, const Vec3d& value); - void setAttr(const char* key, const Quat& value); - - //! Delete attrbute. - void delAttr(const char* key); - //! Remove all node attributes. - void removeAllAttributes(); - - //! Get attribute value of node. - bool getAttr(const char* key, int& value) const; - bool getAttr(const char* key, unsigned int& value) const; - bool getAttr(const char* key, int64& value) const; - bool getAttr(const char* key, uint64& value, bool useHexFormat = true /*ignored*/) const; - bool getAttr(const char* key, float& value) const; - bool getAttr(const char* key, double& value) const; - bool getAttr(const char* key, bool& value) const; - bool getAttr(const char* key, XmlString& value) const - { - XmlString v; - if (v = getAttr(key)) - { - value = v; - return true; - } - else - { - return false; - } - } - bool getAttr(const char* key, Vec2& value) const; - bool getAttr(const char* key, Vec2d& value) const; - bool getAttr(const char* key, Ang3& value) const; - bool getAttr(const char* key, Vec3& value) const; - bool getAttr(const char* key, Vec3d& value) const; - bool getAttr(const char* key, Vec4& value) const; - bool getAttr(const char* key, Quat& value) const; - bool getAttr(const char* key, ColorB& value) const; - // bool getAttr( const char *key,string &value ) const { XmlString v; if (getAttr(key,v)) { value = (const char*)v; return true; } else return false; } - -#if !defined(RESOURCE_COMPILER) - // - // Summary: - // Collect all allocated memory - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const { assert(0); }; - - // Summary: - // Copies children to this node from a given node. - // Children are reference copied (shallow copy) and the children's parent is NOT set to this - // node, but left with its original parent (which is still the parent) - void shareChildren([[maybe_unused]] const XmlNodeRef& fromNode) { assert(0); }; - - // Summary: - // Returns XML of this node and sub nodes into tmpBuffer without XML checks (much faster) - XmlString getXMLUnsafe(int level, [[maybe_unused]] char* tmpBuffer, [[maybe_unused]] uint32 sizeOfTmpBuffer) const { return getXML(level); } - - // Notes: - // Save in small memory chunks. - bool saveToFile([[maybe_unused]] const char* fileName, [[maybe_unused]] size_t chunkSizeBytes, [[maybe_unused]] AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle) override { assert(0); return false; }; - // -#endif - -private: - void AddToXmlString(XmlString& xml, int level) const; - XmlString MakeValidXmlString(const XmlString& xml) const; - bool IsValidXmlString(const char* str) const; - XmlAttrConstIter GetAttrConstIterator(const char* key) const - { - XmlAttribute tempAttr; - tempAttr.key = key; - - XmlAttributes::const_iterator it = std::find(m_attributes.begin(), m_attributes.end(), tempAttr); - return it; - - /* - XmlAttributes::const_iterator it = std::lower_bound( m_attributes.begin(),m_attributes.end(),tempAttr ); - if (it != m_attributes.end() && _stricmp(it->key,key) == 0) - return it; - return m_attributes.end(); - */ - } - XmlAttrIter GetAttrIterator(const char* key) - { - XmlAttribute tempAttr; - tempAttr.key = key; - - XmlAttributes::iterator it = std::find(m_attributes.begin(), m_attributes.end(), tempAttr); - return it; - - // XmlAttributes::iterator it = std::lower_bound( m_attributes.begin(),m_attributes.end(),tempAttr ); - //if (it != m_attributes.end() && _stricmp(it->key,key) == 0) - //return it; - //return m_attributes.end(); - } - const char* GetValue(const char* key) const - { - XmlAttrConstIter it = GetAttrConstIterator(key); - if (it != m_attributes.end()) - { - return it->value; - } - return 0; - } - -private: - //! Line in XML file where this node firstly appeared (usefull for debugging). - int m_line; - - //! Tag of XML node. - const char* m_tag; - //! Content of XML node. - XmlString m_content; - //! Parent XML node. - CXmlNode* m_parent; - - // String pool used by this node. - IXmlStringPool* m_pStringPool; - - typedef std::vector XmlNodes; - XmlNodes m_childs; - //! Xml node attributes. - XmlAttributes m_attributes; - - friend class XmlParserImp; -}; - -#endif // __XML_HEADER__ - - -/* -#ifndef __XML_HEADER__ -#define __XML_HEADER__ - - - -class CXmlNode : public IXmlNode -{ -public: - //! Constructor. - CXmlNode( const char *tag ); - //! Destructor. - ~CXmlNode(); - - ////////////////////////////////////////////////////////////////////////// - //! Reference counting. - void AddRef() { m_refCount++; }; - //! When ref count reach zero XML node dies. - void Release(); - - //! Create new XML node. - XmlNodeRef createNode( const char *tag ); - - //! Get XML node tag. - const char *getTag() const { return m_tag; }; - void setTag( const char *tag ) { m_tag = tag; } - - //! Return true if givven tag equal to node tag. - bool isTag( const char *tag ) const; - - //! Get XML Node attributes. - virtual int getNumAttributes() const { return (int)m_attributes.size(); }; - //! Return attribute key and value by attribute index. - virtual bool getAttributeByIndex( int index,const char **key,const char **value ); - - virtual void* getFirstAttribute(); - virtual bool getNextAttribute( void** pIterator,const char **key,const char **value ); - - virtual void copyAttributes( XmlNodeRef fromNode ); - - //! Get XML Node attribute for specified key. - const char* getAttr( const char *key ) const; - //! Check if attributes with specified key exist. - bool haveAttr( const char *key ) const; - - //! Adds new child node. - void addChild( const XmlNodeRef &node ); - - //! Creates new xml node and add it to childs list. - XmlNodeRef newChild( const char *tagName ); - - //! Remove child node. - void removeChild( const XmlNodeRef &node ); - - //! Remove all child nodes. - void removeAllChilds(); - - //! Get number of child XML nodes. - int getChildCount() const { return (int)m_childs.size(); }; - - //! Get XML Node child nodes. - XmlNodeRef getChild( int i ) const; - - //! Find node with specified tag. - XmlNodeRef findChild( const char *tag ) const; - - //! Get parent XML node. - XmlNodeRef getParent() const { return m_parent; } - - //! Returns content of this node. - const char* getContent() const { return m_content; }; - void setContent( const char *str ) { m_content = str; }; - void addContent( const char *str ) { m_content += str; }; - - XmlNodeRef clone(); - - //! Returns line number for XML tag. - int getLine() const { return m_line; }; - //! Set line number in xml. - void setLine( int line ) { m_line = line; }; - - //! Returns XML of this node and sub nodes. - XmlString getXML( int level=0 ) const; - XmlString getBinaryXML() const; - bool saveToFile( const char *fileName, bool bBinary = false ); - bool saveToSink(IXMLDataSink* pSink, bool bBinary = false); - - //! Set new XML Node attribute (or override attribute with same key). - void setAttr( const char* key,const char* value ); - void setAttr( const char* key,int value ); - void setAttr( const char* key,unsigned int value ); - void setAttr( const char* key,uint64 value ); - void setAttr( const char* key,float value ); - void setAttr( const char* key,const Ang3& value ); - void setAttr( const char* key,const Vec3& value ); - void setAttr( const char* key,const Quat &value ); - - //! Delete attribute. - void delAttr( const char* key ); - //! Remove all node attributes. - void removeAllAttributes(); - - //! Get attribute value of node. - bool getAttr( const char *key,int &value ) const; - bool getAttr( const char *key,unsigned int &value ) const; - bool getAttr( const char *key,uint64 &value ) const; - bool getAttr( const char *key,float &value ) const; - bool getAttr( const char *key,Ang3& value ) const; - bool getAttr( const char *key,Vec3& value ) const; - bool getAttr( const char *key,Quat &value ) const; - bool getAttr( const char *key,bool &value ) const; - bool getAttr( const char *key,XmlString &value ) const { XmlString v; if (v=getAttr(key)) { value = v; return true; } else return false; } -// bool getAttr( const char *key,string &value ) const { XmlString v; if (getAttr(key,v)) { value = (const char*)v; return true; } else return false; } - - // Add an attribute structure directly. - void addAttr(XmlAttribute& attribute); - - void SetBuffer(StringBuffer* pStringBuffer); - -private: - void AddToXmlString( XmlString &xml,int level ) const; - -private: - StringBuffer* m_pStringBuffer; - - //! Ref count itself, its zeroed on node creation. - int m_refCount; - - //! Line in XML file where this node firstly appeared (usefull for debuggin). - int m_line; - //! Tag of XML node. - XmlString m_tag; - - //! Content of XML node. - XmlString m_content; - //! Parent XML node. - CXmlNode *m_parent; - //! Next XML node in same hierarchy level. - - typedef std::vector XmlNodes; - XmlNodes m_childs; - //! Xml node attributes. - XmlAttributes m_attributes; - static XmlAttribute tempAttr; -}; - -#endif // CRYINCLUDE_CRYXML_XML_XML_H -*/ diff --git a/Code/Tools/CryXML/XMLSerializer.cpp b/Code/Tools/CryXML/XMLSerializer.cpp deleted file mode 100644 index e1152f93a3..0000000000 --- a/Code/Tools/CryXML/XMLSerializer.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CryXML_precompiled.h" -#include "XMLSerializer.h" -#include "XML/xml.h" -#include "IXMLSerializer.h" -#include "StringUtils.h" - -XmlNodeRef XMLSerializer::CreateNode(const char* tag) -{ - return new CXmlNode(tag); -} - -bool XMLSerializer::Write(XmlNodeRef root, const char* szFileName) -{ - return root->saveToFile(szFileName); -} - -XmlNodeRef XMLSerializer::Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer) -{ - XmlParser parser(bRemoveNonessentialSpacesFromContent); - XmlNodeRef root = parser.parseSource(&source); - if (nErrorBufferSize > 0 && szErrorBuffer) - { - const char* const err = parser.getErrorString(); - cry_strcpy(szErrorBuffer, nErrorBufferSize, err ? err : ""); - } - return root; -} diff --git a/Code/Tools/CryXML/XMLSerializer.h b/Code/Tools/CryXML/XMLSerializer.h deleted file mode 100644 index 7730b19963..0000000000 --- a/Code/Tools/CryXML/XMLSerializer.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYXML_XMLSERIALIZER_H -#define CRYINCLUDE_CRYXML_XMLSERIALIZER_H -#pragma once - - -#include "IXMLSerializer.h" - -class XMLSerializer - : public IXMLSerializer -{ -public: - virtual XmlNodeRef CreateNode(const char* tag); - virtual bool Write(XmlNodeRef root, const char* szFileName); - - virtual XmlNodeRef Read(const IXmlBufferSource& source, bool bRemoveNonessentialSpacesFromContent, int nErrorBufferSize, char* szErrorBuffer); -}; - -#endif // CRYINCLUDE_CRYXML_XMLSERIALIZER_H diff --git a/Code/Tools/CryXML/cryxml_files.cmake b/Code/Tools/CryXML/cryxml_files.cmake deleted file mode 100644 index d81ace11b7..0000000000 --- a/Code/Tools/CryXML/cryxml_files.cmake +++ /dev/null @@ -1,22 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - CryXML.cpp - XMLSerializer.cpp - ICryXML.h - IXMLSerializer.h - XMLSerializer.h - XML/xml.cpp - XML/xml.h - CryXML_precompiled.h - CryXML_precompiled.cpp -) diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings deleted file mode 100644 index e7bbaccd46..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/Bump2NormalHighQ.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /bumptype=1 /mipmirror=1 /preset=Bump2Normalmap_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings deleted file mode 100644 index 5f78477ca8..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha256512.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings deleted file mode 100644 index 5f78477ca8..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/DiffusehighQWithAlpha512256.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_highQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings deleted file mode 100644 index 6466dc9099..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/LuminanceOnly.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /mipalphacoverage=0 /mipmirror=1 /preset=Diffuse_highQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings deleted file mode 100644 index acfbe2a750..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPreset3DC_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=0 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings deleted file mode 100644 index 00ecf3a56e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings deleted file mode 100644 index 00ecf3a56e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8WithAlpha.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings deleted file mode 100644 index cab995b31e..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_bump.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Bump2Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoPresetX8R8G8B8_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings deleted file mode 100644 index 1048249b71..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Diffuse_lowQ diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings deleted file mode 100644 index db0b877f24..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings300400.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=ReferenceImage diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings deleted file mode 100644 index 1048249b71..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettingsGrey_DDNDIF.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=Diffuse_lowQ diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings deleted file mode 100644 index 84c0416421..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NoTIFSettings_DDNDIF.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /ms=0 /preset=Diffuse_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings deleted file mode 100644 index cb9f25b5d9..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQReduce1_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=1 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings deleted file mode 100644 index c5a53f8bd5..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/NormalmapLowQ_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumpblur=0.000000 /bumpstrength=5.000000 /mipmirror=1 /preset=Normalmap_lowQ /reduce=0 diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings deleted file mode 100644 index 47b9f504fd..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/TestColorChart_cch.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /preset=ColorChart diff --git a/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings b/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings deleted file mode 100644 index 3e5edcd652..0000000000 --- a/Code/Tools/TestBed/ResourceCompilerImage/Input/diamand_plate_ddn.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /bumptype=1 /preset=Bump2Normalmap_lowQ /reduce=0 diff --git a/Gems/Blast/Assets/.p4ignore b/Gems/Blast/Assets/.p4ignore deleted file mode 100644 index 7015097e56..0000000000 --- a/Gems/Blast/Assets/.p4ignore +++ /dev/null @@ -1 +0,0 @@ -*.physx diff --git a/Tools/AnimationTest/assetImportTest.bat b/Tools/AnimationTest/assetImportTest.bat deleted file mode 100644 index 205c17280b..0000000000 --- a/Tools/AnimationTest/assetImportTest.bat +++ /dev/null @@ -1,31 +0,0 @@ -REM -REM -REM All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -REM its licensors. -REM -REM For complete copyright and license terms please see the LICENSE at the root of this -REM distribution (the "License"). All use of this software is governed by the License, -REM or, if provided, by the license below or the license accompanying this file. Do not -REM remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -REM - -TITLE asset import test - -SETLOCAL EnableExtensions -set EXE=AssetProcessor_tmp.exe -FOR /F %%x IN ('tasklist /NH /FI "IMAGENAME eq %EXE%"') DO IF %%x == %EXE% goto FOUND -echo Make sure asset processor is running before run this script. -goto FIN -:FOUND - -SET F="..\..\Cache\SamplesProject\pc\samplesproject\objects" - -IF EXIST %F% ( - RMDIR /S /Q %F% - ECHO Detected folder at %F% - ECHO Make sure there's no fail / crash in asset processor after all job finished. -) ELSE (ECHO folder %F% NOT FOUND) - -:FIN -PAUSE \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/7z.exe b/Tools/DeepBandwidthToExcel/7z.exe deleted file mode 100644 index 85fa5e2917..0000000000 --- a/Tools/DeepBandwidthToExcel/7z.exe +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2ca56c2a96859b5171e7d24c81ed4d281da0ea26a7eaff7eac975d337eb4a2e1 -size 266752 diff --git a/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe b/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe deleted file mode 100644 index b89cb8c457..0000000000 --- a/Tools/DeepBandwidthToExcel/DeepBandwidthToExcel.exe +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6b8dc17c53df32173fd82d8bfc844bc3752bf6cbaf1bf2fd334dd6949f44b04b -size 1050344 diff --git a/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml b/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml deleted file mode 100644 index 3c4fc1468a..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/[Content_Types].xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/_rels/.rels b/Tools/DeepBandwidthToExcel/Template/_rels/.rels deleted file mode 100644 index 74bfd8d955..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/_rels/.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/docProps/app.xml b/Tools/DeepBandwidthToExcel/Template/docProps/app.xml deleted file mode 100644 index 6430cd86f5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/docProps/app.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Microsoft Excel0falseWorksheets9Group TotalsMessage TotalsPolicy CountPolicy ImpactSerialisation ImpactBandwidth Over TimeSocket Packets Over TimeSocket Bits Over TimeWarningsCrytek UKfalsefalsefalse12.0000 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/docProps/core.xml b/Tools/DeepBandwidthToExcel/Template/docProps/core.xml deleted file mode 100644 index f1efda39ff..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/docProps/core.xml +++ /dev/null @@ -1,2 +0,0 @@ - -leelee2012-03-06T13:44:11Z2012-03-23T08:28:17Z \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels deleted file mode 100644 index e9dc190f2c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/_rels/workbook.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml b/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml deleted file mode 100644 index 2fb95911c6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/calcChain.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml deleted file mode 100644 index 3e3737423c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Schedule Group'Group Totals'!###---SHEET1_COL0---###peterpaul'Group Totals'!###---SHEET1_COL1---###General55 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml deleted file mode 100644 index 54d3f0da26..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Message'Message Totals'!###---SHEET2_COL0---###peterpaul'Message Totals'!###---SHEET2_COL1---###General55 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml deleted file mode 100644 index f405df758f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Policy Count'Policy Count'!###---SHEET3_COL0---###ui2eid'Policy Count'!###---SHEET3_COL1---###General20801811398975 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml deleted file mode 100644 index 6d461a7cd5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart4.xml +++ /dev/null @@ -1,2 +0,0 @@ - -Overall By Policy Impact (Bits Per Policy)'Policy Impact'!###---SHEET4_COL0---###wrlddMov'Policy Impact'!###---SHEET4_COL1---###General5354582913312905 diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml deleted file mode 100644 index 5276503965..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart5.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - - - - - - - - - - - - - - Overall By Serialisation Impact (Bits - - - - Per Serialise) - - - - - - - - - - - - - - - - - - - - 'Serialisation Impact'!###---SHEET5_COL0---### - - - - wrld - - - dMov - - - - - - - 'Serialisation Impact'!###---SHEET5_COL1---### - - General - - - 53545829 - - - 13312905 - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml deleted file mode 100644 index 3dbcb710ee..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart6.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - - - - - - - - - - - - Bandwidth Over Time - - - - - - - - - - ###---SHEET6_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml deleted file mode 100644 index 324a3d0296..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart7.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - - - - - - - - - - - - - - Socket - - - - Packets Per Second - - - - - - - - - - - ###---SHEET7_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml b/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml deleted file mode 100644 index 9aed1eaa0b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/charts/chart8.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - - - - - - - - Socket - - - - Bits Per Second - - - - - - - - - - ###---SHEET8_CHART---### - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels deleted file mode 100644 index 91223aab09..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing1.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels deleted file mode 100644 index 63233beb83..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing2.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels deleted file mode 100644 index c53f6617a5..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing3.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels deleted file mode 100644 index 7fe138bac4..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing4.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels deleted file mode 100644 index 22864411ec..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing5.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels deleted file mode 100644 index 424914396d..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing6.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels deleted file mode 100644 index b1404c3db9..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing7.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels deleted file mode 100644 index a9e371607f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/_rels/drawing8.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml deleted file mode 100644 index 70ea7ed3be..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -43809902857429952440114299 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml deleted file mode 100644 index f8a60ce08a..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -338100076199285810254057150 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml deleted file mode 100644 index 75e5d9ed25..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -2276225095250283714754019050 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml deleted file mode 100644 index de297dbb14..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing4.xml +++ /dev/null @@ -1,2 +0,0 @@ - -3001333492851435040123824 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml deleted file mode 100644 index b7c2cf9c02..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing5.xml +++ /dev/null @@ -1,2 +0,0 @@ - -25524500104775284572004095250 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml deleted file mode 100644 index c610b4c052..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing6.xml +++ /dev/null @@ -1,2 +0,0 @@ - -338099914287528257174409525 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml deleted file mode 100644 index 14d255a242..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing7.xml +++ /dev/null @@ -1,2 +0,0 @@ - -247624310477526533399389525 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml b/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml deleted file mode 100644 index 1b94acd279..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/drawings/drawing8.xml +++ /dev/null @@ -1,2 +0,0 @@ - -23809931047752744767539114301 \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml b/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml deleted file mode 100644 index 2fbc1ad0b7..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/sharedStrings.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---STRINGSTABLE---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/styles.xml b/Tools/DeepBandwidthToExcel/Template/xl/styles.xml deleted file mode 100644 index 8238b50fd0..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/styles.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml b/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml deleted file mode 100644 index 9944f3ecab..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/theme/theme1.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml b/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml deleted file mode 100644 index 19c26d83b6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/workbook.xml +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels deleted file mode 100644 index 205832e91b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet1.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels deleted file mode 100644 index b48a928346..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet2.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels deleted file mode 100644 index c0c5ded4a6..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet3.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels deleted file mode 100644 index f34eab954f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet4.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels deleted file mode 100644 index 67118d3a1e..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet5.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels deleted file mode 100644 index 656a337f58..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet6.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels deleted file mode 100644 index efc518bb3f..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet7.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels deleted file mode 100644 index 586d2d3c76..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/_rels/sheet8.xml.rels +++ /dev/null @@ -1,2 +0,0 @@ - - \ No newline at end of file diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml deleted file mode 100644 index 1fbfb22964..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet1.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET1_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml deleted file mode 100644 index 0d72f8c9da..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet2.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET2_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml deleted file mode 100644 index 18717c6987..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet3.xml +++ /dev/null @@ -1,2 +0,0 @@ - -###---SHEET3_DATA---### diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml deleted file mode 100644 index 9442249676..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet4.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - -###---SHEET4_DATA---### - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml deleted file mode 100644 index 14f48b192c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet5.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - -###---SHEET5_DATA---### - - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml deleted file mode 100644 index fa7a8d800b..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet6.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET6_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml deleted file mode 100644 index 708d01d20c..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet7.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET7_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml deleted file mode 100644 index 164cdcdde2..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet8.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - - -###---SHEET8_DATA---### - - diff --git a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml b/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml deleted file mode 100644 index a3a3b40230..0000000000 --- a/Tools/DeepBandwidthToExcel/Template/xl/worksheets/sheet9.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - -###---SHEET9_DATA---### - - diff --git a/scripts/build/package/Platform/Windows/package_filelists/atom.json b/scripts/build/package/Platform/Windows/package_filelists/atom.json index f084173cb2..5f3d3b78cb 100644 --- a/scripts/build/package/Platform/Windows/package_filelists/atom.json +++ b/scripts/build/package/Platform/Windows/package_filelists/atom.json @@ -38,24 +38,13 @@ "AzTestRunner/**": "#include", "CrashHandler/**": "#include", "CryCommonTools/**": "#include", - "CrySCompileServer/**": "#include", - "CryXML/**": "#include", "DeltaCataloger/**": "#include", - "GemRegistry/**": "#include", "GridHub/**": "#include", - "HLSLCrossCompiler/**": "#include", - "HLSLCrossCompilerMETAL/**": "#include", - "LyIdentity/**": "#include", - "LyMetrics/**": "#include", "News/**": "#include", "PythonBindingsExample/**": "#include", - "RC/**": "#include", "RemoteConsole/**": "#include", "SceneAPI/**": "#include", "SerializeContextTools/**": "#include", - "ShaderCacheGen/**": "#include", - "SharedQMLResource/**": "#include", - "Woodpecker/**": "#include", "CMakeLists.txt": "#include" }, "CMakeLists.txt": "#include" From 795aa114e69f6846133442da9d74cae56416ca39 Mon Sep 17 00:00:00 2001 From: Tom Hulton-Harrop <82228511+hultonha@users.noreply.github.com> Date: Thu, 13 May 2021 16:19:53 +0100 Subject: [PATCH 47/47] Improve selection in the viewport (#720) * improve selection in the viewport * remove debug code * updates following review feedback - update API comments from /// to //! from - add [[nodiscard]] attribute to member function - move constructor implementations to .cpp files * use lambda instead of ternary operator * fix unit test failure caused by typo --- .../AzFramework/Viewport/CameraInput.cpp | 95 ++++++----- .../AzFramework/Viewport/CameraInput.h | 29 ++-- .../AzFramework/Viewport/ClickDetector.cpp | 68 ++++++++ .../AzFramework/Viewport/ClickDetector.h | 75 +++++++++ .../AzFramework/Viewport/CursorState.h | 56 +++++++ .../AzFramework/azframework_files.cmake | 3 + .../EditorTransformComponentSelection.cpp | 36 +++- .../EditorTransformComponentSelection.h | 156 +++++++++--------- Code/Framework/Tests/ClickDetectorTests.cpp | 142 ++++++++++++++++ Code/Framework/Tests/CursorStateTests.cpp | 54 ++++++ .../Tests/frameworktests_files.cmake | 2 + 11 files changed, 573 insertions(+), 143 deletions(-) create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h create mode 100644 Code/Framework/AzFramework/AzFramework/Viewport/CursorState.h create mode 100644 Code/Framework/Tests/ClickDetectorTests.cpp create mode 100644 Code/Framework/Tests/CursorStateTests.cpp diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 8669b58911..daf2c63921 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -156,35 +157,25 @@ namespace AzFramework camera.m_lookAt = transform.GetTranslation() + (camera.Rotation().GetBasisY() * -camera.m_lookDist); } - static ScreenVector CursorDelta(const AZStd::optional& currentPosition, const AZStd::optional& lastPosition) - { - return currentPosition.has_value() && lastPosition.has_value() ? currentPosition.value() - lastPosition.value() - : ScreenVector(0, 0); - } - bool CameraSystem::HandleEvents(const InputEvent& event) { if (const auto& cursor = AZStd::get_if(&event)) { - m_currentCursorPosition = cursor->m_position; + m_cursorState.SetCurrentPosition(cursor->m_position); } else if (const auto& scroll = AZStd::get_if(&event)) { m_scrollDelta = scroll->m_delta; } - return m_cameras.HandleEvents(event, CursorDelta(m_currentCursorPosition, m_lastCursorPosition), m_scrollDelta); + return m_cameras.HandleEvents(event, m_cursorState.CursorDelta(), m_scrollDelta); } Camera CameraSystem::StepCamera(const Camera& targetCamera, const float deltaTime) { - const auto cursorDelta = CursorDelta(m_currentCursorPosition, m_lastCursorPosition); - if (m_currentCursorPosition.has_value()) - { - m_lastCursorPosition = m_currentCursorPosition; - } + const auto nextCamera = m_cameras.StepCamera(targetCamera, m_cursorState.CursorDelta(), m_scrollDelta, deltaTime); - const auto nextCamera = m_cameras.StepCamera(targetCamera, cursorDelta, m_scrollDelta, deltaTime); + m_cursorState.Update(); m_scrollDelta = 0.0f; @@ -236,12 +227,12 @@ namespace AzFramework } } - // accumulate - Camera nextCamera = targetCamera; - for (auto& cameraInput : m_activeCameraInputs) - { - nextCamera = cameraInput->StepCamera(nextCamera, cursorDelta, scrollDelta, deltaTime); - } + const Camera nextCamera = AZStd::accumulate( + AZStd::begin(m_activeCameraInputs), AZStd::end(m_activeCameraInputs), targetCamera, + [cursorDelta, scrollDelta, deltaTime](Camera acc, auto& camera) { + acc = camera->StepCamera(acc, cursorDelta, scrollDelta, deltaTime); + return acc; + }); for (int i = 0; i < m_activeCameraInputs.size();) { @@ -275,34 +266,42 @@ namespace AzFramework } } + RotateCameraInput::RotateCameraInput(const InputChannelId rotateChannelId) + : m_rotateChannelId(rotateChannelId) + { + } + void RotateCameraInput::HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { - if (const auto& input = AZStd::get_if(&event)) - { - if (input->m_channelId == m_rotateChannelId) + const ClickDetector::ClickEvent clickEvent = [&event, this] { + if (const auto& input = AZStd::get_if(&event)) { - if (input->m_state == InputChannel::State::Began) + if (input->m_channelId == m_rotateChannelId) { - m_tryingToBegin = true; - m_moveAccumulator = 0.0f; - } - else if (input->m_state == InputChannel::State::Ended) - { - m_tryingToBegin = false; - EndActivation(); + if (input->m_state == InputChannel::State::Began) + { + return ClickDetector::ClickEvent::Down; + } + else if (input->m_state == InputChannel::State::Ended) + { + return ClickDetector::ClickEvent::Up; + } } } - } + return ClickDetector::ClickEvent::Nil; + }(); - if (m_tryingToBegin) + switch (const auto outcome = m_clickDetector.DetectClick(clickEvent, cursorDelta); outcome) { - // only allow the action to begin if the mouse has been moved a small amount - m_moveAccumulator += ScreenVectorLength(cursorDelta); - if (m_moveAccumulator > ed_cameraSystemLookDeadzone) - { - BeginActivation(); - m_tryingToBegin = false; - } + case ClickDetector::ClickOutcome::Move: + BeginActivation(); + break; + case ClickDetector::ClickOutcome::Release: + EndActivation(); + break; + default: + // noop + break; } } @@ -324,6 +323,12 @@ namespace AzFramework return nextCamera; } + PanCameraInput::PanCameraInput(const InputChannelId panChannelId, PanAxesFn panAxesFn) + : m_panAxesFn(AZStd::move(panAxesFn)) + , m_panChannelId(panChannelId) + { + } + void PanCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { @@ -400,6 +405,11 @@ namespace AzFramework return TranslationType::Nil; } + TranslateCameraInput::TranslateCameraInput(TranslationAxesFn translationAxesFn) + : m_translationAxesFn(AZStd::move(translationAxesFn)) + { + } + void TranslateCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { @@ -574,6 +584,11 @@ namespace AzFramework return nextCamera; } + OrbitDollyCursorMoveCameraInput::OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) + : m_dollyChannelId(dollyChannelId) + { + } + void OrbitDollyCursorMoveCameraInput::HandleEvents( const InputEvent& event, [[maybe_unused]] const ScreenVector& cursorDelta, [[maybe_unused]] float scrollDelta) { diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 6475753017..41d7f11385 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -17,6 +17,8 @@ #include #include #include +#include +#include #include #include @@ -188,26 +190,21 @@ namespace AzFramework Cameras m_cameras; private: + CursorState m_cursorState; float m_scrollDelta = 0.0f; - AZStd::optional m_lastCursorPosition; - AZStd::optional m_currentCursorPosition; }; class RotateCameraInput : public CameraInput { public: - explicit RotateCameraInput(const InputChannelId rotateChannelId) - : m_rotateChannelId(rotateChannelId) - { - } + explicit RotateCameraInput(InputChannelId rotateChannelId); void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; private: InputChannelId m_rotateChannelId; - float m_moveAccumulator = 0.0f; - bool m_tryingToBegin = false; + ClickDetector m_clickDetector; }; struct PanAxes @@ -240,11 +237,8 @@ namespace AzFramework class PanCameraInput : public CameraInput { public: - PanCameraInput(const InputChannelId panChannelId, PanAxesFn panAxesFn) - : m_panAxesFn(AZStd::move(panAxesFn)) - , m_panChannelId(panChannelId) - { - } + PanCameraInput(InputChannelId panChannelId, PanAxesFn panAxesFn); + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; @@ -283,10 +277,8 @@ namespace AzFramework class TranslateCameraInput : public CameraInput { public: - explicit TranslateCameraInput(TranslationAxesFn translationAxesFn) - : m_translationAxesFn(AZStd::move(translationAxesFn)) - { - } + explicit TranslateCameraInput(TranslationAxesFn translationAxesFn); + void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; void ResetImpl() override; @@ -363,8 +355,7 @@ namespace AzFramework class OrbitDollyCursorMoveCameraInput : public CameraInput { public: - explicit OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) - : m_dollyChannelId(dollyChannelId) {} + explicit OrbitDollyCursorMoveCameraInput(InputChannelId dollyChannelId); void HandleEvents(const InputEvent& event, const ScreenVector& cursorDelta, float scrollDelta) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp new file mode 100644 index 0000000000..5af44a81bc --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp @@ -0,0 +1,68 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#include +#include + +namespace AzFramework +{ + ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta) + { + if (clickEvent == ClickEvent::Down) + { + const auto now = std::chrono::steady_clock::now(); + if (m_tryBeginTime) + { + const std::chrono::duration diff = now - m_tryBeginTime.value(); + if (diff.count() < m_doubleClickInterval) + { + return ClickOutcome::Nil; + } + } + + m_detectionState = DetectionState::WaitingForMove; + m_moveAccumulator = 0.0f; + + m_tryBeginTime = now; + } + else if (clickEvent == ClickEvent::Up) + { + const auto clickOutcome = [detectionState = m_detectionState] { + if (detectionState == DetectionState::WaitingForMove) + { + return ClickOutcome::Click; + } + if (detectionState == DetectionState::Moved) + { + return ClickOutcome::Release; + } + return ClickOutcome::Nil; + }(); + + m_detectionState = DetectionState::Nil; + return clickOutcome; + } + + if (m_detectionState == DetectionState::WaitingForMove) + { + // only allow the action to begin if the mouse has been moved a small amount + m_moveAccumulator += ScreenVectorLength(cursorDelta); + if (m_moveAccumulator > m_deadZone) + { + m_detectionState = DetectionState::Moved; + return ClickOutcome::Move; + } + } + + return ClickOutcome::Nil; + } +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h new file mode 100644 index 0000000000..997ccd07d9 --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h @@ -0,0 +1,75 @@ +/* + * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or + * its licensors. + * + * For complete copyright and license terms please see the LICENSE at the root of this + * distribution (the "License"). All use of this software is governed by the License, + * or, if provided, by the license below or the license accompanying this file. Do not + * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * + */ + +#pragma once + +#include + +#include + +namespace AzFramework +{ + struct ScreenVector; + + //! Utility class to help detect different types of mouse click (mouse down and up with + //! no movement), mouse move (down and initial move after some threshold) and mouse release + //! (mouse down with movement and then mouse up). + class ClickDetector + { + //! Alias for recording time of mouse down events + using Time = std::chrono::time_point; + + public: + //! Internal representation of click event (map from external event for this when + //! calling DetectClick). + enum class ClickEvent + { + Nil, + Down, + Up + }; + + //! The type of mouse click. + enum class ClickOutcome + { + Nil, //!< Not recognized. + Move, //!< Initial move after mouse down. + Click, //!< Mouse down and up with no intermediate movement. + Release //!< Mouse down with movement and then mouse up. + }; + + //! Called from any type of 'handle event' function. + ClickOutcome DetectClick(ClickEvent clickEvent, const ScreenVector& cursorDelta); + + void SetDoubleClickInterval(float doubleClickInterval); + + private: + //! Internal state of ClickDetector based on incoming events. + enum class DetectionState + { + Nil, //!< Initial state + WaitingForMove, //! Mouse down has happened but mouse hasn't yet moved. + Moved //! Mouse has moved, no longer will be counted as a click. + }; + + float m_moveAccumulator = 0.0f; //!< How far the mouse has moved after mouse down. + float m_deadZone = 2.0f; //!< How far to move before a click is cancelled (when Move will fire). + float m_doubleClickInterval = 0.4f; //!< Default double click interval, can be overridden. + DetectionState m_detectionState; //!< Internal state of ClickDetector. + AZStd::optional