diff --git a/AutomatedTesting/Gem/PythonTests/AWS/README.md b/AutomatedTesting/Gem/PythonTests/AWS/README.md index 1429fc487f..1bb36f178d 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/README.md +++ b/AutomatedTesting/Gem/PythonTests/AWS/README.md @@ -11,7 +11,7 @@ 3. Open a new Command Prompt window at the engine root and set the following environment variables: Set O3DE_AWS_PROJECT_NAME=AWSAUTO Set O3DE_AWS_DEPLOY_REGION=us-east-1 - Set ASSUME_ROLE_ARN="arn:aws:iam::{your_aws_account_id}:role/o3de-automation-tests" + Set ASSUME_ROLE_ARN=arn:aws:iam::{your_aws_account_id}:role/o3de-automation-tests Set COMMIT_ID=HEAD 4. In the same Command Prompt window, Deploy the CDK applications for AWS gems by running deploy_cdk_applications.cmd. diff --git a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py index a0a53f92b5..34b2217916 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py +++ b/AutomatedTesting/Gem/PythonTests/AWS/Windows/aws_metrics/aws_metrics_automation_test.py @@ -31,7 +31,7 @@ def setup(launcher: pytest.fixture, Set up the resource mapping configuration and start the log monitor. :param launcher: Client launcher for running the test level. :param asset_processor: asset_processor fixture. - :return log monitor object, metrics file path and the metrics stack name. + :return log monitor object. """ asset_processor.start() asset_processor.wait_for_idle() @@ -73,12 +73,11 @@ def monitor_metrics_submission(log_monitor: pytest.fixture) -> None: f'unexpected_lines values: {unexpected_lines}') -def query_metrics_from_s3(aws_metrics_utils: pytest.fixture, resource_mappings: pytest.fixture, stack_name: str) -> None: +def query_metrics_from_s3(aws_metrics_utils: pytest.fixture, resource_mappings: pytest.fixture) -> None: """ Verify that the metrics events are delivered to the S3 bucket and can be queried. :param aws_metrics_utils: aws_metrics_utils fixture. :param resource_mappings: resource_mappings fixture. - :param stack_name: name of the CloudFormation stack. """ aws_metrics_utils.verify_s3_delivery( resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsBucketName') @@ -89,23 +88,24 @@ def query_metrics_from_s3(aws_metrics_utils: pytest.fixture, resource_mappings: resource_mappings.get_resource_name_id('AWSMetrics.EventsCrawlerName')) # Remove the events_json table if exists so that the sample query can create a table with the same name. - aws_metrics_utils.delete_table(f'{stack_name}-eventsdatabase', 'events_json') - aws_metrics_utils.run_named_queries(f'{stack_name}-AthenaWorkGroup') + aws_metrics_utils.delete_table(resource_mappings.get_resource_name_id('AWSMetrics.EventDatabaseName'), 'events_json') + aws_metrics_utils.run_named_queries(resource_mappings.get_resource_name_id('AWSMetrics.AthenaWorkGroupName')) logger.info('Query metrics from S3 successfully.') -def verify_operational_metrics(aws_metrics_utils: pytest.fixture, stack_name: str, start_time: datetime) -> None: +def verify_operational_metrics(aws_metrics_utils: pytest.fixture, + resource_mappings: pytest.fixture, start_time: datetime) -> None: """ Verify that operational health metrics are delivered to CloudWatch. - aws_metrics_utils: aws_metrics_utils fixture. - stack_name: name of the CloudFormation stack. - start_time: Time when the game launcher starts. + :param aws_metrics_utils: aws_metrics_utils fixture. + :param resource_mappings: resource_mappings fixture. + :param start_time: Time when the game launcher starts. """ aws_metrics_utils.verify_cloud_watch_delivery( 'AWS/Lambda', 'Invocations', [{'Name': 'FunctionName', - 'Value': f'{stack_name}-AnalyticsProcessingLambda'}], + 'Value': resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsProcessingLambdaName')}], start_time) logger.info('AnalyticsProcessingLambda metrics are sent to CloudWatch.') @@ -113,7 +113,7 @@ def verify_operational_metrics(aws_metrics_utils: pytest.fixture, stack_name: st 'AWS/Lambda', 'Invocations', [{'Name': 'FunctionName', - 'Value': f'{stack_name}-EventsProcessingLambda'}], + 'Value': resource_mappings.get_resource_name_id('AWSMetrics.EventProcessingLambdaName')}], start_time) logger.info('EventsProcessingLambda metrics are sent to CloudWatch.') @@ -139,7 +139,6 @@ def update_kinesis_analytics_application_status(aws_metrics_utils: pytest.fixtur @pytest.mark.usefixtures('resource_mappings') @pytest.mark.parametrize('assume_role_arn', [constants.ASSUME_ROLE_ARN]) @pytest.mark.parametrize('feature_name', [AWS_METRICS_FEATURE_NAME]) -@pytest.mark.parametrize('level', ['AWS/Metrics']) @pytest.mark.parametrize('profile_name', ['AWSAutomationTest']) @pytest.mark.parametrize('project', ['AutomatedTesting']) @pytest.mark.parametrize('region_name', [constants.AWS_REGION]) @@ -150,6 +149,7 @@ class TestAWSMetricsWindows(object): """ Test class to verify the real-time and batch analytics for metrics. """ + @pytest.mark.parametrize('level', ['AWS/Metrics']) def test_realtime_and_batch_analytics(self, level: str, launcher: pytest.fixture, @@ -157,7 +157,6 @@ class TestAWSMetricsWindows(object): workspace: pytest.fixture, aws_utils: pytest.fixture, resource_mappings: pytest.fixture, - stacks: typing.List, aws_metrics_utils: pytest.fixture): """ Verify that the metrics events are sent to CloudWatch and S3 for analytics. @@ -189,10 +188,10 @@ class TestAWSMetricsWindows(object): operational_threads = list() operational_threads.append( AWSMetricsThread(target=query_metrics_from_s3, - args=(aws_metrics_utils, resource_mappings, stacks[0]))) + args=(aws_metrics_utils, resource_mappings))) operational_threads.append( AWSMetricsThread(target=verify_operational_metrics, - args=(aws_metrics_utils, stacks[0], start_time))) + args=(aws_metrics_utils, resource_mappings, start_time))) operational_threads.append( AWSMetricsThread(target=update_kinesis_analytics_application_status, args=(aws_metrics_utils, resource_mappings, False))) @@ -201,10 +200,7 @@ class TestAWSMetricsWindows(object): for thread in operational_threads: thread.join() - # Clear the analytics bucket objects so that the S3 bucket can be destroyed during tear down. - aws_metrics_utils.empty_bucket( - resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsBucketName')) - + @pytest.mark.parametrize('level', ['AWS/Metrics']) def test_unauthorized_user_request_rejected(self, level: str, launcher: pytest.fixture, @@ -227,3 +223,13 @@ class TestAWSMetricsWindows(object): halt_on_unexpected=True) assert result, 'Metrics events are sent successfully by unauthorized user' logger.info('Unauthorized user is rejected to send metrics.') + + def test_clean_up_s3_bucket(self, + aws_utils: pytest.fixture, + resource_mappings: pytest.fixture, + aws_metrics_utils: pytest.fixture): + """ + Clear the analytics bucket objects so that the S3 bucket can be destroyed during tear down. + """ + aws_metrics_utils.empty_bucket( + resource_mappings.get_resource_name_id('AWSMetrics.AnalyticsBucketName')) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index a54229f6ba..7fd3b3a241 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -21,7 +21,7 @@ add_subdirectory(assetpipeline) add_subdirectory(atom_renderer) ## Physics ## -add_subdirectory(physics) +add_subdirectory(Physics) ## ScriptCanvas ## add_subdirectory(scripting) diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py index fec9d9880b..154b5730d7 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/editor_entity_utils.py @@ -20,6 +20,7 @@ import azlmbr.legacy.general as general # Helper file Imports from editor_python_test_tools.utils import Report + class EditorComponent: """ EditorComponent class used to set and get the component property value using path @@ -28,7 +29,6 @@ class EditorComponent: which also assigns self.id and self.type_id to the EditorComponent object. """ - # Methods def get_component_name(self) -> str: """ Used to get name of component @@ -87,6 +87,13 @@ class EditorComponent: outcome.IsSuccess() ), f"Failure: Could not set value to '{self.get_component_name()}' : '{component_property_path}'" + def is_enabled(self): + """ + Used to verify if the component is enabled. + :return: True if enabled, otherwise False. + """ + return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", self.id) + @staticmethod def get_type_ids(component_names: list) -> list: """ @@ -254,7 +261,7 @@ class EditorEntity: def get_components_of_type(self, component_names: list) -> List[EditorComponent]: """ Used to get components of type component_name that already exists on Entity - :param component_name: Name to component to check + :param component_names: List of names of components to check :return: List of Entity Component objects of given component name """ component_list = [] @@ -318,3 +325,39 @@ class EditorEntity: editor.EditorEntityAPIBus(bus.Event, "SetStartStatus", self.id, status_to_set) set_status = self.get_start_status() assert set_status == status_to_set, f"Failed to set start status of {desired_start_status} to {self.get_name}" + + def delete(self) -> None: + """ + Used to delete the Entity. + :return: None + """ + editor.ToolsApplicationRequestBus(bus.Broadcast, "DeleteEntityById", self.id) + + def set_visibility_state(self, is_visible: bool) -> None: + """ + Sets the visibility state on the object to visible or not visible. + :param is_visible: True for making visible, False to make not visible. + :return: None + """ + editor.EditorEntityAPIBus(bus.Event, "SetVisibilityState", self.id, is_visible) + + def exists(self) -> bool: + """ + Used to verify if the Entity exists. + :return: True if the Entity exists, False otherwise. + """ + return editor.ToolsApplicationRequestBus(bus.Broadcast, "EntityExists", self.id) + + def is_hidden(self) -> bool: + """ + Gets the "isHidden" value from the Entity. + :return: True if "isHidden" is enabled, False otherwise. + """ + return editor.EditorEntityInfoRequestBus(bus.Event, "IsHidden", self.id) + + def is_visible(self) -> bool: + """ + Gets the "isVisible" value from the Entity. + :return: True if "isVisible" is enabled, False otherwise. + """ + return editor.EditorEntityInfoRequestBus(bus.Event, "IsVisible", self.id) diff --git a/AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/Physics/CMakeLists.txt similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/CMakeLists.txt rename to AutomatedTesting/Gem/PythonTests/Physics/CMakeLists.txt diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py b/AutomatedTesting/Gem/PythonTests/Physics/TestSuite_InDevelopment.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/TestSuite_InDevelopment.py rename to AutomatedTesting/Gem/PythonTests/Physics/TestSuite_InDevelopment.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Main.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py rename to AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Main.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main_Optimized.py b/AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Main_Optimized.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main_Optimized.py rename to AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Main_Optimized.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Periodic.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py rename to AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Periodic.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py b/AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Sandbox.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py rename to AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Sandbox.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Utils.py b/AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Utils.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/TestSuite_Utils.py rename to AutomatedTesting/Gem/PythonTests/Physics/TestSuite_Utils.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/__init__.py b/AutomatedTesting/Gem/PythonTests/Physics/__init__.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/__init__.py rename to AutomatedTesting/Gem/PythonTests/Physics/__init__.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/Physics_DynamicSliceWithPhysNotSpawnsStaticSlice.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/Physics_DynamicSliceWithPhysNotSpawnsStaticSlice.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/Physics_DynamicSliceWithPhysNotSpawnsStaticSlice.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/Physics_DynamicSliceWithPhysNotSpawnsStaticSlice.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/Physics_UndoRedoWorksOnEntityWithPhysComponents.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/Physics_UndoRedoWorksOnEntityWithPhysComponents.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/Physics_UndoRedoWorksOnEntityWithPhysComponents.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/Physics_UndoRedoWorksOnEntityWithPhysComponents.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/Physics_VerifyColliderRigidBodyMeshAndTerrainWorkTogether.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/Physics_VerifyColliderRigidBodyMeshAndTerrainWorkTogether.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/Physics_VerifyColliderRigidBodyMeshAndTerrainWorkTogether.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/Physics_VerifyColliderRigidBodyMeshAndTerrainWorkTogether.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/Physics_WorldBodyBusWorksOnEditorComponents.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/Physics_WorldBodyBusWorksOnEditorComponents.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/Physics_WorldBodyBusWorksOnEditorComponents.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/Physics_WorldBodyBusWorksOnEditorComponents.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/character_controller/CharacterController_SwitchLevels.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/character_controller/CharacterController_SwitchLevels.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/character_controller/CharacterController_SwitchLevels.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/character_controller/CharacterController_SwitchLevels.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_AddColliderComponent.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_AddColliderComponent.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_AddColliderComponent.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_AddColliderComponent.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_AddingNewGroupWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_AddingNewGroupWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_AddingNewGroupWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_AddingNewGroupWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_BoxShapeEditting.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_BoxShapeEditting.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_BoxShapeEditting.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_BoxShapeEditting.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_CapsuleShapeEditting.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_CapsuleShapeEditting.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_CapsuleShapeEditting.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_CapsuleShapeEditting.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_CheckDefaultShapeSettingIsPxMesh.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_CheckDefaultShapeSettingIsPxMesh.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_CheckDefaultShapeSettingIsPxMesh.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_CheckDefaultShapeSettingIsPxMesh.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_ColliderPositionOffset.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_ColliderPositionOffset.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_ColliderPositionOffset.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_ColliderPositionOffset.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_ColliderRotationOffset.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_ColliderRotationOffset.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_ColliderRotationOffset.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_ColliderRotationOffset.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_CollisionGroupsWorkflow.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_CollisionGroupsWorkflow.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_CollisionGroupsWorkflow.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_CollisionGroupsWorkflow.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_DiffCollisionGroupDiffCollidingLayersNotCollide.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_DiffCollisionGroupDiffCollidingLayersNotCollide.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_DiffCollisionGroupDiffCollidingLayersNotCollide.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_DiffCollisionGroupDiffCollidingLayersNotCollide.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_MultipleSurfaceSlots.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_MultipleSurfaceSlots.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_MultipleSurfaceSlots.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_MultipleSurfaceSlots.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_NoneCollisionGroupSameLayerNotCollide.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_NoneCollisionGroupSameLayerNotCollide.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_NoneCollisionGroupSameLayerNotCollide.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_NoneCollisionGroupSameLayerNotCollide.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshAutoAssignedWhenAddingRenderMeshComponent.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshAutoAssignedWhenAddingRenderMeshComponent.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshAutoAssignedWhenAddingRenderMeshComponent.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshAutoAssignedWhenAddingRenderMeshComponent.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshAutoAssignedWhenModifyingRenderMeshComponent.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshAutoAssignedWhenModifyingRenderMeshComponent.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshAutoAssignedWhenModifyingRenderMeshComponent.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshAutoAssignedWhenModifyingRenderMeshComponent.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshConvexMeshCollides.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshConvexMeshCollides.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshConvexMeshCollides.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshConvexMeshCollides.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshErrorIfNoMesh.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshErrorIfNoMesh.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshErrorIfNoMesh.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshErrorIfNoMesh.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshNotAutoAssignedWhenNoPhysicsFbx.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshNotAutoAssignedWhenNoPhysicsFbx.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_PxMeshNotAutoAssignedWhenNoPhysicsFbx.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_PxMeshNotAutoAssignedWhenNoPhysicsFbx.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_SameCollisionGroupDiffLayersCollide.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_SameCollisionGroupDiffLayersCollide.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_SameCollisionGroupDiffLayersCollide.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_SameCollisionGroupDiffLayersCollide.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_SameCollisionGroupSameCustomLayerCollide.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_SameCollisionGroupSameCustomLayerCollide.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_SameCollisionGroupSameCustomLayerCollide.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_SameCollisionGroupSameCustomLayerCollide.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_SameCollisionGroupSameLayerCollide.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_SameCollisionGroupSameLayerCollide.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_SameCollisionGroupSameLayerCollide.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_SameCollisionGroupSameLayerCollide.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_SphereShapeEditting.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_SphereShapeEditting.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_SphereShapeEditting.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_SphereShapeEditting.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_TriggerPassThrough.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_TriggerPassThrough.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/collider/Collider_TriggerPassThrough.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/collider/Collider_TriggerPassThrough.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_CapsuleShapedForce.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_CapsuleShapedForce.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_CapsuleShapedForce.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_CapsuleShapedForce.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_DirectionHasNoAffectOnTotalForce.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_DirectionHasNoAffectOnTotalForce.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_DirectionHasNoAffectOnTotalForce.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_DirectionHasNoAffectOnTotalForce.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_HighValuesDirectionAxesWorkWithNoError.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_HighValuesDirectionAxesWorkWithNoError.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_HighValuesDirectionAxesWorkWithNoError.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_HighValuesDirectionAxesWorkWithNoError.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ImpulsesBoxShapedRigidBody.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ImpulsesBoxShapedRigidBody.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ImpulsesBoxShapedRigidBody.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ImpulsesBoxShapedRigidBody.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ImpulsesCapsuleShapedRigidBody.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ImpulsesCapsuleShapedRigidBody.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ImpulsesCapsuleShapedRigidBody.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ImpulsesCapsuleShapedRigidBody.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ImpulsesPxMeshShapedRigidBody.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ImpulsesPxMeshShapedRigidBody.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ImpulsesPxMeshShapedRigidBody.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ImpulsesPxMeshShapedRigidBody.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_LinearDampingForceOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_LinearDampingForceOnRigidBodies.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_LinearDampingForceOnRigidBodies.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_LinearDampingForceOnRigidBodies.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_LocalSpaceForceOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_LocalSpaceForceOnRigidBodies.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_LocalSpaceForceOnRigidBodies.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_LocalSpaceForceOnRigidBodies.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_MovingForceRegionChangesNetForce.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_MovingForceRegionChangesNetForce.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_MovingForceRegionChangesNetForce.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_MovingForceRegionChangesNetForce.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_MultipleComponentsCombineForces.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_MultipleComponentsCombineForces.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_MultipleComponentsCombineForces.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_MultipleComponentsCombineForces.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_MultipleForcesInSameComponentCombineForces.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_MultipleForcesInSameComponentCombineForces.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_MultipleForcesInSameComponentCombineForces.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_MultipleForcesInSameComponentCombineForces.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_NoQuiverOnHighLinearDampingForce.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_NoQuiverOnHighLinearDampingForce.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_NoQuiverOnHighLinearDampingForce.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_NoQuiverOnHighLinearDampingForce.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ParentChildForcesCombineForces.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ParentChildForcesCombineForces.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ParentChildForcesCombineForces.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ParentChildForcesCombineForces.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_PointForceOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_PointForceOnRigidBodies.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_PointForceOnRigidBodies.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_PointForceOnRigidBodies.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_PositionOffset.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_PositionOffset.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_PositionOffset.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_PositionOffset.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_PxMeshShapedForce.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_PxMeshShapedForce.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_PxMeshShapedForce.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_PxMeshShapedForce.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_RotationalOffset.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_RotationalOffset.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_RotationalOffset.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_RotationalOffset.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SimpleDragForceOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SimpleDragForceOnRigidBodies.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SimpleDragForceOnRigidBodies.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SimpleDragForceOnRigidBodies.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SliceFileInstantiates.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SliceFileInstantiates.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SliceFileInstantiates.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SliceFileInstantiates.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SmallMagnitudeDeviationOnLargeForces.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SmallMagnitudeDeviationOnLargeForces.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SmallMagnitudeDeviationOnLargeForces.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SmallMagnitudeDeviationOnLargeForces.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SphereShapedForce.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SphereShapedForce.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SphereShapedForce.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SphereShapedForce.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SplineForceOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SplineForceOnRigidBodies.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SplineForceOnRigidBodies.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SplineForceOnRigidBodies.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SplineRegionWithModifiedTransform.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SplineRegionWithModifiedTransform.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_SplineRegionWithModifiedTransform.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_SplineRegionWithModifiedTransform.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_WithNonTriggerColliderWarning.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_WithNonTriggerColliderWarning.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_WithNonTriggerColliderWarning.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_WithNonTriggerColliderWarning.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_WorldSpaceForceOnRigidBodies.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_WorldSpaceForceOnRigidBodies.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_WorldSpaceForceOnRigidBodies.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_WorldSpaceForceOnRigidBodies.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroLinearDampingDoesNothing.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroLinearDampingDoesNothing.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroLinearDampingDoesNothing.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroLinearDampingDoesNothing.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroLocalSpaceForceDoesNothing.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroLocalSpaceForceDoesNothing.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroLocalSpaceForceDoesNothing.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroLocalSpaceForceDoesNothing.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroPointForceDoesNothing.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroPointForceDoesNothing.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroPointForceDoesNothing.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroPointForceDoesNothing.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroSimpleDragForceDoesNothing.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroSimpleDragForceDoesNothing.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroSimpleDragForceDoesNothing.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroSimpleDragForceDoesNothing.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroSplineForceDoesNothing.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroSplineForceDoesNothing.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroSplineForceDoesNothing.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroSplineForceDoesNothing.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroWorldSpaceForceDoesNothing.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroWorldSpaceForceDoesNothing.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/force_region/ForceRegion_ZeroWorldSpaceForceDoesNothing.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/force_region/ForceRegion_ZeroWorldSpaceForceDoesNothing.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/JointsHelper.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/JointsHelper.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/JointsHelper.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/JointsHelper.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_Ball2BodiesConstrained.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_Ball2BodiesConstrained.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_Ball2BodiesConstrained.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_Ball2BodiesConstrained.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_BallBreakable.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_BallBreakable.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_BallBreakable.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_BallBreakable.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_BallLeadFollowerCollide.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_BallLeadFollowerCollide.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_BallLeadFollowerCollide.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_BallLeadFollowerCollide.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_BallNoLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_BallNoLimitsConstrained.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_BallNoLimitsConstrained.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_BallNoLimitsConstrained.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_BallSoftLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_BallSoftLimitsConstrained.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_BallSoftLimitsConstrained.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_BallSoftLimitsConstrained.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_Fixed2BodiesConstrained.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_Fixed2BodiesConstrained.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_Fixed2BodiesConstrained.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_Fixed2BodiesConstrained.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_FixedBreakable.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_FixedBreakable.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_FixedBreakable.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_FixedBreakable.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_FixedLeadFollowerCollide.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_FixedLeadFollowerCollide.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_FixedLeadFollowerCollide.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_FixedLeadFollowerCollide.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_GlobalFrameConstrained.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_GlobalFrameConstrained.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_GlobalFrameConstrained.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_GlobalFrameConstrained.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_Hinge2BodiesConstrained.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_Hinge2BodiesConstrained.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_Hinge2BodiesConstrained.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_Hinge2BodiesConstrained.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_HingeBreakable.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_HingeBreakable.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_HingeBreakable.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_HingeBreakable.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_HingeLeadFollowerCollide.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_HingeLeadFollowerCollide.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_HingeLeadFollowerCollide.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_HingeLeadFollowerCollide.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_HingeNoLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_HingeNoLimitsConstrained.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_HingeNoLimitsConstrained.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_HingeNoLimitsConstrained.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_HingeSoftLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_HingeSoftLimitsConstrained.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/joints/Joints_HingeSoftLimitsConstrained.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/joints/Joints_HingeSoftLimitsConstrained.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/AddModifyDelete_Utils.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/AddModifyDelete_Utils.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/AddModifyDelete_Utils.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/AddModifyDelete_Utils.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_CanBeAssignedToTerrain.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_CanBeAssignedToTerrain.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_CanBeAssignedToTerrain.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_CanBeAssignedToTerrain.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_CharacterController.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_CharacterController.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_CharacterController.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_CharacterController.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_ComponentsInSyncWithLibrary.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_ComponentsInSyncWithLibrary.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_ComponentsInSyncWithLibrary.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_ComponentsInSyncWithLibrary.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DefaultLibraryConsistentOnAllFeatures.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DefaultLibraryConsistentOnAllFeatures.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DefaultLibraryConsistentOnAllFeatures.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DefaultLibraryConsistentOnAllFeatures.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DefaultLibraryUpdatedAcrossLevels_after.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DefaultLibraryUpdatedAcrossLevels_after.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DefaultLibraryUpdatedAcrossLevels_after.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DefaultLibraryUpdatedAcrossLevels_after.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DefaultLibraryUpdatedAcrossLevels_before.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DefaultLibraryUpdatedAcrossLevels_before.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DefaultLibraryUpdatedAcrossLevels_before.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DefaultLibraryUpdatedAcrossLevels_before.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DefaultMaterialLibraryChangesWork.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DefaultMaterialLibraryChangesWork.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DefaultMaterialLibraryChangesWork.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DefaultMaterialLibraryChangesWork.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DynamicFriction.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DynamicFriction.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_DynamicFriction.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_DynamicFriction.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_EmptyLibraryUsesDefault.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_EmptyLibraryUsesDefault.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_EmptyLibraryUsesDefault.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_EmptyLibraryUsesDefault.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_FrictionCombine.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_FrictionCombine.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_FrictionCombine.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_FrictionCombine.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_FrictionCombinePriorityOrder.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_FrictionCombinePriorityOrder.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_FrictionCombinePriorityOrder.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_FrictionCombinePriorityOrder.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryChangesReflectInstantly.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryChangesReflectInstantly.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryChangesReflectInstantly.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryChangesReflectInstantly.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryClearingAssignsDefault.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryClearingAssignsDefault.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryClearingAssignsDefault.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryClearingAssignsDefault.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryCrudOperationsReflectOnCharacterController.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryCrudOperationsReflectOnCharacterController.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryCrudOperationsReflectOnCharacterController.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryCrudOperationsReflectOnCharacterController.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryCrudOperationsReflectOnCollider.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryCrudOperationsReflectOnCollider.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryCrudOperationsReflectOnCollider.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryCrudOperationsReflectOnCollider.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryCrudOperationsReflectOnRagdollBones.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryCrudOperationsReflectOnRagdollBones.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryCrudOperationsReflectOnRagdollBones.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryCrudOperationsReflectOnRagdollBones.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryCrudOperationsReflectOnTerrain.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryCrudOperationsReflectOnTerrain.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryCrudOperationsReflectOnTerrain.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryCrudOperationsReflectOnTerrain.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryUpdatedAcrossLevels.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryUpdatedAcrossLevels.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_LibraryUpdatedAcrossLevels.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_LibraryUpdatedAcrossLevels.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_NoEffectIfNoColliderShape.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_NoEffectIfNoColliderShape.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_NoEffectIfNoColliderShape.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_NoEffectIfNoColliderShape.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_PerFaceMaterialGetsCorrectMaterial.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_PerFaceMaterialGetsCorrectMaterial.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_PerFaceMaterialGetsCorrectMaterial.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_PerFaceMaterialGetsCorrectMaterial.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_RagdollBones.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_RagdollBones.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_RagdollBones.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_RagdollBones.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_Restitution.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_Restitution.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_Restitution.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_Restitution.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_RestitutionCombine.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_RestitutionCombine.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_RestitutionCombine.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_RestitutionCombine.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_RestitutionCombinePriorityOrder.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_RestitutionCombinePriorityOrder.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_RestitutionCombinePriorityOrder.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_RestitutionCombinePriorityOrder.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_StaticFriction.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_StaticFriction.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Material_StaticFriction.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Material_StaticFriction.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/material/Physmaterial_Editor.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/material/Physmaterial_Editor.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/material/Physmaterial_Editor.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/material/Physmaterial_Editor.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/ragdoll/Ragdoll_AddPhysxRagdollComponentWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/ragdoll/Ragdoll_AddPhysxRagdollComponentWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/ragdoll/Ragdoll_AddPhysxRagdollComponentWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/ragdoll/Ragdoll_AddPhysxRagdollComponentWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/ragdoll/Ragdoll_LevelSwitchDoesNotCrash.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/ragdoll/Ragdoll_LevelSwitchDoesNotCrash.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/ragdoll/Ragdoll_LevelSwitchDoesNotCrash.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/ragdoll/Ragdoll_LevelSwitchDoesNotCrash.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/ragdoll/Ragdoll_OldRagdollSerializationNoErrors.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/ragdoll/Ragdoll_OldRagdollSerializationNoErrors.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/ragdoll/Ragdoll_OldRagdollSerializationNoErrors.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/ragdoll/Ragdoll_OldRagdollSerializationNoErrors.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/ragdoll/Ragdoll_WorldBodyBusWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/ragdoll/Ragdoll_WorldBodyBusWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/ragdoll/Ragdoll_WorldBodyBusWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/ragdoll/Ragdoll_WorldBodyBusWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_AddRigidBodyComponent.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_AddRigidBodyComponent.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_AddRigidBodyComponent.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_AddRigidBodyComponent.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_AngularDampingAffectsRotation.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_AngularDampingAffectsRotation.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_AngularDampingAffectsRotation.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_AngularDampingAffectsRotation.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_COM_ComputingWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_COM_ComputingWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_COM_ComputingWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_COM_ComputingWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_COM_ManualSettingWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_COM_ManualSettingWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_COM_ManualSettingWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_COM_ManualSettingWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_COM_NotIncludesTriggerShapes.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_COM_NotIncludesTriggerShapes.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_COM_NotIncludesTriggerShapes.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_COM_NotIncludesTriggerShapes.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_ComputeInertiaWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_ComputeInertiaWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_ComputeInertiaWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_ComputeInertiaWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_EnablingGravityWorksPoC.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_EnablingGravityWorksPoC.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_EnablingGravityWorksPoC.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_EnablingGravityWorksPoC.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_EnablingGravityWorksUsingNotificationsPoC.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_EnablingGravityWorksUsingNotificationsPoC.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_EnablingGravityWorksUsingNotificationsPoC.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_EnablingGravityWorksUsingNotificationsPoC.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_InitialAngularVelocity.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_InitialAngularVelocity.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_InitialAngularVelocity.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_InitialAngularVelocity.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_InitialLinearVelocity.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_InitialLinearVelocity.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_InitialLinearVelocity.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_InitialLinearVelocity.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_KinematicModeWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_KinematicModeWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_KinematicModeWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_KinematicModeWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_LinearDampingAffectsMotion.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_LinearDampingAffectsMotion.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_LinearDampingAffectsMotion.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_LinearDampingAffectsMotion.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_MassDifferentValuesWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_MassDifferentValuesWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_MassDifferentValuesWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_MassDifferentValuesWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_MaxAngularVelocityWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_MaxAngularVelocityWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_MaxAngularVelocityWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_MaxAngularVelocityWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_MomentOfInertiaManualSetting.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_MomentOfInertiaManualSetting.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_MomentOfInertiaManualSetting.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_MomentOfInertiaManualSetting.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_SetGravityWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_SetGravityWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_SetGravityWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_SetGravityWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_SleepWhenBelowKineticThreshold.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_SleepWhenBelowKineticThreshold.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_SleepWhenBelowKineticThreshold.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_SleepWhenBelowKineticThreshold.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_StartAsleepWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_StartAsleepWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_StartAsleepWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_StartAsleepWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_StartGravityEnabledWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_StartGravityEnabledWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/rigid_body/RigidBody_StartGravityEnabledWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/rigid_body/RigidBody_StartGravityEnabledWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_CollisionEvents.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_CollisionEvents.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_CollisionEvents.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_CollisionEvents.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_GetCollisionNameReturnsName.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_GetCollisionNameReturnsName.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_GetCollisionNameReturnsName.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_GetCollisionNameReturnsName.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_GetCollisionNameReturnsNothingWhenHasToggledLayer.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_GetCollisionNameReturnsNothingWhenHasToggledLayer.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_GetCollisionNameReturnsNothingWhenHasToggledLayer.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_GetCollisionNameReturnsNothingWhenHasToggledLayer.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_MultipleRaycastNode.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_MultipleRaycastNode.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_MultipleRaycastNode.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_MultipleRaycastNode.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_OverlapNode.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_OverlapNode.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_OverlapNode.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_OverlapNode.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_PostPhysicsUpdate.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_PostPhysicsUpdate.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_PostPhysicsUpdate.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_PostPhysicsUpdate.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_PostUpdateEvent.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_PostUpdateEvent.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_PostUpdateEvent.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_PostUpdateEvent.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_PreUpdateEvent.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_PreUpdateEvent.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_PreUpdateEvent.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_PreUpdateEvent.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_SetKinematicTargetTransform.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_SetKinematicTargetTransform.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_SetKinematicTargetTransform.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_SetKinematicTargetTransform.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_ShapeCast.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_ShapeCast.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_ShapeCast.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_ShapeCast.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_SpawnEntityWithPhysComponents.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_SpawnEntityWithPhysComponents.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_SpawnEntityWithPhysComponents.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_SpawnEntityWithPhysComponents.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_TriggerEvents.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_TriggerEvents.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/script_canvas/ScriptCanvas_TriggerEvents.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/script_canvas/ScriptCanvas_TriggerEvents.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/shape_collider/ShapeCollider_CanBeAddedWitNoWarnings.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/shape_collider/ShapeCollider_CanBeAddedWitNoWarnings.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/shape_collider/ShapeCollider_CanBeAddedWitNoWarnings.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/shape_collider/ShapeCollider_CanBeAddedWitNoWarnings.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/shape_collider/ShapeCollider_CylinderShapeCollides.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/shape_collider/ShapeCollider_CylinderShapeCollides.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/shape_collider/ShapeCollider_CylinderShapeCollides.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/shape_collider/ShapeCollider_CylinderShapeCollides.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/shape_collider/ShapeCollider_InactiveWhenNoShapeComponent.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/shape_collider/ShapeCollider_InactiveWhenNoShapeComponent.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/shape_collider/ShapeCollider_InactiveWhenNoShapeComponent.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/shape_collider/ShapeCollider_InactiveWhenNoShapeComponent.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/shape_collider/ShapeCollider_LargeNumberOfShapeCollidersWontCrashEditor.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/shape_collider/ShapeCollider_LargeNumberOfShapeCollidersWontCrashEditor.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/shape_collider/ShapeCollider_LargeNumberOfShapeCollidersWontCrashEditor.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/shape_collider/ShapeCollider_LargeNumberOfShapeCollidersWontCrashEditor.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_AddPhysTerrainComponent.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_AddPhysTerrainComponent.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_AddPhysTerrainComponent.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_AddPhysTerrainComponent.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_CanAddMultipleTerrainComponents.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_CanAddMultipleTerrainComponents.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_CanAddMultipleTerrainComponents.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_CanAddMultipleTerrainComponents.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_CollisionAgainstRigidBody.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_CollisionAgainstRigidBody.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_CollisionAgainstRigidBody.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_CollisionAgainstRigidBody.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_MultipleResolutionsValid.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_MultipleResolutionsValid.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_MultipleResolutionsValid.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_MultipleResolutionsValid.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_MultipleTerrainComponentsWarning.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_MultipleTerrainComponentsWarning.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_MultipleTerrainComponentsWarning.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_MultipleTerrainComponentsWarning.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_NoPhysTerrainComponentNoCollision.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_NoPhysTerrainComponentNoCollision.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_NoPhysTerrainComponentNoCollision.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_NoPhysTerrainComponentNoCollision.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_SpawnSecondTerrainComponentWarning.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_SpawnSecondTerrainComponentWarning.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_SpawnSecondTerrainComponentWarning.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_SpawnSecondTerrainComponentWarning.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_TerrainTexturePainterWorks.py b/AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_TerrainTexturePainterWorks.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/tests/terrain/Terrain_TerrainTexturePainterWorks.py rename to AutomatedTesting/Gem/PythonTests/Physics/tests/terrain/Terrain_TerrainTexturePainterWorks.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/utils/FileManagement.py b/AutomatedTesting/Gem/PythonTests/Physics/utils/FileManagement.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/utils/FileManagement.py rename to AutomatedTesting/Gem/PythonTests/Physics/utils/FileManagement.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_Managed_Files.py b/AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_Managed_Files.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_Managed_Files.py rename to AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_Managed_Files.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_Physmaterial_Editor.py b/AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_Physmaterial_Editor.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_Physmaterial_Editor.py rename to AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_Physmaterial_Editor.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_PhysxConfig_Default.py b/AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_PhysxConfig_Default.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_PhysxConfig_Default.py rename to AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_PhysxConfig_Default.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_PhysxConfig_Override.py b/AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_PhysxConfig_Override.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_PhysxConfig_Override.py rename to AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_PhysxConfig_Override.py diff --git a/AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_Tracer_PicksErrorsAndWarnings.py b/AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_Tracer_PicksErrorsAndWarnings.py similarity index 100% rename from AutomatedTesting/Gem/PythonTests/physics/utils/UtilTest_Tracer_PicksErrorsAndWarnings.py rename to AutomatedTesting/Gem/PythonTests/Physics/utils/UtilTest_Tracer_PicksErrorsAndWarnings.py diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt index f056623ecd..f91423324d 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt @@ -22,6 +22,21 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED AND AutomatedT AssetProcessor AutomatedTesting.Assets Editor + COMPONENT + Atom + ) + ly_add_pytest( + NAME AutomatedTesting::AtomRenderer_HydraTests_MainOptimized + TEST_SUITE main + PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_MainSuite_Optimized.py + TEST_SERIAL + TIMEOUT 600 + RUNTIME_DEPENDENCIES + AssetProcessor + AutomatedTesting.Assets + Editor + COMPONENT + Atom ) ly_add_pytest( NAME AutomatedTesting::AtomRenderer_HydraTests_Sandbox @@ -33,6 +48,8 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED AND AutomatedT AssetProcessor AutomatedTesting.Assets Editor + COMPONENT + Atom ) ly_add_pytest( NAME AutomatedTesting::AtomRenderer_HydraTests_GPUTests @@ -45,5 +62,18 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED AND AutomatedT AssetProcessor AutomatedTesting.Assets Editor + COMPONENT + Atom + ) + ly_add_pytest( + NAME AutomatedTesting::AtomRenderer_HydraTests_ShaderBuildPipeline + TEST_SUITE main + PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_ShaderBuildPipelineSuite.py + TEST_SERIAL + TIMEOUT 600 + RUNTIME_DEPENDENCIES + AssetProcessor + AutomatedTesting.Assets + Editor ) endif() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt new file mode 100644 index 0000000000..c0b64f40b7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt @@ -0,0 +1,55 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + /* + This is a dummy shader used to validate detection of "#included files" + */ + +#include + +#include "Test1Color.azsli" +#include + +ShaderResourceGroup DummySrg : SRG_PerDraw +{ + float4 m_color; +} + +struct VSInput +{ + float3 m_position : POSITION; + float4 m_color : COLOR0; +}; + +struct VSOutput +{ + float4 m_position : SV_Position; + float4 m_color : COLOR0; +}; + +VSOutput MainVS(VSInput vsInput) +{ + VSOutput OUT; + OUT.m_position = float4(vsInput.m_position, 1.0); + OUT.m_color = vsInput.m_color; + return OUT; +} + +struct PSOutput +{ + float4 m_color : SV_Target0; +}; + +PSOutput MainPS(VSOutput vsOutput) +{ + PSOutput OUT; + + OUT.m_color = GetTest1Color(DummySrg::m_color) + GetTest3Color(DummySrg::m_color); + + return OUT; +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt new file mode 100644 index 0000000000..b0eac1783e --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt @@ -0,0 +1,26 @@ +// This is a dummy shader used to validate detection of "#included files" +{ + "Source" : "DependencyValidation.azsl", + + "DepthStencilState" : { + "Depth" : { "Enable" : false, "CompareFunc" : "GreaterEqual" } + }, + + "DrawList" : "forward", + + "ProgramSettings": + { + "EntryPoints": + [ + { + "name": "MainVS", + "type": "Vertex" + }, + { + "name": "MainPS", + "type": "Fragment" + } + ] + } + +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt new file mode 100644 index 0000000000..7d097beafb --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt @@ -0,0 +1,18 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + /* + This is a dummy shader used to validate detection of "#included files" + */ + +#include "Test2Color.azsli" + +float4 GetTest1Color(float4 color) +{ + return color + GetTest2Color(color); +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt new file mode 100644 index 0000000000..2ef946b947 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt @@ -0,0 +1,16 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + /* + This is a dummy shader used to validate detection of "#included files" + */ + +float4 GetTest2Color(float4 color) +{ + return color * 0.5; +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt new file mode 100644 index 0000000000..73b0cca434 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt @@ -0,0 +1,16 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + /* + This is a dummy shader used to validate detection of "#included files" + */ + +float4 GetTest3Color(float4 color) +{ + return color * 0.13; +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py index cd10caf57b..a2e950e1dc 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py @@ -3,8 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that creates an entity and attaches Atom components to it for test verification. """ import os @@ -17,6 +15,7 @@ import azlmbr.asset as asset import azlmbr.entity as entity import azlmbr.legacy.general as general import azlmbr.editor as editor +import azlmbr.render as render sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) @@ -125,6 +124,19 @@ def run(): def verify_set_property(entity_obj, path, value): entity_obj.get_set_test(0, path, value) + # Verify cubemap generation + def verify_cubemap_generation(component_name, entity_obj): + # Initially Check if the component has Reflection Probe component + if not hydra.has_components(entity_obj.id, ["Reflection Probe"]): + raise ValueError(f"Given entity {entity_obj.name} has no Reflection Probe component") + render.EditorReflectionProbeBus(azlmbr.bus.Event, "BakeReflectionProbe", entity_obj.id) + + def get_value(): + hydra.get_component_property_value(entity_obj.components[0], "Cubemap|Baked Cubemap Path") + + TestHelper.wait_for_condition(lambda: get_value() != "", 20.0) + general.log(f"{component_name}_test: Cubemap is generated: {get_value() != ''}") + # Wait for Editor idle loop before executing Python hydra scripts. TestHelper.init_idle() @@ -215,6 +227,12 @@ def run(): # Display Mapper Component ComponentTests("Display Mapper") + # Reflection Probe Component + reflection_probe = "Reflection Probe" + ComponentTests( + reflection_probe, + lambda entity_obj: verify_required_component_addition(entity_obj, ["Box Shape"], reflection_probe), + lambda entity_obj: verify_cubemap_generation(reflection_probe, entity_obj),) if __name__ == "__main__": run() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DecalAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DecalAdded.py new file mode 100644 index 0000000000..d68e1f5844 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DecalAdded.py @@ -0,0 +1,151 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + decal_creation = ("Decal Entity successfully created", "Decal Entity failed to be created") + decal_component = ("Entity has a Decal component", "Entity failed to find Decal component") + material_property_set = ("Material property set on Decal component", "Couldn't set Material property on Decal component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_Decal_AddedToEntity(): + """ + Summary: + Tests the Decal component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Decal entity with no components. + 2) Add Decal component to Decal entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Set Material property on Decal component. + 9) Delete Decal entity. + 10) UNDO deletion. + 11) REDO deletion. + 12) Look for errors. + + :return: None + """ + import os + + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Decal entity with no components. + decal_name = "Decal (Atom)" + decal_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), decal_name) + Report.critical_result(Tests.decal_creation, decal_entity.exists()) + + # 2. Add Decal component to Decal entity. + decal_component = decal_entity.add_component(decal_name) + Report.critical_result(Tests.decal_component, decal_entity.has_component(decal_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not decal_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, decal_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + decal_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, decal_entity.is_hidden() is True) + + # 7. Test IsVisible. + decal_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, decal_entity.is_visible() is True) + + # 8. Set Material property on Decal component. + decal_material_property_path = "Controller|Configuration|Material" + decal_material_asset_path = os.path.join("AutomatedTesting", "Materials", "basic_grey.material") + decal_material_asset = asset.AssetCatalogRequestBus( + bus.Broadcast, "GetAssetIdByPath", decal_material_asset_path, math.Uuid(), False) + decal_component.set_component_property_value(decal_material_property_path, decal_material_asset) + get_material_property = decal_component.get_component_property_value(decal_material_property_path) + Report.result(Tests.material_property_set, get_material_property == decal_material_asset) + + # 9. Delete Decal entity. + decal_entity.delete() + Report.result(Tests.entity_deleted, not decal_entity.exists()) + + # 10. UNDO deletion. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.deletion_undo, decal_entity.exists()) + + # 11. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not decal_entity.exists()) + + # 12. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_Decal_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DepthOfFieldAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DepthOfFieldAdded.py new file mode 100644 index 0000000000..80284902ea --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DepthOfFieldAdded.py @@ -0,0 +1,173 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to Camera entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + camera_property_set = ("DepthOfField Entity set Camera Entity", "DepthOfField Entity could not set Camera Entity") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + depth_of_field_creation = ("DepthOfField Entity successfully created", "DepthOfField Entity failed to be created") + depth_of_field_component = ("Entity has a DepthOfField component", "Entity failed to find DepthOfField component") + depth_of_field_disabled = ("DepthOfField component disabled", "DepthOfField component was not disabled.") + post_fx_component = ("Entity has a Post FX Layer component", "Entity did not have a Post FX Layer component") + depth_of_field_enabled = ("DepthOfField component enabled", "DepthOfField component was not enabled.") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_DepthOfField_AddedToEntity(): + """ + Summary: + Tests the DepthOfField component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a DepthOfField entity with no components. + 2) Add a DepthOfField component to DepthOfField entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Verify DepthOfField component not enabled. + 6) Add Post FX Layer component since it is required by the DepthOfField component. + 7) Verify DepthOfField component is enabled. + 8) Enter/Exit game mode. + 9) Test IsHidden. + 10) Test IsVisible. + 11) Add Camera entity. + 12) Add Camera component to Camera entity. + 13) Set the DepthOfField components's Camera Entity to the newly created Camera entity. + 14) Delete DepthOfField entity. + 15) UNDO deletion. + 16) REDO deletion. + 17) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a DepthOfField entity with no components. + depth_of_field_name = "DepthOfField" + depth_of_field_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), depth_of_field_name) + Report.critical_result(Tests.depth_of_field_creation, depth_of_field_entity.exists()) + + # 2. Add a DepthOfField component to DepthOfField entity. + depth_of_field_component = depth_of_field_entity.add_component(depth_of_field_name) + Report.critical_result(Tests.depth_of_field_component, depth_of_field_entity.has_component(depth_of_field_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not depth_of_field_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, depth_of_field_entity.exists()) + + # 5. Verify DepthOfField component not enabled. + Report.result(Tests.depth_of_field_disabled, not depth_of_field_component.is_enabled()) + + # 6. Add Post FX Layer component since it is required by the DepthOfField component. + post_fx_layer = "PostFX Layer" + depth_of_field_entity.add_component(post_fx_layer) + Report.result(Tests.post_fx_component, depth_of_field_entity.has_component(post_fx_layer)) + + # 7. Verify DepthOfField component is enabled. + Report.result(Tests.depth_of_field_enabled, depth_of_field_component.is_enabled()) + + # 8. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 9. Test IsHidden. + depth_of_field_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, depth_of_field_entity.is_hidden() is True) + + # 10. Test IsVisible. + depth_of_field_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, depth_of_field_entity.is_visible() is True) + + # 11. Add Camera entity. + camera_name = "Camera" + camera_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), camera_name) + Report.result(Tests.camera_creation, camera_entity.exists()) + + # 12. Add Camera component to Camera entity. + camera_entity.add_component(camera_name) + Report.result(Tests.camera_component_added, camera_entity.has_component(camera_name)) + + # 13. Set the DepthOfField components's Camera Entity to the newly created Camera entity. + depth_of_field_camera_property_path = "Controller|Configuration|Camera Entity" + depth_of_field_component.set_component_property_value(depth_of_field_camera_property_path, camera_entity.id) + camera_entity_set = depth_of_field_component.get_component_property_value(depth_of_field_camera_property_path) + Report.result(Tests.camera_property_set, camera_entity.id == camera_entity_set) + + # 14. Delete DepthOfField entity. + depth_of_field_entity.delete() + Report.result(Tests.entity_deleted, not depth_of_field_entity.exists()) + + # 15. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, depth_of_field_entity.exists()) + + # 16. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not depth_of_field_entity.exists()) + + # 17. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_DepthOfField_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DirectionalLightAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DirectionalLightAdded.py new file mode 100644 index 0000000000..048e132df4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DirectionalLightAdded.py @@ -0,0 +1,157 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + directional_light_creation = ("Directional Light Entity successfully created", "Directional Light Entity failed to be created") + directional_light_component = ("Entity has a Directional Light component", "Entity failed to find Directional Light component") + shadow_camera_check = ("Directional Light component Shadow camera set", "Directional Light component Shadow camera was not set") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_DirectionalLight_AddedToEntity(): + """ + Summary: + Tests the Directional Light component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Directional Light entity with no components. + 2) Add Directional Light component to Directional Light entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Add Camera entity. + 9) Add Camera component to Camera entity + 10) Set the Directional Light component property Shadow|Camera to the Camera entity. + 11) Delete Directional Light entity. + 12) UNDO deletion. + 13) REDO deletion. + 14) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Directional Light entity with no components. + directional_light_name = "Directional Light" + directional_light_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), directional_light_name) + Report.critical_result(Tests.directional_light_creation, directional_light_entity.exists()) + + # 2. Add Directional Light component to Directional Light entity. + directional_light_component = directional_light_entity.add_component(directional_light_name) + Report.critical_result( + Tests.directional_light_component, directional_light_entity.has_component(directional_light_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not directional_light_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, directional_light_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + directional_light_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, directional_light_entity.is_hidden() is True) + + # 7. Test IsVisible. + directional_light_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, directional_light_entity.is_visible() is True) + + # 8. Add Camera entity. + camera_name = "Camera" + camera_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), camera_name) + Report.result(Tests.camera_creation, camera_entity.exists()) + + # 9. Add Camera component to Camera entity. + camera_entity.add_component(camera_name) + Report.result(Tests.camera_component_added, camera_entity.has_component(camera_name)) + + # 10. Set the Directional Light component property Shadow|Camera to the Camera entity. + shadow_camera_property_path = "Controller|Configuration|Shadow|Camera" + directional_light_component.set_component_property_value(shadow_camera_property_path, camera_entity.id) + shadow_camera_set = directional_light_component.get_component_property_value(shadow_camera_property_path) + Report.result(Tests.shadow_camera_check, camera_entity.id == shadow_camera_set) + + # 11. Delete DirectionalLight entity. + directional_light_entity.delete() + Report.result(Tests.entity_deleted, not directional_light_entity.exists()) + + # 12. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, directional_light_entity.exists()) + + # 13. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not directional_light_entity.exists()) + + # 14. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_DirectionalLight_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DisplayMapperAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DisplayMapperAdded.py new file mode 100644 index 0000000000..39d7acf4f4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_DisplayMapperAdded.py @@ -0,0 +1,137 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + display_mapper_creation = ("Display Mapper Entity successfully created", "Display Mapper Entity failed to be created") + display_mapper_component = ("Entity has a Display Mapper component", "Entity failed to find Display Mapper component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_DisplayMapper_AddedToEntity(): + """ + Summary: + Tests the Display Mapper component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Display Mapper entity with no components. + 2) Add Display Mapper component to Display Mapper entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Delete Display Mapper entity. + 9) UNDO deletion. + 10) REDO deletion. + 11) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Display Mapper entity with no components. + display_mapper = "Display Mapper" + display_mapper_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), f"{display_mapper}") + Report.critical_result(Tests.display_mapper_creation, display_mapper_entity.exists()) + + # 2. Add Display Mapper component to Display Mapper entity. + display_mapper_entity.add_component(display_mapper) + Report.critical_result(Tests.display_mapper_component, display_mapper_entity.has_component(display_mapper)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not display_mapper_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, display_mapper_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + display_mapper_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, display_mapper_entity.is_hidden() is True) + + # 7. Test IsVisible. + display_mapper_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, display_mapper_entity.is_visible() is True) + + # 8. Delete Display Mapper entity. + display_mapper_entity.delete() + Report.result(Tests.entity_deleted, not display_mapper_entity.exists()) + + # 9. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, display_mapper_entity.exists()) + + # 10. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not display_mapper_entity.exists()) + + # 11. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_DisplayMapper_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_ExposureControlAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_ExposureControlAdded.py new file mode 100644 index 0000000000..23a84435f7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_ExposureControlAdded.py @@ -0,0 +1,145 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + exposure_control_creation = ("ExposureControl Entity successfully created", "ExposureControl Entity failed to be created") + exposure_control_component = ("Entity has a Exposure Control component", "Entity failed to find Exposure Control component") + post_fx_component = ("Entity has a Post FX Layer component", "Entity did not have a Post FX Layer component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_ExposureControl_AddedToEntity(): + """ + Summary: + Tests the Exposure Control component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create an Exposure Control entity with no components. + 2) Add Exposure Control component to Exposure Control entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Add Post FX Layer component. + 9) Delete Exposure Control entity. + 10) UNDO deletion. + 11) REDO deletion. + 12) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Creation of Exposure Control entity with no components. + exposure_control_name = "Exposure Control" + exposure_control_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), f"{exposure_control_name}") + Report.critical_result(Tests.exposure_control_creation, exposure_control_entity.exists()) + + # 2. Add Exposure Control component to Exposure Control entity. + exposure_control_entity.add_component(exposure_control_name) + Report.critical_result( + Tests.exposure_control_component, exposure_control_entity.has_component(exposure_control_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not exposure_control_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, exposure_control_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + exposure_control_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, exposure_control_entity.is_hidden() is True) + + # 7. Test IsVisible. + exposure_control_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, exposure_control_entity.is_visible() is True) + + # 8. Add Post FX Layer component. + post_fx_layer_name = "PostFX Layer" + exposure_control_entity.add_component(post_fx_layer_name) + Report.result(Tests.post_fx_component, exposure_control_entity.has_component(post_fx_layer_name)) + + # 9. Delete ExposureControl entity. + exposure_control_entity.delete() + Report.result(Tests.entity_deleted, not exposure_control_entity.exists()) + + # 10. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, exposure_control_entity.exists()) + + # 11. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not exposure_control_entity.exists()) + + # 12. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_ExposureControl_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_GlobalSkylightIBLAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_GlobalSkylightIBLAdded.py new file mode 100644 index 0000000000..cc891f5929 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_GlobalSkylightIBLAdded.py @@ -0,0 +1,164 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + global_skylight_creation = ("Global Skylight (IBL) Entity successfully created", "Global Skylight (IBL) Entity failed to be created") + global_skylight_component = ("Entity has a Global Skylight (IBL) component", "Entity failed to find Global Skylight (IBL) component") + diffuse_image_set = ("Entity has the Diffuse Image set", "Entity did not the Diffuse Image set") + specular_image_set = ("Entity has the Specular Image set", "Entity did not the Specular Image set") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_GlobalSkylightIBL_AddedToEntity(): + """ + Summary: + Tests the Global Skylight (IBL) component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Global Skylight (IBL) entity with no components. + 2) Add Global Skylight (IBL) component to Global Skylight (IBL) entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Add Post FX Layer component. + 9) Add Camera component + 10) Delete Global Skylight (IBL) entity. + 11) UNDO deletion. + 12) REDO deletion. + 13) Look for errors. + + :return: None + """ + import os + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.asset_utils import Asset + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Global Skylight (IBL) entity with no components. + global_skylight_name = "Global Skylight (IBL)" + global_skylight_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), global_skylight_name) + Report.critical_result(Tests.global_skylight_creation, global_skylight_entity.exists()) + + # 2. Add Global Skylight (IBL) component to Global Skylight (IBL) entity. + global_skylight_component = global_skylight_entity.add_component(global_skylight_name) + Report.critical_result( + Tests.global_skylight_component, global_skylight_entity.has_component(global_skylight_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not global_skylight_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, global_skylight_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + global_skylight_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, global_skylight_entity.is_hidden() is True) + + # 7. Test IsVisible. + global_skylight_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, global_skylight_entity.is_visible() is True) + + # 8. Set the Diffuse Image asset on the Global Skylight (IBL) entity. + global_skylight_diffuse_image_property = "Controller|Configuration|Diffuse Image" + diffuse_image_path = os.path.join("LightingPresets", "greenwich_park_02_4k_iblskyboxcm.exr.streamingimage") + diffuse_image_asset = Asset.find_asset_by_path(diffuse_image_path, False) + global_skylight_component.set_component_property_value( + global_skylight_diffuse_image_property, diffuse_image_asset.id) + diffuse_image_set = global_skylight_component.get_component_property_value( + global_skylight_diffuse_image_property) + Report.result(Tests.diffuse_image_set, diffuse_image_set == diffuse_image_asset.id) + + # 9. Set the Specular Image asset on the Global Light (IBL) entity. + global_skylight_specular_image_property = "Controller|Configuration|Specular Image" + specular_image_path = os.path.join("LightingPresets", "greenwich_park_02_4k_iblskyboxcm.exr.streamingimage") + specular_image_asset = Asset.find_asset_by_path(specular_image_path, False) + global_skylight_component.set_component_property_value( + global_skylight_specular_image_property, specular_image_asset.id) + specular_image_added = global_skylight_component.get_component_property_value( + global_skylight_specular_image_property) + Report.result(Tests.specular_image_set, specular_image_added == specular_image_asset.id) + + # 10. Delete Global Skylight (IBL) entity. + global_skylight_entity.delete() + Report.result(Tests.entity_deleted, not global_skylight_entity.exists()) + + # 11. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, global_skylight_entity.exists()) + + # 12. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not global_skylight_entity.exists()) + + # 13. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_GlobalSkylightIBL_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightAdded.py new file mode 100644 index 0000000000..8b1432f1f7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightAdded.py @@ -0,0 +1,136 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + light_creation = ("Light Entity successfully created", "Light Entity failed to be created") + light_component = ("Entity has a Light component", "Entity failed to find Light component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_Light_AddedToEntity(): + """ + Summary: + Tests the Light component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Light entity with no components. + 2) Add Light component to the Light entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Delete Light entity. + 9) UNDO deletion. + 10) REDO deletion. + 11) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Light entity with no components. + light_name = "Light" + light_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), light_name) + Report.critical_result(Tests.light_creation, light_entity.exists()) + + # 2. Add Light component to the Light entity. + light_entity.add_component(light_name) + Report.critical_result(Tests.light_component, light_entity.has_component(light_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not light_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, light_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + light_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, light_entity.is_hidden() is True) + + # 7. Test IsVisible. + light_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, light_entity.is_visible() is True) + + # 8. Delete Light entity. + light_entity.delete() + Report.result(Tests.entity_deleted, not light_entity.exists()) + + # 9. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, light_entity.exists()) + + # 10. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not light_entity.exists()) + + # 11. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_Light_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py index 24866f3b19..6da922bd9f 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py @@ -1,10 +1,8 @@ """ -Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that creates an entity, attaches the Light component to it for test verifications. -The test verifies that each light type option is available and can be selected without errors. """ import os @@ -31,8 +29,6 @@ SPHERE_AND_SPOT_DISK_LIGHT_PROPERTIES = [ ("Controller|Configuration|Shadows|Shadow filter method", 1), # PCF ("Controller|Configuration|Shadows|Filtering sample count", 4.0), ("Controller|Configuration|Shadows|Filtering sample count", 64.0), - ("Controller|Configuration|Shadows|PCF method", 0), # Bicubic - ("Controller|Configuration|Shadows|PCF method", 1), # Boundary search ("Controller|Configuration|Shadows|Shadow filter method", 2), # ECM ("Controller|Configuration|Shadows|ESM exponent", 50), ("Controller|Configuration|Shadows|ESM exponent", 5000), diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_PhysicalSkyAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_PhysicalSkyAdded.py new file mode 100644 index 0000000000..04441d5b2c --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_PhysicalSkyAdded.py @@ -0,0 +1,136 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + physical_sky_creation = ("Physical Sky Entity successfully created", "Physical Sky Entity failed to be created") + physical_sky_component = ("Entity has a Physical Sky component", "Entity failed to find Physical Sky component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_PhysicalSky_AddedToEntity(): + """ + Summary: + Tests the Physical Sky component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Physical Sky entity with no components. + 2) Add Physical Sky component to Physical Sky entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Delete Physical Sky entity. + 9) UNDO deletion. + 10) REDO deletion. + 11) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Physical Sky entity with no components. + physical_sky_name = "Physical Sky" + physical_sky_entity = EditorEntity.create_editor_entity_at(math.Vector3(512.0, 512.0, 34.0), physical_sky_name) + Report.critical_result(Tests.physical_sky_creation, physical_sky_entity.exists()) + + # 2. Add Physical Sky component to Physical Sky entity. + physical_sky_entity.add_component(physical_sky_name) + Report.critical_result(Tests.physical_sky_component, physical_sky_entity.has_component(physical_sky_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not physical_sky_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, physical_sky_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + physical_sky_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, physical_sky_entity.is_hidden() is True) + + # 7. Test IsVisible. + physical_sky_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, physical_sky_entity.is_visible() is True) + + # 8. Delete Physical Sky entity. + physical_sky_entity.delete() + Report.result(Tests.entity_deleted, not physical_sky_entity.exists()) + + # 9. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, physical_sky_entity.exists()) + + # 10. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not physical_sky_entity.exists()) + + # 11. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_PhysicalSky_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_PostFXRadiusWeightModifierAdded.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_PostFXRadiusWeightModifierAdded.py new file mode 100644 index 0000000000..8914ab9e7e --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_PostFXRadiusWeightModifierAdded.py @@ -0,0 +1,138 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# fmt: off +class Tests: + camera_creation = ("Camera Entity successfully created", "Camera Entity failed to be created") + camera_component_added = ("Camera component was added to entity", "Camera component failed to be added to entity") + camera_component_check = ("Entity has a Camera component", "Entity failed to find Camera component") + creation_undo = ("UNDO Entity creation success", "UNDO Entity creation failed") + creation_redo = ("REDO Entity creation success", "REDO Entity creation failed") + postfx_radius_weight_creation = ("PostFX Radius Weight Modifier Entity successfully created", "PostFX Radius Weight Modifier Entity failed to be created") + postfx_radius_weight_component = ("Entity has a PostFX Radius Weight Modifier component", "Entity failed to find PostFX Radius Weight Modifier component") + enter_game_mode = ("Entered game mode", "Failed to enter game mode") + exit_game_mode = ("Exited game mode", "Couldn't exit game mode") + is_visible = ("Entity is visible", "Entity was not visible") + is_hidden = ("Entity is hidden", "Entity was not hidden") + entity_deleted = ("Entity deleted", "Entity was not deleted") + deletion_undo = ("UNDO deletion success", "UNDO deletion failed") + deletion_redo = ("REDO deletion success", "REDO deletion failed") + no_error_occurred = ("No errors detected", "Errors were detected") +# fmt: on + + +def AtomEditorComponents_PostFXRadiusWeightModifier_AddedToEntity(): + """ + Summary: + Tests the PostFX Radius Weight Modifier component can be added to an entity and has the expected functionality. + + Test setup: + - Wait for Editor idle loop. + - Open the "Base" level. + + Expected Behavior: + The component can be added, used in game mode, hidden/shown, deleted, and has accurate required components. + Creation and deletion undo/redo should also work. + + Test Steps: + 1) Create a Post FX Radius Weight Modifier entity with no components. + 2) Add Post FX Radius Weight Modifier component to Post FX Radius Weight Modifier entity. + 3) UNDO the entity creation and component addition. + 4) REDO the entity creation and component addition. + 5) Enter/Exit game mode. + 6) Test IsHidden. + 7) Test IsVisible. + 8) Delete PostFX Radius Weight Modifier entity. + 9) UNDO deletion. + 10) REDO deletion. + 11) Look for errors. + + :return: None + """ + + import azlmbr.legacy.general as general + import azlmbr.math as math + + from editor_python_test_tools.editor_entity_utils import EditorEntity + from editor_python_test_tools.utils import Report, Tracer, TestHelper as helper + + with Tracer() as error_tracer: + # Test setup begins. + # Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level. + helper.init_idle() + helper.open_level("", "Base") + + # Test steps begin. + # 1. Create a Post FX Radius Weight Modifier entity with no components. + postfx_radius_weight_name = "PostFX Radius Weight Modifier" + postfx_radius_weight_entity = EditorEntity.create_editor_entity_at( + math.Vector3(512.0, 512.0, 34.0), postfx_radius_weight_name) + Report.critical_result(Tests.postfx_radius_weight_creation, postfx_radius_weight_entity.exists()) + + # 2. Add Post FX Radius Weight Modifier component to Post FX Radius Weight Modifier entity. + postfx_radius_weight_entity.add_component(postfx_radius_weight_name) + Report.critical_result( + Tests.postfx_radius_weight_component, postfx_radius_weight_entity.has_component(postfx_radius_weight_name)) + + # 3. UNDO the entity creation and component addition. + # -> UNDO component addition. + general.undo() + # -> UNDO naming entity. + general.undo() + # -> UNDO selecting entity. + general.undo() + # -> UNDO entity creation. + general.undo() + general.idle_wait_frames(1) + Report.result(Tests.creation_undo, not postfx_radius_weight_entity.exists()) + + # 4. REDO the entity creation and component addition. + # -> REDO entity creation. + general.redo() + # -> REDO selecting entity. + general.redo() + # -> REDO naming entity. + general.redo() + # -> REDO component addition. + general.redo() + general.idle_wait_frames(1) + Report.result(Tests.creation_redo, postfx_radius_weight_entity.exists()) + + # 5. Enter/Exit game mode. + helper.enter_game_mode(Tests.enter_game_mode) + general.idle_wait_frames(1) + helper.exit_game_mode(Tests.exit_game_mode) + + # 6. Test IsHidden. + postfx_radius_weight_entity.set_visibility_state(False) + Report.result(Tests.is_hidden, postfx_radius_weight_entity.is_hidden() is True) + + # 7. Test IsVisible. + postfx_radius_weight_entity.set_visibility_state(True) + general.idle_wait_frames(1) + Report.result(Tests.is_visible, postfx_radius_weight_entity.is_visible() is True) + + # 8. Delete PostFX Radius Weight Modifier entity. + postfx_radius_weight_entity.delete() + Report.result(Tests.entity_deleted, not postfx_radius_weight_entity.exists()) + + # 9. UNDO deletion. + general.undo() + Report.result(Tests.deletion_undo, postfx_radius_weight_entity.exists()) + + # 10. REDO deletion. + general.redo() + Report.result(Tests.deletion_redo, not postfx_radius_weight_entity.exists()) + + # 11. Look for errors. + helper.wait_for_condition(lambda: error_tracer.has_errors, 1.0) + Report.result(Tests.no_error_occurred, not error_tracer.has_errors) + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(AtomEditorComponents_PostFXRadiusWeightModifier_AddedToEntity) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py index 9047b4c871..1e250e5b9f 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomMaterialEditor_BasicTests.py @@ -3,12 +3,12 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -import azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe -This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe -You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. """ +# import azlmbr.materialeditor will fail with a ModuleNotFound error when using this script with Editor.exe +# This is because azlmbr.materialeditor only binds to MaterialEditor.exe and not Editor.exe +# You need to launch this script with MaterialEditor.exe in order for azlmbr.materialeditor to appear. + import os import sys import time diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py index 3aa9fe660c..7e7087fb42 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py @@ -3,11 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that is used to create a new level with a default rendering setup. -After the level is setup, screenshots are diffed against golden images are used to verify pass/fail results of the test. - -See the run() function for more in-depth test info. """ import os diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_BasicLevelSetup.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_BasicLevelSetup.py index 920c044be0..24ebbdff63 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_BasicLevelSetup.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_BasicLevelSetup.py @@ -3,11 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that is used to create a new level with a default rendering setup. -After the level is setup, screenshots are diffed against golden images are used to verify pass/fail results of the test. - -See the run() function for more in-depth test info. """ import os diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py index 8063445608..5c019dc3f3 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_LightComponent.py @@ -3,12 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that is used to create an entity with a Light component attached. -It then updates the property values of the Light component and takes a screenshot. -The screenshot is compared against an expected golden image for test verification. - -See the run() function for more in-depth test info. """ import os import sys diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py new file mode 100644 index 0000000000..a05420d960 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py @@ -0,0 +1,188 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +""" + +import os +import shutil + +def _copy_file(src_file, src_path, target_file, target_path): + # type: (str, str, str, str) -> None + """ + Copies the [src_file] located in [src_path] to the [target_file] located at [target_path]. + Leaves the [target_file] unlocked for reading and writing privileges + :param src_file: The source file to copy (file name) + :param src_path: The source file's path + :param target_file: The target file to copy into (file name) + :param target_path: The target file's path + :return: None + """ + target_file_path = os.path.join(target_path, target_file) + src_file_path = os.path.join(src_path, src_file) + if os.path.exists(target_file_path): + fs.unlock_file(target_file_path) + shutil.copyfile(src_file_path, target_file_path) + +def _copy_tmp_files_in_order(src_directory, file_list, dst_directory, wait_time_in_between = 0.0): + # type: (str, list, str, float) -> None + """ + This function assumes that for each file name listed in @file_list + there's file named "@filename.txt" which the original source file + but they will be copied with just the @filename (.txt removed). + """ + for filename in file_list: + src_name = f"{filename}.txt" + _copy_file(src_name, src_directory, filename, dst_directory) + if wait_time_in_between > 0.0: + print(f"Created {filename} in {dst_directory}") + general.idle_wait(wait_time_in_between) + + +def _remove_file(src_file, src_path): + # type: (str, str) -> None + """ + Removes the [src_file] located in [src_path]. + :param src_file: The source file to copy (file name) + :param src_path: The source file's path + :return: None + """ + src_file_path = os.path.join(src_path, src_file) + if os.path.exists(src_file_path): + fs.unlock_file(src_file_path) + os.remove(src_file_path) + + +def _remove_files(directory, file_list): + for filename in file_list: + _remove_file(filename, directory) + + +def _asset_exists(cache_relative_path): + asset_id = azasset.AssetCatalogRequestBus(azbus.Broadcast, "GetAssetIdByPath", cache_relative_path, azmath.Uuid(), False) + return asset_id.is_valid() + +# List of results that we want to check, this is not 100% necessary but it's a good +# practice to make it easier to debug tests. +# Here we define a tuple of tests +class Results(): + azshader_was_removed = ("azshader was removed", "Failed to remove azshader") + azshader_was_compiled = ("azshader was compiled", "Failed to compile azshader") + + +def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): + """ + This test validates [ATOM-5441] Shader Builders May Fail When Multiple New Files Are Added + It creates source assets to compile a particular shader. + 1- The first phase generates the source assets out of order and slowly. The AP should + wakeup each time one of the source dependencies appears but will fail each time. Only when the + last dependency appears then the shader should build successfully. + 2- The second phase is similar as above, except that all source assets will be created + at once and We also expect that in the end the shader is built successfully. + """ + # Required for automated tests + helper.init_idle() + + game_root_path = os.path.normpath(general.get_game_folder()) + game_asset_path = os.path.join(game_root_path, "Assets") + + base_dir = os.path.dirname(__file__) + src_assets_subdir = os.path.join(base_dir, "TestAssets", "ShaderAssetBuilder") + + with Tracer() as error_tracer: + # The script drives the execution of the test, to return the flow back to the editor, + # we will tick it one time + general.idle_wait_frames(1) + + # This is the order in which the source assets should be deployed + # to avoid source dependency issues with the old MCPP-based CreateJobs. + file_list = [ + "Test2Color.azsli", + "Test3Color.azsli", + "Test1Color.azsli", + "DependencyValidation.azsl", + "DependencyValidation.shader" + ] + + reverse_file_list = file_list[::-1] + + # Remove files in reverse order + _remove_files(game_asset_path, reverse_file_list) + + # Wait here until the azshader doesn't exist anymore. + azshader_name = "assets/dependencyvalidation.azshader" + helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + + Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + + _copy_tmp_files_in_order(src_assets_subdir, file_list, game_asset_path, 1.0) + + # Give enough time to AP to compile the shader + helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) + + Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + + # The first part was about compiling the shader under normal conditions. + # Let's remove the files from the previous phase and will proceed + # to make the source files visible to the AP in reverse order. The + # ShaderAssetBuilder will only succeed when the last file becomes visible. + _remove_files(game_asset_path, reverse_file_list) + helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + + # Remark, if you are running this test manually from the Editor with "pyRunFile", + # You'll notice how the AP issues notifications that it fails to compile the shader + # as the source files are being copied to the "Assets" subfolder. + # Those errors are OK and also expected because We need the AP to wake up as each + # reported source dependency exists. Once the last file is copied then all source + # dependencies are fully satisfied and the shader should compile successfully. + # And this summarizes the importance of this Test: The previous version + # of ShaderAssetBuilder::CreateJobs was incapable of compiling the shader under the conditions + # presented in this test, but with the new version of ShaderAssetBuilder::CreateJobs, which + # doesn't use MCPP for #include files discovery, it should eventually compile the shader + # once all the source files are in place. + _copy_tmp_files_in_order(src_assets_subdir, reverse_file_list, game_asset_path, 3.0) + + # Give enough time to AP to compile the shader + helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) + + Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + + # The last phase of the test puts stress on potential race conditions + # when all required files appear as soon as possible. + + # First Clean up. + # Remove left over files. + _remove_files(game_asset_path, reverse_file_list) + helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + + # Now let's copy all the source files to the "Assets" folder as fast as possible. + _copy_tmp_files_in_order(src_assets_subdir, reverse_file_list, game_asset_path) + + # Give enough time to AP to compile the shader + helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) + + Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + + # All good, let's cleanup leftover files before closing the test. + _remove_files(game_asset_path, reverse_file_list) + helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + + +if __name__ == "__main__": + # All exposed python bindings are in azlmbr + import azlmbr.legacy.general as general + import azlmbr.bus as azbus + import azlmbr.asset as azasset + import azlmbr.math as azmath + + # Import report and test helper utilities + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + from editor_python_test_tools.utils import Tracer + import ly_test_tools.environment.file_system as fs + + Report.start_test(ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index c40dc8f178..16e281e494 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -161,6 +161,21 @@ class TestAtomEditorComponentsMain(object): "Display Mapper_test: Entity deleted: True", "Display Mapper_test: UNDO entity deletion works: True", "Display Mapper_test: REDO entity deletion works: True", + # Reflection Probe Component + "Reflection Probe Entity successfully created", + "Reflection Probe_test: Component added to the entity: True", + "Reflection Probe_test: Component removed after UNDO: True", + "Reflection Probe_test: Component added after REDO: True", + "Reflection Probe_test: Entered game mode: True", + "Reflection Probe_test: Exit game mode: True", + "Reflection Probe_test: Entity disabled initially: True", + "Reflection Probe_test: Entity enabled after adding required components: True", + "Reflection Probe_test: Cubemap is generated: True", + "Reflection Probe_test: Entity is hidden: True", + "Reflection Probe_test: Entity is shown: True", + "Reflection Probe_test: Entity deleted: True", + "Reflection Probe_test: UNDO entity deletion works: True", + "Reflection Probe_test: REDO entity deletion works: True", ] unexpected_lines = [ @@ -200,8 +215,6 @@ class TestAtomEditorComponentsMain(object): "Controller|Configuration|Shadows|Shadow filter method set to 1", # PCF "Controller|Configuration|Shadows|Filtering sample count set to 4", "Controller|Configuration|Shadows|Filtering sample count set to 64", - "Controller|Configuration|Shadows|PCF method set to 0", - "Controller|Configuration|Shadows|PCF method set to 1", "Controller|Configuration|Shadows|Shadow filter method set to 2", # ESM "Controller|Configuration|Shadows|ESM exponent set to 50.0", "Controller|Configuration|Shadows|ESM exponent set to 5000.0", diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite_Optimized.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite_Optimized.py new file mode 100644 index 0000000000..329d3ecb91 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite_Optimized.py @@ -0,0 +1,43 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" +import pytest + +from ly_test_tools.o3de.editor_test import EditorSharedTest, EditorTestSuite + + +@pytest.mark.xfail(reason="Optimized tests are experimental, we will enable xfail and monitor them temporarily.") +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +class TestAutomation(EditorTestSuite): + + class AtomEditorComponents_DecalAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import hydra_AtomEditorComponents_DecalAdded as test_module + + class AtomEditorComponents_DepthOfFieldAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import hydra_AtomEditorComponents_DepthOfFieldAdded as test_module + + class AtomEditorComponents_DirectionalLightAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import hydra_AtomEditorComponents_DirectionalLightAdded as test_module + + class AtomEditorComponents_ExposureControlAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import hydra_AtomEditorComponents_ExposureControlAdded as test_module + + class AtomEditorComponents_GlobalSkylightIBLAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import hydra_AtomEditorComponents_GlobalSkylightIBLAdded as test_module + + class AtomEditorComponents_PhysicalSkyAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import hydra_AtomEditorComponents_PhysicalSkyAdded as test_module + + class AtomEditorComponents_PostFXRadiusWeightModifierAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import ( + hydra_AtomEditorComponents_PostFXRadiusWeightModifierAdded as test_module) + + class AtomEditorComponents_LightAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import hydra_AtomEditorComponents_LightAdded as test_module + + class AtomEditorComponents_DisplayMapperAdded(EditorSharedTest): + from atom_renderer.atom_hydra_scripts import hydra_AtomEditorComponents_DisplayMapperAdded as test_module diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py new file mode 100644 index 0000000000..9ef93ea238 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py @@ -0,0 +1,19 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +Main suite tests for the Shader Build Pipeline. +""" +import pytest +from ly_test_tools import LAUNCHERS +from ly_test_tools.o3de.editor_test import EditorTestSuite, EditorSingleTest + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +class TestShaderBuildPipelineMain(EditorTestSuite): + """Holds tests for Shader Build Pipeline validation""" + + class ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(EditorSingleTest): + from .atom_hydra_scripts import hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges as test_module \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py index 6d1b688315..d525e4a599 100755 --- a/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py +++ b/AutomatedTesting/Gem/PythonTests/largeworlds/dyn_veg/test_DistanceBetweenFilter.py @@ -35,6 +35,7 @@ class TestDistanceBetweenFilter(object): @pytest.mark.test_case_id("C4851066") @pytest.mark.SUITE_periodic @pytest.mark.dynveg_filter + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/4155") def test_DistanceBetweenFilter_InstancesPlantAtSpecifiedRadius(self, request, editor, level, launcher_platform): expected_lines = [ @@ -56,6 +57,7 @@ class TestDistanceBetweenFilter(object): @pytest.mark.test_case_id("C4814458") @pytest.mark.SUITE_periodic @pytest.mark.dynveg_filter + @pytest.mark.xfail(reason="https://github.com/o3de/o3de/issues/4155") def test_DistanceBetweenFilterOverrides_InstancesPlantAtSpecifiedRadius(self, request, editor, level, launcher_platform): diff --git a/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt index 25988216b2..ed61dfaf33 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/scripting/CMakeLists.txt @@ -28,5 +28,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::Editor AZ::AssetProcessor AutomatedTesting.Assets + COMPONENT + ScriptCanvas ) endif() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py index 642818281b..0862e03a79 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py @@ -37,6 +37,7 @@ class TestAutomation(TestAutomationBase): from . import Pane_HappyPath_ResizesProperly as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_TwoComponents_InteractSuccessfully(self, request, workspace, editor, launcher_platform, level): def teardown(): @@ -46,6 +47,7 @@ class TestAutomation(TestAutomationBase): from . import ScriptCanvas_TwoComponents_InteractSuccessfully as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_ChangingAssets_ComponentStable(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -63,6 +65,7 @@ class TestAutomation(TestAutomationBase): from . import NodePalette_HappyPath_CanSelectNode as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -76,6 +79,7 @@ class TestAutomation(TestAutomationBase): from . import NodePalette_HappyPath_ClearSelection as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptCanvas_TwoEntities_UseSimultaneously(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -139,6 +143,7 @@ class TestAutomation(TestAutomationBase): from . import Pane_Default_RetainOnSCRestart as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptEvents_HappyPath_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -148,6 +153,7 @@ class TestAutomation(TestAutomationBase): from . import ScriptEvents_HappyPath_SendReceiveAcrossMultiple as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptEvents_Default_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -157,6 +163,7 @@ class TestAutomation(TestAutomationBase): from . import ScriptEvents_Default_SendReceiveSuccessfully as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") @pytest.mark.parametrize("level", ["tmp_level"]) def test_ScriptEvents_ReturnSetType_Successfully(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -204,6 +211,7 @@ class TestScriptCanvasTests(object): The following tests use hydra_test_utils.py to launch the editor and validate the results. """ + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") def test_FileMenu_Default_NewAndOpen(self, request, editor, launcher_platform): expected_lines = [ "File->New action working as expected: True", @@ -213,6 +221,7 @@ class TestScriptCanvasTests(object): request, TEST_DIRECTORY, editor, "FileMenu_Default_NewAndOpen.py", expected_lines, auto_test_mode=False, timeout=60, ) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") def test_NewScriptEventButton_HappyPath_ContainsSCCategory(self, request, editor, launcher_platform): expected_lines = [ "New Script event action found: True", @@ -295,6 +304,7 @@ class TestScriptCanvasTests(object): timeout=60, ) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") def test_ScriptEvent_AddRemoveMethod_UpdatesInSC(self, request, workspace, editor, launcher_platform): def teardown(): file_system.delete( @@ -322,6 +332,7 @@ class TestScriptCanvasTests(object): timeout=60, ) + @pytest.mark.xfail(reason="Test fails to find expected lines, it needs to be fixed.") def test_ScriptEvents_AllParamDatatypes_CreationSuccess(self, request, workspace, editor, launcher_platform): def teardown(): file_system.delete( diff --git a/Code/Editor/2DViewport.h b/Code/Editor/2DViewport.h index 4ffda18514..007c1a47d3 100644 --- a/Code/Editor/2DViewport.h +++ b/Code/Editor/2DViewport.h @@ -35,32 +35,32 @@ public: Q2DViewport(QWidget* parent = nullptr); virtual ~Q2DViewport(); - virtual void SetType(EViewportType type); - virtual EViewportType GetType() const { return m_viewType; } - virtual float GetAspectRatio() const { return 1.0f; }; + void SetType(EViewportType type) override; + EViewportType GetType() const override { return m_viewType; } + float GetAspectRatio() const override { return 1.0f; }; - virtual void ResetContent(); - virtual void UpdateContent(int flags); + void ResetContent() override; + void UpdateContent(int flags) override; public slots: // Called every frame to update viewport. - virtual void Update(); + void Update() override; public: //! Map world space position to viewport position. - virtual QPoint WorldToView(const Vec3& wp) const; + QPoint WorldToView(const Vec3& wp) const override; - virtual QPoint WorldToViewParticleEditor(const Vec3& wp, int width, int height) const; //Eric@conffx + QPoint WorldToViewParticleEditor(const Vec3& wp, int width, int height) const override; //Eric@conffx //! Map viewport position to world space position. - virtual Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; + Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; //! Map viewport position to world space ray from camera. - virtual void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const; + void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const override; void OnTitleMenu(QMenu* menu) override; - virtual bool HitTest(const QPoint& point, HitContext& hitInfo) override; - virtual bool IsBoundsVisible(const AABB& box) const; + bool HitTest(const QPoint& point, HitContext& hitInfo) override; + bool IsBoundsVisible(const AABB& box) const override; // ovverided from CViewport. float GetScreenScaleFactor(const Vec3& worldPoint) const override; @@ -111,8 +111,8 @@ protected: virtual void SetZoom(float fZoomFactor, const QPoint& center); // overrides from CViewport. - virtual void MakeConstructionPlane(int axis); - virtual const Matrix34& GetConstructionMatrix(RefCoordSys coordSys); + void MakeConstructionPlane(int axis) override; + const Matrix34& GetConstructionMatrix(RefCoordSys coordSys) override; //! Calculate view transformation matrix. virtual void CalculateViewTM(); @@ -146,9 +146,9 @@ protected: void showEvent(QShowEvent* event) override; void paintEvent(QPaintEvent* event) override; int OnCreate(); - void OnRButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point); - void OnRButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point); - void OnMouseWheel(Qt::KeyboardModifiers modifiers, short zDelta, const QPoint& pt); + void OnRButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) override; + void OnRButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) override; + void OnMouseWheel(Qt::KeyboardModifiers modifiers, short zDelta, const QPoint& pt) override; void OnDestroy(); protected: diff --git a/Code/Editor/AboutDialog.cpp b/Code/Editor/AboutDialog.cpp index f8abe67376..2c76526731 100644 --- a/Code/Editor/AboutDialog.cpp +++ b/Code/Editor/AboutDialog.cpp @@ -20,6 +20,7 @@ // AzCore #include // for aznumeric_cast +#include AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include @@ -46,8 +47,13 @@ CAboutDialog::CAboutDialog(QString versionText, QString richTextCopyrightNotice, CAboutDialog > QLabel#link { text-decoration: underline; color: #94D2FF; }"); // Prepare background image - QImage backgroundImage(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")); - m_backgroundImage = QPixmap::fromImage(backgroundImage.scaled(m_enforcedWidth, m_enforcedHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + m_backgroundImage = AzQtComponents::ScalePixmapForScreenDpi( + QPixmap(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")), + screen(), + QSize(m_enforcedWidth, m_enforcedHeight), + Qt::IgnoreAspectRatio, + Qt::SmoothTransformation + ); // Draw the Open 3D Engine logo from svg m_ui->m_logo->load(QStringLiteral(":/StartupLogoDialog/o3de_logo.svg")); diff --git a/Code/Editor/ActionManager.h b/Code/Editor/ActionManager.h index 2481b7e3ef..8879bdc1fb 100644 --- a/Code/Editor/ActionManager.h +++ b/Code/Editor/ActionManager.h @@ -353,7 +353,7 @@ public: m_actionHandlers[id] = std::bind(method, object, id); } - bool eventFilter(QObject* watched, QEvent* event); + bool eventFilter(QObject* watched, QEvent* event) override; // returns false if the action was already inserted, indicating that the action should not be processed again bool InsertActionExecuting(int id); diff --git a/Code/Editor/AnimationContext.h b/Code/Editor/AnimationContext.h index 98c951eda7..62ffa26634 100644 --- a/Code/Editor/AnimationContext.h +++ b/Code/Editor/AnimationContext.h @@ -197,7 +197,7 @@ private: virtual void OnSequenceRemoved(CTrackViewSequence* pSequence) override; - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); + virtual void OnEditorNotifyEvent(EEditorNotifyEvent event) override; void AnimateActiveSequence(); diff --git a/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui b/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui index df7474d9d4..a345438aed 100644 --- a/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui +++ b/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.ui @@ -140,9 +140,6 @@ QAbstractItemView::ScrollPerPixel - - false - true @@ -201,6 +198,11 @@
AzToolsFramework/AssetBrowser/Search/SearchWidget.h
1 + + AzQtComponents::TableView + QTreeView +
AzQtComponents/Components/Widgets/TableView.h
+
AzToolsFramework::AssetBrowser::AssetBrowserTreeView QTreeView @@ -214,7 +216,7 @@ AzToolsFramework::AssetBrowser::AssetBrowserTableView - QTableView + AzQtComponents::TableView
AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h
diff --git a/Code/Editor/BaseLibrary.h b/Code/Editor/BaseLibrary.h index 6c807df56b..55079d3fde 100644 --- a/Code/Editor/BaseLibrary.h +++ b/Code/Editor/BaseLibrary.h @@ -40,57 +40,57 @@ public: //! Set library name. virtual void SetName(const QString& name); //! Get library name. - const QString& GetName() const; + const QString& GetName() const override; //! Set new filename for this library. virtual bool SetFilename(const QString& filename, [[maybe_unused]] bool checkForUnique = true) { m_filename = filename.toLower(); return true; }; - const QString& GetFilename() const { return m_filename; }; + const QString& GetFilename() const override { return m_filename; }; - virtual bool Save() = 0; - virtual bool Load(const QString& filename) = 0; - virtual void Serialize(XmlNodeRef& node, bool bLoading) = 0; + bool Save() override = 0; + bool Load(const QString& filename) override = 0; + void Serialize(XmlNodeRef& node, bool bLoading) override = 0; //! Mark library as modified. - void SetModified(bool bModified = true); + void SetModified(bool bModified = true) override; //! Check if library was modified. - bool IsModified() const { return m_bModified; }; + bool IsModified() const override { return m_bModified; }; ////////////////////////////////////////////////////////////////////////// // Working with items. ////////////////////////////////////////////////////////////////////////// //! Add a new prototype to library. - void AddItem(IDataBaseItem* item, bool bRegister = true); + void AddItem(IDataBaseItem* item, bool bRegister = true) override; //! Get number of known prototypes. - int GetItemCount() const { return static_cast(m_items.size()); } + int GetItemCount() const override { return static_cast(m_items.size()); } //! Get prototype by index. - IDataBaseItem* GetItem(int index); + IDataBaseItem* GetItem(int index) override; //! Delete item by pointer of item. - void RemoveItem(IDataBaseItem* item); + void RemoveItem(IDataBaseItem* item) override; //! Delete all items from library. - void RemoveAllItems(); + void RemoveAllItems() override; //! Find library item by name. //! Using linear search. - IDataBaseItem* FindItem(const QString& name); + IDataBaseItem* FindItem(const QString& name) override; //! Check if this library is local level library. - bool IsLevelLibrary() const { return m_bLevelLib; }; + bool IsLevelLibrary() const override { return m_bLevelLib; }; //! Set library to be level library. - void SetLevelLibrary(bool bEnable) { m_bLevelLib = bEnable; }; + void SetLevelLibrary(bool bEnable) override { m_bLevelLib = bEnable; }; ////////////////////////////////////////////////////////////////////////// //! Return manager for this library. - IBaseLibraryManager* GetManager(); + IBaseLibraryManager* GetManager() override; // Saves the library with the main tag defined by the parameter name bool SaveLibrary(const char* name, bool saveEmptyLibrary = false); //CONFETTI BEGIN // Used to change the library item order - virtual void ChangeItemOrder(CBaseLibraryItem* item, unsigned int newLocation) override; + void ChangeItemOrder(CBaseLibraryItem* item, unsigned int newLocation) override; //CONFETTI END signals: diff --git a/Code/Editor/BaseLibraryManager.h b/Code/Editor/BaseLibraryManager.h index 6f0b905760..118c7ef1f0 100644 --- a/Code/Editor/BaseLibraryManager.h +++ b/Code/Editor/BaseLibraryManager.h @@ -35,112 +35,112 @@ public: ~CBaseLibraryManager(); //! Clear all libraries. - virtual void ClearAll() override; + void ClearAll() override; ////////////////////////////////////////////////////////////////////////// // IDocListener implementation. ////////////////////////////////////////////////////////////////////////// - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event) override; + void OnEditorNotifyEvent(EEditorNotifyEvent event) override; ////////////////////////////////////////////////////////////////////////// // Library items. ////////////////////////////////////////////////////////////////////////// //! Make a new item in specified library. - virtual IDataBaseItem* CreateItem(IDataBaseLibrary* pLibrary) override; + IDataBaseItem* CreateItem(IDataBaseLibrary* pLibrary) override; //! Delete item from library and manager. - virtual void DeleteItem(IDataBaseItem* pItem) override; + void DeleteItem(IDataBaseItem* pItem) override; //! Find Item by its GUID. - virtual IDataBaseItem* FindItem(REFGUID guid) const; - virtual IDataBaseItem* FindItemByName(const QString& fullItemName); - virtual IDataBaseItem* LoadItemByName(const QString& fullItemName); + IDataBaseItem* FindItem(REFGUID guid) const override; + IDataBaseItem* FindItemByName(const QString& fullItemName) override; + IDataBaseItem* LoadItemByName(const QString& fullItemName) override; virtual IDataBaseItem* FindItemByName(const char* fullItemName); virtual IDataBaseItem* LoadItemByName(const char* fullItemName); - virtual IDataBaseItemEnumerator* GetItemEnumerator() override; + IDataBaseItemEnumerator* GetItemEnumerator() override; ////////////////////////////////////////////////////////////////////////// // Set item currently selected. - virtual void SetSelectedItem(IDataBaseItem* pItem) override; + void SetSelectedItem(IDataBaseItem* pItem) override; // Get currently selected item. - virtual IDataBaseItem* GetSelectedItem() const override; - virtual IDataBaseItem* GetSelectedParentItem() const override; + IDataBaseItem* GetSelectedItem() const override; + IDataBaseItem* GetSelectedParentItem() const override; ////////////////////////////////////////////////////////////////////////// // Libraries. ////////////////////////////////////////////////////////////////////////// //! Add Item library. - virtual IDataBaseLibrary* AddLibrary(const QString& library, bool bIsLevelLibrary = false, bool bIsLoading = true) override; - virtual void DeleteLibrary(const QString& library, bool forceDeleteLevel = false) override; + IDataBaseLibrary* AddLibrary(const QString& library, bool bIsLevelLibrary = false, bool bIsLoading = true) override; + void DeleteLibrary(const QString& library, bool forceDeleteLevel = false) override; //! Get number of libraries. - virtual int GetLibraryCount() const override { return static_cast(m_libs.size()); }; + int GetLibraryCount() const override { return static_cast(m_libs.size()); }; //! Get number of modified libraries. - virtual int GetModifiedLibraryCount() const override; + int GetModifiedLibraryCount() const override; //! Get Item library by index. - virtual IDataBaseLibrary* GetLibrary(int index) const override; + IDataBaseLibrary* GetLibrary(int index) const override; //! Get Level Item library. - virtual IDataBaseLibrary* GetLevelLibrary() const override; + IDataBaseLibrary* GetLevelLibrary() const override; //! Find Items Library by name. - virtual IDataBaseLibrary* FindLibrary(const QString& library) override; + IDataBaseLibrary* FindLibrary(const QString& library) override; //! Find Items Library's index by name. int FindLibraryIndex(const QString& library) override; //! Load Items library. - virtual IDataBaseLibrary* LoadLibrary(const QString& filename, bool bReload = false) override; + IDataBaseLibrary* LoadLibrary(const QString& filename, bool bReload = false) override; //! Save all modified libraries. - virtual void SaveAllLibs() override; + void SaveAllLibs() override; //! Serialize property manager. - virtual void Serialize(XmlNodeRef& node, bool bLoading) override; + void Serialize(XmlNodeRef& node, bool bLoading) override; //! Export items to game. - virtual void Export([[maybe_unused]] XmlNodeRef& node) override {}; + void Export([[maybe_unused]] XmlNodeRef& node) override {}; //! Returns unique name base on input name. - virtual QString MakeUniqueItemName(const QString& name, const QString& libName = "") override; - virtual QString MakeFullItemName(IDataBaseLibrary* pLibrary, const QString& group, const QString& itemName) override; + QString MakeUniqueItemName(const QString& name, const QString& libName = "") override; + QString MakeFullItemName(IDataBaseLibrary* pLibrary, const QString& group, const QString& itemName) override; //! Root node where this library will be saved. - virtual QString GetRootNodeName() override = 0; + QString GetRootNodeName() override = 0; //! Path to libraries in this manager. - virtual QString GetLibsPath() override = 0; + QString GetLibsPath() override = 0; ////////////////////////////////////////////////////////////////////////// //! Validate library items for errors. - virtual void Validate() override; + void Validate() override; ////////////////////////////////////////////////////////////////////////// - virtual void GatherUsedResources(CUsedResources& resources) override; + void GatherUsedResources(CUsedResources& resources) override; - virtual void AddListener(IDataBaseManagerListener* pListener) override; - virtual void RemoveListener(IDataBaseManagerListener* pListener) override; + void AddListener(IDataBaseManagerListener* pListener) override; + void RemoveListener(IDataBaseManagerListener* pListener) override; ////////////////////////////////////////////////////////////////////////// - virtual void RegisterItem(CBaseLibraryItem* pItem, REFGUID newGuid) override; - virtual void RegisterItem(CBaseLibraryItem* pItem) override; - virtual void UnregisterItem(CBaseLibraryItem* pItem) override; + void RegisterItem(CBaseLibraryItem* pItem, REFGUID newGuid) override; + void RegisterItem(CBaseLibraryItem* pItem) override; + void UnregisterItem(CBaseLibraryItem* pItem) override; // Only Used internally. - virtual void OnRenameItem(CBaseLibraryItem* pItem, const QString& oldName) override; + void OnRenameItem(CBaseLibraryItem* pItem, const QString& oldName) override; // Called by items to indicated that they have been modified. // Sends item changed event to listeners. - virtual void OnItemChanged(IDataBaseItem* pItem) override; - virtual void OnUpdateProperties(IDataBaseItem* pItem, bool bRefresh) override; + void OnItemChanged(IDataBaseItem* pItem) override; + void OnUpdateProperties(IDataBaseItem* pItem, bool bRefresh) override; QString MakeFilename(const QString& library); - virtual bool IsUniqueFilename(const QString& library) override; + bool IsUniqueFilename(const QString& library) override; //CONFETTI BEGIN // Used to change the library item order - virtual void ChangeLibraryOrder(IDataBaseLibrary* lib, unsigned int newLocation) override; + void ChangeLibraryOrder(IDataBaseLibrary* lib, unsigned int newLocation) override; - virtual bool SetLibraryName(CBaseLibrary* lib, const QString& name) override; + bool SetLibraryName(CBaseLibrary* lib, const QString& name) override; protected: void SplitFullItemName(const QString& fullItemName, QString& libraryName, QString& itemName); @@ -199,8 +199,8 @@ public: m_pMap = pMap; m_iterator = m_pMap->begin(); } - virtual void Release() { delete this; }; - virtual IDataBaseItem* GetFirst() + void Release() override { delete this; }; + IDataBaseItem* GetFirst() override { m_iterator = m_pMap->begin(); if (m_iterator == m_pMap->end()) @@ -209,7 +209,7 @@ public: } return m_iterator->second; } - virtual IDataBaseItem* GetNext() + IDataBaseItem* GetNext() override { if (m_iterator != m_pMap->end()) { diff --git a/Code/Editor/Controls/ColorGradientCtrl.h b/Code/Editor/Controls/ColorGradientCtrl.h index a3f95fcd8c..bb1a83b0c1 100644 --- a/Code/Editor/Controls/ColorGradientCtrl.h +++ b/Code/Editor/Controls/ColorGradientCtrl.h @@ -81,7 +81,7 @@ protected: HIT_SPLINE, }; - void paintEvent(QPaintEvent* e); + void paintEvent(QPaintEvent* e) override; void resizeEvent(QResizeEvent* event) override; void mousePressEvent(QMouseEvent* event) override; void mouseReleaseEvent(QMouseEvent* event) override; diff --git a/Code/Editor/Controls/FolderTreeCtrl.h b/Code/Editor/Controls/FolderTreeCtrl.h index 48eff10a92..f74cca6143 100644 --- a/Code/Editor/Controls/FolderTreeCtrl.h +++ b/Code/Editor/Controls/FolderTreeCtrl.h @@ -83,7 +83,7 @@ protected Q_SLOTS: void OnIndexDoubleClicked(const QModelIndex& index); protected: - virtual void OnFileMonitorChange(const SFileChangeInfo& rChange); + void OnFileMonitorChange(const SFileChangeInfo& rChange) override; void contextMenuEvent(QContextMenuEvent* e) override; void InitTree(); diff --git a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.h b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.h index 9c49f1ae1a..4bcd6dcaa3 100644 --- a/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.h +++ b/Code/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.h @@ -123,7 +123,7 @@ public: void SetVariable(IVariable* pVariable) override; void SyncReflectedVarToIVar(IVariable* pVariable) override; void SyncIVarToReflectedVar(IVariable* pVariable) override; - virtual void OnVariableChange(IVariable* var); + void OnVariableChange(IVariable* var) override; CReflectedVar* GetReflectedVar() override { return m_reflectedVar.data(); } protected: diff --git a/Code/Editor/Controls/SplineCtrlEx.cpp b/Code/Editor/Controls/SplineCtrlEx.cpp index 9e0a954c79..1dc2ff19e1 100644 --- a/Code/Editor/Controls/SplineCtrlEx.cpp +++ b/Code/Editor/Controls/SplineCtrlEx.cpp @@ -70,7 +70,7 @@ protected: m_splineEntries.resize(m_splineEntries.size() + 1); SplineEntry& entry = m_splineEntries.back(); ISplineSet* pSplineSet = (pCtrl ? pCtrl->m_pSplineSet : nullptr); - entry.id = (pSplineSet ? pSplineSet->GetIDFromSpline(pSpline) : nullptr); + entry.id = (pSplineSet ? pSplineSet->GetIDFromSpline(pSpline) : AZStd::string{}); entry.pSpline = pSpline; const int numKeys = pSpline->GetKeyCount(); diff --git a/Code/Editor/Controls/SplineCtrlEx.h b/Code/Editor/Controls/SplineCtrlEx.h index 711cbcf8d4..9bf412f056 100644 --- a/Code/Editor/Controls/SplineCtrlEx.h +++ b/Code/Editor/Controls/SplineCtrlEx.h @@ -159,15 +159,15 @@ public: ////////////////////////////////////////////////////////////////////////// // IKeyTimeSet Implementation - virtual int GetKeyTimeCount() const; - virtual float GetKeyTime(int index) const; - virtual void MoveKeyTimes(int numChanges, int* indices, float scale, float offset, bool copyKeys); - virtual bool GetKeyTimeSelected(int index) const; - virtual void SetKeyTimeSelected(int index, bool selected); - virtual int GetKeyCount(int index) const; - virtual int GetKeyCountBound() const; - virtual void BeginEdittingKeyTimes(); - virtual void EndEdittingKeyTimes(); + int GetKeyTimeCount() const override; + float GetKeyTime(int index) const override; + void MoveKeyTimes(int numChanges, int* indices, float scale, float offset, bool copyKeys) override; + bool GetKeyTimeSelected(int index) const override; + void SetKeyTimeSelected(int index, bool selected) override; + int GetKeyCount(int index) const override; + int GetKeyCountBound() const override; + void BeginEdittingKeyTimes() override; + void EndEdittingKeyTimes() override; void SetEditLock(bool bLock) { m_bEditLock = bLock; } @@ -361,8 +361,8 @@ public: SplineWidget(QWidget* parent); virtual ~SplineWidget(); - void update() { QWidget::update(); } - void update(const QRect& rect) { QWidget::update(rect); } + void update() override { QWidget::update(); } + void update(const QRect& rect) override { QWidget::update(rect); } QPoint mapFromGlobal(const QPoint& point) const override { return QWidget::mapFromGlobal(point); } diff --git a/Code/Editor/Controls/TimelineCtrl.h b/Code/Editor/Controls/TimelineCtrl.h index f87bdf3410..7e1fc6fcb2 100644 --- a/Code/Editor/Controls/TimelineCtrl.h +++ b/Code/Editor/Controls/TimelineCtrl.h @@ -56,7 +56,7 @@ public: void setGeometry(const QRect& r) override { QWidget::setGeometry(r); } void SetTimeRange(const Range& r) { m_timeRange = r; } - void SetTimeMarker(float fTime); + void SetTimeMarker(float fTime) override; float GetTimeMarker() const { return m_fTimeMarker; } void SetZoom(float fZoom); @@ -113,7 +113,7 @@ protected: void OnLButtonUp(const QPoint& point, Qt::KeyboardModifiers modifiers); void OnRButtonDown(const QPoint& point, Qt::KeyboardModifiers modifiers); void OnRButtonUp(const QPoint& point, Qt::KeyboardModifiers modifiers); - void keyPressEvent(QKeyEvent* event); + void keyPressEvent(QKeyEvent* event) override; // Drawing functions float ClientToTime(int x); diff --git a/Code/Editor/Core/QtEditorApplication.cpp b/Code/Editor/Core/QtEditorApplication.cpp index a4aab24be4..66ed42af8f 100644 --- a/Code/Editor/Core/QtEditorApplication.cpp +++ b/Code/Editor/Core/QtEditorApplication.cpp @@ -44,7 +44,7 @@ enum { // in milliseconds GameModeIdleFrequency = 0, - EditorModeIdleFrequency = 1, + EditorModeIdleFrequency = 0, InactiveModeFrequency = 10, UninitializedFrequency = 9999, }; diff --git a/Code/Editor/CryEdit.h b/Code/Editor/CryEdit.h index 4ab37ac1e5..730af7c034 100644 --- a/Code/Editor/CryEdit.h +++ b/Code/Editor/CryEdit.h @@ -462,6 +462,7 @@ class CCryDocManager CCrySingleDocTemplate* m_pDefTemplate = nullptr; public: CCryDocManager(); + virtual ~CCryDocManager() = default; CCrySingleDocTemplate* SetDefaultTemplate(CCrySingleDocTemplate* pNew); // Copied from MFC to get rid of the silly ugly unoverridable doc-type pick dialog virtual void OnFileNew(); diff --git a/Code/Editor/CryEditDoc.cpp b/Code/Editor/CryEditDoc.cpp index a61429fc87..07d946c609 100644 --- a/Code/Editor/CryEditDoc.cpp +++ b/Code/Editor/CryEditDoc.cpp @@ -1135,7 +1135,6 @@ bool CCryEditDoc::SaveLevel(const QString& filename) { // if we're saving to a new folder, we need to copy the old folder tree. auto pIPak = GetIEditor()->GetSystem()->GetIPak(); - pIPak->Lock(); const QString oldLevelPattern = QDir(oldLevelFolder).absoluteFilePath("*.*"); const QString oldLevelName = Path::GetFile(GetLevelPathName()); @@ -1199,7 +1198,6 @@ bool CCryEditDoc::SaveLevel(const QString& filename) QFile(filePath).setPermissions(QFile::ReadOther | QFile::WriteOther); }); - pIPak->Unlock(); } // Save level to XML archive. @@ -1813,8 +1811,8 @@ bool CCryEditDoc::BackupBeforeSave(bool force) QString subFolder = theTime.toString("yyyy-MM-dd [HH.mm.ss]"); QString levelName = GetIEditor()->GetGameEngine()->GetLevelName(); - QString backupPath = saveBackupPath + "/" + subFolder + "/"; - gEnv->pCryPak->MakeDir(backupPath.toUtf8().data()); + QString backupPath = saveBackupPath + "/" + subFolder; + AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(backupPath.toUtf8().data()); QString sourcePath = QString::fromUtf8(resolvedLevelPath) + "/"; @@ -2028,7 +2026,7 @@ const char* CCryEditDoc::GetTemporaryLevelName() const void CCryEditDoc::DeleteTemporaryLevel() { QString tempLevelPath = (Path::GetEditingGameDataFolder() + "/Levels/" + GetTemporaryLevelName()).c_str(); - GetIEditor()->GetSystem()->GetIPak()->ClosePacks(tempLevelPath.toUtf8().data(), AZ::IO::IArchive::EPathResolutionRules::FLAGS_ADD_TRAILING_SLASH); + GetIEditor()->GetSystem()->GetIPak()->ClosePacks(tempLevelPath.toUtf8().data()); CFileUtil::Deltree(tempLevelPath.toUtf8().data(), true); } diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp index 7a407aac37..1b38fe23b8 100644 --- a/Code/Editor/CryEditPy.cpp +++ b/Code/Editor/CryEditPy.cpp @@ -77,10 +77,6 @@ namespace // This closes the current document (level) currentLevel->OnNewDocument(); - // Then we freeze the viewport's input - AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Broadcast( - &AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Events::FreezeViewportInput, true); - // Then we need to tell the game engine there is no level to render anymore if (GetIEditor()->GetGameEngine()) { diff --git a/Code/Editor/Dialogs/PythonScriptsDialog.cpp b/Code/Editor/Dialogs/PythonScriptsDialog.cpp index 7c6b445387..e95fb90c0a 100644 --- a/Code/Editor/Dialogs/PythonScriptsDialog.cpp +++ b/Code/Editor/Dialogs/PythonScriptsDialog.cpp @@ -79,6 +79,8 @@ CPythonScriptsDialog::CPythonScriptsDialog(QWidget* parent) GetGemSourcePathsVisitor(AZ::SettingsRegistryInterface& settingsRegistry) : m_settingsRegistry(settingsRegistry) {} + + using AZ::SettingsRegistryInterface::Visitor::Visit; void Visit(AZStd::string_view path, AZStd::string_view, AZ::SettingsRegistryInterface::Type, AZStd::string_view value) override { diff --git a/Code/Editor/EditorPreferencesPageViewportGeneral.cpp b/Code/Editor/EditorPreferencesPageViewportGeneral.cpp index a9eec22e69..77560e24f8 100644 --- a/Code/Editor/EditorPreferencesPageViewportGeneral.cpp +++ b/Code/Editor/EditorPreferencesPageViewportGeneral.cpp @@ -5,9 +5,11 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ + #include "EditorDefs.h" #include "EditorPreferencesPageViewportGeneral.h" +#include "EditorViewportSettings.h" #include @@ -15,7 +17,6 @@ #include "DisplaySettings.h" #include "Settings.h" - void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& serialize) { serialize.Class() @@ -23,7 +24,8 @@ void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& seria ->Field("Sync2DViews", &General::m_sync2DViews) ->Field("DefaultFOV", &General::m_defaultFOV) ->Field("DefaultAspectRatio", &General::m_defaultAspectRatio) - ->Field("EnableContextMenu", &General::m_enableContextMenu); + ->Field("EnableContextMenu", &General::m_contextMenuEnabled) + ->Field("StickySelect", &General::m_stickySelectEnabled); serialize.Class() ->Version(1) @@ -46,10 +48,12 @@ void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& seria ->Field("ShowGridGuide", &Display::m_showGridGuide) ->Field("DisplayDimensions", &Display::m_displayDimension); + // clang-format off serialize.Class() ->Version(1) ->Field("SwapXY", &MapViewport::m_swapXY) ->Field("Resolution", &MapViewport::m_resolution); + // clang-format on serialize.Class() ->Version(1) @@ -80,31 +84,51 @@ void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& seria editContext->Class("General Viewport Settings", "") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &General::m_sync2DViews, "Synchronize 2D Viewports", "Synchronize 2D Viewports") ->DataElement(AZ::Edit::UIHandlers::SpinBox, &General::m_defaultFOV, "Perspective View FOV", "Perspective View FOV") - ->Attribute("Multiplier", RAD2DEG(1)) - ->Attribute(AZ::Edit::Attributes::Min, 1.0f) - ->Attribute(AZ::Edit::Attributes::Max, 120.0f) - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &General::m_defaultAspectRatio, "Perspective View Aspect Ratio", "Perspective View Aspect Ratio") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &General::m_enableContextMenu, "Enable Right-Click Context Menu", "Enable Right-Click Context Menu"); + ->Attribute("Multiplier", RAD2DEG(1)) + ->Attribute(AZ::Edit::Attributes::Min, 1.0f) + ->Attribute(AZ::Edit::Attributes::Max, 120.0f) + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &General::m_defaultAspectRatio, "Perspective View Aspect Ratio", + "Perspective View Aspect Ratio") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &General::m_contextMenuEnabled, "Enable Right-Click Context Menu", + "Enable Right-Click Context Menu") + ->DataElement(AZ::Edit::UIHandlers::CheckBox, &General::m_stickySelectEnabled, "Enable Sticky Select", "Enable Sticky Select"); editContext->Class("Viewport Display Settings", "") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showSafeFrame, "Show 4:3 Aspect Ratio Frame", "Show 4:3 Aspect Ratio Frame") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightSelGeom, "Highlight Selected Geometry", "Highlight Selected Geometry") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightSelVegetation, "Highlight Selected Vegetation", "Highlight Selected Vegetation") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightOnMouseOver, "Highlight Geometry On Mouse Over", "Highlight Geometry On Mouse Over") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_hideMouseCursorWhenCaptured, "Hide Cursor When Captured", "Hide Mouse Cursor When Captured") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_showSafeFrame, "Show 4:3 Aspect Ratio Frame", "Show 4:3 Aspect Ratio Frame") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightSelGeom, "Highlight Selected Geometry", "Highlight Selected Geometry") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightSelVegetation, "Highlight Selected Vegetation", + "Highlight Selected Vegetation") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_highlightOnMouseOver, "Highlight Geometry On Mouse Over", + "Highlight Geometry On Mouse Over") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_hideMouseCursorWhenCaptured, "Hide Cursor When Captured", + "Hide Mouse Cursor When Captured") ->DataElement(AZ::Edit::UIHandlers::SpinBox, &Display::m_dragSquareSize, "Drag Square Size", "Drag Square Size") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_displayLinks, "Display Object Links", "Display Object Links") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_displayTracks, "Display Animation Tracks", "Display Animation Tracks") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_alwaysShowRadii, "Always Show Radii", "Always Show Radii") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showBBoxes, "Show Bounding Boxes", "Show Bounding Boxes") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_drawEntityLabels, "Always Draw Entity Labels", "Always Draw Entity Labels") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showTriggerBounds, "Always Show Trigger Bounds", "Always Show Trigger Bounds") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_drawEntityLabels, "Always Draw Entity Labels", "Always Draw Entity Labels") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_showTriggerBounds, "Always Show Trigger Bounds", "Always Show Trigger Bounds") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showIcons, "Show Object Icons", "Show Object Icons") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_distanceScaleIcons, "Scale Object Icons with Distance", "Scale Object Icons with Distance") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showFrozenHelpers, "Show Helpers of Frozen Objects", "Show Helpers of Frozen Objects") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_distanceScaleIcons, "Scale Object Icons with Distance", + "Scale Object Icons with Distance") + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_showFrozenHelpers, "Show Helpers of Frozen Objects", + "Show Helpers of Frozen Objects") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_fillSelectedShapes, "Fill Selected Shapes", "Fill Selected Shapes") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_showGridGuide, "Show Snapping Grid Guide", "Show Snapping Grid Guide") - ->DataElement(AZ::Edit::UIHandlers::CheckBox, &Display::m_displayDimension, "Display Dimension Figures", "Display Dimension Figures"); + ->DataElement( + AZ::Edit::UIHandlers::CheckBox, &Display::m_displayDimension, "Display Dimension Figures", "Display Dimension Figures"); editContext->Class("Map Viewport Settings", "") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &MapViewport::m_swapXY, "Swap X/Y Axis", "Swap X/Y Axis") @@ -113,42 +137,64 @@ void CEditorPreferencesPage_ViewportGeneral::Reflect(AZ::SerializeContext& seria editContext->Class("Text Label Settings", "") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &TextLabels::m_labelsOn, "Enabled", "Enabled") ->DataElement(AZ::Edit::UIHandlers::CheckBox, &TextLabels::m_labelsDistance, "Distance", "Distance") - ->Attribute(AZ::Edit::Attributes::Min, 0.f) - ->Attribute(AZ::Edit::Attributes::Max, 100000.f); + ->Attribute(AZ::Edit::Attributes::Min, 0.f) + ->Attribute(AZ::Edit::Attributes::Max, 100000.f); editContext->Class("Selection Preview Color Settings", "") ->DataElement(AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_colorGroupBBox, "Group Bounding Box", "Group Bounding Box") - ->DataElement(AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_colorEntityBBox, "Entity Bounding Box", "Entity Bounding Box") - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_fBBoxAlpha, "Bounding Box Highlight Alpha", "Bounding Box Highlight Alpha") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::Max, 1.0f) + ->DataElement( + AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_colorEntityBBox, "Entity Bounding Box", "Entity Bounding Box") + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_fBBoxAlpha, "Bounding Box Highlight Alpha", + "Bounding Box Highlight Alpha") + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 1.0f) ->DataElement(AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_geometryHighlightColor, "Geometry Color", "Geometry Color") - ->DataElement(AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_solidBrushGeometryColor, "Solid Brush Geometry Color", "Solid Brush Geometry Color") - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_fgeomAlpha, "Geometry Highlight Alpha", "Geometry Highlight Alpha") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::Max, 1.0f) - ->DataElement(AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_childObjectGeomAlpha, "Child Geometry Highlight Alpha", "Child Geometry Highlight Alpha") - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::Max, 1.0f); + ->DataElement( + AZ::Edit::UIHandlers::Color, &SelectionPreviewColor::m_solidBrushGeometryColor, "Solid Brush Geometry Color", + "Solid Brush Geometry Color") + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_fgeomAlpha, "Geometry Highlight Alpha", "Geometry Highlight Alpha") + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 1.0f) + ->DataElement( + AZ::Edit::UIHandlers::SpinBox, &SelectionPreviewColor::m_childObjectGeomAlpha, "Child Geometry Highlight Alpha", + "Child Geometry Highlight Alpha") + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, 1.0f); editContext->Class("General Viewport Preferences", "General Viewport Preferences") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20)) - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_general, "General Viewport Settings", "General Viewport Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_display, "Viewport Display Settings", "Viewport Display Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_map, "Map Viewport Settings", "Map Viewport Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_textLabels, "Text Label Settings", "Text Label Settings") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_selectionPreviewColor, "Selection Preview Color Settings", "Selection Preview Color Settings"); + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_general, "General Viewport Settings", + "General Viewport Settings") + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_display, "Viewport Display Settings", + "Viewport Display Settings") + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_map, "Map Viewport Settings", + "Map Viewport Settings") + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_textLabels, "Text Label Settings", + "Text Label Settings") + ->DataElement( + AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_ViewportGeneral::m_selectionPreviewColor, + "Selection Preview Color Settings", "Selection Preview Color Settings"); } } - CEditorPreferencesPage_ViewportGeneral::CEditorPreferencesPage_ViewportGeneral() { InitializeSettings(); m_icon = QIcon(":/res/Viewport.svg"); } +const char* CEditorPreferencesPage_ViewportGeneral::GetCategory() +{ + return "Viewports"; +} + const char* CEditorPreferencesPage_ViewportGeneral::GetTitle() { return "Viewport"; @@ -159,14 +205,25 @@ QIcon& CEditorPreferencesPage_ViewportGeneral::GetIcon() return m_icon; } +void CEditorPreferencesPage_ViewportGeneral::OnCancel() +{ + // noop +} + +bool CEditorPreferencesPage_ViewportGeneral::OnQueryCancel() +{ + return true; +} + void CEditorPreferencesPage_ViewportGeneral::OnApply() { CDisplaySettings* ds = GetIEditor()->GetDisplaySettings(); gSettings.viewports.fDefaultAspectRatio = m_general.m_defaultAspectRatio; gSettings.viewports.fDefaultFov = m_general.m_defaultFOV; - gSettings.viewports.bEnableContextMenu = m_general.m_enableContextMenu; + gSettings.viewports.bEnableContextMenu = m_general.m_contextMenuEnabled; gSettings.viewports.bSync2DViews = m_general.m_sync2DViews; + SandboxEditor::SetStickySelectEnabled(m_general.m_stickySelectEnabled); gSettings.viewports.bShowSafeFrame = m_display.m_showSafeFrame; gSettings.viewports.bHighlightSelectedGeometry = m_display.m_highlightSelGeom; @@ -202,19 +259,19 @@ void CEditorPreferencesPage_ViewportGeneral::OnApply() gSettings.objectColorSettings.fChildGeomAlpha = m_selectionPreviewColor.m_childObjectGeomAlpha; gSettings.objectColorSettings.entityHighlight = QColor( - static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetR() * 255.0f), - static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetG() * 255.0f), - static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetB() * 255.0f)); + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorEntityBBox.GetB() * 255.0f)); gSettings.objectColorSettings.groupHighlight = QColor( - static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetR() * 255.0f), - static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetG() * 255.0f), - static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetB() * 255.0f)); + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_colorGroupBBox.GetB() * 255.0f)); gSettings.objectColorSettings.fBBoxAlpha = m_selectionPreviewColor.m_fBBoxAlpha; gSettings.objectColorSettings.fGeomAlpha = m_selectionPreviewColor.m_fgeomAlpha; gSettings.objectColorSettings.geometryHighlightColor = QColor( - static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetR() * 255.0f), - static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetG() * 255.0f), - static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetB() * 255.0f)); + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetR() * 255.0f), + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetG() * 255.0f), + static_cast(m_selectionPreviewColor.m_geometryHighlightColor.GetB() * 255.0f)); gSettings.objectColorSettings.solidBrushGeometryColor = QColor( static_cast(m_selectionPreviewColor.m_solidBrushGeometryColor.GetR() * 255.0f), static_cast(m_selectionPreviewColor.m_solidBrushGeometryColor.GetG() * 255.0f), @@ -227,8 +284,9 @@ void CEditorPreferencesPage_ViewportGeneral::InitializeSettings() m_general.m_defaultAspectRatio = gSettings.viewports.fDefaultAspectRatio; m_general.m_defaultFOV = gSettings.viewports.fDefaultFov; - m_general.m_enableContextMenu = gSettings.viewports.bEnableContextMenu; + m_general.m_contextMenuEnabled = gSettings.viewports.bEnableContextMenu; m_general.m_sync2DViews = gSettings.viewports.bSync2DViews; + m_general.m_stickySelectEnabled = SandboxEditor::StickySelectEnabled(); m_display.m_showSafeFrame = gSettings.viewports.bShowSafeFrame; m_display.m_highlightSelGeom = gSettings.viewports.bHighlightSelectedGeometry; @@ -256,10 +314,22 @@ void CEditorPreferencesPage_ViewportGeneral::InitializeSettings() m_textLabels.m_labelsDistance = ds->GetLabelsDistance(); m_selectionPreviewColor.m_childObjectGeomAlpha = gSettings.objectColorSettings.fChildGeomAlpha; - m_selectionPreviewColor.m_colorEntityBBox.Set(static_cast(gSettings.objectColorSettings.entityHighlight.redF()), static_cast(gSettings.objectColorSettings.entityHighlight.greenF()), static_cast(gSettings.objectColorSettings.entityHighlight.blueF()), 1.0f); - m_selectionPreviewColor.m_colorGroupBBox.Set(static_cast(gSettings.objectColorSettings.groupHighlight.redF()), static_cast(gSettings.objectColorSettings.groupHighlight.greenF()), static_cast(gSettings.objectColorSettings.groupHighlight.blueF()), 1.0f); + m_selectionPreviewColor.m_colorEntityBBox.Set( + static_cast(gSettings.objectColorSettings.entityHighlight.redF()), + static_cast(gSettings.objectColorSettings.entityHighlight.greenF()), + static_cast(gSettings.objectColorSettings.entityHighlight.blueF()), 1.0f); + m_selectionPreviewColor.m_colorGroupBBox.Set( + static_cast(gSettings.objectColorSettings.groupHighlight.redF()), + static_cast(gSettings.objectColorSettings.groupHighlight.greenF()), + static_cast(gSettings.objectColorSettings.groupHighlight.blueF()), 1.0f); m_selectionPreviewColor.m_fBBoxAlpha = gSettings.objectColorSettings.fBBoxAlpha; m_selectionPreviewColor.m_fgeomAlpha = gSettings.objectColorSettings.fGeomAlpha; - m_selectionPreviewColor.m_geometryHighlightColor.Set(static_cast(gSettings.objectColorSettings.geometryHighlightColor.redF()), static_cast(gSettings.objectColorSettings.geometryHighlightColor.greenF()), static_cast(gSettings.objectColorSettings.geometryHighlightColor.blueF()), 1.0f); - m_selectionPreviewColor.m_solidBrushGeometryColor.Set(static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.redF()), static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.greenF()), static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.blueF()), 1.0f); + m_selectionPreviewColor.m_geometryHighlightColor.Set( + static_cast(gSettings.objectColorSettings.geometryHighlightColor.redF()), + static_cast(gSettings.objectColorSettings.geometryHighlightColor.greenF()), + static_cast(gSettings.objectColorSettings.geometryHighlightColor.blueF()), 1.0f); + m_selectionPreviewColor.m_solidBrushGeometryColor.Set( + static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.redF()), + static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.greenF()), + static_cast(gSettings.objectColorSettings.solidBrushGeometryColor.blueF()), 1.0f); } diff --git a/Code/Editor/EditorPreferencesPageViewportGeneral.h b/Code/Editor/EditorPreferencesPageViewportGeneral.h index a042bcf19b..be89cc6df4 100644 --- a/Code/Editor/EditorPreferencesPageViewportGeneral.h +++ b/Code/Editor/EditorPreferencesPageViewportGeneral.h @@ -5,18 +5,17 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ + #pragma once #include "Include/IPreferencesPage.h" -#include -#include -#include #include +#include +#include +#include #include - -class CEditorPreferencesPage_ViewportGeneral - : public IPreferencesPage +class CEditorPreferencesPage_ViewportGeneral : public IPreferencesPage { public: AZ_RTTI(CEditorPreferencesPage_ViewportGeneral, "{8511FF7F-F774-47E1-A99B-3DE3A867E403}", IPreferencesPage) @@ -26,12 +25,12 @@ public: CEditorPreferencesPage_ViewportGeneral(); virtual ~CEditorPreferencesPage_ViewportGeneral() = default; - virtual const char* GetCategory() override { return "Viewports"; } + virtual const char* GetCategory() override; virtual const char* GetTitle() override; virtual QIcon& GetIcon() override; virtual void OnApply() override; - virtual void OnCancel() override {} - virtual bool OnQueryCancel() override { return true; } + virtual void OnCancel() override; + virtual bool OnQueryCancel() override; private: void InitializeSettings(); @@ -43,7 +42,8 @@ private: bool m_sync2DViews; float m_defaultFOV; float m_defaultAspectRatio; - bool m_enableContextMenu; + bool m_contextMenuEnabled; + bool m_stickySelectEnabled; }; struct Display @@ -106,5 +106,3 @@ private: SelectionPreviewColor m_selectionPreviewColor; QIcon m_icon; }; - - diff --git a/Code/Editor/EditorToolsApplication.cpp b/Code/Editor/EditorToolsApplication.cpp index 1e5d747e4a..26e608f657 100644 --- a/Code/Editor/EditorToolsApplication.cpp +++ b/Code/Editor/EditorToolsApplication.cpp @@ -34,10 +34,14 @@ namespace EditorInternal : ToolsApplication(argc, argv) { EditorToolsApplicationRequests::Bus::Handler::BusConnect(); + AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler::BusConnect(); + AzToolsFramework::ViewportInteraction::EditorViewportInputTimeNowRequestBus::Handler::BusConnect(); } EditorToolsApplication::~EditorToolsApplication() { + AzToolsFramework::ViewportInteraction::EditorViewportInputTimeNowRequestBus::Handler::BusDisconnect(); + AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler::BusDisconnect(); EditorToolsApplicationRequests::Bus::Handler::BusDisconnect(); Stop(); } @@ -48,7 +52,6 @@ namespace EditorInternal return m_StartupAborted; } - void EditorToolsApplication::RegisterCoreComponents() { AzToolsFramework::ToolsApplication::RegisterCoreComponents(); @@ -274,5 +277,14 @@ namespace EditorInternal Exit(); } -} + AzToolsFramework::ViewportInteraction::KeyboardModifiers EditorToolsApplication::QueryKeyboardModifiers() + { + return AzToolsFramework::ViewportInteraction::BuildKeyboardModifiers(QGuiApplication::queryKeyboardModifiers()); + } + AZStd::chrono::milliseconds EditorToolsApplication::EditorViewportInputTimeNow() + { + const auto now = AZStd::chrono::high_resolution_clock::now(); + return AZStd::chrono::time_point_cast(now).time_since_epoch(); + } +} // namespace EditorInternal diff --git a/Code/Editor/EditorToolsApplication.h b/Code/Editor/EditorToolsApplication.h index 93916cfc8c..d4e6223445 100644 --- a/Code/Editor/EditorToolsApplication.h +++ b/Code/Editor/EditorToolsApplication.h @@ -7,7 +7,9 @@ */ #pragma once + #include +#include #include "Core/EditorMetricsPlainTextNameRegistration.h" #include "EditorToolsApplicationAPI.h" @@ -19,6 +21,8 @@ namespace EditorInternal class EditorToolsApplication : public AzToolsFramework::ToolsApplication , public EditorToolsApplicationRequests::Bus::Handler + , public AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler + , public AzToolsFramework::ViewportInteraction::EditorViewportInputTimeNowRequestBus::Handler { public: EditorToolsApplication(int* argc, char*** argv); @@ -28,7 +32,7 @@ namespace EditorInternal void RegisterCoreComponents() override; - AZ::ComponentTypeList GetRequiredSystemComponents() const; + AZ::ComponentTypeList GetRequiredSystemComponents() const override; void StartCommon(AZ::Entity* systemEntity) override; @@ -44,6 +48,12 @@ namespace EditorInternal void CreateReflectionManager() override; void Reflect(AZ::ReflectContext* context) override; + // EditorModifierKeyRequestBus overrides ... + AzToolsFramework::ViewportInteraction::KeyboardModifiers QueryKeyboardModifiers() override; + + // EditorViewportInputTimeNowRequestBus overrides ... + AZStd::chrono::milliseconds EditorViewportInputTimeNow() override; + protected: // From EditorToolsApplicationRequests bool OpenLevel(AZStd::string_view levelName) override; diff --git a/Code/Editor/EditorViewportSettings.cpp b/Code/Editor/EditorViewportSettings.cpp index c1bd85a174..063ec125ba 100644 --- a/Code/Editor/EditorViewportSettings.cpp +++ b/Code/Editor/EditorViewportSettings.cpp @@ -20,6 +20,7 @@ namespace SandboxEditor constexpr AZStd::string_view AngleSnappingSetting = "/Amazon/Preferences/Editor/AngleSnapping"; constexpr AZStd::string_view AngleSizeSetting = "/Amazon/Preferences/Editor/AngleSize"; constexpr AZStd::string_view ShowGridSetting = "/Amazon/Preferences/Editor/ShowGrid"; + constexpr AZStd::string_view StickySelectSetting = "/Amazon/Preferences/Editor/StickySelect"; constexpr AZStd::string_view ManipulatorLineBoundWidthSetting = "/Amazon/Preferences/Editor/Manipulator/LineBoundWidth"; constexpr AZStd::string_view ManipulatorCircleBoundWidthSetting = "/Amazon/Preferences/Editor/Manipulator/CircleBoundWidth"; constexpr AZStd::string_view CameraTranslateSpeedSetting = "/Amazon/Preferences/Editor/Camera/TranslateSpeed"; @@ -158,6 +159,16 @@ namespace SandboxEditor SetRegistry(ShowGridSetting, showing); } + bool StickySelectEnabled() + { + return GetRegistry(StickySelectSetting, false); + } + + void SetStickySelectEnabled(const bool enabled) + { + SetRegistry(StickySelectSetting, enabled); + } + float ManipulatorLineBoundWidth() { return aznumeric_cast(GetRegistry(ManipulatorLineBoundWidthSetting, 0.1)); diff --git a/Code/Editor/EditorViewportSettings.h b/Code/Editor/EditorViewportSettings.h index 8aeeee1384..20d397a29e 100644 --- a/Code/Editor/EditorViewportSettings.h +++ b/Code/Editor/EditorViewportSettings.h @@ -47,6 +47,9 @@ namespace SandboxEditor SANDBOX_API bool ShowingGrid(); SANDBOX_API void SetShowingGrid(bool showing); + SANDBOX_API bool StickySelectEnabled(); + SANDBOX_API void SetStickySelectEnabled(bool enabled); + SANDBOX_API float ManipulatorLineBoundWidth(); SANDBOX_API void SetManipulatorLineBoundWidth(float lineBoundWidth); diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 736bbe5feb..5b5b52d28f 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -295,28 +295,17 @@ void EditorViewportWidget::mousePressEvent(QMouseEvent* event) QtViewport::mousePressEvent(event); } -AzToolsFramework::ViewportInteraction::MousePick EditorViewportWidget::BuildMousePickInternal(const QPoint& point) const +AzToolsFramework::ViewportInteraction::MousePick EditorViewportWidget::BuildMousePick(const QPoint& point) const { - using namespace AzToolsFramework::ViewportInteraction; - - MousePick mousePick; - mousePick.m_screenCoordinates = ScreenPointFromQPoint(point); - const auto& ray = m_renderViewport->ViewportScreenToWorldRay(mousePick.m_screenCoordinates); - if (ray.has_value()) + AzToolsFramework::ViewportInteraction::MousePick mousePick; + mousePick.m_screenCoordinates = AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(point); + if (const auto& ray = m_renderViewport->ViewportScreenToWorldRay(mousePick.m_screenCoordinates); + ray.has_value()) { mousePick.m_rayOrigin = ray.value().origin; mousePick.m_rayDirection = ray.value().direction; } - return mousePick; -} -AzToolsFramework::ViewportInteraction::MousePick EditorViewportWidget::BuildMousePick(const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - - PreWidgetRendering(); - const MousePick mousePick = BuildMousePickInternal(point); - PostWidgetRendering(); return mousePick; } @@ -325,9 +314,7 @@ AzToolsFramework::ViewportInteraction::MouseInteraction EditorViewportWidget::Bu const AzToolsFramework::ViewportInteraction::KeyboardModifiers modifiers, const AzToolsFramework::ViewportInteraction::MousePick& mousePick) const { - using namespace AzToolsFramework::ViewportInteraction; - - MouseInteraction mouse; + AzToolsFramework::ViewportInteraction::MouseInteraction mouse; mouse.m_interactionId.m_cameraId = m_viewEntityId; mouse.m_interactionId.m_viewportId = GetViewportId(); mouse.m_mouseButtons = buttons; @@ -339,11 +326,11 @@ AzToolsFramework::ViewportInteraction::MouseInteraction EditorViewportWidget::Bu AzToolsFramework::ViewportInteraction::MouseInteraction EditorViewportWidget::BuildMouseInteraction( const Qt::MouseButtons buttons, const Qt::KeyboardModifiers modifiers, const QPoint& point) { - using namespace AzToolsFramework::ViewportInteraction; + namespace AztfVi = AzToolsFramework::ViewportInteraction; return BuildMouseInteractionInternal( - BuildMouseButtons(buttons), - BuildKeyboardModifiers(modifiers), + AztfVi::BuildMouseButtons(buttons), + AztfVi::BuildKeyboardModifiers(modifiers), BuildMousePick(WidgetToViewport(point))); } @@ -682,16 +669,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) case eNotify_OnEndSceneSave: PopDisableRendering(); break; - - case eNotify_OnBeginLoad: // disables viewport input when starting to load an existing level - case eNotify_OnBeginCreate: // disables viewport input when starting to create a new level - m_freezeViewportInput = true; - break; - - case eNotify_OnEndLoad: // enables viewport input when finished loading an existing level - case eNotify_OnEndCreate: // enables viewport input when finished creating a new level - m_freezeViewportInput = false; - break; } } @@ -721,8 +698,6 @@ void EditorViewportWidget::OnBeginPrepareRender() return; } - PreWidgetRendering(); - RenderAll(); // Draw 2D helpers. @@ -748,8 +723,6 @@ void EditorViewportWidget::OnBeginPrepareRender() m_debugDisplay->SetState(prevState); m_debugDisplay->DepthTestOn(); - - PostWidgetRendering(); } ////////////////////////////////////////////////////////////////////////// @@ -769,15 +742,18 @@ void EditorViewportWidget::RenderAll() if (m_manipulatorManager != nullptr) { - using namespace AzToolsFramework::ViewportInteraction; + namespace AztfVi = AzToolsFramework::ViewportInteraction; + + AztfVi::KeyboardModifiers keyboardModifiers; + AztfVi::EditorModifierKeyRequestBus::BroadcastResult( + keyboardModifiers, &AztfVi::EditorModifierKeyRequestBus::Events::QueryKeyboardModifiers); m_debugDisplay->DepthTestOff(); m_manipulatorManager->DrawManipulators( *m_debugDisplay, GetCameraState(), BuildMouseInteractionInternal( - MouseButtons(TranslateMouseButtons(QGuiApplication::mouseButtons())), - BuildKeyboardModifiers(QGuiApplication::queryKeyboardModifiers()), - BuildMousePickInternal(WidgetToViewport(mapFromGlobal(QCursor::pos()))))); + AztfVi::MouseButtons(AztfVi::TranslateMouseButtons(QGuiApplication::mouseButtons())), keyboardModifiers, + BuildMousePick(WidgetToViewport(mapFromGlobal(QCursor::pos()))))); m_debugDisplay->DepthTestOn(); } } @@ -950,8 +926,6 @@ AZ::Vector3 EditorViewportWidget::PickTerrain(const AzFramework::ScreenPoint& po AZ::EntityId EditorViewportWidget::PickEntity(const AzFramework::ScreenPoint& point) { - PreWidgetRendering(); - AZ::EntityId entityId; HitContext hitInfo; hitInfo.view = this; @@ -964,8 +938,6 @@ AZ::EntityId EditorViewportWidget::PickEntity(const AzFramework::ScreenPoint& po } } - PostWidgetRendering(); - return entityId; } @@ -984,43 +956,28 @@ AzFramework::ScreenPoint EditorViewportWidget::ViewportWorldToScreen(const AZ::V return m_renderViewport->ViewportWorldToScreen(worldPosition); } -bool EditorViewportWidget::IsViewportInputFrozen() -{ - return m_freezeViewportInput; -} - -void EditorViewportWidget::FreezeViewportInput(bool freeze) -{ - m_freezeViewportInput = freeze; -} - QWidget* EditorViewportWidget::GetWidgetForViewportContextMenu() { return this; } -void EditorViewportWidget::BeginWidgetContext() -{ - PreWidgetRendering(); -} - -void EditorViewportWidget::EndWidgetContext() -{ - PostWidgetRendering(); -} - bool EditorViewportWidget::ShowingWorldSpace() { - using namespace AzToolsFramework::ViewportInteraction; - return BuildKeyboardModifiers(QGuiApplication::queryKeyboardModifiers()).Shift(); + namespace AztfVi = AzToolsFramework::ViewportInteraction; + + AztfVi::KeyboardModifiers keyboardModifiers; + AztfVi::EditorModifierKeyRequestBus::BroadcastResult( + keyboardModifiers, &AztfVi::EditorModifierKeyRequestBus::Events::QueryKeyboardModifiers); + + return keyboardModifiers.Shift(); } void EditorViewportWidget::SetViewportId(int id) { CViewport::SetViewportId(id); - // Clear the cached debugdisplay pointer. we're about to delete that render viewport, and deleting the render - // viewport invalidates the debugdisplay. + // Clear the cached DebugDisplay pointer. we're about to delete that render viewport, and deleting the render + // viewport invalidates the DebugDisplay. m_debugDisplay = nullptr; // First delete any existing layout @@ -1085,7 +1042,6 @@ void EditorViewportWidget::SetViewportId(int id) void EditorViewportWidget::ConnectViewportInteractionRequestBus() { - AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler::BusConnect(GetViewportId()); AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); m_viewportUi.ConnectViewportUiBus(GetViewportId()); @@ -1100,7 +1056,6 @@ void EditorViewportWidget::DisconnectViewportInteractionRequestBus() m_viewportUi.DisconnectViewportUiBus(); AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler::BusDisconnect(); AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusDisconnect(); - AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler::BusDisconnect(); } namespace AZ::ViewportHelpers @@ -2570,6 +2525,11 @@ float EditorViewportSettings::ManipulatorCircleBoundWidth() const return SandboxEditor::ManipulatorCircleBoundWidth(); } +bool EditorViewportSettings::StickySelectEnabled() const +{ + return SandboxEditor::StickySelectEnabled(); +} + AZ_CVAR_EXTERNED(bool, ed_previewGameInFullscreen_once); bool EditorViewportWidget::ShouldPreviewFullscreen() const diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index dff0adb55a..49930a2a13 100644 --- a/Code/Editor/EditorViewportWidget.h +++ b/Code/Editor/EditorViewportWidget.h @@ -77,6 +77,7 @@ struct EditorViewportSettings : public AzToolsFramework::ViewportInteraction::Vi float AngleStep() const override; float ManipulatorLineBoundWidth() const override; float ManipulatorCircleBoundWidth() const override; + bool StickySelectEnabled() const override; }; // EditorViewportWidget window @@ -89,7 +90,6 @@ class SANDBOX_API EditorViewportWidget final , private Camera::EditorCameraRequestBus::Handler , private Camera::CameraNotificationBus::Handler , private AzFramework::InputSystemCursorConstraintRequestBus::Handler - , private AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler , private AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler , private AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler , private AzFramework::AssetCatalogEventBus::Handler @@ -201,18 +201,12 @@ private: // AzFramework::InputSystemCursorConstraintRequestBus overrides ... void* GetSystemCursorConstraintWindow() const override; - // AzToolsFramework::ViewportFreezeRequestBus overrides ... - bool IsViewportInputFrozen() override; - void FreezeViewportInput(bool freeze) override; - - // AzToolsFramework::MainEditorViewportInteractionRequestBus + // AzToolsFramework::MainEditorViewportInteractionRequestBus overrides ... AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) override; AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) override; float TerrainHeight(const AZ::Vector2& position) override; bool ShowingWorldSpace() override; QWidget* GetWidgetForViewportContextMenu() override; - void BeginWidgetContext() override; - void EndWidgetContext() override; // EditorEntityViewportInteractionRequestBus overrides ... void FindVisibleEntities(AZStd::vector& visibleEntities) override; @@ -271,7 +265,7 @@ private: // note: The argument passed to parameter **point**, originating // from a Qt event, must first be passed to WidgetToViewport before being // passed to BuildMousePick. - AzToolsFramework::ViewportInteraction::MousePick BuildMousePick(const QPoint& point); + AzToolsFramework::ViewportInteraction::MousePick BuildMousePick(const QPoint& point) const; bool CheckRespondToInput() const; @@ -281,7 +275,6 @@ private: void PushDisableRendering(); void PopDisableRendering(); bool IsRenderingDisabled() const; - AzToolsFramework::ViewportInteraction::MousePick BuildMousePickInternal(const QPoint& point) const; void RestoreViewportAfterGameMode(); @@ -386,9 +379,6 @@ private: // Unclear if it's still necessary. QSet m_keyDown; - // State for ViewportFreezeRequestBus, currently does nothing - bool m_freezeViewportInput = false; - // This widget holds a reference to the manipulator manage because its responsible for drawing manipulators AZStd::shared_ptr m_manipulatorManager; diff --git a/Code/Editor/Export/ExportManager.h b/Code/Editor/Export/ExportManager.h index be81591e56..14318be957 100644 --- a/Code/Editor/Export/ExportManager.h +++ b/Code/Editor/Export/ExportManager.h @@ -36,8 +36,8 @@ namespace Export public: CMesh(); - virtual int GetFaceCount() const { return static_cast(m_faces.size()); } - virtual const Face* GetFaceBuffer() const { return m_faces.size() ? &m_faces[0] : 0; } + int GetFaceCount() const override { return static_cast(m_faces.size()); } + const Face* GetFaceBuffer() const override { return !m_faces.empty() ? &m_faces[0] : nullptr; } private: std::vector m_faces; @@ -54,13 +54,13 @@ namespace Export CObject(const char* pName); int GetVertexCount() const override { return static_cast(m_vertices.size()); } - const Vector3D* GetVertexBuffer() const override { return m_vertices.size() ? &m_vertices[0] : nullptr; } + const Vector3D* GetVertexBuffer() const override { return !m_vertices.empty() ? &m_vertices[0] : nullptr; } int GetNormalCount() const override { return static_cast(m_normals.size()); } - const Vector3D* GetNormalBuffer() const override { return m_normals.size() ? &m_normals[0] : nullptr; } + const Vector3D* GetNormalBuffer() const override { return !m_normals.empty() ? &m_normals[0] : nullptr; } int GetTexCoordCount() const override { return static_cast(m_texCoords.size()); } - const UV* GetTexCoordBuffer() const override { return m_texCoords.size() ? &m_texCoords[0] : nullptr; } + const UV* GetTexCoordBuffer() const override { return !m_texCoords.empty() ? &m_texCoords[0] : nullptr; } int GetMeshCount() const override { return static_cast(m_meshes.size()); } Mesh* GetMesh(int index) const override { return m_meshes[index]; } @@ -68,9 +68,9 @@ namespace Export size_t MeshHash() const override{return m_MeshHash; } void SetMaterialName(const char* pName); - virtual int GetEntityAnimationDataCount() const {return static_cast(m_entityAnimData.size()); } - virtual const EntityAnimData* GetEntityAnimationData(int index) const {return &m_entityAnimData[index]; } - virtual void SetEntityAnimationData(EntityAnimData entityData){ m_entityAnimData.push_back(entityData); }; + int GetEntityAnimationDataCount() const override {return static_cast(m_entityAnimData.size()); } + const EntityAnimData* GetEntityAnimationData(int index) const override {return &m_entityAnimData[index]; } + void SetEntityAnimationData(EntityAnimData entityData) override{ m_entityAnimData.push_back(entityData); }; void SetLastPtr(CBaseObject* pObject){m_pLastObject = pObject; }; CBaseObject* GetLastObjectPtr(){return m_pLastObject; }; @@ -92,9 +92,11 @@ namespace Export : public IData { public: - virtual int GetObjectCount() const { return static_cast(m_objects.size()); } - virtual Object* GetObject(int index) const { return m_objects[index]; } - virtual Object* AddObject(const char* objectName); + virtual ~CData() = default; + + int GetObjectCount() const override { return static_cast(m_objects.size()); } + Object* GetObject(int index) const override { return m_objects[index]; } + Object* AddObject(const char* objectName) override; void Clear(); private: @@ -117,7 +119,7 @@ public: //! Register exporter //! return true if succeed, otherwise false - virtual bool RegisterExporter(IExporter* pExporter); + bool RegisterExporter(IExporter* pExporter) override; //! Export specified geometry //! return true if succeed, otherwise false @@ -139,15 +141,15 @@ public: //! Exports the stat obj to the obj file specified //! returns true if succeeded, otherwise false - virtual bool ExportSingleStatObj(IStatObj* pStatObj, const char* filename); + bool ExportSingleStatObj(IStatObj* pStatObj, const char* filename) override; void SetBakedKeysSequenceExport(bool bBaked){m_bBakedKeysSequenceExport = bBaked; }; void SaveNodeKeysTimeToXML(); private: - void AddMesh(Export::CObject* pObj, const IIndexedMesh* pIndMesh, Matrix34A* pTm = 0); - bool AddStatObj(Export::CObject* pObj, IStatObj* pStatObj, Matrix34A* pTm = 0); + void AddMesh(Export::CObject* pObj, const IIndexedMesh* pIndMesh, Matrix34A* pTm = nullptr); + bool AddStatObj(Export::CObject* pObj, IStatObj* pStatObj, Matrix34A* pTm = nullptr); bool AddMeshes(Export::CObject* pObj); bool AddObject(CBaseObject* pBaseObj); void SolveHierarchy(); diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp index 1fc980fdac..9315505e08 100644 --- a/Code/Editor/GameExporter.cpp +++ b/Code/Editor/GameExporter.cpp @@ -318,7 +318,7 @@ void CGameExporter::ExportLevelInfo(const QString& path) root->setAttr("Name", levelName.toUtf8().data()); auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); const AZ::Aabb terrainAabb = terrain ? terrain->GetTerrainAabb() : AZ::Aabb::CreateFromPoint(AZ::Vector3::CreateZero()); - const AZ::Vector2 terrainGridResolution = terrain ? terrain->GetTerrainGridResolution() : AZ::Vector2::CreateOne(); + const AZ::Vector2 terrainGridResolution = terrain ? terrain->GetTerrainHeightQueryResolution() : AZ::Vector2::CreateOne(); const int compiledHeightmapSize = static_cast(terrainAabb.GetXExtent() / terrainGridResolution.GetX()); root->setAttr("HeightmapSize", compiledHeightmapSize); @@ -432,25 +432,6 @@ void CGameExporter::ExportFileList(const QString& path, const QString& levelName newFileNode->setAttr("src", handle.m_filename.data()); newFileNode->setAttr("dest", handle.m_filename.data()); newFileNode->setAttr("size", handle.m_fileDesc.nSize); - - unsigned char md5[16]; - AZStd::string filenameToHash = GetIEditor()->GetGameEngine()->GetLevelPath().toUtf8().data(); - filenameToHash += "/"; - filenameToHash += AZStd::string{ handle.m_filename.data(), handle.m_filename.size() }; - if (gEnv->pCryPak->ComputeMD5(filenameToHash.data(), md5)) - { - char md5string[33]; - sprintf_s(md5string, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - md5[0], md5[1], md5[2], md5[3], - md5[4], md5[5], md5[6], md5[7], - md5[8], md5[9], md5[10], md5[11], - md5[12], md5[13], md5[14], md5[15]); - newFileNode->setAttr("md5", md5string); - } - else - { - newFileNode->setAttr("md5", ""); - } } } } while (handle = gEnv->pCryPak->FindNext(handle)); diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp index 51ef0dedc3..66c64d5bef 100644 --- a/Code/Editor/IEditorImpl.cpp +++ b/Code/Editor/IEditorImpl.cpp @@ -632,14 +632,7 @@ void CEditorImpl::SetReferenceCoordSys(RefCoordSys refCoords) CViewport* pViewport = GetActiveView(); if (pViewport) { - //Pre and Post widget rendering calls are made here to make sure that the proper camera state is set. - //MakeConstructionPlane will make a call to ViewToWorldRay which needs the correct camera state - //in the CRenderViewport to be set. - pViewport->PreWidgetRendering(); - pViewport->MakeConstructionPlane(GetIEditor()->GetAxisConstrains()); - - pViewport->PostWidgetRendering(); } Notify(eNotify_OnRefCoordSysChange); diff --git a/Code/Editor/IEditorImpl.h b/Code/Editor/IEditorImpl.h index 762dd1db11..26701edec2 100644 --- a/Code/Editor/IEditorImpl.h +++ b/Code/Editor/IEditorImpl.h @@ -79,70 +79,70 @@ public: void SetGameEngine(CGameEngine* ge); - void DeleteThis() { delete this; }; - IEditorClassFactory* GetClassFactory(); - CEditorCommandManager* GetCommandManager() { return m_pCommandManager; }; - ICommandManager* GetICommandManager() { return m_pCommandManager; } - void ExecuteCommand(const char* sCommand, ...); - void ExecuteCommand(const QString& command); - void SetDocument(CCryEditDoc* pDoc); - CCryEditDoc* GetDocument() const; + void DeleteThis() override { delete this; }; + IEditorClassFactory* GetClassFactory() override; + CEditorCommandManager* GetCommandManager() override { return m_pCommandManager; }; + ICommandManager* GetICommandManager() override { return m_pCommandManager; } + void ExecuteCommand(const char* sCommand, ...) override; + void ExecuteCommand(const QString& command) override; + void SetDocument(CCryEditDoc* pDoc) override; + CCryEditDoc* GetDocument() const override; bool IsLevelLoaded() const override; - void SetModifiedFlag(bool modified = true); - void SetModifiedModule(EModifiedModule eModifiedModule, bool boSet = true); - bool IsLevelExported() const; - bool SetLevelExported(bool boExported = true); + void SetModifiedFlag(bool modified = true) override; + void SetModifiedModule(EModifiedModule eModifiedModule, bool boSet = true) override; + bool IsLevelExported() const override; + bool SetLevelExported(bool boExported = true) override; void InitFinished(); - bool IsModified(); - bool IsInitialized() const{ return m_bInitialized; } - bool SaveDocument(); - ISystem* GetSystem(); - void WriteToConsole(const char* string) { CLogFile::WriteLine(string); }; - void WriteToConsole(const QString& string) { CLogFile::WriteLine(string); }; + bool IsModified() override; + bool IsInitialized() const override{ return m_bInitialized; } + bool SaveDocument() override; + ISystem* GetSystem() override; + void WriteToConsole(const char* string) override { CLogFile::WriteLine(string); }; + void WriteToConsole(const QString& string) override { CLogFile::WriteLine(string); }; // Change the message in the status bar - void SetStatusText(const QString& pszString); - virtual IMainStatusBar* GetMainStatusBar() override; - bool ShowConsole([[maybe_unused]] bool show) + void SetStatusText(const QString& pszString) override; + IMainStatusBar* GetMainStatusBar() override; + bool ShowConsole([[maybe_unused]] bool show) override { //if (AfxGetMainWnd())return ((CMainFrame *) (AfxGetMainWnd()))->ShowConsole(show); return false; } - void SetConsoleVar(const char* var, float value); - float GetConsoleVar(const char* var); + void SetConsoleVar(const char* var, float value) override; + float GetConsoleVar(const char* var) override; //! Query main window of the editor QMainWindow* GetEditorMainWindow() const override { return MainWindow::instance(); }; - QString GetPrimaryCDFolder(); + QString GetPrimaryCDFolder() override; QString GetLevelName() override; - QString GetLevelFolder(); - QString GetLevelDataFolder(); - QString GetSearchPath(EEditorPathName path); - QString GetResolvedUserFolder(); - bool ExecuteConsoleApp(const QString& CommandLine, QString& OutputText, bool bNoTimeOut = false, bool bShowWindow = false); - virtual bool IsInGameMode() override; - virtual void SetInGameMode(bool inGame) override; - virtual bool IsInSimulationMode() override; - virtual bool IsInTestMode() override; - virtual bool IsInPreviewMode() override; - virtual bool IsInConsolewMode() override; - virtual bool IsInLevelLoadTestMode() override; - virtual bool IsInMatEditMode() override { return m_bMatEditMode; } + QString GetLevelFolder() override; + QString GetLevelDataFolder() override; + QString GetSearchPath(EEditorPathName path) override; + QString GetResolvedUserFolder() override; + bool ExecuteConsoleApp(const QString& CommandLine, QString& OutputText, bool bNoTimeOut = false, bool bShowWindow = false) override; + bool IsInGameMode() override; + void SetInGameMode(bool inGame) override; + bool IsInSimulationMode() override; + bool IsInTestMode() override; + bool IsInPreviewMode() override; + bool IsInConsolewMode() override; + bool IsInLevelLoadTestMode() override; + bool IsInMatEditMode() override { return m_bMatEditMode; } //! Enables/Disable updates of editor. - void EnableUpdate(bool enable) { m_bUpdates = enable; }; + void EnableUpdate(bool enable) override { m_bUpdates = enable; }; //! Enable/Disable accelerator table, (Enabled by default). - void EnableAcceleratos(bool bEnable); - CGameEngine* GetGameEngine() { return m_pGameEngine; }; - CDisplaySettings* GetDisplaySettings() { return m_pDisplaySettings; }; - const SGizmoParameters& GetGlobalGizmoParameters(); - CBaseObject* NewObject(const char* typeName, const char* fileName = "", const char* name = "", float x = 0.0f, float y = 0.0f, float z = 0.0f, bool modifyDoc = true); - void DeleteObject(CBaseObject* obj); - CBaseObject* CloneObject(CBaseObject* obj); - IObjectManager* GetObjectManager(); + void EnableAcceleratos(bool bEnable) override; + CGameEngine* GetGameEngine() override { return m_pGameEngine; }; + CDisplaySettings* GetDisplaySettings() override { return m_pDisplaySettings; }; + const SGizmoParameters& GetGlobalGizmoParameters() override; + CBaseObject* NewObject(const char* typeName, const char* fileName = "", const char* name = "", float x = 0.0f, float y = 0.0f, float z = 0.0f, bool modifyDoc = true) override; + void DeleteObject(CBaseObject* obj) override; + CBaseObject* CloneObject(CBaseObject* obj) override; + IObjectManager* GetObjectManager() override; // This will return a null pointer if CrySystem is not loaded before // Global Sandbox Settings are loaded from the registry before CrySystem // At that stage GetSettingsManager will return null and xml node in @@ -150,27 +150,27 @@ public: // After m_IEditor is created and CrySystem loaded, it is possible // to feed memory node with all necessary data needed for export // (gSettings.Load() and CXTPDockingPaneManager/CXTPDockingPaneLayout Sandbox layout management) - CSettingsManager* GetSettingsManager(); - CSelectionGroup* GetSelection(); - int ClearSelection(); - CBaseObject* GetSelectedObject(); - void SelectObject(CBaseObject* obj); - void LockSelection(bool bLock); - bool IsSelectionLocked(); + CSettingsManager* GetSettingsManager() override; + CSelectionGroup* GetSelection() override; + int ClearSelection() override; + CBaseObject* GetSelectedObject() override; + void SelectObject(CBaseObject* obj) override; + void LockSelection(bool bLock) override; + bool IsSelectionLocked() override; - IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType); - CMusicManager* GetMusicManager() { return m_pMusicManager; }; + IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType) override; + CMusicManager* GetMusicManager() override { return m_pMusicManager; }; IEditorFileMonitor* GetFileMonitor() override; void RegisterEventLoopHook(IEventLoopHook* pHook) override; void UnregisterEventLoopHook(IEventLoopHook* pHook) override; - IIconManager* GetIconManager(); - float GetTerrainElevation(float x, float y); - Editor::EditorQtApplication* GetEditorQtApplication() { return m_QtApplication; } + IIconManager* GetIconManager() override; + float GetTerrainElevation(float x, float y) override; + Editor::EditorQtApplication* GetEditorQtApplication() override { return m_QtApplication; } const QColor& GetColorByName(const QString& name) override; ////////////////////////////////////////////////////////////////////////// - IMovieSystem* GetMovieSystem() + IMovieSystem* GetMovieSystem() override { if (m_pSystem) { @@ -179,37 +179,37 @@ public: return nullptr; }; - CPluginManager* GetPluginManager() { return m_pPluginManager; } - CViewManager* GetViewManager(); - CViewport* GetActiveView(); - void SetActiveView(CViewport* viewport); + CPluginManager* GetPluginManager() override { return m_pPluginManager; } + CViewManager* GetViewManager() override; + CViewport* GetActiveView() override; + void SetActiveView(CViewport* viewport) override; - CLevelIndependentFileMan* GetLevelIndependentFileMan() { return m_pLevelIndependentFileMan; } + CLevelIndependentFileMan* GetLevelIndependentFileMan() override { return m_pLevelIndependentFileMan; } - void UpdateViews(int flags, const AABB* updateRegion); - void ResetViews(); - void ReloadTrackView(); - Vec3 GetMarkerPosition() { return m_marker; }; - void SetMarkerPosition(const Vec3& pos) { m_marker = pos; }; - void SetSelectedRegion(const AABB& box); - void GetSelectedRegion(AABB& box); + void UpdateViews(int flags, const AABB* updateRegion) override; + void ResetViews() override; + void ReloadTrackView() override; + Vec3 GetMarkerPosition() override { return m_marker; }; + void SetMarkerPosition(const Vec3& pos) override { m_marker = pos; }; + void SetSelectedRegion(const AABB& box) override; + void GetSelectedRegion(AABB& box) override; bool AddToolbarItem(uint8 iId, IUIEvent* pIHandler); - void SetDataModified(); - void SetOperationMode(EOperationMode mode); - EOperationMode GetOperationMode(); + void SetDataModified() override; + void SetOperationMode(EOperationMode mode) override; + EOperationMode GetOperationMode() override; - ITransformManipulator* ShowTransformManipulator(bool bShow); - ITransformManipulator* GetTransformManipulator(); - void SetAxisConstraints(AxisConstrains axis); - AxisConstrains GetAxisConstrains(); - void SetAxisVectorLock(bool bAxisVectorLock) { m_bAxisVectorLock = bAxisVectorLock; } - bool IsAxisVectorLocked() { return m_bAxisVectorLock; } - void SetTerrainAxisIgnoreObjects(bool bIgnore); - bool IsTerrainAxisIgnoreObjects(); - void SetReferenceCoordSys(RefCoordSys refCoords); - RefCoordSys GetReferenceCoordSys(); - XmlNodeRef FindTemplate(const QString& templateName); - void AddTemplate(const QString& templateName, XmlNodeRef& tmpl); + ITransformManipulator* ShowTransformManipulator(bool bShow) override; + ITransformManipulator* GetTransformManipulator() override; + void SetAxisConstraints(AxisConstrains axis) override; + AxisConstrains GetAxisConstrains() override; + void SetAxisVectorLock(bool bAxisVectorLock) override { m_bAxisVectorLock = bAxisVectorLock; } + bool IsAxisVectorLocked() override { return m_bAxisVectorLock; } + void SetTerrainAxisIgnoreObjects(bool bIgnore) override; + bool IsTerrainAxisIgnoreObjects() override; + void SetReferenceCoordSys(RefCoordSys refCoords) override; + RefCoordSys GetReferenceCoordSys() override; + XmlNodeRef FindTemplate(const QString& templateName) override; + void AddTemplate(const QString& templateName, XmlNodeRef& tmpl) override; const QtViewPane* OpenView(QString sViewClassName, bool reuseOpened = true) override; @@ -220,87 +220,87 @@ public: */ QWidget* FindView(QString viewClassName) override; - bool CloseView(const char* sViewClassName); - bool SetViewFocus(const char* sViewClassName); + bool CloseView(const char* sViewClassName) override; + bool SetViewFocus(const char* sViewClassName) override; - virtual QWidget* OpenWinWidget(WinWidgetId openId) override; - virtual WinWidget::WinWidgetManager* GetWinWidgetManager() const override; + QWidget* OpenWinWidget(WinWidgetId openId) override; + WinWidget::WinWidgetManager* GetWinWidgetManager() const override; // close ALL panels related to classId, used when unloading plugins. - void CloseView(const GUID& classId); + void CloseView(const GUID& classId) override; bool SelectColor(QColor &color, QWidget *parent = 0) override; void Update(); - SFileVersion GetFileVersion() { return m_fileVersion; }; - SFileVersion GetProductVersion() { return m_productVersion; }; + SFileVersion GetFileVersion() override { return m_fileVersion; }; + SFileVersion GetProductVersion() override { return m_productVersion; }; //! Get shader enumerator. - CUndoManager* GetUndoManager() { return m_pUndoManager; }; - void BeginUndo(); - void RestoreUndo(bool undo); - void AcceptUndo(const QString& name); - void CancelUndo(); - void SuperBeginUndo(); - void SuperAcceptUndo(const QString& name); - void SuperCancelUndo(); - void SuspendUndo(); - void ResumeUndo(); - void Undo(); - void Redo(); - bool IsUndoRecording(); - bool IsUndoSuspended(); - void RecordUndo(IUndoObject* obj); - bool FlushUndo(bool isShowMessage = false); - bool ClearLastUndoSteps(int steps); - bool ClearRedoStack(); + CUndoManager* GetUndoManager() override { return m_pUndoManager; }; + void BeginUndo() override; + void RestoreUndo(bool undo) override; + void AcceptUndo(const QString& name) override; + void CancelUndo() override; + void SuperBeginUndo() override; + void SuperAcceptUndo(const QString& name) override; + void SuperCancelUndo() override; + void SuspendUndo() override; + void ResumeUndo() override; + void Undo() override; + void Redo() override; + bool IsUndoRecording() override; + bool IsUndoSuspended() override; + void RecordUndo(IUndoObject* obj) override; + bool FlushUndo(bool isShowMessage = false) override; + bool ClearLastUndoSteps(int steps) override; + bool ClearRedoStack() override; //! Retrieve current animation context. - CAnimationContext* GetAnimation(); + CAnimationContext* GetAnimation() override; CTrackViewSequenceManager* GetSequenceManager() override; ITrackViewSequenceManager* GetSequenceManagerInterface() override; - CToolBoxManager* GetToolBoxManager() { return m_pToolBoxManager; }; - IErrorReport* GetErrorReport() { return m_pErrorReport; } - IErrorReport* GetLastLoadedLevelErrorReport() { return m_pLasLoadedLevelErrorReport; } + CToolBoxManager* GetToolBoxManager() override { return m_pToolBoxManager; }; + IErrorReport* GetErrorReport() override { return m_pErrorReport; } + IErrorReport* GetLastLoadedLevelErrorReport() override { return m_pLasLoadedLevelErrorReport; } void StartLevelErrorReportRecording() override; - void CommitLevelErrorReport() {SAFE_DELETE(m_pLasLoadedLevelErrorReport); m_pLasLoadedLevelErrorReport = new CErrorReport(*m_pErrorReport); } - virtual IFileUtil* GetFileUtil() override { return m_pFileUtil; } - void Notify(EEditorNotifyEvent event); - void NotifyExcept(EEditorNotifyEvent event, IEditorNotifyListener* listener); - void RegisterNotifyListener(IEditorNotifyListener* listener); - void UnregisterNotifyListener(IEditorNotifyListener* listener); + void CommitLevelErrorReport() override {SAFE_DELETE(m_pLasLoadedLevelErrorReport); m_pLasLoadedLevelErrorReport = new CErrorReport(*m_pErrorReport); } + IFileUtil* GetFileUtil() override { return m_pFileUtil; } + void Notify(EEditorNotifyEvent event) override; + void NotifyExcept(EEditorNotifyEvent event, IEditorNotifyListener* listener) override; + void RegisterNotifyListener(IEditorNotifyListener* listener) override; + void UnregisterNotifyListener(IEditorNotifyListener* listener) override; //! Register document notifications listener. - void RegisterDocListener(IDocListener* listener); + void RegisterDocListener(IDocListener* listener) override; //! Unregister document notifications listener. - void UnregisterDocListener(IDocListener* listener); + void UnregisterDocListener(IDocListener* listener) override; //! Retrieve interface to the source control. - ISourceControl* GetSourceControl(); + ISourceControl* GetSourceControl() override; //! Retrieve true if source control is provided and enabled in settings bool IsSourceControlAvailable() override; //! Only returns true if source control is both available AND currently connected and functioning bool IsSourceControlConnected() override; //! Setup Material Editor mode void SetMatEditMode(bool bIsMatEditMode); - CUIEnumsDatabase* GetUIEnumsDatabase() { return m_pUIEnumsDatabase; }; - void AddUIEnums(); - void ReduceMemory(); + CUIEnumsDatabase* GetUIEnumsDatabase() override { return m_pUIEnumsDatabase; }; + void AddUIEnums() override; + void ReduceMemory() override; // Get Export manager - IExportManager* GetExportManager(); + IExportManager* GetExportManager() override; // Set current configuration spec of the editor. - void SetEditorConfigSpec(ESystemConfigSpec spec, ESystemConfigPlatform platform); - ESystemConfigSpec GetEditorConfigSpec() const; - ESystemConfigPlatform GetEditorConfigPlatform() const; - void ReloadTemplates(); + void SetEditorConfigSpec(ESystemConfigSpec spec, ESystemConfigPlatform platform) override; + ESystemConfigSpec GetEditorConfigSpec() const override; + ESystemConfigPlatform GetEditorConfigPlatform() const override; + void ReloadTemplates() override; void AddErrorMessage(const QString& text, const QString& caption); - virtual void ShowStatusText(bool bEnable); + void ShowStatusText(bool bEnable) override; void OnObjectContextMenuOpened(QMenu* pMenu, const CBaseObject* pObject); - virtual void RegisterObjectContextMenuExtension(TContextMenuExtensionFunc func) override; + void RegisterObjectContextMenuExtension(TContextMenuExtensionFunc func) override; - virtual SSystemGlobalEnvironment* GetEnv() override; - virtual IBaseLibraryManager* GetMaterialManagerLibrary() override; // Vladimir@Conffx - virtual IEditorMaterialManager* GetIEditorMaterialManager() override; // Vladimir@Conffx - virtual IImageUtil* GetImageUtil() override; // Vladimir@conffx - virtual SEditorSettings* GetEditorSettings() override; - virtual IEditorPanelUtils* GetEditorPanelUtils() override; - virtual ILogFile* GetLogFile() override { return m_pLogFile; } + SSystemGlobalEnvironment* GetEnv() override; + IBaseLibraryManager* GetMaterialManagerLibrary() override; // Vladimir@Conffx + IEditorMaterialManager* GetIEditorMaterialManager() override; // Vladimir@Conffx + IImageUtil* GetImageUtil() override; // Vladimir@conffx + SEditorSettings* GetEditorSettings() override; + IEditorPanelUtils* GetEditorPanelUtils() override; + ILogFile* GetLogFile() override { return m_pLogFile; } void UnloadPlugins() override; void LoadPlugins() override; diff --git a/Code/Editor/Include/IEditorClassFactory.h b/Code/Editor/Include/IEditorClassFactory.h index 0827dc96dc..dd47f803e2 100644 --- a/Code/Editor/Include/IEditorClassFactory.h +++ b/Code/Editor/Include/IEditorClassFactory.h @@ -14,8 +14,10 @@ #define CRYINCLUDE_EDITOR_INCLUDE_IEDITORCLASSFACTORY_H #pragma once +#include #include #include +#include #define DEFINE_UUID(l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ static const GUID uuid() { return { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } }; } @@ -34,7 +36,7 @@ struct IUnknown #endif #define __uuidof(T) T::uuid() -#if defined(AZ_PLATFORM_LINUX) +#if defined(AZ_PLATFORM_LINUX) || defined(AZ_PLATFORM_MAC) # ifndef _REFGUID_DEFINED # define _REFGUID_DEFINED @@ -65,7 +67,7 @@ enum }; #endif -#endif // defined(AZ_PLATFORM_LINUX) +#endif // defined(AZ_PLATFORM_LINUX) || defined(AZ_PLATFORM_MAC) #include "SandboxAPI.h" diff --git a/Code/Editor/LevelTreeModel.h b/Code/Editor/LevelTreeModel.h index 4f0e36a311..7cc5cf5496 100644 --- a/Code/Editor/LevelTreeModel.h +++ b/Code/Editor/LevelTreeModel.h @@ -23,7 +23,7 @@ class LevelTreeModelFilter Q_OBJECT public: explicit LevelTreeModelFilter(QObject* parent = nullptr); - bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const; + bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; void setFilterText(const QString&); QVariant data(const QModelIndex& index, int role) const override; private: diff --git a/Code/Editor/Lib/Tests/IEditorMock.h b/Code/Editor/Lib/Tests/IEditorMock.h index cb01757b9c..390ffebe79 100644 --- a/Code/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Editor/Lib/Tests/IEditorMock.h @@ -25,6 +25,8 @@ public: } public: + virtual ~CEditorMock() = default; + MOCK_METHOD0(DeleteThis, void()); MOCK_METHOD0(GetSystem, ISystem*()); MOCK_METHOD0(GetClassFactory, IEditorClassFactory* ()); diff --git a/Code/Editor/Objects/AxisGizmo.h b/Code/Editor/Objects/AxisGizmo.h index dfd35388b6..bab667a629 100644 --- a/Code/Editor/Objects/AxisGizmo.h +++ b/Code/Editor/Objects/AxisGizmo.h @@ -35,21 +35,21 @@ public: ////////////////////////////////////////////////////////////////////////// // Ovverides from CGizmo ////////////////////////////////////////////////////////////////////////// - virtual void GetWorldBounds(AABB& bbox); - virtual void Display(DisplayContext& dc); - virtual bool HitTest(HitContext& hc); - virtual const Matrix34& GetMatrix() const; + void GetWorldBounds(AABB& bbox) override; + void Display(DisplayContext& dc) override; + bool HitTest(HitContext& hc) override; + const Matrix34& GetMatrix() const override; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // ITransformManipulator implementation. ////////////////////////////////////////////////////////////////////////// - virtual Matrix34 GetTransformation(RefCoordSys coordSys, IDisplayViewport* view = nullptr) const; - virtual void SetTransformation(RefCoordSys coordSys, const Matrix34& tm); - virtual bool HitTestManipulator(HitContext& hc); - virtual bool MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, int nFlags); - virtual void SetAlwaysUseLocal(bool on) + Matrix34 GetTransformation(RefCoordSys coordSys, IDisplayViewport* view = nullptr) const override; + void SetTransformation(RefCoordSys coordSys, const Matrix34& tm) override; + bool HitTestManipulator(HitContext& hc) override; + bool MouseCallback(CViewport* view, EMouseEvent event, QPoint& point, int nFlags) override; + void SetAlwaysUseLocal(bool on) override { m_bAlwaysUseLocal = on; } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Objects/BaseObject.h b/Code/Editor/Objects/BaseObject.h index ea58b4e78d..3865696ecb 100644 --- a/Code/Editor/Objects/BaseObject.h +++ b/Code/Editor/Objects/BaseObject.h @@ -712,7 +712,7 @@ protected: // May be overridden in derived classes to handle helpers scaling. ////////////////////////////////////////////////////////////////////////// virtual void SetHelperScale([[maybe_unused]] float scale) {}; - virtual float GetHelperScale() { return 1; }; + virtual float GetHelperScale() { return 1.0f; }; void SetNameInternal(const QString& name) { m_name = name; } @@ -743,9 +743,6 @@ private: //! Only called once after creation by ObjectManager. void SetClassDesc(CObjectClassDesc* classDesc); - // From CObject, (not implemented) - virtual void Serialize([[maybe_unused]] CArchive& ar) {}; - EScaleWarningLevel GetScaleWarningLevel() const; ERotationWarningLevel GetRotationWarningLevel() const; diff --git a/Code/Editor/Objects/EntityObject.h b/Code/Editor/Objects/EntityObject.h index d5600d15b7..dcc6ff7b22 100644 --- a/Code/Editor/Objects/EntityObject.h +++ b/Code/Editor/Objects/EntityObject.h @@ -82,14 +82,14 @@ public: // Overrides from CBaseObject. ////////////////////////////////////////////////////////////////////////// //! Return type name of Entity. - QString GetTypeDescription() const { return GetEntityClass(); }; + QString GetTypeDescription() const override { return GetEntityClass(); }; ////////////////////////////////////////////////////////////////////////// - bool IsSameClass(CBaseObject* obj); + bool IsSameClass(CBaseObject* obj) override; - virtual bool Init(IEditor* ie, CBaseObject* prev, const QString& file); - virtual void InitVariables(); - virtual void Done(); + bool Init(IEditor* ie, CBaseObject* prev, const QString& file) override; + void InitVariables() override; + void Done() override; void DrawExtraLightInfo (DisplayContext& disp); @@ -102,29 +102,30 @@ public: void SetEntityPropertyFloat(const char* name, float value); void SetEntityPropertyString(const char* name, const QString& value); - virtual int MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags); - virtual void OnContextMenu(QMenu* menu); + int MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags) override; + void OnContextMenu(QMenu* menu) override; - void SetName(const QString& name); - void SetSelected(bool bSelect); + void SetName(const QString& name) override; + void SetSelected(bool bSelect) override; - virtual void GetLocalBounds(AABB& box); + void GetLocalBounds(AABB& box) override; - virtual bool HitTest(HitContext& hc); - virtual bool HitHelperTest(HitContext& hc); - virtual bool HitTestRect(HitContext& hc); - void UpdateVisibility(bool bVisible); - bool ConvertFromObject(CBaseObject* object); + bool HitTest(HitContext& hc) override; + bool HitHelperTest(HitContext& hc) override; + bool HitTestRect(HitContext& hc) override; + void UpdateVisibility(bool bVisible) override; + bool ConvertFromObject(CBaseObject* object) override; - virtual void Serialize(CObjectArchive& ar); - virtual void PostLoad(CObjectArchive& ar); + using CBaseObject::Serialize; + void Serialize(CObjectArchive& ar) override; + void PostLoad(CObjectArchive& ar) override; - XmlNodeRef Export(const QString& levelPath, XmlNodeRef& xmlNode); + XmlNodeRef Export(const QString& levelPath, XmlNodeRef& xmlNode) override; ////////////////////////////////////////////////////////////////////////// - void OnEvent(ObjectEvent event); + void OnEvent(ObjectEvent event) override; - virtual void SetTransformDelegate(ITransformDelegate* pTransformDelegate) override; + void SetTransformDelegate(ITransformDelegate* pTransformDelegate) override; // Set attach flags and target enum EAttachmentType @@ -139,15 +140,15 @@ public: EAttachmentType GetAttachType() const { return m_attachmentType; } QString GetAttachTarget() const { return m_attachmentTarget; } - virtual void SetHelperScale(float scale); - virtual float GetHelperScale(); + void SetHelperScale(float scale) override; + float GetHelperScale() override; - virtual void GatherUsedResources(CUsedResources& resources); - virtual bool IsSimilarObject(CBaseObject* pObject); + void GatherUsedResources(CUsedResources& resources) override; + bool IsSimilarObject(CBaseObject* pObject) override; - virtual bool HasMeasurementAxis() const { return false; } + bool HasMeasurementAxis() const override { return false; } - virtual bool IsIsolated() const { return false; } + bool IsIsolated() const override { return false; } ////////////////////////////////////////////////////////////////////////// // END CBaseObject @@ -232,7 +233,7 @@ protected: ////////////////////////////////////////////////////////////////////////// //! Must be called after cloning the object on clone of object. //! This will make sure object references are cloned correctly. - virtual void PostClone(CBaseObject* pFromObject, CObjectCloneContext& ctx); + void PostClone(CBaseObject* pFromObject, CObjectCloneContext& ctx) override; //! Draw default object items. void DrawProjectorPyramid(DisplayContext& dc, float dist); @@ -264,7 +265,7 @@ public: } protected: - void DeleteThis() { delete this; }; + void DeleteThis() override { delete this; }; ////////////////////////////////////////////////////////////////////////// // Radius callbacks. diff --git a/Code/Editor/Objects/GizmoManager.h b/Code/Editor/Objects/GizmoManager.h index c3a71ad81b..efc3e99205 100644 --- a/Code/Editor/Objects/GizmoManager.h +++ b/Code/Editor/Objects/GizmoManager.h @@ -23,14 +23,14 @@ class CGizmoManager : public IGizmoManager { public: - void AddGizmo(CGizmo* gizmo); - void RemoveGizmo(CGizmo* gizmo); + void AddGizmo(CGizmo* gizmo) override; + void RemoveGizmo(CGizmo* gizmo) override; int GetGizmoCount() const override; CGizmo* GetGizmoByIndex(int nIndex) const override; - void Display(DisplayContext& dc); - bool HitTest(HitContext& hc); + void Display(DisplayContext& dc) override; + bool HitTest(HitContext& hc) override; void DeleteAllTransformManipulators(); diff --git a/Code/Editor/Objects/LineGizmo.h b/Code/Editor/Objects/LineGizmo.h index af3b38b199..e50f044f3c 100644 --- a/Code/Editor/Objects/LineGizmo.h +++ b/Code/Editor/Objects/LineGizmo.h @@ -30,10 +30,10 @@ public: ////////////////////////////////////////////////////////////////////////// // Ovverides from CGizmo ////////////////////////////////////////////////////////////////////////// - virtual void SetName(const char* sName); - virtual void GetWorldBounds(AABB& bbox); - virtual void Display(DisplayContext& dc); - virtual bool HitTest(HitContext& hc); + void SetName(const char* sName) override; + void GetWorldBounds(AABB& bbox) override; + void Display(DisplayContext& dc) override; + bool HitTest(HitContext& hc) override; ////////////////////////////////////////////////////////////////////////// void SetObjects(CBaseObject* pObject1, CBaseObject* pObject2, const QString& boneName = ""); diff --git a/Code/Editor/Objects/ObjectManager.cpp b/Code/Editor/Objects/ObjectManager.cpp index e053d10fd1..06aa8866b3 100644 --- a/Code/Editor/Objects/ObjectManager.cpp +++ b/Code/Editor/Objects/ObjectManager.cpp @@ -52,6 +52,7 @@ public: GUID guid; public: + virtual ~CXMLObjectClassDesc() = default; REFGUID ClassID() override { return guid; diff --git a/Code/Editor/Objects/ObjectManager.h b/Code/Editor/Objects/ObjectManager.h index de0a4ce849..4ffa5e9a07 100644 --- a/Code/Editor/Objects/ObjectManager.h +++ b/Code/Editor/Objects/ObjectManager.h @@ -103,142 +103,142 @@ public: void RegisterObjectClasses(); - CBaseObject* NewObject(CObjectClassDesc* cls, CBaseObject* prev = 0, const QString& file = "", const char* newObjectName = nullptr); - CBaseObject* NewObject(const QString& typeName, CBaseObject* prev = 0, const QString& file = "", const char* newEntityName = nullptr); + CBaseObject* NewObject(CObjectClassDesc* cls, CBaseObject* prev = 0, const QString& file = "", const char* newObjectName = nullptr) override; + CBaseObject* NewObject(const QString& typeName, CBaseObject* prev = 0, const QString& file = "", const char* newEntityName = nullptr) override; - void DeleteObject(CBaseObject* obj); - void DeleteSelection(CSelectionGroup* pSelection); - void DeleteAllObjects(); - CBaseObject* CloneObject(CBaseObject* obj); + void DeleteObject(CBaseObject* obj) override; + void DeleteSelection(CSelectionGroup* pSelection) override; + void DeleteAllObjects() override; + CBaseObject* CloneObject(CBaseObject* obj) override; - void BeginEditParams(CBaseObject* obj, int flags); - void EndEditParams(int flags = 0); + void BeginEditParams(CBaseObject* obj, int flags) override; + void EndEditParams(int flags = 0) override; // Hides all transform manipulators. void HideTransformManipulators(); //! Get number of objects manager by ObjectManager (not contain sub objects of groups). - int GetObjectCount() const; + int GetObjectCount() const override; //! Get array of objects, managed by manager (not contain sub objects of groups). //! @param layer if 0 get objects for all layers, or layer to get objects from. - void GetObjects(CBaseObjectsArray& objects) const; + void GetObjects(CBaseObjectsArray& objects) const override; //! Get array of objects that pass the filter. //! @param filter The filter functor, return true if you want to get the certain obj, return false if want to skip it. - void GetObjects(CBaseObjectsArray& objects, BaseObjectFilterFunctor const& filter) const; + void GetObjects(CBaseObjectsArray& objects, BaseObjectFilterFunctor const& filter) const override; //! Update objects. void Update(); //! Display objects on display context. - void Display(DisplayContext& dc); + void Display(DisplayContext& dc) override; //! Called when selecting without selection helpers - this is needed since //! the visible object cache is normally not updated when not displaying helpers. - void ForceUpdateVisibleObjectCache(DisplayContext& dc); + void ForceUpdateVisibleObjectCache(DisplayContext& dc) override; //! Check intersection with objects. //! Find intersection with nearest to ray origin object hit by ray. //! If distance tollerance is specified certain relaxation applied on collision test. //! @return true if hit any object, and fills hitInfo structure. - bool HitTest(HitContext& hitInfo); + bool HitTest(HitContext& hitInfo) override; //! Check intersection with an object. //! @return true if hit, and fills hitInfo structure. - bool HitTestObject(CBaseObject* obj, HitContext& hc); + bool HitTestObject(CBaseObject* obj, HitContext& hc) override; //! Send event to all objects. //! Will cause OnEvent handler to be called on all objects. - void SendEvent(ObjectEvent event); + void SendEvent(ObjectEvent event) override; //! Send event to all objects within given bounding box. //! Will cause OnEvent handler to be called on objects within bounding box. - void SendEvent(ObjectEvent event, const AABB& bounds); + void SendEvent(ObjectEvent event, const AABB& bounds) override; ////////////////////////////////////////////////////////////////////////// //! Find object by ID. - CBaseObject* FindObject(REFGUID guid) const; + CBaseObject* FindObject(REFGUID guid) const override; ////////////////////////////////////////////////////////////////////////// //! Find object by name. - CBaseObject* FindObject(const QString& sName) const; + CBaseObject* FindObject(const QString& sName) const override; ////////////////////////////////////////////////////////////////////////// //! Find objects of given type. void FindObjectsOfType(const QMetaObject* pClass, std::vector& result) override; void FindObjectsOfType(ObjectType type, std::vector& result) override; ////////////////////////////////////////////////////////////////////////// //! Find objects which intersect with a given AABB. - virtual void FindObjectsInAABB(const AABB& aabb, std::vector& result) const; + void FindObjectsInAABB(const AABB& aabb, std::vector& result) const override; ////////////////////////////////////////////////////////////////////////// // Operations on objects. ////////////////////////////////////////////////////////////////////////// //! Makes object visible or invisible. - void HideObject(CBaseObject* obj, bool hide); + void HideObject(CBaseObject* obj, bool hide) override; //! Shows the last hidden object based on hidden ID - void ShowLastHiddenObject(); + void ShowLastHiddenObject() override; //! Freeze object, making it unselectable. - void FreezeObject(CBaseObject* obj, bool freeze); + void FreezeObject(CBaseObject* obj, bool freeze) override; //! Unhide all hidden objects. - void UnhideAll(); + void UnhideAll() override; //! Unfreeze all frozen objects. - void UnfreezeAll(); + void UnfreezeAll() override; ////////////////////////////////////////////////////////////////////////// // Object Selection. ////////////////////////////////////////////////////////////////////////// - bool SelectObject(CBaseObject* obj, bool bUseMask = true); - void UnselectObject(CBaseObject* obj); + bool SelectObject(CBaseObject* obj, bool bUseMask = true) override; + void UnselectObject(CBaseObject* obj) override; //! Select objects within specified distance from given position. //! Return number of selected objects. - int SelectObjects(const AABB& box, bool bUnselect = false); + int SelectObjects(const AABB& box, bool bUnselect = false) override; - virtual void SelectEntities(std::set& s); + void SelectEntities(std::set& s) override; - int MoveObjects(const AABB& box, const Vec3& offset, ImageRotationDegrees rotation, bool bIsCopy = false); + int MoveObjects(const AABB& box, const Vec3& offset, ImageRotationDegrees rotation, bool bIsCopy = false) override; //! Selects/Unselects all objects within 2d rectangle in given viewport. - void SelectObjectsInRect(CViewport* view, const QRect& rect, bool bSelect); - void FindObjectsInRect(CViewport* view, const QRect& rect, std::vector& guids); + void SelectObjectsInRect(CViewport* view, const QRect& rect, bool bSelect) override; + void FindObjectsInRect(CViewport* view, const QRect& rect, std::vector& guids) override; //! Clear default selection set. //! @Return number of objects removed from selection. - int ClearSelection(); + int ClearSelection() override; //! Deselect all current selected objects and selects object that were unselected. //! @Return number of selected objects. - int InvertSelection(); + int InvertSelection() override; //! Get current selection. - CSelectionGroup* GetSelection() const { return m_currSelection; }; + CSelectionGroup* GetSelection() const override { return m_currSelection; }; //! Get named selection. - CSelectionGroup* GetSelection(const QString& name) const; + CSelectionGroup* GetSelection(const QString& name) const override; // Get selection group names - void GetNameSelectionStrings(QStringList& names); + void GetNameSelectionStrings(QStringList& names) override; //! Change name of current selection group. //! And store it in list. - void NameSelection(const QString& name); + void NameSelection(const QString& name) override; //! Set one of name selections as current selection. - void SetSelection(const QString& name); - void RemoveSelection(const QString& name); + void SetSelection(const QString& name) override; + void RemoveSelection(const QString& name) override; bool IsObjectDeletionAllowed(CBaseObject* pObject); //! Delete all objects in selection group. - void DeleteSelection(); + void DeleteSelection() override; - uint32 ForceID() const{return m_ForceID; } - void ForceID(uint32 FID){m_ForceID = FID; } + uint32 ForceID() const override{return m_ForceID; } + void ForceID(uint32 FID) override{m_ForceID = FID; } //! Generates uniq name base on type name of object. - QString GenerateUniqueObjectName(const QString& typeName); + QString GenerateUniqueObjectName(const QString& typeName) override; //! Register object name in object manager, needed for generating uniq names. - void RegisterObjectName(const QString& name); + void RegisterObjectName(const QString& name) override; //! Decrease name number and remove if it was last in object manager, needed for generating uniq names. void UpdateRegisterObjectName(const QString& name); //! Enable/Disable generating of unique object names (Enabled by default). //! Return previous value. - bool EnableUniqObjectNames(bool bEnable); + bool EnableUniqObjectNames(bool bEnable) override; //! Register XML template of runtime class. void RegisterClassTemplate(const XmlNodeRef& templ); @@ -249,25 +249,25 @@ public: void RegisterCVars(); //! Find object class by name. - CObjectClassDesc* FindClass(const QString& className); - void GetClassCategories(QStringList& categories); + CObjectClassDesc* FindClass(const QString& className) override; + void GetClassCategories(QStringList& categories) override; void GetClassCategoryToolClassNamePairs(std::vector< std::pair >& categoryToolClassNamePairs) override; - void GetClassTypes(const QString& category, QStringList& types); + void GetClassTypes(const QString& category, QStringList& types) override; //! Export objects to xml. //! When onlyShared is true ony objects with shared flags exported, overwise only not shared object exported. - void Export(const QString& levelPath, XmlNodeRef& rootNode, bool onlyShared); - void ExportEntities(XmlNodeRef& rootNode); + void Export(const QString& levelPath, XmlNodeRef& rootNode, bool onlyShared) override; + void ExportEntities(XmlNodeRef& rootNode) override; //! Serialize Objects in manager to specified XML Node. //! @param flags Can be one of SerializeFlags. - void Serialize(XmlNodeRef& rootNode, bool bLoading, int flags = SERIALIZE_ALL); + void Serialize(XmlNodeRef& rootNode, bool bLoading, int flags = SERIALIZE_ALL) override; - void SerializeNameSelection(XmlNodeRef& rootNode, bool bLoading); + void SerializeNameSelection(XmlNodeRef& rootNode, bool bLoading) override; //! Load objects from object archive. //! @param bSelect if set newly loaded object will be selected. - void LoadObjects(CObjectArchive& ar, bool bSelect); + void LoadObjects(CObjectArchive& ar, bool bSelect) override; //! Delete from Object manager all objects without SHARED flag. void DeleteNotSharedObjects(); @@ -276,57 +276,57 @@ public: bool AddObject(CBaseObject* obj); void RemoveObject(CBaseObject* obj); - void ChangeObjectId(REFGUID oldId, REFGUID newId); - bool IsDuplicateObjectName(const QString& newName) const + void ChangeObjectId(REFGUID oldId, REFGUID newId) override; + bool IsDuplicateObjectName(const QString& newName) const override { return FindObject(newName) ? true : false; } - void ShowDuplicationMsgWarning(CBaseObject* obj, const QString& newName, bool bShowMsgBox) const; - void ChangeObjectName(CBaseObject* obj, const QString& newName); + void ShowDuplicationMsgWarning(CBaseObject* obj, const QString& newName, bool bShowMsgBox) const override; + void ChangeObjectName(CBaseObject* obj, const QString& newName) override; //! Convert object of one type to object of another type. //! Original object is deleted. - bool ConvertToType(CBaseObject* pObject, const QString& typeName); + bool ConvertToType(CBaseObject* pObject, const QString& typeName) override; //! Set new selection callback. //! @return previous selection callback. - IObjectSelectCallback* SetSelectCallback(IObjectSelectCallback* callback); + IObjectSelectCallback* SetSelectCallback(IObjectSelectCallback* callback) override; // Enables/Disables creating of game objects. - void SetCreateGameObject(bool enable) { m_createGameObjects = enable; }; + void SetCreateGameObject(bool enable) override { m_createGameObjects = enable; }; //! Return true if objects loaded from xml should immidiatly create game objects associated with them. - bool IsCreateGameObjects() const { return m_createGameObjects; }; + bool IsCreateGameObjects() const override { return m_createGameObjects; }; ////////////////////////////////////////////////////////////////////////// //! Get access to gizmo manager. - IGizmoManager* GetGizmoManager(); + IGizmoManager* GetGizmoManager() override; ////////////////////////////////////////////////////////////////////////// //! Invalidate visibily settings of objects. - void InvalidateVisibleList(); + void InvalidateVisibleList() override; ////////////////////////////////////////////////////////////////////////// // ObjectManager notification Callbacks. ////////////////////////////////////////////////////////////////////////// - void AddObjectEventListener(EventListener* listener); - void RemoveObjectEventListener(EventListener* listener); + void AddObjectEventListener(EventListener* listener) override; + void RemoveObjectEventListener(EventListener* listener) override; ////////////////////////////////////////////////////////////////////////// // Used to indicate starting and ending of objects loading. ////////////////////////////////////////////////////////////////////////// - void StartObjectsLoading(int numObjects); - void EndObjectsLoading(); + void StartObjectsLoading(int numObjects) override; + void EndObjectsLoading() override; ////////////////////////////////////////////////////////////////////////// // Gathers all resources used by all objects. - void GatherUsedResources(CUsedResources& resources); + void GatherUsedResources(CUsedResources& resources) override; - virtual bool IsLightClass(CBaseObject* pObject); + bool IsLightClass(CBaseObject* pObject) override; - virtual void FindAndRenameProperty2(const char* property2Name, const QString& oldValue, const QString& newValue); - virtual void FindAndRenameProperty2If(const char* property2Name, const QString& oldValue, const QString& newValue, const char* otherProperty2Name, const QString& otherValue); + virtual void FindAndRenameProperty2(const char* property2Name, const QString& oldValue, const QString& newValue) override; + virtual void FindAndRenameProperty2If(const char* property2Name, const QString& oldValue, const QString& newValue, const char* otherProperty2Name, const QString& otherValue) override; - bool IsReloading() const { return m_bInReloading; } + bool IsReloading() const override { return m_bInReloading; } void SetSkipUpdate(bool bSkipUpdate) override { m_bSkipObjectUpdate = bSkipUpdate; } void SetExportingLevel(bool bExporting) override { m_bLevelExporting = bExporting; } @@ -341,7 +341,7 @@ private: @param objectNode Xml node to serialize object info from. @param pUndoObject Pointer to deleted object for undo. */ - CBaseObject* NewObject(CObjectArchive& archive, CBaseObject* pUndoObject, bool bMakeNewId); + CBaseObject* NewObject(CObjectArchive& archive, CBaseObject* pUndoObject, bool bMakeNewId) override; //! Update visibility of all objects. void UpdateVisibilityList(); diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h b/Code/Editor/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h index 23151eb05c..bb19f4d77e 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h @@ -86,7 +86,7 @@ public: // Always returns false as Component entity highlighting (accenting) is taken care of elsewhere bool IsHighlighted() { return false; } // Component entity highlighting (accenting) is taken care of elsewhere - void DrawHighlight(DisplayContext& /*dc*/) {}; + void DrawHighlight(DisplayContext& /*dc*/) override {}; // Don't auto-clone children. Cloning happens in groups with reference fixups, // and individually selected objercts should be cloned as individuals. @@ -164,7 +164,7 @@ protected: float GetRadius(); - void DeleteThis() { delete this; }; + void DeleteThis() override { delete this; }; bool IsNonLayerAncestorSelected() const; bool IsLayer() const; diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h index f2764681b2..617c5cb2c8 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.h @@ -182,7 +182,7 @@ private: ////////////////////////////////////////////////////////////////////////// // AzToolsFramework::EditorContextMenu::Bus::Handler overrides void PopulateEditorGlobalContextMenu(QMenu* menu, const AZ::Vector2& point, int flags) override; - int GetMenuPosition() const; + int GetMenuPosition() const override; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/FavoriteComponentList.h b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/FavoriteComponentList.h index 5f704237ab..2bd2d83e04 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/FavoriteComponentList.h +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/FavoriteComponentList.h @@ -102,7 +102,7 @@ protected: void AddFavorites(const AZStd::vector& classDataContainer) override; ////////////////////////////////////////////////////////////////////////// - void rowsInserted(const QModelIndex& parent, int start, int end); + void rowsInserted(const QModelIndex& parent, int start, int end) override; // Context menu handlers void ShowContextMenu(const QPoint&); diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerListModel.hxx b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerListModel.hxx index 346a5e938a..8acb2f1a72 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerListModel.hxx +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/Outliner/OutlinerListModel.hxx @@ -255,7 +255,7 @@ protected: bool DropMimeDataAssets(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent); bool CanDropMimeDataAssets(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) const; - QMap itemData(const QModelIndex &index) const; + QMap itemData(const QModelIndex &index) const override; QVariant dataForAll(const QModelIndex& index, int role) const; QVariant dataForName(const QModelIndex& index, int role) const; QVariant dataForVisibility(const QModelIndex& index, int role) const; diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp index 10c43c3d1b..dd9ccaa832 100644 --- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp +++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp @@ -6,6 +6,7 @@ * */ +#include #include "CryFile.h" #include "PerforceSourceControl.h" #include "PasswordDlg.h" diff --git a/Code/Editor/PreferencesStdPages.h b/Code/Editor/PreferencesStdPages.h index f4a6e0b783..8a182bde55 100644 --- a/Code/Editor/PreferencesStdPages.h +++ b/Code/Editor/PreferencesStdPages.h @@ -28,16 +28,16 @@ public: ////////////////////////////////////////////////////////////////////////// // IUnkown implementation. - virtual HRESULT STDMETHODCALLTYPE QueryInterface(const IID& riid, void** ppvObj); - virtual ULONG STDMETHODCALLTYPE AddRef(); - virtual ULONG STDMETHODCALLTYPE Release(); + HRESULT STDMETHODCALLTYPE QueryInterface(const IID& riid, void** ppvObj) override; + ULONG STDMETHODCALLTYPE AddRef() override; + ULONG STDMETHODCALLTYPE Release() override; ////////////////////////////////////////////////////////////////////////// - virtual REFGUID ClassID(); + REFGUID ClassID() override; ////////////////////////////////////////////////////////////////////////// - virtual int GetPagesCount(); - virtual IPreferencesPage* CreateEditorPreferencesPage(int index) override; + int GetPagesCount() override; + IPreferencesPage* CreateEditorPreferencesPage(int index) override; }; #endif // CRYINCLUDE_EDITOR_PREFERENCESSTDPAGES_H diff --git a/Code/Editor/PythonEditorEventsBus.h b/Code/Editor/PythonEditorEventsBus.h index 5107a1c9cc..ffc357e64d 100644 --- a/Code/Editor/PythonEditorEventsBus.h +++ b/Code/Editor/PythonEditorEventsBus.h @@ -8,6 +8,7 @@ */ #pragma once +#include #include namespace AzToolsFramework @@ -138,7 +139,7 @@ namespace AzToolsFramework /* * Finds a pak file name for a given file. */ - virtual const char* GetPakFromFile(const char* filename) = 0; + virtual AZ::IO::Path GetPakFromFile(const char* filename) = 0; /* * Prints the message to the editor console window. diff --git a/Code/Editor/PythonEditorFuncs.cpp b/Code/Editor/PythonEditorFuncs.cpp index 200fd28f87..455cdfa17d 100644 --- a/Code/Editor/PythonEditorFuncs.cpp +++ b/Code/Editor/PythonEditorFuncs.cpp @@ -625,7 +625,7 @@ namespace } ////////////////////////////////////////////////////////////////////////// - const char* PyGetPakFromFile(const char* filename) + AZ::IO::Path PyGetPakFromFile(const char* filename) { auto pIPak = GetIEditor()->GetSystem()->GetIPak(); AZ::IO::HandleType fileHandle = pIPak->FOpen(filename, "rb"); @@ -633,8 +633,9 @@ namespace { throw std::logic_error("Invalid file name."); } - const char* pArchPath = pIPak->GetFileArchivePath(fileHandle); + AZ::IO::Path pArchPath = pIPak->GetFileArchivePath(fileHandle); pIPak->FClose(fileHandle); + return pArchPath; } @@ -1040,7 +1041,7 @@ namespace AzToolsFramework return PySetAxisConstraint(pConstrain); } - const char* PythonEditorComponent::GetPakFromFile(const char* filename) + AZ::IO::Path PythonEditorComponent::GetPakFromFile(const char* filename) { return PyGetPakFromFile(filename); } @@ -1114,7 +1115,7 @@ namespace AzToolsFramework addLegacyGeneral(behaviorContext->Method("get_axis_constraint", PyGetAxisConstraint, nullptr, "Gets axis.")); addLegacyGeneral(behaviorContext->Method("set_axis_constraint", PySetAxisConstraint, nullptr, "Sets axis.")); - addLegacyGeneral(behaviorContext->Method("get_pak_from_file", PyGetPakFromFile, nullptr, "Finds a pak file name for a given file.")); + addLegacyGeneral(behaviorContext->Method("get_pak_from_file", [](const char* filename) -> AZStd::string { return PyGetPakFromFile(filename).Native(); }, nullptr, "Finds a pak file name for a given file.")); addLegacyGeneral(behaviorContext->Method("log", PyLog, nullptr, "Prints the message to the editor console window.")); diff --git a/Code/Editor/PythonEditorFuncs.h b/Code/Editor/PythonEditorFuncs.h index 97ad8829ba..ef0c1327fa 100644 --- a/Code/Editor/PythonEditorFuncs.h +++ b/Code/Editor/PythonEditorFuncs.h @@ -91,7 +91,7 @@ namespace AzToolsFramework void SetAxisConstraint(AZStd::string_view pConstrain) override; - const char* GetPakFromFile(const char* filename) override; + AZ::IO::Path GetPakFromFile(const char* filename) override; void Log(const char* pMessage) override; diff --git a/Code/Editor/QtViewPane.h b/Code/Editor/QtViewPane.h index 09fc215833..194dd8919a 100644 --- a/Code/Editor/QtViewPane.h +++ b/Code/Editor/QtViewPane.h @@ -123,18 +123,18 @@ public: { } - virtual ESystemClassID SystemClassID() { return m_classId; }; + ESystemClassID SystemClassID() override { return m_classId; }; static const GUID& GetClassID() { return TWidget::GetClassID(); } - virtual const GUID& ClassID() + const GUID& ClassID() override { return GetClassID(); } - virtual QString ClassName() { return m_name; }; - virtual QString Category() { return m_category; }; + QString ClassName() override { return m_name; }; + QString Category() override { return m_category; }; QObject* CreateQObject() const override { return new TWidget(); }; QString GetPaneTitle() override { return m_name; }; diff --git a/Code/Editor/SelectSequenceDialog.h b/Code/Editor/SelectSequenceDialog.h index 5531949c1a..960da7ebe3 100644 --- a/Code/Editor/SelectSequenceDialog.h +++ b/Code/Editor/SelectSequenceDialog.h @@ -30,7 +30,7 @@ protected: void OnInitDialog() override; // Derived Dialogs should override this - virtual void GetItems(std::vector& outItems); + void GetItems(std::vector& outItems) override; }; #endif // CRYINCLUDE_EDITOR_SELECTSEQUENCEDIALOG_H diff --git a/Code/Editor/Settings.cpp b/Code/Editor/Settings.cpp index 80d248e1bf..05a6960695 100644 --- a/Code/Editor/Settings.cpp +++ b/Code/Editor/Settings.cpp @@ -171,7 +171,6 @@ SEditorSettings::SEditorSettings() bBackupOnSave = true; backupOnSaveMaxCount = 3; bApplyConfigSpecInEditor = true; - useLowercasePaths = 0; showErrorDialogOnLoad = 1; consoleBackgroundColorTheme = AzToolsFramework::ConsoleColorTheme::Dark; @@ -887,6 +886,7 @@ void SEditorSettings::Load() ////////////////////////////////////////////////////////////////////////// AZ_CVAR(bool, ed_previewGameInFullscreen_once, false, nullptr, AZ::ConsoleFunctorFlags::IsInvisible, "Preview the game (Ctrl+G, \"Play Game\", etc.) in fullscreen once"); +AZ_CVAR(bool, ed_lowercasepaths, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Convert CCryFile paths to lowercase on Open"); void SEditorSettings::PostInitApply() { @@ -898,7 +898,6 @@ void SEditorSettings::PostInitApply() // Create CVars. REGISTER_CVAR2("ed_highlightGeometry", &viewports.bHighlightMouseOverGeometry, viewports.bHighlightMouseOverGeometry, 0, "Highlight geometry when mouse over it"); REGISTER_CVAR2("ed_showFrozenHelpers", &viewports.nShowFrozenHelpers, viewports.nShowFrozenHelpers, 0, "Show helpers of frozen objects"); - REGISTER_CVAR2("ed_lowercasepaths", &useLowercasePaths, useLowercasePaths, 0, "generate paths in lowercase"); gEnv->pConsole->RegisterInt("fe_fbx_savetempfile", 0, 0, "When importing an FBX file into Facial Editor, this will save out a conversion FSQ to the Animations/temp folder for trouble shooting"); REGISTER_CVAR2_CB("ed_toolbarIconSize", &gui.nToolbarIconSize, gui.nToolbarIconSize, VF_NULL, "Override size of the toolbar icons 0-default, 16,32,...", ToolbarIconSizeChanged); diff --git a/Code/Editor/Settings.h b/Code/Editor/Settings.h index a408822129..8bf22b43e5 100644 --- a/Code/Editor/Settings.h +++ b/Code/Editor/Settings.h @@ -340,8 +340,6 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING //! how many save backups to keep int backupOnSaveMaxCount; - int useLowercasePaths; - ////////////////////////////////////////////////////////////////////////// // Autobackup. ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/StartupLogoDialog.cpp b/Code/Editor/StartupLogoDialog.cpp index d9625aff1a..ab251b1564 100644 --- a/Code/Editor/StartupLogoDialog.cpp +++ b/Code/Editor/StartupLogoDialog.cpp @@ -9,11 +9,11 @@ // Description : implementation file - #include "EditorDefs.h" - #include "StartupLogoDialog.h" +#include + // Qt #include #include @@ -22,8 +22,6 @@ AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - ///////////////////////////////////////////////////////////////////////////// // CStartupLogoDialog dialog @@ -36,13 +34,16 @@ CStartupLogoDialog::CStartupLogoDialog(QString versionText, QString richTextCopy m_ui->setupUi(this); s_pLogoWindow = this; - - m_backgroundImage = QPixmap(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")); setFixedSize(QSize(600, 300)); // Prepare background image - QImage backgroundImage(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")); - m_backgroundImage = QPixmap::fromImage(backgroundImage.scaled(m_enforcedWidth, m_enforcedHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + m_backgroundImage = AzQtComponents::ScalePixmapForScreenDpi( + QPixmap(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")), + screen(), + QSize(m_enforcedWidth, m_enforcedHeight), + Qt::IgnoreAspectRatio, + Qt::SmoothTransformation + ); // Draw the Open 3D Engine logo from svg m_ui->m_logo->load(QStringLiteral(":/StartupLogoDialog/o3de_logo.svg")); diff --git a/Code/Editor/Style/Editor.qss b/Code/Editor/Style/Editor.qss index 302b7703a5..5eb280260e 100644 --- a/Code/Editor/Style/Editor.qss +++ b/Code/Editor/Style/Editor.qss @@ -191,94 +191,4 @@ ConsoleTextEdit:focus, border-width: 0px; border-color: #e9e9e9; border-style: solid; -} - -/* Welcome Screen styling */ - -WelcomeScreenDialog QLabel -{ - font-size: 12px; - color: #FFFFFF; - line-height: 20px; - background-color: transparent; - margin: 0; -} - -WelcomeScreenDialog QLabel#currentProjectLabel -{ - margin-top: 10px; -} - -WelcomeScreenDialog QPushButton -{ - font-size: 14px; - line-height: 16px; -} - -WelcomeScreenDialog QWidget#articleViewContainerRoot -{ - background: #444444; -} - -WelcomeScreenDialog QWidget#levelViewFTUEContainer -{ - background: #282828; -} - -QTableWidget#recentLevelTable::item { - background-color: rgb(64,64,64); - margin-bottom: 4px; - margin-top: 4px; -} - -/* Particle Editor */ - -#NumParticlesLabel -{ - margin-top: 6px; -} - -#LibrarySearchIcon -{ - max-width: 16px; - max-height: 16px; - qproperty-iconSize: 16px 16px; -} - - -#ClosePrefabDialog, #SavePrefabDialog -{ - min-width : 640px; -} - -#SaveDependentPrefabsCard -{ - margin: 0px 15px 10px 15px; -} - -#PrefabSavedMessageFrame{ - border: 1px solid green; - margin: 10px 15px 10px 15px; - border-radius: 2px; - padding: 5px 2px 5px 2px; -} - -#ClosePrefabDialog #PrefabSaveWarningFrame -{ - border: 1px solid orange; - margin: 10px 15px 10px 15px; - border-radius: 2px; - padding: 5px 2px 5px 2px; - color : white; -} - -#SavePrefabDialog #FooterSeparatorLine -{ - color: gray; -} - -#SavePrefabDialog #PrefabSavePreferenceHint -{ - font: italic; - color: #999999; } \ No newline at end of file diff --git a/Code/Editor/ToolbarCustomizationDialog.h b/Code/Editor/ToolbarCustomizationDialog.h index 7063c2b792..0e64bfbb5b 100644 --- a/Code/Editor/ToolbarCustomizationDialog.h +++ b/Code/Editor/ToolbarCustomizationDialog.h @@ -39,7 +39,7 @@ public: protected: void dragMoveEvent(QDragMoveEvent* ev) override; void dragEnterEvent(QDragEnterEvent* ev) override; - void dropEvent(QDropEvent* ev); + void dropEvent(QDropEvent* ev) override; private: void OnTabChanged(int index); diff --git a/Code/Editor/TopRendererWnd.h b/Code/Editor/TopRendererWnd.h index 3a5c1026bc..c5bc7a31f2 100644 --- a/Code/Editor/TopRendererWnd.h +++ b/Code/Editor/TopRendererWnd.h @@ -35,11 +35,11 @@ public: /** Get type of this viewport. */ - virtual EViewportType GetType() const { return ET_ViewportMap; } - virtual void SetType(EViewportType type); + EViewportType GetType() const override { return ET_ViewportMap; } + void SetType(EViewportType type) override; - virtual void ResetContent(); - virtual void UpdateContent(int flags); + void ResetContent() override; + void UpdateContent(int flags) override; //! Map viewport position to world space position. virtual Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; @@ -52,7 +52,7 @@ public: protected: // Draw everything. - virtual void Draw(DisplayContext& dc); + void Draw(DisplayContext& dc) override; private: bool m_bContentsUpdated; diff --git a/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp b/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp index b510315995..6b3f1c2633 100644 --- a/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp +++ b/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp @@ -36,6 +36,9 @@ #include "CryEdit.h" #include "Viewport.h" +// Atom Renderer +#include + AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING @@ -1234,6 +1237,13 @@ void CSequenceBatchRenderDialog::OnKickIdleTimout() { componentApplication->TickSystem(); } + + // Directly tick the renderer, as it's no longer part of the system tick + if (auto rpiSystem = AZ::RPI::RPISystemInterface::Get()) + { + rpiSystem->SimulationTick(); + rpiSystem->RenderTick(); + } } } diff --git a/Code/Editor/TrackView/SequenceBatchRenderDialog.h b/Code/Editor/TrackView/SequenceBatchRenderDialog.h index 5d8934f783..9be10c22af 100644 --- a/Code/Editor/TrackView/SequenceBatchRenderDialog.h +++ b/Code/Editor/TrackView/SequenceBatchRenderDialog.h @@ -187,7 +187,7 @@ protected: int m_customFPS; void InitializeContext(); - virtual void OnMovieEvent(IMovieListener::EMovieEvent event, IAnimSequence* pSequence); + void OnMovieEvent(IMovieListener::EMovieEvent event, IAnimSequence* pSequence) override; void CaptureItemStart(); diff --git a/Code/Editor/TrackView/TrackViewCurveEditor.h b/Code/Editor/TrackView/TrackViewCurveEditor.h index b2e019899b..1af55a9e0c 100644 --- a/Code/Editor/TrackView/TrackViewCurveEditor.h +++ b/Code/Editor/TrackView/TrackViewCurveEditor.h @@ -50,8 +50,8 @@ public: void SetPlayCallback(const std::function& callback); // IAnimationContextListener - virtual void OnSequenceChanged(CTrackViewSequence* pNewSequence); - virtual void OnTimeChanged(float newTime); + void OnSequenceChanged(CTrackViewSequence* pNewSequence) override; + void OnTimeChanged(float newTime) override; protected: void showEvent(QShowEvent* event) override; @@ -65,7 +65,7 @@ private: void OnSplineTimeMarkerChange(); // IEditorNotifyListener - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event) override; + void OnEditorNotifyEvent(EEditorNotifyEvent event) override; //ITrackViewSequenceListener void OnKeysChanged(CTrackViewSequence* pSequence) override; @@ -109,8 +109,8 @@ public: float GetFPS() const { return m_widget->GetFPS(); } void SetTickDisplayMode(ETVTickMode mode) { m_widget->SetTickDisplayMode(mode); } - virtual void OnSequenceChanged(CTrackViewSequence* pNewSequence) { m_widget->OnSequenceChanged(pNewSequence); } - virtual void OnTimeChanged(float newTime) { m_widget->OnTimeChanged(newTime); } + void OnSequenceChanged(CTrackViewSequence* pNewSequence) override { m_widget->OnSequenceChanged(pNewSequence); } + void OnTimeChanged(float newTime) override { m_widget->OnTimeChanged(newTime); } // ITrackViewSequenceListener delegation to m_widget void OnKeysChanged(CTrackViewSequence* pSequence) override { m_widget->OnKeysChanged(pSequence); } diff --git a/Code/Editor/TrackView/TrackViewDialog.h b/Code/Editor/TrackView/TrackViewDialog.h index f6c1126713..c66f31e1f7 100644 --- a/Code/Editor/TrackView/TrackViewDialog.h +++ b/Code/Editor/TrackView/TrackViewDialog.h @@ -69,10 +69,10 @@ public: void UpdateSequenceLockStatus(); // IAnimationContextListener - virtual void OnSequenceChanged(CTrackViewSequence* pNewSequence) override; + void OnSequenceChanged(CTrackViewSequence* pNewSequence) override; // ITrackViewSequenceListener - virtual void OnSequenceSettingsChanged(CTrackViewSequence* pSequence) override; + void OnSequenceSettingsChanged(CTrackViewSequence* pSequence) override; void UpdateDopeSheetTime(CTrackViewSequence* pSequence); @@ -197,8 +197,8 @@ private: bool processRawInput(MSG* pMsg); #endif - virtual void OnNodeSelectionChanged(CTrackViewSequence* pSequence) override; - virtual void OnNodeRenamed(CTrackViewNode* pNode, const char* pOldName) override; + void OnNodeSelectionChanged(CTrackViewSequence* pSequence) override; + void OnNodeRenamed(CTrackViewNode* pNode, const char* pOldName) override; void OnSequenceAdded(CTrackViewSequence* pSequence) override; void OnSequenceRemoved(CTrackViewSequence* pSequence) override; @@ -209,8 +209,8 @@ private: void AddDialogListeners(); void RemoveDialogListeners(); - virtual void BeginUndoTransaction(); - virtual void EndUndoTransaction(); + void BeginUndoTransaction() override; + void EndUndoTransaction() override; void SaveCurrentSequenceToFBX(); void SaveSequenceTimingToXML(); diff --git a/Code/Editor/TrackView/TrackViewNode.h b/Code/Editor/TrackView/TrackViewNode.h index 59df06750b..80ca7b9d49 100644 --- a/Code/Editor/TrackView/TrackViewNode.h +++ b/Code/Editor/TrackView/TrackViewNode.h @@ -117,13 +117,14 @@ class CTrackViewKeyBundle public: CTrackViewKeyBundle() : m_bAllOfSameType(true) {} + virtual ~CTrackViewKeyBundle() = default; - virtual bool AreAllKeysOfSameType() const override { return m_bAllOfSameType; } + bool AreAllKeysOfSameType() const override { return m_bAllOfSameType; } - virtual unsigned int GetKeyCount() const override { return static_cast(m_keys.size()); } - virtual CTrackViewKeyHandle GetKey(unsigned int index) override { return m_keys[index]; } + unsigned int GetKeyCount() const override { return static_cast(m_keys.size()); } + CTrackViewKeyHandle GetKey(unsigned int index) override { return m_keys[index]; } - virtual void SelectKeys(const bool bSelected) override; + void SelectKeys(const bool bSelected) override; CTrackViewKeyHandle GetSingleSelectedKey(); diff --git a/Code/Editor/TrackView/TrackViewSequence.h b/Code/Editor/TrackView/TrackViewSequence.h index 69858adf8f..a392ad00f9 100644 --- a/Code/Editor/TrackView/TrackViewSequence.h +++ b/Code/Editor/TrackView/TrackViewSequence.h @@ -100,16 +100,16 @@ public: void Load() override; // ITrackViewNode - virtual ETrackViewNodeType GetNodeType() const override { return eTVNT_Sequence; } + ETrackViewNodeType GetNodeType() const override { return eTVNT_Sequence; } - virtual AZStd::string GetName() const override { return m_pAnimSequence->GetName(); } - virtual bool SetName(const char* pName) override; - virtual bool CanBeRenamed() const override { return true; } + AZStd::string GetName() const override { return m_pAnimSequence->GetName(); } + bool SetName(const char* pName) override; + bool CanBeRenamed() const override { return true; } // Binding/Unbinding - virtual void BindToEditorObjects() override; - virtual void UnBindFromEditorObjects() override; - virtual bool IsBoundToEditorObjects() const override; + void BindToEditorObjects() override; + void UnBindFromEditorObjects() override; + bool IsBoundToEditorObjects() const override; // Time range void SetTimeRange(Range timeRange); @@ -136,10 +136,10 @@ public: uint32 GetCryMovieId() const { return m_pAnimSequence->GetId(); } // Rendering - virtual void Render(const SAnimContext& animContext) override; + void Render(const SAnimContext& animContext) override; // Playback control - virtual void Animate(const SAnimContext& animContext) override; + void Animate(const SAnimContext& animContext) override; void Resume() { m_pAnimSequence->Resume(); } void Pause() { m_pAnimSequence->Pause(); } void StillUpdate() { m_pAnimSequence->StillUpdate(); } @@ -162,7 +162,7 @@ public: void TimeChanged(float newTime) { m_pAnimSequence->TimeChanged(newTime); } // Check if it's a group node - virtual bool IsGroupNode() const override { return true; } + bool IsGroupNode() const override { return true; } // Track Events (TODO: Undo?) int GetTrackEventsCount() const { return m_pAnimSequence->GetTrackEventsCount(); } @@ -195,7 +195,7 @@ public: bool IsActiveSequence() const; // The root sequence node is always an active director - virtual bool IsActiveDirector() const override { return true; } + bool IsActiveDirector() const override { return true; } // Copy keys to clipboard (in XML form) void CopyKeysToClipboard(const bool bOnlySelectedKeys, const bool bOnlyFromSelectedTracks); @@ -306,15 +306,15 @@ private: // Called when an animation updates needs to be schedules void ForceAnimation(); - virtual void CopyKeysToClipboard(XmlNodeRef& xmlNode, const bool bOnlySelectedKeys, const bool bOnlyFromSelectedTracks) override; + void CopyKeysToClipboard(XmlNodeRef& xmlNode, const bool bOnlySelectedKeys, const bool bOnlyFromSelectedTracks) override; std::deque GetMatchingTracks(CTrackViewAnimNode* pAnimNode, XmlNodeRef trackNode); void GetMatchedPasteLocationsRec(std::vector& locations, CTrackViewNode* pCurrentNode, XmlNodeRef clipboardNode); - virtual void BeginUndoTransaction(); - virtual void EndUndoTransaction(); - virtual void BeginRestoreTransaction(); - virtual void EndRestoreTransaction(); + void BeginUndoTransaction() override; + void EndUndoTransaction() override; + void BeginRestoreTransaction() override; + void EndRestoreTransaction() override; // For record mode on AZ::Entities - connect (or disconnect) to buses for notification of property changes void ConnectToBusesForRecording(const AZ::EntityId& entityIdForBus, bool enableConnection); diff --git a/Code/Editor/TrackView/TrackViewSequenceManager.h b/Code/Editor/TrackView/TrackViewSequenceManager.h index 21c10f009a..1474323dc6 100644 --- a/Code/Editor/TrackView/TrackViewSequenceManager.h +++ b/Code/Editor/TrackView/TrackViewSequenceManager.h @@ -27,7 +27,7 @@ public: CTrackViewSequenceManager(); ~CTrackViewSequenceManager(); - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); + void OnEditorNotifyEvent(EEditorNotifyEvent event) override; unsigned int GetCount() const { return static_cast(m_sequences.size()); } @@ -65,7 +65,7 @@ private: void OnSequenceAdded(CTrackViewSequence* pSequence); void OnSequenceRemoved(CTrackViewSequence* pSequence); - virtual void OnDataBaseItemEvent(IDataBaseItem* pItem, EDataBaseItemEvent event); + void OnDataBaseItemEvent(IDataBaseItem* pItem, EDataBaseItemEvent event) override; // AZ::EntitySystemBus void OnEntityNameChanged(const AZ::EntityId& entityId, const AZStd::string& name) override; diff --git a/Code/Editor/TrackView/TrackViewSplineCtrl.h b/Code/Editor/TrackView/TrackViewSplineCtrl.h index 2f4c790627..7cf12fb750 100644 --- a/Code/Editor/TrackView/TrackViewSplineCtrl.h +++ b/Code/Editor/TrackView/TrackViewSplineCtrl.h @@ -28,7 +28,7 @@ public: CTrackViewSplineCtrl(QWidget* parent); virtual ~CTrackViewSplineCtrl(); - virtual void ClearSelection(); + void ClearSelection() override; void AddSpline(ISplineInterpolator* pSpline, CTrackViewTrack* pTrack, const QColor& color); void AddSpline(ISplineInterpolator * pSpline, CTrackViewTrack * pTrack, QColor anColorArray[4]); @@ -53,12 +53,12 @@ protected: void wheelEvent(QWheelEvent* event) override; private: - virtual void SelectKey(ISplineInterpolator* pSpline, int nKey, int nDimension, bool bSelect) override; - virtual void SelectRectangle(const QRect& rc, bool bSelect) override; + void SelectKey(ISplineInterpolator* pSpline, int nKey, int nDimension, bool bSelect) override; + void SelectRectangle(const QRect& rc, bool bSelect) override; std::vector m_tracks; - virtual bool GetTangentHandlePts(QPoint& inTangentPt, QPoint& pt, QPoint& outTangentPt, + bool GetTangentHandlePts(QPoint& inTangentPt, QPoint& pt, QPoint& outTangentPt, int nSpline, int nKey, int nDimension) override; void ComputeIncomingTangentAndEaseTo(float& ds, float& easeTo, QPoint inTangentPt, int nSpline, int nKey, int nDimension); @@ -67,7 +67,7 @@ private: void AdjustTCB(float d_tension, float d_continuity, float d_bias); void MoveSelectedTangentHandleTo(const QPoint& point); - virtual ISplineCtrlUndo* CreateSplineCtrlUndoObject(std::vector& splineContainer); + ISplineCtrlUndo* CreateSplineCtrlUndoObject(std::vector& splineContainer) override; bool m_bKeysFreeze; bool m_bTangentsFreeze; diff --git a/Code/Editor/Util/ColumnGroupTreeView.h b/Code/Editor/Util/ColumnGroupTreeView.h index 3c7dea91c3..eda5f8e9c9 100644 --- a/Code/Editor/Util/ColumnGroupTreeView.h +++ b/Code/Editor/Util/ColumnGroupTreeView.h @@ -44,7 +44,7 @@ public slots: QVector Groups() const; protected: - void paintEvent(QPaintEvent* event) + void paintEvent(QPaintEvent* event) override { if (model() && model()->rowCount() > 0) { diff --git a/Code/Editor/Util/FileUtil.cpp b/Code/Editor/Util/FileUtil.cpp index 610a9c6e16..eeb6912acf 100644 --- a/Code/Editor/Util/FileUtil.cpp +++ b/Code/Editor/Util/FileUtil.cpp @@ -149,12 +149,13 @@ bool CFileUtil::ExtractFile(QString& file, bool bMsgBoxAskForExtraction, const c // Check if in pack. if (cryfile.IsInPak()) { - const char* sPakName = cryfile.GetPakPath(); - if (bMsgBoxAskForExtraction) { + AZ::IO::FixedMaxPath sPakName{ cryfile.GetPakPath() }; // Cannot edit file in pack, suggest to extract it for editing. - if (QMessageBox::critical(QApplication::activeWindow(), QString(), QObject::tr("File %1 is inside a PAK file %2\r\nDo you want it to be extracted for editing ?").arg(file, sPakName), QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) + if (QMessageBox::critical(QApplication::activeWindow(), QString(), + QObject::tr("File %1 is inside a PAK file %2\r\nDo you want it to be extracted for editing ?").arg(file, sPakName.c_str()), + QMessageBox::Yes | QMessageBox::No) == QMessageBox::No) { return false; } @@ -173,10 +174,9 @@ bool CFileUtil::ExtractFile(QString& file, bool bMsgBoxAskForExtraction, const c if (diskFile.open(QFile::WriteOnly)) { // Copy data from packed file to disk file. - char* data = new char[cryfile.GetLength()]; - cryfile.ReadRaw(data, cryfile.GetLength()); - diskFile.write(data, cryfile.GetLength()); - delete []data; + auto data = AZStd::make_unique(cryfile.GetLength()); + cryfile.ReadRaw(data.get(), cryfile.GetLength()); + diskFile.write(data.get(), cryfile.GetLength()); } else { @@ -185,7 +185,14 @@ bool CFileUtil::ExtractFile(QString& file, bool bMsgBoxAskForExtraction, const c } else { - file = cryfile.GetAdjustedFilename(); + + if (auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); fileIoBase != nullptr) + { + if (AZ::IO::FixedMaxPath resolvedFilePath; fileIoBase->ResolvePath(resolvedFilePath, cryfile.GetFilename())) + { + file = QString::fromUtf8(resolvedFilePath.c_str(), static_cast(resolvedFilePath.Native().size())); + } + } } return true; @@ -2157,13 +2164,13 @@ uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*= return SCC_FILE_ATTRIBUTE_READONLY | SCC_FILE_ATTRIBUTE_INPAK; } - const char* adjustedFile = file.GetAdjustedFilename(); - if (!AZ::IO::SystemFile::Exists(adjustedFile)) + auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); + if (!fileIoBase->Exists(file.GetFilename())) { return SCC_FILE_ATTRIBUTE_INVALID; } - if (!AZ::IO::SystemFile::IsWritable(adjustedFile)) + if (fileIoBase->IsReadOnly(file.GetFilename())) { return SCC_FILE_ATTRIBUTE_NORMAL | SCC_FILE_ATTRIBUTE_READONLY; } diff --git a/Code/Editor/Util/PakFile.cpp b/Code/Editor/Util/PakFile.cpp index fc8431ef24..b629b45f74 100644 --- a/Code/Editor/Util/PakFile.cpp +++ b/Code/Editor/Util/PakFile.cpp @@ -68,7 +68,7 @@ bool CPakFile::Open(const char* filename, bool bAbsolutePath) if (bAbsolutePath) { - m_pArchive = pCryPak->OpenArchive(filename, nullptr, AZ::IO::INestedArchive::FLAGS_ABSOLUTE_PATHS); + m_pArchive = pCryPak->OpenArchive(filename, {}, AZ::IO::INestedArchive::FLAGS_ABSOLUTE_PATHS); } else { @@ -93,7 +93,7 @@ bool CPakFile::OpenForRead(const char* filename) { return false; } - m_pArchive = pCryPak->OpenArchive(filename, nullptr, AZ::IO::INestedArchive::FLAGS_OPTIMIZED_READ_ONLY | AZ::IO::INestedArchive::FLAGS_ABSOLUTE_PATHS); + m_pArchive = pCryPak->OpenArchive(filename, {}, AZ::IO::INestedArchive::FLAGS_OPTIMIZED_READ_ONLY | AZ::IO::INestedArchive::FLAGS_ABSOLUTE_PATHS); if (m_pArchive) { return true; diff --git a/Code/Editor/Util/Variable.h b/Code/Editor/Util/Variable.h index 9c3f96a3f6..639161775c 100644 --- a/Code/Editor/Util/Variable.h +++ b/Code/Editor/Util/Variable.h @@ -379,11 +379,11 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING public: virtual ~CVariableBase() {} - void SetName(const QString& name) { m_name = name; }; + void SetName(const QString& name) override { m_name = name; }; //! Get name of parameter. - QString GetName() const { return m_name; }; + QString GetName() const override { return m_name; }; - QString GetHumanName() const + QString GetHumanName() const override { if (!m_humanName.isEmpty()) { @@ -391,82 +391,82 @@ public: } return m_name; } - void SetHumanName(const QString& name) { m_humanName = name; } + void SetHumanName(const QString& name) override { m_humanName = name; } - void SetDescription(const char* desc) { m_description = desc; }; - void SetDescription(const QString& desc) { m_description = desc; }; + void SetDescription(const char* desc) override { m_description = desc; }; + void SetDescription(const QString& desc) override { m_description = desc; }; //! Get name of parameter. - QString GetDescription() const { return m_description; }; + QString GetDescription() const override { return m_description; }; - EType GetType() const { return IVariable::UNKNOWN; }; - int GetSize() const { return sizeof(*this); }; + EType GetType() const override { return IVariable::UNKNOWN; }; + int GetSize() const override { return sizeof(*this); }; - unsigned char GetDataType() const { return m_dataType; }; - void SetDataType(unsigned char dataType) { m_dataType = dataType; } + unsigned char GetDataType() const override { return m_dataType; }; + void SetDataType(unsigned char dataType) override { m_dataType = dataType; } - void SetFlags(int flags) { m_flags = static_cast(flags); } - int GetFlags() const { return m_flags; } - void SetFlagRecursive(EFlags flag) { m_flags |= flag; } + void SetFlags(int flags) override { m_flags = static_cast(flags); } + int GetFlags() const override { return m_flags; } + void SetFlagRecursive(EFlags flag) override { m_flags |= flag; } - void SetUserData(const QVariant &data){ m_userData = data; }; - QVariant GetUserData() const { return m_userData; } + void SetUserData(const QVariant &data) override { m_userData = data; }; + QVariant GetUserData() const override { return m_userData; } ////////////////////////////////////////////////////////////////////////// // Set methods. ////////////////////////////////////////////////////////////////////////// - void Set([[maybe_unused]] int value) { assert(0); } - void Set([[maybe_unused]] bool value) { assert(0); } - void Set([[maybe_unused]] float value) { assert(0); } - void Set([[maybe_unused]] double value) { assert(0); } - void Set([[maybe_unused]] const Vec2& value) { assert(0); } - void Set([[maybe_unused]] const Vec3& value) { assert(0); } - void Set([[maybe_unused]] const Vec4& value) { assert(0); } - void Set([[maybe_unused]] const Ang3& value) { assert(0); } - void Set([[maybe_unused]] const Quat& value) { assert(0); } - void Set([[maybe_unused]] const QString& value) { assert(0); } - void Set([[maybe_unused]] const char* value) { assert(0); } - void SetDisplayValue(const QString& value) { Set(value); } + void Set([[maybe_unused]] int value) override { assert(0); } + void Set([[maybe_unused]] bool value) override { assert(0); } + void Set([[maybe_unused]] float value) override { assert(0); } + void Set([[maybe_unused]] double value) override { assert(0); } + void Set([[maybe_unused]] const Vec2& value) override { assert(0); } + void Set([[maybe_unused]] const Vec3& value) override { assert(0); } + void Set([[maybe_unused]] const Vec4& value) override { assert(0); } + void Set([[maybe_unused]] const Ang3& value) override { assert(0); } + void Set([[maybe_unused]] const Quat& value) override { assert(0); } + void Set([[maybe_unused]] const QString& value) override { assert(0); } + void Set([[maybe_unused]] const char* value) override { assert(0); } + void SetDisplayValue(const QString& value) override { Set(value); } ////////////////////////////////////////////////////////////////////////// // Get methods. ////////////////////////////////////////////////////////////////////////// - void Get([[maybe_unused]] int& value) const { assert(0); } - void Get([[maybe_unused]] bool& value) const { assert(0); } - void Get([[maybe_unused]] float& value) const { assert(0); } - void Get([[maybe_unused]] double& value) const { assert(0); } - void Get([[maybe_unused]] Vec2& value) const { assert(0); } - void Get([[maybe_unused]] Vec3& value) const { assert(0); } - void Get([[maybe_unused]] Vec4& value) const { assert(0); } - void Get([[maybe_unused]] Ang3& value) const { assert(0); } - void Get([[maybe_unused]] Quat& value) const { assert(0); } - void Get([[maybe_unused]] QString& value) const { assert(0); } - QString GetDisplayValue() const { QString val; Get(val); return val; } + void Get([[maybe_unused]] int& value) const override { assert(0); } + void Get([[maybe_unused]] bool& value) const override { assert(0); } + void Get([[maybe_unused]] float& value) const override { assert(0); } + void Get([[maybe_unused]] double& value) const override { assert(0); } + void Get([[maybe_unused]] Vec2& value) const override { assert(0); } + void Get([[maybe_unused]] Vec3& value) const override { assert(0); } + void Get([[maybe_unused]] Vec4& value) const override { assert(0); } + void Get([[maybe_unused]] Ang3& value) const override { assert(0); } + void Get([[maybe_unused]] Quat& value) const override { assert(0); } + void Get([[maybe_unused]] QString& value) const override { assert(0); } + QString GetDisplayValue() const override { QString val; Get(val); return val; } ////////////////////////////////////////////////////////////////////////// // IVariableContainer functions ////////////////////////////////////////////////////////////////////////// - virtual void AddVariable([[maybe_unused]] IVariable* var) { assert(0); } + void AddVariable([[maybe_unused]] IVariable* var) override { assert(0); } - virtual bool DeleteVariable([[maybe_unused]] IVariable* var, [[maybe_unused]] bool recursive = false) { return false; } - virtual void DeleteAllVariables() {} + bool DeleteVariable([[maybe_unused]] IVariable* var, [[maybe_unused]] bool recursive = false) override { return false; } + void DeleteAllVariables() override {} - virtual int GetNumVariables() const { return 0; } - virtual IVariable* GetVariable([[maybe_unused]] int index) const { return nullptr; } + int GetNumVariables() const override { return 0; } + IVariable* GetVariable([[maybe_unused]] int index) const override { return nullptr; } - virtual bool IsContainsVariable([[maybe_unused]] IVariable* pVar, [[maybe_unused]] bool bRecursive = false) const { return false; } + bool IsContainsVariable([[maybe_unused]] IVariable* pVar, [[maybe_unused]] bool bRecursive = false) const override { return false; } - virtual IVariable* FindVariable([[maybe_unused]] const char* name, [[maybe_unused]] bool bRecursive = false, [[maybe_unused]] bool bHumanName = false) const { return nullptr; } + IVariable* FindVariable([[maybe_unused]] const char* name, [[maybe_unused]] bool bRecursive = false, [[maybe_unused]] bool bHumanName = false) const override { return nullptr; } - virtual bool IsEmpty() const { return true; } + bool IsEmpty() const override { return true; } ////////////////////////////////////////////////////////////////////////// - void Wire(IVariable* var) + void Wire(IVariable* var) override { m_wiredVars.push_back(var); } ////////////////////////////////////////////////////////////////////////// - void Unwire(IVariable* var) + void Unwire(IVariable* var) override { if (!var) { @@ -480,7 +480,7 @@ public: } ////////////////////////////////////////////////////////////////////////// - void AddOnSetCallback(OnSetCallback* func) + void AddOnSetCallback(OnSetCallback* func) override { if (!stl::find(m_onSetFuncs, func)) { @@ -489,13 +489,13 @@ public: } ////////////////////////////////////////////////////////////////////////// - void RemoveOnSetCallback(OnSetCallback* func) + void RemoveOnSetCallback(OnSetCallback* func) override { stl::find_and_erase(m_onSetFuncs, func); } ////////////////////////////////////////////////////////////////////////// - void ClearOnSetCallbacks() + void ClearOnSetCallbacks() override { m_onSetFuncs.clear(); } @@ -509,7 +509,7 @@ public: } ////////////////////////////////////////////////////////////////////////// - void RemoveOnSetEnumCallback(OnSetCallback* func) + void RemoveOnSetEnumCallback(OnSetCallback* func) override { stl::find_and_erase(m_onSetEnumFuncs, func); } @@ -520,7 +520,7 @@ public: } - virtual void OnSetValue([[maybe_unused]] bool bRecursive) + void OnSetValue([[maybe_unused]] bool bRecursive) override { // If have wired variables or OnSet callback, process them. // Send value to wired variable. @@ -549,7 +549,8 @@ public: } ////////////////////////////////////////////////////////////////////////// - void Serialize(XmlNodeRef node, bool load) + using IVariable::Serialize; + void Serialize(XmlNodeRef node, bool load) override { if (load) { @@ -567,8 +568,8 @@ public: } } - virtual void EnableUpdateCallbacks(bool boEnable){m_boUpdateCallbacksEnabled = boEnable; }; - virtual void SetForceModified(bool bForceModified) { m_bForceModified = bForceModified; } + void EnableUpdateCallbacks(bool boEnable) override{m_boUpdateCallbacksEnabled = boEnable; }; + void SetForceModified(bool bForceModified) override { m_bForceModified = bForceModified; } protected: // Constructor. CVariableBase() @@ -641,13 +642,13 @@ public: CVariableArray(){} //! Get name of parameter. - virtual EType GetType() const { return IVariable::ARRAY; }; - virtual int GetSize() const { return sizeof(CVariableArray); }; + EType GetType() const override { return IVariable::ARRAY; }; + int GetSize() const override { return sizeof(CVariableArray); }; ////////////////////////////////////////////////////////////////////////// // Set methods. ////////////////////////////////////////////////////////////////////////// - virtual void Set(const QString& value) + void Set(const QString& value) override { if (m_strValue != value) { @@ -655,7 +656,7 @@ public: OnSetValue(false); } } - void OnSetValue(bool bRecursive) + void OnSetValue(bool bRecursive) override { CVariableBase::OnSetValue(bRecursive); if (bRecursive) @@ -666,7 +667,7 @@ public: } } } - void SetFlagRecursive(EFlags flag) + void SetFlagRecursive(EFlags flag) override { CVariableBase::SetFlagRecursive(flag); for (Variables::iterator it = m_vars.begin(); it != m_vars.end(); ++it) @@ -677,9 +678,9 @@ public: ////////////////////////////////////////////////////////////////////////// // Get methods. ////////////////////////////////////////////////////////////////////////// - virtual void Get(QString& value) const { value = m_strValue; } + void Get(QString& value) const override { value = m_strValue; } - virtual bool HasDefaultValue() const + bool HasDefaultValue() const override { for (Variables::const_iterator it = m_vars.begin(); it != m_vars.end(); ++it) { @@ -691,7 +692,7 @@ public: return true; } - virtual void ResetToDefault() + void ResetToDefault() override { for (Variables::const_iterator it = m_vars.begin(); it != m_vars.end(); ++it) { @@ -700,7 +701,7 @@ public: } ////////////////////////////////////////////////////////////////////////// - IVariable* Clone(bool bRecursive) const + IVariable* Clone(bool bRecursive) const override { CVariableArray* var = new CVariableArray(*this); @@ -713,7 +714,7 @@ public: } ////////////////////////////////////////////////////////////////////////// - void CopyValue(IVariable* fromVar) + void CopyValue(IVariable* fromVar) override { assert(fromVar); if (fromVar->GetType() != IVariable::ARRAY) @@ -733,20 +734,20 @@ public: } ////////////////////////////////////////////////////////////////////////// - virtual int GetNumVariables() const { return static_cast(m_vars.size()); } + int GetNumVariables() const override { return static_cast(m_vars.size()); } - virtual IVariable* GetVariable(int index) const + IVariable* GetVariable(int index) const override { assert(index >= 0 && index < (int)m_vars.size()); return m_vars[index]; } - virtual void AddVariable(IVariable* var) + void AddVariable(IVariable* var) override { m_vars.push_back(var); } - virtual bool DeleteVariable(IVariable* var, bool recursive /*=false*/) + bool DeleteVariable(IVariable* var, bool recursive /*=false*/) override { bool found = stl::find_and_erase(m_vars, var); if (!found && recursive) @@ -762,12 +763,12 @@ public: return found; } - virtual void DeleteAllVariables() + void DeleteAllVariables() override { m_vars.clear(); } - virtual bool IsContainsVariable(IVariable* pVar, bool bRecursive) const + bool IsContainsVariable(IVariable* pVar, bool bRecursive) const override { for (Variables::const_iterator it = m_vars.begin(); it != m_vars.end(); ++it) { @@ -793,14 +794,15 @@ public: return false; } - virtual IVariable* FindVariable(const char* name, bool bRecursive, bool bHumanName) const; + IVariable* FindVariable(const char* name, bool bRecursive, bool bHumanName) const override; - virtual bool IsEmpty() const + bool IsEmpty() const override { return m_vars.empty(); } - void Serialize(XmlNodeRef node, bool load) + using IVariable::Serialize; + void Serialize(XmlNodeRef node, bool load) override { if (load) { @@ -1074,11 +1076,11 @@ class CVariableVoid { public: CVariableVoid(){}; - virtual EType GetType() const { return IVariable::UNKNOWN; }; - virtual IVariable* Clone([[maybe_unused]] bool bRecursive) const { return new CVariableVoid(*this); } - virtual void CopyValue([[maybe_unused]] IVariable* fromVar) {}; - virtual bool HasDefaultValue() const { return true; } - virtual void ResetToDefault() {}; + EType GetType() const override { return IVariable::UNKNOWN; }; + IVariable* Clone([[maybe_unused]] bool bRecursive) const override { return new CVariableVoid(*this); } + void CopyValue([[maybe_unused]] IVariable* fromVar) override {}; + bool HasDefaultValue() const override { return true; } + void ResetToDefault() override {}; protected: CVariableVoid(const CVariableVoid& v) : CVariableBase(v) {}; @@ -1112,44 +1114,44 @@ public: } //! Get name of parameter. - virtual EType GetType() const { return (EType)var_type::type_traits::type(); }; - virtual int GetSize() const { return sizeof(T); }; + EType GetType() const override { return (EType)var_type::type_traits::type(); }; + int GetSize() const override { return sizeof(T); }; ////////////////////////////////////////////////////////////////////////// // Set methods. ////////////////////////////////////////////////////////////////////////// - virtual void Set(int value) { SetValue(value); } - virtual void Set(bool value) { SetValue(value); } - virtual void Set(float value) { SetValue(value); } - virtual void Set(double value) { SetValue(value); } - virtual void Set(const Vec2& value) { SetValue(value); } - virtual void Set(const Vec3& value) { SetValue(value); } - virtual void Set(const Vec4& value) { SetValue(value); } - virtual void Set(const Ang3& value) { SetValue(value); } - virtual void Set(const Quat& value) { SetValue(value); } - virtual void Set(const QString& value) { SetValue(value); } - virtual void Set(const char* value) { SetValue(QString(value)); } + void Set(int value) override { SetValue(value); } + void Set(bool value) override { SetValue(value); } + void Set(float value) override { SetValue(value); } + void Set(double value) override { SetValue(value); } + void Set(const Vec2& value) override { SetValue(value); } + void Set(const Vec3& value) override { SetValue(value); } + void Set(const Vec4& value) override { SetValue(value); } + void Set(const Ang3& value) override { SetValue(value); } + void Set(const Quat& value) override { SetValue(value); } + void Set(const QString& value) override { SetValue(value); } + void Set(const char* value) override { SetValue(QString(value)); } ////////////////////////////////////////////////////////////////////////// // Get methods. ////////////////////////////////////////////////////////////////////////// - virtual void Get(int& value) const { GetValue(value); } - virtual void Get(bool& value) const { GetValue(value); } - virtual void Get(float& value) const { GetValue(value); } - virtual void Get(double& value) const { GetValue(value); } - virtual void Get(Vec2& value) const { GetValue(value); } - virtual void Get(Vec3& value) const { GetValue(value); } - virtual void Get(Vec4& value) const { GetValue(value); } - virtual void Get(Quat& value) const { GetValue(value); } - virtual void Get(QString& value) const { GetValue(value); } - virtual bool HasDefaultValue() const + void Get(int& value) const override { GetValue(value); } + void Get(bool& value) const override { GetValue(value); } + void Get(float& value) const override { GetValue(value); } + void Get(double& value) const override { GetValue(value); } + void Get(Vec2& value) const override { GetValue(value); } + void Get(Vec3& value) const override { GetValue(value); } + void Get(Vec4& value) const override { GetValue(value); } + void Get(Quat& value) const override { GetValue(value); } + void Get(QString& value) const override { GetValue(value); } + bool HasDefaultValue() const override { T defval; var_type::init(defval); return m_valueDef == defval; } - virtual void ResetToDefault() + void ResetToDefault() override { T defval; var_type::init(defval); @@ -1159,7 +1161,7 @@ public: ////////////////////////////////////////////////////////////////////////// // Limits. ////////////////////////////////////////////////////////////////////////// - virtual void SetLimits(float fMin, float fMax, float fStep = 0.f, bool bHardMin = true, bool bHardMax = true) + void SetLimits(float fMin, float fMax, float fStep = 0.f, bool bHardMin = true, bool bHardMax = true) override { m_valueMin = fMin; m_valueMax = fMax; @@ -1171,7 +1173,7 @@ public: m_customLimits = true; } - virtual void GetLimits(float& fMin, float& fMax, float& fStep, bool& bHardMin, bool& bHardMax) + void GetLimits(float& fMin, float& fMax, float& fStep, bool& bHardMin, bool& bHardMax) override { if (!m_customLimits && var_type::type_traits::supports_range()) { @@ -1199,7 +1201,7 @@ public: m_customLimits = false; } - virtual bool HasCustomLimits() + bool HasCustomLimits() override { return m_customLimits; } @@ -1217,14 +1219,14 @@ public: void operator=(const T& value) { SetValue(value); } ////////////////////////////////////////////////////////////////////////// - IVariable* Clone([[maybe_unused]] bool bRecursive) const + IVariable* Clone([[maybe_unused]] bool bRecursive) const override { Self* var = new Self(*this); return var; } ////////////////////////////////////////////////////////////////////////// - void CopyValue(IVariable* fromVar) + void CopyValue(IVariable* fromVar) override { assert(fromVar); T val; @@ -1668,7 +1670,7 @@ struct CSmartVariableBase return *pV; } // Cast to CVariableBase& VarType& operator*() const { return *pVar; } - VarType* operator->(void) const { return pVar; } + VarType* operator->() const { return pVar; } VarType* GetVar() const { return pVar; }; @@ -1730,7 +1732,7 @@ struct CSmartVariableArray } VarType& operator*() const { return *pVar; } - VarType* operator->(void) const { return pVar; } + VarType* operator->() const { return pVar; } VarType* GetVar() const { return pVar; }; @@ -1752,35 +1754,35 @@ public: // Dtor. virtual ~CVarBlock() {} //! Add variable to block. - virtual void AddVariable(IVariable* var); + void AddVariable(IVariable* var) override; //! Remove variable from block - virtual bool DeleteVariable(IVariable* var, bool bRecursive = false); + bool DeleteVariable(IVariable* var, bool bRecursive = false) override; void AddVariable(IVariable* pVar, const char* varName, unsigned char dataType = IVariable::DT_SIMPLE); // This used from smart variable pointer. void AddVariable(CVariableBase& var, const char* varName, unsigned char dataType = IVariable::DT_SIMPLE); //! Returns number of variables in block. - virtual int GetNumVariables() const { return static_cast(m_vars.size()); } + int GetNumVariables() const override { return static_cast(m_vars.size()); } //! Get pointer to stored variable by index. - virtual IVariable* GetVariable(int index) const + IVariable* GetVariable(int index) const override { assert(index >= 0 && index < m_vars.size()); return m_vars[index]; } // Clear all vars from VarBlock. - virtual void DeleteAllVariables() { m_vars.clear(); }; + void DeleteAllVariables() override { m_vars.clear(); }; //! Return true if variable block is empty (Does not have any vars). - virtual bool IsEmpty() const { return m_vars.empty(); } + bool IsEmpty() const override { return m_vars.empty(); } // Returns true if var block contains specified variable. - virtual bool IsContainsVariable(IVariable* pVar, bool bRecursive = true) const; + bool IsContainsVariable(IVariable* pVar, bool bRecursive = true) const override; //! Find variable by name. - virtual IVariable* FindVariable(const char* name, bool bRecursive = true, bool bHumanName = false) const; + IVariable* FindVariable(const char* name, bool bRecursive = true, bool bHumanName = false) const override; ////////////////////////////////////////////////////////////////////////// //! Clone var block. diff --git a/Code/Editor/Util/XmlArchive.cpp b/Code/Editor/Util/XmlArchive.cpp index e6bc93fdf4..18c3fc8e63 100644 --- a/Code/Editor/Util/XmlArchive.cpp +++ b/Code/Editor/Util/XmlArchive.cpp @@ -124,7 +124,7 @@ bool CXmlArchive::SaveToPak([[maybe_unused]] const QString& levelPath, CPakFile& if (pakFile.GetArchive()) { - CLogFile::FormatLine("Saving pak file %s", (const char*)pakFile.GetArchive()->GetFullPath()); + CLogFile::FormatLine("Saving pak file %.*s", AZ_STRING_ARG(pakFile.GetArchive()->GetFullPath().Native())); } pNamedData->Save(pakFile); diff --git a/Code/Editor/Viewport.cpp b/Code/Editor/Viewport.cpp index 9c6088e340..2d41538d92 100644 --- a/Code/Editor/Viewport.cpp +++ b/Code/Editor/Viewport.cpp @@ -43,12 +43,7 @@ void QtViewport::BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt) { context.m_hitLocation = AZ::Vector3::CreateZero(); - - PreWidgetRendering(); // required so that the current render cam is set. - context.m_hitLocation = GetHitLocation(pt); - - PostWidgetRendering(); } @@ -1352,28 +1347,6 @@ bool QtViewport::MouseCallback(EMouseEvent event, const QPoint& point, Qt::Keybo return true; } - // RAII wrapper for Pre / PostWidgetRendering calls. - // It also tracks the times a mouse callback potentially created a new viewport context. - struct ScopedProcessingMouseCallback - { - explicit ScopedProcessingMouseCallback(QtViewport* viewport) - : m_viewport(viewport) - { - m_viewport->m_processingMouseCallbacksCounter++; - m_viewport->PreWidgetRendering(); - } - - ~ScopedProcessingMouseCallback() - { - m_viewport->PostWidgetRendering(); - m_viewport->m_processingMouseCallbacksCounter--; - } - - QtViewport* m_viewport; - }; - - ScopedProcessingMouseCallback scopedProcessingMouseCallback(this); - ////////////////////////////////////////////////////////////////////////// // Hit test gizmo objects. ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Viewport.h b/Code/Editor/Viewport.h index 6b5bfb5c34..60c1306420 100644 --- a/Code/Editor/Viewport.h +++ b/Code/Editor/Viewport.h @@ -172,7 +172,7 @@ public: //! Get current view matrix. //! This is a matrix that transforms from world space to view space. - virtual const Matrix34& GetViewTM() const + const Matrix34& GetViewTM() const override { AZ_Error("CryLegacy", false, "QtViewport::GetViewTM not implemented"); static const Matrix34 m; @@ -182,7 +182,7 @@ public: ////////////////////////////////////////////////////////////////////////// //! Get current screen matrix. //! Screen matrix transform from World space to Screen space. - virtual const Matrix34& GetScreenTM() const + const Matrix34& GetScreenTM() const override { return m_screenTM; } @@ -190,9 +190,9 @@ public: virtual Vec3 MapViewToCP(const QPoint& point) = 0; //! Map viewport position to world space position. - virtual Vec3 ViewToWorld(const QPoint& vp, bool* pCollideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const = 0; + Vec3 ViewToWorld(const QPoint& vp, bool* pCollideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override = 0; //! Convert point on screen to world ray. - virtual void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const = 0; + void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const override = 0; //! Get normal for viewport position virtual Vec3 ViewToWorldNormal(const QPoint& vp, bool onlyTerrain, bool bTestRenderMesh = false) = 0; @@ -261,7 +261,7 @@ public: virtual void SetCursorString(const QString& str) = 0; virtual void SetFocus() = 0; - virtual void Invalidate(bool bErase = 1) = 0; + virtual void Invalidate(bool bErase = true) = 0; // Is overridden by RenderViewport virtual void SetFOV([[maybe_unused]] float fov) {} @@ -274,13 +274,7 @@ public: void SetViewPane(CLayoutViewPane* viewPane) { m_viewPane = viewPane; } - //Child classes can override these to provide extra logic that wraps - //widget rendering. Needed by the RenderViewport to handle raycasts - //from screen-space to world-space. - virtual void PreWidgetRendering() {} - virtual void PostWidgetRendering() {} - - virtual CViewport *asCViewport() { return this; } + CViewport *asCViewport() override { return this; } protected: CLayoutViewPane* m_viewPane = nullptr; @@ -289,7 +283,7 @@ protected: // Screen Matrix Matrix34 m_screenTM; int m_nCurViewportID; - // Final game view matrix before drpping back to editor + // Final game view matrix before dropping back to editor Matrix34 m_gameTM; AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING @@ -342,7 +336,7 @@ public: void SetActiveWindow() override { activateWindow(); } //! Called while window is idle. - virtual void Update(); + void Update() override; /** Set name of this viewport. */ @@ -350,24 +344,24 @@ public: /** Get name of viewport */ - QString GetName() const; + QString GetName() const override; - virtual void SetFocus() { setFocus(); } - virtual void Invalidate([[maybe_unused]] bool bErase = 1) { update(); } + void SetFocus() override { setFocus(); } + void Invalidate([[maybe_unused]] bool bErase = 1) override { update(); } // Is overridden by RenderViewport - virtual void SetFOV([[maybe_unused]] float fov) {} - virtual float GetFOV() const; + void SetFOV([[maybe_unused]] float fov) override {} + float GetFOV() const override; // Must be overridden in derived classes. // Returns: // e.g. 4.0/3.0 - virtual float GetAspectRatio() const = 0; - virtual void GetDimensions(int* pWidth, int* pHeight) const; - virtual void ScreenToClient(QPoint& pPoint) const override; + float GetAspectRatio() const override = 0; + void GetDimensions(int* pWidth, int* pHeight) const override; + void ScreenToClient(QPoint& pPoint) const override; - virtual void ResetContent(); - virtual void UpdateContent(int flags); + void ResetContent() override; + void UpdateContent(int flags) override; //! Set current zoom factor for this viewport. virtual void SetZoomFactor(float fZoomFactor); @@ -379,10 +373,10 @@ public: virtual void OnDeactivate(); //! Map world space position to viewport position. - virtual QPoint WorldToView(const Vec3& wp) const override; + QPoint WorldToView(const Vec3& wp) const override; //! Map world space position to 3D viewport position. - virtual Vec3 WorldToView3D(const Vec3& wp, int nFlags = 0) const; + Vec3 WorldToView3D(const Vec3& wp, int nFlags = 0) const override; //! Map viewport position to world space position. virtual Vec3 ViewToWorld(const QPoint& vp, bool* pCollideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; @@ -397,17 +391,18 @@ public: //! This method return a vector (p2-p1) in world space alligned to construction plane and restriction axises. //! p1 and p2 must be given in world space and lie on construction plane. - virtual Vec3 GetCPVector(const Vec3& p1, const Vec3& p2, int axis); + using CViewport::GetCPVector; + Vec3 GetCPVector(const Vec3& p1, const Vec3& p2, int axis) override; //! Snap any given 3D world position to grid lines if snap is enabled. Vec3 SnapToGrid(const Vec3& vec) override; - virtual float GetGridStep() const; + float GetGridStep() const override; //! Returns the screen scale factor for a point given in world coordinates. //! This factor gives the width in world-space units at the point's distance of the viewport. - virtual float GetScreenScaleFactor([[maybe_unused]] const Vec3& worldPoint) const { return 1; }; + float GetScreenScaleFactor([[maybe_unused]] const Vec3& worldPoint) const override { return 1; }; - void SetAxisConstrain(int axis); + void SetAxisConstrain(int axis) override; /// Take raw input and create a final mouse interaction. /// @attention Do not map **point** from widget to viewport explicitly, @@ -419,7 +414,7 @@ public: // Selection. ////////////////////////////////////////////////////////////////////////// //! Resets current selection region. - virtual void ResetSelectionRegion(); + void ResetSelectionRegion() override; //! Set 2D selection rectangle. void SetSelectionRectangle(const QRect& rect) override; @@ -427,13 +422,13 @@ public: QRect GetSelectionRectangle() const override { return m_selectedRect; }; //! Called when dragging selection rectangle. void OnDragSelectRectangle(const QRect& rect, bool bNormalizeRect = false) override; - //! Get selection procision tolerance. - float GetSelectionTolerance() const { return m_selectionTolerance; } + //! Get selection precision tolerance. + float GetSelectionTolerance() const override { return m_selectionTolerance; } //! Center viewport on selection. void CenterOnSelection() override {} void CenterOnAABB([[maybe_unused]] const AABB& aabb) override {} - virtual void CenterOnSliceInstance() {} + void CenterOnSliceInstance() override {} //! Performs hit testing of 2d point in view to find which object hit. bool HitTest(const QPoint& point, HitContext& hitInfo) override; @@ -446,10 +441,10 @@ public: float GetDistanceToLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& point) const override; // Access to the member m_bAdvancedSelectMode so interested modules can know its value. - bool GetAdvancedSelectModeFlag(); + bool GetAdvancedSelectModeFlag() override; - virtual void GetPerpendicularAxis(EAxis* pAxis, bool* pIs2D) const; - virtual const ::Plane* GetConstructionPlane() const { return &m_constructionPlane; } + void GetPerpendicularAxis(EAxis* pAxis, bool* pIs2D) const override; + const ::Plane* GetConstructionPlane() const override { return &m_constructionPlane; } ////////////////////////////////////////////////////////////////////////// @@ -457,7 +452,7 @@ public: //! Set construction plane from given position construction matrix refrence coord system and axis settings. ////////////////////////////////////////////////////////////////////////// void MakeConstructionPlane(int axis) override; - virtual void SetConstructionMatrix(RefCoordSys coordSys, const Matrix34& xform); + void SetConstructionMatrix(RefCoordSys coordSys, const Matrix34& xform) override; virtual const Matrix34& GetConstructionMatrix(RefCoordSys coordSys); // Set simple construction plane origin. void SetConstructionOrigin(const Vec3& worldPos); @@ -467,11 +462,11 @@ public: ////////////////////////////////////////////////////////////////////////// // Undo for viewpot operations. - void BeginUndo(); - void AcceptUndo(const QString& undoDescription); - void CancelUndo(); - void RestoreUndo(); - bool IsUndoRecording() const; + void BeginUndo() override; + void AcceptUndo(const QString& undoDescription) override; + void CancelUndo() override; + void RestoreUndo() override; + bool IsUndoRecording() const override; ////////////////////////////////////////////////////////////////////////// //! Get prefered original size for this viewport. @@ -479,39 +474,39 @@ public: virtual QSize GetIdealSize() const; //! Check if world space bounding box is visible in this view. - virtual bool IsBoundsVisible(const AABB& box) const; + bool IsBoundsVisible(const AABB& box) const override; ////////////////////////////////////////////////////////////////////////// - void SetCursor(const QCursor& cursor) + void SetCursor(const QCursor& cursor) override { setCursor(cursor); } // Set`s current cursor string. void SetCurrentCursor(const QCursor& hCursor, const QString& cursorString); - virtual void SetCurrentCursor(EStdCursor stdCursor, const QString& cursorString); - void SetCurrentCursor(EStdCursor stdCursor); - virtual void SetCursorString(const QString& cursorString); - void ResetCursor(); - void SetSupplementaryCursorStr(const QString& str); + void SetCurrentCursor(EStdCursor stdCursor, const QString& cursorString) override; + void SetCurrentCursor(EStdCursor stdCursor) override; + void SetCursorString(const QString& cursorString) override; + void ResetCursor() override; + void SetSupplementaryCursorStr(const QString& str) override; ////////////////////////////////////////////////////////////////////////// // Return visble objects cache. - CBaseObjectsCache* GetVisibleObjectsCache() { return m_pVisibleObjectsCache; }; + CBaseObjectsCache* GetVisibleObjectsCache() override { return m_pVisibleObjectsCache; }; - void RegisterRenderListener(IRenderListener* piListener); - bool UnregisterRenderListener(IRenderListener* piListener); - bool IsRenderListenerRegistered(IRenderListener* piListener); + void RegisterRenderListener(IRenderListener* piListener) override; + bool UnregisterRenderListener(IRenderListener* piListener) override; + bool IsRenderListenerRegistered(IRenderListener* piListener) override; - void AddPostRenderer(IPostRenderer* pPostRenderer); - bool RemovePostRenderer(IPostRenderer* pPostRenderer); + void AddPostRenderer(IPostRenderer* pPostRenderer) override; + bool RemovePostRenderer(IPostRenderer* pPostRenderer) override; void CaptureMouse() override { m_mouseCaptured = true; QWidget::grabMouse(); } void ReleaseMouse() override { m_mouseCaptured = false; QWidget::releaseMouse(); } - virtual void setRay(QPoint& vp, Vec3& raySrc, Vec3& rayDir); - virtual void setHitcontext(QPoint& vp, Vec3& raySrc, Vec3& rayDir); + void setRay(QPoint& vp, Vec3& raySrc, Vec3& rayDir) override; + void setHitcontext(QPoint& vp, Vec3& raySrc, Vec3& rayDir) override; QPoint m_vp; AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING Vec3 m_raySrc; @@ -572,12 +567,6 @@ protected: void dragLeaveEvent(QDragLeaveEvent* event) override; void dropEvent(QDropEvent* event) override; - //Child classes can override these to provide extra logic that wraps - //widget rendering. Needed by the RenderViewport to handle raycasts - //from screen-space to world-space. - virtual void PreWidgetRendering() {} - virtual void PostWidgetRendering() {} - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AzToolsFramework::ViewportUi::ViewportUiManager m_viewportUi; AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp index 1f04f71712..65d6de8944 100644 --- a/Code/Editor/ViewportTitleDlg.cpp +++ b/Code/Editor/ViewportTitleDlg.cpp @@ -154,6 +154,8 @@ void CViewportTitleDlg::SetupCameraDropdownMenu() cameraMenu->addMenu(GetFovMenu()); m_ui->m_cameraMenu->setMenu(cameraMenu); m_ui->m_cameraMenu->setPopupMode(QToolButton::InstantPopup); + QObject::connect(cameraMenu, &QMenu::aboutToShow, this, &CViewportTitleDlg::CheckForCameraSpeedUpdate); + QAction* gotoPositionAction = new QAction("Go to position", cameraMenu); connect(gotoPositionAction, &QAction::triggered, this, &CViewportTitleDlg::OnBnClickedGotoPosition); cameraMenu->addAction(gotoPositionAction); diff --git a/Code/Editor/ViewportTitleDlg.h b/Code/Editor/ViewportTitleDlg.h index 5acb04ca99..4a2a454907 100644 --- a/Code/Editor/ViewportTitleDlg.h +++ b/Code/Editor/ViewportTitleDlg.h @@ -77,7 +77,7 @@ Q_SIGNALS: protected: virtual void OnInitDialog(); - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); + void OnEditorNotifyEvent(EEditorNotifyEvent event) override; void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) override; void OnMaximize(); diff --git a/Code/Editor/WelcomeScreen/WelcomeScreenDialog.cpp b/Code/Editor/WelcomeScreen/WelcomeScreenDialog.cpp index 0f73023acf..17f576b5ee 100644 --- a/Code/Editor/WelcomeScreen/WelcomeScreenDialog.cpp +++ b/Code/Editor/WelcomeScreen/WelcomeScreenDialog.cpp @@ -34,6 +34,7 @@ // AzQtComponents #include #include +#include // Editor #include "Settings.h" @@ -79,8 +80,11 @@ WelcomeScreenDialog::WelcomeScreenDialog(QWidget* pParent) { projectPreviewPath = ":/WelcomeScreenDialog/DefaultProjectImage.png"; } + ui->activeProjectIcon->setPixmap( - QPixmap(projectPreviewPath).scaled( + AzQtComponents::ScalePixmapForScreenDpi( + QPixmap(projectPreviewPath), + screen(), ui->activeProjectIcon->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation diff --git a/Code/Framework/AtomCore/AtomCore/Utils/ScopedValue.h b/Code/Framework/AtomCore/AtomCore/Utils/ScopedValue.h new file mode 100644 index 0000000000..f6ed6d6df4 --- /dev/null +++ b/Code/Framework/AtomCore/AtomCore/Utils/ScopedValue.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include + +namespace AZ +{ + //! Sets a variable upon construction and again when the object goes out of scope. + template + class ScopedValue + { + private: + T* m_ptr; + T m_finalValue; + + public: + ScopedValue(T* ptr, T initialValue, T finalValue) : + m_ptr(ptr), m_finalValue(finalValue) + { + AZ_Assert(m_ptr, "ScopedValue::m_ptr is null"); + *m_ptr = initialValue; + } + + ~ScopedValue() + { + *m_ptr = m_finalValue; + } + }; + +} // namespace AZ diff --git a/Code/Framework/AtomCore/AtomCore/atomcore_files.cmake b/Code/Framework/AtomCore/AtomCore/atomcore_files.cmake index c90263468f..9167c1e645 100644 --- a/Code/Framework/AtomCore/AtomCore/atomcore_files.cmake +++ b/Code/Framework/AtomCore/AtomCore/atomcore_files.cmake @@ -19,4 +19,5 @@ set(FILES std/containers/vector_set.h std/containers/vector_set_base.h std/parallel/concurrency_checker.h + Utils/ScopedValue.h ) diff --git a/Code/Framework/AtomCore/Tests/ScopedValueTest.cpp b/Code/Framework/AtomCore/Tests/ScopedValueTest.cpp new file mode 100644 index 0000000000..9578cb2329 --- /dev/null +++ b/Code/Framework/AtomCore/Tests/ScopedValueTest.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +namespace UnitTest +{ + TEST(ScopedValueTest, TestBoolValue) + { + bool localValue = false; + + { + AZ::ScopedValue scopedValue(&localValue, true, false); + EXPECT_EQ(true, localValue); + } + + EXPECT_EQ(false, localValue); + } + + TEST(ScopedValueTest, TestIntValue) + { + int localValue = 0; + + { + AZ::ScopedValue scopedValue(&localValue, 1, 2); + EXPECT_EQ(1, localValue); + } + + EXPECT_EQ(2, localValue); + } +} diff --git a/Code/Framework/AtomCore/Tests/atomcore_tests_files.cmake b/Code/Framework/AtomCore/Tests/atomcore_tests_files.cmake index 0f5fcb441d..4522a4b7b6 100644 --- a/Code/Framework/AtomCore/Tests/atomcore_tests_files.cmake +++ b/Code/Framework/AtomCore/Tests/atomcore_tests_files.cmake @@ -12,5 +12,6 @@ set(FILES InstanceDatabase.cpp lru_cache.cpp Main.cpp + ScopedValueTest.cpp vector_set.cpp ) diff --git a/Code/Framework/AzCore/AzCore/Component/Component.h b/Code/Framework/AzCore/AzCore/Component/Component.h index 9b4ae3f55f..3cbb9b5a86 100644 --- a/Code/Framework/AzCore/AzCore/Component/Component.h +++ b/Code/Framework/AzCore/AzCore/Component/Component.h @@ -266,7 +266,7 @@ namespace AZ _ComponentClass::RTTI_Type().ToString().c_str(), descriptor->GetName(), _ComponentClass::RTTI_TypeName()); \ return nullptr; \ } \ - else if (descriptor->GetName() != _ComponentClass::RTTI_TypeName()) \ + if (descriptor->GetName() != _ComponentClass::RTTI_TypeName()) \ { \ AZ_Error("Component", false, "The same component UUID (%s) / name (%s) was registered twice. This isn't allowed, " \ "it can cause lifetime management issues / crashes.\nThis situation can happen by declaring a component " \ diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index c76156c006..a13f11c007 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -74,6 +74,8 @@ #include #include +AZ_CVAR(float, g_simulation_tick_rate, 0, nullptr, AZ::ConsoleFunctorFlags::Null, "The rate at which the game simulation tick loop runs, or 0 for as fast as possible"); + static void PrintEntityName(const AZ::ConsoleCommandContainer& arguments) { if (arguments.empty()) @@ -1249,6 +1251,8 @@ namespace AZ return AZ::SettingsRegistryInterface::VisitResponse::Continue; } + + using SettingsRegistryInterface::Visitor::Visit; void Visit(AZStd::string_view path, AZStd::string_view valueName, AZ::SettingsRegistryInterface::Type, bool value) override { // By default the auto load option is true @@ -1392,6 +1396,23 @@ namespace AZ AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:OnTick"); EBUS_EVENT(TickBus, OnTick, m_deltaTime, ScriptTimePoint(now)); } + + // If tick rate limiting is on, ensure (1 / g_simulation_tick_rate) ms has elapsed since the last frame, + // sleeping if there's still time remaining. + if (g_simulation_tick_rate > 0.f) + { + now = AZStd::chrono::system_clock::now(); + + // Work in microsecond durations here as that's the native measurement time for time_point + constexpr float microsecondsPerSecond = 1000.f * 1000.f; + const AZStd::chrono::microseconds timeBudgetPerTick(static_cast(microsecondsPerSecond / g_simulation_tick_rate)); + AZStd::chrono::microseconds timeUntilNextTick = m_currentTime + timeBudgetPerTick - now; + + if (timeUntilNextTick.count() > 0) + { + AZStd::this_thread::sleep_for(timeUntilNextTick); + } + } } } diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h index 3768a75d83..bfc541ca09 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h @@ -196,14 +196,14 @@ namespace AZ ////////////////////////////////////////////////////////////////////////// // ComponentApplicationRequests - void RegisterComponentDescriptor(const ComponentDescriptor* descriptor) override final; - void UnregisterComponentDescriptor(const ComponentDescriptor* descriptor) override final; - void RegisterEntityAddedEventHandler(EntityAddedEvent::Handler& handler) override final; - void RegisterEntityRemovedEventHandler(EntityRemovedEvent::Handler& handler) override final; - void RegisterEntityActivatedEventHandler(EntityActivatedEvent::Handler& handler) override final; - void RegisterEntityDeactivatedEventHandler(EntityDeactivatedEvent::Handler& handler) override final; - void SignalEntityActivated(Entity* entity) override final; - void SignalEntityDeactivated(Entity* entity) override final; + void RegisterComponentDescriptor(const ComponentDescriptor* descriptor) final; + void UnregisterComponentDescriptor(const ComponentDescriptor* descriptor) final; + void RegisterEntityAddedEventHandler(EntityAddedEvent::Handler& handler) final; + void RegisterEntityRemovedEventHandler(EntityRemovedEvent::Handler& handler) final; + void RegisterEntityActivatedEventHandler(EntityActivatedEvent::Handler& handler) final; + void RegisterEntityDeactivatedEventHandler(EntityDeactivatedEvent::Handler& handler) final; + void SignalEntityActivated(Entity* entity) final; + void SignalEntityDeactivated(Entity* entity) final; bool AddEntity(Entity* entity) override; bool RemoveEntity(Entity* entity) override; bool DeleteEntity(const EntityId& id) override; diff --git a/Code/Framework/AzCore/AzCore/Component/TickBus.h b/Code/Framework/AzCore/AzCore/Component/TickBus.h index e65efb93f2..966a3c303e 100644 --- a/Code/Framework/AzCore/AzCore/Component/TickBus.h +++ b/Code/Framework/AzCore/AzCore/Component/TickBus.h @@ -46,6 +46,8 @@ namespace AZ TICK_PRE_RENDER = 750, ///< Suggested tick handler position to update render-related data. + TICK_RENDER = 800, ///< Suggested tick handler position for rendering. + TICK_DEFAULT = 1000, ///< Default tick handler position when the handler is constructed. TICK_UI = 2000, ///< Suggested tick handler position for UI components. diff --git a/Code/Framework/AzCore/AzCore/Debug/AssetTrackingTypes.h b/Code/Framework/AzCore/AzCore/Debug/AssetTrackingTypes.h index c46edbb80e..f538c516c3 100644 --- a/Code/Framework/AzCore/AzCore/Debug/AssetTrackingTypes.h +++ b/Code/Framework/AzCore/AzCore/Debug/AssetTrackingTypes.h @@ -86,6 +86,7 @@ namespace AZ class AssetTreeNodeBase { public: + virtual ~AssetTreeNodeBase() = default; virtual const AssetPrimaryInfo* GetAssetPrimaryInfo() const = 0; virtual AssetTreeNodeBase* FindOrAddChild(const AssetTrackingId& id, const AssetPrimaryInfo* info) = 0; }; @@ -94,6 +95,7 @@ namespace AZ class AssetTreeBase { public: + virtual ~AssetTreeBase() = default; virtual AssetTreeNodeBase& GetRoot() = 0; }; @@ -101,6 +103,7 @@ namespace AZ class AssetAllocationTableBase { public: + virtual ~AssetAllocationTableBase() = default; virtual AssetTreeNodeBase* FindAllocation(void* ptr) const = 0; }; } diff --git a/Code/Framework/AzCore/AzCore/Debug/AssetTrackingTypesImpl.h b/Code/Framework/AzCore/AzCore/Debug/AssetTrackingTypesImpl.h index 7916a442b5..eac809c406 100644 --- a/Code/Framework/AzCore/AzCore/Debug/AssetTrackingTypesImpl.h +++ b/Code/Framework/AzCore/AzCore/Debug/AssetTrackingTypesImpl.h @@ -31,6 +31,8 @@ namespace AZ { } + ~AssetTreeNode() override = default; + const AssetPrimaryInfo* GetAssetPrimaryInfo() const override { return m_primaryinfo; @@ -67,6 +69,8 @@ namespace AZ class AssetTree : public AssetTreeBase { public: + ~AssetTree() override = default; + AssetTreeNodeBase& GetRoot() override { return m_rootAssets; @@ -99,6 +103,7 @@ namespace AZ AllocationTable(mutex_type& mutex) : m_mutex(mutex) { } + ~AllocationTable() override = default; AssetTreeNodeBase* FindAllocation(void* ptr) const override { diff --git a/Code/Framework/AzCore/AzCore/Debug/BudgetTracker.h b/Code/Framework/AzCore/AzCore/Debug/BudgetTracker.h index 1357bb5870..34d8510349 100644 --- a/Code/Framework/AzCore/AzCore/Debug/BudgetTracker.h +++ b/Code/Framework/AzCore/AzCore/Debug/BudgetTracker.h @@ -19,7 +19,7 @@ namespace AZ::Debug class BudgetTracker { public: - AZ_RTTI(BudgetTracker, "{E14A746D-BFFE-4C02-90FB-4699B79864A5}"); + AZ_TYPE_INFO(BudgetTracker, "{E14A746D-BFFE-4C02-90FB-4699B79864A5}"); static Budget* GetBudgetFromEnvironment(const char* budgetName, uint32_t crc); ~BudgetTracker(); diff --git a/Code/Framework/AzCore/AzCore/Debug/TraceMessagesDriller.h b/Code/Framework/AzCore/AzCore/Debug/TraceMessagesDriller.h index 16d8f4fba3..32726931fc 100644 --- a/Code/Framework/AzCore/AzCore/Debug/TraceMessagesDriller.h +++ b/Code/Framework/AzCore/AzCore/Debug/TraceMessagesDriller.h @@ -28,21 +28,21 @@ namespace AZ protected: ////////////////////////////////////////////////////////////////////////// // Driller - virtual const char* GroupName() const { return "SystemDrillers"; } - virtual const char* GetName() const { return "TraceMessagesDriller"; } - virtual const char* GetDescription() const { return "Handles all system messages like Assert, Exception, Error, Warning, Printf, etc."; } - virtual void Start(const Param* params = NULL, int numParams = 0); - virtual void Stop(); + const char* GroupName() const override { return "SystemDrillers"; } + const char* GetName() const override { return "TraceMessagesDriller"; } + const char* GetDescription() const override { return "Handles all system messages like Assert, Exception, Error, Warning, Printf, etc."; } + void Start(const Param* params = NULL, int numParams = 0) override; + void Stop() override; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // TraceMessagesDrillerBus /// Triggered when a AZ_Assert failed. This is terminating event! (the code will break, crash). - virtual void OnAssert(const char* message); - virtual void OnException(const char* message); - virtual void OnError(const char* window, const char* message); - virtual void OnWarning(const char* window, const char* message); - virtual void OnPrintf(const char* window, const char* message); + void OnAssert(const char* message) override; + void OnException(const char* message) override; + void OnError(const char* window, const char* message) override; + void OnWarning(const char* window, const char* message) override; + void OnPrintf(const char* window, const char* message) override; ////////////////////////////////////////////////////////////////////////// }; } // namespace Debug diff --git a/Code/Framework/AzCore/AzCore/Driller/Stream.h b/Code/Framework/AzCore/AzCore/Driller/Stream.h index f883984b11..5efa416ef4 100644 --- a/Code/Framework/AzCore/AzCore/Driller/Stream.h +++ b/Code/Framework/AzCore/AzCore/Driller/Stream.h @@ -443,7 +443,7 @@ namespace AZ const unsigned char* GetData() const { return m_data.data(); } unsigned int GetDataSize() const { return static_cast(m_data.size()); } inline void Reset() { m_data.clear(); } - virtual void WriteBinary(const void* data, unsigned int dataSize) + void WriteBinary(const void* data, unsigned int dataSize) override { m_data.insert(m_data.end(), reinterpret_cast(data), reinterpret_cast(data) + dataSize); } @@ -489,7 +489,7 @@ namespace AZ } unsigned int GetDataLeft() const { return static_cast(m_dataEnd - m_data); } - virtual unsigned int ReadBinary(void* data, unsigned int maxDataSize) + unsigned int ReadBinary(void* data, unsigned int maxDataSize) override { AZ_Assert(m_data != nullptr, "You must call SetData function, before you can read data!"); AZ_Assert(data != nullptr && maxDataSize > 0, "We must have a valid pointer and max data size!"); @@ -523,7 +523,7 @@ namespace AZ bool Open(const char* fileName, int mode, int platformFlags = 0); void Close(); - virtual void WriteBinary(const void* data, unsigned int dataSize); + void WriteBinary(const void* data, unsigned int dataSize) override; }; /** @@ -540,7 +540,7 @@ namespace AZ DrillerInputFileStream(); ~DrillerInputFileStream(); bool Open(const char* fileName, int mode, int platformFlags = 0); - virtual unsigned int ReadBinary(void* data, unsigned int maxDataSize); + unsigned int ReadBinary(void* data, unsigned int maxDataSize) override; void Close(); }; diff --git a/Code/Framework/AzCore/AzCore/EBus/EBus.h b/Code/Framework/AzCore/AzCore/EBus/EBus.h index 1bff4ff297..58754ff9b8 100644 --- a/Code/Framework/AzCore/AzCore/EBus/EBus.h +++ b/Code/Framework/AzCore/AzCore/EBus/EBus.h @@ -1717,6 +1717,7 @@ AZ_POP_DISABLE_WARNING { EBusRouterNode m_routerNode; public: + virtual ~EBusNestedVersionRouter() = default; template void BusRouterConnect(Container& container, int order = 0); diff --git a/Code/Framework/AzCore/AzCore/EBus/Environment.h b/Code/Framework/AzCore/AzCore/EBus/Environment.h index e5cec765be..93a0f714f9 100644 --- a/Code/Framework/AzCore/AzCore/EBus/Environment.h +++ b/Code/Framework/AzCore/AzCore/EBus/Environment.h @@ -96,7 +96,7 @@ namespace AZ const char* get_name() const { return m_name; } void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return AZ_CORE_MAX_ALLOCATOR_SIZE; } + constexpr size_type max_size() const { return AZ_CORE_MAX_ALLOCATOR_SIZE; } size_type get_allocated_size() const { return 0; } bool is_lock_free() { return false; } diff --git a/Code/Framework/AzCore/AzCore/IO/CompressorZLib.h b/Code/Framework/AzCore/AzCore/IO/CompressorZLib.h index abd21e1450..dd1fb226c3 100644 --- a/Code/Framework/AzCore/AzCore/IO/CompressorZLib.h +++ b/Code/Framework/AzCore/AzCore/IO/CompressorZLib.h @@ -98,21 +98,21 @@ namespace AZ /// Return compressor type id. static AZ::u32 TypeId(); - virtual AZ::u32 GetTypeId() const { return TypeId(); } + AZ::u32 GetTypeId() const override { return TypeId(); } /// Called when we open a stream to Read for the first time. Data contains the first. dataSize <= m_maxHeaderSize. - virtual bool ReadHeaderAndData(CompressorStream* stream, AZ::u8* data, unsigned int dataSize); + bool ReadHeaderAndData(CompressorStream* stream, AZ::u8* data, unsigned int dataSize) override; /// Called when we are about to start writing to a compressed stream. - virtual bool WriteHeaderAndData(CompressorStream* stream); + bool WriteHeaderAndData(CompressorStream* stream) override; /// Forwarded function from the Device when we from a compressed stream. - virtual SizeType Read(CompressorStream* stream, SizeType byteSize, SizeType offset, void* buffer); + SizeType Read(CompressorStream* stream, SizeType byteSize, SizeType offset, void* buffer) override; /// Forwarded function from the Device when we write to a compressed stream. - virtual SizeType Write(CompressorStream* stream, SizeType byteSize, const void* data, SizeType offset = SizeType(-1)); + SizeType Write(CompressorStream* stream, SizeType byteSize, const void* data, SizeType offset = SizeType(-1)) override; /// Write a seek point. - virtual bool WriteSeekPoint(CompressorStream* stream); + bool WriteSeekPoint(CompressorStream* stream) override; /// Set auto seek point even dataSize bytes. - virtual bool StartCompressor(CompressorStream* stream, int compressionLevel, SizeType autoSeekDataSize); + bool StartCompressor(CompressorStream* stream, int compressionLevel, SizeType autoSeekDataSize) override; /// Called just before we close the stream. All compression data will be flushed and finalized. (You can't add data afterwards). - virtual bool Close(CompressorStream* stream); + bool Close(CompressorStream* stream) override; protected: diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.h b/Code/Framework/AzCore/AzCore/IO/Path/Path.h index c0c4b1c974..24f26daa51 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.h +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.h @@ -273,7 +273,7 @@ namespace AZ::IO // If the path input = 'D:bar', then the new PathIterable parts = [D:, 'bar' ] static constexpr void AppendNormalPathParts(PathIterable& pathIterableResult, const AZ::IO::PathView& path) noexcept; - constexpr int compare_string_view(AZStd::string_view other) const; + constexpr int ComparePathView(const PathView& other) const; constexpr AZStd::string_view root_name_view() const; constexpr AZStd::string_view root_directory_view() const; constexpr AZStd::string_view root_path_raw_view() const; @@ -480,6 +480,8 @@ namespace AZ::IO // compare //! Performs a compare of each of the path parts for equivalence //! Each part of the path is compare using string comparison + //! If both *this path and the input path uses the WindowsPathSeparator + //! then a non-case sensitive compare is performed //! Ex: Comparing "test/foo" against "test/fop" returns -1; //! Path separators of the contained path string aren't compared //! Ex. Comparing "C:/test\foo" against C:\test/foo" returns 0; diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl index 40cbf6f46b..0147ad3356 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl @@ -224,15 +224,15 @@ namespace AZ::IO // compare constexpr int PathView::Compare(const PathView& other) const noexcept { - return compare_string_view(other.m_path); + return ComparePathView(other); } constexpr int PathView::Compare(AZStd::string_view pathView) const noexcept { - return compare_string_view(pathView); + return ComparePathView(PathView(pathView, m_preferred_separator)); } constexpr int PathView::Compare(const value_type* path) const noexcept { - return compare_string_view(path); + return ComparePathView(PathView(path, m_preferred_separator)); } constexpr AZStd::fixed_string PathView::FixedMaxPathString() const noexcept @@ -398,10 +398,10 @@ namespace AZ::IO return true; } - constexpr int PathView::compare_string_view(AZStd::string_view pathView) const + constexpr int PathView::ComparePathView(const PathView& other) const { auto lhsPathParser = parser::PathParser::CreateBegin(m_path, m_preferred_separator); - auto rhsPathParser = parser::PathParser::CreateBegin(pathView, m_preferred_separator); + auto rhsPathParser = parser::PathParser::CreateBegin(other.m_path, other.m_preferred_separator); if (int res = CompareRootName(&lhsPathParser, &rhsPathParser); res != 0) { @@ -476,6 +476,8 @@ namespace AZ::IO template constexpr void PathView::MakeRelativeTo(PathResultType& pathResult, const AZ::IO::PathView& path, const AZ::IO::PathView& base) { + const bool exactCaseCompare = path.m_preferred_separator == PosixPathSeparator + || base.m_preferred_separator == PosixPathSeparator; { // perform root-name/root-directory mismatch checks auto pathParser = parser::PathParser::CreateBegin(path.m_path, path.m_preferred_separator); @@ -487,7 +489,7 @@ namespace AZ::IO }; if (pathParser.InRootName() && pathParserBase.InRootName()) { - if (int res = Internal::ComparePathSegment(*pathParser, *pathParserBase, pathParser.m_preferred_separator); + if (int res = Internal::ComparePathSegment(*pathParser, *pathParserBase, exactCaseCompare); res != 0) { pathResult.m_path = AZStd::string_view{}; @@ -519,7 +521,7 @@ namespace AZ::IO auto pathParser = parser::PathParser::CreateBegin(path.m_path, path.m_preferred_separator); auto pathParserBase = parser::PathParser::CreateBegin(base.m_path, base.m_preferred_separator); while (pathParser && pathParserBase && pathParser.m_parser_state == pathParserBase.m_parser_state && - Internal::ComparePathSegment(*pathParser, *pathParserBase, pathParser.m_preferred_separator) == 0) + Internal::ComparePathSegment(*pathParser, *pathParserBase, exactCaseCompare) == 0) { ++pathParser; ++pathParserBase; @@ -1080,25 +1082,25 @@ namespace AZ::IO template constexpr int BasicPath::Compare(const PathView& other) const noexcept { - return static_cast(*this).compare_string_view(other.m_path); + return static_cast(*this).ComparePathView(other); } template constexpr int BasicPath::Compare(const string_type& pathString) const { - return static_cast(*this).compare_string_view(pathString); + return static_cast(*this).ComparePathView(PathView(pathString, m_preferred_separator)); } template constexpr int BasicPath::Compare(AZStd::string_view pathView) const noexcept { - return static_cast(*this).compare_string_view(pathView); + return static_cast(*this).ComparePathView(pathView); } template constexpr int BasicPath::Compare(const value_type* pathString) const noexcept { - return static_cast(*this).compare_string_view(pathString); + return static_cast(*this).ComparePathView(pathString); } // decomposition @@ -1330,10 +1332,12 @@ namespace AZ::IO // PathView::LexicallyRelative is not being used as it returns a FixedMaxPath // which has a limitation that it requires the relative path to fit within // an AZ::IO::MaxPathLength buffer - auto ComparePathPart = [pathSeparator = m_preferred_separator]( + const bool exactCaseCompare = m_preferred_separator == PosixPathSeparator + || base.m_preferred_separator == PosixPathSeparator; + auto ComparePathPart = [exactCaseCompare]( const PathIterable::PartKindPair& left, const PathIterable::PartKindPair& right) -> bool { - return Internal::ComparePathSegment(left.first, right.first, pathSeparator) == 0; + return Internal::ComparePathSegment(left.first, right.first, exactCaseCompare) == 0; }; const PathIterable thisPathParts = GetNormalPathParts(*this); @@ -1471,37 +1475,16 @@ namespace AZStd template <> struct hash { - /// Path is using FNV-1a algorithm 64 bit version. - static size_t hash_path(AZStd::string_view pathSegment, const char pathSeparator) - { - size_t hash = 14695981039346656037ULL; - constexpr size_t fnvPrime = 1099511628211ULL; - - for (const char first : pathSegment) - { - hash ^= static_cast((pathSeparator == AZ::IO::PosixPathSeparator) - ? first : tolower(first)); - hash *= fnvPrime; - } - return hash; - } - size_t operator()(const AZ::IO::PathView& pathToHash) noexcept { auto pathParser = AZ::IO::parser::PathParser::CreateBegin(pathToHash.Native(), pathToHash.m_preferred_separator); - size_t hash_value = 0; - while (pathParser) - { - AZStd::hash_combine(hash_value, hash_path(*pathParser, pathToHash.m_preferred_separator)); - ++pathParser; - } - return hash_value; + return AZ::IO::parser::HashPath(pathParser); } }; template struct hash> { - const size_t operator()(const AZ::IO::BasicPath& pathToHash) noexcept + size_t operator()(const AZ::IO::BasicPath& pathToHash) noexcept { return AZStd::hash{}(pathToHash); } diff --git a/Code/Framework/AzCore/AzCore/IO/Path/PathParser.inl b/Code/Framework/AzCore/AzCore/IO/Path/PathParser.inl index 3ab2c4376c..b19c518ff9 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/PathParser.inl +++ b/Code/Framework/AzCore/AzCore/IO/Path/PathParser.inl @@ -183,13 +183,12 @@ namespace AZ::IO::Internal return IsAbsolute(pathView.begin(), pathView.end(), preferredSeparator); } - // Compares path segments using either Posix or Windows path rules based on the path separator in use - // Posix paths perform a case-sensitive comparison, while Windows paths perform a case-insensitive comparison - static int ComparePathSegment(AZStd::string_view left, AZStd::string_view right, char pathSeparator) + // Compares path segments using either Posix or Windows path rules based on the exactCaseCompare option + static int ComparePathSegment(AZStd::string_view left, AZStd::string_view right, bool exactCaseCompare) { const size_t maxCharsToCompare = (AZStd::min)(left.size(), right.size()); - int charCompareResult = pathSeparator == PosixPathSeparator + int charCompareResult = exactCaseCompare ? maxCharsToCompare ? strncmp(left.data(), right.data(), maxCharsToCompare) : 0 : maxCharsToCompare ? azstrnicmp(left.data(), right.data(), maxCharsToCompare) : 0; return charCompareResult == 0 @@ -594,7 +593,10 @@ namespace AZ::IO::parser { return pathParser->InRootName() ? **pathParser : ""; }; - int res = Internal::ComparePathSegment(GetRootName(lhsPathParser), GetRootName(rhsPathParser), lhsPathParser->m_preferred_separator); + + const bool exactCaseCompare = lhsPathParser->m_preferred_separator == PosixPathSeparator + || rhsPathParser->m_preferred_separator == PosixPathSeparator; + int res = Internal::ComparePathSegment(GetRootName(lhsPathParser), GetRootName(rhsPathParser), exactCaseCompare); ConsumeRootName(lhsPathParser); ConsumeRootName(rhsPathParser); return res; @@ -621,9 +623,11 @@ namespace AZ::IO::parser auto& lhsPathParser = *lhsPathParserPtr; auto& rhsPathParser = *rhsPathParserPtr; + const bool exactCaseCompare = lhsPathParser.m_preferred_separator == PosixPathSeparator + || rhsPathParser.m_preferred_separator == PosixPathSeparator; while (lhsPathParser && rhsPathParser) { - if (int res = Internal::ComparePathSegment(*lhsPathParser, *rhsPathParser, lhsPathParser.m_preferred_separator); + if (int res = Internal::ComparePathSegment(*lhsPathParser, *rhsPathParser, exactCaseCompare); res != 0) { return res; @@ -646,6 +650,46 @@ namespace AZ::IO::parser return 0; } + //path.hash + /// Path is using FNV-1a algorithm 64 bit version. + inline size_t HashSegment(AZStd::string_view pathSegment, bool hashExactPath) + { + size_t hash = 14695981039346656037ULL; + constexpr size_t fnvPrime = 1099511628211ULL; + + for (const char first : pathSegment) + { + hash ^= static_cast(hashExactPath ? first : tolower(first)); + hash *= fnvPrime; + } + return hash; + } + constexpr size_t HashPath(PathParser& pathParser) + { + size_t hash_value = 0; + const bool hashExactPath = pathParser.m_preferred_separator == AZ::IO::PosixPathSeparator; + while (pathParser) + { + switch (pathParser.m_parser_state) + { + case PS_InRootName: + case PS_InFilenames: + AZStd::hash_combine(hash_value, HashSegment(*pathParser, hashExactPath)); + break; + case PS_InRootDir: + // Only hash the PosixPathSeparator when a root directory is seen + // This makes the hash consistent for root directories path of C:\ and C:/ + AZStd::hash_combine(hash_value, HashSegment("/", hashExactPath)); + break; + default: + // The BeforeBegin and AtEnd states contain no segments to hash + break; + } + ++pathParser; + } + return hash_value; + } + constexpr int DetermineLexicalElementCount(PathParser pathParser) { int count = 0; diff --git a/Code/Framework/AzCore/AzCore/Jobs/Internal/JobNotify.h b/Code/Framework/AzCore/AzCore/Jobs/Internal/JobNotify.h index 9b6a39af4f..1c15b7105e 100644 --- a/Code/Framework/AzCore/AzCore/Jobs/Internal/JobNotify.h +++ b/Code/Framework/AzCore/AzCore/Jobs/Internal/JobNotify.h @@ -31,7 +31,7 @@ namespace AZ { } protected: - virtual void Process() + void Process() override { m_notifyFlag->store(true, AZStd::memory_order_release); } diff --git a/Code/Framework/AzCore/AzCore/Math/InterpolationSample.h b/Code/Framework/AzCore/AzCore/Math/InterpolationSample.h index 12b18f86b8..942f02727e 100644 --- a/Code/Framework/AzCore/AzCore/Math/InterpolationSample.h +++ b/Code/Framework/AzCore/AzCore/Math/InterpolationSample.h @@ -77,7 +77,7 @@ namespace AZ : public Sample { public: - Vector3 GetInterpolatedValue(TimeType time) override final + Vector3 GetInterpolatedValue(TimeType time) final { Vector3 interpolatedValue = m_previousValue; if (m_targetTimestamp != 0) @@ -108,7 +108,7 @@ namespace AZ : public Sample { public: - Quaternion GetInterpolatedValue(TimeType time) override final + Quaternion GetInterpolatedValue(TimeType time) final { Quaternion interpolatedValue = m_previousValue; if (m_targetTimestamp != 0) @@ -144,7 +144,7 @@ namespace AZ : public Sample { public: - Vector3 GetInterpolatedValue(TimeType /*time*/) override final + Vector3 GetInterpolatedValue(TimeType /*time*/) final { return GetTargetValue(); } @@ -155,7 +155,7 @@ namespace AZ : public Sample { public: - Quaternion GetInterpolatedValue(TimeType /*time*/) override final + Quaternion GetInterpolatedValue(TimeType /*time*/) final { return GetTargetValue(); } diff --git a/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.cpp b/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.cpp index 69fbe2a519..154d59edd3 100644 --- a/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.cpp @@ -216,6 +216,11 @@ namespace AZ return m_source->GetMaxAllocationSize(); } + auto AllocatorOverrideShim::GetMaxContiguousAllocationSize() const -> size_type + { + return m_source->GetMaxContiguousAllocationSize(); + } + IAllocatorAllocate* AllocatorOverrideShim::GetSubAllocator() { return m_source->GetSubAllocator(); diff --git a/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.h b/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.h index ae3859a938..3b45b9953e 100644 --- a/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.h +++ b/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.h @@ -52,6 +52,7 @@ namespace AZ size_type NumAllocatedBytes() const override; size_type Capacity() const override; size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; IAllocatorAllocate* GetSubAllocator() override; private: diff --git a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.cpp b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.cpp index cf26c8f723..ca414df4b5 100644 --- a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.cpp @@ -188,6 +188,11 @@ BestFitExternalMapAllocator::GetMaxAllocationSize() const return m_schema->GetMaxAllocationSize(); } +auto BestFitExternalMapAllocator::GetMaxContiguousAllocationSize() const -> size_type +{ + return m_schema->GetMaxContiguousAllocationSize(); +} + //========================================================================= // GetSubAllocator // [1/28/2011] diff --git a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.h b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.h index 474619ad9f..17425625b7 100644 --- a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.h @@ -63,6 +63,7 @@ namespace AZ size_type NumAllocatedBytes() const override; size_type Capacity() const override; size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; IAllocatorAllocate* GetSubAllocator() override; ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.cpp index d94d1dfe35..715ecd221e 100644 --- a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.cpp @@ -136,6 +136,12 @@ BestFitExternalMapSchema::GetMaxAllocationSize() const return 0; } +auto BestFitExternalMapSchema::GetMaxContiguousAllocationSize() const -> size_type +{ + // Return the maximum size of any single allocation + return AZ_CORE_MAX_ALLOCATOR_SIZE; +} + //========================================================================= // GarbageCollect // [1/28/2011] diff --git a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.h b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.h index 221407421f..eaab614593 100644 --- a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.h @@ -57,6 +57,7 @@ namespace AZ AZ_FORCE_INLINE size_type NumAllocatedBytes() const { return m_used; } AZ_FORCE_INLINE size_type Capacity() const { return m_desc.m_memoryBlockByteSize; } size_type GetMaxAllocationSize() const; + size_type GetMaxContiguousAllocationSize() const; AZ_FORCE_INLINE IAllocatorAllocate* GetSubAllocator() const { return m_desc.m_mapAllocator; } /** diff --git a/Code/Framework/AzCore/AzCore/Memory/HeapSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/HeapSchema.cpp index 50e6a47630..aceafa1b28 100644 --- a/Code/Framework/AzCore/AzCore/Memory/HeapSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/HeapSchema.cpp @@ -244,6 +244,11 @@ namespace AZ return maxChunk; } + auto HeapSchema::GetMaxContiguousAllocationSize() const -> size_type + { + return MAX_REQUEST; + } + AZ_FORCE_INLINE HeapSchema::size_type HeapSchema::ChunckSize(pointer_type ptr) { diff --git a/Code/Framework/AzCore/AzCore/Memory/HeapSchema.h b/Code/Framework/AzCore/AzCore/Memory/HeapSchema.h index af3e2d9986..f72ae31057 100644 --- a/Code/Framework/AzCore/AzCore/Memory/HeapSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/HeapSchema.h @@ -48,17 +48,18 @@ namespace AZ HeapSchema(const Descriptor& desc); virtual ~HeapSchema(); - virtual pointer_type Allocate(size_type byteSize, size_type alignment, int flags, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0); - virtual void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0); - virtual pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) { (void)ptr; (void)newSize; (void)newAlignment; return NULL; } - virtual size_type Resize(pointer_type ptr, size_type newSize) { (void)ptr; (void)newSize; return 0; } - virtual size_type AllocationSize(pointer_type ptr); + pointer_type Allocate(size_type byteSize, size_type alignment, int flags, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override; + void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override; + pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override { (void)ptr; (void)newSize; (void)newAlignment; return NULL; } + size_type Resize(pointer_type ptr, size_type newSize) override { (void)ptr; (void)newSize; return 0; } + size_type AllocationSize(pointer_type ptr) override; - virtual size_type NumAllocatedBytes() const { return m_used; } - virtual size_type Capacity() const { return m_capacity; } - virtual size_type GetMaxAllocationSize() const; - virtual IAllocatorAllocate* GetSubAllocator() { return m_subAllocator; } - virtual void GarbageCollect() {} + size_type NumAllocatedBytes() const override { return m_used; } + size_type Capacity() const override { return m_capacity; } + size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; + IAllocatorAllocate* GetSubAllocator() override { return m_subAllocator; } + void GarbageCollect() override {} private: AZ_FORCE_INLINE size_type ChunckSize(pointer_type ptr); diff --git a/Code/Framework/AzCore/AzCore/Memory/HphaSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/HphaSchema.cpp index f5df0dfe96..6af8f201c2 100644 --- a/Code/Framework/AzCore/AzCore/Memory/HphaSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/HphaSchema.cpp @@ -1069,6 +1069,7 @@ namespace AZ { /// returns allocation size for the pointer if it belongs to the allocator. result is undefined if the pointer doesn't belong to the allocator. size_t AllocationSize(void* ptr); size_t GetMaxAllocationSize() const; + size_t GetMaxContiguousAllocationSize() const; size_t GetUnAllocatedMemory(bool isPrint) const; void* SystemAlloc(size_t size, size_t align); @@ -2301,6 +2302,11 @@ namespace AZ { return maxSize; } + size_t HpAllocator::GetMaxContiguousAllocationSize() const + { + return AZ_CORE_MAX_ALLOCATOR_SIZE; + } + //========================================================================= // GetUnAllocatedMemory // [9/30/2013] @@ -2677,6 +2683,11 @@ namespace AZ { return m_allocator->GetMaxAllocationSize(); } + auto HphaSchema::GetMaxContiguousAllocationSize() const -> size_type + { + return m_allocator->GetMaxContiguousAllocationSize(); + } + //========================================================================= // GetUnAllocatedMemory // [9/30/2013] diff --git a/Code/Framework/AzCore/AzCore/Memory/HphaSchema.h b/Code/Framework/AzCore/AzCore/Memory/HphaSchema.h index fc10bcd768..5ee0205196 100644 --- a/Code/Framework/AzCore/AzCore/Memory/HphaSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/HphaSchema.h @@ -56,21 +56,22 @@ namespace AZ HphaSchema(const Descriptor& desc); virtual ~HphaSchema(); - virtual 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); - virtual void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0); - virtual pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment); + 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; + void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override; + pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override; /// Resizes allocated memory block to the size possible and returns that size. - virtual size_type Resize(pointer_type ptr, size_type newSize); - virtual size_type AllocationSize(pointer_type ptr); + size_type Resize(pointer_type ptr, size_type newSize) override; + size_type AllocationSize(pointer_type ptr) override; - virtual size_type NumAllocatedBytes() const; - virtual size_type Capacity() const; - virtual size_type GetMaxAllocationSize() const; - virtual size_type GetUnAllocatedMemory(bool isPrint = false) const; - virtual IAllocatorAllocate* GetSubAllocator() { return m_desc.m_subAllocator; } + size_type NumAllocatedBytes() const override; + size_type Capacity() const override; + size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; + size_type GetUnAllocatedMemory(bool isPrint = false) const override; + IAllocatorAllocate* GetSubAllocator() override { return m_desc.m_subAllocator; } /// Return unused memory to the OS (if we don't use fixed block). Don't call this unless you really need free memory, it is slow. - virtual void GarbageCollect(); + void GarbageCollect() override; private: // [LY-84974][sconel@][2018-08-10] SliceStrike integration up to CL 671758 diff --git a/Code/Framework/AzCore/AzCore/Memory/IAllocator.h b/Code/Framework/AzCore/AzCore/Memory/IAllocator.h index 02f08fe77f..1aa4cf70f5 100644 --- a/Code/Framework/AzCore/AzCore/Memory/IAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/IAllocator.h @@ -62,6 +62,8 @@ namespace AZ virtual size_type Capacity() const = 0; /// Returns max allocation size if possible. If not returned value is 0 virtual size_type GetMaxAllocationSize() const { return 0; } + /// Returns the maximum contiguous allocation size of a single allocation + virtual size_type GetMaxContiguousAllocationSize() const { return 0; } /** * Returns memory allocated by the allocator and available to the user for allocations. * IMPORTANT: this is not the overhead memory this is just the memory that is allocated, but not used. Example: the pool allocators diff --git a/Code/Framework/AzCore/AzCore/Memory/MallocSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/MallocSchema.cpp index 581b6f2d57..76a71e0f08 100644 --- a/Code/Framework/AzCore/AzCore/Memory/MallocSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/MallocSchema.cpp @@ -144,6 +144,11 @@ AZ::MallocSchema::size_type AZ::MallocSchema::GetMaxAllocationSize() const return 0xFFFFFFFFull; } +AZ::MallocSchema::size_type AZ::MallocSchema::GetMaxContiguousAllocationSize() const +{ + return AZ_CORE_MAX_ALLOCATOR_SIZE; +} + AZ::IAllocatorAllocate* AZ::MallocSchema::GetSubAllocator() { return nullptr; diff --git a/Code/Framework/AzCore/AzCore/Memory/MallocSchema.h b/Code/Framework/AzCore/AzCore/Memory/MallocSchema.h index 3a363cb069..7a8c4a0366 100644 --- a/Code/Framework/AzCore/AzCore/Memory/MallocSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/MallocSchema.h @@ -41,17 +41,18 @@ namespace AZ //--------------------------------------------------------------------- // IAllocatorAllocate //--------------------------------------------------------------------- - virtual pointer_type Allocate(size_type byteSize, size_type alignment, int flags, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override; - virtual void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override; - virtual pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override; - virtual size_type Resize(pointer_type ptr, size_type newSize) override; - virtual size_type AllocationSize(pointer_type ptr) override; + pointer_type Allocate(size_type byteSize, size_type alignment, int flags, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override; + void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override; + pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override; + size_type Resize(pointer_type ptr, size_type newSize) override; + size_type AllocationSize(pointer_type ptr) override; - virtual size_type NumAllocatedBytes() const override; - virtual size_type Capacity() const override; - virtual size_type GetMaxAllocationSize() const override; - virtual IAllocatorAllocate* GetSubAllocator() override; - virtual void GarbageCollect() override; + size_type NumAllocatedBytes() const override; + size_type Capacity() const override; + size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; + IAllocatorAllocate* GetSubAllocator() override; + void GarbageCollect() override; private: typedef void* (*MallocFn)(size_t); diff --git a/Code/Framework/AzCore/AzCore/Memory/Memory.h b/Code/Framework/AzCore/AzCore/Memory/Memory.h index af175c7a64..2e08ec1b15 100644 --- a/Code/Framework/AzCore/AzCore/Memory/Memory.h +++ b/Code/Framework/AzCore/AzCore/Memory/Memory.h @@ -839,12 +839,17 @@ namespace AZ return AZ::AllocatorInstance::Get().GetMaxAllocationSize(); } + size_type GetMaxContiguousAllocationSize() const override + { + return AZ::AllocatorInstance::Get().GetMaxContiguousAllocationSize(); + } + size_type GetUnAllocatedMemory(bool isPrint = false) const override { return AZ::AllocatorInstance::Get().GetUnAllocatedMemory(isPrint); } - virtual IAllocatorAllocate* GetSubAllocator() override + IAllocatorAllocate* GetSubAllocator() override { return AZ::AllocatorInstance::Get().GetSubAllocator(); } @@ -896,7 +901,7 @@ namespace AZ } AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return AllocatorInstance::Get().GetMaxAllocationSize(); } + size_type max_size() const { return AllocatorInstance::Get().GetMaxContiguousAllocationSize(); } size_type get_allocated_size() const { return AllocatorInstance::Get().NumAllocatedBytes(); } AZ_FORCE_INLINE bool is_lock_free() { return AllocatorInstance::Get().is_lock_free(); } @@ -954,7 +959,7 @@ namespace AZ } AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return m_allocator->GetMaxAllocationSize(); } + size_type max_size() const { return m_allocator->GetMaxContiguousAllocationSize(); } size_type get_allocated_size() const { return m_allocator->NumAllocatedBytes(); } AZ_FORCE_INLINE bool operator==(const AZStdIAllocator& rhs) const { return m_allocator == rhs.m_allocator; } @@ -1006,7 +1011,7 @@ namespace AZ } constexpr const char* get_name() const { return m_name; } void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return m_allocatorFunctor().GetMaxAllocationSize(); } + size_type max_size() const { return m_allocatorFunctor().GetMaxContiguousAllocationSize(); } size_type get_allocated_size() const { return m_allocatorFunctor().NumAllocatedBytes(); } constexpr bool operator==(const AZStdFunctorAllocator& rhs) const { return m_allocatorFunctor == rhs.m_allocatorFunctor; } diff --git a/Code/Framework/AzCore/AzCore/Memory/MemoryDriller.h b/Code/Framework/AzCore/AzCore/Memory/MemoryDriller.h index 94c364c719..9bcbc85217 100644 --- a/Code/Framework/AzCore/AzCore/Memory/MemoryDriller.h +++ b/Code/Framework/AzCore/AzCore/Memory/MemoryDriller.h @@ -38,24 +38,24 @@ namespace AZ protected: ////////////////////////////////////////////////////////////////////////// // Driller - virtual const char* GroupName() const { return "SystemDrillers"; } - virtual const char* GetName() const { return "MemoryDriller"; } - virtual const char* GetDescription() const { return "Reports all allocators and memory allocations."; } - virtual void Start(const Param* params = NULL, int numParams = 0); - virtual void Stop(); + const char* GroupName() const override { return "SystemDrillers"; } + const char* GetName() const override { return "MemoryDriller"; } + const char* GetDescription() const override { return "Reports all allocators and memory allocations."; } + void Start(const Param* params = NULL, int numParams = 0) override; + void Stop() override; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // MemoryDrillerBus - virtual void RegisterAllocator(IAllocator* allocator); - virtual void UnregisterAllocator(IAllocator* allocator); + void RegisterAllocator(IAllocator* allocator) override; + void UnregisterAllocator(IAllocator* allocator) override; - virtual void RegisterAllocation(IAllocator* allocator, void* address, size_t byteSize, size_t alignment, const char* name, const char* fileName, int lineNum, unsigned int stackSuppressCount); - virtual void UnregisterAllocation(IAllocator* allocator, void* address, size_t byteSize, size_t alignment, AllocationInfo* info); - virtual void ReallocateAllocation(IAllocator* allocator, void* prevAddress, void* newAddress, size_t newByteSize, size_t newAlignment); - virtual void ResizeAllocation(IAllocator* allocator, void* address, size_t newSize); + void RegisterAllocation(IAllocator* allocator, void* address, size_t byteSize, size_t alignment, const char* name, const char* fileName, int lineNum, unsigned int stackSuppressCount) override; + void UnregisterAllocation(IAllocator* allocator, void* address, size_t byteSize, size_t alignment, AllocationInfo* info) override; + void ReallocateAllocation(IAllocator* allocator, void* prevAddress, void* newAddress, size_t newByteSize, size_t newAlignment) override; + void ResizeAllocation(IAllocator* allocator, void* address, size_t newSize) override; - virtual void DumpAllAllocations(); + void DumpAllAllocations() override; ////////////////////////////////////////////////////////////////////////// void RegisterAllocatorOutput(IAllocator* allocator); diff --git a/Code/Framework/AzCore/AzCore/Memory/OSAllocator.h b/Code/Framework/AzCore/AzCore/Memory/OSAllocator.h index 6154e97f38..b327cf6349 100644 --- a/Code/Framework/AzCore/AzCore/Memory/OSAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/OSAllocator.h @@ -61,6 +61,7 @@ namespace AZ size_type NumAllocatedBytes() const override { return m_custom ? m_custom->NumAllocatedBytes() : m_numAllocatedBytes; } size_type Capacity() const override { return m_custom ? m_custom->Capacity() : AZ_CORE_MAX_ALLOCATOR_SIZE; } // custom size or unlimited size_type GetMaxAllocationSize() const override { return m_custom ? m_custom->GetMaxAllocationSize() : AZ_CORE_MAX_ALLOCATOR_SIZE; } // custom size or unlimited + size_type GetMaxContiguousAllocationSize() const override { return m_custom ? m_custom->GetMaxContiguousAllocationSize() : AZ_CORE_MAX_ALLOCATOR_SIZE; } // custom size or unlimited IAllocatorAllocate* GetSubAllocator() override { return m_custom ? m_custom : NULL; } protected: diff --git a/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.cpp b/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.cpp index 35ad19dd9e..ed5e0febc2 100644 --- a/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.cpp @@ -232,6 +232,7 @@ namespace AZ size_type NumAllocatedBytes() const; size_type Capacity() const; size_type GetMaxAllocationSize() const; + size_type GetMaxContiguousAllocationSize() const; IAllocatorAllocate* GetSubAllocator(); void GarbageCollect(); @@ -674,6 +675,11 @@ AZ::OverrunDetectionSchema::size_type AZ::OverrunDetectionSchemaImpl::GetMaxAllo return 0; } +auto AZ::OverrunDetectionSchemaImpl::GetMaxContiguousAllocationSize() const -> size_type +{ + return 0; +} + AZ::IAllocatorAllocate* AZ::OverrunDetectionSchemaImpl::GetSubAllocator() { return nullptr; @@ -799,6 +805,11 @@ AZ::OverrunDetectionSchema::size_type AZ::OverrunDetectionSchema::GetMaxAllocati return m_impl->GetMaxAllocationSize(); } +auto AZ::OverrunDetectionSchema::GetMaxContiguousAllocationSize() const -> size_type +{ + return m_impl->GetMaxContiguousAllocationSize(); +} + AZ::IAllocatorAllocate* AZ::OverrunDetectionSchema::GetSubAllocator() { return m_impl->GetSubAllocator(); diff --git a/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.h b/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.h index 669fda8a04..9895a5f84f 100644 --- a/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.h @@ -77,17 +77,18 @@ namespace AZ //--------------------------------------------------------------------- // IAllocatorAllocate //--------------------------------------------------------------------- - virtual pointer_type Allocate(size_type byteSize, size_type alignment, int flags, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override; - virtual void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override; - virtual pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override; - virtual size_type Resize(pointer_type ptr, size_type newSize) override; - virtual size_type AllocationSize(pointer_type ptr) override; + pointer_type Allocate(size_type byteSize, size_type alignment, int flags, const char* name = 0, const char* fileName = 0, int lineNum = 0, unsigned int suppressStackRecord = 0) override; + void DeAllocate(pointer_type ptr, size_type byteSize = 0, size_type alignment = 0) override; + pointer_type ReAllocate(pointer_type ptr, size_type newSize, size_type newAlignment) override; + size_type Resize(pointer_type ptr, size_type newSize) override; + size_type AllocationSize(pointer_type ptr) override; - virtual size_type NumAllocatedBytes() const override; - virtual size_type Capacity() const override; - virtual size_type GetMaxAllocationSize() const override; - virtual IAllocatorAllocate* GetSubAllocator() override; - virtual void GarbageCollect() override; + size_type NumAllocatedBytes() const override; + size_type Capacity() const override; + size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; + IAllocatorAllocate* GetSubAllocator() override; + void GarbageCollect() override; private: OverrunDetectionSchemaImpl* m_impl; diff --git a/Code/Framework/AzCore/AzCore/Memory/PoolSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/PoolSchema.cpp index 3e71f530a0..0bef6b7d28 100644 --- a/Code/Framework/AzCore/AzCore/Memory/PoolSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/PoolSchema.cpp @@ -707,6 +707,11 @@ PoolSchema::GarbageCollect() //m_impl->GarbageCollect(); } +auto PoolSchema::GetMaxContiguousAllocationSize() const -> size_type +{ + return m_impl->m_allocator.m_maxAllocationSize; +} + //========================================================================= // NumAllocatedBytes // [11/1/2010] @@ -1052,6 +1057,11 @@ ThreadPoolSchema::GarbageCollect() m_impl->GarbageCollect(); } +auto ThreadPoolSchema::GetMaxContiguousAllocationSize() const -> size_type +{ + return m_impl->m_maxAllocationSize; +} + //========================================================================= // NumAllocatedBytes // [11/1/2010] diff --git a/Code/Framework/AzCore/AzCore/Memory/PoolSchema.h b/Code/Framework/AzCore/AzCore/Memory/PoolSchema.h index d9c89d28bd..cfc5e3ea07 100644 --- a/Code/Framework/AzCore/AzCore/Memory/PoolSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/PoolSchema.h @@ -70,6 +70,7 @@ namespace AZ /// Return unused memory to the OS. Don't call this too often because you will force unnecessary allocations. void GarbageCollect() override; + size_type GetMaxContiguousAllocationSize() const override; size_type NumAllocatedBytes() const override; size_type Capacity() const override; IAllocatorAllocate* GetSubAllocator() override; @@ -115,6 +116,7 @@ namespace AZ /// Return unused memory to the OS. Don't call this too often because you will force unnecessary allocations. void GarbageCollect() override; + size_type GetMaxContiguousAllocationSize() const override; size_type NumAllocatedBytes() const override; size_type Capacity() const override; IAllocatorAllocate* GetSubAllocator() override; diff --git a/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h b/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h index e9d001aec3..5fbc890203 100644 --- a/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h @@ -179,6 +179,11 @@ namespace AZ return m_schema->GetMaxAllocationSize(); } + size_type GetMaxContiguousAllocationSize() const override + { + return m_schema->GetMaxContiguousAllocationSize(); + } + size_type GetUnAllocatedMemory(bool isPrint = false) const override { return m_schema->GetUnAllocatedMemory(isPrint); diff --git a/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.h b/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.h index 9fd5734dbb..c02ada5843 100644 --- a/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.h @@ -103,6 +103,7 @@ namespace AZ size_type Capacity() const override { return m_allocator->Capacity(); } /// Keep in mind this operation will execute GarbageCollect to make sure it returns, max allocation. This function WILL be slow. size_type GetMaxAllocationSize() const override { return m_allocator->GetMaxAllocationSize(); } + size_type GetMaxContiguousAllocationSize() const override { return m_allocator->GetMaxContiguousAllocationSize(); } size_type GetUnAllocatedMemory(bool isPrint = false) const override { return m_allocator->GetUnAllocatedMemory(isPrint); } IAllocatorAllocate* GetSubAllocator() override { return m_isCustom ? m_allocator : m_allocator->GetSubAllocator(); } diff --git a/Code/Framework/AzCore/AzCore/Module/Environment.cpp b/Code/Framework/AzCore/AzCore/Module/Environment.cpp index c07b7444d4..71da948a35 100644 --- a/Code/Framework/AzCore/AzCore/Module/Environment.cpp +++ b/Code/Framework/AzCore/AzCore/Module/Environment.cpp @@ -61,7 +61,7 @@ namespace AZ const char* get_name() const { return m_name; } void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return AZ_CORE_MAX_ALLOCATOR_SIZE; } + constexpr size_type max_size() const { return AZ_CORE_MAX_ALLOCATOR_SIZE; } size_type get_allocated_size() const { return 0; } bool is_lock_free() { return false; } diff --git a/Code/Framework/AzCore/AzCore/Module/Module.h b/Code/Framework/AzCore/AzCore/Module/Module.h index a4843f002c..3809bd1bb4 100644 --- a/Code/Framework/AzCore/AzCore/Module/Module.h +++ b/Code/Framework/AzCore/AzCore/Module/Module.h @@ -62,7 +62,7 @@ namespace AZ * DO NOT OVERRIDE. This method will return in the future, but at this point things reflected here are not unreflected for all ReflectContexts (Serialize, Editor, Network, Script, etc.) * Place all calls to non-component reflect functions inside of a component reflect function to ensure that your types are unreflected. */ - virtual void Reflect(AZ::ReflectContext*) final { } + void Reflect(AZ::ReflectContext*) {} /** * Override to require specific components on the system entity. diff --git a/Code/Framework/AzCore/AzCore/RTTI/BehaviorContext.h b/Code/Framework/AzCore/AzCore/RTTI/BehaviorContext.h index b436f5adab..0a1af21213 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/BehaviorContext.h +++ b/Code/Framework/AzCore/AzCore/RTTI/BehaviorContext.h @@ -594,8 +594,8 @@ namespace AZ void SetArgumentName(size_t index, const AZStd::string& name) override; const AZStd::string* GetArgumentToolTip(size_t index) const override; void SetArgumentToolTip(size_t index, const AZStd::string& name) override; - virtual void SetDefaultValue(size_t index, BehaviorDefaultValuePtr defaultValue) override; - virtual BehaviorDefaultValuePtr GetDefaultValue(size_t index) const override; + void SetDefaultValue(size_t index, BehaviorDefaultValuePtr defaultValue) override; + BehaviorDefaultValuePtr GetDefaultValue(size_t index) const override; const BehaviorParameter* GetResult() const override; void OverrideParameterTraits(size_t index, AZ::u32 addTraits, AZ::u32 removeTraits) override; diff --git a/Code/Framework/AzCore/AzCore/RTTI/RTTI.h b/Code/Framework/AzCore/AzCore/RTTI/RTTI.h index fa081a9497..acf6f64f77 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/RTTI.h +++ b/Code/Framework/AzCore/AzCore/RTTI/RTTI.h @@ -5,8 +5,8 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZCORE_RTTI_H -#define AZCORE_RTTI_H + +#pragma once #include #include @@ -44,21 +44,9 @@ namespace AZ /// RTTI typeId typedef void (* RTTI_EnumCallback)(const AZ::TypeId& /*typeId*/, void* /*userData*/); - // Disabling missing override warning because we intentionally want to allow for declaring RTTI base classes that don't impelment RTTI. -#if defined(AZ_COMPILER_CLANG) -# define AZ_PUSH_DISABLE_OVERRIDE_WARNING \ - _Pragma("clang diagnostic push") \ - _Pragma("clang diagnostic ignored \"-Winconsistent-missing-override\"") -# define AZ_POP_DISABLE_OVERRIDE_WARNING \ - _Pragma("clang diagnostic pop") -#else -# define AZ_PUSH_DISABLE_OVERRIDE_WARNING -# define AZ_POP_DISABLE_OVERRIDE_WARNING -#endif - // We require AZ_TYPE_INFO to be declared #define AZ_RTTI_COMMON() \ - AZ_PUSH_DISABLE_OVERRIDE_WARNING \ + AZ_PUSH_DISABLE_WARNING(26433, "-Winconsistent-missing-override") \ void RTTI_Enable(); \ virtual inline const AZ::TypeId& RTTI_GetType() const { return RTTI_Type(); } \ virtual inline const char* RTTI_GetTypeName() const { return RTTI_TypeName(); } \ @@ -66,7 +54,7 @@ namespace AZ virtual void RTTI_EnumTypes(AZ::RTTI_EnumCallback cb, void* userData) { RTTI_EnumHierarchy(cb, userData); } \ static inline const AZ::TypeId& RTTI_Type() { return TYPEINFO_Uuid(); } \ static inline const char* RTTI_TypeName() { return TYPEINFO_Name(); } \ - AZ_POP_DISABLE_OVERRIDE_WARNING + AZ_POP_DISABLE_WARNING //#define AZ_RTTI_1(_1) static_assert(false,"You must provide a valid classUuid!") @@ -74,8 +62,10 @@ namespace AZ #define AZ_RTTI_1() AZ_RTTI_COMMON() \ static bool RTTI_IsContainType(const AZ::TypeId& id) { return id == RTTI_Type(); } \ static void RTTI_EnumHierarchy(AZ::RTTI_EnumCallback cb, void* userData) { cb(RTTI_Type(), userData); } \ + AZ_PUSH_DISABLE_WARNING(26433, "-Winconsistent-missing-override") \ virtual inline const void* RTTI_AddressOf(const AZ::TypeId& id) const { return (id == RTTI_Type()) ? this : nullptr; } \ - virtual inline void* RTTI_AddressOf(const AZ::TypeId& id) { return (id == RTTI_Type()) ? this : nullptr; } + virtual inline void* RTTI_AddressOf(const AZ::TypeId& id) { return (id == RTTI_Type()) ? this : nullptr; } \ + AZ_POP_DISABLE_WARNING /// AZ_RTTI(BaseClass) #define AZ_RTTI_2(_1) AZ_RTTI_COMMON() \ @@ -85,14 +75,14 @@ namespace AZ static void RTTI_EnumHierarchy(AZ::RTTI_EnumCallback cb, void* userData) { \ cb(RTTI_Type(), userData); \ AZ::Internal::RttiCaller<_1>::RTTI_EnumHierarchy(cb, userData); } \ - AZ_PUSH_DISABLE_OVERRIDE_WARNING \ + AZ_PUSH_DISABLE_WARNING(26433, "-Winconsistent-missing-override") \ virtual inline const void* RTTI_AddressOf(const AZ::TypeId& id) const { \ if (id == RTTI_Type()) { return this; } \ return AZ::Internal::RttiCaller<_1>::RTTI_AddressOf(this, id); } \ virtual inline void* RTTI_AddressOf(const AZ::TypeId& id) { \ if (id == RTTI_Type()) { return this; } \ return AZ::Internal::RttiCaller<_1>::RTTI_AddressOf(this, id); } \ - AZ_POP_DISABLE_OVERRIDE_WARNING + AZ_POP_DISABLE_WARNING /// AZ_RTTI(BaseClass1,BaseClass2) #define AZ_RTTI_3(_1, _2) AZ_RTTI_COMMON() \ @@ -104,7 +94,7 @@ namespace AZ cb(RTTI_Type(), userData); \ AZ::Internal::RttiCaller<_1>::RTTI_EnumHierarchy(cb, userData); \ AZ::Internal::RttiCaller<_2>::RTTI_EnumHierarchy(cb, userData); } \ - AZ_PUSH_DISABLE_OVERRIDE_WARNING \ + AZ_PUSH_DISABLE_WARNING(26433, "-Winconsistent-missing-override") \ virtual inline const void* RTTI_AddressOf(const AZ::TypeId& id) const { \ if (id == RTTI_Type()) { return this; } \ const void* r = AZ::Internal::RttiCaller<_1>::RTTI_AddressOf(this, id); if (r) { return r; } \ @@ -113,7 +103,7 @@ namespace AZ if (id == RTTI_Type()) { return this; } \ void* r = AZ::Internal::RttiCaller<_1>::RTTI_AddressOf(this, id); if (r) { return r; } \ return AZ::Internal::RttiCaller<_2>::RTTI_AddressOf(this, id); } \ - AZ_POP_DISABLE_OVERRIDE_WARNING + AZ_POP_DISABLE_WARNING /// AZ_RTTI(BaseClass1,BaseClass2,BaseClass3) #define AZ_RTTI_4(_1, _2, _3) AZ_RTTI_COMMON() \ @@ -127,7 +117,7 @@ namespace AZ AZ::Internal::RttiCaller<_1>::RTTI_EnumHierarchy(cb, userData); \ AZ::Internal::RttiCaller<_2>::RTTI_EnumHierarchy(cb, userData); \ AZ::Internal::RttiCaller<_3>::RTTI_EnumHierarchy(cb, userData); } \ - AZ_PUSH_DISABLE_OVERRIDE_WARNING \ + AZ_PUSH_DISABLE_WARNING(26433, "-Winconsistent-missing-override") \ virtual inline const void* RTTI_AddressOf(const AZ::TypeId& id) const { \ if (id == RTTI_Type()) { return this; } \ const void* r = AZ::Internal::RttiCaller<_1>::RTTI_AddressOf(this, id); if (r) { return r; } \ @@ -138,7 +128,7 @@ namespace AZ void* r = AZ::Internal::RttiCaller<_1>::RTTI_AddressOf(this, id); if (r) { return r; } \ r = AZ::Internal::RttiCaller<_2>::RTTI_AddressOf(this, id); if (r) { return r; } \ return AZ::Internal::RttiCaller<_3>::RTTI_AddressOf(this, id); } \ - AZ_POP_DISABLE_OVERRIDE_WARNING + AZ_POP_DISABLE_WARNING /// AZ_RTTI(BaseClass1,BaseClass2,BaseClass3,BaseClass4) #define AZ_RTTI_5(_1, _2, _3, _4) AZ_RTTI_COMMON() \ @@ -154,7 +144,7 @@ namespace AZ AZ::Internal::RttiCaller<_2>::RTTI_EnumHierarchy(cb, userData); \ AZ::Internal::RttiCaller<_3>::RTTI_EnumHierarchy(cb, userData); \ AZ::Internal::RttiCaller<_4>::RTTI_EnumHierarchy(cb, userData); } \ - AZ_PUSH_DISABLE_OVERRIDE_WARNING \ + AZ_PUSH_DISABLE_WARNING(26433, "-Winconsistent-missing-override") \ virtual inline const void* RTTI_AddressOf(const AZ::TypeId& id) const { \ if (id == RTTI_Type()) { return this; } \ const void* r = AZ::Internal::RttiCaller<_1>::RTTI_AddressOf(this, id); if (r) { return r; } \ @@ -167,7 +157,7 @@ namespace AZ r = AZ::Internal::RttiCaller<_2>::RTTI_AddressOf(this, id); if (r) { return r; } \ r = AZ::Internal::RttiCaller<_3>::RTTI_AddressOf(this, id); if (r) { return r; } \ return AZ::Internal::RttiCaller<_4>::RTTI_AddressOf(this, id); } \ - AZ_POP_DISABLE_OVERRIDE_WARNING + AZ_POP_DISABLE_WARNING /// AZ_RTTI(BaseClass1,BaseClass2,BaseClass3,BaseClass4,BaseClass5) #define AZ_RTTI_6(_1, _2, _3, _4, _5) AZ_RTTI_COMMON() \ @@ -185,7 +175,7 @@ namespace AZ AZ::Internal::RttiCaller<_3>::RTTI_EnumHierarchy(cb, userData); \ AZ::Internal::RttiCaller<_4>::RTTI_EnumHierarchy(cb, userData); \ AZ::Internal::RttiCaller<_5>::RTTI_EnumHierarchy(cb, userData); } \ - AZ_PUSH_DISABLE_OVERRIDE_WARNING \ + AZ_PUSH_DISABLE_WARNING(26433, "-Winconsistent-missing-override") \ virtual inline const void* RTTI_AddressOf(const AZ::TypeId& id) const { \ if (id == RTTI_Type()) { return this; } \ const void* r = AZ::Internal::RttiCaller<_1>::RTTI_AddressOf(this, id); if (r) { return r; } \ @@ -200,7 +190,7 @@ namespace AZ r = AZ::Internal::RttiCaller<_3>::RTTI_AddressOf(this, id); if (r) { return r; } \ r = AZ::Internal::RttiCaller<_4>::RTTI_AddressOf(this, id); if (r) { return r; } \ return AZ::Internal::RttiCaller<_5>::RTTI_AddressOf(this, id); } \ - AZ_POP_DISABLE_OVERRIDE_WARNING + AZ_POP_DISABLE_WARNING ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MACRO specialization to allow optional parameters for template version of AZ_RTTI @@ -951,10 +941,7 @@ namespace AZ { return AZStd::shared_ptr(ptr, castPtr); } - else - { - return AZStd::shared_ptr(); - } + return AZStd::shared_ptr(); } // RttiCast specialization for intrusive_ptr. @@ -1077,7 +1064,6 @@ namespace AZ { return AZ::Internal::RttiIsTypeOfIdHelper::Check(id, data, typename HasAZRtti>::kind_type()); } + } // namespace AZ -#endif // AZCORE_RTTI_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptContext.cpp b/Code/Framework/AzCore/AzCore/Script/ScriptContext.cpp index 5a35603d0a..b03d413507 100644 --- a/Code/Framework/AzCore/AzCore/Script/ScriptContext.cpp +++ b/Code/Framework/AzCore/AzCore/Script/ScriptContext.cpp @@ -2306,7 +2306,7 @@ LUA_API const Node* lua_getDummyNode() else // even references are stored by value as we need to convert from lua native type, i.e. there is not real reference for NativeTypes (numbers, strings, etc.) { bool usedBackupAlloc = false; - if (backupAllocator != nullptr && sizeof(T) > tempAllocator.get_max_size()) + if (backupAllocator != nullptr && sizeof(T) > AZStd::allocator_traits::max_size(tempAllocator)) { value.m_value = backupAllocator->allocate(sizeof(T), AZStd::alignment_of::value, 0); usedBackupAlloc = true; @@ -2340,7 +2340,7 @@ LUA_API const Node* lua_getDummyNode() else // it's a value type { bool usedBackupAlloc = false; - if (backupAllocator != nullptr && valueClass->m_size > tempAllocator.get_max_size()) + if (backupAllocator != nullptr && valueClass->m_size > AZStd::allocator_traits::max_size(tempAllocator)) { value.m_value = backupAllocator->allocate(valueClass->m_size, valueClass->m_alignment, 0); usedBackupAlloc = true; diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSystemComponent.h b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSystemComponent.h index c46ba32209..a691bb1bcb 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSystemComponent.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSystemComponent.h @@ -19,8 +19,8 @@ namespace AZ public: AZ_COMPONENT(JsonSystemComponent, "{3C2C7234-9512-4E24-86F0-C40865D7EECE}", Component); - void Activate(); - void Deactivate(); + void Activate() override; + void Deactivate() override; static void Reflect(ReflectContext* reflectContext); }; diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/MapSerializer.h b/Code/Framework/AzCore/AzCore/Serialization/Json/MapSerializer.h index e0d2635fc3..937c8389ff 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/MapSerializer.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/MapSerializer.h @@ -46,7 +46,8 @@ namespace AZ public: AZ_RTTI(JsonUnorderedMapSerializer, "{EF4478D3-1820-4FDB-A7B7-C9711EB41602}", JsonMapSerializer); AZ_CLASS_ALLOCATOR_DECL; - + + using JsonMapSerializer::Store; JsonSerializationResult::Result Store(rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue, const Uuid& valueTypeId, JsonSerializerContext& context) override; }; @@ -63,6 +64,7 @@ namespace AZ const SerializeContext::ClassElement* keyElement, const SerializeContext::ClassElement* valueElement, const rapidjson::Value& key, const rapidjson::Value& value, JsonDeserializerContext& context) override; + using JsonMapSerializer::Store; JsonSerializationResult::Result Store(rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue, const Uuid& valueTypeId, JsonSerializerContext& context) override; }; diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h index 106e232904..3dc1be87c5 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistry.h @@ -370,6 +370,11 @@ namespace AZ //! @param applyPatchSettings The ApplyPatchSettings which are using during JSON Merging virtual void SetApplyPatchSettings(const AZ::JsonApplyPatchSettings& applyPatchSettings) = 0; virtual void GetApplyPatchSettings(AZ::JsonApplyPatchSettings& applyPatchSettings) = 0; + + //! Stores option to indicate whether the FileIOBase instance should be used for file operations + //! @param useFileIo If true the FileIOBase instance will attempted to be used for FileIOBase + //! operations before falling back to use SystemFile + virtual void SetUseFileIO(bool useFileIo) = 0; }; inline SettingsRegistryInterface::Visitor::~Visitor() = default; diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp index 6864dcd1c8..7ef1fa661d 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.cpp @@ -9,11 +9,14 @@ #include #include #include +#include +#include #include #include #include #include #include +#include #include #include @@ -131,6 +134,12 @@ namespace AZ pointer.Create(m_settings, m_settings.GetAllocator()).SetArray(); } + SettingsRegistryImpl::SettingsRegistryImpl(bool useFileIo) + : SettingsRegistryImpl() + { + m_useFileIo = useFileIo; + } + void SettingsRegistryImpl::SetContext(SerializeContext* context) { AZStd::scoped_lock lock(m_settingMutex); @@ -723,15 +732,10 @@ namespace AZ RegistryFileList fileList; scratchBuffer->clear(); - AZ::IO::FixedMaxPathString folderPath{ path }; - constexpr AZStd::string_view pathSeparators{ AZ_CORRECT_AND_WRONG_DATABASE_SEPARATOR }; - if (pathSeparators.find_first_of(folderPath.back()) == AZStd::string_view::npos) - { - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); - } + AZ::IO::FixedMaxPath folderPath{ path }; - const size_t platformKeyOffset = folderPath.size(); - folderPath.push_back('*'); + const size_t platformKeyOffset = folderPath.Native().size(); + folderPath /= '*'; Value specialzationArray(kArrayType); size_t specializationCount = specializations.GetCount(); @@ -741,47 +745,13 @@ namespace AZ specialzationArray.PushBack(Value(name.data(), aznumeric_caster(name.length()), m_settings.GetAllocator()), m_settings.GetAllocator()); } pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() - .AddMember(StringRef("Folder"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator()) + .AddMember(StringRef("Folder"), Value(folderPath.c_str(), aznumeric_caster(folderPath.Native().size()), m_settings.GetAllocator()), m_settings.GetAllocator()) .AddMember(StringRef("Specializations"), AZStd::move(specialzationArray), m_settings.GetAllocator()); - auto callback = [this, &fileList, &specializations, &pointer, &folderPath](const char* filename, bool isFile) -> bool + + auto CreateSettingsFindCallback = [this, &fileList, &specializations, &pointer, &folderPath](bool isPlatformFile) { - if (isFile) - { - if (fileList.size() >= MaxRegistryFolderEntries) - { - AZ_Error("Settings Registry", false, "Too many files in registry folder."); - AZStd::scoped_lock lock(m_settingMutex); - pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() - .AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator()) - .AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator()) - .AddMember(StringRef("File"), Value(filename, m_settings.GetAllocator()), m_settings.GetAllocator()); - return false; - } - - fileList.push_back(); - RegistryFile& registryFile = fileList.back(); - if (!ExtractFileDescription(registryFile, filename, specializations)) - { - fileList.pop_back(); - } - } - return true; - }; - SystemFile::FindFiles(folderPath.c_str(), callback); - - - if (!platform.empty()) - { - // Move the folderPath prefix back to the supplied path before the wildcard - folderPath.erase(platformKeyOffset); - folderPath += PlatformFolder; - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); - folderPath += platform; - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); - folderPath.push_back('*'); - - auto platformCallback = [this, &fileList, &specializations, &pointer, &folderPath](const char* filename, bool isFile) -> bool + return [this, &fileList, &specializations, &pointer, &folderPath, isPlatformFile](AZStd::string_view filename, bool isFile) -> bool { if (isFile) { @@ -791,8 +761,8 @@ namespace AZ AZStd::scoped_lock lock(m_settingMutex); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() .AddMember(StringRef("Error"), StringRef("Too many files in registry folder."), m_settings.GetAllocator()) - .AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.size()), m_settings.GetAllocator()), m_settings.GetAllocator()) - .AddMember(StringRef("File"), Value(filename, m_settings.GetAllocator()), m_settings.GetAllocator()); + .AddMember(StringRef("Path"), Value(folderPath.c_str(), aznumeric_caster(folderPath.Native().size()), m_settings.GetAllocator()), m_settings.GetAllocator()) + .AddMember(StringRef("File"), Value(filename.data(), aznumeric_caster(filename.size()), m_settings.GetAllocator()), m_settings.GetAllocator()); return false; } @@ -800,7 +770,7 @@ namespace AZ RegistryFile& registryFile = fileList.back(); if (ExtractFileDescription(registryFile, filename, specializations)) { - registryFile.m_isPlatformFile = true; + registryFile.m_isPlatformFile = isPlatformFile; } else { @@ -809,7 +779,42 @@ namespace AZ } return true; }; - SystemFile::FindFiles(folderPath.c_str(), platformCallback); + }; + + struct FindFilesPayload + { + bool m_isPlatformFile{}; + AZStd::fixed_vector m_pathSegmentsToAppend; + }; + + AZStd::fixed_vector findFilesPayloads{ {false} }; + if (!platform.empty()) + { + findFilesPayloads.push_back(FindFilesPayload{ true, { PlatformFolder, platform } }); + } + + for (const FindFilesPayload& findFilesPayload : findFilesPayloads) + { + // Erase back to initial path + folderPath.Native().erase(platformKeyOffset); + for (AZStd::string_view pathSegmentToAppend : findFilesPayload.m_pathSegmentsToAppend) + { + folderPath /= pathSegmentToAppend; + } + + auto findFilesCallback = CreateSettingsFindCallback(findFilesPayload.m_isPlatformFile); + if (AZ::IO::FileIOBase* fileIo = m_useFileIo ? AZ::IO::FileIOBase::GetInstance() : nullptr; fileIo != nullptr) + { + auto FileIoToSystemFileFindFiles = [findFilesCallback = AZStd::move(findFilesCallback), fileIo](const char* filePath) -> bool + { + return findFilesCallback(AZ::IO::PathView(filePath).Filename().Native(), !fileIo->IsDirectory(filePath)); + }; + fileIo->FindFiles(folderPath.c_str(), "*", FileIoToSystemFileFindFiles); + } + else + { + SystemFile::FindFiles((folderPath / "*").c_str(), findFilesCallback); + } } if (!fileList.empty()) @@ -831,16 +836,14 @@ namespace AZ // Load the registry files in the sorted order. for (RegistryFile& registryFile : fileList) { - folderPath.erase(platformKeyOffset); // Erase all characters after the platformKeyOffset + folderPath.Native().erase(platformKeyOffset); // Erase all characters after the platformKeyOffset if (registryFile.m_isPlatformFile) { - folderPath += PlatformFolder; - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); - folderPath += platform; - folderPath.push_back(AZ_CORRECT_DATABASE_SEPARATOR); + folderPath /= PlatformFolder; + folderPath /= platform; } - folderPath += registryFile.m_relativePath; + folderPath /= registryFile.m_relativePath; if (!registryFile.m_isPatch) { @@ -1027,39 +1030,44 @@ namespace AZ return false; } - bool SettingsRegistryImpl::ExtractFileDescription(RegistryFile& output, const char* filename, const Specializations& specializations) + bool SettingsRegistryImpl::ExtractFileDescription(RegistryFile& output, AZStd::string_view filename, const Specializations& specializations) { - if (!filename || filename[0] == 0) + static constexpr auto PatchExtensionWithDot = AZStd::fixed_string<32>(".") + PatchExtension; + static constexpr auto ExtensionWithDot = AZStd::fixed_string<32>(".") + Extension; + static constexpr AZ::IO::PathView PatchExtensionView(PatchExtensionWithDot); + static constexpr AZ::IO::PathView ExtensionView(ExtensionWithDot); + + if (filename.empty()) { AZ_Error("Settings Registry", false, "Settings file without name found"); return false; } - AZStd::string_view filePath{ filename }; - const size_t filePathSize = filePath.size(); + AZ::IO::PathView filePath{ filename }; + const size_t filePathSize = filePath.Native().size(); // The filePath.empty() check makes sure that the file extension after the final isn't added to the output.m_tags - AZStd::optional pathTag = AZ::StringFunc::TokenizeNext(filePath, '.'); - for (; pathTag && !filePath.empty(); pathTag = AZ::StringFunc::TokenizeNext(filePath, '.')) + auto AppendSpecTags = [&output](AZStd::string_view pathTag) { - output.m_tags.push_back(Specializations::Hash(*pathTag)); - } + output.m_tags.push_back(Specializations::Hash(pathTag)); + }; + AZ::StringFunc::TokenizeVisitor(filePath.Stem().Native(), AppendSpecTags, '.'); // If token is invalid, then the filename has no characters and therefore no extension - if (pathTag) + if (AZ::IO::PathView fileExtension = filePath.Extension(); !fileExtension.empty()) { - if (pathTag->size() >= AZStd::char_traits::length(PatchExtension) && azstrnicmp(pathTag->data(), PatchExtension, pathTag->size()) == 0) + if (fileExtension == PatchExtensionView) { output.m_isPatch = true; } - else if (pathTag->size() != AZStd::char_traits::length(Extension) || azstrnicmp(pathTag->data(), Extension, pathTag->size()) != 0) + else if (fileExtension != ExtensionView) { return false; } } else { - AZ_Error("Settings Registry", false, R"(Settings file without extension found: "%s")", filename); + AZ_Error("Settings Registry", false, R"(Settings file without extension found: "%.*s")", AZ_STRING_ARG(filename)); return false; } @@ -1074,7 +1082,7 @@ namespace AZ { if (*currentIt == *(currentIt - 1)) { - AZ_Error("Settings Registry", false, R"(One or more tags are duplicated in registry file "%s")", filename); + AZ_Error("Settings Registry", false, R"(One or more tags are duplicated in registry file "%.*s")", AZ_STRING_ARG(filename)); return false; } ++currentIt; @@ -1103,11 +1111,123 @@ namespace AZ } else { - AZ_Error("Settings Registry", false, R"(Found relative path to settings file "%s" is too long.)", filename); + AZ_Error("Settings Registry", false, R"(Found relative path to settings file "%.*s" is too long.)", AZ_STRING_ARG(filename)); return false; } } + //! Structure which encapsulates Commands to either the FileIOBase or SystemFile classes based on + //! the SettingsRegistry option to use FileIO + struct SettingsRegistryFileReader + { + using FileHandleType = AZStd::variant; + + SettingsRegistryFileReader() = default; + SettingsRegistryFileReader(bool useFileIo, const char* filePath) + { + Open(useFileIo, filePath); + } + + ~SettingsRegistryFileReader() + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + if (AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance(); fileIo != nullptr) + { + fileIo->Close(*fileHandle); + } + } + } + + bool Open(bool useFileIo, const char* filePath) + { + Close(); + if (AZ::IO::FileIOBase* fileIo = useFileIo ? AZ::IO::FileIOBase::GetInstance() : nullptr; fileIo != nullptr) + { + AZ::IO::HandleType fileHandle; + if (fileIo->Open(filePath, IO::OpenMode::ModeRead, fileHandle)) + { + m_file = fileHandle; + return true; + } + } + else + { + AZ::IO::SystemFile file; + if (file.Open(filePath, IO::SystemFile::OpenMode::SF_OPEN_READ_ONLY)) + { + m_file = AZStd::move(file); + return true; + } + } + + return false; + } + + bool IsOpen() const + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + return *fileHandle != AZ::IO::InvalidHandle; + } + else if (auto systemFile = AZStd::get_if(&m_file); systemFile != nullptr) + { + return systemFile->IsOpen(); + } + + return false; + } + + void Close() + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + if (AZ::IO::FileIOBase* fileIo = AZ::IO::FileIOBase::GetInstance(); fileIo != nullptr) + { + fileIo->Close(*fileHandle); + } + } + + m_file = AZStd::monostate{}; + } + + u64 Length() const + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + if (u64 fileSize{}; AZ::IO::FileIOBase::GetInstance()->Size(*fileHandle, fileSize)) + { + return fileSize; + } + } + else if (auto systemFile = AZStd::get_if(&m_file); systemFile != nullptr) + { + return systemFile->Length(); + } + + return 0; + } + + AZ::IO::SizeType Read(AZ::IO::SizeType byteSize, void* buffer) + { + if (auto fileHandle = AZStd::get_if(&m_file); fileHandle != nullptr) + { + if (AZ::u64 bytesRead{}; AZ::IO::FileIOBase::GetInstance()->Read(*fileHandle, buffer, byteSize, false, &bytesRead)) + { + return bytesRead; + } + } + else if (auto systemFile = AZStd::get_if(&m_file); systemFile != nullptr) + { + return systemFile->Read(byteSize, buffer); + } + + return 0; + } + + FileHandleType m_file; + }; + bool SettingsRegistryImpl::MergeSettingsFileInternal(const char* path, Format format, AZStd::string_view rootKey, AZStd::vector& scratchBuffer) { @@ -1116,8 +1236,8 @@ namespace AZ Pointer pointer(AZ_SETTINGS_REGISTRY_HISTORY_KEY "/-"); - SystemFile file; - if (!file.Open(path, SystemFile::OpenMode::SF_OPEN_READ_ONLY)) + SettingsRegistryFileReader fileReader(m_useFileIo, path); + if (!fileReader.IsOpen()) { AZ_Error("Settings Registry", false, R"(Unable to open registry file "%s".)", path); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() @@ -1126,7 +1246,7 @@ namespace AZ return false; } - u64 fileSize = file.Length(); + u64 fileSize = fileReader.Length(); if (fileSize == 0) { AZ_Warning("Settings Registry", false, R"(Registry file "%s" is 0 bytes in length. There is no nothing to merge)", path); @@ -1136,9 +1256,10 @@ namespace AZ .AddMember(StringRef("Path"), Value(path, m_settings.GetAllocator()), m_settings.GetAllocator()); return false; } + scratchBuffer.clear(); scratchBuffer.resize_no_construct(fileSize + 1); - if (file.Read(fileSize, scratchBuffer.data()) != fileSize) + if (fileReader.Read(fileSize, scratchBuffer.data()) != fileSize) { AZ_Error("Settings Registry", false, R"(Unable to read registry file "%s".)", path); pointer.Create(m_settings, m_settings.GetAllocator()).SetObject() @@ -1268,4 +1389,9 @@ namespace AZ { applyPatchSettings = m_applyPatchSettings; } + + void SettingsRegistryImpl::SetUseFileIO(bool useFileIo) + { + m_useFileIo = useFileIo; + } } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h index 036f5c6596..ac214711b8 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryImpl.h @@ -35,6 +35,10 @@ namespace AZ static constexpr size_t MaxRegistryFolderEntries = 128; SettingsRegistryImpl(); + //! @param useFileIo - If true attempt to redirect + //! file read operations through the FileIOBase instance first before falling back to SystemFile + //! otherwise always use SystemFile + explicit SettingsRegistryImpl(bool useFileIo); AZ_DISABLE_COPY_MOVE(SettingsRegistryImpl); ~SettingsRegistryImpl() override = default; @@ -83,6 +87,8 @@ namespace AZ void SetApplyPatchSettings(const AZ::JsonApplyPatchSettings& applyPatchSettings) override; void GetApplyPatchSettings(AZ::JsonApplyPatchSettings& applyPatchSettings) override; + void SetUseFileIO(bool useFileIo) override; + private: using TagList = AZStd::fixed_vector; struct RegistryFile @@ -104,7 +110,7 @@ namespace AZ // Compares if lhs is less than rhs in terms of processing order. This can also detect and report conflicts. bool IsLessThan(bool& collisionFound, const RegistryFile& lhs, const RegistryFile& rhs, const Specializations& specializations, const rapidjson::Pointer& historyPointer, AZStd::string_view folderPath); - bool ExtractFileDescription(RegistryFile& output, const char* filename, const Specializations& specializations); + bool ExtractFileDescription(RegistryFile& output, AZStd::string_view filename, const Specializations& specializations); bool MergeSettingsFileInternal(const char* path, Format format, AZStd::string_view rootKey, AZStd::vector& scratchBuffer); void SignalNotifier(AZStd::string_view jsonPath, Type type); @@ -119,5 +125,7 @@ namespace AZ JsonSerializerSettings m_serializationSettings; JsonDeserializerSettings m_deserializationSettings; JsonApplyPatchSettings m_applyPatchSettings; + + bool m_useFileIo{}; }; } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp index 71ffece892..5290c9b02a 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.cpp @@ -78,6 +78,7 @@ namespace AZ::Internal struct EnginePathsVisitor : public AZ::SettingsRegistryInterface::Visitor { + using AZ::SettingsRegistryInterface::Visitor::Visit; void Visit( [[maybe_unused]] AZStd::string_view path, AZStd::string_view valueName, [[maybe_unused]] AZ::SettingsRegistryInterface::Type type, AZStd::string_view value) override @@ -355,6 +356,7 @@ namespace AZ::SettingsRegistryMergeUtils : m_settingsSpecialization{ specializations } {} + using AZ::SettingsRegistryInterface::Visitor::Visit; void Visit([[maybe_unused]] AZStd::string_view path, AZStd::string_view valueName, [[maybe_unused]] AZ::SettingsRegistryInterface::Type type, bool value) override { @@ -761,6 +763,7 @@ namespace AZ::SettingsRegistryMergeUtils return SettingsRegistryInterface::VisitResponse::Continue; } + using AZ::SettingsRegistryInterface::Visitor::Visit; void Visit(AZStd::string_view, [[maybe_unused]] AZStd::string_view valueName, SettingsRegistryInterface::Type, AZStd::string_view value) override { if (processingSourcePathKey) @@ -896,6 +899,7 @@ namespace AZ::SettingsRegistryMergeUtils struct CommandLineVisitor : AZ::SettingsRegistryInterface::Visitor { + using AZ::SettingsRegistryInterface::Visitor::Visit; void Visit(AZStd::string_view, AZStd::string_view valueName, AZ::SettingsRegistryInterface::Type , AZStd::string_view value) override { diff --git a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h index 7e6bb3d7b4..91dc0924c8 100644 --- a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h +++ b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockSettingsRegistry.h @@ -57,6 +57,7 @@ namespace AZ MOCK_METHOD1(SetApplyPatchSettings, void(const JsonApplyPatchSettings&)); MOCK_METHOD1(GetApplyPatchSettings, void(JsonApplyPatchSettings&)); + MOCK_METHOD1(SetUseFileIO, void(bool)); }; } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/UnitTest/TestTypes.h b/Code/Framework/AzCore/AzCore/UnitTest/TestTypes.h index c3e3f5210a..e5dcb32d9d 100644 --- a/Code/Framework/AzCore/AzCore/UnitTest/TestTypes.h +++ b/Code/Framework/AzCore/AzCore/UnitTest/TestTypes.h @@ -45,7 +45,7 @@ namespace UnitTest virtual ~AllocatorsBase() = default; - void SetupAllocator() + void SetupAllocator(const AZ::SystemAllocator::Descriptor& allocatorDesc = {}) { m_drillerManager = AZ::Debug::DrillerManager::Create(); m_drillerManager->Register(aznew AZ::Debug::MemoryDriller); @@ -54,7 +54,7 @@ namespace UnitTest // Only create the SystemAllocator if it s not ready if (!AZ::AllocatorInstance::IsReady()) { - AZ::AllocatorInstance::Create(); + AZ::AllocatorInstance::Create(allocatorDesc); m_ownsAllocator = true; } } @@ -85,6 +85,7 @@ namespace UnitTest { public: ScopedAllocatorSetupFixture() { SetupAllocator(); } + explicit ScopedAllocatorSetupFixture(const AZ::SystemAllocator::Descriptor& allocatorDesc) { SetupAllocator(allocatorDesc); } ~ScopedAllocatorSetupFixture() { TeardownAllocator(); } }; @@ -130,17 +131,23 @@ namespace UnitTest , public AllocatorsBase { public: - // Bring in both const and non-const SetUp and TearDown function into scope to resolve warning 4266 - // no override available for virtual member function from base 'benchmark::Fixture'; function is hidden - using ::benchmark::Fixture::SetUp, ::benchmark::Fixture::TearDown; - //Benchmark interface + void SetUp(const ::benchmark::State& st) override + { + AZ_UNUSED(st); + SetupAllocator(); + } void SetUp(::benchmark::State& st) override { AZ_UNUSED(st); SetupAllocator(); } + void TearDown(const ::benchmark::State& st) override + { + AZ_UNUSED(st); + TeardownAllocator(); + } void TearDown(::benchmark::State& st) override { AZ_UNUSED(st); diff --git a/Code/Framework/AzCore/AzCore/UserSettings/UserSettingsProvider.h b/Code/Framework/AzCore/AzCore/UserSettings/UserSettingsProvider.h index 4721d3baa8..6a807c915e 100644 --- a/Code/Framework/AzCore/AzCore/UserSettings/UserSettingsProvider.h +++ b/Code/Framework/AzCore/AzCore/UserSettings/UserSettingsProvider.h @@ -116,9 +116,9 @@ namespace AZ ////////////////////////////////////////////////////////////////////////// // UserSettingsBus - virtual AZStd::intrusive_ptr FindUserSettings(u32 id); - virtual void AddUserSettings(u32 id, UserSettings* settings); - virtual bool Save(const char* settingsPath, SerializeContext* sc); + AZStd::intrusive_ptr FindUserSettings(u32 id) override; + void AddUserSettings(u32 id, UserSettings* settings) override; + bool Save(const char* settingsPath, SerializeContext* sc) override; ////////////////////////////////////////////////////////////////////////// static void Reflect(ReflectContext* reflection); diff --git a/Code/Framework/AzCore/AzCore/XML/rapidxml.h b/Code/Framework/AzCore/AzCore/XML/rapidxml.h index 694e0a1bf6..9e6d648293 100644 --- a/Code/Framework/AzCore/AzCore/XML/rapidxml.h +++ b/Code/Framework/AzCore/AzCore/XML/rapidxml.h @@ -13,6 +13,7 @@ // the intention is that you only include the customized version of rapidXML through this header, so that // you can override behavior here. +#include #include #endif // AZCORE_RAPIDXML_RAPIDXML_H_INCLUDED diff --git a/Code/Framework/AzCore/AzCore/std/algorithm.h b/Code/Framework/AzCore/AzCore/std/algorithm.h index 3508eff2b4..e28d127062 100644 --- a/Code/Framework/AzCore/AzCore/std/algorithm.h +++ b/Code/Framework/AzCore/AzCore/std/algorithm.h @@ -831,7 +831,6 @@ namespace AZStd // find first element that value is before, using operator< typename iterator_traits::difference_type count = AZStd::distance(first, last); typename iterator_traits::difference_type step{}; - count = AZStd::distance(first, last); for (; 0 < count; ) { // divide and conquer, find half that contains answer step = count / 2; diff --git a/Code/Framework/AzCore/AzCore/std/allocator.cpp b/Code/Framework/AzCore/AzCore/std/allocator.cpp index 0aaad5a5a8..fdf1903882 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator.cpp +++ b/Code/Framework/AzCore/AzCore/std/allocator.cpp @@ -40,15 +40,11 @@ namespace AZStd return AZ::AllocatorInstance::Get().Resize(ptr, newSize); } - //========================================================================= - // get_max_size - // [1/1/2008] - //========================================================================= - allocator::size_type - allocator::get_max_size() const + auto allocator::max_size() const -> size_type { - return AZ::AllocatorInstance::Get().GetMaxAllocationSize(); + return AZ::AllocatorInstance::Get().GetMaxContiguousAllocationSize(); } + //========================================================================= // get_allocated_size // [1/1/2008] diff --git a/Code/Framework/AzCore/AzCore/std/allocator.h b/Code/Framework/AzCore/AzCore/std/allocator.h index 0fee5481e2..225350e883 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator.h +++ b/Code/Framework/AzCore/AzCore/std/allocator.h @@ -49,8 +49,8 @@ namespace AZStd * const char* get_name() const; * void set_name(const char* name); * - * // Returns maximum size we can allocate from this allocator. - * size_type get_max_size() const; + * // Returns theoretical maximum size of a single contiguous allocation from this allocator. + * size_type max_size() const; * size_type get_allocated_size() const; * }; * @@ -100,7 +100,8 @@ namespace AZStd pointer_type allocate(size_type byteSize, size_type alignment, int flags = 0); void deallocate(pointer_type ptr, size_type byteSize, size_type alignment); size_type resize(pointer_type ptr, size_type newSize); - size_type get_max_size() const; + // max_size actually returns the true maximum size of a single allocation + size_type max_size() const; size_type get_allocated_size() const; AZ_FORCE_INLINE bool is_lock_free() { return false; } @@ -157,7 +158,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const; AZ_FORCE_INLINE void set_name(const char* name); - AZ_FORCE_INLINE size_type get_max_size() const; + AZ_FORCE_INLINE size_type max_size() const; AZ_FORCE_INLINE bool is_lock_free(); AZ_FORCE_INLINE bool is_stale_read_allowed(); diff --git a/Code/Framework/AzCore/AzCore/std/allocator_ref.h b/Code/Framework/AzCore/AzCore/std/allocator_ref.h index 659ee0cc8f..62a3cf68de 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator_ref.h +++ b/Code/Framework/AzCore/AzCore/std/allocator_ref.h @@ -41,7 +41,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return m_allocator->get_max_size(); } + constexpr size_type max_size() const { return m_allocator->max_size(); } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_allocator->get_allocated_size(); } diff --git a/Code/Framework/AzCore/AzCore/std/allocator_stack.h b/Code/Framework/AzCore/AzCore/std/allocator_stack.h index 202e62bd0f..d8546bfd18 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator_stack.h +++ b/Code/Framework/AzCore/AzCore/std/allocator_stack.h @@ -59,7 +59,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return m_size - (m_freeData - m_data); } + constexpr size_type max_size() const { return m_size; } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_freeData - m_data; } pointer_type allocate(size_type byteSize, size_type alignment, int flags = 0) diff --git a/Code/Framework/AzCore/AzCore/std/allocator_static.h b/Code/Framework/AzCore/AzCore/std/allocator_static.h index 0c079eaa9d..7f793c6d6b 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator_static.h +++ b/Code/Framework/AzCore/AzCore/std/allocator_static.h @@ -63,7 +63,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return Size - (m_freeData - reinterpret_cast(&m_data)); } + constexpr size_type max_size() const { return Size; } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_freeData - reinterpret_cast(&m_data); } pointer_type allocate(size_type byteSize, size_type alignment, int flags = 0) @@ -190,7 +190,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return (NumNodes - m_numOfAllocatedNodes) * sizeof(Node); } + constexpr size_type max_size() const { return NumNodes * sizeof(Node); } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_numOfAllocatedNodes * sizeof(Node); } inline Node* allocate() diff --git a/Code/Framework/AzCore/AzCore/std/containers/deque.h b/Code/Framework/AzCore/AzCore/std/containers/deque.h index 215845a8f4..db585e0ec9 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/deque.h +++ b/Code/Framework/AzCore/AzCore/std/containers/deque.h @@ -6,11 +6,10 @@ * */ #pragma once -#ifndef AZSTD_DEQUE_H -#define AZSTD_DEQUE_H 1 #include +#include #include #include #include @@ -350,7 +349,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_size; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.get_max_size() / sizeof(block_node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(block_node_type); } AZ_FORCE_INLINE bool empty() const { return m_size == 0; } AZ_FORCE_INLINE const_reference at(size_type offset) const { return *const_iterator(AZSTD_CHECKED_ITERATOR_2(const_iterator_impl, m_firstOffset + offset, this)); } @@ -1243,5 +1242,3 @@ namespace AZStd return removedCount; } } - -#endif // AZSTD_DEQUE_H diff --git a/Code/Framework/AzCore/AzCore/std/containers/forward_list.h b/Code/Framework/AzCore/AzCore/std/containers/forward_list.h index c311991ee3..407d65ffa9 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/forward_list.h +++ b/Code/Framework/AzCore/AzCore/std/containers/forward_list.h @@ -286,7 +286,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_numElements; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } AZ_FORCE_INLINE bool empty() const { return (m_numElements == 0); } AZ_FORCE_INLINE iterator begin() { return iterator(AZSTD_CHECKED_ITERATOR(iterator_impl, m_head.m_next)); } diff --git a/Code/Framework/AzCore/AzCore/std/containers/list.h b/Code/Framework/AzCore/AzCore/std/containers/list.h index 124d8b7d7c..60d2977749 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/list.h +++ b/Code/Framework/AzCore/AzCore/std/containers/list.h @@ -5,11 +5,11 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZSTD_LIST_H -#define AZSTD_LIST_H 1 + #pragma once #include +#include #include #include #include @@ -316,7 +316,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_numElements; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } AZ_FORCE_INLINE bool empty() const { return (m_numElements == 0); } AZ_FORCE_INLINE iterator begin() { return iterator(AZSTD_CHECKED_ITERATOR(iterator_impl, m_head.m_next)); } @@ -1346,5 +1346,3 @@ namespace AZStd return container.remove_if(predicate); } } - -#endif // AZSTD_LIST_H diff --git a/Code/Framework/AzCore/AzCore/std/containers/rbtree.h b/Code/Framework/AzCore/AzCore/std/containers/rbtree.h index c8f0883eaf..fd268f4936 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/rbtree.h +++ b/Code/Framework/AzCore/AzCore/std/containers/rbtree.h @@ -484,7 +484,7 @@ namespace AZStd AZ_FORCE_INLINE bool empty() const { return m_numElements == 0; } AZ_FORCE_INLINE size_type size() const { return m_numElements; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } rbtree(this_type&& rhs) : m_numElements(0) // it will be set during swap diff --git a/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h b/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h index 7e84124958..d8c3c6ecda 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h +++ b/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h @@ -5,10 +5,11 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZSTD_RINGBUFFER_H -#define AZSTD_RINGBUFFER_H 1 + +#pragma once #include +#include #include #include #include @@ -416,7 +417,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_size; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } AZ_FORCE_INLINE bool empty() const { return m_size == 0; } AZ_FORCE_INLINE bool full() const { return size_type(m_end - m_buff) == m_size; } AZ_FORCE_INLINE size_type free() const { return size_type(m_end - m_buff) - m_size; } @@ -1240,6 +1241,3 @@ namespace AZStd lhs.swap(rhs); } } - -#endif // AZSTD_RINGBUFFER_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/containers/vector.h b/Code/Framework/AzCore/AzCore/std/containers/vector.h index bf02527d77..48de12a5b4 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/vector.h +++ b/Code/Framework/AzCore/AzCore/std/containers/vector.h @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -431,7 +432,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_last - m_start; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.get_max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } AZ_FORCE_INLINE bool empty() const { return m_start == m_last; } void reserve(size_type numElements) diff --git a/Code/Framework/AzCore/AzCore/std/parallel/allocator_concurrent_static.h b/Code/Framework/AzCore/AzCore/std/parallel/allocator_concurrent_static.h index 72c687beab..b9cd5207dd 100644 --- a/Code/Framework/AzCore/AzCore/std/parallel/allocator_concurrent_static.h +++ b/Code/Framework/AzCore/AzCore/std/parallel/allocator_concurrent_static.h @@ -22,7 +22,7 @@ namespace AZStd * Internally the buffer is allocated using aligned_storage. * \note only allocate/deallocate are thread safe. * reset, leak_before_destroy and comparison operators are not thread safe. - * get_max_size and get_allocated_size are thread safe but the returned value is not perfectly in + * get_allocated_size is thread safe but the returned value is not perfectly in * sync on the actual number of allocations (the number of allocations is incremented before the * allocation happens and decremented after the allocation happens, trying to give a conservative * number) @@ -71,7 +71,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return (NumNodes - m_numOfAllocatedNodes.load(AZStd::memory_order_relaxed)) * sizeof(Node); } + constexpr size_type max_size() const { return NumNodes * sizeof(Node); } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_numOfAllocatedNodes.load(AZStd::memory_order_relaxed) * sizeof(Node); } inline Node* allocate() diff --git a/Code/Framework/AzCore/AzCore/std/parallel/thread.h b/Code/Framework/AzCore/AzCore/std/parallel/thread.h index 9f7830c91b..15d8c9dc8e 100644 --- a/Code/Framework/AzCore/AzCore/std/parallel/thread.h +++ b/Code/Framework/AzCore/AzCore/std/parallel/thread.h @@ -187,7 +187,7 @@ namespace AZStd : m_f(AZStd::move(f)) {} thread_info_impl(Internal::thread_move_t f) : m_f(f) {} - virtual void execute() { m_f(); } + void execute() override { m_f(); } private: F m_f; diff --git a/Code/Framework/AzCore/AzCore/std/smart_ptr/shared_count.h b/Code/Framework/AzCore/AzCore/std/smart_ptr/shared_count.h index c86adbd69e..ac49dc9ae5 100644 --- a/Code/Framework/AzCore/AzCore/std/smart_ptr/shared_count.h +++ b/Code/Framework/AzCore/AzCore/std/smart_ptr/shared_count.h @@ -129,16 +129,16 @@ namespace AZStd { } - virtual void dispose() // nothrow + void dispose() override // nothrow { AZStd::checked_delete(px_); } - virtual void destroy() // nothrow + void destroy() override // nothrow { this->~this_type(); a_.deallocate(this, sizeof(this_type), AZStd::alignment_of::value); } - virtual void* get_deleter(Internal::sp_typeinfo const&) + void* get_deleter(Internal::sp_typeinfo const&) override { return 0; } @@ -176,18 +176,18 @@ namespace AZStd { } - virtual void dispose() // nothrow + void dispose() override // nothrow { d_(p_); } - virtual void destroy() // nothrow + void destroy() override // nothrow { this->~this_type(); a_.deallocate(this, sizeof(this_type), AZStd::alignment_of::value); } - virtual void* get_deleter(Internal::sp_typeinfo const& ti) + void* get_deleter(Internal::sp_typeinfo const& ti) override { return ti == aztypeid(D) ? &reinterpret_cast(d_) : 0; } diff --git a/Code/Framework/AzCore/AzCore/std/string/fixed_string.h b/Code/Framework/AzCore/AzCore/std/string/fixed_string.h index 079fe40cda..b68f21784b 100644 --- a/Code/Framework/AzCore/AzCore/std/string/fixed_string.h +++ b/Code/Framework/AzCore/AzCore/std/string/fixed_string.h @@ -96,6 +96,10 @@ namespace AZStd && !is_convertible_v>> constexpr basic_fixed_string(const T& convertibleToView, size_type rhsOffset, size_type count); + + // #12 + constexpr basic_fixed_string(AZStd::nullptr_t) = delete; + constexpr operator AZStd::basic_string_view() const; constexpr auto begin() -> iterator; @@ -120,6 +124,7 @@ namespace AZStd constexpr auto operator=(const T& convertible_to_view) -> AZStd::enable_if_t> && !is_convertible_v, basic_fixed_string&>; + constexpr auto operator=(AZStd::nullptr_t) -> basic_fixed_string& = delete; constexpr auto operator+=(const basic_fixed_string& rhs) -> basic_fixed_string&; constexpr auto operator+=(const_pointer ptr) -> basic_fixed_string&; diff --git a/Code/Framework/AzCore/AzCore/std/string/regex.h b/Code/Framework/AzCore/AzCore/std/string/regex.h index 2ca223937b..3d4a2a0b38 100644 --- a/Code/Framework/AzCore/AzCore/std/string/regex.h +++ b/Code/Framework/AzCore/AzCore/std/string/regex.h @@ -215,6 +215,7 @@ namespace AZStd struct ErrorSink { + virtual ~ErrorSink() = default; virtual void RegexError(regex_constants::error_type code) = 0; }; } @@ -1079,7 +1080,7 @@ namespace AZStd NodeBase* m_next; NodeBase* m_previous; - virtual ~NodeBase() { } + virtual ~NodeBase() = default; }; inline void DestroyNode(NodeBase* node, NodeBase* end = nullptr) @@ -1758,7 +1759,7 @@ namespace AZStd return (*this); } - ~basic_regex() + ~basic_regex() override { // destroy the object Clear(); } @@ -2916,7 +2917,7 @@ namespace AZStd } template - inline NodeBase* Builder::BeginGroup(void) + inline NodeBase* Builder::BeginGroup() { // add group node return (NewNode(NT_group)); } @@ -3026,7 +3027,7 @@ namespace AZStd } template - inline RootNode* Builder::EndPattern(void) + inline RootNode* Builder::EndPattern() { // wrap up NewNode(NT_end); return m_root; diff --git a/Code/Framework/AzCore/AzCore/std/string/string.h b/Code/Framework/AzCore/AzCore/std/string/string.h index ad3546ab09..9ef7ea3086 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string.h +++ b/Code/Framework/AzCore/AzCore/std/string/string.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -167,6 +168,9 @@ namespace AZStd { } + // C++23 overload to prevent initializing a string_view via a nullptr or integer type + constexpr basic_string(AZStd::nullptr_t) = delete; + inline ~basic_string() { // destroy the string @@ -196,6 +200,7 @@ namespace AZStd inline this_type& operator=(AZStd::basic_string_view view) { return assign(view); } inline this_type& operator=(const_pointer ptr) { return assign(ptr); } inline this_type& operator=(Element ch) { return assign(1, ch); } + inline this_type& operator=(AZStd::nullptr_t) = delete; inline this_type& operator+=(const this_type& rhs) { return append(rhs); } inline this_type& operator+=(const_pointer ptr) { return append(ptr); } inline this_type& operator+=(Element ch) { return append(1, ch); } @@ -862,8 +867,7 @@ namespace AZStd inline size_type max_size() const { // return maximum possible length of sequence - size_type num = m_allocator.get_max_size(); - return (num <= 1 ? 1 : num - 1); + return AZStd::allocator_traits::max_size(m_allocator) / sizeof(value_type); } inline void resize(size_type newSize) diff --git a/Code/Framework/AzCore/AzCore/std/string/string_view.h b/Code/Framework/AzCore/AzCore/std/string/string_view.h index b2390c293a..30e61f95ce 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string_view.h +++ b/Code/Framework/AzCore/AzCore/std/string/string_view.h @@ -502,6 +502,9 @@ namespace AZStd swap(other); } + // C++23 overload to prevent initializing a string_view via a nullptr or integer type + constexpr basic_string_view(AZStd::nullptr_t) = delete; + constexpr const_reference operator[](size_type index) const { return data()[index]; } /// Returns value, not reference. If index is out of bounds, 0 is returned (can't be reference). constexpr value_type at(size_type index) const diff --git a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/PlatformIncl_UnixLike.h b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/PlatformIncl_UnixLike.h index 451ba1763a..63e8a4ce70 100644 --- a/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/PlatformIncl_UnixLike.h +++ b/Code/Framework/AzCore/Platform/Common/UnixLike/AzCore/PlatformIncl_UnixLike.h @@ -9,16 +9,3 @@ #pragma once #include - -#define __STDC_FORMAT_MACROS -#include - -// types like AZ::u64 require an usigned long long, but inttypes.h has it as unsigned long -#undef PRIX64 -#undef PRIx64 -#undef PRId64 -#undef PRIu64 -#define PRIX64 "llX" -#define PRIx64 "llx" -#define PRId64 "lld" -#define PRIu64 "llu" diff --git a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Memory/OverrunDetectionAllocator_WinAPI.h b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Memory/OverrunDetectionAllocator_WinAPI.h index 19f83374e7..b5cdc11d5d 100644 --- a/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Memory/OverrunDetectionAllocator_WinAPI.h +++ b/Code/Framework/AzCore/Platform/Common/WinAPI/AzCore/Memory/OverrunDetectionAllocator_WinAPI.h @@ -21,7 +21,7 @@ namespace AZ class WinAPIOverrunDetectionSchema : public OverrunDetectionSchema::PlatformAllocator { public: - virtual SystemInformation GetSystemInformation() override + SystemInformation GetSystemInformation() override { SystemInformation result; SYSTEM_INFO info; @@ -32,7 +32,7 @@ namespace AZ return result; } - virtual void* ReserveBytes(size_t amount) override + void* ReserveBytes(size_t amount) override { void* result = VirtualAlloc(0, amount, MEM_RESERVE, PAGE_NOACCESS); @@ -45,12 +45,12 @@ namespace AZ return result; } - virtual void ReleaseReservedBytes(void* base) override + void ReleaseReservedBytes(void* base) override { VirtualFree(base, 0, MEM_RELEASE); } - virtual void* CommitBytes(void* base, size_t amount) override + void* CommitBytes(void* base, size_t amount) override { void* result = VirtualAlloc(base, amount, MEM_COMMIT, PAGE_READWRITE); @@ -63,7 +63,7 @@ namespace AZ return result; } - virtual void DecommitBytes(void* base, size_t amount) override + void DecommitBytes(void* base, size_t amount) override { VirtualFree(base, amount, MEM_DECOMMIT); } diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp index fe6d83b7a4..0a73da5a92 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/IO/Streamer/StreamerConfiguration_Windows.cpp @@ -267,6 +267,7 @@ namespace AZ::IO SettingsRegistryInterface::VisitResponse::Continue : SettingsRegistryInterface::VisitResponse::Skip; } + using SettingsRegistryInterface::Visitor::Visit; void Visit([[maybe_unused]] AZStd::string_view path, [[maybe_unused]] AZStd::string_view valueName, [[maybe_unused]] AZ::SettingsRegistryInterface::Type type, AZStd::string_view value) override { diff --git a/Code/Framework/AzCore/Tests/AZStd/Allocators.cpp b/Code/Framework/AzCore/Tests/AZStd/Allocators.cpp index 6b82c642d5..8b5d1494fc 100644 --- a/Code/Framework/AzCore/Tests/AZStd/Allocators.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/Allocators.cpp @@ -122,8 +122,15 @@ namespace UnitTest TEST_F(AllocatorDefaultTest, AllocatorTraitsMaxSizeCompilesWithoutErrors) { - using AZStdAllocatorTraits = AZStd::allocator_traits; - AZStd::allocator testAllocator("trait allocator"); + struct AllocatorWithGetMaxSize + : AZStd::allocator + { + using AZStd::allocator::allocator; + size_t get_max_size() { return max_size(); } + }; + + using AZStdAllocatorTraits = AZStd::allocator_traits; + AllocatorWithGetMaxSize testAllocator("trait allocator"); typename AZStdAllocatorTraits::size_type maxSize = AZStdAllocatorTraits::max_size(testAllocator); EXPECT_EQ(testAllocator.get_max_size(), maxSize); } @@ -149,32 +156,32 @@ namespace UnitTest myalloc.set_name(newName); AZ_TEST_ASSERT(strcmp(myalloc.get_name(), newName) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() == AZStd::size_t(bufferSize)); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); buffer_alloc_type::pointer_type data = myalloc.allocate(100, 1); AZ_TEST_ASSERT(data != nullptr); - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize - 100); + EXPECT_EQ(bufferSize - 100, myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 100); myalloc.deallocate(data, 100, 1); // we can free the last allocation only - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); data = myalloc.allocate(100, 1); myalloc.allocate(3, 1); myalloc.deallocate(data); // can't free allocation which is not the last. - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize - 103); + EXPECT_EQ(bufferSize - 103, myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 103); myalloc.reset(); - AZ_TEST_ASSERT(myalloc.get_max_size() == AZStd::size_t(bufferSize)); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); data = myalloc.allocate(50, 64); AZ_TEST_ASSERT(data != nullptr); AZ_TEST_ASSERT(((AZStd::size_t)data & 63) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() <= bufferSize - 50); + EXPECT_LE(myalloc.max_size() - myalloc.get_allocated_size(), bufferSize - 50); AZ_TEST_ASSERT(myalloc.get_allocated_size() >= 50); buffer_alloc_type myalloc2; @@ -194,28 +201,28 @@ namespace UnitTest myalloc.set_name(newName); AZ_TEST_ASSERT(strcmp(myalloc.get_name(), newName) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() == sizeof(int) * numNodes); + EXPECT_EQ(numNodes * sizeof(int), myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); int* data = reinterpret_cast(myalloc.allocate(sizeof(int), 1)); AZ_TEST_ASSERT(data != nullptr); - AZ_TEST_ASSERT(myalloc.get_max_size() == (numNodes - 1) * sizeof(int)); + EXPECT_EQ((numNodes - 1) * sizeof(int), myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == sizeof(int)); myalloc.deallocate(data, sizeof(int), 1); - AZ_TEST_ASSERT(myalloc.get_max_size() == sizeof(int) * numNodes); + EXPECT_EQ(numNodes * sizeof(int), myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); for (int i = 0; i < numNodes; ++i) { data = reinterpret_cast(myalloc.allocate(sizeof(int), 1)); AZ_TEST_ASSERT(data != nullptr); - AZ_TEST_ASSERT(myalloc.get_max_size() == (numNodes - (i + 1)) * sizeof(int)); + EXPECT_EQ((numNodes - (i + 1)) * sizeof(int), myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == (i + 1) * sizeof(int)); } myalloc.reset(); - AZ_TEST_ASSERT(myalloc.get_max_size() == numNodes * sizeof(int)); + EXPECT_EQ(numNodes * sizeof(int), myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); AZ_TEST_ASSERT(myalloc == myalloc); @@ -233,7 +240,7 @@ namespace UnitTest AZ_TEST_ASSERT(aligned_data != nullptr); AZ_TEST_ASSERT(((AZStd::size_t)aligned_data & (dataAlignment - 1)) == 0); - AZ_TEST_ASSERT(myaligned_pool.get_max_size() == (numNodes - 1) * sizeof(aligned_int_type)); + EXPECT_EQ((numNodes - 1) * sizeof(aligned_int_type), myaligned_pool.max_size() - myaligned_pool.get_allocated_size()); AZ_TEST_ASSERT(myaligned_pool.get_allocated_size() == sizeof(aligned_int_type)); myaligned_pool.deallocate(aligned_data, sizeof(aligned_int_type), dataAlignment); // Make sure we free what we have allocated. @@ -268,32 +275,32 @@ namespace UnitTest ref_allocator_type::pointer_type data1 = ref_allocator1.allocate(10, 1); AZ_TEST_ASSERT(data1 != nullptr); - AZ_TEST_ASSERT(ref_allocator1.get_max_size() == bufferSize - 10); + EXPECT_EQ(bufferSize - 10, ref_allocator1.max_size() - ref_allocator1.get_allocated_size()); AZ_TEST_ASSERT(ref_allocator1.get_allocated_size() == 10); - AZ_TEST_ASSERT(shared_allocator.get_max_size() == bufferSize - 10); + EXPECT_EQ(bufferSize - 10, shared_allocator.max_size() - shared_allocator.get_allocated_size()); AZ_TEST_ASSERT(shared_allocator.get_allocated_size() == 10); ref_allocator_type::pointer_type data2 = ref_allocator2.allocate(10, 1); AZ_TEST_ASSERT(data2 != nullptr); - AZ_TEST_ASSERT(ref_allocator2.get_max_size() <= bufferSize - 20); + EXPECT_LE(ref_allocator2.max_size() - ref_allocator2.get_allocated_size(), bufferSize - 20); AZ_TEST_ASSERT(ref_allocator2.get_allocated_size() >= 20); - AZ_TEST_ASSERT(shared_allocator.get_max_size() <= bufferSize - 20); + EXPECT_LE(shared_allocator.max_size() - shared_allocator.get_allocated_size(), bufferSize - 20); AZ_TEST_ASSERT(shared_allocator.get_allocated_size() >= 20); shared_allocator.reset(); data1 = ref_allocator1.allocate(10, 32); AZ_TEST_ASSERT(data1 != nullptr); - AZ_TEST_ASSERT(ref_allocator1.get_max_size() <= bufferSize - 10); + EXPECT_LE(ref_allocator1.max_size() - ref_allocator1.get_allocated_size(), bufferSize - 10); AZ_TEST_ASSERT(ref_allocator1.get_allocated_size() >= 10); - AZ_TEST_ASSERT(shared_allocator.get_max_size() <= bufferSize - 10); + EXPECT_LE(shared_allocator.max_size() - shared_allocator.get_allocated_size(), bufferSize - 10); AZ_TEST_ASSERT(shared_allocator.get_allocated_size() >= 10); data2 = ref_allocator2.allocate(10, 32); AZ_TEST_ASSERT(data2 != nullptr); - AZ_TEST_ASSERT(ref_allocator1.get_max_size() <= bufferSize - 20); + EXPECT_LE(ref_allocator1.max_size() - ref_allocator1.get_allocated_size(), bufferSize - 20); AZ_TEST_ASSERT(ref_allocator1.get_allocated_size() >= 20); - AZ_TEST_ASSERT(shared_allocator.get_max_size() <= bufferSize - 20); + EXPECT_LE(shared_allocator.max_size() - shared_allocator.get_allocated_size(), bufferSize - 20); AZ_TEST_ASSERT(shared_allocator.get_allocated_size() >= 20); AZ_TEST_ASSERT(ref_allocator1 == ref_allocator2); @@ -312,31 +319,31 @@ namespace UnitTest myalloc.set_name(newName); AZ_TEST_ASSERT(strcmp(myalloc.get_name(), newName) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() == AZStd::size_t(bufferSize)); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); stack_allocator::pointer_type data = myalloc.allocate(100, 1); AZ_TEST_ASSERT(data != nullptr); - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize - 100); + EXPECT_EQ(bufferSize - 100, myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 100); myalloc.deallocate(data, 100, 1); // this allocator doesn't free data - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize - 100); + EXPECT_EQ(bufferSize - 100, myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 100); myalloc.reset(); - AZ_TEST_ASSERT(myalloc.get_max_size() == AZStd::size_t(bufferSize)); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); data = myalloc.allocate(50, 64); AZ_TEST_ASSERT(data != nullptr); AZ_TEST_ASSERT(((AZStd::size_t)data & 63) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() <= bufferSize - 50); + EXPECT_LE(myalloc.max_size() - myalloc.get_allocated_size(), bufferSize - 50); AZ_TEST_ASSERT(myalloc.get_allocated_size() >= 50); AZ_STACK_ALLOCATOR(myalloc2, 200); // test the macro declaration - AZ_TEST_ASSERT(myalloc2.get_max_size() == 200); + EXPECT_EQ(200, myalloc2.max_size() ); AZ_TEST_ASSERT(myalloc == myalloc); AZ_TEST_ASSERT((myalloc2 != myalloc)); diff --git a/Code/Framework/AzCore/Tests/AZStd/ConcurrentAllocators.cpp b/Code/Framework/AzCore/Tests/AZStd/ConcurrentAllocators.cpp index 5be17a75e2..86ac22bfc9 100644 --- a/Code/Framework/AzCore/Tests/AZStd/ConcurrentAllocators.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/ConcurrentAllocators.cpp @@ -49,7 +49,7 @@ namespace UnitTest const char newName[] = "My new test allocator"; myalloc.set_name(newName); EXPECT_EQ(0, strcmp(myalloc.get_name(), newName)); - EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * s_allocatorCapacity, myalloc.get_max_size()); + EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * s_allocatorCapacity, myalloc.max_size()); } } @@ -61,10 +61,10 @@ namespace UnitTest typename TestFixture::allocator_type::pointer_type data = myalloc.allocate(); EXPECT_NE(nullptr, data); EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type), myalloc.get_allocated_size()); - EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * (s_allocatorCapacity - 1), myalloc.get_max_size()); + EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * (s_allocatorCapacity - 1), myalloc.max_size() - myalloc.get_allocated_size()); myalloc.deallocate(data); EXPECT_EQ(0, myalloc.get_allocated_size()); - EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * s_allocatorCapacity, myalloc.get_max_size()); + EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * s_allocatorCapacity, myalloc.max_size()); } TYPED_TEST(ConcurrentAllocatorTestFixture, MultipleAllocateDeallocate) @@ -84,19 +84,19 @@ namespace UnitTest EXPECT_EQ(dataSize, dataSet.size()); dataSet.clear(); EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * dataSize, myalloc.get_allocated_size()); - EXPECT_EQ((s_allocatorCapacity - dataSize) * sizeof(typename TestFixture::allocator_type::value_type), myalloc.get_max_size()); + EXPECT_EQ((s_allocatorCapacity - dataSize) * sizeof(typename TestFixture::allocator_type::value_type), myalloc.max_size() - myalloc.get_allocated_size()); for (size_t i = 0; i < dataSize; i += 2) { myalloc.deallocate(data[i]); } EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * (dataSize / 2), myalloc.get_allocated_size()); - EXPECT_EQ((s_allocatorCapacity - dataSize / 2) * sizeof(typename TestFixture::allocator_type::value_type), myalloc.get_max_size()); + EXPECT_EQ((s_allocatorCapacity - dataSize / 2) * sizeof(typename TestFixture::allocator_type::value_type), myalloc.max_size() - myalloc.get_allocated_size()); for (size_t i = 1; i < dataSize; i += 2) { myalloc.deallocate(data[i]); } EXPECT_EQ(0, myalloc.get_allocated_size()); - EXPECT_EQ(s_allocatorCapacity * sizeof(typename TestFixture::allocator_type::value_type), myalloc.get_max_size()); + EXPECT_EQ(s_allocatorCapacity * sizeof(typename TestFixture::allocator_type::value_type), myalloc.max_size()); } TYPED_TEST(ConcurrentAllocatorTestFixture, ConcurrentAllocateoDeallocate) @@ -159,7 +159,7 @@ namespace UnitTest EXPECT_NE(nullptr, aligned_data); EXPECT_EQ(0, ((AZStd::size_t)aligned_data & (dataAlignment - 1))); - EXPECT_EQ((s_allocatorCapacity - 1) * sizeof(aligned_int_type), myaligned_pool.get_max_size()); + EXPECT_EQ((s_allocatorCapacity - 1) * sizeof(aligned_int_type), myaligned_pool.max_size() - myaligned_pool.get_allocated_size()); EXPECT_EQ(sizeof(aligned_int_type), myaligned_pool.get_allocated_size()); myaligned_pool.deallocate(aligned_data, sizeof(aligned_int_type), dataAlignment); // Make sure we free what we have allocated. diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp index 91d2237ca2..68bdd311d5 100644 --- a/Code/Framework/AzCore/Tests/AZStd/String.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp @@ -1210,9 +1210,6 @@ namespace UnitTest AZStd::string findStr("Hay"); string_view view3(findStr); - string_view nullptrView4(nullptr); - - EXPECT_EQ(emptyView1, nullptrView4); // copy const size_t destBufferSize = 32; @@ -1264,9 +1261,6 @@ namespace UnitTest AZStd::size_t rfindResult = view3.rfind('a', 2); EXPECT_EQ(1, rfindResult); - rfindResult = nullptrView4.rfind(""); - EXPECT_EQ(string_view::npos, rfindResult); - rfindResult = emptyView1.rfind(""); EXPECT_EQ(string_view::npos, rfindResult); @@ -1373,17 +1367,11 @@ namespace UnitTest { string_view view1("The quick brown fox jumped over the lazy dog"); string_view view2("Needle in Haystack"); - string_view nullBeaverView(nullptr); string_view emptyBeaverView; string_view superEmptyBeaverView(""); - EXPECT_EQ(nullBeaverView, emptyBeaverView); - EXPECT_EQ(superEmptyBeaverView, nullBeaverView); - EXPECT_EQ(emptyBeaverView, superEmptyBeaverView); - EXPECT_EQ(nullBeaverView, ""); - EXPECT_EQ(nullBeaverView, nullptr); EXPECT_EQ("", emptyBeaverView); - EXPECT_EQ(nullptr, superEmptyBeaverView); + EXPECT_EQ("", superEmptyBeaverView); EXPECT_EQ("The quick brown fox jumped over the lazy dog", view1); EXPECT_NE("The slow brown fox jumped over the lazy dog", view1); @@ -1421,8 +1409,6 @@ namespace UnitTest EXPECT_LE(beaverView, "Busy Beaver"); EXPECT_LE("Likable Beaver", notBeaverView); EXPECT_LE("Busy Beaver", beaverView); - EXPECT_LE(nullBeaverView, nullBeaverView); - EXPECT_LE(nullBeaverView, lowerBeaverStr); EXPECT_LE(microBeaverStr, view1); EXPECT_LE(compareStr, beaverView); diff --git a/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp b/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp index 2ca564681c..e968ee28fc 100644 --- a/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/AssetJsonSerializerTests.cpp @@ -100,6 +100,7 @@ namespace JsonSerializationTests AZ::AllocatorInstance::Destroy(); } + using JsonSerializerConformityTestDescriptor>::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); diff --git a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp index dbdb4fee78..34076a10f6 100644 --- a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp +++ b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp @@ -213,6 +213,82 @@ namespace UnitTest AZStd::tuple(R"(foO/Bar)", "foo/bar") )); + + struct PathHashCompareParams + { + AZ::IO::PathView m_testPath{}; + ::testing::Matcher m_compareMatcher; + ::testing::Matcher m_hashMatcher; + }; + + class PathHashCompareFixture + : public ScopedAllocatorSetupFixture + , public ::testing::WithParamInterface + {}; + + // Verifies that two paths that compare equal has their hash value compare equal + TEST_P(PathHashCompareFixture, PathsWhichCompareEqual_HashesToSameValue_Succeeds) + { + auto&& [testPath1, compareMatcher, hashMatcher] = GetParam(); + + // Compare path using parameterized Matcher + EXPECT_THAT(testPath1, compareMatcher); + // Compare hash using parameterized Matcher + const size_t testPath1Hash = AZStd::hash{}(testPath1); +AZ_PUSH_DISABLE_WARNING(4296, "-Wunknown-warning-option") + EXPECT_THAT(testPath1Hash, hashMatcher); +AZ_POP_DISABLE_WARNING + } + + INSTANTIATE_TEST_CASE_P( + HashPathCompareValidation, + PathHashCompareFixture, + ::testing::Values( + PathHashCompareParams{ AZ::IO::PathView("C:/test/foo", AZ::IO::WindowsPathSeparator), + testing::Eq(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/foo", AZ::IO::WindowsPathSeparator), + testing::Eq(AZ::IO::PathView(R"(/test/FOO)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(/test/FOO)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("C:/test/foo", AZ::IO::WindowsPathSeparator), + testing::Eq(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("C:/test/foo", AZ::IO::PosixPathSeparator), + testing::Ne(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView(R"(C:\test\foo)", AZ::IO::WindowsPathSeparator), + testing::Ne(AZ::IO::PathView(R"(c:/test/foo)", AZ::IO::PosixPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(c:/test/foo)", AZ::IO::PosixPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::WindowsPathSeparator), + testing::Eq(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::PosixPathSeparator), + testing::Gt(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::WindowsPathSeparator), + testing::Gt(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::PosixPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::PosixPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/AOO", AZ::IO::PosixPathSeparator), + testing::Lt(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/AOO", AZ::IO::WindowsPathSeparator), + testing::Lt(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::PosixPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::PosixPathSeparator))) }, + // Paths with different character values, comparison based on path separator + PathHashCompareParams{ AZ::IO::PathView("/test/BOO", AZ::IO::PosixPathSeparator), + testing::Le(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/BOO", AZ::IO::WindowsPathSeparator), + testing::Ge(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::WindowsPathSeparator), + testing::Le(AZ::IO::PathView(R"(/test/Boo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/Boo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::PosixPathSeparator), + testing::Ge(AZ::IO::PathView(R"(/test/Boo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/Boo)", AZ::IO::WindowsPathSeparator))) } + )); + class PathSingleParamFixture : public ScopedAllocatorSetupFixture , public ::testing::WithParamInterface> @@ -880,18 +956,8 @@ namespace UnitTest namespace Benchmark { class PathBenchmarkFixture - : public ::benchmark::Fixture - , public ::UnitTest::AllocatorsBase + : public ::UnitTest::AllocatorsBenchmarkFixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override - { - ::UnitTest::AllocatorsBase::SetupAllocator(); - } - void TearDown([[maybe_unused]] const ::benchmark::State& state) override - { - ::UnitTest::AllocatorsBase::TeardownAllocator(); - } protected: AZStd::fixed_vector m_appendPaths{ "foo", "bar", "baz", "bazzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", "boo/bar/base", "C:\\path\\to\\O3DE", "C", "\\\\", "/", R"(test\\path/with\mixed\separators)" }; diff --git a/Code/Framework/AzCore/Tests/Jobs.cpp b/Code/Framework/AzCore/Tests/Jobs.cpp index b63e139dd0..041f4970d1 100644 --- a/Code/Framework/AzCore/Tests/Jobs.cpp +++ b/Code/Framework/AzCore/Tests/Jobs.cpp @@ -1704,7 +1704,7 @@ namespace Benchmark static const AZ::u32 MEDIUM_NUMBER_OF_JOBS = 1024; static const AZ::u32 LARGE_NUMBER_OF_JOBS = 16384; - void SetUp([[maybe_unused]] ::benchmark::State& state) override + void internalSetUp() { AllocatorInstance::Create(); AllocatorInstance::Create(); @@ -1749,8 +1749,16 @@ namespace Benchmark return randomDepthDistribution(randomDepthGenerator); }); } + void SetUp(::benchmark::State&) override + { + internalSetUp(); + } + void SetUp(const ::benchmark::State&) override + { + internalSetUp(); + } - void TearDown([[maybe_unused]] ::benchmark::State& state) override + void internalTearDown() { JobContext::SetGlobalContext(nullptr); @@ -1763,6 +1771,14 @@ namespace Benchmark AllocatorInstance::Destroy(); AllocatorInstance::Destroy(); } + void TearDown(::benchmark::State&) override + { + internalTearDown(); + } + void TearDown(const ::benchmark::State&) override + { + internalTearDown(); + } protected: inline void RunCalculatePiJob(AZ::s32 depth, AZ::s8 priority) diff --git a/Code/Framework/AzCore/Tests/Math/FrustumPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/FrustumPerformanceTests.cpp index b132c9f726..e26d896e5a 100644 --- a/Code/Framework/AzCore/Tests/Math/FrustumPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/FrustumPerformanceTests.cpp @@ -19,8 +19,7 @@ namespace Benchmark class BM_MathFrustum : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_testFrustum = AZ::Frustum(AZ::ViewFrustumAttributes(AZ::Transform::CreateIdentity(), 1.0f, 2.0f * atanf(0.5f), 10.0f, 90.0f)); @@ -40,6 +39,15 @@ namespace Benchmark return data; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct Data { diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x3PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x3PerformanceTests.cpp index f345f26d06..918673d475 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x3PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x3PerformanceTests.cpp @@ -23,8 +23,7 @@ namespace Benchmark class BM_MathMatrix3x3 : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_testDataArray.resize(1000); @@ -44,6 +43,15 @@ namespace Benchmark return testData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct TestData { diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x4PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x4PerformanceTests.cpp index 9aed29005d..63ddefdd2c 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x4PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x4PerformanceTests.cpp @@ -21,8 +21,7 @@ namespace Benchmark class BM_MathMatrix3x4 : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const::benchmark::State& state) override + void internalSetUp() { m_testDataArray.resize(1000); @@ -58,6 +57,15 @@ namespace Benchmark return testData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct TestData { diff --git a/Code/Framework/AzCore/Tests/Math/Matrix4x4PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix4x4PerformanceTests.cpp index 90865064c8..21f440c3a1 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix4x4PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix4x4PerformanceTests.cpp @@ -20,8 +20,7 @@ namespace Benchmark class BM_MathMatrix4x4 : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_testDataArray.resize(1000); @@ -41,6 +40,15 @@ namespace Benchmark return testData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct TestData { diff --git a/Code/Framework/AzCore/Tests/Math/ObbPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/ObbPerformanceTests.cpp index 8463758fa5..d1e8ac2225 100644 --- a/Code/Framework/AzCore/Tests/Math/ObbPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/ObbPerformanceTests.cpp @@ -19,8 +19,7 @@ namespace Benchmark class BM_MathObb : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_position.Set(1.0f, 2.0f, 3.0f); m_rotation = AZ::Quaternion::CreateRotationZ(AZ::Constants::QuarterPi); @@ -28,6 +27,16 @@ namespace Benchmark m_obb = AZ::Obb::CreateFromPositionRotationAndHalfLengths(m_position, m_rotation, m_halfLengths); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } + AZ::Obb m_obb; AZ::Vector3 m_position; AZ::Quaternion m_rotation; diff --git a/Code/Framework/AzCore/Tests/Math/PlanePerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/PlanePerformanceTests.cpp index c23ded582c..e066207635 100644 --- a/Code/Framework/AzCore/Tests/Math/PlanePerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/PlanePerformanceTests.cpp @@ -18,14 +18,7 @@ namespace Benchmark class BM_MathPlane : public benchmark::Fixture { - public: - BM_MathPlane() - { - const unsigned int seed = 1; - rng = std::mt19937_64(seed); - } - - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { for (int i = 0; i < m_numIters; ++i) { @@ -39,7 +32,7 @@ namespace Benchmark m_distance = unif(rng); m_dists.push_back(m_distance); - //set these differently so they don't overlap with same values as other vectors + // set these differently so they don't overlap with same values as other vectors m_normal = AZ::Vector3(unif(rng), unif(rng), unif(rng)); m_normal.Normalize(); m_distance = unif(rng); @@ -47,6 +40,21 @@ namespace Benchmark m_planes.push_back(m_plane); } } + public: + BM_MathPlane() + { + const unsigned int seed = 1; + rng = std::mt19937_64(seed); + } + + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } AZ::Plane m_plane; AZ::Vector3 m_normal; diff --git a/Code/Framework/AzCore/Tests/Math/QuaternionPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/QuaternionPerformanceTests.cpp index 6f5a23d027..486a33ba67 100644 --- a/Code/Framework/AzCore/Tests/Math/QuaternionPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/QuaternionPerformanceTests.cpp @@ -17,8 +17,7 @@ namespace Benchmark class BM_MathQuaternion : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_quatDataArray.resize(1000); @@ -42,6 +41,15 @@ namespace Benchmark return quatData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct QuatData { diff --git a/Code/Framework/AzCore/Tests/Math/ShapeIntersectionPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/ShapeIntersectionPerformanceTests.cpp index b088330302..ecab1717b2 100644 --- a/Code/Framework/AzCore/Tests/Math/ShapeIntersectionPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/ShapeIntersectionPerformanceTests.cpp @@ -35,8 +35,7 @@ namespace Benchmark class BM_MathShapeIntersection : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_testDataArray.resize(1000); @@ -58,6 +57,15 @@ namespace Benchmark return testData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct TestData { diff --git a/Code/Framework/AzCore/Tests/Math/TransformPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/TransformPerformanceTests.cpp index 193535c020..dde0192ef9 100644 --- a/Code/Framework/AzCore/Tests/Math/TransformPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/TransformPerformanceTests.cpp @@ -22,8 +22,7 @@ namespace Benchmark class BM_MathTransform : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_testDataArray.resize(1000); @@ -51,6 +50,15 @@ namespace Benchmark return testData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct TestData { diff --git a/Code/Framework/AzCore/Tests/Math/Vector2PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Vector2PerformanceTests.cpp index e8506890aa..3ab306ff66 100644 --- a/Code/Framework/AzCore/Tests/Math/Vector2PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Vector2PerformanceTests.cpp @@ -19,8 +19,7 @@ namespace Benchmark class BM_MathVector2 : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_vecDataArray.resize(1000); @@ -37,6 +36,15 @@ namespace Benchmark return vecData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct VecData { diff --git a/Code/Framework/AzCore/Tests/Math/Vector3PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Vector3PerformanceTests.cpp index 27fa01ae95..5f33730bca 100644 --- a/Code/Framework/AzCore/Tests/Math/Vector3PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Vector3PerformanceTests.cpp @@ -19,8 +19,7 @@ namespace Benchmark class BM_MathVector3 : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_vecDataArray.resize(1000); @@ -37,6 +36,15 @@ namespace Benchmark return vecData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct VecData { diff --git a/Code/Framework/AzCore/Tests/Math/Vector4PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Vector4PerformanceTests.cpp index 4a0bcb49d2..f12851b1ed 100644 --- a/Code/Framework/AzCore/Tests/Math/Vector4PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Vector4PerformanceTests.cpp @@ -19,8 +19,7 @@ namespace Benchmark class BM_MathVector4 : public benchmark::Fixture { - public: - void SetUp([[maybe_unused]] const ::benchmark::State& state) override + void internalSetUp() { m_vecDataArray.resize(1000); @@ -38,6 +37,15 @@ namespace Benchmark return vecData; }); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } struct VecData { diff --git a/Code/Framework/AzCore/Tests/Memory.cpp b/Code/Framework/AzCore/Tests/Memory.cpp index 611af827d2..eb854050b6 100644 --- a/Code/Framework/AzCore/Tests/Memory.cpp +++ b/Code/Framework/AzCore/Tests/Memory.cpp @@ -1179,6 +1179,8 @@ namespace UnitTest size_type Capacity() const override { return 1 * 1024 * 1024 * 1024; } /// Returns max allocation size if possible. If not returned value is 0 size_type GetMaxAllocationSize() const override { return 1 * 1024 * 1024 * 1024; } + /// Returns max allocation size of a single contiguous allocation + size_type GetMaxContiguousAllocationSize() const override { return 1 * 1024 * 1024 * 1024; } /// Returns a pointer to a sub-allocator or NULL. IAllocatorAllocate* GetSubAllocator() override { return NULL; } }; diff --git a/Code/Framework/AzCore/Tests/Memory/HphaSchema.cpp b/Code/Framework/AzCore/Tests/Memory/HphaSchema.cpp index aaf4ce1811..85dd79931d 100644 --- a/Code/Framework/AzCore/Tests/Memory/HphaSchema.cpp +++ b/Code/Framework/AzCore/Tests/Memory/HphaSchema.cpp @@ -120,19 +120,34 @@ namespace Benchmark class HphaSchemaBenchmarkFixture : public ::benchmark::Fixture { - public: - void SetUp(const ::benchmark::State& state) override + void internalSetUp() { - AZ_UNUSED(state); AZ::AllocatorInstance::Create(); } - void TearDown(const ::benchmark::State& state) override + void internalTearDown() { - AZ_UNUSED(state); AZ::AllocatorInstance::Destroy(); } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } + void TearDown(const benchmark::State&) override + { + internalTearDown(); + } + void TearDown(benchmark::State&) override + { + internalTearDown(); + } + static void BM_Allocations(benchmark::State& state, const AllocationSizeArray& allocationArray) { AZStd::vector allocations; diff --git a/Code/Framework/AzCore/Tests/Name/NameTests.cpp b/Code/Framework/AzCore/Tests/Name/NameTests.cpp index 5417d36051..eb0a048e2f 100644 --- a/Code/Framework/AzCore/Tests/Name/NameTests.cpp +++ b/Code/Framework/AzCore/Tests/Name/NameTests.cpp @@ -362,7 +362,7 @@ namespace UnitTest // Test specific construction case that was failing. // The constructor calls Name::SetName() which does a move assignment // Name& Name::operator=(Name&& rhs) was leaving m_view pointing to the m_data in a temporary Name object. - AZ::Name emptyName(AZStd::string_view(nullptr)); + AZ::Name emptyName(AZStd::string_view{}); EXPECT_TRUE(emptyName.IsEmpty()); EXPECT_EQ(0, emptyName.GetStringView().data()[0]); } diff --git a/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp b/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp index 6d572a02a3..22fb6379d2 100644 --- a/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp +++ b/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp @@ -1155,6 +1155,23 @@ namespace Benchmark { class StorageDriveWindowsFixture : public benchmark::Fixture { + void internalTearDown() + { + using namespace AZ::IO; + + AZStd::string temp; + m_absolutePath.swap(temp); + + delete m_streamer; + m_streamer = nullptr; + + SystemFile::Delete(TestFileName); + + AZ::IO::FileIOBase::SetInstance(nullptr); + AZ::IO::FileIOBase::SetInstance(m_previousFileIO); + delete m_fileIO; + m_fileIO = nullptr; + } public: constexpr static const char* TestFileName = "StreamerBenchmark.bin"; constexpr static size_t FileSize = 64_mib; @@ -1197,20 +1214,13 @@ namespace Benchmark } } - void TearDown([[maybe_unused]] const ::benchmark::State& state) override + void TearDown(const benchmark::State&) override { - using namespace AZ::IO; - - AZStd::string temp; - m_absolutePath.swap(temp); - - delete m_streamer; - - SystemFile::Delete(TestFileName); - - AZ::IO::FileIOBase::SetInstance(nullptr); - AZ::IO::FileIOBase::SetInstance(m_previousFileIO); - delete m_fileIO; + internalTearDown(); + } + void TearDown(benchmark::State&) override + { + internalTearDown(); } void RepeatedlyReadFile(benchmark::State& state) diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/ArraySerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/ArraySerializerTests.cpp index e410ba9ca4..8582453683 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/ArraySerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/ArraySerializerTests.cpp @@ -35,6 +35,7 @@ namespace JsonSerializationTests features.m_fixedSizeArray = true; } + using JsonSerializerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -243,6 +244,7 @@ namespace JsonSerializationTests ])"; } + using ArraySerializerTestDescriptionBase>::Reflect; void Reflect(AZStd::unique_ptr& context) override { Base::Reflect(context); @@ -299,6 +301,7 @@ namespace JsonSerializationTests AZ::JsonArraySerializer m_serializer; public: + using BaseJsonSerializerFixture::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& context) override { context->RegisterGenericType(); diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/BasicContainerSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/BasicContainerSerializerTests.cpp index 3bc574c2ce..4a6a8e9e8a 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/BasicContainerSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/BasicContainerSerializerTests.cpp @@ -60,6 +60,7 @@ namespace JsonSerializationTests return "[188, 288, 388]"; } + using BasicContainerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -133,6 +134,7 @@ namespace JsonSerializationTests return "[188, 288, 388]"; } + using BasicContainerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -225,6 +227,7 @@ namespace JsonSerializationTests features.m_supportsPartialInitialization = true; } + using BasicContainerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { SimpleClass::Reflect(context, true); @@ -291,6 +294,7 @@ namespace JsonSerializationTests using Container = AZStd::vector; using BaseClassContainer = AZStd::vector>; + using JsonBasicContainerSerializerTests::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& serializeContext) override { SimpleClass::Reflect(serializeContext, true); @@ -352,6 +356,7 @@ namespace JsonSerializationTests static constexpr size_t ContainerSize = 4; using Container = AZStd::fixed_vector; + using JsonBasicContainerSerializerTests::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& serializeContext) override { serializeContext->RegisterGenericType(); @@ -387,6 +392,7 @@ namespace JsonSerializationTests public: using Set = AZStd::set; + using JsonBasicContainerSerializerTests::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& serializeContext) override { serializeContext->RegisterGenericType(); diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/BoolSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/BoolSerializerTests.cpp index a670a2a6e1..e9bb404ba8 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/BoolSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/BoolSerializerTests.cpp @@ -83,6 +83,7 @@ namespace JsonSerializationTests BaseJsonSerializerFixture::TearDown(); } + using BaseJsonSerializerFixture::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& serializeContext) override { serializeContext->Class() diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/DoubleSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/DoubleSerializerTests.cpp index 76aaae393d..53eb855a63 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/DoubleSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/DoubleSerializerTests.cpp @@ -95,6 +95,7 @@ namespace JsonSerializationTests BaseJsonSerializerFixture::TearDown(); } + using BaseJsonSerializerFixture::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& serializeContext) override { serializeContext->Class() diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/MapSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/MapSerializerTests.cpp index 4979df04be..7ffe3ffee0 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/MapSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/MapSerializerTests.cpp @@ -44,6 +44,7 @@ namespace JsonSerializationTests features.m_supportsPartialInitialization = false; } + using JsonSerializerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -247,6 +248,7 @@ namespace JsonSerializationTests features.m_supportsPartialInitialization = true; } + using MapBaseTestDescription, Serializer>::Reflect; void Reflect(AZStd::unique_ptr& context) override { SimpleClass::Reflect(context, true); diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp index 43dc1a85d9..d89d9bfb33 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp @@ -33,6 +33,7 @@ namespace JsonSerializationTests return AZStd::make_shared(); } + using JsonSerializerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -102,6 +103,7 @@ namespace JsonSerializationTests return *lhs == *rhs; } + using Base::Reflect; void Reflect(AZStd::unique_ptr& context) override { SimpleClass::Reflect(context, true); @@ -176,6 +178,7 @@ namespace JsonSerializationTests features.m_supportsPartialInitialization = true; } + using SmartPointerBaseTestDescription>::Reflect; void Reflect(AZStd::unique_ptr& context) override { SimpleInheritence::Reflect(context, true); @@ -340,6 +343,7 @@ namespace JsonSerializationTests features.m_supportsPartialInitialization = true; } + using SmartPointerBaseTestDescription>::Reflect; void Reflect(AZStd::unique_ptr& context) override { MultipleInheritence::Reflect(context, true); @@ -513,7 +517,8 @@ namespace JsonSerializationTests public: using SmartPointer = typename SmartPointerSimpleDerivedClassTestDescription::SmartPointer; using InstanceSmartPointer = AZStd::shared_ptr; - + + using BaseJsonSerializerFixture::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& context) override { m_description.Reflect(context); diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/TupleSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/TupleSerializerTests.cpp index ff0fbcc5a6..cfd844f3f5 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/TupleSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/TupleSerializerTests.cpp @@ -72,6 +72,7 @@ namespace JsonSerializationTests TupleSerializerTestsInternal::ConfigureFeatures(features); } + using JsonSerializerConformityTestDescriptor>::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->Class()->Field("pair", &PairPlaceholder::m_pair); @@ -126,6 +127,7 @@ namespace JsonSerializationTests TupleSerializerTestsInternal::ConfigureFeatures(features); } + using JsonSerializerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -344,6 +346,7 @@ namespace JsonSerializationTests features.m_enableNewInstanceTests = false; } + using JsonSerializerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->Class() @@ -477,6 +480,7 @@ namespace JsonSerializationTests features.m_typeToInject = rapidjson::kNullType; } + using JsonSerializerConformityTestDescriptor::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -535,6 +539,7 @@ namespace JsonSerializationTests BaseJsonSerializerFixture::TearDown(); } + using BaseJsonSerializerFixture::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& serializeContext) override { SimpleClass::Reflect(serializeContext, true); diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/UnorderedSetSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/UnorderedSetSerializerTests.cpp index 17902b6900..f4a1f48dc5 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/UnorderedSetSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/UnorderedSetSerializerTests.cpp @@ -54,6 +54,7 @@ namespace JsonSerializationTests features.m_supportsPartialInitialization = false; } + using JsonSerializerConformityTestDescriptor>::Reflect; void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -108,6 +109,7 @@ namespace JsonSerializationTests context->RegisterGenericType(); } + using JsonSerializerConformityTestDescriptor::Reflect; bool AreEqual(const MultiSet& lhs, const MultiSet& rhs) override { return @@ -139,6 +141,7 @@ namespace JsonSerializationTests BaseJsonSerializerFixture::TearDown(); } + using BaseJsonSerializerFixture::RegisterAdditional; void RegisterAdditional(AZStd::unique_ptr& serializeContext) override { serializeContext->RegisterGenericType(); diff --git a/Code/Framework/AzCore/Tests/SettingsRegistryTests.cpp b/Code/Framework/AzCore/Tests/SettingsRegistryTests.cpp index 61f93fb860..2da5701207 100644 --- a/Code/Framework/AzCore/Tests/SettingsRegistryTests.cpp +++ b/Code/Framework/AzCore/Tests/SettingsRegistryTests.cpp @@ -423,6 +423,8 @@ namespace SettingsRegistryTests struct : public AZ::SettingsRegistryInterface::Visitor { + using AZ::SettingsRegistryInterface::Visitor::Visit; + using ValueType [[maybe_unused]] = typename SettingsType::ValueType; void Visit([[maybe_unused]] AZStd::string_view path, [[maybe_unused]] AZStd::string_view valueName, AZ::SettingsRegistryInterface::Type type, ValueType value) override { @@ -452,6 +454,8 @@ namespace SettingsRegistryTests struct : public AZ::SettingsRegistryInterface::Visitor { + using AZ::SettingsRegistryInterface::Visitor::Visit; + using ValueType [[maybe_unused]] = typename SettingsType::ValueType; void Visit([[maybe_unused]] AZStd::string_view path, [[maybe_unused]] AZStd::string_view valueName, AZ::SettingsRegistryInterface::Type type, ValueType value) override { @@ -482,6 +486,7 @@ namespace SettingsRegistryTests struct : public AZ::SettingsRegistryInterface::Visitor { + using AZ::SettingsRegistryInterface::Visitor::Visit; void Visit([[maybe_unused]] AZStd::string_view path, [[maybe_unused]] AZStd::string_view valueName, AZ::SettingsRegistryInterface::Type type, AZ::s64 value) override { EXPECT_EQ(AZ::SettingsRegistryInterface::Type::Integer, type); @@ -517,6 +522,8 @@ namespace SettingsRegistryTests EXPECT_TRUE(path.ends_with(valueName)); return AZ::SettingsRegistryInterface::VisitResponse::Continue; } + + using AZ::SettingsRegistryInterface::Visitor::Visit; void Visit(AZStd::string_view path, AZStd::string_view valueName, AZ::SettingsRegistryInterface::Type , AZStd::string_view)override { EXPECT_TRUE(path.ends_with(valueName)); @@ -1510,7 +1517,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_TRUE(result); EXPECT_EQ(4, counter); @@ -1552,7 +1559,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, "Special", nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, "Special"); EXPECT_TRUE(result); EXPECT_EQ(6, counter); @@ -1591,7 +1598,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_TRUE(result); EXPECT_EQ(4, counter); @@ -1632,7 +1639,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_TRUE(result); EXPECT_EQ(4, counter); @@ -1665,7 +1672,7 @@ namespace SettingsRegistryTests m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, "Special", nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, "Special"); EXPECT_TRUE(result); EXPECT_EQ(1, counter); @@ -1715,7 +1722,7 @@ namespace SettingsRegistryTests TEST_F(SettingsRegistryTest, MergeSettingsFolder_EmptyFolder_ReportsSuccessButNothingAdded) { - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_TRUE(result); EXPECT_EQ(AZ::SettingsRegistryInterface::Type::Object, m_registry->GetType(AZ_SETTINGS_REGISTRY_HISTORY_KEY "/0")); // Folder and specialization settings. @@ -1727,7 +1734,7 @@ namespace SettingsRegistryTests constexpr AZStd::fixed_string path(AZ::IO::MaxPathLength + 1, 'a'); AZ_TEST_START_TRACE_SUPPRESSION; - bool result = m_registry->MergeSettingsFolder(path, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(path, { "editor", "test" }, {}); AZ_TEST_STOP_TRACE_SUPPRESSION(1); EXPECT_FALSE(result); @@ -1744,7 +1751,7 @@ namespace SettingsRegistryTests AZ_TEST_START_TRACE_SUPPRESSION; m_testFolder->push_back(AZ_CORRECT_DATABASE_SEPARATOR); *m_testFolder += AZ::SettingsRegistryInterface::RegistryFolder; - bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}, nullptr); + bool result = m_registry->MergeSettingsFolder(*m_testFolder, { "editor", "test" }, {}); EXPECT_GT(::UnitTest::TestRunner::Instance().StopAssertTests(), 0); EXPECT_FALSE(result); diff --git a/Code/Framework/AzCore/Tests/TaskTests.cpp b/Code/Framework/AzCore/Tests/TaskTests.cpp index f65dffcd99..e743ab6643 100644 --- a/Code/Framework/AzCore/Tests/TaskTests.cpp +++ b/Code/Framework/AzCore/Tests/TaskTests.cpp @@ -551,19 +551,37 @@ namespace Benchmark { class TaskGraphBenchmarkFixture : public ::benchmark::Fixture { - public: - void SetUp(benchmark::State&) override + void internalSetUp() { executor = new TaskExecutor; graph = new TaskGraph; } - void TearDown(benchmark::State&) override + void internalTearDown() { delete graph; delete executor; } + public: + void SetUp(const benchmark::State&) override + { + internalSetUp(); + } + void SetUp(benchmark::State&) override + { + internalSetUp(); + } + + void TearDown(const benchmark::State&) override + { + internalTearDown(); + } + void TearDown(benchmark::State&) override + { + internalTearDown(); + } + TaskDescriptor descriptors[4] = { { "critical", "benchmark", TaskPriority::CRITICAL }, { "high", "benchmark", TaskPriority::HIGH }, { "medium", "benchmark", TaskPriority::MEDIUM }, diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp index 958dba2cc9..12974d03cf 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp @@ -81,71 +81,6 @@ namespace AzFramework static constexpr const char s_prefabSystemKey[] = "/Amazon/Preferences/EnablePrefabSystem"; static constexpr const char s_prefabWipSystemKey[] = "/Amazon/Preferences/EnablePrefabSystemWipFeatures"; static constexpr const char s_legacySlicesAssertKey[] = "/Amazon/Preferences/ShouldAssertForLegacySlicesUsage"; - - // A Helper function that can load an app descriptor from file. - AZ::Outcome, AZStd::string> LoadDescriptorFromFilePath(const char* appDescriptorFilePath, AZ::SerializeContext& serializeContext) - { - AZStd::unique_ptr loadedDescriptor; - - AZ::IO::SystemFile appDescriptorFile; - if (!appDescriptorFile.Open(appDescriptorFilePath, AZ::IO::SystemFile::SF_OPEN_READ_ONLY)) - { - return AZ::Failure(AZStd::string::format("Failed to open file: %s", appDescriptorFilePath)); - } - - AZ::IO::SystemFileStream appDescriptorFileStream(&appDescriptorFile, true); - if (!appDescriptorFileStream.IsOpen()) - { - return AZ::Failure(AZStd::string::format("Failed to stream file: %s", appDescriptorFilePath)); - } - - // Callback function for allocating the root elements in the file. - AZ::ObjectStream::InplaceLoadRootInfoCB inplaceLoadCb = - [](void** rootAddress, const AZ::SerializeContext::ClassData**, const AZ::Uuid& classId, AZ::SerializeContext*) - { - if (rootAddress && classId == azrtti_typeid()) - { - // ComponentApplication::Descriptor is normally a singleton. - // Force a unique instance to be created. - *rootAddress = aznew AZ::ComponentApplication::Descriptor(); - } - }; - - // Callback function for saving the root elements in the file. - AZ::ObjectStream::ClassReadyCB classReadyCb = - [&loadedDescriptor](void* classPtr, const AZ::Uuid& classId, AZ::SerializeContext* context) - { - // Save descriptor, delete anything else loaded from file. - if (classId == azrtti_typeid()) - { - loadedDescriptor.reset(static_cast(classPtr)); - } - else if (const AZ::SerializeContext::ClassData* classData = context->FindClassData(classId)) - { - classData->m_factory->Destroy(classPtr); - } - else - { - AZ_Error("Application", false, "Unexpected type %s found in application descriptor file. This memory will leak.", - classId.ToString().c_str()); - } - }; - - // There's other stuff in the file we may not recognize (system components), but we're not interested in that stuff. - AZ::ObjectStream::FilterDescriptor loadFilter(&AZ::Data::AssetFilterNoAssetLoading, AZ::ObjectStream::FILTERFLAG_IGNORE_UNKNOWN_CLASSES); - - if (!AZ::ObjectStream::LoadBlocking(&appDescriptorFileStream, serializeContext, classReadyCb, loadFilter, inplaceLoadCb)) - { - return AZ::Failure(AZStd::string::format("Failed to load objects from file: %s", appDescriptorFilePath)); - } - - if (!loadedDescriptor) - { - return AZ::Failure(AZStd::string::format("Failed to find descriptor object in file: %s", appDescriptorFilePath)); - } - - return AZ::Success(AZStd::move(loadedDescriptor)); - } } Application::Application() diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp index 012d713cf5..d2a81102dc 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp @@ -40,8 +40,6 @@ #include -#include - namespace AZ::IO { AZ_CVAR(int, sys_PakPriority, aznumeric_cast(ArchiveVars{}.nPriority), nullptr, AZ::ConsoleFunctorFlags::Null, @@ -64,40 +62,6 @@ namespace AZ::IO::ArchiveInternal // to the actual index , this offset is added to get the valid handle static constexpr size_t PseudoFileIdxOffset = 1; - // Explanation of this function: it is like a 'find and replace' for paths - // if the source path starts with 'aliasToLookFor' it will replace it with 'aliasToReplaceWith' - // else it will leave it untouched. - // the only caveat here is that it will perform this replacement if the source path either begins - // with the literal alias to look for, or begins with the actual absolute path that the alias to - // look for represents. It is a way of redirecting all @devassets@ to @assets@ regardless of whether - // you input a string that literally starts with @devassets@ or one that starts with the absolute path to the - // folder that @devassets@ aliases. - AZStd::optional ConvertAbsolutePathToAliasedPath(AZStd::string_view sourcePath, - AZStd::string_view aliasToLookFor, AZStd::string_view aliasToReplaceWith) - { - if (auto fileIo = AZ::IO::FileIOBase::GetDirectInstance(); !aliasToLookFor.empty() && !aliasToReplaceWith.empty() && !sourcePath.empty() && fileIo) - { - auto convertedPath = fileIo->ConvertToAlias(sourcePath); - if (!convertedPath) - { - return AZStd::nullopt; - } - - if (convertedPath->Native().starts_with(aliasToLookFor)) - { - convertedPath->Native().replace(0, aliasToLookFor.size(), aliasToReplaceWith); - } - // lowercase path if it starts with either the @assets@ or @root@ alias - if (convertedPath->Native().starts_with("@assets@") || convertedPath->Native().starts_with("@root@") - || convertedPath->Native().starts_with("@projectplatformcache@")) - { - AZStd::to_lower(convertedPath->Native().begin(), convertedPath->Native().end()); - } - return convertedPath; - } - return AZStd::make_optional(sourcePath); - } - struct CCachedFileRawData { void* m_pCachedData; @@ -146,15 +110,12 @@ namespace AZ::IO::ArchiveInternal uint32_t GetFileSize() { return GetFile() ? GetFile()->GetFileEntry()->desc.lSizeUncompressed : 0; } int FSeek(uint64_t nOffset, int nMode); - size_t FRead(void* pDest, size_t nSize, size_t nCount, AZ::IO::HandleType fileHandle); - size_t FReadAll(void* pDest, size_t nFileSize, AZ::IO::HandleType fileHandle); + size_t FRead(void* pDest, size_t bytesToRead, AZ::IO::HandleType fileHandle); void* GetFileData(size_t& nFileSize, AZ::IO::HandleType fileHandle); int FEof(); - char* FGets(char* pBuf, int n); - int Getc(); uint64_t GetModificationTime() { return m_pFileData->GetFileEntry()->GetModificationTime(); } - const char* GetArchivePath() { return m_pFileData->GetZip()->GetFilePath(); } + AZ::IO::PathView GetArchivePath() { return m_pFileData->GetZip()->GetFilePath(); } protected: uint64_t m_nCurSeek; CCachedFileDataPtr m_pFileData; @@ -205,7 +166,7 @@ namespace AZ::IO::ArchiveInternal } ////////////////////////////////////////////////////////////////////////// - size_t ArchiveInternal::CZipPseudoFile::FRead(void* pDest, size_t nSize, size_t nCount, [[maybe_unused]] AZ::IO::HandleType fileHandle) + size_t ArchiveInternal::CZipPseudoFile::FRead(void* pDest, size_t bytesToRead, [[maybe_unused]] AZ::IO::HandleType fileHandle) { AZ_PROFILE_FUNCTION(AzCore); @@ -214,21 +175,13 @@ namespace AZ::IO::ArchiveInternal return 0; } - size_t nTotal = nSize * nCount; + size_t nTotal = bytesToRead; if (!nTotal || (uint32_t)m_nCurSeek >= GetFileSize()) { return 0; } - if (nTotal > GetFileSize() - m_nCurSeek) - { - nTotal = GetFileSize() - m_nCurSeek; - if (nTotal < nSize) - { - return 0; - } - nTotal -= nTotal % nSize; - } + nTotal = AZStd::min(nTotal, GetFileSize() - m_nCurSeek); int64_t nReadBytes = GetFile()->ReadData(pDest, m_nCurSeek, nTotal); if (nReadBytes == -1) @@ -242,32 +195,9 @@ namespace AZ::IO::ArchiveInternal nTotal = (size_t)nReadBytes; } m_nCurSeek += nTotal; - return nTotal / nSize; + return nTotal; } - ////////////////////////////////////////////////////////////////////////// - size_t ArchiveInternal::CZipPseudoFile::FReadAll(void* pDest, size_t nFileSize, [[maybe_unused]] AZ::IO::HandleType fileHandle) - { - if (!GetFile()) - { - return 0; - } - - if (nFileSize != GetFileSize()) - { - AZ_Assert(false, "File size parameter of nFileSize does not match the file size of the zip file"); // Bad call - return 0; - } - - if (!GetFile()->ReadData(pDest, 0, nFileSize)) - { - return 0; - } - - m_nCurSeek = nFileSize; - - return nFileSize; - } ////////////////////////////////////////////////////////////////////////// void* ArchiveInternal::CZipPseudoFile::GetFileData(size_t& nFileSize, [[maybe_unused]] AZ::IO::HandleType fileHandle) @@ -292,70 +222,6 @@ namespace AZ::IO::ArchiveInternal return (uint32_t)m_nCurSeek >= GetFileSize(); } - char* ArchiveInternal::CZipPseudoFile::FGets(char* pBuf, int n) - { - if (!GetFile()) - { - return nullptr; - } - - char* pData = (char*)GetFile()->GetData(); - if (!pData) - { - return nullptr; - } - int nn = 0; - int i; - for (i = 0; i < n; i++) - { - if (i + m_nCurSeek == GetFileSize()) - { - break; - } - char c = pData[i + m_nCurSeek]; - if (c == 0xa || c == 0) - { - pBuf[nn++] = c; - i++; - break; - } - else - if (c == 0xd) - { - continue; - } - pBuf[nn++] = c; - } - pBuf[nn] = 0; - m_nCurSeek += i; - - if (m_nCurSeek == GetFileSize()) - { - return nullptr; - } - return pBuf; - } - - int ArchiveInternal::CZipPseudoFile::Getc() - { - if (!GetFile()) - { - return EOF; - } - char* pData = (char*)GetFile()->GetData(); - if (!pData) - { - return EOF; - } - int c = EOF; - if (m_nCurSeek == GetFileSize()) - { - return c; - } - c = pData[m_nCurSeek]; - m_nCurSeek += 1; - return c; - } } namespace AZ::IO @@ -379,16 +245,17 @@ namespace AZ::IO void Add(AZStd::string_view sResourceFile) override { - auto filename = ArchiveInternal::ConvertAbsolutePathToAliasedPath(sResourceFile); - if (!filename) + if (sResourceFile.empty()) { - AZ_Error("Archive", false, "Path %s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", aznumeric_cast(sResourceFile.size()), - sResourceFile.data(), AZ::IO::MaxPathLength); return; } - AZ::IO::FixedMaxPathString& convertedFilename = filename->Native(); - AZStd::replace(convertedFilename.begin(), convertedFilename.end(), AZ_WRONG_DATABASE_SEPARATOR, AZ_CORRECT_DATABASE_SEPARATOR); - AZStd::to_lower(convertedFilename.begin(), convertedFilename.end()); + AZ::IO::FixedMaxPath convertedFilename; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(convertedFilename, sResourceFile)) + { + AZ_Error("Archive", false, "Path %.*s cannot be resolved. It is longer than MaxPathLength %zu", + AZ_STRING_ARG(sResourceFile), AZ::IO::MaxPathLength); + return; + } AZStd::scoped_lock lock(m_lock); m_set.emplace(convertedFilename); @@ -397,23 +264,20 @@ namespace AZ::IO { AZStd::scoped_lock lock(m_lock); m_set.clear(); - m_iter = m_set.begin(); + m_iter = m_set.end(); } bool IsExist(AZStd::string_view sResourceFile) override { - auto filename = ArchiveInternal::ConvertAbsolutePathToAliasedPath(sResourceFile); - if (!filename) + AZ::IO::FixedMaxPath convertedFilename; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(convertedFilename, sResourceFile)) { - AZ_Error("Archive", false, "Path %.*s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", aznumeric_cast(sResourceFile.size()), - sResourceFile.data(), AZ::IO::MaxPathLength); + AZ_Error("Archive", false, "Path %.*s cannot be resolved. It is longer than MaxPathLength %zu", + AZ_STRING_ARG(sResourceFile), AZ::IO::MaxPathLength); return false; } - AZ::IO::FixedMaxPathString& convertedFilename = filename->Native(); - AZStd::replace(convertedFilename.begin(), convertedFilename.end(), AZ_WRONG_DATABASE_SEPARATOR, AZ_CORRECT_DATABASE_SEPARATOR); - AZStd::to_lower(convertedFilename.begin(), convertedFilename.end()); AZStd::scoped_lock lock(m_lock); - return m_set.contains(AZStd::string_view{ convertedFilename }); + return m_set.contains(AZ::IO::PathView{ convertedFilename }); } bool Load(AZStd::string_view sResourceListFilename) override { @@ -425,9 +289,8 @@ namespace AZ::IO AZ::IO::SizeType nLen = file.Length(); AZStd::string pMemBlock; - pMemBlock.resize_no_construct(nLen); - char* buf = pMemBlock.data(); - file.Read(nLen, buf); + pMemBlock.resize_no_construct(nLen);; + file.Read(pMemBlock.size(), pMemBlock.data()); // Parse file, every line in a file represents a resource filename. AZ::StringFunc::TokenizeVisitor(pMemBlock, @@ -464,7 +327,7 @@ namespace AZ::IO } private: - using ResourceSet = AZStd::set; + using ResourceSet = AZStd::set>; AZStd::recursive_mutex m_lock; ResourceSet m_set; ResourceSet::iterator m_iter; @@ -499,12 +362,13 @@ namespace AZ::IO , m_pNextLevelResourceList{ new CResourceList{} } , m_mainThreadId{ AZStd::this_thread::get_id() } { + CompressionBus::Handler::BusConnect(); } ////////////////////////////////////////////////////////////////////////// Archive::~Archive() { - Release(); + CompressionBus::Handler::BusDisconnect(); m_arrZips = {}; @@ -530,51 +394,13 @@ namespace AZ::IO AZ_Assert(m_cachedFileRawDataSet.empty(), "All Archive file cached raw data instances not closed"); } - bool Archive::CheckFileAccessDisabled([[maybe_unused]] AZStd::string_view name, [[maybe_unused]] const char* mode) - { - return false; - } - void Archive::LogFileAccessCallStack([[maybe_unused]] AZStd::string_view name, [[maybe_unused]] AZStd::string_view nameFull, [[maybe_unused]] const char* mode) { // Print call stack for each find. - AZ_TracePrintf("Archive", "LogFileAccessCallStack() - name=%.*s; nameFull=%.*s; mode=%s\n", aznumeric_cast(name.size()), name.data(), aznumeric_cast(nameFull.size()), nameFull.data(), mode); + AZ_TracePrintf("Archive", "LogFileAccessCallStack() - name=%.*s; nameFull=%.*s; mode=%s\n", AZ_STRING_ARG(name), AZ_STRING_ARG(nameFull), mode); AZ::Debug::Trace::PrintCallstack("Archive", 32); } - ////////////////////////////////////////////////////////////////////////// - - bool Archive::IsInstalledToHDD(AZStd::string_view) const - { - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void Archive::ParseAliases(AZStd::string_view szCommandLine) - { - // this is a list of pairs separated by commas, i.e. Folder1,FolderNew,Textures,TestBuildTextures etc. - AZStd::optional aliasKey = AZ::StringFunc::TokenizeNext(szCommandLine, ','); - AZStd::optional aliasPath = AZ::StringFunc::TokenizeNext(szCommandLine, ','); - for ( ;aliasKey && aliasPath; aliasKey = AZ::StringFunc::TokenizeNext(szCommandLine,','), AZ::StringFunc::TokenizeNext(szCommandLine,',')) - { - // inform the Archive system - SetAlias(*aliasKey, *aliasPath, true); - AZ_TracePrintf("Archive", "Archive ALIAS:%.*s = %.*s\n", aznumeric_cast(aliasKey->size()), aliasKey->data(), - aznumeric_cast(aliasPath->size()), aliasPath->data()); - - } - } - - ////////////////////////////////////////////////////////////////////////// - //! if bReturnSame==true, it will return the input name if an alias doesn't exist. Otherwise returns nullptr - const char* Archive::GetAlias(AZStd::string_view szName, bool bReturnSame) - { - constexpr size_t MaxAliasLength = 32; - AZStd::fixed_string aliasKey{ szName }; - const char* dest = AZ::IO::FileIOBase::GetDirectInstance()->GetAlias(aliasKey.c_str()); - return (bReturnSame && !dest) ? szName.data() : dest; - } - ////////////////////////////////////////////////////////////////////////// void Archive::SetLocalizationFolder(AZStd::string_view sLocalizationFolder) { @@ -591,28 +417,6 @@ namespace AZ::IO m_sLocalizationFolder += AZ_CORRECT_FILESYSTEM_SEPARATOR_STRING; } - ////////////////////////////////////////////////////////////////////////// - void Archive::SetAlias(AZStd::string_view szName, AZStd::string_view szAlias, bool bAdd) - { - constexpr size_t MaxAliasLength = 32; - AZStd::fixed_string aliasKey{ szName }; - if (bAdd) - { - AZ::IO::PathString aliasPath{ szAlias }; - AZ::IO::FileIOBase::GetDirectInstance()->SetAlias(aliasKey.c_str(), aliasPath.c_str()); - } - else - { - AZ::IO::FileIOBase::GetDirectInstance()->ClearAlias(aliasKey.c_str()); - } - } - - - const char* Archive::AdjustFileName(AZStd::string_view src, char* dst, size_t dstSize, uint32_t, bool) - { - AZ::IO::FixedMaxPathString srcPath{ src }; - return AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(srcPath.c_str(), dst, dstSize) ? dst : nullptr; - } ////////////////////////////////////////////////////////////////////////// bool Archive::IsFileExist(AZStd::string_view sFilename, EFileSearchLocation fileLocation) @@ -679,52 +483,50 @@ namespace AZ::IO } ////////////////////////////////////////////////////////////////////////// - AZ::IO::HandleType Archive::FOpen(AZStd::string_view pName, const char* szMode, uint32_t nInputFlags) + AZ::IO::HandleType Archive::FOpen(AZStd::string_view pName, const char* szMode) { AZ_PROFILE_FUNCTION(AzCore); const size_t pathLen = pName.size(); - if (pathLen == 0 || pathLen >= MaxPath) + if (pathLen == 0 || pathLen >= AZ::IO::MaxPathLength) { return AZ::IO::InvalidHandle; } SAutoCollectFileAccessTime accessTime(this); - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - - const bool bFileCanBeOnDisk = 0 != (nInputFlags & FOPEN_ONDISK); - // get the priority into local variable to avoid it changing in the course of // this function execution (?) const ArchiveLocationPriority nVarPakPriority = GetPakPriority(); AZ::IO::OpenMode nOSFlags = AZ::IO::GetOpenModeFromStringMode(szMode); - auto szFullPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pName); - if (!szFullPath) + AZ::IO::FixedMaxPath szFullPath; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(szFullPath, pName)) { - AZ_Assert(szFullPath, "Unable to resolve path for filepath %.*s", aznumeric_cast(pName.size()), pName.data()); + AZ_Assert(false, "Unable to resolve path for filepath %.*s", aznumeric_cast(pName.size()), pName.data()); return false; } const bool fileWritable = (nOSFlags & (AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeAppend | AZ::IO::OpenMode::ModeUpdate)) != AZ::IO::OpenMode::Invalid; - AZ_PROFILE_SCOPE(Game, "File: %s Archive: %p", szFullPath->c_str(), this); + AZ_PROFILE_SCOPE(Game, "File: %s Archive: %p", szFullPath.c_str(), this); if (fileWritable) { // we need to open the file for writing, but we failed to do so. // the only reason that can be is that there are no directories for that file. // now create those dirs - if (!MakeDir(szFullPath->ParentPath().Native())) + if (AZ::IO::FixedMaxPath parentPath = szFullPath.ParentPath(); + !AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(parentPath.c_str())) { return AZ::IO::InvalidHandle; } - if (AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath->c_str(), nOSFlags, fileHandle)) + if (AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; + AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath.c_str(), nOSFlags, fileHandle)) { if (az_archive_verbosity) { - AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s for writing", szFullPath->c_str()); + AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s for writing", szFullPath.c_str()); } return fileHandle; } @@ -732,35 +534,41 @@ namespace AZ::IO return AZ::IO::InvalidHandle; } - if (nVarPakPriority == ArchiveLocationPriority::ePakPriorityFileFirst) // if the file system files have priority now.. + auto OpenFromFileSystem = [this, &szFullPath, pName, nOSFlags]() -> HandleType { - if (AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath->c_str(), nOSFlags, fileHandle)) + if (AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; + AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath.c_str(), nOSFlags, fileHandle)) { if (az_archive_verbosity) { - AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s with FileFirst priority", szFullPath->c_str()); + AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s on for reading", szFullPath.c_str()); } RecordFile(fileHandle, pName); return fileHandle; } - } - uint32_t archiveFlags = 0; - CCachedFileDataPtr pFileData = GetFileData(szFullPath->Native(), archiveFlags); - if (pFileData) + return AZ::IO::InvalidHandle; + }; + auto OpenFromArchive = [this, &szFullPath, pName]() -> HandleType { - bool logged = false; - ZipDir::Cache* pZip = pFileData->GetZip(); - if (pZip) + uint32_t archiveFlags = 0; + CCachedFileDataPtr pFileData = GetFileData(szFullPath.Native(), archiveFlags); + if (pFileData == nullptr) { - const char* pZipFilePath = pZip->GetFilePath(); - if (pZipFilePath && pZipFilePath[0]) + return AZ::IO::InvalidHandle; + } + + bool logged = false; + if (ZipDir::Cache* pZip = pFileData->GetZip(); pZip != nullptr) + { + AZ::IO::PathView pZipFilePath = pZip->GetFilePath(); + if (!pZipFilePath.empty()) { if (az_archive_verbosity) { - AZ_TracePrintf("Archive", " Archive::FOpen() has opened requested file %s from archive %s, disk offset %u", - szFullPath->c_str(), pZipFilePath, pFileData->GetFileEntry()->nFileDataOffset); + AZ_TracePrintf("Archive", " Archive::FOpen() has opened requested file %s from archive %.*s, disk offset %u", + szFullPath.c_str(), AZ_STRING_ARG(pZipFilePath.Native()), pFileData->GetFileEntry()->nFileDataOffset); logged = true; } } @@ -771,57 +579,54 @@ namespace AZ::IO if (az_archive_verbosity) { AZ_TracePrintf("Archive", " Archive::FOpen() has opened requested file %s from an archive file who's path isn't known", - szFullPath->c_str()); + szFullPath.c_str()); } } - } - else - { - if (nVarPakPriority != ArchiveLocationPriority::ePakPriorityPakOnly || bFileCanBeOnDisk) // if the archive files had more priority, we didn't attempt fopen before- try it now + + size_t nFile; + // find the empty slot and open the file there; return the handle { - if (AZ::IO::FileIOBase::GetDirectInstance()->Open(szFullPath->c_str(), nOSFlags, fileHandle)) + // try to open the pseudofile from one of the zips, make sure there is no user alias + AZStd::unique_lock lock(m_csOpenFiles); + for (nFile = 0; nFile < m_arrOpenFiles.size() && m_arrOpenFiles[nFile]->GetFile(); ++nFile) { - if (az_archive_verbosity) - { - AZ_TracePrintf("Archive", " Archive::FOpen() has directly opened requested file %s after failing to open from archives", - szFullPath->c_str()); - } - - RecordFile(fileHandle, pName); - return fileHandle; + continue; } + if (nFile == m_arrOpenFiles.size()) + { + m_arrOpenFiles.emplace_back(AZStd::make_unique()); + } + AZStd::unique_ptr& rZipFile = m_arrOpenFiles[nFile]; + rZipFile->Construct(pFileData.get()); } - return AZ::IO::InvalidHandle; // we can't find such file in the pack files - } - // try to open the pseudofile from one of the zips, make sure there is no user alias - AZStd::unique_lock lock(m_csOpenFiles); + AZ::IO::HandleType handle = (AZ::IO::HandleType)(nFile + ArchiveInternal::PseudoFileIdxOffset); - size_t nFile; - // find the empty slot and open the file there; return the handle + RecordFile(handle, pName); + + return handle; // the handle to the file + }; + + switch (nVarPakPriority) { - for (nFile = 0; nFile < m_arrOpenFiles.size() && m_arrOpenFiles[nFile]->GetFile(); ++nFile) - { - continue; - } - if (nFile == m_arrOpenFiles.size()) - { - m_arrOpenFiles.emplace_back(AZStd::make_unique()); - } - AZStd::unique_ptr& rZipFile = m_arrOpenFiles[nFile]; - rZipFile->Construct(pFileData.get()); - } - - AZ::IO::HandleType ret = (AZ::IO::HandleType)(nFile + ArchiveInternal::PseudoFileIdxOffset); - - if (az_archive_verbosity) + case ArchiveLocationPriority::ePakPriorityFileFirst: { - AZ_TracePrintf("Archive", " Archive::FOpen() has opened psuedo zip file %.*s", aznumeric_cast(pName.size()), pName.data()); + AZ::IO::HandleType fileHandle = OpenFromFileSystem(); + return fileHandle != AZ::IO::InvalidHandle ? fileHandle : OpenFromArchive(); + } + case ArchiveLocationPriority::ePakPriorityPakFirst: + { + AZ::IO::HandleType fileHandle = OpenFromArchive(); + return fileHandle != AZ::IO::InvalidHandle ? fileHandle : OpenFromFileSystem(); + } + case ArchiveLocationPriority::ePakPriorityPakOnly: + { + return OpenFromArchive(); + } + default: + return AZ::IO::InvalidHandle; } - RecordFile(ret, pName); - - return ret; // the handle to the file } ////////////////////////////////////////////////////////////////////////// @@ -872,19 +677,14 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// // tests if the given file path refers to an existing file inside registered (opened) packs // the path must be absolute normalized lower-case with forward-slashes - ZipDir::FileEntry* Archive::FindPakFileEntry(AZStd::string_view szPath, uint32_t& nArchiveFlags, ZipDir::CachePtr* pZip, bool bSkipInMemoryArchives) const + ZipDir::FileEntry* Archive::FindPakFileEntry(AZStd::string_view szPath, uint32_t& nArchiveFlags, ZipDir::CachePtr* pZip) const { - AZ::IO::FixedMaxPath unaliasedPath; + AZ::IO::FixedMaxPath resolvedPath; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(resolvedPath, szPath)) { - auto convertedPath = ArchiveInternal::ConvertAbsolutePathToAliasedPath(szPath); - - if (!convertedPath) - { - AZ_Error("Archive", false, "Path %s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", aznumeric_cast(szPath.size()), - szPath.data(), AZ::IO::MaxPathLength); - return nullptr; - } - unaliasedPath = AZStd::move(*convertedPath); + AZ_Error("Archive", false, "Path %s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", aznumeric_cast(szPath.size()), + szPath.data(), AZ::IO::MaxPathLength); + return nullptr; } @@ -892,28 +692,17 @@ namespace AZ::IO // scan through registered archive files and try to find this file for (auto itZip = m_arrZips.rbegin(); itZip != m_arrZips.rend(); ++itZip) { - if (bSkipInMemoryArchives && itZip->pArchive->GetFlags() & INestedArchive::FLAGS_IN_MEMORY_MASK) - { - continue; - } - if (itZip->pArchive->GetFlags() & INestedArchive::FLAGS_DISABLE_PAK) { continue; } - auto [bindRootIter, unaliasedIter] = AZStd::mismatch(itZip->m_pathBindRoot.begin(), itZip->m_pathBindRoot.end(), - unaliasedPath.begin(), unaliasedPath.end()); // If the bindRootIter is at the end then it is a prefix of the source path - if (bindRootIter == itZip->m_pathBindRoot.end()) + if (resolvedPath.IsRelativeTo(itZip->m_pathBindRoot)) { // unaliasedIter is past the bind root, so append the rest of it to a new relative path object - AZ::IO::FixedMaxPath relativePathInZip; - for (; unaliasedIter != unaliasedPath.end(); ++unaliasedIter) - { - relativePathInZip /= *unaliasedIter; - } + AZ::IO::FixedMaxPath relativePathInZip = resolvedPath.LexicallyRelative(itZip->m_pathBindRoot); ZipDir::FileEntry* pFileEntry = itZip->pZip->FindFile(relativePathInZip.Native()); if (pFileEntry) @@ -955,7 +744,7 @@ namespace AZ::IO } // returns the path to the archive in which the file was opened - const char* Archive::GetFileArchivePath(AZ::IO::HandleType fileHandle) + AZ::IO::PathView Archive::GetFileArchivePath(AZ::IO::HandleType fileHandle) { ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); if (pseudoFile) @@ -964,7 +753,7 @@ namespace AZ::IO } else { - return nullptr; + return {}; } } @@ -1066,7 +855,7 @@ namespace AZ::IO return 1; } - size_t Archive::FWrite(const void* data, size_t length, size_t elems, AZ::IO::HandleType fileHandle) + size_t Archive::FWrite(const void* data, size_t bytesToWrite, AZ::IO::HandleType fileHandle) { SAutoCollectFileAccessTime accessTime(this); @@ -1077,47 +866,28 @@ namespace AZ::IO } AZ_Assert(fileHandle != AZ::IO::InvalidHandle, "Invalid file has been passed to FWrite"); - if (AZ::IO::FileIOBase::GetDirectInstance()->Write(fileHandle, data, length * elems)) + if (AZ::u64 bytesWritten{}; AZ::IO::FileIOBase::GetDirectInstance()->Write(fileHandle, data, bytesToWrite, &bytesWritten)) { - return elems; + return bytesWritten; } return 0; } ////////////////////////////////////////////////////////////////////////// - size_t Archive::FReadRaw(void* pData, size_t nSize, size_t nCount, AZ::IO::HandleType fileHandle) + size_t Archive::FRead(void* pData, size_t bytesToRead, AZ::IO::HandleType fileHandle) { AZ_PROFILE_FUNCTION(AzCore); - AZ_PROFILE_SCOPE(Game, "Size: %d Archive: %p", nSize, this); SAutoCollectFileAccessTime accessTime(this); ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); if (pseudoFile) { - return pseudoFile->FRead(pData, nSize, nCount, fileHandle); + return pseudoFile->FRead(pData, bytesToRead, fileHandle); } AZ::u64 bytesRead = 0; - AZ::IO::FileIOBase::GetDirectInstance()->Read(fileHandle, pData, nSize * nCount, false, &bytesRead); - return static_cast(bytesRead / nSize); - } - - ////////////////////////////////////////////////////////////////////////// - size_t Archive::FReadRawAll(void* pData, size_t nFileSize, AZ::IO::HandleType fileHandle) - { - AZ_PROFILE_FUNCTION(AzCore); - - SAutoCollectFileAccessTime accessTime(this); - ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); - if (pseudoFile) - { - return pseudoFile->FReadAll(pData, nFileSize, fileHandle); - } - - AZ::IO::FileIOBase::GetDirectInstance()->Seek(fileHandle, 0, AZ::IO::SeekType::SeekFromStart); - AZ::u64 bytesRead = 0; - AZ::IO::FileIOBase::GetDirectInstance()->Read(fileHandle, pData, nFileSize, false, &bytesRead); - return static_cast(bytesRead); + AZ::IO::FileIOBase::GetDirectInstance()->Read(fileHandle, pData, bytesToRead, false, &bytesRead); + return bytesRead; } ////////////////////////////////////////////////////////////////////////// @@ -1234,48 +1004,6 @@ namespace AZ::IO } - int Archive::FPrintf(AZ::IO::HandleType fileHandle, const char* szFormat, ...) - { - SAutoCollectFileAccessTime accessTime(this); - ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); - if (pseudoFile) - { - return 0; // we don't support it now - } - - va_list arglist; - int rv; - va_start(arglist, szFormat); - rv = static_cast(AZ::IO::PrintV(fileHandle, szFormat, arglist)); - va_end(arglist); - return rv; - } - - char* Archive::FGets(char* str, int n, AZ::IO::HandleType fileHandle) - { - SAutoCollectFileAccessTime accessTime(this); - ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); - if (pseudoFile) - { - return pseudoFile->FGets(str, n); - } - - return AZ::IO::FGetS(str, n, fileHandle); - } - - int Archive::Getc(AZ::IO::HandleType fileHandle) - { - SAutoCollectFileAccessTime accessTime(this); - ArchiveInternal::CZipPseudoFile* pseudoFile = GetPseudoFile(fileHandle); - if (pseudoFile) - { - return pseudoFile->Getc(); - } - - return AZ::IO::GetC(fileHandle); - } - - ////////////////////////////////////////////////////////////////////////// AZ::IO::ArchiveFileIterator Archive::FindFirst(AZStd::string_view pDir, EFileSearchType searchType) { @@ -1304,7 +1032,7 @@ namespace AZ::IO break; } - AZStd::intrusive_ptr pFindData = new AZ::IO::FindData(); + AZStd::intrusive_ptr pFindData = aznew AZ::IO::FindData(); pFindData->Scan(this, szFullPath->Native(), bAllowUseFileSystem, bScanZips); return pFindData->Fetch(); @@ -1322,18 +1050,6 @@ namespace AZ::IO return true; } - ////////////////////////////////////////////////////////////////////////// - bool Archive::LoadPakToMemory([[maybe_unused]] AZStd::string_view pName, [[maybe_unused]] IArchive::EInMemoryArchiveLocation nLoadPakToMemory, - [[maybe_unused]] AZStd::intrusive_ptr pMemoryBlock) - { - return true; - } - - ////////////////////////////////////////////////////////////////////////// - void Archive::LoadPaksToMemory([[maybe_unused]] int nMaxArchiveSize, [[maybe_unused]] bool bLoadToMemory) - { - } - auto Archive::GetLevelPackOpenEvent() -> LevelPackOpenEvent* { return &m_levelOpenEvent; @@ -1344,7 +1060,7 @@ namespace AZ::IO return &m_levelCloseEvent; } //====================================================================== - bool Archive::OpenPack(AZStd::string_view szBindRootIn, AZStd::string_view szPath, uint32_t nFlags, + bool Archive::OpenPack(AZStd::string_view szBindRootIn, AZStd::string_view szPath, AZStd::intrusive_ptr pData, AZ::IO::FixedMaxPathString* pFullPath, bool addLevels) { AZ_Assert(!szBindRootIn.empty(), "Bind Root should not be empty"); @@ -1363,7 +1079,7 @@ namespace AZ::IO return false; } - bool result = OpenPackCommon(szBindRoot->Native(), szFullPath->Native(), nFlags, pData, addLevels); + bool result = OpenPackCommon(szBindRoot->Native(), szFullPath->Native(), pData, addLevels); if (pFullPath) { @@ -1373,7 +1089,7 @@ namespace AZ::IO return result; } - bool Archive::OpenPack(AZStd::string_view szPath, uint32_t nFlags, AZStd::intrusive_ptr pData, + bool Archive::OpenPack(AZStd::string_view szPath, AZStd::intrusive_ptr pData, AZ::IO::FixedMaxPathString* pFullPath, bool addLevels) { auto szFullPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(szPath); @@ -1385,7 +1101,7 @@ namespace AZ::IO AZStd::string_view bindRoot = szFullPath->ParentPath().Native(); - bool result = OpenPackCommon(bindRoot, szFullPath->Native(), nFlags, pData, addLevels); + bool result = OpenPackCommon(bindRoot, szFullPath->Native(), pData, addLevels); if (pFullPath) { @@ -1396,34 +1112,22 @@ namespace AZ::IO } - bool Archive::OpenPackCommon(AZStd::string_view szBindRoot, AZStd::string_view szFullPath, uint32_t nArchiveFlags, + bool Archive::OpenPackCommon(AZStd::string_view szBindRoot, AZStd::string_view szFullPath, AZStd::intrusive_ptr pData, bool addLevels) { - // Note this will replace @devassets@ with @assets@ to provide a proper bind root for the archives - auto conversionResult = ArchiveInternal::ConvertAbsolutePathToAliasedPath(szBindRoot); - if (!conversionResult) - { - AZ_Error("Archive", false, "Path %.*s cannot be converted to @alias@ form. It is longer than MaxPathLength %zu", - aznumeric_cast(szBindRoot.size()), szBindRoot.data(), AZ::IO::MaxPathLength); - return false; - } - // setup PackDesc before the duplicate test PackDesc desc; - desc.strFileName = szFullPath; + desc.m_strFileName = szFullPath; - if (!conversionResult || conversionResult->empty()) + if (AZ::IO::FixedMaxPath pathBindRoot; !AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pathBindRoot, szBindRoot)) { - desc.m_pathBindRoot = "@assets@"; + AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pathBindRoot, "@assets@"); + desc.m_pathBindRoot = pathBindRoot.LexicallyNormal().String(); } else { - // Create a bind root without any trailing slashes - desc.m_pathBindRoot = AZStd::move(*conversionResult); - if (desc.m_pathBindRoot.HasRelativePath() && !desc.m_pathBindRoot.HasFilename()) - { - desc.m_pathBindRoot = desc.m_pathBindRoot.ParentPath(); - } + // Create a bind root + desc.m_pathBindRoot = pathBindRoot.LexicallyNormal().String(); } // hold the lock from the point we query the zip array, @@ -1433,56 +1137,23 @@ namespace AZ::IO // try to find this - maybe the pack has already been opened for (auto it = m_arrZips.begin(); it != m_arrZips.end(); ++it) { - const char* pFilePath = it->pZip->GetFilePath(); - if (pFilePath == desc.strFileName && it->m_pathBindRoot == desc.m_pathBindRoot) + if (AZ::IO::PathView archiveFilePath = it->pZip->GetFilePath(); + archiveFilePath == desc.m_strFileName && it->m_pathBindRoot == desc.m_pathBindRoot) { return true; // already opened } } } - int flags = INestedArchive::FLAGS_OPTIMIZED_READ_ONLY | INestedArchive::FLAGS_ABSOLUTE_PATHS; - if ((nArchiveFlags & FLAGS_PAK_IN_MEMORY) != 0) - { - flags |= INestedArchive::FLAGS_IN_MEMORY; - } - if ((nArchiveFlags & FLAGS_PAK_IN_MEMORY_CPU) != 0) - { - flags |= INestedArchive::FLAGS_IN_MEMORY_CPU; - } - if ((nArchiveFlags & FLAGS_FILENAMES_AS_CRC32) != 0) - { - flags |= INestedArchive::FLAGS_FILENAMES_AS_CRC32; - } - if ((nArchiveFlags & FLAGS_REDIRECT_TO_DISC) != 0) - { - flags |= FLAGS_REDIRECT_TO_DISC; - } - if ((nArchiveFlags & INestedArchive::FLAGS_OVERRIDE_PAK) != 0) - { - flags |= INestedArchive::FLAGS_OVERRIDE_PAK; - } - if ((nArchiveFlags & FLAGS_LEVEL_PAK_INSIDE_PAK) != 0) - { - flags |= INestedArchive::FLAGS_INSIDE_PAK; - } + const int flags = INestedArchive::FLAGS_OPTIMIZED_READ_ONLY | INestedArchive::FLAGS_ABSOLUTE_PATHS; desc.pArchive = OpenArchive(szFullPath, szBindRoot, flags, pData); if (!desc.pArchive) { return false; // couldn't open the archive } - if (m_filesCachedOnHDD.size()) - { - uint32_t crc = AZ::Crc32(szFullPath); - if (m_filesCachedOnHDD.find(crc) != m_filesCachedOnHDD.end()) - { - uint32_t eFlags = desc.pArchive->GetFlags(); - desc.pArchive->SetFlags(eFlags | INestedArchive::FLAGS_ON_HDD); - } - } - AZ_TracePrintf("Archive", "Opening archive file %.*s\n", aznumeric_cast(szFullPath.size()), szFullPath.data()); + AZ_TracePrintf("Archive", "Opening archive file %.*s\n", AZ_STRING_ARG(szFullPath)); desc.pZip = static_cast(desc.pArchive.get())->GetCache(); AZStd::unique_lock lock(m_csZips); @@ -1493,20 +1164,14 @@ namespace AZ::IO // All we have to do is name the archive appropriately to make // sure later archives added to the current set of archives sort higher // and therefore get used instead of lower sorted archives - AZStd::string_view nextBundle; + AZ::IO::PathView nextBundle; ZipArray::reverse_iterator revItZip = m_arrZips.rbegin(); - if ((nArchiveFlags & INestedArchive::FLAGS_OVERRIDE_PAK) == 0) + for (; revItZip != m_arrZips.rend(); ++revItZip) { - for (; revItZip != m_arrZips.rend(); ++revItZip) + nextBundle = revItZip->GetFullPath(); + if (desc.GetFullPath() > revItZip->GetFullPath()) { - if ((revItZip->pArchive->GetFlags() & INestedArchive::FLAGS_OVERRIDE_PAK) == 0) - { - nextBundle = revItZip->GetFullPath(); - if (azstricmp(desc.GetFullPath(), revItZip->GetFullPath()) > 0) - { - break; - } - } + break; } } @@ -1555,17 +1220,17 @@ namespace AZ::IO } AZ::IO::ArchiveNotificationBus::Broadcast([](AZ::IO::ArchiveNotifications* archiveNotifications, const char* bundleName, - AZStd::shared_ptr bundleManifest, const char* nextBundle, AZStd::shared_ptr bundleCatalog) + AZStd::shared_ptr bundleManifest, const AZ::IO::FixedMaxPath& nextBundle, AZStd::shared_ptr bundleCatalog) { - archiveNotifications->BundleOpened(bundleName, bundleManifest, nextBundle, bundleCatalog); - }, desc.strFileName.c_str(), bundleManifest, nextBundle.data(), bundleCatalog); + archiveNotifications->BundleOpened(bundleName, bundleManifest, nextBundle.c_str(), bundleCatalog); + }, desc.m_strFileName.c_str(), bundleManifest, nextBundle, bundleCatalog); return true; } // after this call, the file will be unlocked and closed, and its contents won't be used to search for files - bool Archive::ClosePack(AZStd::string_view pName, [[maybe_unused]] uint32_t nFlags) + bool Archive::ClosePack(AZStd::string_view pName) { auto szZipPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pName); if (!szZipPath) @@ -1581,16 +1246,16 @@ namespace AZ::IO AZStd::unique_lock lock(m_csZips); for (auto it = m_arrZips.begin(); it != m_arrZips.end();) { - if (azstricmp(szZipPath->c_str(), it->GetFullPath()) == 0) + if (szZipPath == it->GetFullPath()) { // this is the pack with the given name - remove it, and if possible it will be deleted // the zip is referenced from the archive and *it; the archive is referenced only from *it // // the pZip (cache) can be referenced from stream engine and pseudo-files. // the archive can be referenced from outside - AZ::IO::ArchiveNotificationBus::Broadcast([](AZ::IO::ArchiveNotifications* archiveNotifications, const char* bundleName) + AZ::IO::ArchiveNotificationBus::Broadcast([](AZ::IO::ArchiveNotifications* archiveNotifications, const AZ::IO::FixedMaxPath& bundleName) { - archiveNotifications->BundleClosed(bundleName); + archiveNotifications->BundleClosed(bundleName.c_str()); }, it->GetFullPath()); if (usePrefabSystemForLevels) @@ -1643,7 +1308,7 @@ namespace AZ::IO return foundMatchingPackFile; } - bool Archive::OpenPacks(AZStd::string_view pWildcardIn, uint32_t nFlags, AZStd::vector* pFullPaths) + bool Archive::OpenPacks(AZStd::string_view pWildcardIn, AZStd::vector* pFullPaths) { auto strBindRoot{ AZ::IO::PathView(pWildcardIn).ParentPath() }; AZ::IO::FixedMaxPath bindRoot; @@ -1651,10 +1316,10 @@ namespace AZ::IO { bindRoot = strBindRoot; } - return OpenPacksCommon(bindRoot.Native(), pWildcardIn, nFlags, pFullPaths); + return OpenPacksCommon(bindRoot.Native(), pWildcardIn, pFullPaths); } - bool Archive::OpenPacks(AZStd::string_view szBindRoot, AZStd::string_view pWildcardIn, uint32_t nFlags, AZStd::vector* pFullPaths) + bool Archive::OpenPacks(AZStd::string_view szBindRoot, AZStd::string_view pWildcardIn, AZStd::vector* pFullPaths) { auto bindRoot = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(szBindRoot); if (!bindRoot) @@ -1662,16 +1327,16 @@ namespace AZ::IO AZ_Assert(false, "Unable to resolve path for filepath %.*s", aznumeric_cast(szBindRoot.size()), szBindRoot.data()); return false; } - return OpenPacksCommon(bindRoot->Native(), pWildcardIn, nFlags, pFullPaths); + return OpenPacksCommon(bindRoot->Native(), pWildcardIn, pFullPaths); } - bool Archive::OpenPacksCommon(AZStd::string_view szDir, AZStd::string_view pWildcardIn, uint32_t nArchiveFlags, AZStd::vector* pFullPaths, bool addLevels) + bool Archive::OpenPacksCommon(AZStd::string_view szDir, AZStd::string_view pWildcardIn, AZStd::vector* pFullPaths, bool addLevels) { constexpr AZStd::string_view wildcards{ "*?" }; if (wildcards.find_first_of(pWildcardIn) == AZStd::string_view::npos) { // No wildcards, just open pack - if (OpenPackCommon(szDir, pWildcardIn, nArchiveFlags, nullptr, addLevels)) + if (OpenPackCommon(szDir, pWildcardIn, nullptr, addLevels)) { if (pFullPaths) { @@ -1683,25 +1348,24 @@ namespace AZ::IO if (AZ::IO::ArchiveFileIterator fileIterator = FindFirst(pWildcardIn, IArchive::eFileSearchType_AllowOnDiskOnly); fileIterator) { - AZStd::vector files; + AZStd::vector files; do { - AZStd::string foundFilename{ fileIterator.m_filename }; - AZStd::to_lower(foundFilename.begin(), foundFilename.end()); - files.emplace_back(AZStd::move(foundFilename)); + auto& foundFilename = files.emplace_back(fileIterator.m_filename); + AZStd::to_lower(foundFilename.Native().begin(), foundFilename.Native().end()); } while (fileIterator = FindNext(fileIterator)); - // Open files in alphabet order. + // Open files in alphabetical order. AZStd::sort(files.begin(), files.end()); bool bAllOk = true; - for (const AZStd::string& file : files) + for (const AZ::IO::FixedMaxPath& file : files) { - bAllOk = OpenPackCommon(szDir, file, nArchiveFlags, nullptr, addLevels) && bAllOk; + bAllOk = OpenPackCommon(szDir, file.Native(), nullptr, addLevels) && bAllOk; if (pFullPaths) { - pFullPaths->emplace_back(file.begin(), file.end()); + pFullPaths->emplace_back(AZStd::move(file.Native())); } } @@ -1713,7 +1377,7 @@ namespace AZ::IO } - bool Archive::ClosePacks(AZStd::string_view pWildcardIn, uint32_t nFlags) + bool Archive::ClosePacks(AZStd::string_view pWildcardIn) { auto path = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pWildcardIn); if (!path) @@ -1723,26 +1387,13 @@ namespace AZ::IO } return AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(AZ::IO::FixedMaxPath(path->ParentPath()).c_str(), - AZ::IO::FixedMaxPath(path->Filename()).c_str(), [&](const char* filePath) -> bool + AZ::IO::FixedMaxPath(path->Filename()).c_str(), [this](const char* filePath) -> bool { - ClosePack(filePath, nFlags); + ClosePack(filePath); return true; }); } - - ///////////////////////////////////////////////////// - bool Archive::Init([[maybe_unused]] AZStd::string_view szBasePath) - { - BusConnect(); - return true; - } - - void Archive::Release() - { - BusDisconnect(); - } - ////////////////////////////////////////////////////////////////////////// ArchiveInternal::CZipPseudoFile* Archive::GetPseudoFile(AZ::IO::HandleType fileHandle) const { @@ -1912,36 +1563,6 @@ namespace AZ::IO return m_pFileEntry->nFileDataOffset; } - bool Archive::MakeDir(AZStd::string_view szPathIn) - { - AZ::IO::StackString pathStr{ szPathIn }; - // Determine if there is a period ('.') after the last slash to determine if the path contains a file. - // This used to be a strchr on the whole path which could contain a period in a path, such as network domain paths (domain.user). - size_t findDotFromPos = pathStr.rfind(AZ_CORRECT_FILESYSTEM_SEPARATOR); - if (findDotFromPos == AZ::IO::StackString::npos) - { - findDotFromPos = pathStr.rfind(AZ_WRONG_FILESYSTEM_SEPARATOR); - if (findDotFromPos == AZ::IO::StackString::npos) - { - findDotFromPos = 0; - } - } - size_t dotPos = pathStr.find('.', findDotFromPos); - if (dotPos != AZ::IO::StackString::npos) - { - AZStd::string fullPath; - AZ::StringFunc::Path::GetFullPath(pathStr.c_str(), fullPath); - pathStr = fullPath; - } - - if (pathStr.empty()) - { - return true; - } - - return AZ::IO::FileIOBase::GetDirectInstance()->CreatePath(pathStr.c_str()); - } - ////////////////////////////////////////////////////////////////////////// // open the physical archive file - creates if it doesn't exist // returns nullptr if it's invalid or can't open the file @@ -1962,15 +1583,6 @@ namespace AZ::IO uint32_t nFactoryFlags = 0; - if (nFlags & INestedArchive::FLAGS_IN_MEMORY) - { - nFactoryFlags |= ZipDir::CacheFactory::FLAGS_IN_MEMORY; - } - - if (nFlags & INestedArchive::FLAGS_IN_MEMORY_CPU) - { - nFactoryFlags |= ZipDir::CacheFactory::FLAGS_IN_MEMORY_CPU; - } if (nFlags & INestedArchive::FLAGS_DONT_COMPACT) { @@ -1982,10 +1594,6 @@ namespace AZ::IO nFactoryFlags |= ZipDir::CacheFactory::FLAGS_READ_ONLY; } - if (nFlags & INestedArchive::FLAGS_INSIDE_PAK) - { - nFactoryFlags |= ZipDir::CacheFactory::FLAGS_READ_INSIDE_PAK; - } INestedArchive* pArchive = FindArchive(szFullPath->Native()); if (pArchive) @@ -2016,7 +1624,10 @@ namespace AZ::IO if (!pakOnDisk && (nFactoryFlags & ZipDir::CacheFactory::FLAGS_READ_ONLY)) { // Archive file not found. - AZ_TracePrintf("Archive", "Archive file %s does not exist\n", szFullPath->c_str()); + if (az_archive_verbosity) + { + AZ_TracePrintf("Archive", "Archive file %s does not exist\n", szFullPath->c_str()); + } return nullptr; } @@ -2031,148 +1642,6 @@ namespace AZ::IO return nullptr; } - uint32_t Archive::ComputeCRC(AZStd::string_view szPath, [[maybe_unused]] uint32_t nFileOpenFlags) - { - AZ_Assert(!szPath.empty(), "Path to compute Crc cannot be empty"); - - AZ::Crc32 dwCRC = 0; - - // generate crc32 - { - // avoid heap allocation by working in 8k chunks - const uint32_t dwChunkSize = 1024 * 8; - - // note that the actual CRC algorithm can work on various sized words but operates on individual words - // so there's little difference between feeding it 8k and 8mb, except you might save yourself some io calls. - - uint8_t pMem[dwChunkSize]; - - - AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); - if (!fileIO) - { - return ZipDir::ZD_ERROR_INVALID_CALL; - } - - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - - if (AZ::IO::PathString filepath{ szPath }; !fileIO->Open(filepath.c_str(), AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, fileHandle)) - { - return ZipDir::ZD_ERROR_INVALID_PATH; - } - // load whole file in chunks and compute CRC - while (true) - { - AZ::u64 bytesRead = 0; - fileIO->Read(fileHandle, pMem, dwChunkSize, false, &bytesRead); // read up to ChunkSize bytes and put the actual number of bytes read into bytesRead. - - if (bytesRead) - { - dwCRC.Add(pMem, aznumeric_caster(bytesRead)); - } - else - { - break; - } - } - - FClose(fileHandle); - } - - return dwCRC; - } - - bool Archive::ComputeMD5(AZStd::string_view szPath, uint8_t* md5, uint32_t nFileOpenFlags, bool useDirectFileAccess) - { - if (szPath.empty() || !md5) - { - return false; - } - - MD5Context context; - MD5Init(&context); - - // generate checksum - { - const AZ::u64 dwChunkSize = 1024 * 1024; // 1MB chunks - AZStd::unique_ptr pMem{ reinterpret_cast(AZ::AllocatorInstance::Get().Allocate(dwChunkSize, alignof(uint8_t))), - [](uint8_t* ptr) { AZ::AllocatorInstance::Get().DeAllocate(ptr); } - }; - - if (!pMem) - { - return false; - } - - AZ::u64 dwSize = 0; - - AZ::IO::PathString filepath{ szPath }; - if (useDirectFileAccess) - { - - AZ::IO::FileIOBase::GetDirectInstance()->Size(filepath.c_str(), dwSize); - } - else - { - AZ::IO::HandleType fileHandle = FOpen(filepath, "rb", nFileOpenFlags); - - if (fileHandle != AZ::IO::InvalidHandle) - { - dwSize = FGetSize(fileHandle); - FClose(fileHandle); - } - } - - // rbx open flags, x is a hint to not cache whole file in memory. - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - if (useDirectFileAccess) - { - AZ::IO::FileIOBase::GetDirectInstance()->Open(filepath.c_str(), AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, fileHandle); - } - else - { - fileHandle = FOpen(filepath, "rbx", nFileOpenFlags); - } - - if (fileHandle == AZ::IO::InvalidHandle) - { - return false; - } - - // load whole file in chunks and compute Md5 - while (dwSize > 0) - { - uint64_t dwLocalSize = AZStd::min(dwSize, dwChunkSize); - - AZ::u64 read{ 0 }; - if (useDirectFileAccess) - { - AZ::IO::FileIOBase::GetDirectInstance()->Read(fileHandle, pMem.get(), dwLocalSize, false, &read); - } - else - { - read = FReadRaw(pMem.get(), 1, dwLocalSize, fileHandle); - } - AZ_Assert(read == dwLocalSize, "Failed to read dwLocalSize %" PRIu32 " bytes from file", dwLocalSize); - - MD5Update(&context, pMem.get(), aznumeric_cast(dwLocalSize)); - dwSize -= dwLocalSize; - } - - if (useDirectFileAccess) - { - AZ::IO::FileIOBase::GetDirectInstance()->Close(fileHandle); - } - else - { - FClose(fileHandle); - } - } - - MD5Final(md5, &context); - return true; - } - void Archive::Register(INestedArchive* pArchive) { AZStd::unique_lock lock(m_archiveMutex); @@ -2185,7 +1654,7 @@ namespace AZ::IO AZStd::unique_lock lock(m_archiveMutex); if (pArchive) { - AZ_TracePrintf("Archive", "Closing Archive file: %s", pArchive->GetFullPath()); + AZ_TracePrintf("Archive", "Closing Archive file: %.*s\n", AZ_STRING_ARG(pArchive->GetFullPath().Native())); } ArchiveArray::iterator it; if (m_arrArchives.size() < 16) @@ -2212,7 +1681,7 @@ namespace AZ::IO { AZStd::shared_lock lock(m_archiveMutex); auto it = AZStd::lower_bound(m_arrArchives.begin(), m_arrArchives.end(), szFullPath, NestedArchiveSortByName()); - if (it != m_arrArchives.end() && !azstrnicmp(szFullPath.data(), (*it)->GetFullPath(), szFullPath.size())) + if (it != m_arrArchives.end() && szFullPath == (*it)->GetFullPath()) { return *it; } @@ -2280,7 +1749,7 @@ namespace AZ::IO case RFOM_Disabled: default: - AZ_Assert(false, "File record option %d", aznumeric_cast(eList));; + AZ_Assert(false, "File record option %d", aznumeric_cast(eList)); } return nullptr; } @@ -2325,11 +1794,14 @@ namespace AZ::IO if (m_eRecordFileOpenList != IArchive::RFOM_Disabled) { // we only want to record ASSET access - // assets are identified as things which start with no alias, or with the @assets@ alias - auto assetPath = AZ::IO::FileIOBase::GetInstance()->ConvertToAlias(szFilename); - if (assetPath && (assetPath->Native().starts_with("@assets@") - || assetPath->Native().starts_with("@root@") - || assetPath->Native().starts_with("@projectplatformcache@"))) + // assets are identified as files that are relative to the resolved @assets@ alias path + auto fileIoBase = AZ::IO::FileIOBase::GetInstance(); + const char* aliasValue = fileIoBase->GetAlias("@assets@"); + + if (AZ::IO::FixedMaxPath resolvedFilePath; + fileIoBase->ResolvePath(resolvedFilePath, szFilename) + && aliasValue != nullptr + && resolvedFilePath.IsRelativeTo(aliasValue)) { IResourceList* pList = GetResourceList(m_eRecordFileOpenList); @@ -2360,13 +1832,8 @@ namespace AZ::IO bool prev = false; if (threadId == m_mainThreadId) { - prev = m_disableRuntimeFileAccess[0]; - m_disableRuntimeFileAccess[0] = status; - } - else if (threadId == m_renderThreadId) - { - prev = m_disableRuntimeFileAccess[1]; - m_disableRuntimeFileAccess[1] = status; + prev = m_disableRuntimeFileAccess; + m_disableRuntimeFileAccess = status; } return prev; } @@ -2440,16 +1907,6 @@ namespace AZ::IO return AZ::AllocatorInstance::Get().DeAllocate(p); } - void Archive::Lock() - { - m_csMain.lock(); - } - - void Archive::Unlock() - { - m_csMain.unlock(); - } - // gets the current archive priority ArchiveLocationPriority Archive::GetPakPriority() const { @@ -2519,7 +1976,7 @@ namespace AZ::IO { found = true; - info.m_archiveFilename.InitFromRelativePath(archive->GetFilePath()); + info.m_archiveFilename.InitFromRelativePath(archive->GetFilePath().Native()); info.m_offset = pFileData->GetFileDataOffset(); info.m_compressedSize = entry->desc.lSizeCompressed; info.m_uncompressedSize = entry->desc.lSizeUncompressed; @@ -2561,7 +2018,7 @@ namespace AZ::IO ZipDir::CachePtr pZip; uint32_t nArchiveFlags; - ZipDir::FileEntry* pFileEntry = FindPakFileEntry(szFullPath->Native(), nArchiveFlags, &pZip, false); + ZipDir::FileEntry* pFileEntry = FindPakFileEntry(szFullPath->Native(), nArchiveFlags, &pZip); if (!pFileEntry) { return 0; @@ -2589,7 +2046,7 @@ namespace AZ::IO return static_cast(StreamMediaType::TypeHDD); } - bool Archive::SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard, uint32_t nFlags) + bool Archive::SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard) { auto filePath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pWildcard); if (!filePath) @@ -2601,24 +2058,24 @@ namespace AZ::IO return AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(AZ::IO::FixedMaxPath(filePath->ParentPath()).c_str(), AZ::IO::FixedMaxPath(filePath->Filename()).c_str(), [&](const char* filePath) -> bool { - SetPackAccessible(bAccessible, filePath, nFlags); + SetPackAccessible(bAccessible, filePath); return true; }); } - bool Archive::SetPackAccessible(bool bAccessible, AZStd::string_view pName, [[maybe_unused]] uint32_t nFlags) + bool Archive::SetPackAccessible(bool bAccessible, AZStd::string_view pName) { auto szZipPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(pName); if (!szZipPath) { - AZ_Assert(false, "Unable to resolve path for filepath %.*s", aznumeric_cast(pName.size()), pName.data()); + AZ_Assert(false, "Unable to resolve path for filepath %.*s", AZ_STRING_ARG(pName)); return false; } AZStd::unique_lock lock(m_csZips); for (auto it = m_arrZips.begin(); it != m_arrZips.end(); ++it) { - if (!azstricmp(szZipPath->c_str(), it->GetFullPath())) + if (szZipPath == it->GetFullPath()) { return it->pArchive->SetPackAccessible(bAccessible); } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.h b/Code/Framework/AzFramework/AzFramework/Archive/Archive.h index ec964f7fa3..f08d90a66e 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -26,7 +27,6 @@ #include #include #include -#include #include #include @@ -115,12 +115,12 @@ namespace AZ::IO struct PackDesc { AZ::IO::Path m_pathBindRoot; // the zip binding root - AZStd::string strFileName; // the zip file name (with path) - very useful for debugging so please don't remove + AZ::IO::Path m_strFileName; // the zip file name (with path) - very useful for debugging so please don't remove // [LYN-2376] Remove once legacy slice support is removed bool m_containsLevelPak = false; // indicates whether this archive has level.pak inside it or not - const char* GetFullPath() const { return pZip->GetFilePath(); } + AZ::IO::PathView GetFullPath() const { return pZip->GetFilePath(); } AZStd::intrusive_ptr pArchive; ZipDir::CachePtr pZip; @@ -129,10 +129,7 @@ namespace AZ::IO // ArchiveFindDataSet entire purpose is to keep a reference to the intrusive_ptr of ArchiveFindData // so that it doesn't go out of scope - using ArchiveFindDataSet = AZStd::set, AZ::OSStdAllocator>; - - // given the source relative path, constructs the full path to the file according to the flags - const char* AdjustFileName(AZStd::string_view src, char* dst, size_t dstSize, uint32_t nFlags, bool skipMods = false) override; + using ArchiveFindDataSet = AZStd::set>; /** @@ -154,29 +151,17 @@ namespace AZ::IO //! CompressionBus Handler implementation. void FindCompressionInfo(bool& found, AZ::IO::CompressionInfo& info, const AZStd::string_view filename) override; - //! Processes an alias command line containing multiple aliases. - void ParseAliases(AZStd::string_view szCommandLine) override; - //! adds or removes an alias from the list - if bAdd set to false will remove it - void SetAlias(AZStd::string_view szName, AZStd::string_view szAlias, bool bAdd) override; - //! gets an alias from the list, if any exist. - //! if bReturnSame==true, it will return the input name if an alias doesn't exist. Otherwise returns nullptr - const char* GetAlias(AZStd::string_view szName, bool bReturnSame = true) override; - // Set the localization folder void SetLocalizationFolder(AZStd::string_view sLocalizationFolder) override; const char* GetLocalizationFolder() const override { return m_sLocalizationFolder.c_str(); } const char* GetLocalizationRoot() const override { return m_sLocalizationRoot.c_str(); } - // lock all the operations - void Lock() override; - void Unlock() override; - // open the physical archive file - creates if it doesn't exist // returns nullptr if it's invalid or can't open the file - AZStd::intrusive_ptr OpenArchive(AZStd::string_view szPath, AZStd::string_view bindRoot = {}, uint32_t nFlags = 0, AZStd::intrusive_ptr pData = nullptr) override; + AZStd::intrusive_ptr OpenArchive(AZStd::string_view szPath, AZStd::string_view bindRoot = {}, uint32_t nArchiveFlags = 0, AZStd::intrusive_ptr pData = nullptr) override; // returns the path to the archive in which the file was opened - const char* GetFileArchivePath(AZ::IO::HandleType fileHandle) override; + AZ::IO::PathView GetFileArchivePath(AZ::IO::HandleType fileHandle) override; ////////////////////////////////////////////////////////////////////////// @@ -192,40 +177,31 @@ namespace AZ::IO void RegisterFileAccessSink(IArchiveFileAccessSink* pSink) override; void UnregisterFileAccessSink(IArchiveFileAccessSink* pSink) override; - bool Init(AZStd::string_view szBasePath) override; - void Release() override; - - bool IsInstalledToHDD(AZStd::string_view acFilePath = 0) const override; - // [LYN-2376] Remove 'addLevels' parameter once legacy slice support is removed - bool OpenPack(AZStd::string_view pName, uint32_t nFlags = 0, AZStd::intrusive_ptr pData = nullptr, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) override; - bool OpenPack(AZStd::string_view szBindRoot, AZStd::string_view pName, uint32_t nFlags = 0, AZStd::intrusive_ptr pData = nullptr, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) override; + bool OpenPack(AZStd::string_view pName, AZStd::intrusive_ptr pData = nullptr, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) override; + bool OpenPack(AZStd::string_view szBindRoot, AZStd::string_view pName, AZStd::intrusive_ptr pData = nullptr, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) override; // after this call, the file will be unlocked and closed, and its contents won't be used to search for files - bool ClosePack(AZStd::string_view pName, uint32_t nFlags = 0) override; - bool OpenPacks(AZStd::string_view pWildcard, uint32_t nFlags = 0, AZStd::vector* pFullPaths = nullptr) override; - bool OpenPacks(AZStd::string_view szBindRoot, AZStd::string_view pWildcard, uint32_t nFlags = 0, AZStd::vector* pFullPaths = nullptr) override; + bool ClosePack(AZStd::string_view pName) override; + bool OpenPacks(AZStd::string_view pWildcard, AZStd::vector* pFullPaths = nullptr) override; + bool OpenPacks(AZStd::string_view szBindRoot, AZStd::string_view pWildcard, AZStd::vector* pFullPaths = nullptr) override; // closes pack files by the path and wildcard - bool ClosePacks(AZStd::string_view pWildcard, uint32_t nFlags = 0) override; + bool ClosePacks(AZStd::string_view pWildcard) override; //returns if a archive exists matching the wildcard bool FindPacks(AZStd::string_view pWildcardIn) override; // prevent access to specific archive files - bool SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard, uint32_t nFlags = 0) override; - bool SetPackAccessible(bool bAccessible, AZStd::string_view pName, uint32_t nFlags = 0) override; + bool SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard) override; + bool SetPackAccessible(bool bAccessible, AZStd::string_view pName) override; // returns the file modification time uint64_t GetModificationTime(AZ::IO::HandleType fileHandle) override; - bool LoadPakToMemory(AZStd::string_view pName, EInMemoryArchiveLocation nLoadArchiveToMemory, AZStd::intrusive_ptr pMemoryBlock = nullptr) override; - void LoadPaksToMemory(int nMaxArchiveSize, bool bLoadToMemory) override; - - AZ::IO::HandleType FOpen(AZStd::string_view pName, const char* mode, uint32_t nPathFlags = 0) override; - size_t FReadRaw(void* data, size_t length, size_t elems, AZ::IO::HandleType handle) override; - size_t FReadRawAll(void* data, size_t nFileSize, AZ::IO::HandleType handle) override; + AZ::IO::HandleType FOpen(AZStd::string_view pName, const char* mode) override; + size_t FRead(void* data, size_t bytesToRead, AZ::IO::HandleType handle) override; void* FGetCachedFileData(AZ::IO::HandleType handle, size_t& nFileSize) override; - size_t FWrite(const void* data, size_t length, size_t elems, AZ::IO::HandleType handle) override; + size_t FWrite(const void* data, size_t bytesToWrite, AZ::IO::HandleType handle) override; size_t FSeek(AZ::IO::HandleType handle, uint64_t seek, int mode) override; uint64_t FTell(AZ::IO::HandleType handle) override; int FFlush(AZ::IO::HandleType handle) override; @@ -234,9 +210,7 @@ namespace AZ::IO AZ::IO::ArchiveFileIterator FindNext(AZ::IO::ArchiveFileIterator fileIterator) override; bool FindClose(AZ::IO::ArchiveFileIterator fileIterator) override; int FEof(AZ::IO::HandleType handle) override; - char* FGets(char*, int, AZ::IO::HandleType) override; - int Getc(AZ::IO::HandleType) override; - int FPrintf(AZ::IO::HandleType handle, const char* format, ...) override; + size_t FGetSize(AZ::IO::HandleType fileHandle) override; size_t FGetSize(AZStd::string_view sFilename, bool bAllowUseFileSystem = false) override; bool IsInPak(AZ::IO::HandleType handle) override; @@ -248,9 +222,6 @@ namespace AZ::IO bool IsFolder(AZStd::string_view sPath) override; IArchive::SignedFileSize GetFileSizeOnDisk(AZStd::string_view filename) override; - // creates a directory - bool MakeDir(AZStd::string_view szPath) override; - // 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) // MT-safe @@ -275,22 +246,12 @@ namespace AZ::IO IResourceList* GetResourceList(ERecordFileOpenList eList) override; void SetResourceList(ERecordFileOpenList eList, IResourceList* pResourceList) override; - uint32_t ComputeCRC(AZStd::string_view szPath, uint32_t nFileOpenFlags = 0) override; - bool ComputeMD5(AZStd::string_view szPath, uint8_t* md5, uint32_t nFileOpenFlags = 0, bool useDirectFileAccess = false) override; - void DisableRuntimeFileAccess(bool status) override { - m_disableRuntimeFileAccess[0] = status; - m_disableRuntimeFileAccess[1] = status; + m_disableRuntimeFileAccess = status; } bool DisableRuntimeFileAccess(bool status, AZStd::thread_id threadId) override; - bool CheckFileAccessDisabled(AZStd::string_view name, const char* mode) override; - - void SetRenderThreadId(AZStd::thread_id renderThreadId) override - { - m_renderThreadId = renderThreadId; - } // gets the current archive priority ArchiveLocationPriority GetPakPriority() const override; @@ -307,11 +268,11 @@ namespace AZ::IO // Return cached file data for entries inside archive file. CCachedFileDataPtr GetOpenedFileDataInZip(AZ::IO::HandleType file); ZipDir::FileEntry* FindPakFileEntry(AZStd::string_view szPath, uint32_t& nArchiveFlags, - ZipDir::CachePtr* pZip = {}, bool bSkipInMemoryArchives = {}) const; + ZipDir::CachePtr* pZip = {}) const; private: - bool OpenPackCommon(AZStd::string_view szBindRoot, AZStd::string_view pName, uint32_t nArchiveFlags, AZStd::intrusive_ptr pData = nullptr, bool addLevels = true); - bool OpenPacksCommon(AZStd::string_view szDir, AZStd::string_view pWildcardIn, uint32_t nArchiveFlags, AZStd::vector* pFullPaths = nullptr, bool addLevels = true); + bool OpenPackCommon(AZStd::string_view szBindRoot, AZStd::string_view pName, AZStd::intrusive_ptr pData = nullptr, bool addLevels = true); + bool OpenPacksCommon(AZStd::string_view szDir, AZStd::string_view pWildcardIn, AZStd::vector* pFullPaths = nullptr, bool addLevels = true); ZipDir::FileEntry* FindPakFileEntry(AZStd::string_view szPath) const; @@ -346,9 +307,6 @@ namespace AZ::IO AZStd::mutex m_cachedFileRawDataMutex; // For m_pCachedFileRawDataSet using RawDataCacheLockGuard = AZStd::scoped_lock; - // The F* emulation functions critical section: protects all F* functions - // that don't have a chance to be called recursively (to avoid deadlocks) - AZStd::mutex m_csMain; mutable AZStd::shared_mutex m_archiveMutex; ArchiveArray m_arrArchives; @@ -360,8 +318,6 @@ namespace AZ::IO ////////////////////////////////////////////////////////////////////////// IArchive::ERecordFileOpenList m_eRecordFileOpenList = RFOM_Disabled; - using RecordedFilesSet = AZStd::set; - RecordedFilesSet m_recordedFilesSet; AZStd::intrusive_ptr m_pEngineStartupResourceList; @@ -372,28 +328,16 @@ namespace AZ::IO float m_fFileAccessTime{}; // Time used to perform file operations AZStd::vector m_FileAccessSinks; // useful for gathering file access statistics - bool m_disableRuntimeFileAccess[2]{}; + bool m_disableRuntimeFileAccess{}; //threads which we don't want to access files from during the game AZStd::thread_id m_mainThreadId{}; - AZStd::thread_id m_renderThreadId{}; AZStd::fixed_string<128> m_sLocalizationFolder; AZStd::fixed_string<128> m_sLocalizationRoot; - AZStd::set, AZ::OSStdAllocator> m_filesCachedOnHDD; - // [LYN-2376] Remove once legacy slice support is removed LevelPackOpenEvent m_levelOpenEvent; LevelPackCloseEvent m_levelCloseEvent; }; } - -namespace AZ::IO::ArchiveInternal -{ - // Utility function to de-alias archive file opening and file-within-archive opening - // if the file specified was an absolute path but it points at one of the aliases, de-alias it and replace it with that alias. - // this works around problems where the level editor is in control but still mounts asset packs (ie, level.pak mounted as @assets@) - AZStd::optional ConvertAbsolutePathToAliasedPath(AZStd::string_view sourcePath, - AZStd::string_view aliasToLookFor = "@devassets@", AZStd::string_view aliasToReplaceWith = "@assets@"); -} diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.cpp index 55f7640785..85ce0b6f9a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.cpp @@ -5,10 +5,9 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#include +#include #include #include // for function<> in the find files callback. -#include #include #include @@ -188,7 +187,7 @@ namespace AZ::IO return IO::ResultCode::Error; } - size_t result = m_archive->FReadRaw(buffer, 1, size, fileHandle); + size_t result = m_archive->FRead(buffer, size, fileHandle); if (bytesRead) { *bytesRead = static_cast(result); @@ -213,7 +212,7 @@ namespace AZ::IO return IO::ResultCode::Error; } - size_t result = m_archive->FWrite(buffer, 1, size, fileHandle); + size_t result = m_archive->FWrite(buffer, size, fileHandle); if (bytesWritten) { *bytesWritten = static_cast(result); @@ -357,14 +356,8 @@ namespace AZ::IO return IO::ResultCode::Error; } - // avoid using AZStd::string if possible - use OSString instead of StringFunc - AZ::OSString destPath(destinationFilePath); + IO::Path destPath(IO::PathView(destinationFilePath).ParentPath()); - AZ::OSString::size_type pos = destPath.find_last_of(AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); - if (pos != AZ::OSString::npos) - { - destPath.resize(pos); - } CreatePath(destPath.c_str()); if (!Open(destinationFilePath, IO::OpenMode::ModeWrite | IO::OpenMode::ModeBinary, destinationFile)) @@ -466,31 +459,25 @@ namespace AZ::IO return IO::ResultCode::Error; } - AZStd::fixed_string total = filePath; + AZ::IO::FixedMaxPath total = filePath; if (total.empty()) { return IO::ResultCode::Error; } - if (!total.ends_with(AZ_CORRECT_FILESYSTEM_SEPARATOR) && !total.ends_with(AZ_WRONG_FILESYSTEM_SEPARATOR)) - { - total.append(AZ_CORRECT_FILESYSTEM_SEPARATOR_STRING); - } - - total.append(filter); + total /= filter; AZ::IO::ArchiveFileIterator fileIterator = m_archive->FindFirst(total.c_str()); if (!fileIterator) { return IO::ResultCode::Success; // its not an actual fatal error to not find anything. } - for (;fileIterator; fileIterator = m_archive->FindNext(fileIterator)) + for (; fileIterator; fileIterator = m_archive->FindNext(fileIterator)) { - total = AZStd::fixed_string::format("%s/%.*s", filePath, aznumeric_cast(fileIterator.m_filename.size()), fileIterator.m_filename.data()); - AZStd::optional resolvedAliasLength = ConvertToAlias(total.data(), total.capacity()); - if (resolvedAliasLength) + total = filePath; + total /= fileIterator.m_filename; + if (ConvertToAlias(total, total)) { - total.resize_no_construct(*resolvedAliasLength); if (!callback(total.c_str())) { break; @@ -510,8 +497,13 @@ namespace AZ::IO const auto fileIt = m_trackedFiles.find(fileHandle); if (fileIt != m_trackedFiles.end()) { - AZ_Assert(filenameSize >= fileIt->second.length(), "Filename size %" PRIu64 " is larger than the size of the tracked file %s:%zu", fileIt->second.c_str(), fileIt->second.size()); - azstrncpy(filename, filenameSize, fileIt->second.c_str(), fileIt->second.length()); + const AZStd::string_view trackedFileView = fileIt->second.Native(); + if (filenameSize <= trackedFileView.size()) + { + return false; + } + size_t trackedFileViewLength = trackedFileView.copy(filename, trackedFileView.size()); + filename[trackedFileViewLength] = '\0'; return true; } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.h b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.h index 2cd8f37adc..21cef18a7a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFileIO.h @@ -13,7 +13,6 @@ #include #include #include -#include namespace AZ::IO @@ -65,7 +64,7 @@ namespace AZ::IO void SetAlias(const char* alias, const char* path) override; void ClearAlias(const char* alias) override; AZStd::optional ConvertToAlias(char* inOutBuffer, AZ::u64 bufferLength) const override; - bool ConvertToAlias(AZ::IO::FixedMaxPath& convertedPath, const AZ::IO::PathView& path) const; + bool ConvertToAlias(AZ::IO::FixedMaxPath& convertedPath, const AZ::IO::PathView& path) const override; using FileIOBase::ConvertToAlias; const char* GetAlias(const char* alias) const override; bool ResolvePath(const char* path, char* resolvedPath, AZ::u64 resolvedPathSize) const override; @@ -78,7 +77,7 @@ namespace AZ::IO protected: // we keep a list of file names ever opened so that we can easily return it. mutable AZStd::recursive_mutex m_operationGuard; - AZStd::unordered_map, AZStd::equal_to, AZ::OSStdAllocator> m_trackedFiles; + AZStd::unordered_map m_trackedFiles; AZStd::fixed_vector m_copyBuffer; IArchive* m_archive; }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp index c4c845a832..d7a92efbf6 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.cpp @@ -15,34 +15,6 @@ namespace AZ::IO { - size_t ArchiveFileIteratorHash::operator()(const AZ::IO::ArchiveFileIterator& iter) const - { - return iter.GetHash(); - } - - bool AZStdStringLessCaseInsensitive::operator()(AZStd::string_view left, AZStd::string_view right) const - { - // If one or both strings are 0-length, return true if the left side is smaller, false if they're equal or left is larger. - size_t compareLength = (AZStd::min)(left.size(), right.size()); - if (compareLength == 0) - { - return left.size() < right.size(); - } - - // They're both non-zero, so compare the strings up until the length of the shorter string. - int compareResult = azstrnicmp(left.data(), right.data(), compareLength); - - // If both strings are equal for the number of characters compared, return true if the left side is shorter, false if - // they're equal or left is longer. - if (compareResult == 0) - { - return left.size() < right.size(); - } - - // Return true if the left side should come first alphabetically, false if the right side should. - return compareResult < 0; - } - FileDesc::FileDesc(Attribute fileAttribute, uint64_t fileSize, time_t accessTime, time_t creationTime, time_t writeTime) : nAttrib{ fileAttribute } , nSize{ fileSize } @@ -52,10 +24,9 @@ namespace AZ::IO { } - ArchiveFileIterator::ArchiveFileIterator(FindData* findData, AZStd::string_view filename, const FileDesc& fileDesc) + // ArchiveFileIterator + ArchiveFileIterator::ArchiveFileIterator(FindData* findData) : m_findData{ findData } - , m_filename{ filename } - , m_fileDesc{ fileDesc } { } @@ -73,21 +44,36 @@ namespace AZ::IO return operator++(); } - bool ArchiveFileIterator::operator==(const AZ::IO::ArchiveFileIterator& rhs) const - { - return GetHash() == rhs.GetHash(); - } ArchiveFileIterator::operator bool() const { return m_findData && m_lastFetchValid; } - size_t ArchiveFileIterator::GetHash() const + // FindData::ArchiveFile + FindData::ArchiveFile::ArchiveFile() = default; + FindData::ArchiveFile::ArchiveFile(AZStd::string_view filename, const FileDesc& fileDesc) + : m_filename(filename) + , m_fileDesc(fileDesc) + { + } + size_t FindData::ArchiveFile::GetHash() const { return AZStd::hash{}(m_filename.c_str()); } + bool FindData::ArchiveFile::operator==(const ArchiveFile& rhs) const + { + return GetHash() == rhs.GetHash(); + } + + // FindData::ArchiveFilehash + size_t FindData::ArchiveFileHash::operator()(const ArchiveFile& archiveFile) const + { + return archiveFile.GetHash(); + } + + // FindData void FindData::Scan(IArchive* archive, AZStd::string_view szDir, bool bAllowUseFS, bool bScanZips) { // get the priority into local variable to avoid it changing in the course of @@ -119,40 +105,37 @@ namespace AZ::IO void FindData::ScanFS([[maybe_unused]] IArchive* archive, AZStd::string_view szDirIn) { - AZStd::string searchDirectory; - AZStd::string pattern; + AZ::IO::PathView directory{ szDirIn }; + AZ::IO::FixedMaxPath searchDirectory = directory.ParentPath(); + AZ::IO::FixedMaxPath pattern = directory.Filename(); + auto ScanFileSystem = [this](const char* filePath) -> bool { - AZ::IO::PathString directory{ szDirIn }; - AZ::StringFunc::Path::GetFullPath(directory.c_str(), searchDirectory); - AZ::StringFunc::Path::GetFullFileName(directory.c_str(), pattern); - } - AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(searchDirectory.c_str(), pattern.c_str(), [&](const char* filePath) -> bool - { - AZ::IO::ArchiveFileIterator fileIterator{ nullptr, AZ::IO::PathView(filePath).Filename().Native(), {} }; + ArchiveFile archiveFile{ AZ::IO::PathView(filePath).Filename().Native(), {} }; if (AZ::IO::FileIOBase::GetDirectInstance()->IsDirectory(filePath)) { - fileIterator.m_fileDesc.nAttrib = fileIterator.m_fileDesc.nAttrib | AZ::IO::FileDesc::Attribute::Subdirectory; - m_fileSet.emplace(AZStd::move(fileIterator)); + archiveFile.m_fileDesc.nAttrib = archiveFile.m_fileDesc.nAttrib | AZ::IO::FileDesc::Attribute::Subdirectory; + m_fileSet.emplace(AZStd::move(archiveFile)); } else { if (AZ::IO::FileIOBase::GetDirectInstance()->IsReadOnly(filePath)) { - fileIterator.m_fileDesc.nAttrib = fileIterator.m_fileDesc.nAttrib | AZ::IO::FileDesc::Attribute::ReadOnly; + archiveFile.m_fileDesc.nAttrib = archiveFile.m_fileDesc.nAttrib | AZ::IO::FileDesc::Attribute::ReadOnly; } AZ::u64 fileSize = 0; AZ::IO::FileIOBase::GetDirectInstance()->Size(filePath, fileSize); - fileIterator.m_fileDesc.nSize = fileSize; - fileIterator.m_fileDesc.tWrite = AZ::IO::FileIOBase::GetDirectInstance()->ModificationTime(filePath); + archiveFile.m_fileDesc.nSize = fileSize; + archiveFile.m_fileDesc.tWrite = AZ::IO::FileIOBase::GetDirectInstance()->ModificationTime(filePath); // These times are not supported by our file interface - fileIterator.m_fileDesc.tAccess = fileIterator.m_fileDesc.tWrite; - fileIterator.m_fileDesc.tCreate = fileIterator.m_fileDesc.tWrite; - m_fileSet.emplace(AZStd::move(fileIterator)); + archiveFile.m_fileDesc.tAccess = archiveFile.m_fileDesc.tWrite; + archiveFile.m_fileDesc.tCreate = archiveFile.m_fileDesc.tWrite; + m_fileSet.emplace(AZStd::move(archiveFile)); } return true; - }); + }; + AZ::IO::FileIOBase::GetDirectInstance()->FindFiles(searchDirectory.c_str(), pattern.c_str(), ScanFileSystem); } ////////////////////////////////////////////////////////////////////////// @@ -180,7 +163,7 @@ namespace AZ::IO fileDesc.nAttrib = AZ::IO::FileDesc::Attribute::ReadOnly | AZ::IO::FileDesc::Attribute::Archive; fileDesc.nSize = fileEntry->desc.lSizeUncompressed; fileDesc.tWrite = fileEntry->GetModificationTime(); - m_fileSet.emplace(AZ::IO::ArchiveFileIterator{ this, fname, fileDesc }); + m_fileSet.emplace(fname, fileDesc); } ZipDir::FindDir findDirectoryEntry(zipCache); @@ -193,7 +176,7 @@ namespace AZ::IO } AZ::IO::FileDesc fileDesc; fileDesc.nAttrib = AZ::IO::FileDesc::Attribute::ReadOnly | AZ::IO::FileDesc::Attribute::Archive | AZ::IO::FileDesc::Attribute::Subdirectory; - m_fileSet.emplace(AZ::IO::ArchiveFileIterator{ this, fname, fileDesc }); + m_fileSet.emplace(fname, fileDesc); } }; @@ -208,30 +191,16 @@ namespace AZ::IO // so there's really no way to filter out opening the pack and looking at the files inside. // however, the bind root is not part of the inner zip entry name either // and the ZipDir::FindFile actually expects just the chopped off piece. - // we have to find whats in common between them and check that: + // we have to find the common path segments between them and check that: - auto resolvedBindRoot = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(it->m_pathBindRoot); - if (!resolvedBindRoot) + AZ::IO::FixedMaxPath bindRoot; + if (!AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(bindRoot, it->m_pathBindRoot)) { AZ_Assert(false, "Unable to resolve Path for archive %s bind root %s", it->GetFullPath(), it->m_pathBindRoot.c_str()); return; } - AZ::IO::FixedMaxPath bindRoot{ *resolvedBindRoot }; - auto [bindRootIter, sourcePathIter] = AZStd::mismatch(AZStd::begin(bindRoot), AZStd::end(bindRoot), - AZStd::begin(sourcePath), AZStd::end(sourcePath)); - if (sourcePathIter == AZStd::begin(sourcePath)) - { - // The path has no characters in common , early out the search as filepath is not part of the iterated zip - continue; - } - - AZ::IO::FixedMaxPath sourcePathRemainder; - for (; sourcePathIter != AZStd::end(sourcePath); ++sourcePathIter) - { - sourcePathRemainder /= *sourcePathIter; - } // Example: // "@assets@\\levels\\*" <--- szDir // "@assets@\\" <--- mount point @@ -256,18 +225,26 @@ namespace AZ::IO // then it means that the pack's mount point itself might be a return value, not the files inside the pack // in that case, we compare the mount point remainder itself with the search filter + auto [bindRootIter, sourcePathIter] = AZStd::mismatch(bindRoot.begin(), bindRoot.end(), + sourcePath.begin(), sourcePath.end()); if (bindRootIter != bindRoot.end()) { + AZ::IO::FixedMaxPath sourcePathRemainder; + for (; sourcePathIter != sourcePath.end(); ++sourcePathIter) + { + sourcePathRemainder /= *sourcePathIter; + } + // Retrieve next path component of the mount point remainder - if (!bindRootIter->empty() && AZStd::wildcard_match(sourcePathRemainder.Native(), bindRootIter->Native())) + if (!bindRootIter->empty() && bindRootIter->Match(sourcePathRemainder.Native())) { AZ::IO::FileDesc fileDesc{ AZ::IO::FileDesc::Attribute::ReadOnly | AZ::IO::FileDesc::Attribute::Archive | AZ::IO::FileDesc::Attribute::Subdirectory }; - m_fileSet.emplace(AZ::IO::ArchiveFileIterator{ this, bindRootIter->Native(), fileDesc }); + m_fileSet.emplace(AZStd::move(bindRootIter->Native()), fileDesc); } } else { - + AZ::IO::FixedMaxPath sourcePathRemainder = sourcePath.LexicallyRelative(bindRoot); // if we get here, it means that the search pattern's root and the mount point for this pack are identical // which means we may search inside the pack. ScanInZip(it->pZip.get(), sourcePathRemainder.Native()); @@ -280,17 +257,17 @@ namespace AZ::IO { if (m_fileSet.empty()) { - AZ::IO::ArchiveFileIterator emptyFileIterator; - emptyFileIterator.m_lastFetchValid = false; - emptyFileIterator.m_findData = this; - return emptyFileIterator; + return {}; } // Remove Fetched item from the FindData map so that the iteration continues - AZ::IO::ArchiveFileIterator fileIterator{ *m_fileSet.begin() }; + AZ::IO::ArchiveFileIterator fileIterator; + auto archiveFileIt = m_fileSet.begin(); + fileIterator.m_filename = archiveFileIt->m_filename; + fileIterator.m_fileDesc = archiveFileIt->m_fileDesc; fileIterator.m_lastFetchValid = true; fileIterator.m_findData = this; - m_fileSet.erase(m_fileSet.begin()); + m_fileSet.erase(archiveFileIt); return fileIterator; } } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.h b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.h index 12544d124d..ebdbf45626 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ArchiveFindData.h @@ -36,56 +36,72 @@ namespace AZ::IO AZ_DEFINE_ENUM_BITWISE_OPERATORS(AZ::IO::FileDesc::Attribute); + inline constexpr size_t ArchiveFilenameMaxLength = 256; + using ArchiveFileString = AZStd::fixed_string; + class FindData; + //! This is not really an iterator, but a handle + //! that extends ownership of any found filenames from an archive file or the file system struct ArchiveFileIterator { ArchiveFileIterator() = default; - ArchiveFileIterator(FindData* findData, AZStd::string_view filename, const FileDesc& fileDesc); + explicit ArchiveFileIterator(FindData* findData); ArchiveFileIterator operator++(); ArchiveFileIterator operator++(int); - bool operator==(const AZ::IO::ArchiveFileIterator& rhs) const; - explicit operator bool() const; - size_t GetHash() const; - - inline static constexpr size_t FilenameMaxLength = 256; - AZStd::fixed_string m_filename; + ArchiveFileString m_filename; FileDesc m_fileDesc; - AZStd::intrusive_ptr m_findData{}; private: friend class FindData; + friend class Archive; + AZStd::intrusive_ptr m_findData; bool m_lastFetchValid{}; }; - struct ArchiveFileIteratorHash - { - size_t operator()(const AZ::IO::ArchiveFileIterator& iter) const; - }; - struct AZStdStringLessCaseInsensitive - { - bool operator()(AZStd::string_view left, AZStd::string_view right) const; - - using is_transparent = void; - }; class FindData : public AZStd::intrusive_base { public: AZ_CLASS_ALLOCATOR(FindData, AZ::SystemAllocator, 0); FindData() = default; - AZ::IO::ArchiveFileIterator Fetch(); + ArchiveFileIterator Fetch(); void Scan(IArchive* archive, AZStd::string_view path, bool bAllowUseFS = false, bool bScanZips = true); protected: void ScanFS(IArchive* archive, AZStd::string_view path); + // Populates the FileSet with files within the that match the path pattern that is + // if it refers to a file within a bound archive root or returns the archive root + // path if the path pattern matches it. void ScanZips(IArchive* archive, AZStd::string_view path); - using FileSet = AZStd::unordered_set; + class ArchiveFile + { + public: + friend class FindData; + + ArchiveFile(); + ArchiveFile(AZStd::string_view filename, const FileDesc& fileDesc); + + size_t GetHash() const; + bool operator==(const ArchiveFile& rhs) const; + + private: + ArchiveFileString m_filename; + FileDesc m_fileDesc; + }; + + struct ArchiveFileHash + { + size_t operator()(const ArchiveFile& archiveFile) const; + }; + + using FileSet = AZStd::unordered_set; FileSet m_fileSet; }; + } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h index 5ac417564a..bd9615110a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/IArchive.h @@ -12,12 +12,10 @@ #include #include #include -#include #include #include #include #include -#include #include @@ -106,66 +104,6 @@ namespace AZ::IO { AZ_RTTI(IArchive, "{764A2260-FF8A-4C86-B958-EBB0B69D9DFA}"); using FileTime = uint64_t; - // Flags used in file path resolution rules - enum EPathResolutionRules - { - // If used, the source path will be treated as the destination path - // and no transformations will be done. Pass this flag when the path is to be the actual - // path on the disk/in the packs and doesn't need adjustment (or after it has come through adjustments already) - // if this is set, AdjustFileName will not map the input path into the folder (Ex: Shaders will not be converted to Game\Shaders) - FLAGS_PATH_REAL = 1 << 16, - - // AdjustFileName will always copy the file path to the destination path: - // regardless of the returned value, szDestpath can be used - FLAGS_COPY_DEST_ALWAYS = 1 << 17, - - // Adds trailing slash to the path - FLAGS_ADD_TRAILING_SLASH = 1L << 18, - - // if this is set, AdjustFileName will not make relative paths into full paths - FLAGS_NO_FULL_PATH = 1 << 21, - - // if this is set, AdjustFileName will redirect path to disc - FLAGS_REDIRECT_TO_DISC = 1 << 22, - - // if this is set, AdjustFileName will not adjust path for writing files - FLAGS_FOR_WRITING = 1 << 23, - - // if this is set, the archive would be stored in memory (gpu) - FLAGS_PAK_IN_MEMORY = 1 << 25, - - // Store all file names as crc32 in a flat directory structure. - FLAGS_FILENAMES_AS_CRC32 = 1 << 26, - - // if this is set, AdjustFileName will try to find the file under any mod paths we know about - FLAGS_CHECK_MOD_PATHS = 1 << 27, - - // if this is set, AdjustFileName will always check the filesystem/disk and not check inside open archives - FLAGS_NEVER_IN_PAK = 1 << 28, - - // returns existing file name from the local data or existing cache file name - // used by the resource compiler to pass the real file name - FLAGS_RESOLVE_TO_CACHE = 1 << 29, - - // if this is set, the archive would be stored in memory (cpu) - FLAGS_PAK_IN_MEMORY_CPU = 1 << 30, - - // if this is set, the level pak is inside another archive - FLAGS_LEVEL_PAK_INSIDE_PAK = 1 << 31, - }; - - // Used for widening FOpen functionality. They're ignored for the regular File System files. - enum EFOpenFlags - { - // If possible, will prevent the file from being read from memory. - FOPEN_HINT_DIRECT_OPERATION = 1, - // Will prevent a "missing file" warnings to be created. - FOPEN_HINT_QUIET = 1 << 1, - // File should be on disk - FOPEN_ONDISK = 1 << 2, - // Open is done by the streaming thread. - FOPEN_FORSTREAMING = 1 << 3, - }; // enum ERecordFileOpenList @@ -175,8 +113,6 @@ namespace AZ::IO RFOM_Level, // during level loading till export2game -> resourcelist.txt, used to generate the list for level2level loading RFOM_NextLevel // used for level2level loading }; - // the size of the buffer that receives the full path to the file - inline static constexpr size_t MaxPath = 1024; //file location enum used in isFileExist to control where the archive system looks for the file. enum EFileSearchLocation @@ -205,63 +141,31 @@ namespace AZ::IO virtual ~IArchive() = default; - /** - * Deprecated: Use the AZ::IO::FileIOBase::ResolvePath function below that doesn't accept the nFlags or skipMods parameters - * given the source relative path, constructs the full path to the file according to the flags - * returns the pointer to the constructed path (can be either szSourcePath, or szDestPath, or NULL in case of error - */ - // - virtual const char* AdjustFileName(AZStd::string_view src, char* dst, size_t dstSize, uint32_t nFlags, bool skipMods = false) = 0; - - virtual bool Init(AZStd::string_view szBasePath) = 0; - virtual void Release() = 0; - - // Summary: - // Returns true if given archivepath is installed to HDD - // If no file path is given it will return true if whole application is installed to HDD - virtual bool IsInstalledToHDD(AZStd::string_view acFilePath = 0) const = 0; - // after this call, the archive file will be searched for files when they aren't on the OS file system // Arguments: // pName - must not be 0 - virtual bool OpenPack(AZStd::string_view pName, uint32_t nFlags = FLAGS_PATH_REAL, AZStd::intrusive_ptr pData = {}, + virtual bool OpenPack(AZStd::string_view pName, AZStd::intrusive_ptr pData = {}, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) = 0; // after this call, the archive file will be searched for files when they aren't on the OS file system - virtual bool OpenPack(AZStd::string_view pBindingRoot, AZStd::string_view pName, uint32_t nFlags = FLAGS_PATH_REAL, + virtual bool OpenPack(AZStd::string_view pBindingRoot, AZStd::string_view pName, AZStd::intrusive_ptr pData = {}, AZ::IO::FixedMaxPathString* pFullPath = nullptr, bool addLevels = true) = 0; // after this call, the file will be unlocked and closed, and its contents won't be used to search for files - virtual bool ClosePack(AZStd::string_view pName, uint32_t nFlags = FLAGS_PATH_REAL) = 0; + virtual bool ClosePack(AZStd::string_view pName) = 0; // opens pack files by the path and wildcard - virtual bool OpenPacks(AZStd::string_view pWildcard, uint32_t nFlags = FLAGS_PATH_REAL, AZStd::vector* pFullPaths = nullptr) = 0; + virtual bool OpenPacks(AZStd::string_view pWildcard, AZStd::vector* pFullPaths = nullptr) = 0; // opens pack files by the path and wildcard - virtual bool OpenPacks(AZStd::string_view pBindingRoot, AZStd::string_view pWildcard, uint32_t nFlags = FLAGS_PATH_REAL, + virtual bool OpenPacks(AZStd::string_view pBindingRoot, AZStd::string_view pWildcard, AZStd::vector* pFullPaths = nullptr) = 0; // closes pack files by the path and wildcard - virtual bool ClosePacks(AZStd::string_view pWildcard, uint32_t nFlags = FLAGS_PATH_REAL) = 0; + virtual bool ClosePacks(AZStd::string_view pWildcard) = 0; //returns if a archive exists matching the wildcard virtual bool FindPacks(AZStd::string_view pWildcardIn) = 0; // Set access status of a archive files with a wildcard - virtual bool SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard, uint32_t nFlags = FLAGS_PATH_REAL) = 0; + virtual bool SetPacksAccessible(bool bAccessible, AZStd::string_view pWildcard) = 0; // Set access status of a pack file - virtual bool SetPackAccessible(bool bAccessible, AZStd::string_view pName, uint32_t nFlags = FLAGS_PATH_REAL) = 0; - - // Load or unload archive file completely to memory. - virtual bool LoadPakToMemory(AZStd::string_view pName, EInMemoryArchiveLocation eLoadToMemory, AZStd::intrusive_ptr pMemoryBlock = nullptr) = 0; - virtual void LoadPaksToMemory(int nMaxArchiveSize, bool bLoadToMemory) = 0; - - // Processes an alias command line containing multiple aliases. - virtual void ParseAliases(AZStd::string_view szCommandLine) = 0; - // adds or removes an alias from the list - virtual void SetAlias(AZStd::string_view szName, AZStd::string_view szAlias, bool bAdd) = 0; - // gets an alias from the list, if any exist. - // if bReturnSame==true, it will return the input name if an alias doesn't exist. Otherwise returns NULL - virtual const char* GetAlias(AZStd::string_view szName, bool bReturnSame = true) = 0; - - // lock all the operations - virtual void Lock() = 0; - virtual void Unlock() = 0; + virtual bool SetPackAccessible(bool bAccessible, AZStd::string_view pName) = 0; // Set and Get the localization folder name (Languages, Localization, ...) virtual void SetLocalizationFolder(AZStd::string_view sLocalizationFolder) = 0; @@ -273,28 +177,19 @@ namespace AZ::IO // ex: AZ::IO::HandleType fileHandle = FOpen( "test.txt","rbx" ); // mode x is a direct access mode, when used file reads will go directly into the low level file system without any internal data caching. // Text mode is not supported for files in Archives. - // for nFlags @see IArchive::EFOpenFlags - virtual AZ::IO::HandleType FOpen(AZStd::string_view pName, const char* mode, uint32_t nFlags = 0) = 0; - - // Read raw data from file, no endian conversion. - virtual size_t FReadRaw(void* data, size_t length, size_t elems, AZ::IO::HandleType fileHandle) = 0; - - // Read all file contents into the provided memory, nSizeOfFile must be the same as returned by GetFileSize(handle) - // Current seek pointer is ignored and reseted to 0. - // no endian conversion. - virtual size_t FReadRawAll(void* data, size_t nFileSize, AZ::IO::HandleType fileHandle) = 0; + virtual AZ::IO::HandleType FOpen(AZStd::string_view pName, const char* mode) = 0; // Get pointer to the internally cached, loaded data of the file. // WARNING! The returned pointer is only valid while the fileHandle has not been closed. virtual void* FGetCachedFileData(AZ::IO::HandleType fileHandle, size_t& nFileSize) = 0; - // Write file data, cannot be used for writing into the Archive. - // Use INestedArchive interface for writing into the archivefiles. - virtual size_t FWrite(const void* data, size_t length, size_t elems, AZ::IO::HandleType fileHandle) = 0; + // Read raw data from file, no endian conversion. + virtual size_t FRead(void* data, size_t bytesToRead, AZ::IO::HandleType fileHandle) = 0; + + // Write file data, cannot be used for writing into the Archive. + // Use INestedArchive interface for writing into the archive files. + virtual size_t FWrite(const void* data, size_t bytesToWrite, AZ::IO::HandleType fileHandle) = 0; - virtual int FPrintf(AZ::IO::HandleType fileHandle, const char* format, ...) = 0; - virtual char* FGets(char*, int, AZ::IO::HandleType) = 0; - virtual int Getc(AZ::IO::HandleType) = 0; virtual size_t FGetSize(AZ::IO::HandleType fileHandle) = 0; virtual size_t FGetSize(AZStd::string_view pName, bool bAllowUseFileSystem = false) = 0; virtual bool IsInPak(AZ::IO::HandleType fileHandle) = 0; @@ -318,7 +213,6 @@ namespace AZ::IO virtual AZStd::intrusive_ptr PoolAllocMemoryBlock(size_t nSize, const char* sUsage, size_t nAlign = 1) = 0; // Arguments: - // nFlags is a combination of EPathResolutionRules flags. virtual ArchiveFileIterator FindFirst(AZStd::string_view pDir, EFileSearchType searchType = eFileSearchType_AllowInZipsOnly) = 0; virtual ArchiveFileIterator FindNext(AZ::IO::ArchiveFileIterator handle) = 0; virtual bool FindClose(AZ::IO::ArchiveFileIterator handle) = 0; @@ -334,9 +228,6 @@ namespace AZ::IO virtual IArchive::SignedFileSize GetFileSizeOnDisk(AZStd::string_view filename) = 0; - // creates a directory - virtual bool MakeDir(AZStd::string_view szPath) = 0; - // open the physical archive file - creates if it doesn't exist // returns NULL if it's invalid or can't open the file // nFlags is a combination of flags from EArchiveFlags enum. @@ -344,8 +235,8 @@ namespace AZ::IO AZStd::intrusive_ptr pData = nullptr) = 0; // returns the path to the archive in which the file was opened - // returns NULL if the file is a physical file, and "" if the path to archive is unknown (shouldn't ever happen) - virtual const char* GetFileArchivePath(AZ::IO::HandleType fileHandle) = 0; + // returns empty path view if the file is a physical file + virtual AZ::IO::PathView GetFileArchivePath(AZ::IO::HandleType fileHandle) = 0; // 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) @@ -378,25 +269,7 @@ namespace AZ::IO // get the current mode, can be set by RecordFileOpen() virtual IArchive::ERecordFileOpenList GetRecordFileOpenList() = 0; - // computes CRC (zip compatible) for a file - // useful if a huge uncompressed file is generation in non continuous way - // good for big files - low memory overhead (1MB) - // Arguments: - // szPath - must not be 0 - // Returns: - // error code - virtual uint32_t ComputeCRC(AZStd::string_view szPath, uint32_t nFileOpenFlags = 0) = 0; - - // computes MD5 checksum for a file - // good for big files - low memory overhead (1MB) - // Arguments: - // szPath - must not be 0 - // md5 - destination array of uint8_t [16] - // Returns: - // true if success, false on failure - virtual bool ComputeMD5(AZStd::string_view szPath, uint8_t* md5, uint32_t nFileOpenFlags = 0, bool useDirectFileAccess = false) = 0; - - // useful for gathering file access statistics, assert if it was inserted already but then it does not become insersted + // useful for gathering file access statistics, assert if it was inserted already but then it does not become inserted // Arguments: // pSink - must not be 0 virtual void RegisterFileAccessSink(IArchiveFileAccessSink* pSink) = 0; @@ -408,8 +281,6 @@ namespace AZ::IO // When enabled, files accessed at runtime will be tracked virtual void DisableRuntimeFileAccess(bool status) = 0; virtual bool DisableRuntimeFileAccess(bool status, AZStd::thread_id threadId) = 0; - virtual bool CheckFileAccessDisabled(AZStd::string_view name, const char* mode) = 0; - virtual void SetRenderThreadId(AZStd::thread_id renderThreadId) = 0; // gets the current pak priority virtual ArchiveLocationPriority GetPakPriority() const = 0; @@ -431,21 +302,6 @@ namespace AZ::IO using LevelPackCloseEvent = AZ::Event; virtual auto GetLevelPackCloseEvent()->LevelPackCloseEvent* = 0; - // Type-safe endian conversion read. - template - size_t FRead(T* data, size_t elems, AZ::IO::HandleType fileHandle, bool bSwapEndian = false) - { - size_t count = FReadRaw(data, sizeof(T), elems, fileHandle); - SwapEndian(data, count, bSwapEndian); - return count; - } - // Type-independent Write. - template - void FWrite(T* data, size_t elems, AZ::IO::HandleType fileHandle) - { - FWrite((void*)data, sizeof(T), elems, fileHandle); - } - inline static constexpr IArchive::SignedFileSize FILE_NOT_PRESENT = -1; }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/INestedArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/INestedArchive.h index b45d705259..f85fd273ce 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/INestedArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/INestedArchive.h @@ -9,9 +9,9 @@ #pragma once +#include #include #include -#include #include namespace AZ::IO @@ -71,28 +71,10 @@ namespace AZ::IO // multiple times FLAGS_DONT_COMPACT = 1 << 5, - // flag is set when complete pak has been loaded into memory - FLAGS_IN_MEMORY = 1 << 6, - FLAGS_IN_MEMORY_CPU = 1 << 7, - FLAGS_IN_MEMORY_MASK = FLAGS_IN_MEMORY | FLAGS_IN_MEMORY_CPU, - - // Store all file names as crc32 in a flat directory structure. - FLAGS_FILENAMES_AS_CRC32 = 1 << 8, - - // flag is set when pak is stored on HDD - FLAGS_ON_HDD = 1 << 9, - - //Override pak - paks opened with this flag go at the end of the list and contents will be found before other paks - //Used for patching - FLAGS_OVERRIDE_PAK = 1 << 10, - // Disable a pak file without unloading it, this flag is used in combination with patches and multiplayer - // to ensure that specific paks stay in the position(to keep the same priority) but beeing disabled + // to ensure that specific paks stay in the position(to keep the same priority) but being disabled // when running multiplayer FLAGS_DISABLE_PAK = 1 << 11, - - // flag is set when pak is inside another pak - FLAGS_INSIDE_PAK = 1 << 12, }; using Handle = void*; @@ -122,7 +104,7 @@ namespace AZ::IO virtual int StartContinuousFileUpdate(AZStd::string_view szRelativePath, uint64_t nSize) = 0; // Summary: - // Adds a new file to the zip or update an existing's segment if it is not compressed - just stored + // Adds a new file to the zip or update an existing segment if it is not compressed - just stored // adds a directory (creates several nested directories if needed) // ( name might be misleading as if nOverwriteSeekPos is used the update is not continuous ) // Arguments: @@ -164,7 +146,7 @@ namespace AZ::IO // Summary: // Get the full path to the archive file. - virtual const char* GetFullPath() const = 0; + virtual AZ::IO::PathView GetFullPath() const = 0; // Summary: // Get the flags of this object. diff --git a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp index dc1d4aa864..1e0f237df5 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.cpp @@ -174,7 +174,7 @@ namespace AZ::IO return m_pCache->ReadFile(reinterpret_cast(fileHandle), nullptr, pBuffer); } - const char* NestedArchive::GetFullPath() const + AZ::IO::PathView NestedArchive::GetFullPath() const { return m_pCache->GetFilePath(); } @@ -193,19 +193,9 @@ namespace AZ::IO if (nFlagsToSet & FLAGS_RELATIVE_PATHS_ONLY) { m_nFlags |= FLAGS_RELATIVE_PATHS_ONLY; - } - - if (nFlagsToSet & FLAGS_ON_HDD) - { - m_nFlags |= FLAGS_ON_HDD; - } - - if (nFlagsToSet & FLAGS_RELATIVE_PATHS_ONLY || - nFlagsToSet & FLAGS_ON_HDD) - { - // we don't support changing of any other flags return true; } + return false; } @@ -252,20 +242,12 @@ namespace AZ::IO return AZ::IO::FixedMaxPathString{ szRelativePath }; } - if ((szRelativePath.size() > 1 && szRelativePath[1] == ':') || (m_nFlags & FLAGS_ABSOLUTE_PATHS)) + if ((m_nFlags & FLAGS_ABSOLUTE_PATHS) == FLAGS_ABSOLUTE_PATHS) { // make the normalized full path and try to match it against the binding root of this object - auto resolvedPath = AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(szRelativePath); - - // Make sure the resolve path is longer than the bind root and that it starts with the bind root - if (!resolvedPath || resolvedPath->Native().size() <= m_strBindRoot.size() || azstrnicmp(resolvedPath->c_str(), m_strBindRoot.c_str(), m_strBindRoot.size()) != 0) - { - return {}; - } - - // Remove the bind root prefix from the resolved path - resolvedPath->Native().erase(0, m_strBindRoot.size() + 1); - return resolvedPath->Native(); + AZ::IO::FixedMaxPath resolvedPath; + AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(resolvedPath, szRelativePath); + return resolvedPath.LexicallyProximate(m_strBindRoot).Native(); } return AZ::IO::FixedMaxPathString{ szRelativePath }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.h b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.h index 8ab943a24e..34bbcdc201 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/NestedArchive.h @@ -19,15 +19,15 @@ namespace AZ::IO { bool operator()(const INestedArchive* left, const INestedArchive* right) const { - return azstricmp(left->GetFullPath(), right->GetFullPath()) < 0; + return left->GetFullPath() < right->GetFullPath(); } bool operator()(AZStd::string_view left, const INestedArchive* right) const { - return azstrnicmp(left.data(), right->GetFullPath(), left.size()) < 0; + return AZ::IO::PathView(left) < right->GetFullPath(); } bool operator()(const INestedArchive* left, AZStd::string_view right) const { - return azstrnicmp(left->GetFullPath(), right.data(), right.size()) < 0; + return left->GetFullPath() < AZ::IO::PathView(right); } }; @@ -40,7 +40,7 @@ namespace AZ::IO NestedArchive(IArchive* pArchive, AZStd::string_view strBindRoot, ZipDir::CachePtr pCache, uint32_t nFlags = 0); ~NestedArchive() override; - auto GetRootFolderHandle() -> Handle; + auto GetRootFolderHandle() -> Handle override; // Adds a new file to the zip or update an existing one // adds a directory (creates several nested directories if needed) @@ -66,26 +66,26 @@ namespace AZ::IO int RemoveDir(AZStd::string_view szRelativePath) override; // deletes all files from the archive - int RemoveAll(); + int RemoveAll() override; // finds the file; you don't have to close the returned handle - Handle FindFile(AZStd::string_view szRelativePath); + Handle FindFile(AZStd::string_view szRelativePath) override; // returns the size of the file (unpacked) by the handle - uint64_t GetFileSize(Handle fileHandle); + uint64_t GetFileSize(Handle fileHandle) override; // reads the file into the preallocated buffer (must be at least the size of GetFileSize()) - int ReadFile(Handle fileHandle, void* pBuffer); + int ReadFile(Handle fileHandle, void* pBuffer) override; // returns the full path to the archive file - const char* GetFullPath() const; + AZ::IO::PathView GetFullPath() const override; ZipDir::Cache* GetCache(); - uint32_t GetFlags() const; - bool SetFlags(uint32_t nFlagsToSet); - bool ResetFlags(uint32_t nFlagsToReset); + uint32_t GetFlags() const override; + bool SetFlags(uint32_t nFlagsToSet) override; + bool ResetFlags(uint32_t nFlagsToReset) override; - bool SetPackAccessible(bool bAccessible); + bool SetPackAccessible(bool bAccessible) override; protected: // returns the pointer to the relative file path to be passed @@ -95,7 +95,7 @@ namespace AZ::IO ZipDir::CachePtr m_pCache; // the binding root may be empty string - in this case, the absolute path binding won't work - AZStd::string m_strBindRoot; + AZ::IO::Path m_strBindRoot; IArchive* m_archive{}; uint32_t m_nFlags{}; }; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp index 81f26d78b8..328541c4d0 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.cpp @@ -9,7 +9,6 @@ #include #include -#include #include #include @@ -104,24 +103,21 @@ namespace AZ::IO::ZipDir : m_pCache(pCache) , m_bCommitted(false) { - AZ::IO::PathString normalizedPath{ szRelativePath }; - AZ::StringFunc::Path::Normalize(normalizedPath); - AZStd::to_lower(AZStd::begin(normalizedPath), AZStd::end(normalizedPath)); // Update the cache string pool with the relative path to the file - auto pathIt = m_pCache->m_relativePathPool.emplace(normalizedPath); + auto pathIt = m_pCache->m_relativePathPool.emplace(AZ::IO::PathView(szRelativePath).LexicallyNormal()); m_szRelativePath = *pathIt.first; // this is the name of the directory - create it or find it - m_pFileEntry = m_pCache->GetRoot()->Add(m_szRelativePath); + m_pFileEntry = m_pCache->GetRoot()->Add(m_szRelativePath.Native()); if (m_pFileEntry && az_archive_zip_directory_cache_verbosity) { - AZ_TracePrintf("Archive", R"(File "%s" has been added to archive at root "%s")", normalizedPath.c_str(), pCache->GetFilePath()); + AZ_TracePrintf("Archive", R"(File "%s" has been added to archive at root "%s")", pathIt.first->c_str(), pCache->GetFilePath()); } } ~FileEntryTransactionAdd() { if (m_pFileEntry && !m_bCommitted) { - m_pCache->RemoveFile(m_szRelativePath); + m_pCache->RemoveFile(m_szRelativePath.Native()); m_pCache->m_relativePathPool.erase(m_szRelativePath); } } @@ -131,11 +127,11 @@ namespace AZ::IO::ZipDir } AZStd::string_view GetRelativePath() const { - return m_szRelativePath; + return m_szRelativePath.Native(); } private: Cache* m_pCache; - AZStd::string_view m_szRelativePath; + AZ::IO::PathView m_szRelativePath; FileEntry* m_pFileEntry; bool m_bCommitted; }; @@ -587,34 +583,27 @@ namespace AZ::IO::ZipDir // deletes the file from the archive ErrorEnum Cache::RemoveFile(AZStd::string_view szRelativePathSrc) { - // Normalize and lower case the relative path - AZ::IO::PathString szRelativePath{ szRelativePathSrc }; - AZ::StringFunc::Path::Normalize(szRelativePath); - AZStd::to_lower(AZStd::begin(szRelativePath), AZStd::end(szRelativePath)); - AZStd::string_view normalizedRelativePath = szRelativePath; - - // find the last slash in the path - size_t slashOffset = normalizedRelativePath.find_last_of(AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); + AZ::IO::PathView szRelativePath{ szRelativePathSrc }; AZStd::string_view fileName; // the name of the file to delete FileEntryTree* pDir; // the dir from which the subdir will be deleted - if (slashOffset != AZStd::string_view::npos) + if (szRelativePath.HasParentPath()) { FindDir fd(GetRoot()); // the directory to remove - pDir = fd.FindExact(normalizedRelativePath.substr(0, slashOffset)); + pDir = fd.FindExact(szRelativePath.ParentPath()); if (!pDir) { return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory } - fileName = normalizedRelativePath.substr(slashOffset + 1); + fileName = szRelativePath.Filename().Native(); } else { pDir = GetRoot(); - fileName = normalizedRelativePath; + fileName = szRelativePath.Native(); } ErrorEnum e = pDir->RemoveFile(fileName); @@ -625,7 +614,7 @@ namespace AZ::IO::ZipDir if (az_archive_zip_directory_cache_verbosity) { AZ_TracePrintf("Archive", R"(File "%.*s" has been remove from archive at root "%s")", - aznumeric_cast(fileName.size()), fileName.data(), GetFilePath()); + AZ_STRING_ARG(szRelativePath.Native()), GetFilePath()); } } return e; @@ -635,45 +624,38 @@ namespace AZ::IO::ZipDir // deletes the directory, with all its descendants (files and subdirs) ErrorEnum Cache::RemoveDir(AZStd::string_view szRelativePathSrc) { - // Normalize and lower case the relative path - AZ::IO::PathString szRelativePath{ szRelativePathSrc }; - AZ::StringFunc::Path::Normalize(szRelativePath); - AZStd::to_lower(AZStd::begin(szRelativePath), AZStd::end(szRelativePath)); - AZStd::string_view normalizedRelativePath = szRelativePath; - - // find the last slash in the path - size_t slashOffset = normalizedRelativePath.find_last_of(AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); + AZ::IO::PathView szRelativePath{ szRelativePathSrc }; AZStd::string_view dirName; // the name of the dir to delete FileEntryTree* pDir; // the dir from which the subdir will be deleted - if (slashOffset != AZStd::string_view::npos) + if (szRelativePath.HasParentPath()) { FindDir fd(GetRoot()); // the directory to remove - pDir = fd.FindExact(normalizedRelativePath.substr(0, slashOffset)); + pDir = fd.FindExact(szRelativePath.ParentPath()); if (!pDir) { return ZD_ERROR_DIR_NOT_FOUND;// there is no such directory } - dirName = normalizedRelativePath.substr(slashOffset + 1); + dirName = szRelativePath.Filename().Native(); } else { pDir = GetRoot(); - dirName = normalizedRelativePath; + dirName = szRelativePath.Native(); } - ErrorEnum e = pDir->RemoveDir(normalizedRelativePath); + ErrorEnum e = pDir->RemoveDir(dirName); if (e == ZD_ERROR_SUCCESS) { m_nFlags |= FLAGS_UNCOMPACTED | FLAGS_CDR_DIRTY; if (az_archive_zip_directory_cache_verbosity) { - AZ_TracePrintf("Archive", R"(File "%.*s" has been remove from archive at root "%s")", - aznumeric_cast(normalizedRelativePath.size()), normalizedRelativePath.data(), GetFilePath()); + AZ_TracePrintf("Archive", R"(Directory "%.*s" has been remove from archive at root "%s")", + AZ_STRING_ARG(szRelativePath.Native()), GetFilePath()); } } return e; @@ -769,9 +751,7 @@ namespace AZ::IO::ZipDir // finds the file by exact path FileEntry* Cache::FindFile(AZStd::string_view szPathSrc, [[maybe_unused]] bool bFullInfo) { - AZ::IO::PathString szPath{ szPathSrc }; - AZ::StringFunc::Path::Normalize(szPath); - AZStd::to_lower(AZStd::begin(szPath), AZStd::end(szPath)); + AZ::IO::PathView szPath{ szPathSrc }; ZipDir::FindFile fd(GetRoot()); FileEntry* fileEntry = fd.FindExact(szPath); @@ -779,19 +759,13 @@ namespace AZ::IO::ZipDir { if (az_archive_zip_directory_cache_verbosity) { - AZ_TracePrintf("Archive", "FindExact failed to find file %s at root %s", szPath.c_str(), GetFilePath()); + AZ_TracePrintf("Archive", "FindExact failed to find file %.*s at root %s", AZ_STRING_ARG(szPath.Native()), GetFilePath()); } return {}; } return fileEntry; } - // returns the size of memory occupied by the instance referred to by this cache - size_t Cache::GetSize() const - { - return sizeof(*this) + m_strFilePath.capacity() + m_treeDir.GetSize() - sizeof(m_treeDir); - } - // refreshes information about the given file entry into this file entry ErrorEnum Cache::Refresh(FileEntryBase* pFileEntry) { diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.h index 35bf0ae251..646410f8db 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCache.h @@ -16,6 +16,7 @@ #pragma once #include +#include #include #include #include @@ -89,9 +90,6 @@ namespace AZ::IO::ZipDir // refreshes information about the given file entry into this file entry ErrorEnum Refresh(FileEntryBase* pFileEntry); - // returns the size of memory occupied by the instance of this cache - size_t GetSize() const; - // QUICK check to determine whether the file entry belongs to this object bool IsOwnerOf(const FileEntry* pFileEntry) const { @@ -100,9 +98,9 @@ namespace AZ::IO::ZipDir // 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 + AZ::IO::PathView GetFilePath() const { - return m_strFilePath.c_str(); + return m_strFilePath; } FileEntryTree* GetRoot() @@ -135,10 +133,10 @@ namespace AZ::IO::ZipDir FileEntryTree m_treeDir; AZ::IO::HandleType m_fileHandle; AZ::IAllocatorAllocate* m_allocator; - AZStd::string m_strFilePath; + AZ::IO::Path m_strFilePath; // String Pool for persistently storing paths as long as they reside in the cache - AZStd::unordered_set m_relativePathPool; + AZStd::unordered_set m_relativePathPool; // 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 diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.cpp index 0092c7c8f8..6adab594ed 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.cpp @@ -41,13 +41,6 @@ namespace AZ::IO::ZipDir m_encryptedHeaders = ZipFile::HEADERS_NOT_ENCRYPTED; m_signedHeaders = ZipFile::HEADERS_NOT_SIGNED; - if (m_nFlags & FLAGS_FILENAMES_AS_CRC32) - { - m_bBuildFileEntryMap = false; - m_bBuildFileEntryTree = false; - m_bBuildOptimizedFileEntry = true; - } - if (m_nFlags & FLAGS_READ_INSIDE_PAK) { m_fileExt.m_fileIOBase = AZ::IO::FileIOBase::GetInstance(); @@ -88,12 +81,12 @@ namespace AZ::IO::ZipDir if (m_fileExt.m_fileHandle == AZ::IO::InvalidHandle) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for reading"); + AZ_Warning("Archive", false, R"(ZD_ERROR_IO_FAILED: Could not open file "%s" in binary mode for reading)", szFileName); return {}; } if (!ReadCache(*pCache)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not read the CDR of the pack file."); + AZ_Warning("Archive", false, R"(ZD_ERROR_IO_FAILED: Could not read the CDR of the pack file "%s".)", pCache->m_strFilePath.c_str()); return {}; } } @@ -113,12 +106,12 @@ namespace AZ::IO::ZipDir size_t nFileSize = (size_t)Tell(); Seek(0, SEEK_SET); - AZ_Assert(nFileSize != 0, "File of size 0 will not be open for reading"); + AZ_Warning("Archive", nFileSize != 0, R"(ZD_ERROR_IO_FAILED: File "%s" with size 0 will not be open for reading)", szFileName); if (nFileSize) { if (!ReadCache(*pCache)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for reading"); + AZ_Warning("Archive", false, R"(ZD_ERROR_IO_FAILED: Could not open file "%s" in binary mode for reading)", szFileName); return {}; } bOpenForWriting = false; @@ -143,7 +136,7 @@ namespace AZ::IO::ZipDir if (m_fileExt.m_fileHandle == AZ::IO::InvalidHandle) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Could not open file in binary mode for appending (read/write)"); + AZ_Warning("Archive", false, R"(ZD_ERROR_IO_FAILED: Could not open file "%s" in binary mode for appending (read/write))", szFileName); return {}; } } @@ -211,7 +204,7 @@ namespace AZ::IO::ZipDir if (m_headerExtended.nHeaderSize != sizeof(m_headerExtended)) { // Extended Header is not valid - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Bad extended header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Bad extended header"); return false; } //We have the header, so read the encryption and signing techniques @@ -224,7 +217,7 @@ namespace AZ::IO::ZipDir if (m_headerExtended.nEncryption != ZipFile::HEADERS_NOT_ENCRYPTED && m_encryptedHeaders != ZipFile::HEADERS_NOT_ENCRYPTED) { //Encryption technique has been specified in both the disk number (old technique) and the custom header (new technique). - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Unexpected encryption technique in header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Unexpected encryption technique in header"); return false; } else @@ -240,7 +233,7 @@ namespace AZ::IO::ZipDir break; default: // Unexpected technique - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Bad encryption technique in header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Bad encryption technique in header"); return false; } } @@ -255,7 +248,7 @@ namespace AZ::IO::ZipDir break; default: // Unexpected technique - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Bad signing technique in header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Bad signing technique in header"); return false; } @@ -266,7 +259,7 @@ namespace AZ::IO::ZipDir Read(&m_headerSignature, sizeof(m_headerSignature)); if (m_headerSignature.nHeaderSize != sizeof(m_headerSignature)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Bad signature header"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Bad signature header"); return false; } } @@ -274,7 +267,7 @@ namespace AZ::IO::ZipDir else { // Unexpected technique - THROW_ZIPDIR_ERROR(ZD_ERROR_DATA_IS_CORRUPT, "Comment field is the wrong length"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: Comment field is the wrong length"); return false; } } @@ -285,7 +278,7 @@ namespace AZ::IO::ZipDir || 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"); + AZ_Warning("Archive", false, "ZD_ERROR_UNSUPPORTED: Multivolume archive detected.Current version of ZipDir does not support multivolume archives"); return false; } @@ -295,7 +288,7 @@ namespace AZ::IO::ZipDir || 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 repare or delete the file"); + AZ_Warning("Archive", false, "ZD_ERROR_DATA_IS_CORRUPT: The central directory offset or size are out of range, the pak is probably corrupt, try to repare or delete the file"); return false; } @@ -394,7 +387,12 @@ namespace AZ::IO::ZipDir // 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 + AZ_Warning("Archive", false, "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; } @@ -418,7 +416,11 @@ namespace AZ::IO::ZipDir } 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"); + AZ_Warning("Archive", false, "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; } } @@ -436,7 +438,7 @@ namespace AZ::IO::ZipDir nOldBufPos = nNewBufPos; memmove(&pReservedBuffer[CDRSearchWindowSize], 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 + AZ_Assert(false, "ZD_ERROR_UNEXPECTED: The program flow may not have possibly lead here. This error is unexplainable"); // we shouldn't be here return false; } @@ -460,13 +462,13 @@ namespace AZ::IO::ZipDir 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"); + AZ_Warning("Archive", false, "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; } if (!ReadHeaderData(&pBuffer[0], m_CDREnd.lCDRSize)) { - THROW_ZIPDIR_ERROR(ZD_ERROR_CORRUPTED_DATA, "Archive contains corrupted CDR."); + AZ_Warning("Archive", false, "ZD_ERROR_CORRUPTED_DATA: Archive contains corrupted CDR."); return false; } @@ -482,7 +484,7 @@ namespace AZ::IO::ZipDir if ((pFile->nVersionNeeded & 0xFF) > 20) { - THROW_ZIPDIR_ERROR(ZD_ERROR_UNSUPPORTED, "Cannot read the archive file (nVersionNeeded > 20)."); + AZ_Warning("Archive", false, "ZD_ERROR_UNSUPPORTED: Cannot read the archive file (nVersionNeeded > 20)."); return false; } //if (pFile->lSignature != pFile->SIGNATURE) // Timur, Dont compare signatures as signatue in memory can be overwritten by the code below @@ -492,7 +494,8 @@ namespace AZ::IO::ZipDir // 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"); + AZ_Warning("Archive", false, "ZD_ERROR_CDR_IS_CORRUPT: Central Directory record is either corrupt, or truncated, or missing." + " Cannot read the archive directory"); return false; } @@ -555,13 +558,17 @@ namespace AZ::IO::ZipDir { 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 + AZ_Warning("Archive", false, "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->nMethod == ZipFile::METHOD_STORE_AND_STREAMCIPHER_KEYTABLE) && 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"); + AZ_Warning("Archive", false, "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; } @@ -617,7 +624,9 @@ namespace AZ::IO::ZipDir //|| 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"); + AZ_Warning("Archive", false, "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; } @@ -628,7 +637,9 @@ namespace AZ::IO::ZipDir if (!AZStd::equal(zipFileDataBegin, zipFileDataEnd, reinterpret_cast(pFileHeader + 1), CompareNoCase)) { // 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"); + AZ_Warning("Archive", false, "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; } @@ -642,7 +653,9 @@ namespace AZ::IO::ZipDir 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"); + AZ_Warning("Archive", false, "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; } @@ -686,29 +699,29 @@ namespace AZ::IO::ZipDir case Z_OK: break; case Z_MEM_ERROR: - THROW_ZIPDIR_ERROR(ZD_ERROR_ZLIB_NO_MEMORY, "ZLib reported out-of-memory error"); + AZ_Warning("Archive", false, "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"); + AZ_Warning("Archive", false, "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"); + AZ_Warning("Archive", false, "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"); + AZ_Warning("Archive", false, "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"); + AZ_Warning("Archive", false, "ZD_ERROR_CORRUPTED_DATA: Uncompressed stream doesn't match the size of uncompressed file stored in the archive file headers"); return; } uLong uCRC32 = AZ::Crc32((Bytef*)pUncompressed, nDestSize); if (uCRC32 != fileEntry.desc.lCRC32) { - THROW_ZIPDIR_ERROR(ZD_ERROR_CRC32_CHECK, "Uncompressed stream CRC32 check failed"); + AZ_Warning("Archive", false, "ZD_ERROR_CRC32_CHECK: Uncompressed stream CRC32 check failed"); return; } } @@ -737,7 +750,7 @@ namespace AZ::IO::ZipDir { if (FSeek(&m_fileExt, 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"); + AZ_Warning("Archive", false, "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; } } @@ -747,7 +760,7 @@ namespace AZ::IO::ZipDir int64_t nPos = FTell(&m_fileExt); 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"); + AZ_Warning("Archive", false, "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 nPos; @@ -757,7 +770,7 @@ namespace AZ::IO::ZipDir { if (FRead(&m_fileExt, pDest, nSize, 1) != 1) { - THROW_ZIPDIR_ERROR(ZD_ERROR_IO_FAILED, "Cannot fread() a portion of data from archive"); + AZ_Warning("Archive", false, "ZD_ERROR_IO_FAILED: Cannot fread() a portion of data from archive"); return false; } return true; diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.h index 1f27cb5504..c31d4d7dfd 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirCacheFactory.h @@ -33,20 +33,13 @@ namespace AZ::IO::ZipDir // if this is set, the archive will be created anew (the existing file will be overwritten) FLAGS_CREATE_NEW = 1 << 3, - // Cache will be loaded completely into the memory. - FLAGS_IN_MEMORY = 1 << 4, - FLAGS_IN_MEMORY_CPU = 1 << 5, - - // Store all file names as crc32 in a flat directory structure. - FLAGS_FILENAMES_AS_CRC32 = 1 << 6, - // if this is set, zip path will be searched inside other zips FLAGS_READ_INSIDE_PAK = 1 << 7, }; // 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, uint32_t nFlags = 0); + CacheFactory(InitMethodEnum nInitMethod, uint32_t nFlags = 0); ~CacheFactory(); // the new function creates a new cache diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.cpp index 30c8676f75..4fb1a54ded 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.cpp @@ -17,7 +17,7 @@ namespace AZ::IO::ZipDir { - bool FindFile::FindFirst(AZStd::string_view szWildcard) + bool FindFile::FindFirst(AZ::IO::PathView szWildcard) { if (!PreFind(szWildcard)) { @@ -29,7 +29,7 @@ namespace AZ::IO::ZipDir return SkipNonMatchingFiles(); } - bool FindDir::FindFirst(AZStd::string_view szWildcard) + bool FindDir::FindFirst(AZ::IO::PathView szWildcard) { if (!PreFind(szWildcard)) { @@ -42,37 +42,20 @@ namespace AZ::IO::ZipDir } // matches the file wildcard 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 FindData::MatchWildcard(AZStd::string_view szName) + bool FindData::MatchWildcard(AZ::IO::PathView szName) { - if (AZStd::wildcard_match(m_szWildcard, szName)) - { - return true; - } - - // check if the file object name contains extension sign (.) - size_t extensionOffset = szName.find('.'); - if (extensionOffset != AZStd::string_view::npos) - { - return false; - } - - // no extension sign - add it - AZStd::fixed_string szAlias{ szName }; - szAlias.push_back('.'); - - return AZStd::wildcard_match(m_szWildcard, szAlias); + return szName.Match(m_szWildcard.Native()); } - FileEntry* FindFile::FindExact(AZStd::string_view szPath) + FileEntry* FindFile::FindExact(AZ::IO::PathView szPath) { if (!PreFind(szPath)) { return nullptr; } - FileEntryTree::FileMap::iterator itFile = m_pDirHeader->FindFile(m_szWildcard.c_str()); + FileEntryTree::FileMap::iterator itFile = m_pDirHeader->FindFile(m_szWildcard); if (itFile == m_pDirHeader->GetFileEnd()) { m_pDirHeader = nullptr; // we didn't find it, fail the search @@ -84,7 +67,7 @@ namespace AZ::IO::ZipDir return m_pDirHeader->GetFileEntry(m_itFile); } - FileEntryTree* FindDir::FindExact(AZStd::string_view szPath) + FileEntryTree* FindDir::FindExact(AZ::IO::PathView szPath) { if (!PreFind(szPath)) { @@ -97,40 +80,50 @@ namespace AZ::IO::ZipDir ////////////////////////////////////////////////////////////////////////// // after this call returns successfully (with true returned), the m_szWildcard - // contains the file name/wildcard and m_pDirHeader contains the directory where + // contains the file name/glob and m_pDirHeader contains the directory where // the file (s) are to be found - bool FindData::PreFind(AZStd::string_view szWildcard) + bool FindData::PreFind(AZ::IO::PathView pathGlob) { if (!m_pRoot) { return false; } - // start the search from the root - m_pDirHeader = m_pRoot; - m_szWildcard = szWildcard; - - // for each path directory, copy it into the wildcard buffer and try to find the subdirectory - for (AZStd::optional pathEntry = AZ::StringFunc::TokenizeNext(szWildcard, AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); pathEntry; - pathEntry = AZ::StringFunc::TokenizeNext(szWildcard, AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR)) + FileEntryTree* entryTreeHeader = m_pRoot; + // If there is a root path in the glob path, attempt to locate it from the root + if (AZ::IO::PathView rootPath = m_szWildcard.RootPath(); !rootPath.empty()) { - // Update wildcard to new path entry - m_szWildcard = *pathEntry; - - // If the wildcard parameter that has been passed to TokenizeNext is empty - // Then pathEntry is the final portion of the path - if (!szWildcard.empty()) + FileEntryTree* dirEntry = entryTreeHeader->FindDir(rootPath); + if (dirEntry == nullptr) { - FileEntryTree* dirEntry = m_pDirHeader->FindDir(*pathEntry); - if (!dirEntry) - { - m_pDirHeader = nullptr; // an intermediate directory has not been found continue the search - return false; - } - m_pDirHeader = dirEntry->GetDirectory(); + return false; } + + entryTreeHeader = dirEntry->GetDirectory(); + pathGlob = pathGlob.RelativePath(); + } + + + AZ::IO::PathView filenameSegment = pathGlob; + // Recurse through the directories within the file tree for each remaining parent path segment + // of pathGlob parameter + auto parentPathIter = pathGlob.begin(); + for (auto filenamePathIter = parentPathIter == pathGlob.end() ? pathGlob.end() : AZStd::next(parentPathIter, 1); + filenamePathIter != pathGlob.end(); ++parentPathIter, ++filenamePathIter) + { + FileEntryTree* dirEntry = entryTreeHeader->FindDir(*parentPathIter); + if (dirEntry == nullptr) + { + return false; + } + entryTreeHeader = dirEntry->GetDirectory(); + filenameSegment = *filenamePathIter; } + // At this point the all the intermediate directories have been found + // so update the directory header to point at the last file entry tree + m_pDirHeader = entryTreeHeader; + m_szWildcard = filenameSegment; return true; } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.h index 2bb3932aa9..f9b773a42d 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirFind.h @@ -38,11 +38,10 @@ namespace AZ::IO::ZipDir // 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(AZStd::string_view szWildcard); + bool PreFind(AZ::IO::PathView szWildcard); // matches the file wildcard 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(AZStd::string_view szName); + bool MatchWildcard(AZ::IO::PathView szName); // the directory inside which the current object (file or directory) is being searched FileEntryTree* m_pDirHeader{}; @@ -50,7 +49,7 @@ namespace AZ::IO::ZipDir 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! - AZStd::fixed_string m_szWildcard; + AZ::IO::FixedMaxPath m_szWildcard; }; class FindFile @@ -66,9 +65,9 @@ namespace AZ::IO::ZipDir { } // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst(AZStd::string_view szWildcard); + bool FindFirst(AZ::IO::PathView szWildcard); - FileEntry* FindExact(AZStd::string_view szPath); + FileEntry* FindExact(AZ::IO::PathView szPath); // goes on to the next file entry bool FindNext(); @@ -94,9 +93,9 @@ namespace AZ::IO::ZipDir { } // if bExactFile is passed, only the file is searched, and besides with the exact name as passed (no wildcards) - bool FindFirst(AZStd::string_view szWildcard); + bool FindFirst(AZ::IO::PathView szWildcard); - FileEntryTree* FindExact(AZStd::string_view szPath); + FileEntryTree* FindExact(AZ::IO::PathView szPath); // goes on to the next file entry bool FindNext(); diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirList.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirList.cpp index 2f96a93a82..729f394b9d 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirList.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirList.cpp @@ -68,14 +68,14 @@ namespace AZ::IO::ZipDir { for (FileEntryTree::SubdirMap::iterator it = pTree->GetDirBegin(); it != pTree->GetDirEnd(); ++it) { - AddAllFiles(it->second.get(), AZStd::string::format("%.*s%.*s/", aznumeric_cast(strRoot.size()), strRoot.data(), aznumeric_cast(it->first.size()), it->first.data())); + AddAllFiles(it->second.get(), (AZ::IO::Path(strRoot) / it->first).Native()); } for (FileEntryTree::FileMap::iterator it = pTree->GetFileBegin(); it != pTree->GetFileEnd(); ++it) { FileRecord rec; rec.pFileEntryBase = pTree->GetFileEntry(it); - rec.strPath = AZStd::string::format("%.*s%.*s", aznumeric_cast(strRoot.size()), strRoot.data(), aznumeric_cast(it->first.size()), it->first.data()); + rec.strPath = (AZ::IO::Path(strRoot) / it->first).Native(); push_back(rec); } } diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp index 1d09705900..f9aa249339 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.cpp @@ -432,18 +432,18 @@ namespace AZ::IO::ZipDir bool CZipFile::EvaluateSectorSize(const char* filename) { - char volume[AZ_MAX_PATH_LEN]; + AZ::IO::FixedMaxPath volume; - if (AZ::StringFunc::Path::IsRelative(filename)) + if (AZ::IO::PathView(filename).IsRelative()) { - AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(filename, volume, AZ_ARRAY_SIZE(volume)); + AZ::IO::FileIOBase::GetDirectInstance()->ResolvePath(volume, filename); } else { - azstrcpy(volume, AZ_ARRAY_SIZE(volume), filename); + volume = filename; } - AZ::IO::FixedMaxPathString drive{ AZ::IO::PathView(volume).RootName().Native() }; + AZ::IO::FixedMaxPath drive = volume.RootName(); if (drive.empty()) { return false; @@ -666,7 +666,9 @@ namespace AZ::IO::ZipDir DirEntry* pEnd = pBegin + this->numDirs; DirEntry* pEntry = AZStd::lower_bound(pBegin, pEnd, szName, pred); #if AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM - if (pEntry != pEnd && !azstrnicmp(szName.data(), pEntry->GetName(pNamePool), szName.size())) + AZ::IO::PathView searchPath(szName, AZ::IO::WindowsPathSeparator); + AZ::IO::PathView entryPath(pEntry->GetName(pNamePool), AZ::IO::WindowsPathSeparator); + if (pEntry != pEnd && searchPath == entryPath) #else if (pEntry != pEnd && szName == pEntry->GetName(pNamePool)) #endif @@ -690,7 +692,9 @@ namespace AZ::IO::ZipDir FileEntry* pEnd = pBegin + this->numFiles; FileEntry* pEntry = AZStd::lower_bound(pBegin, pEnd, szName, pred); #if AZ_TRAIT_LEGACY_CRYPAK_UNIX_LIKE_FILE_SYSTEM - if (pEntry != pEnd && !azstrnicmp(szName.data(), pEntry->GetName(pNamePool), szName.size())) + AZ::IO::PathView searchPath(szName, AZ::IO::WindowsPathSeparator); + AZ::IO::PathView entryPath(pEntry->GetName(pNamePool), AZ::IO::WindowsPathSeparator); + if (pEntry != pEnd && searchPath == entryPath) #else if (pEntry != pEnd && szName == pEntry->GetName(pNamePool)) #endif @@ -990,13 +994,6 @@ namespace AZ::IO::ZipDir } ////////////////////////////////////////////////////////////////////////// - uint32_t FileNameHash(AZStd::string_view filename) - { - AZ::IO::StackString pathname{ filename }; - AZStd::replace(AZStd::begin(pathname), AZStd::end(pathname), AZ_WRONG_DATABASE_SEPARATOR, AZ_CORRECT_DATABASE_SEPARATOR); - - return AZ::Crc32(pathname); - } int64_t FSeek(CZipFile* file, int64_t origin, int command) { diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.h index 2f9046f53e..7e1d54b405 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirStructures.h @@ -119,8 +119,6 @@ namespace AZ::IO::ZipDir const char* m_szDescription; }; -#define THROW_ZIPDIR_ERROR(ZD_ERR, DESC) AZ_Warning("Archive", false, DESC) - // possible initialization methods enum InitMethodEnum { @@ -157,8 +155,6 @@ namespace AZ::IO::ZipDir int FEof(CZipFile* zipFile); - uint32_t FileNameHash(AZStd::string_view filename); - ////////////////////////////////////////////////////////////////////////// struct SExtraZipFileData diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.cpp b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.cpp index 213287ef74..e772cb596a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.cpp @@ -9,7 +9,6 @@ #include #include -#include #include #include #include @@ -18,37 +17,42 @@ namespace AZ::IO::ZipDir { // Adds or finds the file. Returns non-initialized structure if it was added, // or an IsInitialized() structure if it was found - FileEntry* FileEntryTree::Add(AZStd::string_view szPath) + FileEntry* FileEntryTree::Add(AZ::IO::PathView inputPathView) { - AZStd::optional pathEntry = AZ::StringFunc::TokenizeNext(szPath, AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR); - if (!pathEntry) + if (inputPathView.empty()) { AZ_Assert(false, "An empty file path cannot be added to the zip file entry tree"); return nullptr; } // If a path separator was found, add a subdirectory - if (!szPath.empty()) + auto inputPathIter = inputPathView.begin(); + AZ::IO::PathView firstPathSegment(*inputPathIter); + auto inputPathNextIter = inputPathIter == inputPathView.end() ? inputPathView.end() : AZStd::next(inputPathIter, 1); + AZ::IO::PathView remainingPath = inputPathNextIter != inputPathView.end() ? + AZStd::string_view(inputPathNextIter->Native().begin(), inputPathView.Native().end()) + : AZStd::string_view{}; + if (!remainingPath.empty()) { - auto dirEntryIter = m_mapDirs.find(*pathEntry); + auto dirEntryIter = m_mapDirs.find(firstPathSegment); // we have a subdirectory here - create the file in it if (dirEntryIter == m_mapDirs.end()) { - dirEntryIter = m_mapDirs.emplace(*pathEntry, AZStd::make_unique()).first; + dirEntryIter = m_mapDirs.emplace(firstPathSegment, AZStd::make_unique()).first; } - return dirEntryIter->second->Add(szPath); + return dirEntryIter->second->Add(remainingPath); } // Add the filename - auto fileEntryIter = m_mapFiles.find(*pathEntry); + auto fileEntryIter = m_mapFiles.find(firstPathSegment); if (fileEntryIter == m_mapFiles.end()) { - fileEntryIter = m_mapFiles.emplace(*pathEntry, AZStd::make_unique()).first; + fileEntryIter = m_mapFiles.emplace(firstPathSegment, AZStd::make_unique()).first; } return fileEntryIter->second.get(); } // adds a file to this directory - ErrorEnum FileEntryTree::Add(AZStd::string_view szPath, const FileEntryBase& file) + ErrorEnum FileEntryTree::Add(AZ::IO::PathView szPath, const FileEntryBase& file) { FileEntry* pFile = Add(szPath); if (!pFile) @@ -63,7 +67,7 @@ namespace AZ::IO::ZipDir return ZD_ERROR_SUCCESS; } - // returns the number of files in this tree, including this and sublevels + // returns the number of files in this tree, including this and subdirectories uint32_t FileEntryTree::NumFilesTotal() const { uint32_t numFiles = aznumeric_cast(m_mapFiles.size()); @@ -91,21 +95,6 @@ namespace AZ::IO::ZipDir m_mapFiles.clear(); } - size_t FileEntryTree::GetSize() const - { - size_t nSize = sizeof(*this); - for (const auto& [dirname, dirEntry] : m_mapDirs) - { - nSize += dirname.size() + sizeof(decltype(m_mapDirs)::value_type) + dirEntry->GetSize(); - } - - for (const auto& [filename, fileEntry] : m_mapFiles) - { - nSize += filename.size() + sizeof(decltype(m_mapFiles)::value_type); - } - return nSize; - } - bool FileEntryTree::IsOwnerOf(const FileEntry* pFileEntry) const { for (const auto& [path, fileEntry] : m_mapFiles) @@ -127,7 +116,7 @@ namespace AZ::IO::ZipDir return false; } - FileEntryTree* FileEntryTree::FindDir(AZStd::string_view szDirName) + FileEntryTree* FileEntryTree::FindDir(AZ::IO::PathView szDirName) { if (auto it = m_mapDirs.find(szDirName); it != m_mapDirs.end()) { @@ -137,7 +126,7 @@ namespace AZ::IO::ZipDir return nullptr; } - FileEntryTree::FileMap::iterator FileEntryTree::FindFile(AZStd::string_view szFileName) + FileEntryTree::FileMap::iterator FileEntryTree::FindFile(AZ::IO::PathView szFileName) { return m_mapFiles.find(szFileName); } @@ -152,7 +141,7 @@ namespace AZ::IO::ZipDir return it == GetDirEnd() ? nullptr : it->second.get(); } - ErrorEnum FileEntryTree::RemoveDir(AZStd::string_view szDirName) + ErrorEnum FileEntryTree::RemoveDir(AZ::IO::PathView szDirName) { SubdirMap::iterator itRemove = m_mapDirs.find(szDirName); if (itRemove == m_mapDirs.end()) @@ -164,7 +153,13 @@ namespace AZ::IO::ZipDir return ZD_ERROR_SUCCESS; } - ErrorEnum FileEntryTree::RemoveFile(AZStd::string_view szFileName) + ErrorEnum FileEntryTree::RemoveAll() + { + Clear(); + return ZD_ERROR_SUCCESS; + } + + ErrorEnum FileEntryTree::RemoveFile(AZ::IO::PathView szFileName) { FileMap::iterator itRemove = m_mapFiles.find(szFileName); if (itRemove == m_mapFiles.end()) diff --git a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.h b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.h index cfe539e896..9bdc047a7a 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.h +++ b/Code/Framework/AzFramework/AzFramework/Archive/ZipDirTree.h @@ -10,6 +10,7 @@ #pragma once #include +#include #include #include #include @@ -24,12 +25,12 @@ namespace AZ::IO::ZipDir // adds a file to this directory // Function can modify szPath input - ErrorEnum Add(AZStd::string_view szPath, const FileEntryBase& file); + ErrorEnum Add(AZ::IO::PathView szPath, const FileEntryBase& 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(AZStd::string_view szPath); + FileEntry* Add(AZ::IO::PathView szPath); // returns the number of files in this tree, including this and sublevels uint32_t NumFilesTotal() const; @@ -45,24 +46,18 @@ namespace AZ::IO::ZipDir m_mapFiles.swap(rThat.m_mapFiles); } - size_t GetSize() const; - bool IsOwnerOf(const FileEntry* pFileEntry) const; // subdirectories - using SubdirMap = AZStd::map>; + using SubdirMap = AZStd::map>; // file entries - using FileMap = AZStd::map>; + using FileMap = AZStd::map>; - FileEntryTree* FindDir(AZStd::string_view szDirName); - ErrorEnum RemoveDir (AZStd::string_view szDirName); - ErrorEnum RemoveAll () - { - Clear(); - return ZD_ERROR_SUCCESS; - } - FileMap::iterator FindFile(AZStd::string_view szFileName); - ErrorEnum RemoveFile(AZStd::string_view szFileName); + FileEntryTree* FindDir(AZ::IO::PathView szDirName); + ErrorEnum RemoveDir(AZ::IO::PathView szDirName); + ErrorEnum RemoveAll(); + FileMap::iterator FindFile(AZ::IO::PathView szFileName); + ErrorEnum RemoveFile(AZ::IO::PathView szFileName); // the FileEntryTree is simultaneously an entry in the dir list AND the directory header FileEntryTree* GetDirectory() { @@ -75,8 +70,8 @@ namespace AZ::IO::ZipDir SubdirMap::iterator GetDirBegin() { return m_mapDirs.begin(); } SubdirMap::iterator GetDirEnd() { return m_mapDirs.end(); } uint32_t NumDirs() const { return aznumeric_cast(m_mapDirs.size()); } - AZStd::string_view GetFileName(FileMap::iterator it) { return it->first; } - AZStd::string_view GetDirName(SubdirMap::iterator it) { return it->first; } + AZStd::string_view GetFileName(FileMap::iterator it) { return it->first.Native(); } + AZStd::string_view GetDirName(SubdirMap::iterator it) { return it->first.Native(); } FileEntry* GetFileEntry(FileMap::iterator it); FileEntryTree* GetDirEntry(SubdirMap::iterator it); diff --git a/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.h b/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.h index d6d67c2aa2..ac811ae478 100644 --- a/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.h +++ b/Code/Framework/AzFramework/AzFramework/Asset/AssetProcessorMessages.h @@ -866,7 +866,7 @@ namespace AzFramework FileIsReadOnlyResponse() = default; FileIsReadOnlyResponse(bool isReadOnly); - unsigned int GetMessageType() const; + unsigned int GetMessageType() const override; bool m_isReadOnly; }; @@ -945,7 +945,7 @@ namespace AzFramework FileModTimeRequest() = default; FileModTimeRequest(const AZ::OSString& filePath); - unsigned int GetMessageType() const; + unsigned int GetMessageType() const override; AZ::OSString m_filePath; }; diff --git a/Code/Framework/AzFramework/AzFramework/Asset/GenericAssetHandler.h b/Code/Framework/AzFramework/AzFramework/Asset/GenericAssetHandler.h index 5ead8154e6..4c3f911871 100644 --- a/Code/Framework/AzFramework/AzFramework/Asset/GenericAssetHandler.h +++ b/Code/Framework/AzFramework/AzFramework/Asset/GenericAssetHandler.h @@ -75,7 +75,7 @@ namespace AzFramework { public: AZ_RTTI(GenericAssetHandlerBase, "{B153B8B5-25CC-4BB7-A2BD-9A47ECF4123C}", AZ::Data::AssetHandler); - virtual ~GenericAssetHandlerBase() {} + virtual ~GenericAssetHandlerBase() = default; }; template @@ -186,7 +186,7 @@ namespace AzFramework } } - bool CanHandleAsset(const AZ::Data::AssetId& id) const + bool CanHandleAsset(const AZ::Data::AssetId& id) const override { AZStd::string assetPath; EBUS_EVENT_RESULT(assetPath, AZ::Data::AssetCatalogRequestBus, GetAssetPathById, id); diff --git a/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp b/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp index c5fee7ec9a..83f1954e11 100644 --- a/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp +++ b/Code/Framework/AzFramework/AzFramework/AzFrameworkModule.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -47,6 +48,7 @@ namespace AzFramework AzFramework::CreateScriptDebugAgentFactory(), AzFramework::AssetSystem::AssetSystemComponent::CreateDescriptor(), AzFramework::InputSystemComponent::CreateDescriptor(), + AzFramework::InputContextComponent::CreateDescriptor(), #if !defined(AZCORE_EXCLUDE_LUA) AzFramework::ScriptComponent::CreateDescriptor(), diff --git a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.h b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.h index 16032e5337..bc1bf1a6b2 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.h @@ -28,7 +28,7 @@ namespace AzFramework // AZ::NonUniformScaleRequests::Handler ... AZ::Vector3 GetScale() const override; void SetScale(const AZ::Vector3& scale) override; - void RegisterScaleChangedEvent(AZ::NonUniformScaleChangedEvent::Handler& handler); + void RegisterScaleChangedEvent(AZ::NonUniformScaleChangedEvent::Handler& handler) override; protected: // AZ::Component ... diff --git a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h index 68af9dbb26..49506364f4 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h @@ -105,7 +105,7 @@ namespace AzFramework virtual AZ::Matrix3x4 PopPremultipliedMatrix() { return AZ::Matrix3x4::CreateIdentity(); } protected: - ~DebugDisplayRequests() = default; + virtual ~DebugDisplayRequests() = default; }; /// Inherit from DebugDisplayRequestBus::Handler to implement the DebugDisplayRequests interface. diff --git a/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.h b/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.h index 831067d728..b9a4ea0da1 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/GameEntityContextComponent.h @@ -69,7 +69,7 @@ namespace AzFramework // EntityContext AZ::Entity* CreateEntity(const char* name) override; void OnRootEntityReloaded() override; - void OnContextEntitiesAdded(const EntityList& entities); + void OnContextEntitiesAdded(const EntityList& entities) override; void OnContextReset() override; bool ValidateEntitiesAreValidForContext(const EntityList& entities) override; ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzFramework/AzFramework/Gem/GemInfo.cpp b/Code/Framework/AzFramework/AzFramework/Gem/GemInfo.cpp index 62a6334b5d..a7c6b18061 100644 --- a/Code/Framework/AzFramework/AzFramework/Gem/GemInfo.cpp +++ b/Code/Framework/AzFramework/AzFramework/Gem/GemInfo.cpp @@ -34,6 +34,7 @@ namespace AzFramework { } + using AZ::SettingsRegistryInterface::Visitor::Visit; void Visit(AZStd::string_view path, AZStd::string_view, AZ::SettingsRegistryInterface::Type, AZStd::string_view value) override { diff --git a/Code/Framework/AzFramework/AzFramework/IO/LocalFileIO.cpp b/Code/Framework/AzFramework/AzFramework/IO/LocalFileIO.cpp index 50190ac7d5..4072c17ea0 100644 --- a/Code/Framework/AzFramework/AzFramework/IO/LocalFileIO.cpp +++ b/Code/Framework/AzFramework/AzFramework/IO/LocalFileIO.cpp @@ -734,7 +734,7 @@ namespace AZ { if (AZ::StringFunc::StartsWith(pathStrView, aliasKey)) { - // Reduce of the size result result path by the size of the and add the resolved alias size + // Add to the size of result path by the resolved alias length - the alias key length AZStd::string_view postAliasView = pathStrView.substr(aliasKey.size()); size_t requiredFixedMaxPathSize = postAliasView.size(); requiredFixedMaxPathSize += aliasValue.size(); diff --git a/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContext.h b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContext.h index 7220b8b8d5..e7143a25b9 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContext.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContext.h @@ -55,6 +55,10 @@ namespace AzFramework // Allocator AZ_CLASS_ALLOCATOR(InputContext, AZ::SystemAllocator, 0); + //////////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(InputContext, "{D17A85B2-405F-40AB-BBA7-F118256D39AB}", InputDevice); + //////////////////////////////////////////////////////////////////////////////////////////// //! Constructor //! \param[in] name Unique, will be truncated if exceeds InputDeviceId::MAX_NAME_LENGTH = 64 diff --git a/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.cpp b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.cpp new file mode 100644 index 0000000000..ff147bd9d8 --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////// +namespace AzFramework +{ + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC("InputContextService", 0xa2734425)); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Unique Name", &InputContextComponent::m_uniqueName) + ->Field("Input Mappings", &InputContextComponent::m_inputMappings) + ->Field("Local Player Index", &InputContextComponent::m_localPlayerIndex) + ->Field("Input Listener Priority", &InputContextComponent::m_inputListenerPriority) + ->Field("Consumes Processed Input", &InputContextComponent::m_consumesProcessedInput) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class("Input Context", + "An input context is a collection of input mappings, which map 'raw' input to custom input channels (ie. events).") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::Category, "Input") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) + ->DataElement(AZ::Edit::UIHandlers::Default, &InputContextComponent::m_uniqueName, "Unique Name", + "The name of the input context, unique among all active input contexts and input devices.\n" + "This will be truncated if its length exceeds that of InputDeviceId::MAX_NAME_LENGTH = 64") + ->DataElement(AZ::Edit::UIHandlers::Default, &InputContextComponent::m_inputMappings, "Input Mappings", + "The list of all input mappings that will be created when the input context is activated.") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::SpinBox, &InputContextComponent::m_localPlayerIndex, "Local Player Index", + "The local player index that this context will receive input from (0 based, -1 means all controllers).\n" + "Will only work on platforms such as PC where the local user id corresponds to the local player index.\n" + "For other platforms, SetLocalUserId must be called at runtime with the id of a logged in user.") + ->Attribute(AZ::Edit::Attributes::Min, -1) + ->Attribute(AZ::Edit::Attributes::Max, 3) + ->DataElement(AZ::Edit::UIHandlers::SpinBox, &InputContextComponent::m_inputListenerPriority, "Input Listener Priority", + "The priority used to sort the input context relative to all other input event listeners.\n" + "Higher numbers indicate greater priority.") + ->Attribute(AZ::Edit::Attributes::Min, InputChannelEventListener::GetPriorityLast()) + ->Attribute(AZ::Edit::Attributes::Max, InputChannelEventListener::GetPriorityFirst()) + ->DataElement(AZ::Edit::UIHandlers::CheckBox, &InputContextComponent::m_consumesProcessedInput, "Consumes Processed Input", + "Should the input context consume input that is processed by any of its input mappings?") + ; + } + } + + InputMapping::ConfigBase::Reflect(context); + InputMappingAnd::Config::Reflect(context); + InputMappingOr::Config::Reflect(context); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + InputContextComponent::~InputContextComponent() + { + Deactivate(); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::Init() + { + // The local player index that this component will receive input from (0 base, -1 wildcard) + // can be set from data, but will only work on platforms where the local user id corresponds + // to a local player index. For other platforms SetLocalUserId must be called at runtime with + // the id of a logged in local user, which will overwrite anything that is set here from data. + const LocalUserId localUserId = (m_localPlayerIndex == -1) ? LocalUserIdAny : aznumeric_cast(m_localPlayerIndex); + SetLocalUserId(localUserId); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::Activate() + { + InputContextComponentRequestBus::Handler::BusConnect(GetEntityId()); + CreateInputContext(); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::Deactivate() + { + ResetInputContext(); + InputContextComponentRequestBus::Handler::BusDisconnect(GetEntityId()); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::SetLocalUserId(LocalUserId localUserId) + { + // Create a new filter, or reset any existing one if we have been passed LocalUserIdAny. + if (localUserId != LocalUserIdAny) + { + m_localUserIdFilter = AZStd::make_shared(InputChannelEventFilter::AnyChannelNameCrc32, + InputChannelEventFilter::AnyDeviceNameCrc32, + aznumeric_cast(m_localPlayerIndex)); + } + else + { + m_localUserIdFilter.reset(); + } + + // Set the filter if the input context has already been created. + if (m_inputContext) + { + m_inputContext->SetFilter(m_localUserIdFilter); + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::CreateInputContext() + { + if (m_uniqueName.empty()) + { + AZ_Error("InputContextComponent", false, "Cannot create input context with empty name."); + return; + } + + if (InputDeviceRequests::FindInputDevice(InputDeviceId(m_uniqueName.c_str()))) + { + AZ_Error("InputContextComponent", false, + "Cannot create input context '%s' with non-unique name.", m_uniqueName.c_str()); + return; + } + + if (m_inputMappings.empty()) + { + AZ_Error("InputContextComponent", false, + "Cannot create input context '%s' with no input mappings.", m_uniqueName.c_str()); + return; + } + + // Create the input context. + InputContext::InitData initData; + initData.autoActivate = true; + initData.filter = m_localUserIdFilter; + initData.priority = m_inputListenerPriority; + initData.consumesProcessedInput = m_consumesProcessedInput; + m_inputContext = AZStd::make_unique(m_uniqueName.c_str(), initData); + + // Create and add all input mappings. + for (const InputMapping::ConfigBase* inputMapping : m_inputMappings) + { + inputMapping->CreateInputMappingAndAddToContext(*m_inputContext); + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputContextComponent::ResetInputContext() + { + m_inputContext.reset(); + } +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.h b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.h new file mode 100644 index 0000000000..1b9286bd4c --- /dev/null +++ b/Code/Framework/AzFramework/AzFramework/Input/Contexts/InputContextComponent.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +//////////////////////////////////////////////////////////////////////////////////////////////////// +namespace AzFramework +{ + //////////////////////////////////////////////////////////////////////////////////////////////// + class InputContextComponentRequests : public AZ::ComponentBus + { + public: + //////////////////////////////////////////////////////////////////////////////////////////// + //! Set the local user id that the InputContextComponent should process input from + //! \param[in] localUserId Local user id the InputContextComponent should process input from + virtual void SetLocalUserId(LocalUserId localUserId) = 0; + }; + using InputContextComponentRequestBus = AZ::EBus; + + //////////////////////////////////////////////////////////////////////////////////////////////// + //! An InputContextComponent is used to configure (at edit time) the data necessary to create an + //! InputContext (at run time). The life cycle of any InputContextComponent is controlled by the + //! AZ::Entity it is attached to, adhering to the same rules as any other AZ::Component, and the + //! InputContext which it owns is created/destroyed when the component is activated/deactivated. + class InputContextComponent : public AZ::Component + , public InputContextComponentRequestBus::Handler + { + public: + //////////////////////////////////////////////////////////////////////////////////////////// + // AZ::Component Setup + AZ_COMPONENT(InputContextComponent, "{321689F8-A572-47D7-9D1C-EF9E0D2CD472}"); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::ComponentDescriptor::GetProvidedServices + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::ComponentDescriptor::Reflect + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Default Constructor + InputContextComponent() = default; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + ~InputContextComponent() override; + + protected: + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::Component::Init + void Init() override; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::Component::Activate + void Activate() override; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! \ref AZ::Component::Deactivate + void Deactivate() override; + + //////////////////////////////////////////////////////////////////////////////////////////// + // \ref AzFramework::InputContextComponentRequests::SetLocalUserId + void SetLocalUserId(LocalUserId localUserId) override; + + private: + //////////////////////////////////////////////////////////////////////////////////////////// + //! Create the input context. + void CreateInputContext(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Reset the input context. + void ResetInputContext(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! The list of all input mappings that will be created when the input context is activated. + //! Reflected to EditContext, then used to create and add input mapping classes in Activate. + AZStd::vector m_inputMappings; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! The name of the input context, unique among all active input contexts and input devices. + //! This will be truncated if its length exceeds that of InputDeviceId::MAX_NAME_LENGTH = 64 + //! Reflected to EditContext, then used to create the unique input context class in Activate. + AZStd::string m_uniqueName; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Input context that is created and owned by this component. Not reflected to EditContext. + AZStd::unique_ptr m_inputContext; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Filter used to determine whether an input event should be handled by this input context. + //! Not reflected, but created inside SetLocalUserId if needed to fliter by a local user id. + AZStd::shared_ptr m_localUserIdFilter; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! The local player index that this component will receive input from (0 base, -1 wildcard). + //! Will only work on platforms where the local user id corresponds to the local player index. + //! For other platforms, SetLocalUserId must be called at runtime with id of a logged in user. + //! Reflected to EditContext, then used if needed to create the local user id filter in Init. + AZ::s32 m_localPlayerIndex = -1; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! The priority used to sort the input context relative to all other input event listeners. + //! Reflected to EditContext, then used to create the unique input context class in Activate. + AZ::s32 m_inputListenerPriority = InputChannelEventListener::GetPriorityDefault(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Should the input context consume input that is processed by any of its input mappings? + //! Reflected to EditContext, then used to create the unique input context class in Activate. + bool m_consumesProcessedInput = false; + }; +} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.cpp b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.cpp index 2f848368ca..b8a261677f 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.cpp +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.cpp @@ -9,9 +9,156 @@ #include #include +#include +#include +#include + //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework { + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputMapping::InputChannelNameFilteredByDeviceType::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Input Device Type", &InputChannelNameFilteredByDeviceType::m_inputDeviceType) + ->Field("Input Channel Name", &InputChannelNameFilteredByDeviceType::m_inputChannelName) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class("InputChannelNameFilteredByDeviceType", + "An input channel name (filtered by an input device type) to add to the input mapping.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &InputChannelNameFilteredByDeviceType::GetNameLabelOverride) + ->DataElement(AZ::Edit::UIHandlers::ComboBox, &InputChannelNameFilteredByDeviceType::m_inputDeviceType, "Input Device Type", + "The type of input device by which to filter input channel names.") + ->Attribute(AZ::Edit::Attributes::StringList, &InputChannelNameFilteredByDeviceType::GetValidInputDeviceTypes) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &InputChannelNameFilteredByDeviceType::OnInputDeviceTypeSelected) + ->DataElement(AZ::Edit::UIHandlers::ComboBox, &InputChannelNameFilteredByDeviceType::m_inputChannelName, "Input Channel Name", + "The input channel name to add to the input mapping.") + ->Attribute(AZ::Edit::Attributes::StringList, &InputChannelNameFilteredByDeviceType::GetValidInputChannelNamesBySelectedDevice) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ; + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + InputMapping::InputChannelNameFilteredByDeviceType::InputChannelNameFilteredByDeviceType() + { + // Try initialize the selected input device type and input channel name to something valid. + if (m_inputDeviceType.empty()) + { + const AZStd::vector validInputDeviceTypes = GetValidInputDeviceTypes(); + if (!validInputDeviceTypes.empty()) + { + m_inputDeviceType = validInputDeviceTypes[0]; + OnInputDeviceTypeSelected(); + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + AZ::Crc32 InputMapping::InputChannelNameFilteredByDeviceType::OnInputDeviceTypeSelected() + { + const AZStd::vector validInputNames = GetValidInputChannelNamesBySelectedDevice(); + if (!validInputNames.empty()) + { + m_inputChannelName = validInputNames[0]; + } + return AZ::Edit::PropertyRefreshLevels::AttributesAndValues; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + AZStd::string InputMapping::InputChannelNameFilteredByDeviceType::GetNameLabelOverride() const + { + return m_inputChannelName.empty() ? "" : m_outputInputChannelName; + } + //////////////////////////////////////////////////////////////////////////////////////////////// InputMapping::InputMapping(const InputChannelId& inputChannelId, const InputContext& inputContext) : InputChannel(inputChannelId, inputContext) diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.h b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.h index 93ca96eded..c2f82fb7f8 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMapping.h @@ -12,6 +12,7 @@ #include #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework @@ -26,6 +27,111 @@ namespace AzFramework class InputMapping : public InputChannel { public: + //////////////////////////////////////////////////////////////////////////////////////////// + //! Convenience class that allows for selection of an input channel name filtered by device. + struct InputChannelNameFilteredByDeviceType + { + public: + //////////////////////////////////////////////////////////////////////////////////////// + // Allocator + AZ_CLASS_ALLOCATOR(InputChannelNameFilteredByDeviceType, AZ::SystemAllocator, 0); + + //////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(InputChannelNameFilteredByDeviceType, "{68CC4865-1C0E-4E2E-BDAE-AF42EA30DBE8}"); + + //////////////////////////////////////////////////////////////////////////////////////// + // Reflection + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Constructor + InputChannelNameFilteredByDeviceType(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + virtual ~InputChannelNameFilteredByDeviceType() = default; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the currently selected input device type. + //! \return Currently selected input device type. + inline const AZStd::string& GetInputDeviceType() const { return m_inputDeviceType; } + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the currently selected input channel name. + //! \return Currently selected input channel name. + inline const AZStd::string& GetInputChannelName() const { return m_inputChannelName; } + + protected: + //////////////////////////////////////////////////////////////////////////////////////////// + //! Called when an input device type is selected. + //! \return The AZ::Edit::PropertyRefreshLevels to apply to the property tree view. + virtual AZ::Crc32 OnInputDeviceTypeSelected(); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the name label override to display. + //! \return Name label override to display. + virtual AZStd::string GetNameLabelOverride() const; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the valid input device types for this input mapping. + //! \return Valid input device types for this input mapping. + virtual AZStd::vector GetValidInputDeviceTypes() const; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the valid input channel names for this input mapping given the selected device type. + //! \return Valid input channel names for this input mapping given the selected device type. + virtual AZStd::vector GetValidInputChannelNamesBySelectedDevice() const; + + private: + //////////////////////////////////////////////////////////////////////////////////////////// + // Variables + AZStd::string m_inputDeviceType; //!< The currently selected input device type. + AZStd::string m_inputChannelName; //!< The currently selected input channel name. + }; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Base class for input mapping configuration values that are exposed to the editor. + class ConfigBase + { + public: + //////////////////////////////////////////////////////////////////////////////////////// + // Allocator + AZ_CLASS_ALLOCATOR(ConfigBase, AZ::SystemAllocator, 0); + + //////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(ConfigBase, "{72EBBBCC-D57E-4085-AFD9-4910506010B6}"); + + //////////////////////////////////////////////////////////////////////////////////////// + // Reflection + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + virtual ~ConfigBase() = default; + + //////////////////////////////////////////////////////////////////////////////////////// + //! Create an input mapping and add it to the input context. + //! \param[in] inputContext Input context that the input mapping will be added to. + AZStd::shared_ptr CreateInputMappingAndAddToContext(InputContext& inputContext) const; + + //////////////////////////////////////////////////////////////////////////////////////// + //! Override to create the relevant input mapping. + //! \param[in] inputContext Input context that owns the input mapping. + virtual AZStd::shared_ptr CreateInputMapping(const InputContext& inputContext) const = 0; + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Get the name label override to display. + //! \return Name label override to display. + virtual AZStd::string GetNameLabelOverride() const; + + protected: + //////////////////////////////////////////////////////////////////////////////////////// + //! The unique input channel name (event) output by the input mapping. + AZStd::string m_outputInputChannelName; + }; + //////////////////////////////////////////////////////////////////////////////////////////// // Allocator AZ_CLASS_ALLOCATOR(InputMapping, AZ::SystemAllocator, 0); diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.cpp b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.cpp index 5d371888da..6837807f4e 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.cpp +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.cpp @@ -8,9 +8,72 @@ #include +#include +#include +#include + //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework { + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputMappingAnd::Config::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Source Input Channel Names", &Config::m_sourceInputChannelNames) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class("Input Mapping: And", + "Maps multiple different input sources to a single output using 'AND' logic.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &InputMappingAnd::Config::GetNameLabelOverride) + ->DataElement(AZ::Edit::UIHandlers::Default, &Config::m_sourceInputChannelNames, "Source Input Channel Names", + "The source input channel names that will be mapped to the output input channel name.") + ; + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + AZStd::shared_ptr InputMappingAnd::Config::CreateInputMapping(const InputContext& inputContext) const + { + if (m_outputInputChannelName.empty()) + { + AZ_Error("InputMappingAnd::Config", false, "Cannot create input mapping with empty name."); + return nullptr; + } + + if (InputChannelRequests::FindInputChannel(InputChannelId(m_outputInputChannelName.c_str()))) + { + AZ_Error("InputMappingAnd::Config", false, + "Cannot create input mapping '%s' with non-unique name.", m_outputInputChannelName.c_str()); + return nullptr; + } + + if (m_sourceInputChannelNames.empty()) + { + AZ_Error("InputMappingAnd::Config", false, + "Cannot create input mapping '%s' with no source inputs.", m_outputInputChannelName.c_str()); + return nullptr; + } + + const InputChannelId outputInputChannelId(m_outputInputChannelName.c_str()); + AZStd::shared_ptr inputMapping = AZStd::make_shared(outputInputChannelId, + inputContext); + for (const InputChannelNameFilteredByDeviceType& sourceInputChannelName : m_sourceInputChannelNames) + { + const InputChannelId sourceInputChannelId(sourceInputChannelName.GetInputChannelName().c_str()); + inputMapping->AddSourceInput(sourceInputChannelId); + } + return inputMapping; + } + //////////////////////////////////////////////////////////////////////////////////////////////// InputMappingAnd::InputMappingAnd(const InputChannelId& inputChannelId, const InputContext& inputContext) : InputMapping(inputChannelId, inputContext) diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.h b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.h index d7a767e3a5..61e54497db 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingAnd.h @@ -19,6 +19,38 @@ namespace AzFramework class InputMappingAnd : public InputMapping { public: + //////////////////////////////////////////////////////////////////////////////////////////// + //! The input mapping configuration values that are exposed to the editor. + class Config : public InputMapping::ConfigBase + { + public: + //////////////////////////////////////////////////////////////////////////////////////// + // Allocator + AZ_CLASS_ALLOCATOR(Config, AZ::SystemAllocator, 0); + + //////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(Config, "{54E972F3-0477-4E2E-93F5-4E06ED755DF6}", InputMapping::ConfigBase); + + //////////////////////////////////////////////////////////////////////////////////////// + // Reflection + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + ~Config() override = default; + + protected: + //////////////////////////////////////////////////////////////////////////////////////// + //! \ref AzFramework::InputMapping::Type::CreateInputMapping + AZStd::shared_ptr CreateInputMapping(const InputContext& inputContext) const override; + + private: + //////////////////////////////////////////////////////////////////////////////////////// + //! The source input channel names that will be mapped to the output input channel name. + AZStd::vector m_sourceInputChannelNames; + }; + //////////////////////////////////////////////////////////////////////////////////////////// // Allocator AZ_CLASS_ALLOCATOR(InputMappingAnd, AZ::SystemAllocator, 0); diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.cpp b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.cpp index 459d32dc68..bc47065c05 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.cpp +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.cpp @@ -8,9 +8,72 @@ #include +#include +#include +#include + //////////////////////////////////////////////////////////////////////////////////////////////////// namespace AzFramework { + //////////////////////////////////////////////////////////////////////////////////////////////// + void InputMappingOr::Config::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("Source Input Channel Names", &Config::m_sourceInputChannelNames) + ; + + if (AZ::EditContext* editContext = serializeContext->GetEditContext()) + { + editContext->Class("Input Mapping: Or", + "Maps multiple different input sources to a single output using 'OR' logic.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ->Attribute(AZ::Edit::Attributes::NameLabelOverride, &InputMappingOr::Config::GetNameLabelOverride) + ->DataElement(AZ::Edit::UIHandlers::Default, &Config::m_sourceInputChannelNames, "Source Input Channel Names", + "The source input channel names that will be mapped to the output input channel name.") + ; + } + } + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + AZStd::shared_ptr InputMappingOr::Config::CreateInputMapping(const InputContext& inputContext) const + { + if (m_outputInputChannelName.empty()) + { + AZ_Error("InputMappingOr::Config", false, "Cannot create input mapping with empty name."); + return nullptr; + } + + if (InputChannelRequests::FindInputChannel(InputChannelId(m_outputInputChannelName.c_str()))) + { + AZ_Error("InputMappingOr::Config", false, + "Cannot create input mapping '%s' with non-unique name.", m_outputInputChannelName.c_str()); + return nullptr; + } + + if (m_sourceInputChannelNames.empty()) + { + AZ_Error("InputMappingOr::Config", false, + "Cannot create input mapping '%s' with no source inputs.", m_outputInputChannelName.c_str()); + return nullptr; + } + + const InputChannelId outputInputChannelId(m_outputInputChannelName.c_str()); + AZStd::shared_ptr inputMapping = AZStd::make_shared(outputInputChannelId, + inputContext); + for (const InputChannelNameFilteredByDeviceType& sourceInputChannelName : m_sourceInputChannelNames) + { + const InputChannelId sourceInputChannelId(sourceInputChannelName.GetInputChannelName().c_str()); + inputMapping->AddSourceInput(sourceInputChannelId); + } + return inputMapping; + } + //////////////////////////////////////////////////////////////////////////////////////////////// InputMappingOr::InputMappingOr(const InputChannelId& inputChannelId, const InputContext& inputContext) : InputMapping(inputChannelId, inputContext) diff --git a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.h b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.h index b8359f828e..a0440d1855 100644 --- a/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.h +++ b/Code/Framework/AzFramework/AzFramework/Input/Mappings/InputMappingOr.h @@ -19,6 +19,38 @@ namespace AzFramework class InputMappingOr : public InputMapping { public: + //////////////////////////////////////////////////////////////////////////////////////////// + //! The input mapping configuration values that are exposed to the editor. + class Config : public InputMapping::ConfigBase + { + public: + //////////////////////////////////////////////////////////////////////////////////////// + // Allocator + AZ_CLASS_ALLOCATOR(Config, AZ::SystemAllocator, 0); + + //////////////////////////////////////////////////////////////////////////////////////// + // Type Info + AZ_RTTI(Config, "{428AFDD4-D353-494A-BBAC-37E00F82CFFD}", InputMapping::ConfigBase); + + //////////////////////////////////////////////////////////////////////////////////////// + // Reflection + static void Reflect(AZ::ReflectContext* context); + + //////////////////////////////////////////////////////////////////////////////////////////// + //! Destructor + ~Config() override = default; + + protected: + //////////////////////////////////////////////////////////////////////////////////////// + //! \ref AzFramework::InputMapping::Type::CreateInputMapping + AZStd::shared_ptr CreateInputMapping(const InputContext& inputContext) const override; + + private: + //////////////////////////////////////////////////////////////////////////////////////// + //! The source input channel names that will be mapped to the output input channel name. + AZStd::vector m_sourceInputChannelNames; + }; + //////////////////////////////////////////////////////////////////////////////////////////// // Allocator AZ_CLASS_ALLOCATOR(InputMappingOr, AZ::SystemAllocator, 0); diff --git a/Code/Framework/AzFramework/AzFramework/Logging/LoggingComponent.h b/Code/Framework/AzFramework/AzFramework/Logging/LoggingComponent.h index 98eb6df95a..73f2ff2c75 100644 --- a/Code/Framework/AzFramework/AzFramework/Logging/LoggingComponent.h +++ b/Code/Framework/AzFramework/AzFramework/Logging/LoggingComponent.h @@ -31,9 +31,9 @@ namespace AzFramework ////////////////////////////////////////////////////////////////////////// // AZ::Component - virtual void Init(); - virtual void Activate(); - virtual void Deactivate(); + void Init() override; + void Activate() override; + void Deactivate() override; ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp index 617eb3a0b9..75fca39574 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.cpp @@ -36,6 +36,16 @@ namespace AzFramework return m_end; } + const AZ::Entity* const* SpawnableEntityContainerView::begin() const + { + return m_begin; + } + + const AZ::Entity* const* SpawnableEntityContainerView::end() const + { + return m_end; + } + const AZ::Entity* const* SpawnableEntityContainerView::cbegin() { return m_begin; @@ -46,11 +56,28 @@ namespace AzFramework return m_end; } - size_t SpawnableEntityContainerView::size() + AZ::Entity* SpawnableEntityContainerView::operator[](size_t n) + { + AZ_Assert(n < size(), "Index %zu is out of bounds (size: %llu) for Spawnable Entity Container View", n, size()); + return *(m_begin + n); + } + + const AZ::Entity* SpawnableEntityContainerView::operator[](size_t n) const + { + AZ_Assert(n < size(), "Index %zu is out of bounds (size: %llu) for Spawnable Entity Container View", n, size()); + return *(m_begin + n); + } + + size_t SpawnableEntityContainerView::size() const { return AZStd::distance(m_begin, m_end); } + bool SpawnableEntityContainerView::empty() const + { + return m_begin == m_end; + } + // // SpawnableConstEntityContainerView @@ -78,6 +105,16 @@ namespace AzFramework return m_end; } + const AZ::Entity* const* SpawnableConstEntityContainerView::begin() const + { + return m_begin; + } + + const AZ::Entity* const* SpawnableConstEntityContainerView::end() const + { + return m_end; + } + const AZ::Entity* const* SpawnableConstEntityContainerView::cbegin() { return m_begin; @@ -88,11 +125,28 @@ namespace AzFramework return m_end; } - size_t SpawnableConstEntityContainerView::size() + const AZ::Entity* SpawnableConstEntityContainerView::operator[](size_t n) + { + AZ_Assert(n < size(), "Index %zu is out of bounds (size: %llu) for Spawnable Const Entity Container View", n, size()); + return *(m_begin + n); + } + + const AZ::Entity* SpawnableConstEntityContainerView::operator[](size_t n) const + { + AZ_Assert(n < size(), "Index %zu is out of bounds (size: %llu) for Spawnable Entity Container View", n, size()); + return *(m_begin + n); + } + + size_t SpawnableConstEntityContainerView::size() const { return AZStd::distance(m_begin, m_end); } + bool SpawnableConstEntityContainerView::empty() const + { + return m_begin == m_end; + } + // // SpawnableIndexEntityPair diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index 4b09dcbc75..6901fc7116 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -36,11 +36,18 @@ namespace AzFramework SpawnableEntityContainerView(AZ::Entity** begin, size_t length); SpawnableEntityContainerView(AZ::Entity** begin, AZ::Entity** end); - AZ::Entity** begin(); - AZ::Entity** end(); - const AZ::Entity* const* cbegin(); - const AZ::Entity* const* cend(); - size_t size(); + [[nodiscard]] AZ::Entity** begin(); + [[nodiscard]] AZ::Entity** end(); + [[nodiscard]] const AZ::Entity* const* begin() const; + [[nodiscard]] const AZ::Entity* const* end() const; + [[nodiscard]] const AZ::Entity* const* cbegin(); + [[nodiscard]] const AZ::Entity* const* cend(); + + [[nodiscard]] AZ::Entity* operator[](size_t n); + [[nodiscard]] const AZ::Entity* operator[](size_t n) const; + + [[nodiscard]] size_t size() const; + [[nodiscard]] bool empty() const; private: AZ::Entity** m_begin; @@ -53,11 +60,18 @@ namespace AzFramework SpawnableConstEntityContainerView(AZ::Entity** begin, size_t length); SpawnableConstEntityContainerView(AZ::Entity** begin, AZ::Entity** end); - const AZ::Entity* const* begin(); - const AZ::Entity* const* end(); - const AZ::Entity* const* cbegin(); - const AZ::Entity* const* cend(); - size_t size(); + [[nodiscard]] const AZ::Entity* const* begin(); + [[nodiscard]] const AZ::Entity* const* end(); + [[nodiscard]] const AZ::Entity* const* begin() const; + [[nodiscard]] const AZ::Entity* const* end() const; + [[nodiscard]] const AZ::Entity* const* cbegin(); + [[nodiscard]] const AZ::Entity* const* cend(); + + [[nodiscard]] const AZ::Entity* operator[](size_t n); + [[nodiscard]] const AZ::Entity* operator[](size_t n) const; + + [[nodiscard]] size_t size() const; + [[nodiscard]] bool empty() const; private: AZ::Entity** m_begin; diff --git a/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementAPI.h b/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementAPI.h index 6582e145cb..bbfb4c88c1 100644 --- a/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementAPI.h +++ b/Code/Framework/AzFramework/AzFramework/TargetManagement/TargetManagementAPI.h @@ -195,7 +195,7 @@ namespace AzFramework TmMsgCallback(const MsgCB& cb = NULL) : m_cb(cb) {} - virtual void OnReceivedMsg(TmMsgPtr msg) + void OnReceivedMsg(TmMsgPtr msg) override { if (m_cb) { diff --git a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.cpp b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.cpp index 947d3821ab..1fb29cfa30 100644 --- a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.cpp +++ b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.cpp @@ -51,7 +51,8 @@ namespace AzFramework ->Event("GetNormal", &AzFramework::Terrain::TerrainDataRequestBus::Events::GetNormal) ->Event("GetNormalFromFloats", &AzFramework::Terrain::TerrainDataRequestBus::Events::GetNormalFromFloats) ->Event("GetTerrainAabb", &AzFramework::Terrain::TerrainDataRequestBus::Events::GetTerrainAabb) - ->Event("GetTerrainGridResolution", &AzFramework::Terrain::TerrainDataRequestBus::Events::GetTerrainGridResolution) + ->Event("GetTerrainHeightQueryResolution", + &AzFramework::Terrain::TerrainDataRequestBus::Events::GetTerrainHeightQueryResolution) ; } diff --git a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h index 08e238434e..92eb28a110 100644 --- a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h +++ b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h @@ -59,8 +59,11 @@ namespace AzFramework static AZ::Vector3 GetDefaultTerrainNormal() { return AZ::Vector3::CreateAxisZ(); } // System-level queries to understand world size and resolution - virtual AZ::Vector2 GetTerrainGridResolution() const = 0; + virtual AZ::Vector2 GetTerrainHeightQueryResolution() const = 0; + virtual void SetTerrainHeightQueryResolution(AZ::Vector2 queryResolution) = 0; + virtual AZ::Aabb GetTerrainAabb() const = 0; + virtual void SetTerrainAabb(const AZ::Aabb& worldBounds) = 0; //! Returns terrains height in meters at location x,y. //! @terrainExistsPtr: Can be nullptr. If != nullptr then, if there's no terrain at location x,y or location x,y is inside a terrain HOLE then *terrainExistsPtr will become false, diff --git a/Code/Framework/AzFramework/AzFramework/UnitTest/TestDebugDisplayRequests.h b/Code/Framework/AzFramework/AzFramework/UnitTest/TestDebugDisplayRequests.h index d4c6992057..72b15c1a69 100644 --- a/Code/Framework/AzFramework/AzFramework/UnitTest/TestDebugDisplayRequests.h +++ b/Code/Framework/AzFramework/AzFramework/UnitTest/TestDebugDisplayRequests.h @@ -19,6 +19,8 @@ namespace UnitTest { public: TestDebugDisplayRequests(); + ~TestDebugDisplayRequests() override = default; + const AZStd::vector& GetPoints() const; void ClearPoints(); //! Returns the AABB of the points generated from received draw calls. @@ -27,7 +29,9 @@ namespace UnitTest // DebugDisplayRequests ... void DrawWireBox(const AZ::Vector3& min, const AZ::Vector3& max) override; void DrawSolidBox(const AZ::Vector3& min, const AZ::Vector3& max) override; + using AzFramework::DebugDisplayRequests::DrawWireQuad; void DrawWireQuad(float width, float height) override; + using AzFramework::DebugDisplayRequests::DrawQuad; void DrawQuad(float width, float height) override; void DrawTriangles(const AZStd::vector& vertices, const AZ::Color& color) override; void DrawTrianglesIndexed(const AZStd::vector& vertices, const AZStd::vector& indices, const AZ::Color& color) override; diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp index b909689c22..1b3645630e 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.cpp @@ -9,8 +9,19 @@ #include #include +#include + namespace AzFramework { + ClickDetector::ClickDetector() + { + m_timeNowFn = [] + { + const auto now = AZStd::chrono::high_resolution_clock::now(); + return AZStd::chrono::time_point_cast(now).time_since_epoch(); + }; + } + ClickDetector::ClickOutcome ClickDetector::DetectClick(const ClickEvent clickEvent, const ScreenVector& cursorDelta) { const auto previousDetectionState = m_detectionState; @@ -26,11 +37,13 @@ namespace AzFramework if (clickEvent == ClickEvent::Down) { - const auto now = std::chrono::steady_clock::now(); + const auto now = m_timeNowFn(); if (m_tryBeginTime) { - const std::chrono::duration diff = now - m_tryBeginTime.value(); - if (diff.count() < m_doubleClickInterval) + using FloatingPointSeconds = AZStd::chrono::duration; + + const auto diff = now - m_tryBeginTime.value(); + if (FloatingPointSeconds(diff).count() < m_doubleClickInterval) { return ClickOutcome::Nil; } @@ -43,7 +56,8 @@ namespace AzFramework } else if (clickEvent == ClickEvent::Up) { - const auto clickOutcome = [detectionState = m_detectionState] { + const auto clickOutcome = [detectionState = m_detectionState] + { if (detectionState == DetectionState::WaitingForMove) { return ClickOutcome::Click; @@ -66,4 +80,9 @@ namespace AzFramework return ClickOutcome::Nil; } + + void ClickDetector::OverrideTimeNowFn(AZStd::function timeNowFn) + { + m_timeNowFn = AZStd::move(timeNowFn); + } } // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h index f95924550a..70bdeb4619 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/ClickDetector.h @@ -8,6 +8,7 @@ #pragma once +#include #include #include @@ -21,10 +22,9 @@ namespace AzFramework //! (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: + ClickDetector(); + //! Internal representation of click event (map from external event for this when //! calling DetectClick). enum class ClickEvent @@ -51,6 +51,10 @@ namespace AzFramework void SetDoubleClickInterval(float doubleClickInterval); //! Override the dead zone before a 'move' outcome will be triggered. void SetDeadZone(float deadZone); + //! Override how the current time is retrieved. + //! This is helpful to override when it comes to simulating different passages of + //! time to avoid double click issues in tests for example. + void OverrideTimeNowFn(AZStd::function timeNowFn); private: //! Internal state of ClickDetector based on incoming events. @@ -65,7 +69,9 @@ namespace AzFramework 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