Merging from development
Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,131 @@
|
||||
{
|
||||
"ContainerEntity": {
|
||||
"Id": "ContainerEntity",
|
||||
"Name": "PinkFlower",
|
||||
"Components": {
|
||||
"Component_[10444337162843472597]": {
|
||||
"$type": "EditorLockComponent",
|
||||
"Id": 10444337162843472597
|
||||
},
|
||||
"Component_[14431042590323756177]": {
|
||||
"$type": "EditorEntitySortComponent",
|
||||
"Id": 14431042590323756177,
|
||||
"ChildEntityOrderEntryArray": [
|
||||
{
|
||||
"EntityId": "Entity_[491002114939]"
|
||||
}
|
||||
]
|
||||
},
|
||||
"Component_[14577735453176806353]": {
|
||||
"$type": "EditorDisabledCompositionComponent",
|
||||
"Id": 14577735453176806353
|
||||
},
|
||||
"Component_[15674021346798629563]": {
|
||||
"$type": "EditorInspectorComponent",
|
||||
"Id": 15674021346798629563
|
||||
},
|
||||
"Component_[16784074985702513600]": {
|
||||
"$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent",
|
||||
"Id": 16784074985702513600,
|
||||
"Parent Entity": ""
|
||||
},
|
||||
"Component_[3351614541100572773]": {
|
||||
"$type": "EditorOnlyEntityComponent",
|
||||
"Id": 3351614541100572773
|
||||
},
|
||||
"Component_[3600658560328167663]": {
|
||||
"$type": "EditorPrefabComponent",
|
||||
"Id": 3600658560328167663
|
||||
},
|
||||
"Component_[6155673728651558934]": {
|
||||
"$type": "EditorEntityIconComponent",
|
||||
"Id": 6155673728651558934
|
||||
},
|
||||
"Component_[8458684662170321289]": {
|
||||
"$type": "EditorVisibilityComponent",
|
||||
"Id": 8458684662170321289
|
||||
},
|
||||
"Component_[8705192117416252351]": {
|
||||
"$type": "SelectionComponent",
|
||||
"Id": 8705192117416252351
|
||||
},
|
||||
"Component_[8801280051488695852]": {
|
||||
"$type": "EditorPendingCompositionComponent",
|
||||
"Id": 8801280051488695852
|
||||
}
|
||||
}
|
||||
},
|
||||
"Entities": {
|
||||
"Entity_[491002114939]": {
|
||||
"Id": "Entity_[491002114939]",
|
||||
"Name": "PinkFlower",
|
||||
"Components": {
|
||||
"Component_[11083205340162142682]": {
|
||||
"$type": "EditorLockComponent",
|
||||
"Id": 11083205340162142682
|
||||
},
|
||||
"Component_[11327363779873517]": {
|
||||
"$type": "EditorOnlyEntityComponent",
|
||||
"Id": 11327363779873517
|
||||
},
|
||||
"Component_[12717389211269537921]": {
|
||||
"$type": "EditorEntitySortComponent",
|
||||
"Id": 12717389211269537921
|
||||
},
|
||||
"Component_[12826285685970138542]": {
|
||||
"$type": "AZ::Render::EditorMeshComponent",
|
||||
"Id": 12826285685970138542,
|
||||
"Controller": {
|
||||
"Configuration": {
|
||||
"ModelAsset": {
|
||||
"assetId": {
|
||||
"guid": "{549F4C4D-A7D9-5F2A-A6BD-F24C8BC43BBF}",
|
||||
"subId": 280086017
|
||||
},
|
||||
"assetHint": "assets/objects/foliage/grass_flower_pink.azmodel"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"Component_[14101419970865342875]": {
|
||||
"$type": "EditorPendingCompositionComponent",
|
||||
"Id": 14101419970865342875
|
||||
},
|
||||
"Component_[14770464075286403207]": {
|
||||
"$type": "EditorVisibilityComponent",
|
||||
"Id": 14770464075286403207
|
||||
},
|
||||
"Component_[15205142653091190082]": {
|
||||
"$type": "{27F1E1A1-8D9D-4C3B-BD3A-AFB9762449C0} TransformComponent",
|
||||
"Id": 15205142653091190082,
|
||||
"Parent Entity": "ContainerEntity"
|
||||
},
|
||||
"Component_[15510898811147803772]": {
|
||||
"$type": "EditorInspectorComponent",
|
||||
"Id": 15510898811147803772,
|
||||
"ComponentOrderEntryArray": [
|
||||
{
|
||||
"ComponentId": 15205142653091190082
|
||||
},
|
||||
{
|
||||
"ComponentId": 12826285685970138542,
|
||||
"SortIndex": 1
|
||||
}
|
||||
]
|
||||
},
|
||||
"Component_[15988401742428977134]": {
|
||||
"$type": "EditorDisabledCompositionComponent",
|
||||
"Id": 15988401742428977134
|
||||
},
|
||||
"Component_[4300550837037679336]": {
|
||||
"$type": "EditorEntityIconComponent",
|
||||
"Id": 4300550837037679336
|
||||
},
|
||||
"Component_[996914988793716659]": {
|
||||
"$type": "SelectionComponent",
|
||||
"Id": 996914988793716659
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
version https://git-lfs.github.com/spec/v1
|
||||
oid sha256:27f87510ae07771dbad3e430e31502b1d1d13dee868f143b7f1de2a7febc8eb9
|
||||
size 7046400
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"values": [
|
||||
{
|
||||
"$type": "ScriptProcessorRule",
|
||||
"scriptFilename": "Assets/TestAnim/scene_export_actor.py"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
#
|
||||
# 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 traceback, sys, uuid, os, json
|
||||
|
||||
#
|
||||
# Example for exporting ActorGroup scene rules
|
||||
#
|
||||
|
||||
def log_exception_traceback():
|
||||
exc_type, exc_value, exc_tb = sys.exc_info()
|
||||
data = traceback.format_exception(exc_type, exc_value, exc_tb)
|
||||
print(str(data))
|
||||
|
||||
def get_node_names(sceneGraph, nodeTypeName, testEndPoint = False, validList = None):
|
||||
import azlmbr.scene.graph
|
||||
import scene_api.scene_data
|
||||
|
||||
node = sceneGraph.get_root()
|
||||
nodeList = []
|
||||
children = []
|
||||
paths = []
|
||||
|
||||
while node.IsValid():
|
||||
# store children to process after siblings
|
||||
if sceneGraph.has_node_child(node):
|
||||
children.append(sceneGraph.get_node_child(node))
|
||||
|
||||
nodeName = scene_api.scene_data.SceneGraphName(sceneGraph.get_node_name(node))
|
||||
paths.append(nodeName.get_path())
|
||||
|
||||
include = True
|
||||
|
||||
if (validList is not None):
|
||||
include = False # if a valid list filter provided, assume to not include node name
|
||||
name_parts = nodeName.get_path().split('.')
|
||||
for valid in validList:
|
||||
if (valid in name_parts[-1]):
|
||||
include = True
|
||||
break
|
||||
|
||||
# store any node that has provides specifc data content
|
||||
nodeContent = sceneGraph.get_node_content(node)
|
||||
if include and nodeContent.CastWithTypeName(nodeTypeName):
|
||||
if testEndPoint is not None:
|
||||
include = sceneGraph.is_node_end_point(node) is testEndPoint
|
||||
if include:
|
||||
if (len(nodeName.get_path())):
|
||||
nodeList.append(scene_api.scene_data.SceneGraphName(sceneGraph.get_node_name(node)))
|
||||
|
||||
# advance to next node
|
||||
if sceneGraph.has_node_sibling(node):
|
||||
node = sceneGraph.get_node_sibling(node)
|
||||
elif children:
|
||||
node = children.pop()
|
||||
else:
|
||||
node = azlmbr.scene.graph.NodeIndex()
|
||||
|
||||
return nodeList, paths
|
||||
|
||||
def generate_mesh_group(scene, sceneManifest, meshDataList, paths):
|
||||
# Compute the name of the scene file
|
||||
clean_filename = scene.sourceFilename.replace('.', '_')
|
||||
mesh_group_name = os.path.basename(clean_filename)
|
||||
|
||||
# make the mesh group
|
||||
mesh_group = sceneManifest.add_mesh_group(mesh_group_name)
|
||||
mesh_group['id'] = '{' + str(uuid.uuid5(uuid.NAMESPACE_DNS, clean_filename)) + '}'
|
||||
|
||||
# add all nodes to this mesh group
|
||||
for activeMeshIndex in range(len(meshDataList)):
|
||||
mesh_name = meshDataList[activeMeshIndex]
|
||||
mesh_path = mesh_name.get_path()
|
||||
sceneManifest.mesh_group_select_node(mesh_group, mesh_path)
|
||||
|
||||
def create_shape_configuration(nodeName):
|
||||
import scene_api.physics_data
|
||||
|
||||
if(nodeName in ['_foot_','_wrist_']):
|
||||
shapeConfiguration = scene_api.physics_data.BoxShapeConfiguration()
|
||||
shapeConfiguration.scale = [1.1, 1.1, 1.1]
|
||||
shapeConfiguration.dimensions = [2.1, 3.1, 4.1]
|
||||
return shapeConfiguration
|
||||
else:
|
||||
shapeConfiguration = scene_api.physics_data.CapsuleShapeConfiguration()
|
||||
shapeConfiguration.scale = [1.0, 1.0, 1.0]
|
||||
shapeConfiguration.height = 1.0
|
||||
shapeConfiguration.radius = 1.0
|
||||
return shapeConfiguration
|
||||
|
||||
def create_collider_configuration(nodeName):
|
||||
import scene_api.physics_data
|
||||
|
||||
colliderConfiguration = scene_api.physics_data.ColliderConfiguration()
|
||||
colliderConfiguration.Position = [0.1, 0.1, 0.2]
|
||||
colliderConfiguration.Rotation = [45.0, 35.0, 25.0]
|
||||
return colliderConfiguration
|
||||
|
||||
def generate_physics_nodes(actorPhysicsSetupRule, nodeNameList):
|
||||
import scene_api.physics_data
|
||||
|
||||
hitDetectionConfig = scene_api.physics_data.CharacterColliderConfiguration()
|
||||
simulatedObjectColliderConfig = scene_api.physics_data.CharacterColliderConfiguration()
|
||||
clothConfig = scene_api.physics_data.CharacterColliderConfiguration()
|
||||
ragdollConfig = scene_api.physics_data.RagdollConfiguration()
|
||||
|
||||
for nodeName in nodeNameList:
|
||||
shapeConfiguration = create_shape_configuration(nodeName)
|
||||
colliderConfiguration = create_collider_configuration(nodeName)
|
||||
hitDetectionConfig.add_character_collider_node_configuration_node(nodeName, colliderConfiguration, shapeConfiguration)
|
||||
simulatedObjectColliderConfig.add_character_collider_node_configuration_node(nodeName, colliderConfiguration, shapeConfiguration)
|
||||
clothConfig.add_character_collider_node_configuration_node(nodeName, colliderConfiguration, shapeConfiguration)
|
||||
#
|
||||
ragdollNode = scene_api.physics_data.RagdollNodeConfiguration()
|
||||
ragdollNode.JointConfig.Name = nodeName
|
||||
ragdollConfig.add_ragdoll_node_configuration(ragdollNode)
|
||||
ragdollConfig.colliders.add_character_collider_node_configuration_node(nodeName, colliderConfiguration, shapeConfiguration)
|
||||
|
||||
actorPhysicsSetupRule.set_simulated_object_collider_config(simulatedObjectColliderConfig)
|
||||
actorPhysicsSetupRule.set_hit_detection_config(hitDetectionConfig)
|
||||
actorPhysicsSetupRule.set_cloth_config(clothConfig)
|
||||
actorPhysicsSetupRule.set_ragdoll_config(ragdollConfig)
|
||||
|
||||
def generate_actor_group(scene, sceneManifest, meshDataList, paths):
|
||||
import scene_api.scene_data
|
||||
import scene_api.physics_data
|
||||
import scene_api.actor_group
|
||||
|
||||
# fetch bone data
|
||||
validNames = ['_neck_','_pelvis_','_leg_','_knee_','_spine_','_arm_','_clavicle_','_head_','_elbow_','_wrist_']
|
||||
graph = scene_api.scene_data.SceneGraph(scene.graph)
|
||||
nodeList, allNodePaths = get_node_names(graph, 'BoneData', validList = validNames)
|
||||
|
||||
nodeNameList = []
|
||||
for activeMeshIndex, nodeName in enumerate(nodeList):
|
||||
nodeNameList.append(nodeName.get_name())
|
||||
|
||||
# add comment
|
||||
commentRule = scene_api.actor_group.CommentRule()
|
||||
commentRule.text = str(nodeNameList)
|
||||
|
||||
# ActorPhysicsSetupRule
|
||||
actorPhysicsSetupRule = scene_api.actor_group.ActorPhysicsSetupRule()
|
||||
generate_physics_nodes(actorPhysicsSetupRule, nodeNameList)
|
||||
|
||||
# add scale of the Actor rule
|
||||
actorScaleRule = scene_api.actor_group.ActorScaleRule()
|
||||
actorScaleRule.scaleFactor = 2.0
|
||||
|
||||
# add coordinate system rule
|
||||
coordinateSystemRule = scene_api.actor_group.CoordinateSystemRule()
|
||||
coordinateSystemRule.useAdvancedData = False
|
||||
|
||||
# add morph target rule
|
||||
morphTargetRule = scene_api.actor_group.MorphTargetRule()
|
||||
morphTargetRule.targets.select_targets([nodeNameList[0]], nodeNameList)
|
||||
|
||||
# add skeleton optimization rule
|
||||
skeletonOptimizationRule = scene_api.actor_group.SkeletonOptimizationRule()
|
||||
skeletonOptimizationRule.autoSkeletonLOD = True
|
||||
skeletonOptimizationRule.criticalBonesList.select_targets([nodeNameList[0:2]], nodeNameList)
|
||||
|
||||
# add LOD rule
|
||||
lodRule = scene_api.actor_group.LodRule()
|
||||
lodRule0 = lodRule.add_lod_level(0)
|
||||
lodRule0.select_targets([nodeNameList[1:4]], nodeNameList)
|
||||
|
||||
actorGroup = scene_api.actor_group.ActorGroup()
|
||||
actorGroup.name = os.path.basename(scene.sourceFilename)
|
||||
actorGroup.add_rule(actorScaleRule)
|
||||
actorGroup.add_rule(coordinateSystemRule)
|
||||
actorGroup.add_rule(skeletonOptimizationRule)
|
||||
actorGroup.add_rule(morphTargetRule)
|
||||
actorGroup.add_rule(lodRule)
|
||||
actorGroup.add_rule(actorPhysicsSetupRule)
|
||||
actorGroup.add_rule(commentRule)
|
||||
sceneManifest.manifest['values'].append(actorGroup.to_dict())
|
||||
|
||||
def update_manifest(scene):
|
||||
import json, uuid, os
|
||||
import azlmbr.scene.graph
|
||||
import scene_api.scene_data
|
||||
|
||||
graph = scene_api.scene_data.SceneGraph(scene.graph)
|
||||
mesh_name_list, all_node_paths = get_node_names(graph, 'MeshData')
|
||||
scene_manifest = scene_api.scene_data.SceneManifest()
|
||||
generate_actor_group(scene, scene_manifest, mesh_name_list, all_node_paths)
|
||||
generate_mesh_group(scene, scene_manifest, mesh_name_list, all_node_paths)
|
||||
|
||||
# Convert the manifest to a JSON string and return it
|
||||
return scene_manifest.export()
|
||||
|
||||
sceneJobHandler = None
|
||||
|
||||
def on_update_manifest(args):
|
||||
try:
|
||||
scene = args[0]
|
||||
return update_manifest(scene)
|
||||
except RuntimeError as err:
|
||||
print (f'ERROR - {err}')
|
||||
log_exception_traceback()
|
||||
except:
|
||||
log_exception_traceback()
|
||||
|
||||
global sceneJobHandler
|
||||
sceneJobHandler.disconnect()
|
||||
sceneJobHandler = None
|
||||
|
||||
# try to create SceneAPI handler for processing
|
||||
try:
|
||||
import azlmbr.scene
|
||||
|
||||
sceneJobHandler = azlmbr.scene.ScriptBuildingNotificationBusHandler()
|
||||
sceneJobHandler.connect()
|
||||
sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest)
|
||||
except:
|
||||
sceneJobHandler = None
|
||||
@@ -47,18 +47,4 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED)
|
||||
COMPONENT
|
||||
Atom
|
||||
)
|
||||
ly_add_pytest(
|
||||
NAME AutomatedTesting::Atom_TestSuite_Main_GPU_Optimized
|
||||
TEST_SUITE main
|
||||
TEST_REQUIRES gpu
|
||||
TEST_SERIAL
|
||||
TIMEOUT 1200
|
||||
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main_GPU_Optimized.py
|
||||
RUNTIME_DEPENDENCIES
|
||||
AssetProcessor
|
||||
AutomatedTesting.Assets
|
||||
Editor
|
||||
COMPONENT
|
||||
Atom
|
||||
)
|
||||
endif()
|
||||
|
||||
@@ -4,129 +4,82 @@ For complete copyright and license terms please see the LICENSE at the root of t
|
||||
|
||||
SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import logging
|
||||
import os
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
import editor_python_test_tools.hydra_test_utils as hydra
|
||||
import ly_test_tools.environment.file_system as file_system
|
||||
from ly_test_tools.benchmark.data_aggregator import BenchmarkDataAggregator
|
||||
from ly_test_tools.o3de.editor_test import EditorSharedTest, EditorTestSuite
|
||||
from Atom.atom_utils.atom_component_helper import compare_screenshot_to_golden_image, golden_images_directory
|
||||
|
||||
import editor_python_test_tools.hydra_test_utils as hydra
|
||||
from .atom_utils.atom_component_helper import compare_screenshot_similarity, ImageComparisonTestFailure
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
DEFAULT_SUBFOLDER_PATH = 'user/PythonTests/Automated/Screenshots'
|
||||
TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "tests")
|
||||
|
||||
|
||||
def golden_images_directory():
|
||||
"""
|
||||
Uses this file location to return the valid location for golden image files.
|
||||
:return: The path to the golden_images directory, but raises an IOError if the golden_images directory is missing.
|
||||
"""
|
||||
current_file_directory = os.path.join(os.path.dirname(__file__))
|
||||
golden_images_dir = os.path.join(current_file_directory, 'golden_images')
|
||||
|
||||
if not os.path.exists(golden_images_dir):
|
||||
raise IOError(
|
||||
f'golden_images" directory was not found at path "{golden_images_dir}"'
|
||||
f'Please add a "golden_images" directory inside: "{current_file_directory}"'
|
||||
)
|
||||
|
||||
return golden_images_dir
|
||||
|
||||
|
||||
def create_screenshots_archive(screenshot_path):
|
||||
"""
|
||||
Creates a new zip file archive at archive_path containing all files listed within archive_path.
|
||||
:param screenshot_path: location containing the files to archive, the zip archive file will also be saved here.
|
||||
:return: None, but creates a new zip file archive inside path containing all of the files inside archive_path.
|
||||
"""
|
||||
files_to_archive = []
|
||||
|
||||
# Search for .png and .ppm files to add to the zip archive file.
|
||||
for (folder_name, sub_folders, file_names) in os.walk(screenshot_path):
|
||||
for file_name in file_names:
|
||||
if file_name.endswith(".png") or file_name.endswith(".ppm"):
|
||||
file_path = os.path.join(folder_name, file_name)
|
||||
files_to_archive.append(file_path)
|
||||
|
||||
# Setup variables for naming the zip archive file.
|
||||
timestamp = datetime.datetime.now().timestamp()
|
||||
formatted_timestamp = datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d_%H-%M-%S")
|
||||
screenshots_file = os.path.join(screenshot_path, f'zip_archive_{formatted_timestamp}.zip')
|
||||
|
||||
# Write all of the valid .png and .ppm files to the archive file.
|
||||
with zipfile.ZipFile(screenshots_file, 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=True) as zip_archive:
|
||||
for file_path in files_to_archive:
|
||||
file_name = os.path.basename(file_path)
|
||||
zip_archive.write(file_path, file_name)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("project", ["AutomatedTesting"])
|
||||
@pytest.mark.parametrize("launcher_platform", ["windows_editor"])
|
||||
@pytest.mark.parametrize("level", ["Base"])
|
||||
class TestAllComponentsIndepthTests(object):
|
||||
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
|
||||
class TestAutomation(EditorTestSuite):
|
||||
# Remove -autotest_mode from global_extra_cmdline_args since we need rendering for these tests.
|
||||
global_extra_cmdline_args = ["-BatchMode"] # Default is ["-BatchMode", "-autotest_mode"]
|
||||
|
||||
enable_prefab_system = False
|
||||
|
||||
@pytest.mark.parametrize("screenshot_name", ["AtomBasicLevelSetup.ppm"])
|
||||
@pytest.mark.test_case_id("C34603773")
|
||||
def test_BasicLevelSetup_SetsUpLevel(
|
||||
self, request, editor, workspace, project, launcher_platform, level, screenshot_name):
|
||||
"""
|
||||
Please review the hydra script run by this test for more specific test info.
|
||||
Tests that a basic rendering level setup can be created (lighting, meshes, materials, etc.).
|
||||
"""
|
||||
class AtomGPU_BasicLevelSetup_SetsUpLevel(EditorSharedTest):
|
||||
use_null_renderer = False # Default is True
|
||||
screenshot_name = "AtomBasicLevelSetup.ppm"
|
||||
test_screenshots = [] # Gets set by setup()
|
||||
screenshot_directory = "" # Gets set by setup()
|
||||
|
||||
# Clear existing test screenshots before starting test.
|
||||
screenshot_directory = os.path.join(workspace.paths.project(), DEFAULT_SUBFOLDER_PATH)
|
||||
test_screenshots = [os.path.join(screenshot_directory, screenshot_name)]
|
||||
file_system.delete(test_screenshots, True, True)
|
||||
def setup(self, workspace):
|
||||
screenshot_directory = os.path.join(workspace.paths.project(), DEFAULT_SUBFOLDER_PATH)
|
||||
test_screenshots = [os.path.join(screenshot_directory, self.screenshot_name)]
|
||||
file_system.delete(test_screenshots, True, True)
|
||||
|
||||
golden_images = [os.path.join(golden_images_directory(), screenshot_name)]
|
||||
|
||||
level_creation_expected_lines = [
|
||||
"Viewport is set to the expected size: True",
|
||||
"Exited game mode"
|
||||
]
|
||||
unexpected_lines = ["Traceback (most recent call last):"]
|
||||
from Atom.tests import hydra_AtomGPU_BasicLevelSetup as test_module
|
||||
|
||||
hydra.launch_and_validate_results(
|
||||
request,
|
||||
TEST_DIRECTORY,
|
||||
editor,
|
||||
"hydra_GPUTest_BasicLevelSetup.py",
|
||||
timeout=180,
|
||||
expected_lines=level_creation_expected_lines,
|
||||
unexpected_lines=unexpected_lines,
|
||||
halt_on_unexpected=True,
|
||||
cfg_args=[level],
|
||||
null_renderer=False,
|
||||
enable_prefab_system=False,
|
||||
)
|
||||
|
||||
similarity_threshold = 0.99
|
||||
for test_screenshot, golden_image in zip(test_screenshots, golden_images):
|
||||
screenshot_comparison_result = compare_screenshot_similarity(
|
||||
test_screenshot, golden_image, similarity_threshold, True, screenshot_directory)
|
||||
if screenshot_comparison_result != "Screenshots match":
|
||||
raise Exception(f"Screenshot test failed: {screenshot_comparison_result}")
|
||||
assert compare_screenshot_to_golden_image(screenshot_directory, test_screenshots, golden_images, 0.99) is True
|
||||
|
||||
@pytest.mark.test_case_id("C34525095")
|
||||
def test_LightComponent_ScreenshotMatchesGoldenImage(
|
||||
self, request, editor, workspace, project, launcher_platform, level):
|
||||
"""
|
||||
Please review the hydra script run by this test for more specific test info.
|
||||
Tests that the Light component screenshots in a rendered level appear the same as the golden images.
|
||||
"""
|
||||
class AtomGPU_LightComponent_AreaLightScreenshotsMatchGoldenImages(EditorSharedTest):
|
||||
use_null_renderer = False # Default is True
|
||||
screenshot_names = [
|
||||
"AreaLight_1.ppm",
|
||||
"AreaLight_2.ppm",
|
||||
"AreaLight_3.ppm",
|
||||
"AreaLight_4.ppm",
|
||||
"AreaLight_5.ppm",
|
||||
]
|
||||
test_screenshots = [] # Gets set by setup()
|
||||
screenshot_directory = "" # Gets set by setup()
|
||||
|
||||
# Clear existing test screenshots before starting test.
|
||||
def setup(self, workspace):
|
||||
screenshot_directory = os.path.join(workspace.paths.project(), DEFAULT_SUBFOLDER_PATH)
|
||||
for screenshot in self.screenshot_names:
|
||||
screenshot_path = os.path.join(screenshot_directory, screenshot)
|
||||
self.test_screenshots.append(screenshot_path)
|
||||
file_system.delete(self.test_screenshots, True, True)
|
||||
|
||||
golden_images = []
|
||||
for golden_image in screenshot_names:
|
||||
golden_image_path = os.path.join(golden_images_directory(), golden_image)
|
||||
golden_images.append(golden_image_path)
|
||||
|
||||
from Atom.tests import hydra_AtomGPU_AreaLightScreenshotTest as test_module
|
||||
|
||||
assert compare_screenshot_to_golden_image(screenshot_directory, test_screenshots, golden_images, 0.99) is True
|
||||
|
||||
@pytest.mark.test_case_id("C34525110")
|
||||
class AtomGPU_LightComponent_SpotLightScreenshotsMatchGoldenImages(EditorSharedTest):
|
||||
use_null_renderer = False # Default is True
|
||||
screenshot_names = [
|
||||
"SpotLight_1.ppm",
|
||||
"SpotLight_2.ppm",
|
||||
"SpotLight_3.ppm",
|
||||
@@ -134,40 +87,25 @@ class TestAllComponentsIndepthTests(object):
|
||||
"SpotLight_5.ppm",
|
||||
"SpotLight_6.ppm",
|
||||
]
|
||||
screenshot_directory = os.path.join(workspace.paths.project(), DEFAULT_SUBFOLDER_PATH)
|
||||
test_screenshots = []
|
||||
for screenshot in screenshot_names:
|
||||
screenshot_path = os.path.join(screenshot_directory, screenshot)
|
||||
test_screenshots.append(screenshot_path)
|
||||
file_system.delete(test_screenshots, True, True)
|
||||
test_screenshots = [] # Gets set by setup()
|
||||
screenshot_directory = "" # Gets set by setup()
|
||||
|
||||
# Clear existing test screenshots before starting test.
|
||||
def setup(self, workspace):
|
||||
screenshot_directory = os.path.join(workspace.paths.project(), DEFAULT_SUBFOLDER_PATH)
|
||||
for screenshot in self.screenshot_names:
|
||||
screenshot_path = os.path.join(screenshot_directory, screenshot)
|
||||
self.test_screenshots.append(screenshot_path)
|
||||
file_system.delete(self.test_screenshots, True, True)
|
||||
|
||||
golden_images = []
|
||||
for golden_image in screenshot_names:
|
||||
golden_image_path = os.path.join(golden_images_directory(), golden_image)
|
||||
golden_images.append(golden_image_path)
|
||||
|
||||
expected_lines = ["spot_light Controller|Configuration|Shadows|Shadowmap size: SUCCESS"]
|
||||
unexpected_lines = ["Traceback (most recent call last):"]
|
||||
hydra.launch_and_validate_results(
|
||||
request,
|
||||
TEST_DIRECTORY,
|
||||
editor,
|
||||
"hydra_GPUTest_LightComponent.py",
|
||||
timeout=180,
|
||||
expected_lines=expected_lines,
|
||||
unexpected_lines=unexpected_lines,
|
||||
halt_on_unexpected=True,
|
||||
cfg_args=[level],
|
||||
null_renderer=False,
|
||||
enable_prefab_system=False,
|
||||
)
|
||||
from Atom.tests import hydra_AtomGPU_SpotLightScreenshotTest as test_module
|
||||
|
||||
similarity_threshold = 0.99
|
||||
for test_screenshot, golden_image in zip(test_screenshots, golden_images):
|
||||
screenshot_comparison_result = compare_screenshot_similarity(
|
||||
test_screenshot, golden_image, similarity_threshold, True, screenshot_directory)
|
||||
if screenshot_comparison_result != "Screenshots match":
|
||||
raise ImageComparisonTestFailure(f"Screenshot test failed: {screenshot_comparison_result}")
|
||||
assert compare_screenshot_to_golden_image(screenshot_directory, test_screenshots, golden_images, 0.99) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('rhi', ['dx12', 'vulkan'])
|
||||
@@ -198,7 +136,7 @@ class TestPerformanceBenchmarkSuite(object):
|
||||
|
||||
hydra.launch_and_validate_results(
|
||||
request,
|
||||
TEST_DIRECTORY,
|
||||
os.path.join(os.path.dirname(__file__), "tests"),
|
||||
editor,
|
||||
"hydra_GPUTest_AtomFeatureIntegrationBenchmark.py",
|
||||
timeout=600,
|
||||
@@ -235,7 +173,7 @@ class TestMaterialEditor(object):
|
||||
|
||||
hydra.launch_and_validate_results(
|
||||
request,
|
||||
TEST_DIRECTORY,
|
||||
os.path.join(os.path.dirname(__file__), "tests"),
|
||||
generic_launcher,
|
||||
editor_script="",
|
||||
run_python="--runpython",
|
||||
|
||||
@@ -12,6 +12,7 @@ import pytest
|
||||
import ly_test_tools.environment.file_system as file_system
|
||||
import editor_python_test_tools.hydra_test_utils as hydra
|
||||
|
||||
from ly_test_tools.o3de.editor_test import EditorSharedTest, EditorTestSuite
|
||||
from Atom.atom_utils.atom_constants import LIGHT_TYPES
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -159,3 +160,17 @@ class TestMaterialEditorBasicTests(object):
|
||||
enable_prefab_system=False,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("project", ["AutomatedTesting"])
|
||||
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
|
||||
class TestAutomation(EditorTestSuite):
|
||||
|
||||
enable_prefab_system = False
|
||||
|
||||
@pytest.mark.test_case_id("C36529666")
|
||||
class AtomEditorComponentsLevel_DiffuseGlobalIlluminationAdded(EditorSharedTest):
|
||||
from Atom.tests import hydra_AtomEditorComponentsLevel_DiffuseGlobalIlluminationAdded as test_module
|
||||
|
||||
@pytest.mark.test_case_id("C36525660")
|
||||
class AtomEditorComponentsLevel_DisplayMapperAdded(EditorSharedTest):
|
||||
from Atom.tests import hydra_AtomEditorComponentsLevel_DisplayMapperAdded as test_module
|
||||
|
||||
@@ -93,161 +93,165 @@ def compare_screenshot_similarity(
|
||||
return result
|
||||
|
||||
|
||||
def create_basic_atom_level(level_name):
|
||||
def compare_screenshot_to_golden_image(
|
||||
screenshot_directory, test_screenshots, golden_images, similarity_threshold=0.99):
|
||||
"""
|
||||
Creates a new level inside the Editor matching level_name & adds the following:
|
||||
1. "default_level" entity to hold all other entities.
|
||||
2. Adds Grid, Global Skylight (IBL), ground Mesh, Directional Light, Sphere w/ material+mesh, & Camera components.
|
||||
3. Each of these components has its settings tweaked slightly to match the ideal scene to test Atom rendering.
|
||||
:param level_name: name of the level to create and apply this basic setup to.
|
||||
Compares a list of test_screenshots to a list of golden_images and return True if they match within the
|
||||
similarity threshold set. Otherwise, it will raise ImageComparisonTestFailure with a failure message.
|
||||
:param screenshot_directory: path to the directory containing screenshots for creating .zip archives.
|
||||
:param test_screenshots: list of test screenshot path strings.
|
||||
:param golden_images: list of golden image path strings.
|
||||
:param similarity_threshold: float threshold tolerance to set when comparing screenshots to golden images.
|
||||
"""
|
||||
for test_screenshot, golden_image in zip(test_screenshots, golden_images):
|
||||
screenshot_comparison_result = compare_screenshot_similarity(
|
||||
test_screenshot, golden_image, similarity_threshold, True, screenshot_directory)
|
||||
if screenshot_comparison_result != "Screenshots match":
|
||||
raise ImageComparisonTestFailure(f"Screenshot test failed: {screenshot_comparison_result}")
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def initial_viewport_setup(screen_width=1280, screen_height=720):
|
||||
"""
|
||||
For setting up the initial viewport resolution to expected default values before running a screenshot test.
|
||||
Defaults to 1280 x 720 resolution (in pixels).
|
||||
:param screen_width: Width in pixels to set the viewport width size to.
|
||||
:param screen_height: Height in pixels to set the viewport height size to.
|
||||
:return: None
|
||||
"""
|
||||
import azlmbr.asset as asset
|
||||
import azlmbr.bus as bus
|
||||
import azlmbr.camera as camera
|
||||
import azlmbr.editor as editor
|
||||
import azlmbr.entity as entity
|
||||
import azlmbr.legacy.general as general
|
||||
import azlmbr.math as math
|
||||
import azlmbr.object
|
||||
|
||||
import editor_python_test_tools.hydra_editor_utils as hydra
|
||||
from editor_python_test_tools.editor_test_helper import EditorTestHelper
|
||||
|
||||
helper = EditorTestHelper(log_prefix="Atom_EditorTestHelper")
|
||||
|
||||
# Wait for Editor idle loop before executing Python hydra scripts.
|
||||
general.idle_enable(True)
|
||||
|
||||
# Basic setup for opened level.
|
||||
helper.open_level(level_name="Base")
|
||||
general.idle_wait(1.0)
|
||||
general.update_viewport()
|
||||
general.idle_wait(0.5) # half a second is more than enough for updating the viewport.
|
||||
|
||||
# Close out problematic windows, FPS meters, and anti-aliasing.
|
||||
if general.is_helpers_shown(): # Turn off the helper gizmos if visible
|
||||
general.toggle_helpers()
|
||||
general.idle_wait(1.0)
|
||||
if general.is_pane_visible("Error Report"): # Close Error Report windows that block focus.
|
||||
general.close_pane("Error Report")
|
||||
if general.is_pane_visible("Error Log"): # Close Error Log windows that block focus.
|
||||
general.close_pane("Error Log")
|
||||
general.idle_wait(1.0)
|
||||
general.run_console("r_displayInfo=0")
|
||||
general.idle_wait(1.0)
|
||||
|
||||
# Delete all existing entities & create default_level entity
|
||||
search_filter = azlmbr.entity.SearchFilter()
|
||||
all_entities = entity.SearchBus(azlmbr.bus.Broadcast, "SearchEntities", search_filter)
|
||||
editor.ToolsApplicationRequestBus(bus.Broadcast, "DeleteEntities", all_entities)
|
||||
default_level = hydra.Entity("default_level")
|
||||
default_position = math.Vector3(0.0, 0.0, 0.0)
|
||||
default_level.create_entity(default_position, ["Grid"])
|
||||
default_level.get_set_test(0, "Controller|Configuration|Secondary Grid Spacing", 1.0)
|
||||
|
||||
# Set the viewport up correctly after adding the parent default_level entity.
|
||||
screen_width = 1280
|
||||
screen_height = 720
|
||||
degree_radian_factor = 0.0174533 # Used by "Rotation" property for the Transform component.
|
||||
general.set_viewport_size(screen_width, screen_height)
|
||||
general.update_viewport()
|
||||
helper.wait_for_condition(
|
||||
function=lambda: helper.isclose(a=general.get_viewport_size().x, b=screen_width, rel_tol=0.1)
|
||||
and helper.isclose(a=general.get_viewport_size().y, b=screen_height, rel_tol=0.1),
|
||||
timeout_in_seconds=4.0
|
||||
)
|
||||
result = helper.isclose(a=general.get_viewport_size().x, b=screen_width, rel_tol=0.1) and helper.isclose(
|
||||
a=general.get_viewport_size().y, b=screen_height, rel_tol=0.1)
|
||||
general.log(general.get_viewport_size().x)
|
||||
general.log(general.get_viewport_size().y)
|
||||
general.log(general.get_viewport_size().z)
|
||||
general.log(f"Viewport is set to the expected size: {result}")
|
||||
general.log("Basic level created")
|
||||
general.run_console("r_DisplayInfo = 0")
|
||||
|
||||
# Create global_skylight entity and set the properties
|
||||
global_skylight = hydra.Entity("global_skylight")
|
||||
global_skylight.create_entity(
|
||||
entity_position=default_position,
|
||||
components=["HDRi Skybox", "Global Skylight (IBL)"],
|
||||
parent_id=default_level.id)
|
||||
global_skylight_asset_path = os.path.join("LightingPresets", "default_iblskyboxcm.exr.streamingimage")
|
||||
global_skylight_asset_value = asset.AssetCatalogRequestBus(
|
||||
bus.Broadcast, "GetAssetIdByPath", global_skylight_asset_path, math.Uuid(), False)
|
||||
global_skylight.get_set_test(0, "Controller|Configuration|Cubemap Texture", global_skylight_asset_value)
|
||||
global_skylight.get_set_test(1, "Controller|Configuration|Diffuse Image", global_skylight_asset_value)
|
||||
global_skylight.get_set_test(1, "Controller|Configuration|Specular Image", global_skylight_asset_value)
|
||||
|
||||
# Create ground_plane entity and set the properties
|
||||
ground_plane = hydra.Entity("ground_plane")
|
||||
ground_plane.create_entity(
|
||||
entity_position=default_position,
|
||||
components=["Material"],
|
||||
parent_id=default_level.id)
|
||||
azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalUniformScale", ground_plane.id, 32.0)
|
||||
def enter_exit_game_mode_take_screenshot(screenshot_name, enter_game_tuple, exit_game_tuple, timeout_in_seconds=4):
|
||||
"""
|
||||
Enters game mode, takes a screenshot named screenshot_name (must include file extension), and exits game mode.
|
||||
:param screenshot_name: string representing the name of the screenshot file, including file extension.
|
||||
:param enter_game_tuple: tuple where the 1st string is success & 2nd string is failure for entering the game.
|
||||
:param exit_game_tuple: tuple where the 1st string is success & 2nd string is failure for exiting the game.
|
||||
:param timeout_in_seconds: int or float seconds to wait for entering/exiting game mode.
|
||||
:return: None
|
||||
"""
|
||||
import azlmbr.legacy.general as general
|
||||
|
||||
# Work around to add the correct Atom Mesh component and asset.
|
||||
mesh_type_id = azlmbr.globals.property.EditorMeshComponentTypeId
|
||||
ground_plane.components.append(
|
||||
editor.EditorComponentAPIBus(
|
||||
bus.Broadcast, "AddComponentsOfType", ground_plane.id, [mesh_type_id]
|
||||
).GetValue()[0]
|
||||
)
|
||||
from editor_python_test_tools.utils import TestHelper
|
||||
|
||||
from Atom.atom_utils.screenshot_utils import ScreenshotHelper
|
||||
|
||||
TestHelper.enter_game_mode(enter_game_tuple)
|
||||
TestHelper.wait_for_condition(function=lambda: general.is_in_game_mode(), timeout_in_seconds=timeout_in_seconds)
|
||||
ScreenshotHelper(general.idle_wait_frames).capture_screenshot_blocking(screenshot_name)
|
||||
TestHelper.exit_game_mode(exit_game_tuple)
|
||||
TestHelper.wait_for_condition(function=lambda: not general.is_in_game_mode(), timeout_in_seconds=timeout_in_seconds)
|
||||
|
||||
|
||||
def create_basic_atom_rendering_scene():
|
||||
"""
|
||||
Sets up a new scene inside the Editor for testing Atom rendering GPU output.
|
||||
Setup: Deletes all existing entities before creating the scene.
|
||||
The created scene includes:
|
||||
1. "Default Level" entity that holds all of the other entities.
|
||||
2. "Grid" entity: Contains a Grid component.
|
||||
3. "Global Skylight (IBL)" entity: Contains HDRI Skybox & Global Skylight (IBL) components.
|
||||
4. "Ground Plane" entity: Contains Material & Mesh components.
|
||||
5. "Directional Light" entity: Contains Directional Light component.
|
||||
6. "Sphere" entity: Contains Material & Mesh components.
|
||||
7. "Camera" entity: Contains Camera component.
|
||||
:return: None
|
||||
"""
|
||||
import azlmbr.math as math
|
||||
import azlmbr.paths
|
||||
|
||||
from editor_python_test_tools.asset_utils import Asset
|
||||
from editor_python_test_tools.editor_entity_utils import EditorEntity
|
||||
|
||||
from Atom.atom_utils.atom_constants import AtomComponentProperties
|
||||
|
||||
DEGREE_RADIAN_FACTOR = 0.0174533
|
||||
|
||||
# Setup: Deletes all existing entities before creating the scene.
|
||||
search_filter = azlmbr.entity.SearchFilter()
|
||||
all_entities = azlmbr.entity.SearchBus(azlmbr.bus.Broadcast, "SearchEntities", search_filter)
|
||||
azlmbr.editor.ToolsApplicationRequestBus(azlmbr.bus.Broadcast, "DeleteEntities", all_entities)
|
||||
|
||||
# 1. "Default Level" entity that holds all of the other entities.
|
||||
default_level_entity_name = "Default Level"
|
||||
default_level_entity = EditorEntity.create_editor_entity_at(math.Vector3(0.0, 0.0, 0.0), default_level_entity_name)
|
||||
|
||||
# 2. "Grid" entity: Contains a Grid component.
|
||||
grid_entity = EditorEntity.create_editor_entity(AtomComponentProperties.grid(), default_level_entity.id)
|
||||
grid_component = grid_entity.add_component(AtomComponentProperties.grid())
|
||||
secondary_grid_spacing_value = 1.0
|
||||
grid_component.set_component_property_value(
|
||||
AtomComponentProperties.grid('Secondary Grid Spacing'), secondary_grid_spacing_value)
|
||||
|
||||
# 3. "Global Skylight (IBL)" entity: Contains HDRI Skybox & Global Skylight (IBL) components.
|
||||
global_skylight_entity = EditorEntity.create_editor_entity(
|
||||
AtomComponentProperties.global_skylight(), default_level_entity.id)
|
||||
hdri_skybox_component = global_skylight_entity.add_component(AtomComponentProperties.hdri_skybox())
|
||||
global_skylight_component = global_skylight_entity.add_component(AtomComponentProperties.global_skylight())
|
||||
global_skylight_image_asset_path = os.path.join("LightingPresets", "default_iblskyboxcm.exr.streamingimage")
|
||||
global_skylight_image_asset = Asset.find_asset_by_path(global_skylight_image_asset_path, False)
|
||||
hdri_skybox_component.set_component_property_value(
|
||||
AtomComponentProperties.hdri_skybox('Cubemap Texture'), global_skylight_image_asset.id)
|
||||
global_skylight_diffuse_image_asset_path = os.path.join(
|
||||
"LightingPresets", "default_iblskyboxcm_ibldiffuse.exr.streamingimage")
|
||||
global_skylight_diffuse_image_asset = Asset.find_asset_by_path(global_skylight_diffuse_image_asset_path, False)
|
||||
global_skylight_component.set_component_property_value(
|
||||
AtomComponentProperties.global_skylight('Diffuse Image'), global_skylight_diffuse_image_asset.id)
|
||||
global_skylight_specular_image_asset_path = os.path.join(
|
||||
"LightingPresets", "default_iblskyboxcm_iblspecular.exr.streamingimage")
|
||||
global_skylight_specular_image_asset = Asset.find_asset_by_path(
|
||||
global_skylight_specular_image_asset_path, False)
|
||||
global_skylight_component.set_component_property_value(
|
||||
AtomComponentProperties.global_skylight('Specular Image'), global_skylight_specular_image_asset.id)
|
||||
|
||||
# 4. "Ground Plane" entity: Contains Material & Mesh components.
|
||||
ground_plane_name = "Ground Plane"
|
||||
ground_plane_entity = EditorEntity.create_editor_entity(ground_plane_name, default_level_entity.id)
|
||||
ground_plane_material_component = ground_plane_entity.add_component(AtomComponentProperties.material())
|
||||
ground_plane_entity.set_local_uniform_scale(32.0)
|
||||
ground_plane_mesh_component = ground_plane_entity.add_component(AtomComponentProperties.mesh())
|
||||
ground_plane_mesh_asset_path = os.path.join("TestData", "Objects", "plane.azmodel")
|
||||
ground_plane_mesh_asset_value = asset.AssetCatalogRequestBus(
|
||||
bus.Broadcast, "GetAssetIdByPath", ground_plane_mesh_asset_path, math.Uuid(), False)
|
||||
ground_plane.get_set_test(1, "Controller|Configuration|Mesh Asset", ground_plane_mesh_asset_value)
|
||||
|
||||
# Add Atom Material component and asset.
|
||||
ground_plane_mesh_asset = Asset.find_asset_by_path(ground_plane_mesh_asset_path, False)
|
||||
ground_plane_mesh_component.set_component_property_value(
|
||||
AtomComponentProperties.mesh('Mesh Asset'), ground_plane_mesh_asset.id)
|
||||
ground_plane_material_asset_path = os.path.join("Materials", "Presets", "PBR", "metal_chrome.azmaterial")
|
||||
ground_plane_material_asset_value = asset.AssetCatalogRequestBus(
|
||||
bus.Broadcast, "GetAssetIdByPath", ground_plane_material_asset_path, math.Uuid(), False)
|
||||
ground_plane.get_set_test(0, "Default Material|Material Asset", ground_plane_material_asset_value)
|
||||
ground_plane_material_asset = Asset.find_asset_by_path(ground_plane_material_asset_path, False)
|
||||
ground_plane_material_component.set_component_property_value(
|
||||
AtomComponentProperties.material('Material Asset'), ground_plane_material_asset.id)
|
||||
|
||||
# Create directional_light entity and set the properties
|
||||
directional_light = hydra.Entity("directional_light")
|
||||
directional_light.create_entity(
|
||||
entity_position=math.Vector3(0.0, 0.0, 10.0),
|
||||
components=["Directional Light"],
|
||||
parent_id=default_level.id)
|
||||
directional_light_rotation = math.Vector3(degree_radian_factor * -90.0, 0.0, 0.0)
|
||||
azlmbr.components.TransformBus(
|
||||
azlmbr.bus.Event, "SetLocalRotation", directional_light.id, directional_light_rotation)
|
||||
# 5. "Directional Light" entity: Contains Directional Light component.
|
||||
directional_light_entity = EditorEntity.create_editor_entity_at(
|
||||
math.Vector3(0.0, 0.0, 10.0), AtomComponentProperties.directional_light(), default_level_entity.id)
|
||||
directional_light_entity.add_component(AtomComponentProperties.directional_light())
|
||||
directional_light_entity_rotation = math.Vector3(DEGREE_RADIAN_FACTOR * -90.0, 0.0, 0.0)
|
||||
directional_light_entity.set_local_rotation(directional_light_entity_rotation)
|
||||
|
||||
# Create sphere entity and set the properties
|
||||
sphere_entity = hydra.Entity("sphere")
|
||||
sphere_entity.create_entity(
|
||||
entity_position=math.Vector3(0.0, 0.0, 1.0),
|
||||
components=["Material"],
|
||||
parent_id=default_level.id)
|
||||
|
||||
# Work around to add the correct Atom Mesh component and asset.
|
||||
sphere_entity.components.append(
|
||||
editor.EditorComponentAPIBus(
|
||||
bus.Broadcast, "AddComponentsOfType", sphere_entity.id, [mesh_type_id]
|
||||
).GetValue()[0]
|
||||
)
|
||||
# 6. "Sphere" entity: Contains Material & Mesh components.
|
||||
sphere_entity = EditorEntity.create_editor_entity_at(
|
||||
math.Vector3(0.0, 0.0, 1.0), "Sphere", default_level_entity.id)
|
||||
sphere_mesh_component = sphere_entity.add_component(AtomComponentProperties.mesh())
|
||||
sphere_mesh_asset_path = os.path.join("Models", "sphere.azmodel")
|
||||
sphere_mesh_asset_value = asset.AssetCatalogRequestBus(
|
||||
bus.Broadcast, "GetAssetIdByPath", sphere_mesh_asset_path, math.Uuid(), False)
|
||||
sphere_entity.get_set_test(1, "Controller|Configuration|Mesh Asset", sphere_mesh_asset_value)
|
||||
|
||||
# Add Atom Material component and asset.
|
||||
sphere_mesh_asset = Asset.find_asset_by_path(sphere_mesh_asset_path, False)
|
||||
sphere_mesh_component.set_component_property_value(
|
||||
AtomComponentProperties.mesh('Mesh Asset'), sphere_mesh_asset.id)
|
||||
sphere_material_component = sphere_entity.add_component(AtomComponentProperties.material())
|
||||
sphere_material_asset_path = os.path.join("Materials", "Presets", "PBR", "metal_brass_polished.azmaterial")
|
||||
sphere_material_asset_value = asset.AssetCatalogRequestBus(
|
||||
bus.Broadcast, "GetAssetIdByPath", sphere_material_asset_path, math.Uuid(), False)
|
||||
sphere_entity.get_set_test(0, "Default Material|Material Asset", sphere_material_asset_value)
|
||||
sphere_material_asset = Asset.find_asset_by_path(sphere_material_asset_path, False)
|
||||
sphere_material_component.set_component_property_value(
|
||||
AtomComponentProperties.material('Material Asset'), sphere_material_asset.id)
|
||||
|
||||
# Create camera component and set the properties
|
||||
camera_entity = hydra.Entity("camera")
|
||||
camera_entity.create_entity(
|
||||
entity_position=math.Vector3(5.5, -12.0, 9.0),
|
||||
components=["Camera"],
|
||||
parent_id=default_level.id)
|
||||
rotation = math.Vector3(
|
||||
degree_radian_factor * -27.0, degree_radian_factor * -12.0, degree_radian_factor * 25.0
|
||||
)
|
||||
azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", camera_entity.id, rotation)
|
||||
camera_entity.get_set_test(0, "Controller|Configuration|Field of view", 60.0)
|
||||
camera.EditorCameraViewRequestBus(azlmbr.bus.Event, "ToggleCameraAsActiveView", camera_entity.id)
|
||||
# 7. "Camera" entity: Contains Camera component.
|
||||
camera_entity = EditorEntity.create_editor_entity_at(
|
||||
math.Vector3(5.5, -12.0, 9.0), AtomComponentProperties.camera(), default_level_entity.id)
|
||||
camera_component = camera_entity.add_component(AtomComponentProperties.camera())
|
||||
camera_entity_rotation = math.Vector3(
|
||||
DEGREE_RADIAN_FACTOR * -27.0, DEGREE_RADIAN_FACTOR * -12.0, DEGREE_RADIAN_FACTOR * 25.0)
|
||||
camera_entity.set_local_rotation(camera_entity_rotation)
|
||||
camera_fov_value = 60.0
|
||||
camera_component.set_component_property_value(AtomComponentProperties.camera('Field of view'), camera_fov_value)
|
||||
azlmbr.camera.EditorCameraViewRequestBus(azlmbr.bus.Event, "ToggleCameraAsActiveView", camera_entity.id)
|
||||
|
||||
@@ -19,6 +19,20 @@ LIGHT_TYPES = {
|
||||
}
|
||||
|
||||
|
||||
# Attenuation Radius Mode options for the Light component.
|
||||
ATTENUATION_RADIUS_MODE = {
|
||||
'automatic': 1,
|
||||
'explicit': 0,
|
||||
}
|
||||
|
||||
# Qualiity Level settings for Diffuse Global Illumination level component
|
||||
GLOBAL_ILLUMINATION_QUALITY = {
|
||||
'Low': 0,
|
||||
'Medium': 1,
|
||||
'High': 2,
|
||||
}
|
||||
|
||||
|
||||
class AtomComponentProperties:
|
||||
"""
|
||||
Holds Atom component related constants
|
||||
@@ -116,6 +130,21 @@ class AtomComponentProperties:
|
||||
}
|
||||
return properties[property]
|
||||
|
||||
@staticmethod
|
||||
def diffuse_global_illumination(property: str = 'name') -> str:
|
||||
"""
|
||||
Diffuse Global Illumination level component properties.
|
||||
Controls global settings for Diffuse Probe Grid components.
|
||||
- 'Quality Level' from atom_constants.py GLOBAL_ILLUMINATION_QUALITY
|
||||
:param property: From the last element of the property tree path. Default 'name' for component name string.
|
||||
:return: Full property path OR component name if no property specified.
|
||||
"""
|
||||
properties = {
|
||||
'name': 'Diffuse Global Illumination',
|
||||
'Quality Level': 'Controller|Configuration|Quality Level'
|
||||
}
|
||||
return properties[property]
|
||||
|
||||
@staticmethod
|
||||
def diffuse_probe_grid(property: str = 'name') -> str:
|
||||
"""
|
||||
@@ -148,7 +177,8 @@ class AtomComponentProperties:
|
||||
@staticmethod
|
||||
def display_mapper(property: str = 'name') -> str:
|
||||
"""
|
||||
Display Mapper component properties.
|
||||
Display Mapper level component properties.
|
||||
- 'Enable LDR color grading LUT' toggles the use of LDR color grading LUT
|
||||
- 'LDR color Grading LUT' is the Low Definition Range (LDR) color grading for Look-up Textures (LUT) which is
|
||||
an Asset.id value corresponding to a lighting asset file.
|
||||
:param property: From the last element of the property tree path. Default 'name' for component name string.
|
||||
@@ -156,6 +186,7 @@ class AtomComponentProperties:
|
||||
"""
|
||||
properties = {
|
||||
'name': 'Display Mapper',
|
||||
'Enable LDR color grading LUT': 'Controller|Configuration|Enable LDR color grading LUT',
|
||||
'LDR color Grading LUT': 'Controller|Configuration|LDR color Grading LUT',
|
||||
}
|
||||
return properties[property]
|
||||
@@ -252,13 +283,27 @@ class AtomComponentProperties:
|
||||
def light(property: str = 'name') -> str:
|
||||
"""
|
||||
Light component properties.
|
||||
- 'Attenuation Radius Mode' controls whether the attenuation radius is calculated automatically or explicitly.
|
||||
- 'Color' the RGB value to set for the color of the light.
|
||||
- 'Enable shadow' toggle for enabling shadows for the light.
|
||||
- 'Enable shutters' toggle for enabling shutters for the light.
|
||||
- 'Inner angle' inner angle value for the shutters (in degrees)
|
||||
- 'Intensity' the intensity of the light in the set photometric unit (float with no ceiling).
|
||||
- 'Light type' from atom_constants.py LIGHT_TYPES
|
||||
- 'Outer angle' outer angle value for the shutters (in degrees)
|
||||
:param property: From the last element of the property tree path. Default 'name' for component name string.
|
||||
:return: Full property path OR component name if no property specified.
|
||||
"""
|
||||
properties = {
|
||||
'name': 'Light',
|
||||
'Attenuation Radius Mode': 'Controller|Configuration|Attenuation radius|Mode',
|
||||
'Color': 'Controller|Configuration|Color',
|
||||
'Enable shadow': 'Controller|Configuration|Shadows|Enable shadow',
|
||||
'Enable shutters': 'Controller|Configuration|Shutters|Enable shutters',
|
||||
'Inner angle': 'Controller|Configuration|Shutters|Inner angle',
|
||||
'Intensity': 'Controller|Configuration|Intensity',
|
||||
'Light type': 'Controller|Configuration|Light type',
|
||||
'Outer angle': 'Controller|Configuration|Shutters|Outer angle',
|
||||
}
|
||||
return properties[property]
|
||||
|
||||
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
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
|
||||
"""
|
||||
|
||||
class Tests:
|
||||
creation_undo = (
|
||||
"UNDO Level component addition success",
|
||||
"UNDO Level component addition failed")
|
||||
creation_redo = (
|
||||
"REDO Level component addition success",
|
||||
"REDO Level component addition failed")
|
||||
diffuse_global_illumination_component = (
|
||||
"Level has a Diffuse Global Illumination component",
|
||||
"Level failed to find Diffuse Global Illumination component")
|
||||
diffuse_global_illumination_quality = (
|
||||
"Quality Level set",
|
||||
"Quality Level could not be set")
|
||||
enter_game_mode = (
|
||||
"Entered game mode",
|
||||
"Failed to enter game mode")
|
||||
exit_game_mode = (
|
||||
"Exited game mode",
|
||||
"Couldn't exit game mode")
|
||||
|
||||
|
||||
def AtomEditorComponentsLevel_DiffuseGlobalIllumination_AddedToEntity():
|
||||
"""
|
||||
Summary:
|
||||
Tests the Diffuse Global Illumination level component can be added to the level entity and is stable.
|
||||
|
||||
Test setup:
|
||||
- Wait for Editor idle loop.
|
||||
- Open the "Base" level.
|
||||
|
||||
Expected Behavior:
|
||||
The component can be added, used in game mode, and has accurate required components.
|
||||
Creation and deletion undo/redo should also work.
|
||||
|
||||
Test Steps:
|
||||
1) Add Diffuse Global Illumination level component to the level entity.
|
||||
2) UNDO the level component addition.
|
||||
3) REDO the level component addition.
|
||||
4) Set Quality Level property to Low
|
||||
5) Enter/Exit game mode.
|
||||
6) Look for errors and asserts.
|
||||
|
||||
:return: None
|
||||
"""
|
||||
|
||||
import azlmbr.legacy.general as general
|
||||
|
||||
from editor_python_test_tools.editor_entity_utils import EditorLevelEntity
|
||||
from editor_python_test_tools.utils import Report, Tracer, TestHelper
|
||||
from Atom.atom_utils.atom_constants import AtomComponentProperties, GLOBAL_ILLUMINATION_QUALITY
|
||||
|
||||
with Tracer() as error_tracer:
|
||||
# Test setup begins.
|
||||
# Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level.
|
||||
TestHelper.init_idle()
|
||||
TestHelper.open_level("", "Base")
|
||||
|
||||
# Test steps begin.
|
||||
# 1. Add Diffuse Global Illumination level component to the level entity.
|
||||
diffuse_global_illumination_component = EditorLevelEntity.add_component(
|
||||
AtomComponentProperties.diffuse_global_illumination())
|
||||
Report.critical_result(
|
||||
Tests.diffuse_global_illumination_component,
|
||||
EditorLevelEntity.has_component(AtomComponentProperties.diffuse_global_illumination()))
|
||||
|
||||
# 2. UNDO the level component addition.
|
||||
# -> UNDO component addition.
|
||||
general.undo()
|
||||
general.idle_wait_frames(1)
|
||||
Report.result(Tests.creation_undo,
|
||||
not EditorLevelEntity.has_component(AtomComponentProperties.diffuse_global_illumination()))
|
||||
|
||||
# 3. REDO the level component addition.
|
||||
# -> REDO component addition.
|
||||
general.redo()
|
||||
general.idle_wait_frames(1)
|
||||
Report.result(Tests.creation_redo,
|
||||
EditorLevelEntity.has_component(AtomComponentProperties.diffuse_global_illumination()))
|
||||
|
||||
# 4. Set Quality Level property to Low
|
||||
diffuse_global_illumination_component.set_component_property_value(
|
||||
AtomComponentProperties.diffuse_global_illumination('Quality Level', GLOBAL_ILLUMINATION_QUALITY['Low']))
|
||||
quality = diffuse_global_illumination_component.get_component_property_value(
|
||||
AtomComponentProperties.diffuse_global_illumination('Quality Level'))
|
||||
Report.result(diffuse_global_illumination_quality, quality == GLOBAL_ILLUMINATION_QUALITY['Low'])
|
||||
|
||||
# 5. Enter/Exit game mode.
|
||||
TestHelper.enter_game_mode(Tests.enter_game_mode)
|
||||
general.idle_wait_frames(1)
|
||||
TestHelper.exit_game_mode(Tests.exit_game_mode)
|
||||
|
||||
# 6. Look for errors and asserts.
|
||||
TestHelper.wait_for_condition(lambda: error_tracer.has_errors or error_tracer.has_asserts, 1.0)
|
||||
for error_info in error_tracer.errors:
|
||||
Report.info(f"Error: {error_info.filename} {error_info.function} | {error_info.message}")
|
||||
for assert_info in error_tracer.asserts:
|
||||
Report.info(f"Assert: {assert_info.filename} {assert_info.function} | {assert_info.message}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from editor_python_test_tools.utils import Report
|
||||
Report.start_test(AtomEditorComponentsLevel_DiffuseGlobalIllumination_AddedToEntity)
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
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
|
||||
"""
|
||||
|
||||
|
||||
class Tests:
|
||||
creation_undo = (
|
||||
"UNDO level component addition success",
|
||||
"UNDO level component addition failed")
|
||||
creation_redo = (
|
||||
"REDO Level component addition success",
|
||||
"REDO Level component addition failed")
|
||||
display_mapper_component = (
|
||||
"Level has a Display Mapper component",
|
||||
"Level failed to find Display Mapper component")
|
||||
ldr_color_grading_lut = (
|
||||
"LDR color Grading LUT asset set",
|
||||
"LDR color Grading LUT asset could not be set")
|
||||
enable_ldr_color_grading_lut = (
|
||||
"Enable LDR color grading LUT set",
|
||||
"Enable LDR color grading LUT could not be set")
|
||||
enter_game_mode = (
|
||||
"Entered game mode",
|
||||
"Failed to enter game mode")
|
||||
exit_game_mode = (
|
||||
"Exited game mode",
|
||||
"Couldn't exit game mode")
|
||||
|
||||
|
||||
def AtomEditorComponentsLevel_DisplayMapper_AddedToEntity():
|
||||
"""
|
||||
Summary:
|
||||
Tests the Display Mapper level component can be added to the level 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, and has accurate required components.
|
||||
Creation and deletion undo/redo should also work.
|
||||
|
||||
Test Steps:
|
||||
1) Add Display Mapper level component to the level entity.
|
||||
2) UNDO the level component addition.
|
||||
3) REDO the level component addition.
|
||||
4) Set LDR color Grading LUT asset.
|
||||
5) Set Enable LDR color grading LUT property True
|
||||
6) Enter/Exit game mode.
|
||||
7) Look for errors and asserts.
|
||||
|
||||
:return: None
|
||||
"""
|
||||
import os
|
||||
|
||||
import azlmbr.legacy.general as general
|
||||
|
||||
from editor_python_test_tools.asset_utils import Asset
|
||||
from editor_python_test_tools.editor_entity_utils import EditorLevelEntity
|
||||
from editor_python_test_tools.utils import Report, Tracer, TestHelper
|
||||
from Atom.atom_utils.atom_constants import AtomComponentProperties
|
||||
|
||||
with Tracer() as error_tracer:
|
||||
# Test setup begins.
|
||||
# Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level.
|
||||
TestHelper.init_idle()
|
||||
TestHelper.open_level("", "Base")
|
||||
|
||||
# Test steps begin.
|
||||
# 1. Add Display Mapper level component to the level entity.
|
||||
display_mapper_component = EditorLevelEntity.add_component(AtomComponentProperties.display_mapper())
|
||||
Report.critical_result(
|
||||
Tests.display_mapper_component,
|
||||
EditorLevelEntity.has_component(AtomComponentProperties.display_mapper()))
|
||||
|
||||
# 2. UNDO the level component addition.
|
||||
# -> UNDO component addition.
|
||||
general.undo()
|
||||
general.idle_wait_frames(1)
|
||||
Report.result(Tests.creation_undo, not EditorLevelEntity.has_component(AtomComponentProperties.display_mapper()))
|
||||
|
||||
# 3. REDO the level component addition.
|
||||
# -> REDO component addition.
|
||||
general.redo()
|
||||
general.idle_wait_frames(1)
|
||||
Report.result(Tests.creation_redo, EditorLevelEntity.has_component(AtomComponentProperties.display_mapper()))
|
||||
|
||||
# 4. Set LDR color Grading LUT asset.
|
||||
display_mapper_asset_path = os.path.join("TestData", "test.lightingpreset.azasset")
|
||||
display_mapper_asset = Asset.find_asset_by_path(display_mapper_asset_path, False)
|
||||
display_mapper_component.set_component_property_value(
|
||||
AtomComponentProperties.display_mapper('LDR color Grading LUT'), display_mapper_asset.id)
|
||||
Report.result(
|
||||
Tests.ldr_color_grading_lut,
|
||||
display_mapper_component.get_component_property_value(
|
||||
AtomComponentProperties.display_mapper('LDR color Grading LUT')) == display_mapper_asset.id)
|
||||
|
||||
# 5. Set Enable LDR color grading LUT property True
|
||||
display_mapper_component.set_component_property_value(
|
||||
AtomComponentProperties.display_mapper('Enable LDR color grading LUT'), True)
|
||||
Report.result(
|
||||
Test.enable_ldr_color_grading_lut,
|
||||
display_mapper_component.get_component_property_value(
|
||||
AtomComponentProperties.display_mapper('Enable LDR color grading LUT')) is True)
|
||||
|
||||
# 6. Enter/Exit game mode.
|
||||
TestHelper.enter_game_mode(Tests.enter_game_mode)
|
||||
general.idle_wait_frames(1)
|
||||
TestHelper.exit_game_mode(Tests.exit_game_mode)
|
||||
|
||||
# 7. Look for errors and asserts.
|
||||
TestHelper.wait_for_condition(lambda: error_tracer.has_errors or error_tracer.has_asserts, 1.0)
|
||||
for error_info in error_tracer.errors:
|
||||
Report.info(f"Error: {error_info.filename} {error_info.function} | {error_info.message}")
|
||||
for assert_info in error_tracer.asserts:
|
||||
Report.info(f"Assert: {assert_info.filename} {assert_info.function} | {assert_info.message}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from editor_python_test_tools.utils import Report
|
||||
Report.start_test(AtomEditorComponentsLevel_DisplayMapper_AddedToEntity)
|
||||
+39
-36
@@ -7,15 +7,6 @@ SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
|
||||
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")
|
||||
@@ -43,6 +34,9 @@ class Tests:
|
||||
ldr_color_grading_lut = (
|
||||
"LDR color Grading LUT asset set",
|
||||
"LDR color Grading LUT asset could not be set")
|
||||
enable_ldr_color_grading_lut = (
|
||||
"Enable LDR color grading LUT set",
|
||||
"Enable LDR color grading LUT could not be set")
|
||||
entity_deleted = (
|
||||
"Entity deleted",
|
||||
"Entity was not deleted")
|
||||
@@ -72,14 +66,15 @@ def AtomEditorComponents_DisplayMapper_AddedToEntity():
|
||||
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) Set LDR color Grading LUT asset.
|
||||
9) Delete Display Mapper entity.
|
||||
10) UNDO deletion.
|
||||
11) REDO deletion.
|
||||
12) Look for errors and asserts.
|
||||
5) Set LDR color Grading LUT asset.
|
||||
6) Set Enable LDR color grading LUT property True
|
||||
7) Enter/Exit game mode.
|
||||
8) Test IsHidden.
|
||||
9) Test IsVisible.
|
||||
10) Delete Display Mapper entity.
|
||||
11) UNDO deletion.
|
||||
12) REDO deletion.
|
||||
13) Look for errors and asserts.
|
||||
|
||||
:return: None
|
||||
"""
|
||||
@@ -133,21 +128,7 @@ def AtomEditorComponents_DisplayMapper_AddedToEntity():
|
||||
general.idle_wait_frames(1)
|
||||
Report.result(Tests.creation_redo, display_mapper_entity.exists())
|
||||
|
||||
# 5. Enter/Exit game mode.
|
||||
TestHelper.enter_game_mode(Tests.enter_game_mode)
|
||||
general.idle_wait_frames(1)
|
||||
TestHelper.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. Set LDR color Grading LUT asset.
|
||||
# 5. Set LDR color Grading LUT asset.
|
||||
display_mapper_asset_path = os.path.join("TestData", "test.lightingpreset.azasset")
|
||||
display_mapper_asset = Asset.find_asset_by_path(display_mapper_asset_path, False)
|
||||
display_mapper_component.set_component_property_value(
|
||||
@@ -157,19 +138,41 @@ def AtomEditorComponents_DisplayMapper_AddedToEntity():
|
||||
display_mapper_component.get_component_property_value(
|
||||
AtomComponentProperties.display_mapper("LDR color Grading LUT")) == display_mapper_asset.id)
|
||||
|
||||
# 9. Delete Display Mapper entity.
|
||||
# 6. Set Enable LDR color grading LUT property True
|
||||
display_mapper_component.set_component_property_value(
|
||||
AtomComponentProperties.display_mapper('Enable LDR color grading LUT'), True)
|
||||
Report.result(
|
||||
Tests.enable_ldr_color_grading_lut,
|
||||
display_mapper_component.get_component_property_value(
|
||||
AtomComponentProperties.display_mapper('Enable LDR color grading LUT')) is True)
|
||||
|
||||
# 7. Enter/Exit game mode.
|
||||
TestHelper.enter_game_mode(Tests.enter_game_mode)
|
||||
general.idle_wait_frames(1)
|
||||
TestHelper.exit_game_mode(Tests.exit_game_mode)
|
||||
|
||||
# 8. Test IsHidden.
|
||||
display_mapper_entity.set_visibility_state(False)
|
||||
Report.result(Tests.is_hidden, display_mapper_entity.is_hidden() is True)
|
||||
|
||||
# 9. 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)
|
||||
|
||||
# 10. Delete Display Mapper entity.
|
||||
display_mapper_entity.delete()
|
||||
Report.result(Tests.entity_deleted, not display_mapper_entity.exists())
|
||||
|
||||
# 10. UNDO deletion.
|
||||
# 11. UNDO deletion.
|
||||
general.undo()
|
||||
Report.result(Tests.deletion_undo, display_mapper_entity.exists())
|
||||
|
||||
# 11. REDO deletion.
|
||||
# 12. REDO deletion.
|
||||
general.redo()
|
||||
Report.result(Tests.deletion_redo, not display_mapper_entity.exists())
|
||||
|
||||
# 12. Look for errors and asserts.
|
||||
# 13. Look for errors and asserts.
|
||||
TestHelper.wait_for_condition(lambda: error_tracer.has_errors or error_tracer.has_asserts, 1.0)
|
||||
for error_info in error_tracer.errors:
|
||||
Report.info(f"Error: {error_info.filename} {error_info.function} | {error_info.message}")
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""
|
||||
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
|
||||
"""
|
||||
|
||||
|
||||
class Tests:
|
||||
area_light_entity_created = (
|
||||
"Area Light entity successfully created",
|
||||
"Area Light entity failed to be created")
|
||||
area_light_entity_deleted = (
|
||||
"Area Light entity was deleted",
|
||||
"Area Light entity was not deleted")
|
||||
enter_game_mode = (
|
||||
"Entered game mode",
|
||||
"Failed to enter game mode")
|
||||
exit_game_mode = (
|
||||
"Exited game mode",
|
||||
"Couldn't exit game mode")
|
||||
light_component_added = (
|
||||
"Light component was added",
|
||||
"Light component wasn't added")
|
||||
light_component_attenuation_radius_property_set = (
|
||||
"Light component Attenuation Radius Property was set",
|
||||
"Light component Attenuation Radius Property was not set")
|
||||
light_component_color_property_set = (
|
||||
"Light component Color property was set",
|
||||
"Light component Color property was not set")
|
||||
light_component_intensity_property_set = (
|
||||
"Light component Intensity property was set",
|
||||
"Light component Intensity property was not set")
|
||||
light_component_light_type_property_set = (
|
||||
"Light type property was set",
|
||||
"Light type property was not set")
|
||||
|
||||
|
||||
def AtomGPU_LightComponent_AreaLightScreenshotsMatchGoldenImages():
|
||||
"""
|
||||
Summary:
|
||||
Light component test using the Capsule, Spot (disk), and Point (sphere) Light type property options.
|
||||
Sets each scene up and then takes a screenshot of each scene for test comparison.
|
||||
|
||||
Test setup:
|
||||
- Wait for Editor idle loop.
|
||||
- Open the "Base" level.
|
||||
- Close error windows and display helpers then update the viewport size.
|
||||
- Runs the create_basic_atom_rendering_scene() function to setup the test scene.
|
||||
|
||||
Expected Behavior:
|
||||
The test scripts sets up the scenes correctly and takes accurate screenshots.
|
||||
|
||||
Test Steps:
|
||||
1. Create Area Light entity with no components.
|
||||
2. Add a Light component to the Area Light entity.
|
||||
3. Set the Light type property to Capsule for the Light component.
|
||||
4. Set the Light component's Color property to 255, 0, 0.
|
||||
5. Enter game mode and take a screenshot then exit game mode.
|
||||
6. Set the Intensity property of the Light component to 0.0.
|
||||
7. Set the Attenuation Radius Mode property of the Light component to 1 (automatic).
|
||||
8. Enter game mode and take a screenshot then exit game mode.
|
||||
9. Set the Intensity property of the Light component to 1000.0
|
||||
10. Enter game mode and take a screenshot then exit game mode.
|
||||
11. Set the Light type property to Spot (disk) for the Light component & rotate DEGREE_RADIAN_FACTOR * 90 degrees.
|
||||
12. Enter game mode and take a screenshot then exit game mode.
|
||||
13. Set the Light type property to Point (sphere) instead of Spot (disk) for the Light component.
|
||||
14. Enter game mode and take a screenshot then exit game mode.
|
||||
15. Delete the Area Light entity.
|
||||
16. Look for errors.
|
||||
|
||||
:return: None
|
||||
"""
|
||||
|
||||
import azlmbr.legacy.general as general
|
||||
import azlmbr.paths
|
||||
|
||||
from editor_python_test_tools.editor_entity_utils import EditorEntity
|
||||
from editor_python_test_tools.utils import Report, Tracer, TestHelper
|
||||
|
||||
from Atom.atom_utils.atom_constants import AtomComponentProperties, ATTENUATION_RADIUS_MODE, LIGHT_TYPES
|
||||
from Atom.atom_utils.atom_component_helper import (
|
||||
initial_viewport_setup, create_basic_atom_rendering_scene, enter_exit_game_mode_take_screenshot)
|
||||
|
||||
DEGREE_RADIAN_FACTOR = 0.0174533
|
||||
|
||||
with Tracer() as error_tracer:
|
||||
# Test setup begins.
|
||||
# Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level.
|
||||
TestHelper.init_idle()
|
||||
TestHelper.open_level("", "Base")
|
||||
|
||||
# Setup: Close error windows and display helpers then update the viewport size.
|
||||
TestHelper.close_error_windows()
|
||||
TestHelper.close_display_helpers()
|
||||
initial_viewport_setup()
|
||||
general.update_viewport()
|
||||
|
||||
# Setup: Runs the create_basic_atom_rendering_scene() function to setup the test scene.
|
||||
create_basic_atom_rendering_scene()
|
||||
|
||||
# Test steps begin.
|
||||
# 1. Create Area Light entity with no components.
|
||||
area_light_entity_name = "Area Light"
|
||||
area_light_entity = EditorEntity.create_editor_entity_at(
|
||||
azlmbr.math.Vector3(0.0, 0.0, 0.0), area_light_entity_name)
|
||||
Report.critical_result(Tests.area_light_entity_created, area_light_entity.exists())
|
||||
|
||||
# 2. Add a Light component to the Area Light entity.
|
||||
light_component = area_light_entity.add_component(AtomComponentProperties.light())
|
||||
Report.critical_result(
|
||||
Tests.light_component_added, area_light_entity.has_component(AtomComponentProperties.light()))
|
||||
|
||||
# 3. Set the Light type property to Capsule for the Light component.
|
||||
light_component.set_component_property_value(
|
||||
AtomComponentProperties.light('Light type'), LIGHT_TYPES['capsule'])
|
||||
Report.result(
|
||||
Tests.light_component_light_type_property_set,
|
||||
light_component.get_component_property_value(
|
||||
AtomComponentProperties.light('Light type')) == LIGHT_TYPES['capsule'])
|
||||
|
||||
# 4. Set the Light component's Color property to 255, 0, 0.
|
||||
light_component_color_value = azlmbr.math.Color(255.0, 0.0, 0.0, 0.0)
|
||||
light_component.set_component_property_value(
|
||||
AtomComponentProperties.light('Color'), light_component_color_value)
|
||||
Report.result(
|
||||
Tests.light_component_color_property_set,
|
||||
light_component.get_component_property_value(
|
||||
AtomComponentProperties.light('Color')) == light_component_color_value)
|
||||
|
||||
# 5. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("AreaLight_1.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 6. Set the Intensity property of the Light component to 0.0.
|
||||
light_component.set_component_property_value(AtomComponentProperties.light('Intensity'), 0.0)
|
||||
Report.result(
|
||||
Tests.light_component_intensity_property_set,
|
||||
light_component.get_component_property_value(AtomComponentProperties.light('Intensity')) == 0.0)
|
||||
|
||||
# 7. Set the Attenuation Radius Mode property of the Light component to 1 (automatic).
|
||||
light_component.set_component_property_value(
|
||||
AtomComponentProperties.light('Attenuation Radius Mode'), ATTENUATION_RADIUS_MODE['automatic'])
|
||||
Report.result(
|
||||
Tests.light_component_attenuation_radius_property_set,
|
||||
light_component.get_component_property_value(
|
||||
AtomComponentProperties.light('Attenuation Radius Mode')) == ATTENUATION_RADIUS_MODE['automatic'])
|
||||
|
||||
# 8. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("AreaLight_2.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 9. Set the Intensity property of the Light component to 1000.0
|
||||
light_component.set_component_property_value(AtomComponentProperties.light('Intensity'), 1000.0)
|
||||
Report.result(
|
||||
Tests.light_component_intensity_property_set,
|
||||
light_component.get_component_property_value(AtomComponentProperties.light('Intensity')) == 1000.0)
|
||||
|
||||
# 10. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("AreaLight_3.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 11. Set the Light type property to Spot (disk) for the Light component &
|
||||
# rotate DEGREE_RADIAN_FACTOR * 90 degrees.
|
||||
light_component.set_component_property_value(
|
||||
AtomComponentProperties.light('Light type'), LIGHT_TYPES['spot_disk'])
|
||||
area_light_rotation = azlmbr.math.Vector3(DEGREE_RADIAN_FACTOR * 90.0, 0.0, 0.0)
|
||||
azlmbr.components.TransformBus(azlmbr.bus.Event, "SetLocalRotation", area_light_entity.id, area_light_rotation)
|
||||
Report.result(
|
||||
Tests.light_component_light_type_property_set,
|
||||
light_component.get_component_property_value(
|
||||
AtomComponentProperties.light('Light type')) == LIGHT_TYPES['spot_disk'])
|
||||
|
||||
# 12. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("AreaLight_4.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 13. Set the Light type property to Point (sphere) instead of Spot (disk) for the Light component.
|
||||
light_component.set_component_property_value(
|
||||
AtomComponentProperties.light('Light type'), LIGHT_TYPES['sphere'])
|
||||
Report.result(
|
||||
Tests.light_component_light_type_property_set,
|
||||
light_component.get_component_property_value(
|
||||
AtomComponentProperties.light('Light type')) == LIGHT_TYPES['sphere'])
|
||||
|
||||
# 14. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("AreaLight_5.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 15. Delete the Area Light entity.
|
||||
area_light_entity.delete()
|
||||
Report.result(Tests.area_light_entity_deleted, not area_light_entity.exists())
|
||||
|
||||
# 16. Look for errors.
|
||||
TestHelper.wait_for_condition(lambda: error_tracer.has_errors or error_tracer.has_asserts, 1.0)
|
||||
for error_info in error_tracer.errors:
|
||||
Report.info(f"Error: {error_info.filename} {error_info.function} | {error_info.message}")
|
||||
for assert_info in error_tracer.asserts:
|
||||
Report.info(f"Assert: {assert_info.filename} {assert_info.function} | {assert_info.message}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from editor_python_test_tools.utils import Report
|
||||
Report.start_test(AtomGPU_LightComponent_AreaLightScreenshotsMatchGoldenImages)
|
||||
@@ -80,6 +80,7 @@ def AtomGPU_BasicLevelSetup_SetsUpLevel():
|
||||
Test setup:
|
||||
- Wait for Editor idle loop.
|
||||
- Open the "Base" level.
|
||||
- Deletes all existing entities before creating the scene.
|
||||
|
||||
Expected Behavior:
|
||||
The scene can be setup for a basic level.
|
||||
@@ -115,7 +116,6 @@ def AtomGPU_BasicLevelSetup_SetsUpLevel():
|
||||
"""
|
||||
|
||||
import os
|
||||
from math import isclose
|
||||
|
||||
import azlmbr.legacy.general as general
|
||||
import azlmbr.math as math
|
||||
@@ -126,21 +126,11 @@ def AtomGPU_BasicLevelSetup_SetsUpLevel():
|
||||
from editor_python_test_tools.utils import Report, Tracer, TestHelper
|
||||
|
||||
from Atom.atom_utils.atom_constants import AtomComponentProperties
|
||||
from Atom.atom_utils.atom_component_helper import initial_viewport_setup
|
||||
from Atom.atom_utils.screenshot_utils import ScreenshotHelper
|
||||
|
||||
SCREENSHOT_NAME = "AtomBasicLevelSetup"
|
||||
SCREEN_WIDTH = 1280
|
||||
SCREEN_HEIGHT = 720
|
||||
DEGREE_RADIAN_FACTOR = 0.0174533
|
||||
|
||||
def initial_viewport_setup(screen_width, screen_height):
|
||||
general.set_viewport_size(screen_width, screen_height)
|
||||
general.update_viewport()
|
||||
TestHelper.wait_for_condition(
|
||||
function=lambda: isclose(a=general.get_viewport_size().x, b=SCREEN_WIDTH, rel_tol=0.1)
|
||||
and isclose(a=general.get_viewport_size().y, b=SCREEN_HEIGHT, rel_tol=0.1),
|
||||
timeout_in_seconds=4.0
|
||||
)
|
||||
SCREENSHOT_NAME = "AtomBasicLevelSetup"
|
||||
|
||||
with Tracer() as error_tracer:
|
||||
# Test setup begins.
|
||||
@@ -148,11 +138,16 @@ def AtomGPU_BasicLevelSetup_SetsUpLevel():
|
||||
TestHelper.init_idle()
|
||||
TestHelper.open_level("", "Base")
|
||||
|
||||
# Setup: Deletes all existing entities before creating the scene.
|
||||
search_filter = azlmbr.entity.SearchFilter()
|
||||
all_entities = azlmbr.entity.SearchBus(azlmbr.bus.Broadcast, "SearchEntities", search_filter)
|
||||
azlmbr.editor.ToolsApplicationRequestBus(azlmbr.bus.Broadcast, "DeleteEntities", all_entities)
|
||||
|
||||
# Test steps begin.
|
||||
# 1. Close error windows and display helpers then update the viewport size.
|
||||
TestHelper.close_error_windows()
|
||||
TestHelper.close_display_helpers()
|
||||
initial_viewport_setup(SCREEN_WIDTH, SCREEN_HEIGHT)
|
||||
initial_viewport_setup()
|
||||
general.update_viewport()
|
||||
|
||||
# 2. Create Default Level Entity.
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
"""
|
||||
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
|
||||
"""
|
||||
|
||||
|
||||
class Tests:
|
||||
directional_light_component_disabled = (
|
||||
"Disabled Directional Light component",
|
||||
"Couldn't disable Directional Light component")
|
||||
enter_game_mode = (
|
||||
"Entered game mode",
|
||||
"Failed to enter game mode")
|
||||
exit_game_mode = (
|
||||
"Exited game mode",
|
||||
"Couldn't exit game mode")
|
||||
global_skylight_component_disabled = (
|
||||
"Disabled Global Skylight (IBL) component",
|
||||
"Couldn't disable Global Skylight (IBL) component")
|
||||
hdri_skybox_component_disabled = (
|
||||
"Disabled HDRi Skybox component",
|
||||
"Couldn't disable HDRi Skybox component")
|
||||
light_component_added = (
|
||||
"Light component added",
|
||||
"Couldn't add Light component")
|
||||
light_component_color_property_set = (
|
||||
"Color property was set",
|
||||
"Color property was not set")
|
||||
light_component_enable_shadow_property_set = (
|
||||
"Enable shadow property was set",
|
||||
"Enable shadow property was not set")
|
||||
light_component_enable_shutters_property_set = (
|
||||
"Enable shutters property was set",
|
||||
"Enable shutters property was not set")
|
||||
light_component_inner_angle_property_set = (
|
||||
"Inner angle property was set",
|
||||
"Inner angle property was not set")
|
||||
light_component_intensity_property_set = (
|
||||
"Intensity property was set",
|
||||
"Intensity property was not set")
|
||||
light_component_light_type_property_set = (
|
||||
"Light type property was set",
|
||||
"Light type property was not set")
|
||||
light_component_outer_angle_property_set = (
|
||||
"Outer angle property was set",
|
||||
"Outer angle property was not set")
|
||||
material_component_material_asset_property_set = (
|
||||
"Material Asset property was set",
|
||||
"Material Asset property was not set")
|
||||
spot_light_entity_created = (
|
||||
"Spot Light entity created",
|
||||
"Couldn't create Spot Light entity")
|
||||
|
||||
|
||||
def AtomGPU_LightComponent_SpotLightScreenshotsMatchGoldenImages():
|
||||
"""
|
||||
Summary:
|
||||
Light component test using the Spot (disk) Light type property option and modifying the shadows and colors.
|
||||
Sets each scene up and then takes a screenshot of each scene for test comparison.
|
||||
|
||||
Test setup:
|
||||
- Wait for Editor idle loop.
|
||||
- Open the "Base" level.
|
||||
- Close error windows and display helpers then update the viewport size.
|
||||
- Runs the create_basic_atom_rendering_scene() function to setup the test scene.
|
||||
|
||||
Expected Behavior:
|
||||
The test scripts sets up the scenes correctly and takes accurate screenshots.
|
||||
|
||||
Test Steps:
|
||||
1. Find the Directional Light entity then disable its Directional Light component.
|
||||
2. Disable Global Skylight (IBL) component on the Global Skylight (IBL) entity.
|
||||
3. Disable HDRi Skybox component on the Global Skylight (IBL) entity.
|
||||
4. Create a Spot Light entity and rotate it.
|
||||
5. Attach a Light component to the Spot Light entity.
|
||||
6. Set the Light component Light Type to Spot (disk).
|
||||
7. Enter game mode and take a screenshot then exit game mode.
|
||||
8. Change the default material asset for the Ground Plane entity.
|
||||
9. Enter game mode and take a screenshot then exit game mode.
|
||||
10. Increase the Intensity value of the Light component.
|
||||
11. Enter game mode and take a screenshot then exit game mode.
|
||||
12. Change the Light component Color property value.
|
||||
13. Enter game mode and take a screenshot then exit game mode.
|
||||
14. Change the Light component Enable shutters, Inner angle, and Outer angle property values.
|
||||
15. Enter game mode and take a screenshot then exit game mode.
|
||||
16. Change the Light component Enable shadow and Shadowmap size property values then move Spot Light entity.
|
||||
17. Enter game mode and take a screenshot then exit game mode.
|
||||
18. Look for errors.
|
||||
|
||||
:return: None
|
||||
"""
|
||||
import os
|
||||
|
||||
import azlmbr.legacy.general as general
|
||||
import azlmbr.paths
|
||||
|
||||
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
|
||||
|
||||
from Atom.atom_utils.atom_constants import AtomComponentProperties, LIGHT_TYPES
|
||||
from Atom.atom_utils.atom_component_helper import (
|
||||
initial_viewport_setup, create_basic_atom_rendering_scene, enter_exit_game_mode_take_screenshot)
|
||||
|
||||
DEGREE_RADIAN_FACTOR = 0.0174533
|
||||
|
||||
with Tracer() as error_tracer:
|
||||
# Test setup begins.
|
||||
# Setup: Wait for Editor idle loop before executing Python hydra scripts then open "Base" level.
|
||||
TestHelper.init_idle()
|
||||
TestHelper.open_level("", "Base")
|
||||
|
||||
# Setup: Close error windows and display helpers then update the viewport size.
|
||||
TestHelper.close_error_windows()
|
||||
TestHelper.close_display_helpers()
|
||||
initial_viewport_setup()
|
||||
general.update_viewport()
|
||||
|
||||
# Setup: Runs the create_basic_atom_rendering_scene() function to setup the test scene.
|
||||
create_basic_atom_rendering_scene()
|
||||
|
||||
# Test steps begin.
|
||||
# 1. Find the Directional Light entity then disable its Directional Light component.
|
||||
directional_light_entity = EditorEntity.find_editor_entity(AtomComponentProperties.directional_light())
|
||||
directional_light_component = directional_light_entity.get_components_of_type(
|
||||
[AtomComponentProperties.directional_light()])[0]
|
||||
directional_light_component.disable_component()
|
||||
Report.critical_result(Tests.directional_light_component_disabled, not directional_light_component.is_enabled())
|
||||
|
||||
# 2. Disable Global Skylight (IBL) component on the Global Skylight (IBL) entity.
|
||||
global_skylight_entity = EditorEntity.find_editor_entity(AtomComponentProperties.global_skylight())
|
||||
global_skylight_component = global_skylight_entity.get_components_of_type(
|
||||
[AtomComponentProperties.global_skylight()])[0]
|
||||
global_skylight_component.disable_component()
|
||||
Report.critical_result(Tests.global_skylight_component_disabled, not global_skylight_component.is_enabled())
|
||||
|
||||
# 3. Disable HDRi Skybox component on the Global Skylight (IBL) entity.
|
||||
hdri_skybox_component = global_skylight_entity.get_components_of_type(
|
||||
[AtomComponentProperties.hdri_skybox()])[0]
|
||||
hdri_skybox_component.disable_component()
|
||||
Report.critical_result(Tests.hdri_skybox_component_disabled, not hdri_skybox_component.is_enabled())
|
||||
|
||||
# 4. Create a Spot Light entity and rotate it.
|
||||
spot_light_name = "Spot Light"
|
||||
spot_light_entity = EditorEntity.create_editor_entity_at(
|
||||
azlmbr.math.Vector3(0.7, -2.0, 1.0), spot_light_name)
|
||||
rotation = azlmbr.math.Vector3(DEGREE_RADIAN_FACTOR * 300.0, 0.0, 0.0)
|
||||
spot_light_entity.set_local_rotation(rotation)
|
||||
Report.critical_result(Tests.spot_light_entity_created, spot_light_entity.exists())
|
||||
|
||||
# 5. Attach a Light component to the Spot Light entity.
|
||||
light_component = spot_light_entity.add_component(AtomComponentProperties.light())
|
||||
Report.critical_result(Tests.light_component_added, light_component.is_enabled())
|
||||
|
||||
# 6. Set the Light component Light Type to Spot (disk).
|
||||
light_component.set_component_property_value(
|
||||
AtomComponentProperties.light('Light type'), LIGHT_TYPES['spot_disk'])
|
||||
Report.result(
|
||||
Tests.light_component_light_type_property_set,
|
||||
light_component.get_component_property_value(
|
||||
AtomComponentProperties.light('Light type')) == LIGHT_TYPES['spot_disk'])
|
||||
|
||||
# 7. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("SpotLight_1.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 8. Change the default material asset for the Ground Plane entity.
|
||||
ground_plane_name = "Ground Plane"
|
||||
ground_plane_entity = EditorEntity.find_editor_entity(ground_plane_name)
|
||||
ground_plane_material_component_name = AtomComponentProperties.material()
|
||||
ground_plane_material_component = ground_plane_entity.get_components_of_type(
|
||||
[ground_plane_material_component_name])[0]
|
||||
ground_plane_material_asset_path = os.path.join(
|
||||
"Materials", "Presets", "Macbeth", "22_neutral_5-0_0-70d.azmaterial")
|
||||
ground_plane_material_asset = Asset.find_asset_by_path(ground_plane_material_asset_path, False)
|
||||
ground_plane_material_component.set_component_property_value(
|
||||
AtomComponentProperties.material('Material Asset'), ground_plane_material_asset.id)
|
||||
Report.result(
|
||||
Tests.material_component_material_asset_property_set,
|
||||
ground_plane_material_component.get_component_property_value(
|
||||
AtomComponentProperties.material('Material Asset')) == ground_plane_material_asset.id)
|
||||
|
||||
# 9. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("SpotLight_2.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 10. Increase the Intensity value of the Light component.
|
||||
light_component.set_component_property_value(AtomComponentProperties.light('Intensity'), 800.0)
|
||||
Report.result(
|
||||
Tests.light_component_intensity_property_set,
|
||||
light_component.get_component_property_value(
|
||||
AtomComponentProperties.light('Intensity')) == 800.0)
|
||||
|
||||
# 11. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("SpotLight_3.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 12. Change the Light component Color property value.
|
||||
color_value = azlmbr.math.Color(47.0 / 255.0, 75.0 / 255.0, 37.0 / 255.0, 255.0 / 255.0)
|
||||
light_component.set_component_property_value(AtomComponentProperties.light('Color'), color_value)
|
||||
Report.result(
|
||||
Tests.light_component_color_property_set,
|
||||
light_component.get_component_property_value(AtomComponentProperties.light('Color')) == color_value)
|
||||
|
||||
# 13. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("SpotLight_4.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 14. Change the Light component Enable shutters, Inner angle, and Outer angle property values.
|
||||
enable_shutters = True
|
||||
inner_angle = 60.0
|
||||
outer_angle = 75.0
|
||||
light_component.set_component_property_value(AtomComponentProperties.light('Enable shutters'), enable_shutters)
|
||||
light_component.set_component_property_value(AtomComponentProperties.light('Inner angle'), inner_angle)
|
||||
light_component.set_component_property_value(AtomComponentProperties.light('Outer angle'), outer_angle)
|
||||
Report.result(
|
||||
Tests.light_component_enable_shutters_property_set,
|
||||
light_component.get_component_property_value(
|
||||
AtomComponentProperties.light('Enable shutters')) == enable_shutters)
|
||||
Report.result(
|
||||
Tests.light_component_inner_angle_property_set,
|
||||
light_component.get_component_property_value(AtomComponentProperties.light('Inner angle')) == inner_angle)
|
||||
Report.result(
|
||||
Tests.light_component_outer_angle_property_set,
|
||||
light_component.get_component_property_value(AtomComponentProperties.light('Outer angle')) == outer_angle)
|
||||
|
||||
# 15. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("SpotLight_5.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 16. Change the Light component Enable shadow and slightly move Spot Light entity.
|
||||
light_component.set_component_property_value(AtomComponentProperties.light('Enable shadow'), True)
|
||||
Report.result(
|
||||
Tests.light_component_enable_shadow_property_set,
|
||||
light_component.get_component_property_value(AtomComponentProperties.light('Enable shadow')) is True)
|
||||
spot_light_entity.set_world_rotation(azlmbr.math.Vector3(0.7, -2.0, 1.9))
|
||||
|
||||
# 17. Enter game mode and take a screenshot then exit game mode.
|
||||
enter_exit_game_mode_take_screenshot("SpotLight_6.ppm", Tests.enter_game_mode, Tests.exit_game_mode)
|
||||
|
||||
# 18. Look for errors.
|
||||
TestHelper.wait_for_condition(lambda: error_tracer.has_errors or error_tracer.has_asserts, 1.0)
|
||||
for error_info in error_tracer.errors:
|
||||
Report.info(f"Error: {error_info.filename} {error_info.function} | {error_info.message}")
|
||||
for assert_info in error_tracer.asserts:
|
||||
Report.info(f"Assert: {assert_info.filename} {assert_info.function} | {assert_info.message}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from editor_python_test_tools.utils import Report
|
||||
Report.start_test(AtomGPU_LightComponent_SpotLightScreenshotsMatchGoldenImages)
|
||||
+112
-8
@@ -25,7 +25,7 @@ class EditorComponent:
|
||||
"""
|
||||
EditorComponent class used to set and get the component property value using path
|
||||
EditorComponent object is returned from either of
|
||||
EditorEntity.add_component() or Entity.add_components() or EditorEntity.get_component_objects()
|
||||
EditorEntity.add_component() or Entity.add_components() or EditorEntity.get_components_of_type()
|
||||
which also assigns self.id and self.type_id to the EditorComponent object.
|
||||
"""
|
||||
|
||||
@@ -94,6 +94,13 @@ class EditorComponent:
|
||||
"""
|
||||
return editor.EditorComponentAPIBus(bus.Broadcast, "IsComponentEnabled", self.id)
|
||||
|
||||
def disable_component(self):
|
||||
"""
|
||||
Used to disable the component using its id value.
|
||||
:return: None
|
||||
"""
|
||||
editor.EditorComponentAPIBus(bus.Broadcast, "DisableComponents", [self.id])
|
||||
|
||||
@staticmethod
|
||||
def get_type_ids(component_names: list) -> list:
|
||||
"""
|
||||
@@ -107,7 +114,6 @@ class EditorComponent:
|
||||
return type_ids
|
||||
|
||||
|
||||
|
||||
def convert_to_azvector3(xyz) -> azlmbr.math.Vector3:
|
||||
"""
|
||||
Converts a vector3-like element into a azlmbr.math.Vector3
|
||||
@@ -120,6 +126,7 @@ def convert_to_azvector3(xyz) -> azlmbr.math.Vector3:
|
||||
else:
|
||||
raise ValueError("vector must be a 3 element list/tuple or azlmbr.math.Vector3")
|
||||
|
||||
|
||||
class EditorEntity:
|
||||
"""
|
||||
Entity class is used to create and interact with Editor Entities.
|
||||
@@ -136,10 +143,11 @@ class EditorEntity:
|
||||
|
||||
# Creation functions
|
||||
@classmethod
|
||||
def find_editor_entity(cls, entity_name: str, must_be_unique : bool = False) -> EditorEntity:
|
||||
def find_editor_entity(cls, entity_name: str, must_be_unique: bool = False) -> EditorEntity:
|
||||
"""
|
||||
Given Entity name, outputs entity object
|
||||
:param entity_name: Name of entity to find
|
||||
:param must_be_unique: bool that asserts the entity_name specified is unique when set to True
|
||||
:return: EditorEntity class object
|
||||
"""
|
||||
entities = cls.find_editor_entities([entity_name])
|
||||
@@ -147,14 +155,14 @@ class EditorEntity:
|
||||
if must_be_unique:
|
||||
assert len(entities) == 1, f"Failure: Multiple entities with name: '{entity_name}' when expected only one"
|
||||
|
||||
entity = cls(entities[0])
|
||||
entity = entities[0]
|
||||
return entity
|
||||
|
||||
@classmethod
|
||||
def find_editor_entities(cls, entity_names: List[str]) -> EditorEntity:
|
||||
def find_editor_entities(cls, entity_names: List[str]) -> List[EditorEntity]:
|
||||
"""
|
||||
Given Entities names, returns a list of EditorEntity
|
||||
:param entity_name: Name of entity to find
|
||||
:param entity_names: List of entity names to find
|
||||
:return: List[EditorEntity] class object
|
||||
"""
|
||||
searchFilter = azlmbr.entity.SearchFilter()
|
||||
@@ -438,7 +446,7 @@ class EditorEntity:
|
||||
def set_local_rotation(self, new_rotation) -> None:
|
||||
"""
|
||||
Sets the set the local rotation(relative to the parent) of the current entity.
|
||||
:param vector3_rotation: The math.Vector3 value to use for rotation on the entity (uses radians).
|
||||
:param new_rotation: The math.Vector3 value to use for rotation on the entity (uses radians).
|
||||
:return: None
|
||||
"""
|
||||
new_rotation = convert_to_azvector3(new_rotation)
|
||||
@@ -454,7 +462,7 @@ class EditorEntity:
|
||||
def set_local_translation(self, new_translation) -> None:
|
||||
"""
|
||||
Sets the local translation(relative to the parent) of the current entity.
|
||||
:param vector3_translation: The math.Vector3 value to use for translation on the entity.
|
||||
:param new_translation: The math.Vector3 value to use for translation on the entity.
|
||||
:return: None
|
||||
"""
|
||||
new_translation = convert_to_azvector3(new_translation)
|
||||
@@ -470,3 +478,99 @@ class EditorEntity:
|
||||
assert self.id.isValid(), "A valid entity id is required to focus on its owning prefab."
|
||||
focus_prefab_result = azlmbr.prefab.PrefabFocusPublicRequestBus(bus.Broadcast, "FocusOnOwningPrefab", self.id)
|
||||
assert focus_prefab_result.IsSuccess(), f"Prefab operation 'FocusOnOwningPrefab' failed. Error: {focus_prefab_result.GetError()}"
|
||||
|
||||
|
||||
class EditorLevelEntity:
|
||||
"""
|
||||
EditorLevel class used to add and fetch level components.
|
||||
Level entity is a special entity that you do not create/destroy independently of larger systems of level creation.
|
||||
This collects a number of staticmethods that do not rely on entityId since Level entity is found internally by
|
||||
EditorLevelComponentAPIBus requests.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def get_type_ids(component_names: list) -> list:
|
||||
"""
|
||||
Used to get type ids of given components list for EntityType Level
|
||||
:param: component_names: List of components to get type ids
|
||||
:return: List of type ids of given components.
|
||||
"""
|
||||
type_ids = editor.EditorComponentAPIBus(
|
||||
bus.Broadcast, "FindComponentTypeIdsByEntityType", component_names, azlmbr.entity.EntityType().Level
|
||||
)
|
||||
return type_ids
|
||||
|
||||
@staticmethod
|
||||
def add_component(component_name: str) -> EditorComponent:
|
||||
"""
|
||||
Used to add new component to Level.
|
||||
:param component_name: String of component name to add.
|
||||
:return: Component object of newly added component.
|
||||
"""
|
||||
component = EditorLevelEntity.add_components([component_name])[0]
|
||||
return component
|
||||
|
||||
@staticmethod
|
||||
def add_components(component_names: list) -> List[EditorComponent]:
|
||||
"""
|
||||
Used to add multiple components
|
||||
:param: component_names: List of components to add to level
|
||||
:return: List of newly added components to the level
|
||||
"""
|
||||
components = []
|
||||
type_ids = EditorLevelEntity.get_type_ids(component_names)
|
||||
for type_id in type_ids:
|
||||
new_comp = EditorComponent()
|
||||
new_comp.type_id = type_id
|
||||
add_component_outcome = editor.EditorLevelComponentAPIBus(
|
||||
bus.Broadcast, "AddComponentsOfType", [type_id]
|
||||
)
|
||||
assert (
|
||||
add_component_outcome.IsSuccess()
|
||||
), f"Failure: Could not add component: '{new_comp.get_component_name()}' to level"
|
||||
new_comp.id = add_component_outcome.GetValue()[0]
|
||||
components.append(new_comp)
|
||||
return components
|
||||
|
||||
@staticmethod
|
||||
def get_components_of_type(component_names: list) -> List[EditorComponent]:
|
||||
"""
|
||||
Used to get components of type component_name that already exists on the level
|
||||
:param component_names: List of names of components to check
|
||||
:return: List of Level Component objects of given component name
|
||||
"""
|
||||
component_list = []
|
||||
type_ids = EditorLevelEntity.get_type_ids(component_names)
|
||||
for type_id in type_ids:
|
||||
component = EditorComponent()
|
||||
component.type_id = type_id
|
||||
get_component_of_type_outcome = editor.EditorLevelComponentAPIBus(
|
||||
bus.Broadcast, "GetComponentOfType", type_id
|
||||
)
|
||||
assert (
|
||||
get_component_of_type_outcome.IsSuccess()
|
||||
), f"Failure: Level does not have component:'{component.get_component_name()}'"
|
||||
component.id = get_component_of_type_outcome.GetValue()
|
||||
component_list.append(component)
|
||||
|
||||
return component_list
|
||||
|
||||
@staticmethod
|
||||
def has_component(component_name: str) -> bool:
|
||||
"""
|
||||
Used to verify if the level has the specified component
|
||||
:param component_name: Name of component to check for
|
||||
:return: True, if level has specified component. Else, False
|
||||
"""
|
||||
type_ids = EditorLevelEntity.get_type_ids([component_name])
|
||||
return editor.EditorLevelComponentAPIBus(bus.Broadcast, "HasComponentOfType", type_ids[0])
|
||||
|
||||
@staticmethod
|
||||
def count_components_of_type(component_name: str) -> int:
|
||||
"""
|
||||
Used to get a count of the specified level component attached to the level
|
||||
:param component_name: Name of component to check for
|
||||
:return: integer count of occurences of level component attached to level or zero if none are present
|
||||
"""
|
||||
type_ids = EditorLevelEntity.get_type_ids([component_name])
|
||||
return editor.EditorLevelComponentAPIBus(bus.Broadcast, "CountComponentsOfType", type_ids[0])
|
||||
|
||||
+2
-4
@@ -88,8 +88,7 @@ class TestHelper:
|
||||
general.idle_wait_frames(200)
|
||||
|
||||
@staticmethod
|
||||
def enter_game_mode(msgtuple_success_fail : Tuple[str, str]):
|
||||
# type: (tuple) -> None
|
||||
def enter_game_mode(msgtuple_success_fail: Tuple[str, str]) -> None:
|
||||
"""
|
||||
:param msgtuple_success_fail: The tuple with the expected/unexpected messages for entering game mode.
|
||||
|
||||
@@ -102,8 +101,7 @@ class TestHelper:
|
||||
Report.critical_result(msgtuple_success_fail, general.is_in_game_mode())
|
||||
|
||||
@staticmethod
|
||||
def multiplayer_enter_game_mode(msgtuple_success_fail : Tuple[str, str], sv_default_player_spawn_asset : str):
|
||||
# type: (tuple) -> None
|
||||
def multiplayer_enter_game_mode(msgtuple_success_fail: Tuple[str, str], sv_default_player_spawn_asset: str) -> None:
|
||||
"""
|
||||
:param msgtuple_success_fail: The tuple with the expected/unexpected messages for entering game mode.
|
||||
:param sv_default_player_spawn_asset: The path to the network player prefab that will be automatically spawned upon entering gamemode. The engine default is "prefabs/player.network.spawnable"
|
||||
|
||||
@@ -98,38 +98,32 @@ class FileManagement:
|
||||
"""
|
||||
file_map = FileManagement._load_file_map()
|
||||
backup_path = FileManagement.backup_folder_path
|
||||
backup_file_name = "{}.bak".format(file_name)
|
||||
backup_file = os.path.join(backup_path, backup_file_name)
|
||||
# If backup directory DNE, make one
|
||||
if not os.path.exists(backup_path):
|
||||
os.mkdir(backup_path)
|
||||
# If "traditional" backup file exists, delete it (myFile.txt.bak)
|
||||
if os.path.exists(backup_file):
|
||||
fs.delete([backup_file], True, False)
|
||||
# Find my next storage name (myFile_1.txt.bak)
|
||||
backup_storage_file_name = FileManagement._next_available_name(backup_file_name, file_map)
|
||||
if backup_storage_file_name is None:
|
||||
|
||||
# Find my next storage name (myFile_1.txt)
|
||||
backup_file_name = FileManagement._next_available_name(file_name, file_map)
|
||||
if backup_file_name is None:
|
||||
# If _next_available_name returns None, we have backed up MAX_BACKUPS of files name [file_name]
|
||||
raise Exception(
|
||||
"FileManagement class ran out of backups per name. Max: {}".format(FileManagement.MAX_BACKUPS)
|
||||
)
|
||||
backup_storage_file = os.path.join(backup_path, backup_storage_file_name)
|
||||
|
||||
# If this backup file already exists, delete it.
|
||||
backup_storage_file = "{}.bak".format(os.path.normpath(os.path.join(backup_path, backup_file_name)))
|
||||
if os.path.exists(backup_storage_file):
|
||||
# This file should not exists, but if it does it's about to get clobbered!
|
||||
fs.unlock_file(backup_storage_file)
|
||||
# Create "traditional" backup file (myFile.txt.bak)
|
||||
fs.create_backup(os.path.join(file_path, file_name), backup_path)
|
||||
# Copy "traditional" backup file into storage backup (myFile_1.txt.bak)
|
||||
FileManagement._copy_file(backup_file_name, backup_path, backup_storage_file_name, backup_path)
|
||||
fs.lock_file(backup_storage_file)
|
||||
# Delete "traditional" back up file
|
||||
fs.unlock_file(backup_file)
|
||||
fs.delete([backup_file], True, False)
|
||||
fs.delete([backup_storage_file], True, False)
|
||||
|
||||
# Create backup file (myFile_1.txt.bak)
|
||||
original_file = os.path.normpath(os.path.join(file_path, file_name))
|
||||
fs.create_backup(original_file, backup_path, backup_file_name)
|
||||
|
||||
# Update file map with new file
|
||||
file_map[os.path.join(file_path, file_name)] = backup_storage_file_name
|
||||
file_map[original_file] = backup_file_name
|
||||
FileManagement._save_file_map(file_map)
|
||||
# Unlock original file to get it ready to be edited by the test
|
||||
fs.unlock_file(os.path.join(file_path, file_name))
|
||||
fs.unlock_file(original_file)
|
||||
|
||||
@staticmethod
|
||||
def _restore_file(file_name, file_path):
|
||||
@@ -143,20 +137,15 @@ class FileManagement:
|
||||
"""
|
||||
file_map = FileManagement._load_file_map()
|
||||
backup_path = FileManagement.backup_folder_path
|
||||
src_file = os.path.join(file_path, file_name)
|
||||
src_file = os.path.normpath(os.path.join(file_path, file_name))
|
||||
if src_file in file_map:
|
||||
backup_file = os.path.join(backup_path, file_map[src_file])
|
||||
if os.path.exists(backup_file):
|
||||
fs.unlock_file(backup_file)
|
||||
fs.unlock_file(src_file)
|
||||
# Make temporary copy of backed up file to restore from
|
||||
temp_file = "{}.bak".format(file_name)
|
||||
FileManagement._copy_file(file_map[src_file], backup_path, temp_file, backup_path)
|
||||
fs.restore_backup(src_file, backup_path)
|
||||
fs.lock_file(src_file)
|
||||
# Delete backup file
|
||||
fs.delete([os.path.join(backup_path, temp_file)], True, False)
|
||||
backup_file_name = file_map[src_file]
|
||||
backup_file = "{}.bak".format(os.path.join(backup_path, backup_file_name))
|
||||
|
||||
fs.unlock_file(src_file)
|
||||
if fs.restore_backup(src_file, backup_path, backup_file_name):
|
||||
fs.delete([backup_file], True, False)
|
||||
|
||||
# Remove from file map
|
||||
del file_map[src_file]
|
||||
FileManagement._save_file_map(file_map)
|
||||
|
||||
@@ -12,7 +12,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS)
|
||||
NAME AutomatedTesting::PrefabTests
|
||||
TEST_SUITE main
|
||||
TEST_SERIAL
|
||||
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main.py
|
||||
PATH ${CMAKE_CURRENT_LIST_DIR}/TestSuite_Main_Optimized.py
|
||||
RUNTIME_DEPENDENCIES
|
||||
Legacy::Editor
|
||||
AZ::AssetProcessor
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
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 EditorSingleTest, EditorSharedTest, EditorParallelTest, EditorTestSuite
|
||||
|
||||
|
||||
@pytest.mark.SUITE_main
|
||||
@pytest.mark.parametrize("launcher_platform", ['windows_editor'])
|
||||
@pytest.mark.parametrize("project", ["AutomatedTesting"])
|
||||
class TestAutomationNoAutoTestMode(EditorTestSuite):
|
||||
|
||||
# Enable only -BatchMode for these tests. Some tests cannot run in -autotest_mode due to UI interactions
|
||||
global_extra_cmdline_args = ["-BatchMode"]
|
||||
|
||||
class test_CreatePrefab_UnderAnEntity(EditorSharedTest):
|
||||
from .tests.create_prefab import CreatePrefab_UnderAnEntity as test_module
|
||||
|
||||
class test_CreatePrefab_UnderAnotherPrefab(EditorSharedTest):
|
||||
from .tests.create_prefab import CreatePrefab_UnderAnotherPrefab as test_module
|
||||
|
||||
class test_DeleteEntity_UnderAnotherPrefab(EditorSharedTest):
|
||||
from .tests.delete_entity import DeleteEntity_UnderAnotherPrefab as test_module
|
||||
|
||||
class test_DeleteEntity_UnderLevelPrefab(EditorSharedTest):
|
||||
from .tests.delete_entity import DeleteEntity_UnderLevelPrefab as test_module
|
||||
|
||||
class test_ReparentPrefab_UnderAnotherPrefab(EditorSharedTest):
|
||||
from .tests.reparent_prefab import ReparentPrefab_UnderAnotherPrefab as test_module
|
||||
|
||||
class test_DetachPrefab_UnderAnotherPrefab(EditorSharedTest):
|
||||
from .tests.detach_prefab import DetachPrefab_UnderAnotherPrefab as test_module
|
||||
|
||||
class test_OpenLevel_ContainingTwoEntities(EditorSharedTest):
|
||||
from .tests.open_level import OpenLevel_ContainingTwoEntities as test_module
|
||||
|
||||
class test_CreatePrefab_WithSingleEntity(EditorSharedTest):
|
||||
from .tests.create_prefab import CreatePrefab_WithSingleEntity as test_module
|
||||
|
||||
class test_InstantiatePrefab_ContainingASingleEntity(EditorSharedTest):
|
||||
from .tests.instantiate_prefab import InstantiatePrefab_ContainingASingleEntity as test_module
|
||||
|
||||
class test_DeletePrefab_ContainingASingleEntity(EditorSharedTest):
|
||||
from .tests.delete_prefab import DeletePrefab_ContainingASingleEntity as test_module
|
||||
|
||||
class test_DuplicatePrefab_ContainingASingleEntity(EditorSharedTest):
|
||||
from .tests.duplicate_prefab import DuplicatePrefab_ContainingASingleEntity as test_module
|
||||
+1
@@ -24,6 +24,7 @@ def CreatePrefab_WithSingleEntity():
|
||||
# Creates a prefab from the new entity
|
||||
Prefab.create_prefab(car_prefab_entities, CAR_PREFAB_FILE_NAME)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from editor_python_test_tools.utils import Report
|
||||
Report.start_test(CreatePrefab_WithSingleEntity)
|
||||
|
||||
+2
-2
@@ -7,8 +7,8 @@ SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
def DetachPrefab_UnderAnotherPrefab():
|
||||
|
||||
CAR_PREFAB_FILE_NAME = 'car_prefab'
|
||||
WHEEL_PREFAB_FILE_NAME = 'wheel_prefab'
|
||||
CAR_PREFAB_FILE_NAME = 'car_prefab2'
|
||||
WHEEL_PREFAB_FILE_NAME = 'wheel_prefab2'
|
||||
|
||||
import editor_python_test_tools.pyside_utils as pyside_utils
|
||||
|
||||
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
"""
|
||||
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
|
||||
"""
|
||||
|
||||
class MacroMaterialTests:
|
||||
setup_test = (
|
||||
"Setup successful",
|
||||
"Setup failed"
|
||||
)
|
||||
material_changed_not_called_when_inactive = (
|
||||
"OnTerrainMacroMaterialRegionChanged not called successfully",
|
||||
"OnTerrainMacroMaterialRegionChanged called when component inactive."
|
||||
)
|
||||
material_created = (
|
||||
"MaterialCreated called successfully",
|
||||
"MaterialCreated failed"
|
||||
)
|
||||
material_destroyed = (
|
||||
"MaterialDestroyed called successfully",
|
||||
"MaterialDestroyed failed"
|
||||
)
|
||||
material_recreated = (
|
||||
"MaterialCreated called successfully on second test",
|
||||
"MaterialCreated failed on second test"
|
||||
)
|
||||
material_changed_call_on_aabb_change = (
|
||||
"OnTerrainMacroMaterialRegionChanged called successfully",
|
||||
"Timed out waiting for OnTerrainMacroMaterialRegionChanged"
|
||||
)
|
||||
|
||||
def TerrainMacroMaterialComponent_MacroMaterialActivates():
|
||||
"""
|
||||
Summary:
|
||||
Load an empty level, create a MacroMaterialComponent and check assigning textures results in the correct callbacks.
|
||||
:return: None
|
||||
"""
|
||||
|
||||
import os
|
||||
import math as sys_math
|
||||
|
||||
import azlmbr.legacy.general as general
|
||||
import azlmbr.asset as asset
|
||||
import azlmbr.bus as bus
|
||||
import azlmbr.math as math
|
||||
import azlmbr.terrain as terrain
|
||||
import azlmbr.editor as editor
|
||||
import azlmbr.vegetation as vegetation
|
||||
import azlmbr.entity as EntityId
|
||||
|
||||
import editor_python_test_tools.hydra_editor_utils as hydra
|
||||
from editor_python_test_tools.utils import Report
|
||||
from editor_python_test_tools.utils import TestHelper as helper
|
||||
import editor_python_test_tools.pyside_utils as pyside_utils
|
||||
from editor_python_test_tools.editor_entity_utils import EditorEntity
|
||||
from editor_python_test_tools.asset_utils import Asset
|
||||
|
||||
material_created_called = False
|
||||
material_changed_called = False
|
||||
material_region_changed_called = False
|
||||
material_destroyed_called = False
|
||||
|
||||
def create_entity_at(entity_name, components_to_add, x, y, z):
|
||||
entity = EditorEntity.create_editor_entity_at([x, y, z], entity_name)
|
||||
for component in components_to_add:
|
||||
entity.add_component(component)
|
||||
|
||||
return entity
|
||||
|
||||
def on_macro_material_created(args):
|
||||
nonlocal material_created_called
|
||||
material_created_called = True
|
||||
|
||||
def on_macro_material_changed(args):
|
||||
nonlocal material_changed_called
|
||||
material_changed_called = True
|
||||
|
||||
def on_macro_material_region_changed(args):
|
||||
nonlocal material_region_changed_called
|
||||
material_region_changed_called = True
|
||||
|
||||
def on_macro_material_destroyed(args):
|
||||
nonlocal material_destroyed_called
|
||||
material_destroyed_called = True
|
||||
|
||||
helper.init_idle()
|
||||
|
||||
# Open a level.
|
||||
helper.open_level("Physics", "Base")
|
||||
helper.wait_for_condition(lambda: general.get_current_level_name() == "Base", 2.0)
|
||||
|
||||
general.idle_wait_frames(1)
|
||||
|
||||
# Set up a handler to wait for notifications from the TerrainSystem.
|
||||
handler = terrain.TerrainMacroMaterialAutomationBusHandler()
|
||||
handler.connect()
|
||||
handler.add_callback("OnTerrainMacroMaterialCreated", on_macro_material_created)
|
||||
handler.add_callback("OnTerrainMacroMaterialChanged", on_macro_material_changed)
|
||||
handler.add_callback("OnTerrainMacroMaterialRegionChanged", on_macro_material_region_changed)
|
||||
handler.add_callback("OnTerrainMacroMaterialDestroyed", on_macro_material_destroyed)
|
||||
|
||||
macro_material_entity = create_entity_at("macro", ["Terrain Macro Material", "Axis Aligned Box Shape"], 0.0, 0.0, 0.0)
|
||||
|
||||
# Check that no macro material callbacks happened. It should be "inactive" as it has no assets assigned.
|
||||
setup_success = not material_created_called and not material_changed_called and not material_region_changed_called and not material_destroyed_called
|
||||
Report.result(MacroMaterialTests.setup_test, setup_success)
|
||||
|
||||
# Find the aabb component.
|
||||
aabb_component_type_id_type = azlmbr.editor.EditorComponentAPIBus(azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Axis Aligned Box Shape"], 0)[0]
|
||||
aabb_component_id = azlmbr.editor.EditorComponentAPIBus(azlmbr.bus.Broadcast, 'GetComponentOfType', macro_material_entity.id, aabb_component_type_id_type).GetValue()
|
||||
|
||||
# Change the aabb dimensions
|
||||
material_region_changed_called = False
|
||||
box_dimensions_path = "Axis Aligned Box Shape|Box Configuration|Dimensions"
|
||||
editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", aabb_component_id, box_dimensions_path, math.Vector3(1.0, 1.0, 1.0))
|
||||
|
||||
# Check we don't receive a callback. The macro material component should be inactive as it has no images assigned.
|
||||
general.idle_wait_frames(1)
|
||||
Report.result(MacroMaterialTests.material_changed_not_called_when_inactive, material_region_changed_called == False)
|
||||
|
||||
# Find the macro material component.
|
||||
macro_material_id_type = azlmbr.editor.EditorComponentAPIBus(azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Terrain Macro Material"], 0)[0]
|
||||
macro_material_component_id = azlmbr.editor.EditorComponentAPIBus(azlmbr.bus.Broadcast, 'GetComponentOfType', macro_material_entity.id, macro_material_id_type).GetValue()
|
||||
|
||||
# Find a color image asset.
|
||||
color_image_path = os.path.join("assets", "textures", "image.png.streamingimage")
|
||||
color_image_asset = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", color_image_path, math.Uuid(), False)
|
||||
|
||||
# Assign the image to the MacroMaterial component, which should result in a created message.
|
||||
material_created_called = False
|
||||
color_texture_path = "Configuration|Color Texture"
|
||||
editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", macro_material_component_id, color_texture_path, color_image_asset)
|
||||
|
||||
call_result = helper.wait_for_condition(lambda: material_created_called == True, 2.0)
|
||||
Report.result(MacroMaterialTests.material_created, call_result)
|
||||
|
||||
# Find a normal image asset.
|
||||
normal_image_path = os.path.join("assets", "textures", "normal.png.streamingimage")
|
||||
normal_image_asset = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", normal_image_path, math.Uuid(), False)
|
||||
|
||||
# Assign the normal image to the MacroMaterial component, which should result in a created message.
|
||||
material_created_called = False
|
||||
material_destroyed_called = False
|
||||
normal_texture_path = "Configuration|Normal Texture"
|
||||
editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", macro_material_component_id, normal_texture_path, normal_image_asset)
|
||||
|
||||
# Check the MacroMaterial was destroyed and recreated.
|
||||
destroyed_call_result = helper.wait_for_condition(lambda: material_destroyed_called == True, 2.0)
|
||||
Report.result(MacroMaterialTests.material_destroyed, destroyed_call_result)
|
||||
|
||||
recreated_call_result = helper.wait_for_condition(lambda: material_created_called == True, 2.0)
|
||||
Report.result(MacroMaterialTests.material_recreated, recreated_call_result)
|
||||
|
||||
# Change the aabb dimensions.
|
||||
box_dimensions_path = "Axis Aligned Box Shape|Box Configuration|Dimensions"
|
||||
editor.EditorComponentAPIBus(bus.Broadcast, "SetComponentProperty", aabb_component_id, box_dimensions_path, math.Vector3(1.0, 1.0, 1.0))
|
||||
|
||||
# Check that a callback is received.
|
||||
region_changed_call_result = helper.wait_for_condition(lambda: material_region_changed_called == True, 2.0)
|
||||
Report.result(MacroMaterialTests.material_changed_call_on_aabb_change, region_changed_call_result)
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
from editor_python_test_tools.utils import Report
|
||||
Report.start_test(TerrainMacroMaterialComponent_MacroMaterialActivates)
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
"""
|
||||
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
|
||||
"""
|
||||
|
||||
class VegetationTests:
|
||||
vegetation_on_gradient_1 = (
|
||||
"Vegetation detected at correct position on Gradient1",
|
||||
"Vegetation not detected at correct position on Gradient1"
|
||||
)
|
||||
vegetation_on_gradient_2 = (
|
||||
"Vegetation detected at correct position on Gradient2",
|
||||
"Vegetation not detected at correct position on Gradient2"
|
||||
)
|
||||
unfiltered_vegetation_count_correct = (
|
||||
"Unfiltered vegetation spawn count correct",
|
||||
"Unfiltered vegetation spawn count incorrect"
|
||||
)
|
||||
|
||||
testTag2_excluded_vegetation_count_correct = (
|
||||
"TestTag2 filtered vegetation count correct",
|
||||
"TestTag2 filtered vegetation count incorrect"
|
||||
)
|
||||
testTag2_excluded_vegetation_z_correct = (
|
||||
"TestTag2 filtered vegetation spawned in correct position",
|
||||
"TestTag2 filtered vegetation failed to spawn in correct position"
|
||||
)
|
||||
|
||||
testTag3_excluded_vegetation_count_correct = (
|
||||
"TestTag3 filtered vegetation count correct",
|
||||
"TestTag3 filtered vegetation count incorrect"
|
||||
)
|
||||
testTag3_excluded_vegetation_z_correct = (
|
||||
"TestTag3 filtered vegetation spawned in correct position",
|
||||
"TestTag3 filtered vegetation failed to spawn in correct position"
|
||||
)
|
||||
|
||||
cleared_exclusion_vegetation_count_correct = (
|
||||
"Cleared filter vegetation count correct",
|
||||
"Cleared filter vegetation count incorrect"
|
||||
)
|
||||
|
||||
def TerrainSystem_VegetationSpawnsOnTerrainSurfaces():
|
||||
"""
|
||||
Summary:
|
||||
Load an empty level,
|
||||
Create two entities with constant gradient components with different values.
|
||||
Create two entities with TerrainLayerSpawners
|
||||
Create an entity to spawn vegetation
|
||||
Ensure that vegetation spawns at the correct heights
|
||||
Add a VegetationSurfaceMaskFilter and ensure it responds correctly to surface changes.
|
||||
:return: None
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import math as sys_math
|
||||
|
||||
import azlmbr.legacy.general as general
|
||||
import azlmbr.bus as bus
|
||||
import azlmbr.math as math
|
||||
|
||||
import azlmbr.areasystem as areasystem
|
||||
import azlmbr.editor as editor
|
||||
import azlmbr.vegetation as vegetation
|
||||
import azlmbr.terrain as terrain
|
||||
import azlmbr.entity as EntityId
|
||||
import azlmbr.surface_data as surface_data
|
||||
|
||||
import editor_python_test_tools.hydra_editor_utils as hydra
|
||||
from editor_python_test_tools.utils import Report
|
||||
from editor_python_test_tools.utils import TestHelper as helper
|
||||
|
||||
def create_entity_at(entity_name, components_to_add, x, y, z):
|
||||
entity = hydra.Entity(entity_name)
|
||||
entity.create_entity(math.Vector3(x, y, z), components_to_add)
|
||||
|
||||
return entity
|
||||
|
||||
def FindHighestAndLowestZValuesInArea(aabb):
|
||||
vegetation_items = areasystem.AreaSystemRequestBus(bus.Broadcast, 'GetInstancesInAabb', aabb)
|
||||
|
||||
lowest_z = min([item.position.z for item in vegetation_items])
|
||||
highest_z = max([item.position.z for item in vegetation_items])
|
||||
|
||||
return highest_z, lowest_z
|
||||
|
||||
helper.init_idle()
|
||||
|
||||
# Open an empty level.
|
||||
helper.open_level("Physics", "Base")
|
||||
helper.wait_for_condition(lambda: general.get_current_level_name() == "Base", 2.0)
|
||||
|
||||
general.idle_wait_frames(1)
|
||||
|
||||
box_height = 20.0
|
||||
box_y_position = 10.0
|
||||
box_dimensions = math.Vector3(20.0, 20.0, box_height)
|
||||
|
||||
# Add Terrain Rendering
|
||||
hydra.add_level_component("Terrain World")
|
||||
hydra.add_level_component("Terrain World Renderer")
|
||||
|
||||
# Create two terrain entities at adjoining positions
|
||||
terrain_entity_1 = create_entity_at("Terrain1", ["Terrain Layer Spawner", "Axis Aligned Box Shape", "Terrain Height Gradient List", "Terrain Surface Gradient List"], 0.0, box_y_position, box_height/2.0)
|
||||
terrain_entity_1.get_set_test(1, "Axis Aligned Box Shape|Box Configuration|Dimensions", box_dimensions)
|
||||
|
||||
terrain_entity_2 = create_entity_at("Terrain2", ["Terrain Layer Spawner", "Axis Aligned Box Shape", "Terrain Height Gradient List", "Terrain Surface Gradient List"], 20.0, box_y_position, box_height/2.0)
|
||||
terrain_entity_2.get_set_test(1, "Axis Aligned Box Shape|Box Configuration|Dimensions", box_dimensions)
|
||||
|
||||
# Create two gradient entities.
|
||||
gradient_value_1 = 0.25
|
||||
gradient_value_2 = 0.5
|
||||
|
||||
gradient_entity_1 = create_entity_at("Gradient1", ["Constant Gradient"], 0.0, 0.0, 0.0)
|
||||
gradient_entity_1.get_set_test(0, "Configuration|Value", gradient_value_1)
|
||||
|
||||
gradient_entity_2 = create_entity_at("Gradient2", ["Constant Gradient"], 0.0, 0.0, 0.0)
|
||||
gradient_entity_2.get_set_test(0, "Configuration|Value", gradient_value_2)
|
||||
|
||||
mapping = terrain.TerrainSurfaceGradientMapping()
|
||||
mapping.gradientEntityId = gradient_entity_1.id
|
||||
pte = hydra.get_property_tree(terrain_entity_1.components[3])
|
||||
pte.add_container_item("Configuration|Gradient to Surface Mappings", 0, mapping)
|
||||
|
||||
mapping = terrain.TerrainSurfaceGradientMapping()
|
||||
mapping.gradientEntityId = gradient_entity_2.id
|
||||
pte = hydra.get_property_tree(terrain_entity_2.components[3])
|
||||
pte.add_container_item("Configuration|Gradient to Surface Mappings", 0, mapping)
|
||||
|
||||
# create a vegetation entity that overlaps both terrain entities.
|
||||
vegetation_entity = create_entity_at("Vegetation", ["Vegetation Layer Spawner", "Axis Aligned Box Shape", "Vegetation Asset List", "Vegetation Surface Mask Filter"], 10.0, box_y_position, box_height/2.0)
|
||||
vegetation_entity.get_set_test(1, "Axis Aligned Box Shape|Box Configuration|Dimensions", box_dimensions)
|
||||
|
||||
# Set the vegetation area to a PrefabInstanceSpawner with a specific prefab asset selected.
|
||||
prefab_spawner = vegetation.PrefabInstanceSpawner()
|
||||
prefab_spawner.SetPrefabAssetPath(os.path.join("Prefabs", "PinkFlower.spawnable"))
|
||||
descriptor = hydra.get_component_property_value(vegetation_entity.components[2], 'Configuration|Embedded Assets|[0]')
|
||||
descriptor.spawner = prefab_spawner
|
||||
vegetation_entity.get_set_test(2, "Configuration|Embedded Assets|[0]", descriptor)
|
||||
|
||||
# Assign gradients to layer spawners.
|
||||
terrain_entity_1.get_set_test(2, "Configuration|Gradient Entities", [gradient_entity_1.id])
|
||||
terrain_entity_2.get_set_test(2, "Configuration|Gradient Entities", [gradient_entity_2.id])
|
||||
|
||||
# Move view so that the entities are visible.
|
||||
general.set_current_view_position(17.0, -66.0, 41.0)
|
||||
general.set_current_view_rotation(-15, 0, 0)
|
||||
|
||||
# Expected item counts under conditions to be tested.
|
||||
# By default, vegetation spawns at a density of 20 items per 16 meters,
|
||||
# so in a 20m square, there should be around 25 ^ 2 items depending on whether area edges are included.
|
||||
# In this case there are 26 ^ 2 items.
|
||||
expected_surface_tag_excluded_item_count = 338
|
||||
expected_no_exclusions_item_count = 676
|
||||
|
||||
# Wait for the vegetation to spawn
|
||||
helper.wait_for_condition(lambda: vegetation.VegetationSpawnerRequestBus(bus.Event, "GetAreaProductCount", vegetation_entity.id) == expected_no_exclusions_item_count, 5.0)
|
||||
|
||||
# Check the spawn count is correct.
|
||||
item_count = vegetation.VegetationSpawnerRequestBus(bus.Event, "GetAreaProductCount", vegetation_entity.id)
|
||||
Report.result(VegetationTests.unfiltered_vegetation_count_correct, item_count == expected_no_exclusions_item_count)
|
||||
|
||||
test_aabb = math.Aabb_CreateFromMinMax(math.Vector3(-10.0, -10.0, 0.0), math.Vector3(30.0, 10.0, box_height))
|
||||
|
||||
# Find the z positions of the items with the lowest and highest x values, this will avoid the overlap area where z values are blended between the surface heights.
|
||||
highest_z, lowest_z = FindHighestAndLowestZValuesInArea(test_aabb)
|
||||
|
||||
# Check that the z values are as expected.
|
||||
Report.result(VegetationTests.vegetation_on_gradient_1, sys_math.isclose(lowest_z, box_height * gradient_value_1, abs_tol=0.01))
|
||||
Report.result(VegetationTests.vegetation_on_gradient_2, sys_math.isclose(highest_z, box_height * gradient_value_2, abs_tol=0.01))
|
||||
|
||||
# Assign SurfaceTags to the SurfaceGradientLists
|
||||
terrain_entity_1.get_set_test(3, "Configuration|Gradient to Surface Mappings|[0]|Surface Tag", surface_data.SurfaceTag("test_tag2"))
|
||||
terrain_entity_2.get_set_test(3, "Configuration|Gradient to Surface Mappings|[0]|Surface Tag", surface_data.SurfaceTag("test_tag3"))
|
||||
|
||||
# Give the VegetationSurfaceFilter an exclusion list, set it to exclude test_tag2 which should remove all the lower items which are in terrain_entity_1.
|
||||
vegetation_entity.get_set_test(3, "Configuration|Exclusion|Surface Tags", [surface_data.SurfaceTag()])
|
||||
vegetation_entity.get_set_test(3, "Configuration|Exclusion|Surface Tags|[0]", surface_data.SurfaceTag("test_tag2"))
|
||||
|
||||
# Wait for the vegetation to respawn and check z values.
|
||||
helper.wait_for_condition(lambda: vegetation.VegetationSpawnerRequestBus(bus.Event, "GetAreaProductCount", vegetation_entity.id) == expected_surface_tag_excluded_item_count, 5.0)
|
||||
|
||||
item_count = vegetation.VegetationSpawnerRequestBus(bus.Event, "GetAreaProductCount", vegetation_entity.id)
|
||||
Report.result(VegetationTests.testTag2_excluded_vegetation_count_correct, item_count == expected_surface_tag_excluded_item_count)
|
||||
|
||||
highest_z, lowest_z = FindHighestAndLowestZValuesInArea(test_aabb)
|
||||
|
||||
Report.result(VegetationTests.testTag2_excluded_vegetation_z_correct, lowest_z > box_height * gradient_value_1)
|
||||
|
||||
# Clear the filter and ensure vegetation respawns.
|
||||
vegetation_entity.get_set_test(3, "Configuration|Exclusion|Surface Tags|[0]", surface_data.SurfaceTag("invalid"))
|
||||
helper.wait_for_condition(lambda: vegetation.VegetationSpawnerRequestBus(bus.Event, "GetAreaProductCount", vegetation_entity.id) == expected_no_exclusions_item_count, 5.0)
|
||||
|
||||
item_count = vegetation.VegetationSpawnerRequestBus(bus.Event, "GetAreaProductCount", vegetation_entity.id)
|
||||
Report.result(VegetationTests.cleared_exclusion_vegetation_count_correct, item_count == expected_no_exclusions_item_count)
|
||||
|
||||
# Exclude test_tag3 to exclude the higher items in terrain_entity_2 and recheck.
|
||||
vegetation_entity.get_set_test(3, "Configuration|Exclusion|Surface Tags|[0]", surface_data.SurfaceTag("test_tag3"))
|
||||
|
||||
helper.wait_for_condition(lambda: vegetation.VegetationSpawnerRequestBus(bus.Event, "GetAreaProductCount", vegetation_entity.id) == expected_surface_tag_excluded_item_count, 5.0)
|
||||
|
||||
item_count = vegetation.VegetationSpawnerRequestBus(bus.Event, "GetAreaProductCount", vegetation_entity.id)
|
||||
Report.result(VegetationTests.testTag3_excluded_vegetation_count_correct, item_count == expected_surface_tag_excluded_item_count)
|
||||
|
||||
highest_z, lowest_z = FindHighestAndLowestZValuesInArea(test_aabb)
|
||||
|
||||
Report.result(VegetationTests.testTag3_excluded_vegetation_z_correct, highest_z < box_height * gradient_value_2)
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
from editor_python_test_tools.utils import Report
|
||||
Report.start_test(TerrainSystem_VegetationSpawnsOnTerrainSurfaces)
|
||||
@@ -27,6 +27,12 @@ class TestAutomation(EditorTestSuite):
|
||||
|
||||
class test_Terrain_SupportsPhysics(EditorSharedTest):
|
||||
from .EditorScripts import Terrain_SupportsPhysics as test_module
|
||||
|
||||
|
||||
class test_TerrainHeightGradientList_AddRemoveGradientWorks(EditorSharedTest):
|
||||
from .EditorScripts import TerrainHeightGradientList_AddRemoveGradientWorks as test_module
|
||||
|
||||
class test_TerrainSystem_VegetationSpawnsOnTerrainSurfaces(EditorSharedTest):
|
||||
from .EditorScripts import TerrainSystem_VegetationSpawnsOnTerrainSurfaces as test_module
|
||||
|
||||
class test_TerrainMacroMaterialComponent_MacroMaterialActivates(EditorSharedTest):
|
||||
from .EditorScripts import TerrainMacroMaterialComponent_MacroMaterialActivates as test_module
|
||||
|
||||
@@ -8,7 +8,7 @@ SPDX-License-Identifier: Apache-2.0 OR MIT
|
||||
|
||||
import os
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
import pytest
|
||||
import time
|
||||
|
||||
@@ -128,7 +128,8 @@ class TestAutomationBase:
|
||||
errors.append(TestRunError("FAILED TEST", error_str))
|
||||
if return_code and return_code != TestAutomationBase.TEST_FAIL_RETCODE: # Crashed
|
||||
crash_info = "-- No crash log available --"
|
||||
crash_log = os.path.join(workspace.paths.project_log(), 'error.log')
|
||||
crash_log = workspace.paths.crash_log()
|
||||
|
||||
try:
|
||||
waiter.wait_for(lambda: os.path.exists(crash_log), timeout=TestAutomationBase.WAIT_FOR_CRASH_LOG)
|
||||
except AssertionError:
|
||||
|
||||
@@ -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
|
||||
*
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AzCore/DOM/Backends/JSON/JsonSerializationUtils.h>
|
||||
#include <AzCore/DOM/DomBackend.h>
|
||||
#include <AzCore/IO/ByteContainerStream.h>
|
||||
|
||||
namespace AZ::Dom
|
||||
{
|
||||
//! A DOM backend for serializing and deserializing JSON <=> UTF-8 text
|
||||
//! \param ParseFlags Controls how deserialized JSON is parsed.
|
||||
//! \param WriteFormat Controls how serialized JSON is formatted.
|
||||
template<
|
||||
Json::ParseFlags ParseFlags = Json::ParseFlags::ParseComments,
|
||||
Json::OutputFormatting WriteFormat = Json::OutputFormatting::PrettyPrintedJson>
|
||||
class JsonBackend final : public Backend
|
||||
{
|
||||
public:
|
||||
Visitor::Result ReadFromBuffer(const char* buffer, size_t size, AZ::Dom::Lifetime lifetime, Visitor& visitor) override
|
||||
{
|
||||
return Json::VisitSerializedJson<ParseFlags>({ buffer, size }, lifetime, visitor);
|
||||
}
|
||||
|
||||
Visitor::Result ReadFromBufferInPlace(char* buffer, [[maybe_unused]] AZStd::optional<size_t> size, Visitor& visitor) override
|
||||
{
|
||||
return Json::VisitSerializedJsonInPlace<ParseFlags>(buffer, visitor);
|
||||
}
|
||||
|
||||
Visitor::Result WriteToBuffer(AZStd::string& buffer, WriteCallback callback)
|
||||
{
|
||||
AZ::IO::ByteContainerStream<AZStd::string> stream{ &buffer };
|
||||
AZStd::unique_ptr<Visitor> visitor = Json::CreateJsonStreamWriter(stream, WriteFormat);
|
||||
return callback(*visitor);
|
||||
}
|
||||
};
|
||||
} // namespace AZ::Dom
|
||||
@@ -0,0 +1,582 @@
|
||||
/*
|
||||
* 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 <AzCore/DOM/Backends/JSON/JsonSerializationUtils.h>
|
||||
|
||||
#include <AzCore/IO/ByteContainerStream.h>
|
||||
#include <AzCore/IO/TextStreamWriters.h>
|
||||
#include <AzCore/JSON/filewritestream.h>
|
||||
#include <AzCore/JSON/memorystream.h>
|
||||
#include <AzCore/JSON/prettywriter.h>
|
||||
#include <AzCore/JSON/rapidjson.h>
|
||||
#include <AzCore/JSON/reader.h>
|
||||
#include <AzCore/JSON/writer.h>
|
||||
#include <AzCore/std/containers/stack.h>
|
||||
#include <AzCore/std/containers/variant.h>
|
||||
#include <AzCore/std/optional.h>
|
||||
|
||||
namespace AZ::Dom::Json
|
||||
{
|
||||
//
|
||||
// class RapidJsonValueWriter
|
||||
//
|
||||
RapidJsonValueWriter::RapidJsonValueWriter(rapidjson::Value& outputValue, rapidjson::Value::AllocatorType& allocator)
|
||||
: m_result(outputValue)
|
||||
, m_allocator(allocator)
|
||||
{
|
||||
}
|
||||
|
||||
VisitorFlags RapidJsonValueWriter::GetVisitorFlags() const
|
||||
{
|
||||
return VisitorFlags::SupportsRawKeys | VisitorFlags::SupportsArrays | VisitorFlags::SupportsObjects;
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::Null()
|
||||
{
|
||||
CurrentValue().SetNull();
|
||||
return FinishWrite();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::Bool(bool value)
|
||||
{
|
||||
CurrentValue().SetBool(value);
|
||||
return FinishWrite();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::Int64(AZ::s64 value)
|
||||
{
|
||||
CurrentValue().SetInt64(value);
|
||||
return FinishWrite();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::Uint64(AZ::u64 value)
|
||||
{
|
||||
CurrentValue().SetUint64(value);
|
||||
return FinishWrite();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::Double(double value)
|
||||
{
|
||||
CurrentValue().SetDouble(value);
|
||||
return FinishWrite();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::String(AZStd::string_view value, Lifetime lifetime)
|
||||
{
|
||||
if (lifetime == Lifetime::Temporary)
|
||||
{
|
||||
CurrentValue().SetString(value.data(), aznumeric_cast<rapidjson::SizeType>(value.length()), m_allocator);
|
||||
}
|
||||
else
|
||||
{
|
||||
CurrentValue().SetString(value.data(), aznumeric_cast<rapidjson::SizeType>(value.length()));
|
||||
}
|
||||
return FinishWrite();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::StartObject()
|
||||
{
|
||||
CurrentValue().SetObject();
|
||||
|
||||
const bool isObject = true;
|
||||
m_entryStack.emplace_front(isObject, CurrentValue());
|
||||
return VisitorSuccess();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::EndObject(AZ::u64 attributeCount)
|
||||
{
|
||||
if (m_entryStack.empty())
|
||||
{
|
||||
return VisitorFailure(VisitorErrorCode::InternalError, "EndObject called without a matching BeginObject call");
|
||||
}
|
||||
|
||||
const ValueInfo& frontEntry = m_entryStack.front();
|
||||
if (!frontEntry.m_isObject)
|
||||
{
|
||||
return VisitorFailure(VisitorErrorCode::InternalError, "Expected EndArray and received EndObject instead");
|
||||
}
|
||||
|
||||
if (frontEntry.m_entryCount != attributeCount)
|
||||
{
|
||||
return VisitorFailure(
|
||||
VisitorErrorCode::InternalError,
|
||||
AZStd::string::format(
|
||||
"EndObject: Expected %llu attributes but received %llu attributes instead", attributeCount,
|
||||
frontEntry.m_entryCount));
|
||||
}
|
||||
|
||||
m_entryStack.pop_front();
|
||||
return FinishWrite();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::Key(AZ::Name key)
|
||||
{
|
||||
return RawKey(key.GetStringView(), Lifetime::Persistent);
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::RawKey(AZStd::string_view key, Lifetime lifetime)
|
||||
{
|
||||
AZ_Assert(!m_entryStack.empty(), "Attempmted to push a key with no object");
|
||||
AZ_Assert(m_entryStack.front().m_isObject, "Attempted to push a key to an array");
|
||||
if (lifetime == Lifetime::Persistent)
|
||||
{
|
||||
m_entryStack.front().m_key.SetString(key.data(), aznumeric_cast<rapidjson::SizeType>(key.size()));
|
||||
}
|
||||
else
|
||||
{
|
||||
m_entryStack.front().m_key.SetString(key.data(), aznumeric_cast<rapidjson::SizeType>(key.size()), m_allocator);
|
||||
}
|
||||
return VisitorSuccess();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::StartArray()
|
||||
{
|
||||
CurrentValue().SetArray();
|
||||
|
||||
const bool isObject = false;
|
||||
m_entryStack.emplace_front(isObject, CurrentValue());
|
||||
return VisitorSuccess();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::EndArray(AZ::u64 elementCount)
|
||||
{
|
||||
if (m_entryStack.empty())
|
||||
{
|
||||
return VisitorFailure(VisitorErrorCode::InternalError, "EndArray called without a matching BeginArray call");
|
||||
}
|
||||
|
||||
const ValueInfo& frontEntry = m_entryStack.front();
|
||||
if (frontEntry.m_isObject)
|
||||
{
|
||||
return VisitorFailure(VisitorErrorCode::InternalError, "Expected EndObject and received EndArray instead");
|
||||
}
|
||||
|
||||
if (frontEntry.m_entryCount != elementCount)
|
||||
{
|
||||
return VisitorFailure(
|
||||
VisitorErrorCode::InternalError,
|
||||
AZStd::string::format(
|
||||
"EndArray: Expected %llu elements but received %llu elements instead", elementCount, frontEntry.m_entryCount));
|
||||
}
|
||||
|
||||
m_entryStack.pop_front();
|
||||
return FinishWrite();
|
||||
}
|
||||
|
||||
Visitor::Result RapidJsonValueWriter::FinishWrite()
|
||||
{
|
||||
if (m_entryStack.empty())
|
||||
{
|
||||
return VisitorSuccess();
|
||||
}
|
||||
|
||||
// Retrieve the top value of the stack and replace it with a null value
|
||||
rapidjson::Value value;
|
||||
m_entryStack.front().m_value.Swap(value);
|
||||
ValueInfo& newEntry = m_entryStack.front();
|
||||
++newEntry.m_entryCount;
|
||||
|
||||
if (newEntry.m_key.IsString())
|
||||
{
|
||||
newEntry.m_container.AddMember(m_entryStack.front().m_key.Move(), AZStd::move(value), m_allocator);
|
||||
newEntry.m_key.SetNull();
|
||||
}
|
||||
else
|
||||
{
|
||||
newEntry.m_container.PushBack(AZStd::move(value), m_allocator);
|
||||
}
|
||||
|
||||
return VisitorSuccess();
|
||||
}
|
||||
|
||||
rapidjson::Value& RapidJsonValueWriter::CurrentValue()
|
||||
{
|
||||
if (m_entryStack.empty())
|
||||
{
|
||||
return m_result;
|
||||
}
|
||||
return m_entryStack.front().m_value;
|
||||
}
|
||||
|
||||
RapidJsonValueWriter::ValueInfo::ValueInfo(bool isObject, rapidjson::Value& container)
|
||||
: m_isObject(isObject)
|
||||
, m_container(container)
|
||||
{
|
||||
}
|
||||
|
||||
//
|
||||
// class StreamWriter
|
||||
//
|
||||
// Visitor that writes to a rapidjson::Writer
|
||||
template<class Writer>
|
||||
class StreamWriter : public Visitor
|
||||
{
|
||||
public:
|
||||
StreamWriter(AZ::IO::GenericStream* stream)
|
||||
: m_streamWriter(stream)
|
||||
, m_writer(Writer(m_streamWriter))
|
||||
{
|
||||
}
|
||||
|
||||
VisitorFlags GetVisitorFlags() const override
|
||||
{
|
||||
return VisitorFlags::SupportsRawKeys | VisitorFlags::SupportsArrays | VisitorFlags::SupportsObjects;
|
||||
}
|
||||
|
||||
Result Null() override
|
||||
{
|
||||
return CheckWrite(m_writer.Null());
|
||||
}
|
||||
|
||||
Result Bool(bool value) override
|
||||
{
|
||||
return CheckWrite(m_writer.Bool(value));
|
||||
}
|
||||
|
||||
Result Int64(AZ::s64 value) override
|
||||
{
|
||||
return CheckWrite(m_writer.Int64(value));
|
||||
}
|
||||
|
||||
Result Uint64(AZ::u64 value) override
|
||||
{
|
||||
return CheckWrite(m_writer.Uint64(value));
|
||||
}
|
||||
|
||||
Result Double(double value) override
|
||||
{
|
||||
return CheckWrite(m_writer.Double(value));
|
||||
}
|
||||
|
||||
Result String(AZStd::string_view value, Lifetime lifetime) override
|
||||
{
|
||||
const bool shouldCopy = lifetime == Lifetime::Temporary;
|
||||
return CheckWrite(m_writer.String(value.data(), aznumeric_cast<rapidjson::SizeType>(value.size()), shouldCopy));
|
||||
}
|
||||
|
||||
Result StartObject() override
|
||||
{
|
||||
return CheckWrite(m_writer.StartObject());
|
||||
}
|
||||
|
||||
Result EndObject(AZ::u64 attributeCount) override
|
||||
{
|
||||
return CheckWrite(m_writer.EndObject(aznumeric_cast<rapidjson::SizeType>(attributeCount)));
|
||||
}
|
||||
|
||||
Result Key(AZ::Name key) override
|
||||
{
|
||||
return RawKey(key.GetStringView(), Lifetime::Persistent);
|
||||
}
|
||||
|
||||
Result RawKey(AZStd::string_view key, Lifetime lifetime) override
|
||||
{
|
||||
const bool shouldCopy = lifetime == Lifetime::Temporary;
|
||||
return CheckWrite(m_writer.Key(key.data(), aznumeric_cast<rapidjson::SizeType>(key.size()), shouldCopy));
|
||||
}
|
||||
|
||||
Result StartArray() override
|
||||
{
|
||||
return CheckWrite(m_writer.StartArray());
|
||||
}
|
||||
|
||||
Result EndArray(AZ::u64 elementCount) override
|
||||
{
|
||||
return CheckWrite(m_writer.EndArray(aznumeric_cast<rapidjson::SizeType>(elementCount)));
|
||||
}
|
||||
|
||||
private:
|
||||
Result CheckWrite(bool writeSucceeded)
|
||||
{
|
||||
if (writeSucceeded)
|
||||
{
|
||||
return VisitorSuccess();
|
||||
}
|
||||
else
|
||||
{
|
||||
return VisitorFailure(VisitorErrorCode::InternalError, "Failed to write JSON");
|
||||
}
|
||||
}
|
||||
|
||||
AZ::IO::RapidJSONStreamWriter m_streamWriter;
|
||||
Writer m_writer;
|
||||
};
|
||||
|
||||
//
|
||||
// struct JsonReadHandler
|
||||
//
|
||||
RapidJsonReadHandler::RapidJsonReadHandler(Visitor* visitor, Lifetime stringLifetime)
|
||||
: m_visitor(visitor)
|
||||
, m_stringLifetime(stringLifetime)
|
||||
, m_outcome(AZ::Success())
|
||||
{
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::Null()
|
||||
{
|
||||
return CheckResult(m_visitor->Null());
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::Bool(bool b)
|
||||
{
|
||||
return CheckResult(m_visitor->Bool(b));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::Int(int i)
|
||||
{
|
||||
return CheckResult(m_visitor->Int64(aznumeric_cast<AZ::s64>(i)));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::Uint(unsigned i)
|
||||
{
|
||||
return CheckResult(m_visitor->Uint64(aznumeric_cast<AZ::u64>(i)));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::Int64(int64_t i)
|
||||
{
|
||||
return CheckResult(m_visitor->Int64(i));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::Uint64(uint64_t i)
|
||||
{
|
||||
return CheckResult(m_visitor->Uint64(i));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::Double(double d)
|
||||
{
|
||||
return CheckResult(m_visitor->Double(d));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::RawNumber(
|
||||
[[maybe_unused]] const char* str, [[maybe_unused]] rapidjson::SizeType length, [[maybe_unused]] bool copy)
|
||||
{
|
||||
AZ_Assert(false, "Raw numbers are unsupported in the rapidjson DOM backend");
|
||||
return false;
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::String(const char* str, rapidjson::SizeType length, bool copy)
|
||||
{
|
||||
const Lifetime lifetime = copy ? m_stringLifetime : Lifetime::Temporary;
|
||||
return CheckResult(m_visitor->String(AZStd::string_view(str, length), lifetime));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::StartObject()
|
||||
{
|
||||
return CheckResult(m_visitor->StartObject());
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::Key(const char* str, rapidjson::SizeType length, [[maybe_unused]] bool copy)
|
||||
{
|
||||
AZStd::string_view key = AZStd::string_view(str, length);
|
||||
if (!m_visitor->SupportsRawKeys())
|
||||
{
|
||||
m_visitor->Key(AZ::Name(key));
|
||||
}
|
||||
const Lifetime lifetime = copy ? m_stringLifetime : Lifetime::Temporary;
|
||||
return CheckResult(m_visitor->RawKey(key, lifetime));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::EndObject([[maybe_unused]] rapidjson::SizeType memberCount)
|
||||
{
|
||||
return CheckResult(m_visitor->EndObject(memberCount));
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::StartArray()
|
||||
{
|
||||
return CheckResult(m_visitor->StartArray());
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::EndArray([[maybe_unused]] rapidjson::SizeType elementCount)
|
||||
{
|
||||
return CheckResult(m_visitor->EndArray(elementCount));
|
||||
}
|
||||
|
||||
Visitor::Result&& RapidJsonReadHandler::TakeOutcome()
|
||||
{
|
||||
return AZStd::move(m_outcome);
|
||||
}
|
||||
|
||||
bool RapidJsonReadHandler::CheckResult(Visitor::Result result)
|
||||
{
|
||||
if (result.IsSuccess())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
m_outcome = AZStd::move(result);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// Serialized JSON util functions
|
||||
//
|
||||
AZStd::unique_ptr<Visitor> CreateJsonStreamWriter(AZ::IO::GenericStream& stream, OutputFormatting format)
|
||||
{
|
||||
if (format == OutputFormatting::MinifiedJson)
|
||||
{
|
||||
using WriterType = rapidjson::Writer<AZ::IO::RapidJSONStreamWriter>;
|
||||
return AZStd::make_unique<StreamWriter<WriterType>>(&stream);
|
||||
}
|
||||
else
|
||||
{
|
||||
using WriterType = rapidjson::PrettyWriter<AZ::IO::RapidJSONStreamWriter>;
|
||||
return AZStd::make_unique<StreamWriter<WriterType>>(&stream);
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// In-memory rapidjson util functions
|
||||
//
|
||||
AZ::Outcome<rapidjson::Document, AZStd::string> WriteToRapidJsonDocument(Backend::WriteCallback writeCallback)
|
||||
{
|
||||
rapidjson::Document document;
|
||||
RapidJsonValueWriter writer(document, document.GetAllocator());
|
||||
auto result = writeCallback(writer);
|
||||
if (!result.IsSuccess())
|
||||
{
|
||||
return AZ::Failure(result.TakeError().FormatVisitorErrorMessage());
|
||||
}
|
||||
return AZ::Success(AZStd::move(document));
|
||||
}
|
||||
|
||||
Visitor::Result WriteToRapidJsonValue(
|
||||
rapidjson::Value& value, rapidjson::Value::AllocatorType& allocator, Backend::WriteCallback writeCallback)
|
||||
{
|
||||
RapidJsonValueWriter writer(value, allocator);
|
||||
return writeCallback(writer);
|
||||
}
|
||||
|
||||
Visitor::Result VisitRapidJsonValue(const rapidjson::Value& value, Visitor& visitor, Lifetime lifetime)
|
||||
{
|
||||
struct EndArrayMarker
|
||||
{
|
||||
};
|
||||
struct EndObjectMarker
|
||||
{
|
||||
};
|
||||
|
||||
// Processing stack consists of values comprised of one of a:
|
||||
// - rapidjson::Value to process
|
||||
// - EndArrayMarker or EndObjectMarker denoting the end of an array or object
|
||||
// - string denoting a key at the beginning of a key/value pair
|
||||
using Entry = AZStd::variant<const rapidjson::Value*, EndArrayMarker, EndObjectMarker, AZStd::string_view>;
|
||||
AZStd::stack<Entry> entryStack;
|
||||
AZStd::stack<u64> entryCountStack;
|
||||
entryStack.push(&value);
|
||||
|
||||
while (!entryStack.empty())
|
||||
{
|
||||
const Entry currentEntry = entryStack.top();
|
||||
entryStack.pop();
|
||||
|
||||
Visitor::Result result = AZ::Success();
|
||||
|
||||
AZStd::visit(
|
||||
[&visitor, &entryStack, &entryCountStack, &result, lifetime](auto&& arg)
|
||||
{
|
||||
using Alternative = AZStd::decay_t<decltype(arg)>;
|
||||
if constexpr (AZStd::is_same_v<Alternative, const rapidjson::Value*>)
|
||||
{
|
||||
const rapidjson::Value& currentValue = *arg;
|
||||
if (!entryCountStack.empty())
|
||||
{
|
||||
++entryCountStack.top();
|
||||
}
|
||||
|
||||
switch (currentValue.GetType())
|
||||
{
|
||||
case rapidjson::kNullType:
|
||||
result = visitor.Null();
|
||||
break;
|
||||
case rapidjson::kFalseType:
|
||||
result = visitor.Bool(false);
|
||||
break;
|
||||
case rapidjson::kTrueType:
|
||||
result = visitor.Bool(true);
|
||||
break;
|
||||
case rapidjson::kObjectType:
|
||||
entryStack.push(EndObjectMarker{});
|
||||
entryCountStack.push(0);
|
||||
result = visitor.StartObject();
|
||||
for (auto it = currentValue.MemberEnd(); it != currentValue.MemberBegin(); --it)
|
||||
{
|
||||
auto entry = (it - 1);
|
||||
const AZStd::string_view key(
|
||||
entry->name.GetString(), aznumeric_cast<size_t>(entry->name.GetStringLength()));
|
||||
entryStack.push(&entry->value);
|
||||
entryStack.push(key);
|
||||
}
|
||||
break;
|
||||
case rapidjson::kArrayType:
|
||||
entryStack.push(EndArrayMarker{});
|
||||
entryCountStack.push(0);
|
||||
result = visitor.StartArray();
|
||||
for (auto it = currentValue.End(); it != currentValue.Begin(); --it)
|
||||
{
|
||||
auto entry = (it - 1);
|
||||
entryStack.push(entry);
|
||||
}
|
||||
break;
|
||||
case rapidjson::kStringType:
|
||||
result = visitor.String(
|
||||
AZStd::string_view(currentValue.GetString(), aznumeric_cast<size_t>(currentValue.GetStringLength())),
|
||||
lifetime);
|
||||
break;
|
||||
case rapidjson::kNumberType:
|
||||
if (currentValue.IsFloat() || currentValue.IsDouble())
|
||||
{
|
||||
result = visitor.Double(currentValue.GetDouble());
|
||||
}
|
||||
else if (currentValue.IsInt64() || currentValue.IsInt())
|
||||
{
|
||||
result = visitor.Int64(currentValue.GetInt64());
|
||||
}
|
||||
else
|
||||
{
|
||||
result = visitor.Uint64(currentValue.GetUint64());
|
||||
}
|
||||
break;
|
||||
default:
|
||||
result = AZ::Failure(VisitorError(VisitorErrorCode::InvalidData, "Value with invalid type specified"));
|
||||
}
|
||||
}
|
||||
else if constexpr (AZStd::is_same_v<Alternative, EndArrayMarker>)
|
||||
{
|
||||
result = visitor.EndArray(entryCountStack.top());
|
||||
entryCountStack.pop();
|
||||
}
|
||||
else if constexpr (AZStd::is_same_v<Alternative, EndObjectMarker>)
|
||||
{
|
||||
result = visitor.EndObject(entryCountStack.top());
|
||||
entryCountStack.pop();
|
||||
}
|
||||
else if constexpr (AZStd::is_same_v<Alternative, AZStd::string_view>)
|
||||
{
|
||||
if (visitor.SupportsRawKeys())
|
||||
{
|
||||
visitor.RawKey(arg, lifetime);
|
||||
}
|
||||
else
|
||||
{
|
||||
visitor.Key(AZ::Name(arg));
|
||||
}
|
||||
}
|
||||
},
|
||||
currentEntry);
|
||||
|
||||
if (!result.IsSuccess())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return AZ::Success();
|
||||
}
|
||||
} // namespace AZ::Dom::Json
|
||||
@@ -0,0 +1,256 @@
|
||||
/*
|
||||
* 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 <AzCore/DOM/DomBackend.h>
|
||||
#include <AzCore/DOM/DomVisitor.h>
|
||||
#include <AzCore/IO/GenericStreams.h>
|
||||
#include <AzCore/IO/Path/Path.h>
|
||||
#include <AzCore/JSON/document.h>
|
||||
#include <AzCore/std/containers/deque.h>
|
||||
#include <AzCore/std/containers/vector.h>
|
||||
#include <AzCore/std/smart_ptr/unique_ptr.h>
|
||||
|
||||
namespace AZ::Dom::Json
|
||||
{
|
||||
//! Specifies how JSON should be formatted when serialized.
|
||||
enum class OutputFormatting
|
||||
{
|
||||
MinifiedJson, //!< Formats JSON in compact minified form, focusing on minimizing output size.
|
||||
PrettyPrintedJson, //!< Formats JSON in a pretty printed form, focusing on legibility to readers.
|
||||
};
|
||||
|
||||
//! Specifies parsing behavior when deserializing JSON.
|
||||
enum class ParseFlags : int
|
||||
{
|
||||
Null = 0,
|
||||
StopWhenDone = rapidjson::kParseStopWhenDoneFlag,
|
||||
FullFloatingPointPrecision = rapidjson::kParseFullPrecisionFlag,
|
||||
ParseComments = rapidjson::kParseCommentsFlag,
|
||||
ParseNumbersAsStrings = rapidjson::kParseNumbersAsStringsFlag,
|
||||
ParseTrailingCommas = rapidjson::kParseTrailingCommasFlag,
|
||||
ParseNanAndInfinity = rapidjson::kParseNanAndInfFlag,
|
||||
ParseEscapedApostrophies = rapidjson::kParseEscapedApostropheFlag,
|
||||
};
|
||||
|
||||
AZ_DEFINE_ENUM_BITWISE_OPERATORS(ParseFlags);
|
||||
|
||||
//! Visitor that feeds into a rapidjson::Value
|
||||
class RapidJsonValueWriter final : public Visitor
|
||||
{
|
||||
public:
|
||||
RapidJsonValueWriter(rapidjson::Value& outputValue, rapidjson::Value::AllocatorType& allocator);
|
||||
|
||||
VisitorFlags GetVisitorFlags() const override;
|
||||
Result Null() override;
|
||||
Result Bool(bool value) override;
|
||||
Result Int64(AZ::s64 value) override;
|
||||
Result Uint64(AZ::u64 value) override;
|
||||
Result Double(double value) override;
|
||||
|
||||
Result String(AZStd::string_view value, Lifetime lifetime) override;
|
||||
Result StartObject() override;
|
||||
Result EndObject(AZ::u64 attributeCount) override;
|
||||
Result Key(AZ::Name key) override;
|
||||
Result RawKey(AZStd::string_view key, Lifetime lifetime) override;
|
||||
Result StartArray() override;
|
||||
Result EndArray(AZ::u64 elementCount) override;
|
||||
|
||||
private:
|
||||
Result FinishWrite();
|
||||
rapidjson::Value& CurrentValue();
|
||||
|
||||
struct ValueInfo
|
||||
{
|
||||
ValueInfo(bool isObject, rapidjson::Value& container);
|
||||
|
||||
rapidjson::Value m_key;
|
||||
rapidjson::Value m_value;
|
||||
rapidjson::Value& m_container;
|
||||
AZ::u64 m_entryCount = 0;
|
||||
bool m_isObject;
|
||||
};
|
||||
|
||||
rapidjson::Value& m_result;
|
||||
rapidjson::Value::AllocatorType& m_allocator;
|
||||
AZStd::deque<ValueInfo> m_entryStack;
|
||||
};
|
||||
|
||||
//! Handler for a rapidjson::Reader that translates reads into an AZ::Dom::Visitor
|
||||
struct RapidJsonReadHandler
|
||||
{
|
||||
public:
|
||||
RapidJsonReadHandler(Visitor* visitor, Lifetime stringLifetime);
|
||||
|
||||
bool Null();
|
||||
bool Bool(bool b);
|
||||
bool Int(int i);
|
||||
bool Uint(unsigned i);
|
||||
bool Int64(int64_t i);
|
||||
bool Uint64(uint64_t i);
|
||||
bool Double(double d);
|
||||
bool RawNumber(const char* str, rapidjson::SizeType length, bool copy);
|
||||
bool String(const char* str, rapidjson::SizeType length, bool copy);
|
||||
bool StartObject();
|
||||
bool Key(const char* str, rapidjson::SizeType length, bool copy);
|
||||
bool EndObject(rapidjson::SizeType memberCount);
|
||||
bool StartArray();
|
||||
bool EndArray(rapidjson::SizeType elementCount);
|
||||
Visitor::Result&& TakeOutcome();
|
||||
|
||||
private:
|
||||
bool CheckResult(Visitor::Result result);
|
||||
|
||||
Visitor::Result m_outcome;
|
||||
Visitor* m_visitor;
|
||||
Lifetime m_stringLifetime;
|
||||
};
|
||||
|
||||
//! rapidjson stream wrapper for AZStd::string suitable for in-situ parsing
|
||||
//! Faster than rapidjson::MemoryStream for reading from AZStd::string / AZStd::string_view (because it requires a null terminator)
|
||||
//! \note This needs to be inlined for performance reasons.
|
||||
struct NullDelimitedStringStream
|
||||
{
|
||||
using Ch = char; //<! Denotes the string character storage type for rapidjson
|
||||
|
||||
AZ_FORCE_INLINE NullDelimitedStringStream(char* buffer)
|
||||
{
|
||||
m_cursor = buffer;
|
||||
m_begin = m_cursor;
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE NullDelimitedStringStream(AZStd::string_view buffer)
|
||||
{
|
||||
// rapidjson won't actually call PutBegin or Put unless kParseInSituFlag is set, so this is safe
|
||||
m_cursor = const_cast<char*>(buffer.data());
|
||||
m_begin = m_cursor;
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE char Peek() const
|
||||
{
|
||||
return *m_cursor;
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE char Take()
|
||||
{
|
||||
return *m_cursor++;
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE size_t Tell() const
|
||||
{
|
||||
return static_cast<size_t>(m_cursor - m_begin);
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE char* PutBegin()
|
||||
{
|
||||
m_write = m_cursor;
|
||||
return m_cursor;
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE void Put(char c)
|
||||
{
|
||||
(*m_write++) = c;
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE void Flush()
|
||||
{
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE size_t PutEnd(char* begin)
|
||||
{
|
||||
return m_write - begin;
|
||||
}
|
||||
|
||||
AZ_FORCE_INLINE const char* Peek4() const
|
||||
{
|
||||
AZ_Assert(false, "Not implemented, encoding is hard-coded to UTF-8");
|
||||
return m_cursor;
|
||||
}
|
||||
|
||||
char* m_cursor; //!< Current read position.
|
||||
char* m_write; //!< Current write position.
|
||||
const char* m_begin; //!< Head of string.
|
||||
};
|
||||
|
||||
//! Creates a Visitor that will write serialized JSON to the specified stream.
|
||||
//! \param stream The stream the visitor will write to.
|
||||
//! \param format The format to write in.
|
||||
//! \return A Visitor that will write to stream when visited.
|
||||
AZStd::unique_ptr<Visitor> CreateJsonStreamWriter(
|
||||
AZ::IO::GenericStream& stream, OutputFormatting format = OutputFormatting::PrettyPrintedJson);
|
||||
//! Reads serialized JSON from a string and applies it to a visitor.
|
||||
//! \param buffer The UTF-8 serialized JSON to read.
|
||||
//! \param lifetime Specifies the lifetime of the specified buffer. If the string specified by buffer might be deallocated,
|
||||
//! ensure Lifetime::Temporary is specified.
|
||||
//! \param visitor The visitor to visit with the JSON buffer's contents.
|
||||
//! \param parseFlags (template) Settings for adjusting parser behavior.
|
||||
//! \return The aggregate result specifying whether the visitor operations were successful.
|
||||
template<ParseFlags parseFlags = ParseFlags::ParseComments>
|
||||
Visitor::Result VisitSerializedJson(AZStd::string_view buffer, Lifetime lifetime, Visitor& visitor);
|
||||
|
||||
//! Reads serialized JSON from a string in-place and applies it to a visitor.
|
||||
//! \param buffer The UTF-8 serialized JSON to read. This buffer will be modified as part of the deserialization process to
|
||||
//! apply null terminators.
|
||||
//! \param visitor The visitor to visit with the JSON buffer's contents. The strings provided to the visitor will only
|
||||
//! be valid for the lifetime of buffer.
|
||||
//! \param parseFlags (template) Settings for adjusting parser behavior.
|
||||
//! \return The aggregate result specifying whether the visitor operations were successful.
|
||||
template<ParseFlags parseFlags = ParseFlags::ParseComments>
|
||||
Visitor::Result VisitSerializedJsonInPlace(char* buffer, Visitor& visitor);
|
||||
|
||||
//! Takes a visitor specified by a callback and produces a rapidjson::Document.
|
||||
//! \param writeCallback A callback specifying a visitor to accept to build the resulting document.
|
||||
//! \return An outcome with either the rapidjson::Document or an error message.
|
||||
AZ::Outcome<rapidjson::Document, AZStd::string> WriteToRapidJsonDocument(Backend::WriteCallback writeCallback);
|
||||
//! Takes a visitor specified by a callback and reads them into a rapidjson::Value.
|
||||
//! \param value The value to read into, its contents will be overridden.
|
||||
//! \param allocator The allocator to use when performing rapidjson allocations (generally provded by the rapidjson::Document).
|
||||
//! \param writeCallback A callback specifying a visitor to accept to build the resulting document.
|
||||
//! \return An outcome with either the rapidjson::Document or an error message.
|
||||
Visitor::Result WriteToRapidJsonValue(
|
||||
rapidjson::Value& value, rapidjson::Value::AllocatorType& allocator, Backend::WriteCallback writeCallback);
|
||||
//! Accepts a visitor with the contents of a rapidjson::Value.
|
||||
//! \param value The rapidjson::Value to apply to visitor.
|
||||
//! \param visitor The visitor to receive the contents of value.
|
||||
//! \param lifetime The lifetime to specify for visiting strings. If the rapidjson::Value might be destroyed or changed
|
||||
//! before the visitor is finished using these values, Lifetime::Temporary should be specified.
|
||||
//! \return The aggregate result specifying whether the visitor operations were successful.
|
||||
Visitor::Result VisitRapidJsonValue(const rapidjson::Value& value, Visitor& visitor, Lifetime lifetime);
|
||||
|
||||
template<ParseFlags parseFlags>
|
||||
Visitor::Result VisitSerializedJson(AZStd::string_view buffer, Lifetime lifetime, Visitor& visitor)
|
||||
{
|
||||
rapidjson::Reader reader;
|
||||
RapidJsonReadHandler handler(&visitor, lifetime);
|
||||
|
||||
// If the string is null terminated, we can use the faster AzStringStream path - otherwise we fall back on rapidjson::MemoryStream
|
||||
if (buffer.data()[buffer.size()] == '\0')
|
||||
{
|
||||
NullDelimitedStringStream stream(buffer);
|
||||
reader.Parse<aznumeric_cast<unsigned>(parseFlags)>(stream, handler);
|
||||
}
|
||||
else
|
||||
{
|
||||
rapidjson::MemoryStream stream(buffer.data(), buffer.size());
|
||||
reader.Parse<aznumeric_cast<unsigned>(parseFlags)>(stream, handler);
|
||||
}
|
||||
return handler.TakeOutcome();
|
||||
}
|
||||
|
||||
template<ParseFlags parseFlags>
|
||||
Visitor::Result VisitSerializedJsonInPlace(char* buffer, Visitor& visitor)
|
||||
{
|
||||
rapidjson::Reader reader;
|
||||
NullDelimitedStringStream stream(buffer);
|
||||
RapidJsonReadHandler handler(&visitor, Lifetime::Persistent);
|
||||
|
||||
reader.Parse<aznumeric_cast<unsigned>(parseFlags) | rapidjson::kParseInsituFlag>(stream, handler);
|
||||
return handler.TakeOutcome();
|
||||
}
|
||||
} // namespace AZ::Dom::Json
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* 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 <AzCore/DOM/DomBackend.h>
|
||||
|
||||
namespace AZ::Dom
|
||||
{
|
||||
Visitor::Result Backend::ReadFromBufferInPlace(char* buffer, AZStd::optional<size_t> size, Visitor& visitor)
|
||||
{
|
||||
return ReadFromBuffer(buffer, size.value_or(strlen(buffer)), AZ::Dom::Lifetime::Persistent, visitor);
|
||||
}
|
||||
} // namespace AZ::Dom
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* 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 <AzCore/DOM/DomVisitor.h>
|
||||
#include <AzCore/IO/GenericStreams.h>
|
||||
#include <AzCore/IO/Path/Path.h>
|
||||
#include <AzCore/std/containers/vector.h>
|
||||
#include <AzCore/std/optional.h>
|
||||
#include <AzCore/std/smart_ptr/unique_ptr.h>
|
||||
|
||||
namespace AZ::Dom
|
||||
{
|
||||
//! Backends are registered centrally and used to transition DOM formats to and from a textual format.
|
||||
class Backend
|
||||
{
|
||||
public:
|
||||
virtual ~Backend() = default;
|
||||
|
||||
//! Attempt to read this format from the given buffer into the target Visitor.
|
||||
virtual Visitor::Result ReadFromBuffer(
|
||||
const char* buffer, size_t size, AZ::Dom::Lifetime lifetime, Visitor& visitor) = 0;
|
||||
//! Attempt to read this format from a mutable string into the target Visitor. This enables some backends to
|
||||
//! parse without making additional string allocations.
|
||||
//! This string must be null terminated.
|
||||
//! This string may be modified and read in place without being copied, so when calling this please ensure that:
|
||||
//! - The string won't be deallocated until the visitor no longer needs the values and
|
||||
//! - The string is safe to modify in place.
|
||||
//! The base implementation simply calls ReadFromBuffer.
|
||||
virtual Visitor::Result ReadFromBufferInPlace(char* buffer, AZStd::optional<size_t> size, Visitor& visitor);
|
||||
|
||||
//! A callback that accepts a Visitor, making DOM calls to inform the serializer, and returns an
|
||||
//! aggregate error code to indicate whether or not the operation succeeded.
|
||||
using WriteCallback = AZStd::function<Visitor::Result(Visitor&)>;
|
||||
//! Attempt to write a value to the specified string using a write callback.
|
||||
virtual Visitor::Result WriteToBuffer(AZStd::string& buffer, WriteCallback callback) = 0;
|
||||
};
|
||||
} // namespace AZ::Dom
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* 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 <AzCore/DOM/DomUtils.h>
|
||||
|
||||
#include <AzCore/IO/ByteContainerStream.h>
|
||||
|
||||
namespace AZ::Dom::Utils
|
||||
{
|
||||
Visitor::Result ReadFromString(Backend& backend, AZStd::string_view string, AZ::Dom::Lifetime lifetime, Visitor& visitor)
|
||||
{
|
||||
return backend.ReadFromBuffer(string.data(), string.length(), lifetime, visitor);
|
||||
}
|
||||
|
||||
Visitor::Result ReadFromStringInPlace(Backend& backend, AZStd::string& string, Visitor& visitor)
|
||||
{
|
||||
return backend.ReadFromBufferInPlace(string.data(), string.size(), visitor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
* 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 <AzCore/DOM/DomBackend.h>
|
||||
|
||||
namespace AZ::Dom::Utils
|
||||
{
|
||||
Visitor::Result ReadFromString(Backend& backend, AZStd::string_view string, AZ::Dom::Lifetime lifetime, Visitor& visitor);
|
||||
Visitor::Result ReadFromStringInPlace(Backend& backend, AZStd::string& string, Visitor& visitor);
|
||||
} // namespace AZ::Dom::Utils
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
#include <AzCore/DOM/DomVisitor.h>
|
||||
|
||||
namespace AZ::DOM
|
||||
namespace AZ::Dom
|
||||
{
|
||||
const char* VisitorError::CodeToString(VisitorErrorCode code)
|
||||
{
|
||||
@@ -236,4 +236,4 @@ namespace AZ::DOM
|
||||
{
|
||||
return (GetVisitorFlags() & VisitorFlags::SupportsOpaqueValues) != VisitorFlags::Null;
|
||||
}
|
||||
} // namespace AZ::DOM
|
||||
} // namespace AZ::Dom
|
||||
|
||||
@@ -13,11 +13,11 @@
|
||||
#include <AzCore/std/any.h>
|
||||
#include <AzCore/std/string/string.h>
|
||||
|
||||
namespace AZ::DOM
|
||||
namespace AZ::Dom
|
||||
{
|
||||
//
|
||||
// Lifetime enum
|
||||
//
|
||||
//
|
||||
//! Specifies the period in which a reference value will still be alive and safe to read.
|
||||
enum class Lifetime
|
||||
{
|
||||
@@ -30,7 +30,7 @@ namespace AZ::DOM
|
||||
|
||||
//
|
||||
// VisitorErrorCode enum
|
||||
//
|
||||
//
|
||||
//! Error code specifying the reason a Visitor operation failed.
|
||||
enum class VisitorErrorCode
|
||||
{
|
||||
@@ -75,7 +75,7 @@ namespace AZ::DOM
|
||||
};
|
||||
|
||||
//! A type alias for opaque DOM types that aren't meant to be serializable.
|
||||
//! /see VisitorInterface::OpaqueValue
|
||||
//! \see VisitorInterface::OpaqueValue
|
||||
using OpaqueType = AZStd::any;
|
||||
|
||||
//
|
||||
@@ -116,7 +116,7 @@ namespace AZ::DOM
|
||||
//! - \ref Double: 64 bit double precision float
|
||||
//! - \ref Null: sentinel "empty" type with no value representation
|
||||
//! - \ref String: UTF8 encoded string
|
||||
//! - \ref Object: an ordered container of key/value pairs where keys are AZ::Names and values may be any DOM type
|
||||
//! - \ref Object: an ordered container of key/value pairs where keys are \ref AZ::Name and values may be any DOM type
|
||||
//! (including Object)
|
||||
//! - \ref Array: an ordered container of values, in which values are any DOM value type (including Array)
|
||||
//! - \ref Node: a container
|
||||
@@ -144,17 +144,17 @@ namespace AZ::DOM
|
||||
//! Raw (\see VisitorFlags::SupportsRawValues) and opaque values (\see VisitorFlags::SupportsOpaqueValues)
|
||||
//! are disallowed by default, as their handling is intended to be implementation-specific.
|
||||
virtual VisitorFlags GetVisitorFlags() const;
|
||||
//! /see VisitorFlags::SupportsRawValues
|
||||
//! \see VisitorFlags::SupportsRawValues
|
||||
bool SupportsRawValues() const;
|
||||
//! /see VisitorFlags::SupportsRawKeys
|
||||
//! \see VisitorFlags::SupportsRawKeys
|
||||
bool SupportsRawKeys() const;
|
||||
//! /see VisitorFlags::SupportsObjects
|
||||
//! \see VisitorFlags::SupportsObjects
|
||||
bool SupportsObjects() const;
|
||||
//! /see VisitorFlags::SupportsArrays
|
||||
//! \see VisitorFlags::SupportsArrays
|
||||
bool SupportsArrays() const;
|
||||
//! /see VisitorFlags::SupportsNodes
|
||||
//! \see VisitorFlags::SupportsNodes
|
||||
bool SupportsNodes() const;
|
||||
//! /see VisitorFlags::SupportsOpaqueValues
|
||||
//! \see VisitorFlags::SupportsOpaqueValues
|
||||
bool SupportsOpaqueValues() const;
|
||||
|
||||
//! Operates on an empty null value.
|
||||
@@ -231,7 +231,8 @@ namespace AZ::DOM
|
||||
static Result VisitorFailure(VisitorErrorCode code, AZStd::string additionalInfo);
|
||||
//! Helper method, constructs a failure \ref Result with the specified error.
|
||||
static Result VisitorFailure(VisitorError error);
|
||||
|
||||
//! Helper method, constructs a success \ref Result.
|
||||
static Result VisitorSuccess();
|
||||
};
|
||||
} // namespace AZ::DOM
|
||||
} // namespace AZ::Dom
|
||||
|
||||
@@ -5073,13 +5073,26 @@ LUA_API const Node* lua_getDummyNode()
|
||||
// Check all constructors if they have use ScriptDataContext and if so choose this one
|
||||
if (!customConstructorMethod)
|
||||
{
|
||||
int overrideIndex = -1;
|
||||
AZ::AttributeReader(nullptr, FindAttribute
|
||||
( Script::Attributes::DefaultConstructorOverrideIndex, behaviorClass->m_attributes)).Read<int>(overrideIndex);
|
||||
|
||||
int methodIndex = 0;
|
||||
for (BehaviorMethod* method : behaviorClass->m_constructors)
|
||||
{
|
||||
if (methodIndex == overrideIndex)
|
||||
{
|
||||
customConstructorMethod = method;
|
||||
break;
|
||||
}
|
||||
|
||||
if (method->GetNumArguments() && method->GetArgument(method->GetNumArguments() - 1)->m_typeId == AZ::AzTypeInfo<ScriptDataContext>::Uuid())
|
||||
{
|
||||
customConstructorMethod = method;
|
||||
break;
|
||||
}
|
||||
|
||||
++methodIndex;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ namespace AZ
|
||||
static constexpr AZ::Crc32 ClassNameOverride = AZ_CRC_CE("ScriptClassNameOverride"); ///< Provide a custom name for script reflection, that doesn't match the behavior Context name
|
||||
static constexpr AZ::Crc32 MethodOverride = AZ_CRC_CE("ScriptFunctionOverride"); ///< Use a custom function in the attribute instead of the function
|
||||
static constexpr AZ::Crc32 ConstructorOverride = AZ_CRC_CE("ConstructorOverride"); ///< You can provide a custom constructor to be called when created from Lua script
|
||||
static constexpr AZ::Crc32 DefaultConstructorOverrideIndex = AZ_CRC_CE("DefaultConstructorOverrideIndex"); ///< Use a different class constructor as the default constructor in Lua
|
||||
static constexpr AZ::Crc32 EventHandlerCreationFunction = AZ_CRC_CE("EventHandlerCreationFunction"); ///< helps create a handler for any script target so that script functions can be used for AZ::Event signals
|
||||
static constexpr AZ::Crc32 GenericConstructorOverride = AZ_CRC_CE("GenericConstructorOverride"); ///< You can provide a custom constructor to be called when creating a script
|
||||
static constexpr AZ::Crc32 ReaderWriterOverride = AZ_CRC_CE("ReaderWriterOverride"); ///< paired with \ref ScriptContext::CustomReaderWriter allows you to customize read/write to Lua VM
|
||||
|
||||
@@ -133,6 +133,8 @@ namespace AZ
|
||||
const static AZ::Crc32 AllowClearAsset = AZ_CRC("AllowClearAsset", 0x24827182);
|
||||
// Show the name of the asset that was produced from the source asset
|
||||
const static AZ::Crc32 ShowProductAssetFileName = AZ_CRC("ShowProductAssetFileName");
|
||||
//! Regular expression pattern filter for source files
|
||||
const static AZ::Crc32 SourceAssetFilterPattern = AZ_CRC_CE("SourceAssetFilterPattern");
|
||||
|
||||
//! Component icon attributes
|
||||
const static AZ::Crc32 Icon = AZ_CRC("Icon", 0x659429db);
|
||||
|
||||
@@ -204,6 +204,22 @@ namespace AZ
|
||||
// BaseJsonSerializer
|
||||
//
|
||||
|
||||
JsonSerializationResult::Result BaseJsonSerializer::Load(void* outputValue, const Uuid& outputValueTypeId, const rapidjson::Value& inputValue,
|
||||
JsonDeserializerContext& context)
|
||||
{
|
||||
JsonSerializationResult::ResultCode result(JsonSerializationResult::Tasks::ReadField);
|
||||
result.Combine(ContinueLoading(outputValue, outputValueTypeId, inputValue, context, ContinuationFlags::IgnoreTypeSerializer));
|
||||
return context.Report(result, "Ignoring custom serialization during load");
|
||||
}
|
||||
|
||||
JsonSerializationResult::Result BaseJsonSerializer::Store(rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue,
|
||||
const Uuid& valueTypeId, JsonSerializerContext& context)
|
||||
{
|
||||
JsonSerializationResult::ResultCode result(JsonSerializationResult::Tasks::WriteValue);
|
||||
result.Combine(ContinueStoring(outputValue, inputValue, defaultValue, valueTypeId, context, ContinuationFlags::IgnoreTypeSerializer));
|
||||
return context.Report(result, "Ignoring custom serialization during store");
|
||||
}
|
||||
|
||||
BaseJsonSerializer::OperationFlags BaseJsonSerializer::GetOperationsFlags() const
|
||||
{
|
||||
return OperationFlags::None;
|
||||
|
||||
@@ -180,13 +180,16 @@ namespace AZ
|
||||
|
||||
//! Transforms the data from the rapidjson Value to outputValue, if the conversion is possible and supported.
|
||||
//! The serializer is responsible for casting to the proper type and safely writing to the outputValue memory.
|
||||
//! \note The default implementation is to load the object ignoring a custom serializers for the type, which allows for custom serializers
|
||||
//! to modify the object after all default loading has occurred.
|
||||
virtual JsonSerializationResult::Result Load(void* outputValue, const Uuid& outputValueTypeId, const rapidjson::Value& inputValue,
|
||||
JsonDeserializerContext& context) = 0;
|
||||
JsonDeserializerContext& context);
|
||||
|
||||
//! Write the input value to a rapidjson value if the default value is not null and doesn't match the input value, otherwise
|
||||
//! an error is returned and sets the rapidjson value to a null value.
|
||||
//! \note The default implementation is to store the object ignoring custom serializers.
|
||||
virtual JsonSerializationResult::Result Store(rapidjson::Value& outputValue, const void* inputValue, const void* defaultValue,
|
||||
const Uuid& valueTypeId, JsonSerializerContext& context) = 0;
|
||||
const Uuid& valueTypeId, JsonSerializerContext& context);
|
||||
|
||||
//! Returns the operation flags which tells the Json Serialization how this custom json serializer can be used.
|
||||
virtual OperationFlags GetOperationsFlags() const;
|
||||
|
||||
@@ -165,13 +165,12 @@ namespace AZ::Utils
|
||||
}
|
||||
|
||||
Container fileContent;
|
||||
fileContent.resize(length);
|
||||
fileContent.resize_no_construct(length);
|
||||
AZ::IO::SizeType bytesRead = file.Read(length, fileContent.data());
|
||||
file.Close();
|
||||
|
||||
// Resize again just in case bytesRead is less than length for some reason
|
||||
fileContent.resize(bytesRead);
|
||||
|
||||
fileContent.resize_no_construct(bytesRead);
|
||||
return AZ::Success(AZStd::move(fileContent));
|
||||
}
|
||||
|
||||
|
||||
@@ -914,11 +914,11 @@ namespace UnitTest
|
||||
m_testAssetManager->SetParallelDependentLoadingEnabled(true);
|
||||
}
|
||||
|
||||
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
|
||||
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
|
||||
TEST_F(AssetJobsFloodTest, DISABLED_LoadTest_SameAsset_DifferentFilters)
|
||||
#else
|
||||
TEST_F(AssetJobsFloodTest, LoadTest_SameAsset_DifferentFilters)
|
||||
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
|
||||
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
|
||||
{
|
||||
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect();
|
||||
|
||||
@@ -1263,11 +1263,11 @@ namespace UnitTest
|
||||
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusDisconnect();
|
||||
}
|
||||
|
||||
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
|
||||
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
|
||||
TEST_F(AssetJobsFloodTest, DISABLED_AssetWithNoLoadReference_LoadDependencies_NoLoadNotLoaded)
|
||||
#else
|
||||
TEST_F(AssetJobsFloodTest, AssetWithNoLoadReference_LoadDependencies_NoLoadNotLoaded)
|
||||
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
|
||||
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
|
||||
{
|
||||
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect();
|
||||
// Setup has already created/destroyed assets
|
||||
@@ -1304,11 +1304,11 @@ namespace UnitTest
|
||||
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusDisconnect();
|
||||
}
|
||||
|
||||
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
|
||||
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
|
||||
TEST_F(AssetJobsFloodTest, DISABLED_AssetWithNoLoadReference_LoadContainerDependencies_LoadAllLoadsNoLoad)
|
||||
#else
|
||||
TEST_F(AssetJobsFloodTest, AssetWithNoLoadReference_LoadContainerDependencies_LoadAllLoadsNoLoad)
|
||||
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
|
||||
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
|
||||
{
|
||||
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect();
|
||||
// Setup has already created/destroyed assets
|
||||
@@ -1343,11 +1343,11 @@ namespace UnitTest
|
||||
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusDisconnect();
|
||||
}
|
||||
|
||||
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
|
||||
#if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
|
||||
TEST_F(AssetJobsFloodTest, DISABLED_AssetWithNoLoadReference_LoadDependencies_BehaviorObeyed)
|
||||
#else
|
||||
TEST_F(AssetJobsFloodTest, AssetWithNoLoadReference_LoadDependencies_BehaviorObeyed)
|
||||
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS || AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS
|
||||
#endif // AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS
|
||||
{
|
||||
m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect();
|
||||
// Setup has already created/destroyed assets
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
*/
|
||||
|
||||
#if defined(HAVE_BENCHMARK)
|
||||
|
||||
#include <AzCore/DOM/DomUtils.h>
|
||||
#include <AzCore/DOM/Backends/JSON/JsonBackend.h>
|
||||
#include <AzCore/DOM/Backends/JSON/JsonSerializationUtils.h>
|
||||
#include <AzCore/JSON/document.h>
|
||||
#include <AzCore/Name/NameDictionary.h>
|
||||
#include <AzCore/Serialization/Json/JsonUtils.h>
|
||||
#include <AzCore/UnitTest/TestTypes.h>
|
||||
|
||||
namespace Benchmark
|
||||
{
|
||||
class DomJsonBenchmark : public UnitTest::AllocatorsBenchmarkFixture
|
||||
{
|
||||
public:
|
||||
void SetUp(const ::benchmark::State& st) override
|
||||
{
|
||||
UnitTest::AllocatorsBenchmarkFixture::SetUp(st);
|
||||
AZ::NameDictionary::Create();
|
||||
}
|
||||
|
||||
void SetUp(::benchmark::State& st) override
|
||||
{
|
||||
UnitTest::AllocatorsBenchmarkFixture::SetUp(st);
|
||||
AZ::NameDictionary::Create();
|
||||
}
|
||||
|
||||
void TearDown(::benchmark::State& st) override
|
||||
{
|
||||
AZ::NameDictionary::Destroy();
|
||||
UnitTest::AllocatorsBenchmarkFixture::TearDown(st);
|
||||
}
|
||||
|
||||
void TearDown(const ::benchmark::State& st) override
|
||||
{
|
||||
AZ::NameDictionary::Destroy();
|
||||
UnitTest::AllocatorsBenchmarkFixture::TearDown(st);
|
||||
}
|
||||
|
||||
AZStd::string GenerateDomJsonBenchmarkPayload(int64_t entryCount, int64_t stringTemplateLength)
|
||||
{
|
||||
rapidjson::Document document;
|
||||
document.SetObject();
|
||||
|
||||
AZStd::string entryTemplate;
|
||||
while (entryTemplate.size() < static_cast<size_t>(stringTemplateLength))
|
||||
{
|
||||
entryTemplate += "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor ";
|
||||
}
|
||||
entryTemplate.resize(stringTemplateLength);
|
||||
AZStd::string buffer;
|
||||
|
||||
auto createString = [&](int n) -> rapidjson::Value
|
||||
{
|
||||
buffer = AZStd::string::format("#%i %s", n, entryTemplate.c_str());
|
||||
return rapidjson::Value(buffer.data(), static_cast<rapidjson::SizeType>(buffer.size()), document.GetAllocator());
|
||||
};
|
||||
|
||||
auto createEntry = [&](int n) -> rapidjson::Value
|
||||
{
|
||||
rapidjson::Value entry(rapidjson::kObjectType);
|
||||
entry.AddMember("string", createString(n), document.GetAllocator());
|
||||
entry.AddMember("int", rapidjson::Value(n), document.GetAllocator());
|
||||
entry.AddMember("double", rapidjson::Value(static_cast<double>(n) * 0.5), document.GetAllocator());
|
||||
entry.AddMember("bool", rapidjson::Value(n % 2 == 0), document.GetAllocator());
|
||||
entry.AddMember("null", rapidjson::Value(rapidjson::kNullType), document.GetAllocator());
|
||||
return entry;
|
||||
};
|
||||
|
||||
auto createArray = [&]() -> rapidjson::Value
|
||||
{
|
||||
rapidjson::Value array;
|
||||
array.SetArray();
|
||||
for (int i = 0; i < entryCount; ++i)
|
||||
{
|
||||
array.PushBack(createEntry(i), document.GetAllocator());
|
||||
}
|
||||
return array;
|
||||
};
|
||||
|
||||
auto createObject = [&]() -> rapidjson::Value
|
||||
{
|
||||
rapidjson::Value object;
|
||||
object.SetObject();
|
||||
for (int i = 0; i < entryCount; ++i)
|
||||
{
|
||||
buffer = AZStd::string::format("Key%i", i);
|
||||
rapidjson::Value key;
|
||||
key.SetString(buffer.data(), static_cast<rapidjson::SizeType>(buffer.length()), document.GetAllocator());
|
||||
object.AddMember(key.Move(), createArray(), document.GetAllocator());
|
||||
}
|
||||
return object;
|
||||
};
|
||||
|
||||
document.SetObject();
|
||||
document.AddMember("entries", createObject(), document.GetAllocator());
|
||||
|
||||
AZStd::string serializedJson;
|
||||
auto result = AZ::JsonSerializationUtils::WriteJsonString(document, serializedJson);
|
||||
AZ_Assert(result.IsSuccess(), "Failed to serialize generated JSON");
|
||||
return serializedJson;
|
||||
}
|
||||
};
|
||||
|
||||
// Helper macro for registering JSON benchmarks
|
||||
#define BENCHMARK_REGISTER_JSON(BaseClass, Method) \
|
||||
BENCHMARK_REGISTER_F(BaseClass, Method) \
|
||||
->Args({ 10, 5 }) \
|
||||
->Args({ 10, 500 }) \
|
||||
->Args({ 100, 5 }) \
|
||||
->Args({ 100, 500 }) \
|
||||
->Unit(benchmark::kMillisecond);
|
||||
|
||||
BENCHMARK_DEFINE_F(DomJsonBenchmark, DomDeserializeToDocumentInPlace)(benchmark::State& state)
|
||||
{
|
||||
AZ::Dom::JsonBackend backend;
|
||||
AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1));
|
||||
|
||||
for (auto _ : state)
|
||||
{
|
||||
state.PauseTiming();
|
||||
AZStd::string payloadCopy = serializedPayload;
|
||||
state.ResumeTiming();
|
||||
|
||||
auto result = AZ::Dom::Json::WriteToRapidJsonDocument(
|
||||
[&](AZ::Dom::Visitor& visitor)
|
||||
{
|
||||
return AZ::Dom::Utils::ReadFromStringInPlace(backend, payloadCopy, visitor);
|
||||
});
|
||||
|
||||
benchmark::DoNotOptimize(result.GetValue());
|
||||
}
|
||||
|
||||
state.SetBytesProcessed(serializedPayload.size() * state.iterations());
|
||||
}
|
||||
BENCHMARK_REGISTER_JSON(DomJsonBenchmark, DomDeserializeToDocumentInPlace)
|
||||
|
||||
BENCHMARK_DEFINE_F(DomJsonBenchmark, DomDeserializeToDocument)(benchmark::State& state)
|
||||
{
|
||||
AZ::Dom::JsonBackend backend;
|
||||
AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1));
|
||||
|
||||
for (auto _ : state)
|
||||
{
|
||||
auto result = AZ::Dom::Json::WriteToRapidJsonDocument(
|
||||
[&](AZ::Dom::Visitor& visitor)
|
||||
{
|
||||
return AZ::Dom::Utils::ReadFromString(backend, serializedPayload, AZ::Dom::Lifetime::Temporary, visitor);
|
||||
});
|
||||
|
||||
benchmark::DoNotOptimize(result.GetValue());
|
||||
}
|
||||
|
||||
state.SetBytesProcessed(serializedPayload.size() * state.iterations());
|
||||
}
|
||||
BENCHMARK_REGISTER_JSON(DomJsonBenchmark, DomDeserializeToDocument)
|
||||
|
||||
BENCHMARK_DEFINE_F(DomJsonBenchmark, JsonUtilsDeserializeToDocument)(benchmark::State& state)
|
||||
{
|
||||
AZ::Dom::JsonBackend backend;
|
||||
AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1));
|
||||
|
||||
for (auto _ : state)
|
||||
{
|
||||
auto result = AZ::JsonSerializationUtils::ReadJsonString(serializedPayload);
|
||||
|
||||
benchmark::DoNotOptimize(result.GetValue());
|
||||
}
|
||||
|
||||
state.SetBytesProcessed(serializedPayload.size() * state.iterations());
|
||||
}
|
||||
BENCHMARK_REGISTER_JSON(DomJsonBenchmark, JsonUtilsDeserializeToDocument)
|
||||
|
||||
#undef BENCHMARK_REGISTER_JSON
|
||||
} // namespace Benchmark
|
||||
|
||||
#endif // defined(HAVE_BENCHMARK)
|
||||
@@ -0,0 +1,219 @@
|
||||
/*
|
||||
* 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 <AzCore/DOM/Backends/JSON/JsonBackend.h>
|
||||
#include <AzCore/DOM/Backends/JSON/JsonSerializationUtils.h>
|
||||
#include <AzCore/DOM/DomUtils.h>
|
||||
#include <AzCore/Name/NameDictionary.h>
|
||||
#include <AzCore/Serialization/Json/JsonSerialization.h>
|
||||
#include <AzCore/Serialization/Json/JsonUtils.h>
|
||||
#include <AzCore/UnitTest/TestTypes.h>
|
||||
|
||||
namespace AZ::Dom::Tests
|
||||
{
|
||||
class DomJsonTests : public UnitTest::AllocatorsFixture
|
||||
{
|
||||
public:
|
||||
void SetUp() override
|
||||
{
|
||||
UnitTest::AllocatorsFixture::SetUp();
|
||||
NameDictionary::Create();
|
||||
m_document = AZStd::make_unique<rapidjson::Document>();
|
||||
}
|
||||
|
||||
void TearDown() override
|
||||
{
|
||||
m_document.reset();
|
||||
NameDictionary::Destroy();
|
||||
UnitTest::AllocatorsFixture::TearDown();
|
||||
}
|
||||
|
||||
rapidjson::Value CreateString(const AZStd::string& text)
|
||||
{
|
||||
rapidjson::Value key;
|
||||
key.SetString(text.c_str(), static_cast<rapidjson::SizeType>(text.length()), m_document->GetAllocator());
|
||||
return key;
|
||||
}
|
||||
|
||||
template<class T>
|
||||
void AddValue(const AZStd::string& key, T value)
|
||||
{
|
||||
m_document->AddMember(CreateString(key), rapidjson::Value(value), m_document->GetAllocator());
|
||||
}
|
||||
|
||||
// Validate round-trip serialization to and from rapidjson::Document and a UTF-8 encoded string
|
||||
void PerformSerializationChecks()
|
||||
{
|
||||
// Generate a canonical serializaed representation of this document using rapidjson
|
||||
// This will be pretty-printed using the same rapidjson pretty printer we use, so should be binary identical
|
||||
// to any output generated by the visitor API
|
||||
AZStd::string canonicalSerializedDocument;
|
||||
AZ::JsonSerializationUtils::WriteJsonString(*m_document, canonicalSerializedDocument);
|
||||
|
||||
auto visitDocumentFn = [this](AZ::Dom::Visitor& visitor)
|
||||
{
|
||||
return Json::VisitRapidJsonValue(*m_document, visitor, Lifetime::Temporary);
|
||||
};
|
||||
|
||||
// Document -> Document
|
||||
{
|
||||
auto result = Json::WriteToRapidJsonDocument(visitDocumentFn);
|
||||
EXPECT_TRUE(result.IsSuccess());
|
||||
EXPECT_EQ(AZ::JsonSerialization::Compare(*m_document, result.GetValue()), AZ::JsonSerializerCompareResult::Equal);
|
||||
}
|
||||
|
||||
// Document -> string
|
||||
{
|
||||
AZStd::string serializedDocument;
|
||||
JsonBackend backend;
|
||||
auto result = backend.WriteToBuffer(serializedDocument, visitDocumentFn);
|
||||
EXPECT_TRUE(result.IsSuccess());
|
||||
EXPECT_EQ(canonicalSerializedDocument, serializedDocument);
|
||||
}
|
||||
|
||||
// string -> Document
|
||||
{
|
||||
auto result = Json::WriteToRapidJsonDocument(
|
||||
[&canonicalSerializedDocument](AZ::Dom::Visitor& visitor)
|
||||
{
|
||||
JsonBackend backend;
|
||||
return Dom::Utils::ReadFromString(backend, canonicalSerializedDocument, Lifetime::Temporary, visitor);
|
||||
});
|
||||
EXPECT_TRUE(result.IsSuccess());
|
||||
EXPECT_EQ(AZ::JsonSerialization::Compare(*m_document, result.GetValue()), JsonSerializerCompareResult::Equal);
|
||||
}
|
||||
|
||||
// string -> string
|
||||
{
|
||||
AZStd::string serializedDocument;
|
||||
JsonBackend backend;
|
||||
auto result = backend.WriteToBuffer(
|
||||
serializedDocument,
|
||||
[&backend, &canonicalSerializedDocument](AZ::Dom::Visitor& visitor)
|
||||
{
|
||||
return Dom::Utils::ReadFromString(backend, canonicalSerializedDocument, Lifetime::Temporary, visitor);
|
||||
});
|
||||
EXPECT_TRUE(result.IsSuccess());
|
||||
EXPECT_EQ(canonicalSerializedDocument, serializedDocument);
|
||||
}
|
||||
}
|
||||
|
||||
AZStd::unique_ptr<rapidjson::Document> m_document;
|
||||
};
|
||||
|
||||
TEST_F(DomJsonTests, EmptyArray)
|
||||
{
|
||||
m_document->SetArray();
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, SimpleArray)
|
||||
{
|
||||
m_document->SetArray();
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
m_document->PushBack(i, m_document->GetAllocator());
|
||||
}
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, NestedArrays)
|
||||
{
|
||||
m_document->SetArray();
|
||||
for (int j = 0; j < 7; ++j)
|
||||
{
|
||||
rapidjson::Value nestedArray(rapidjson::kArrayType);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
nestedArray.PushBack(i, m_document->GetAllocator());
|
||||
}
|
||||
m_document->PushBack(nestedArray.Move(), m_document->GetAllocator());
|
||||
}
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, EmptyObject)
|
||||
{
|
||||
m_document->SetObject();
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, SimpleObject)
|
||||
{
|
||||
m_document->SetObject();
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
m_document->AddMember(CreateString(AZStd::string::format("Key%i", i)), rapidjson::Value(i), m_document->GetAllocator());
|
||||
}
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, NestedObjects)
|
||||
{
|
||||
m_document->SetObject();
|
||||
for (int j = 0; j < 7; ++j)
|
||||
{
|
||||
rapidjson::Value nestedObject(rapidjson::kObjectType);
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
nestedObject.AddMember(CreateString(AZStd::string::format("Key%i", i)), rapidjson::Value(i), m_document->GetAllocator());
|
||||
}
|
||||
m_document->AddMember(CreateString(AZStd::string::format("Obj%i", j)), nestedObject.Move(), m_document->GetAllocator());
|
||||
}
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, Int64)
|
||||
{
|
||||
m_document->SetObject();
|
||||
AddValue("int64_min", AZStd::numeric_limits<int64_t>::min());
|
||||
AddValue("int64_max", AZStd::numeric_limits<int64_t>::max());
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, Uint64)
|
||||
{
|
||||
m_document->SetObject();
|
||||
AddValue("uint64_min", AZStd::numeric_limits<uint64_t>::min());
|
||||
AddValue("uint64_max", AZStd::numeric_limits<uint64_t>::max());
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, Double)
|
||||
{
|
||||
m_document->SetObject();
|
||||
AddValue("double_min", AZStd::numeric_limits<double>::min());
|
||||
AddValue("double_max", AZStd::numeric_limits<double>::max());
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, Null)
|
||||
{
|
||||
m_document->SetObject();
|
||||
m_document->AddMember(CreateString("null_value"), rapidjson::Value(rapidjson::kNullType), m_document->GetAllocator());
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, Bool)
|
||||
{
|
||||
m_document->SetObject();
|
||||
AddValue("true_value", true);
|
||||
AddValue("false_value", false);
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
|
||||
TEST_F(DomJsonTests, String)
|
||||
{
|
||||
m_document->SetObject();
|
||||
m_document->AddMember(CreateString("empty_string"), CreateString(""), m_document->GetAllocator());
|
||||
m_document->AddMember(CreateString("short_string"), CreateString("test"), m_document->GetAllocator());
|
||||
m_document->AddMember(
|
||||
CreateString("long_string"), CreateString("abcdefghijklmnopqrstuvwxyz0123456789"), m_document->GetAllocator());
|
||||
PerformSerializationChecks();
|
||||
}
|
||||
} // namespace AZ::Dom::Tests
|
||||
@@ -13,6 +13,13 @@
|
||||
|
||||
namespace UnitTest
|
||||
{
|
||||
//! Null implementation of DebugDisplayRequests for dummy draw calls.
|
||||
class NullDebugDisplayRequests : public AzFramework::DebugDisplayRequests
|
||||
{
|
||||
public:
|
||||
virtual ~NullDebugDisplayRequests() = default;
|
||||
};
|
||||
|
||||
//! Minimal implementation of DebugDisplayRequests to support testing shapes.
|
||||
//! Stores a list of points based on received draw calls to delineate the exterior of the object requested to be drawn.
|
||||
class TestDebugDisplayRequests : public AzFramework::DebugDisplayRequests
|
||||
|
||||
+2
-1
@@ -29,7 +29,8 @@ namespace UnitTest
|
||||
void SetUpEditorFixtureImpl() override
|
||||
{
|
||||
ToolsApplicationFixtureT::SetUpEditorFixtureImpl();
|
||||
m_viewportManipulatorInteraction = AZStd::make_unique<IndirectCallManipulatorViewportInteraction>();
|
||||
m_viewportManipulatorInteraction =
|
||||
AZStd::make_unique<IndirectCallManipulatorViewportInteraction>(ToolsApplicationFixtureT::CreateDebugDisplayRequests());
|
||||
m_actionDispatcher = AZStd::make_unique<ImmediateModeActionDispatcher>(*m_viewportManipulatorInteraction);
|
||||
m_cameraState =
|
||||
AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize);
|
||||
|
||||
+2
-3
@@ -17,11 +17,10 @@ namespace AzManipulatorTestFramework
|
||||
class ViewportInteraction;
|
||||
|
||||
//! Implementation of manipulator viewport interaction that manipulates the manager directly.
|
||||
class DirectCallManipulatorViewportInteraction
|
||||
: public ManipulatorViewportInteraction
|
||||
class DirectCallManipulatorViewportInteraction : public ManipulatorViewportInteraction
|
||||
{
|
||||
public:
|
||||
DirectCallManipulatorViewportInteraction();
|
||||
explicit DirectCallManipulatorViewportInteraction(AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests);
|
||||
~DirectCallManipulatorViewportInteraction();
|
||||
|
||||
// ManipulatorViewportInteractionInterface ...
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ namespace AzManipulatorTestFramework
|
||||
class IndirectCallManipulatorViewportInteraction : public ManipulatorViewportInteraction
|
||||
{
|
||||
public:
|
||||
IndirectCallManipulatorViewportInteraction();
|
||||
explicit IndirectCallManipulatorViewportInteraction(AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests);
|
||||
~IndirectCallManipulatorViewportInteraction();
|
||||
|
||||
// ManipulatorViewportInteractionInterface ...
|
||||
|
||||
+7
-4
@@ -11,10 +11,13 @@
|
||||
#include <AzFramework/Visibility/EntityVisibilityQuery.h>
|
||||
#include <AzManipulatorTestFramework/AzManipulatorTestFramework.h>
|
||||
|
||||
namespace AzFramework
|
||||
{
|
||||
class DebugDisplayRequests;
|
||||
}
|
||||
|
||||
namespace AzManipulatorTestFramework
|
||||
{
|
||||
class NullDebugDisplayRequests;
|
||||
|
||||
//! Implementation of the viewport interaction model to handle viewport interaction requests.
|
||||
class ViewportInteraction
|
||||
: public ViewportInteractionInterface
|
||||
@@ -23,7 +26,7 @@ namespace AzManipulatorTestFramework
|
||||
, private AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler
|
||||
{
|
||||
public:
|
||||
ViewportInteraction();
|
||||
explicit ViewportInteraction(AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests);
|
||||
~ViewportInteraction();
|
||||
|
||||
// ViewportInteractionInterface overrides ...
|
||||
@@ -63,7 +66,7 @@ namespace AzManipulatorTestFramework
|
||||
static constexpr AzFramework::ViewportId m_viewportId = 1234; //!< Arbitrary viewport id for manipulator tests.
|
||||
|
||||
AzFramework::EntityVisibilityQuery m_entityVisibilityQuery;
|
||||
AZStd::unique_ptr<NullDebugDisplayRequests> m_nullDebugDisplayRequests;
|
||||
AZStd::shared_ptr<AzFramework::DebugDisplayRequests> m_debugDisplayRequests;
|
||||
AzFramework::CameraState m_cameraState;
|
||||
bool m_gridSnapping = false;
|
||||
bool m_angularSnapping = false;
|
||||
|
||||
+3
-2
@@ -118,10 +118,11 @@ namespace AzManipulatorTestFramework
|
||||
return m_manipulatorManager->Interacting();
|
||||
}
|
||||
|
||||
DirectCallManipulatorViewportInteraction::DirectCallManipulatorViewportInteraction()
|
||||
DirectCallManipulatorViewportInteraction::DirectCallManipulatorViewportInteraction(
|
||||
AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests)
|
||||
: m_customManager(
|
||||
AZStd::make_unique<CustomManipulatorManager>(AzToolsFramework::ManipulatorManagerId(AZ::Crc32("TestManipulatorManagerId"))))
|
||||
, m_viewportInteraction(AZStd::make_unique<ViewportInteraction>())
|
||||
, m_viewportInteraction(AZStd::make_unique<ViewportInteraction>(AZStd::move(debugDisplayRequests)))
|
||||
, m_manipulatorManager(AZStd::make_unique<DirectCallManipulatorManager>(m_viewportInteraction.get(), m_customManager))
|
||||
{
|
||||
}
|
||||
|
||||
+3
-2
@@ -76,8 +76,9 @@ namespace AzManipulatorTestFramework
|
||||
return manipulatorInteracting;
|
||||
}
|
||||
|
||||
IndirectCallManipulatorViewportInteraction::IndirectCallManipulatorViewportInteraction()
|
||||
: m_viewportInteraction(AZStd::make_unique<ViewportInteraction>())
|
||||
IndirectCallManipulatorViewportInteraction::IndirectCallManipulatorViewportInteraction(
|
||||
AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests)
|
||||
: m_viewportInteraction(AZStd::make_unique<ViewportInteraction>(AZStd::move(debugDisplayRequests)))
|
||||
, m_manipulatorManager(AZStd::make_unique<IndirectCallManipulatorManager>(*m_viewportInteraction))
|
||||
{
|
||||
}
|
||||
|
||||
@@ -13,15 +13,8 @@
|
||||
|
||||
namespace AzManipulatorTestFramework
|
||||
{
|
||||
// Null debug display for dummy draw calls
|
||||
class NullDebugDisplayRequests : public AzFramework::DebugDisplayRequests
|
||||
{
|
||||
public:
|
||||
virtual ~NullDebugDisplayRequests() = default;
|
||||
};
|
||||
|
||||
ViewportInteraction::ViewportInteraction()
|
||||
: m_nullDebugDisplayRequests(AZStd::make_unique<NullDebugDisplayRequests>())
|
||||
ViewportInteraction::ViewportInteraction(AZStd::shared_ptr<AzFramework::DebugDisplayRequests> debugDisplayRequests)
|
||||
: m_debugDisplayRequests(AZStd::move(debugDisplayRequests))
|
||||
{
|
||||
AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler::BusConnect(m_viewportId);
|
||||
AzToolsFramework::ViewportInteraction::ViewportSettingsRequestBus::Handler::BusConnect(m_viewportId);
|
||||
@@ -102,7 +95,7 @@ namespace AzManipulatorTestFramework
|
||||
|
||||
AzFramework::DebugDisplayRequests& ViewportInteraction::GetDebugDisplay()
|
||||
{
|
||||
return *m_nullDebugDisplayRequests;
|
||||
return *m_debugDisplayRequests;
|
||||
}
|
||||
|
||||
void ViewportInteraction::SetGridSnapping(const bool enabled)
|
||||
|
||||
@@ -26,7 +26,8 @@ namespace UnitTest
|
||||
{
|
||||
public:
|
||||
GridSnappingFixture()
|
||||
: m_viewportManipulatorInteraction(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>())
|
||||
: m_viewportManipulatorInteraction(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>(
|
||||
AZStd::make_shared<NullDebugDisplayRequests>()))
|
||||
, m_actionDispatcher(
|
||||
AZStd::make_unique<AzManipulatorTestFramework::ImmediateModeActionDispatcher>(*m_viewportManipulatorInteraction))
|
||||
{
|
||||
|
||||
@@ -15,7 +15,8 @@ namespace UnitTest
|
||||
{
|
||||
public:
|
||||
AValidViewportInteraction()
|
||||
: m_viewportInteraction(AZStd::make_unique<AzManipulatorTestFramework::ViewportInteraction>())
|
||||
: m_viewportInteraction(
|
||||
AZStd::make_unique<AzManipulatorTestFramework::ViewportInteraction>(AZStd::make_shared<NullDebugDisplayRequests>()))
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
@@ -75,9 +75,11 @@ namespace UnitTest
|
||||
void SetUpEditorFixtureImpl() override
|
||||
{
|
||||
m_directState =
|
||||
AZStd::make_unique<State>(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>());
|
||||
AZStd::make_unique<State>(AZStd::make_unique<AzManipulatorTestFramework::DirectCallManipulatorViewportInteraction>(
|
||||
AZStd::make_shared<NullDebugDisplayRequests>()));
|
||||
m_busState =
|
||||
AZStd::make_unique<State>(AZStd::make_unique<AzManipulatorTestFramework::IndirectCallManipulatorViewportInteraction>());
|
||||
AZStd::make_unique<State>(AZStd::make_unique<AzManipulatorTestFramework::IndirectCallManipulatorViewportInteraction>(
|
||||
AZStd::make_shared<NullDebugDisplayRequests>()));
|
||||
m_cameraState =
|
||||
AzFramework::CreateIdentityDefaultCamera(AZ::Vector3::CreateZero(), AzManipulatorTestFramework::DefaultViewportSize);
|
||||
}
|
||||
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.58087 1.8457C8.88135 1.8457 7.99903 2.19115 6.93392 2.88204L6.92893 2.87676C6.30965 3.2791 5.82426 3.79917 5.22899 4.43697L5.22899 4.43697C4.86895 4.82273 4.46872 5.25156 3.97436 5.72345L4.40762 6.13135C6.90029 8.44469 8.28286 9.60136 9.56289 9.60136C10.2624 9.60136 11.1447 9.25592 12.2098 8.56503L12.2148 8.57031C12.9369 8.10117 13.5717 7.47196 14.368 6.68268L14.3681 6.68264C14.6677 6.38563 14.9902 6.06596 15.3489 5.72362L14.9156 5.31571C12.4229 3.00237 10.8609 1.8457 9.58087 1.8457ZM7.6529 3.64381L7.65238 3.64325C8.14738 3.13093 8.82452 2.81518 9.57127 2.81518C11.0878 2.81518 12.3171 4.11733 12.3171 5.72362C12.3171 6.53856 12.0007 7.27522 11.4909 7.80326L11.4914 7.80381C10.9964 8.31614 10.3192 8.63189 9.57249 8.63189C8.05599 8.63189 6.82663 7.32973 6.82663 5.72345C6.82663 4.90851 7.14307 4.17185 7.6529 3.64381ZM9.56659 3.78466C9.05074 3.78466 8.58461 4.0095 8.25119 4.37149L8.25649 4.3771C7.93789 4.72586 7.74192 5.20047 7.74192 5.72345C7.74192 6.79431 8.56359 7.66241 9.57717 7.66241C10.093 7.66241 10.5592 7.43756 10.8926 7.07558L10.8873 7.06997C11.2059 6.72121 11.4018 6.24659 11.4018 5.72362C11.4018 4.65276 10.5802 3.78466 9.56659 3.78466ZM2.97474 1.99964H6.70318C6.07867 2.40803 5.53108 2.87237 5.07056 3.38303H2.97474C2.38778 3.38303 1.896 3.86007 1.896 4.44841V13.035C1.896 13.6233 2.37192 14.1003 2.97474 14.1003H11.5094C12.0964 14.1003 12.5881 13.6392 12.5881 13.035H12.6199V9.26317C13.1109 8.93674 13.5803 8.5478 14 8.10987V13.035C14 14.4025 12.8895 15.4996 11.5253 15.4996H2.97474C1.61046 15.4996 0.5 14.4025 0.5 13.035V4.44841C0.5 3.09681 1.61046 1.99964 2.97474 1.99964Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -0,0 +1,3 @@
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M3 4.60547C3 2.94862 4.34315 1.60547 6 1.60547C7.65685 1.60547 9 2.94862 9 4.60547V5.84076H10V6.60547C10 7.53544 10 8.00043 9.89778 8.38193C9.62038 9.4172 8.81173 10.2258 7.77646 10.5032C7.39496 10.6055 6.92997 10.6055 6 10.6055C5.07003 10.6055 4.60504 10.6055 4.22354 10.5032C3.18827 10.2258 2.37962 9.4172 2.10222 8.38193C2 8.00043 2 7.53544 2 6.60547V5.84076H3V4.60547ZM5.25 6.89953V9.54659H6.75V6.89953H5.25ZM6 2.66429C4.89543 2.66429 4 3.55972 4 4.66429V5.84076L8 5.84076V4.66429C8 3.55972 7.10457 2.66429 6 2.66429Z" fill="white"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 690 B |
@@ -7,7 +7,9 @@
|
||||
<file alias="prefab.svg">Entity/prefab.svg</file>
|
||||
<file alias="prefab_edit.svg">Entity/prefab_edit.svg</file>
|
||||
<file alias="prefab_edit_open.svg">Entity/prefab_edit_open.svg</file>
|
||||
<file alias="prefab_edit_open_readonly.svg">Entity/prefab_edit_open_readonly.svg</file>
|
||||
<file alias="prefab_edit_close.svg">Entity/prefab_edit_close.svg</file>
|
||||
<file alias="readonly.svg">Entity/readonly.svg</file>
|
||||
</qresource>
|
||||
<qresource prefix="/Level">
|
||||
<file alias="level.svg">Level/level.svg</file>
|
||||
|
||||
@@ -14,7 +14,6 @@
|
||||
#define AZ_TRAIT_UNIT_TEST_DILLER_TRIGGER_EVENT_COUNT 100000
|
||||
|
||||
#define AZ_TRAIT_DISABLE_FAILED_AP_CONNECTION_TESTS true
|
||||
#define AZ_TRAIT_DISABLE_FAILED_ASSET_LOAD_TESTS true
|
||||
|
||||
#define AZ_TRAIT_DISABLE_FAILED_ATOM_RPI_TESTS true
|
||||
#define AZ_TRAIT_DISABLE_FAILED_ARCHIVE_TESTS true
|
||||
|
||||
+12
@@ -99,6 +99,18 @@ namespace AzToolsFramework
|
||||
}
|
||||
}
|
||||
|
||||
if (selection.GetSelectedAssetIds().empty())
|
||||
{
|
||||
for (auto& filePath : selection.GetSelectedFilePaths())
|
||||
{
|
||||
if (!filePath.empty())
|
||||
{
|
||||
selectedAsset = true;
|
||||
m_ui->m_assetBrowserTreeViewWidget->SelectFileAtPath(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!selectedAsset)
|
||||
{
|
||||
m_ui->m_assetBrowserTreeViewWidget->SelectFolder(selection.GetDefaultDirectory());
|
||||
|
||||
+60
-9
@@ -10,18 +10,24 @@
|
||||
#include <AzToolsFramework/AssetBrowser/AssetBrowserBus.h>
|
||||
#include <AzToolsFramework/AssetBrowser/EBusFindAssetTypeByName.h>
|
||||
|
||||
#if !defined(Q_MOC_RUN)
|
||||
AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option")
|
||||
#include <QRegExp>
|
||||
AZ_POP_DISABLE_WARNING
|
||||
#endif
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
namespace AssetBrowser
|
||||
{
|
||||
namespace
|
||||
{
|
||||
FilterConstType ProductsNoFoldersFilter()
|
||||
FilterConstType EntryTypeNoFoldersFilter(AssetBrowserEntry::AssetEntryType entryType = AssetBrowserEntry::AssetEntryType::Product)
|
||||
{
|
||||
EntryTypeFilter* productFilter = new EntryTypeFilter();
|
||||
productFilter->SetEntryType(AssetBrowserEntry::AssetEntryType::Product);
|
||||
EntryTypeFilter* entryTypeFilter = new EntryTypeFilter();
|
||||
entryTypeFilter->SetEntryType(entryType);
|
||||
// in case entry is a source or folder, it may still contain relevant product
|
||||
productFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down);
|
||||
entryTypeFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down);
|
||||
|
||||
EntryTypeFilter* foldersFilter = new EntryTypeFilter();
|
||||
foldersFilter->SetEntryType(AssetBrowserEntry::AssetEntryType::Folder);
|
||||
@@ -30,7 +36,7 @@ namespace AzToolsFramework
|
||||
noFoldersFilter->SetFilter(FilterConstType(foldersFilter));
|
||||
|
||||
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
|
||||
compFilter->AddFilter(FilterConstType(productFilter));
|
||||
compFilter->AddFilter(FilterConstType(entryTypeFilter));
|
||||
compFilter->AddFilter(FilterConstType(noFoldersFilter));
|
||||
|
||||
return FilterConstType(compFilter);
|
||||
@@ -79,15 +85,39 @@ namespace AzToolsFramework
|
||||
|
||||
void AssetSelectionModel::SetSelectedAssetIds(const AZStd::vector<AZ::Data::AssetId>& selectedAssetIds)
|
||||
{
|
||||
m_selectedFilePaths.clear();
|
||||
|
||||
m_selectedAssetIds = selectedAssetIds;
|
||||
}
|
||||
|
||||
void AssetSelectionModel::SetSelectedAssetId(const AZ::Data::AssetId& selectedAssetId)
|
||||
{
|
||||
m_selectedFilePaths.clear();
|
||||
|
||||
m_selectedAssetIds.clear();
|
||||
m_selectedAssetIds.push_back(selectedAssetId);
|
||||
}
|
||||
|
||||
const AZStd::vector<AZStd::string>& AssetSelectionModel::GetSelectedFilePaths() const
|
||||
{
|
||||
return m_selectedFilePaths;
|
||||
}
|
||||
|
||||
void AssetSelectionModel::SetSelectedFilePaths(const AZStd::vector<AZStd::string>& selectedFilePaths)
|
||||
{
|
||||
m_selectedAssetIds.clear();
|
||||
|
||||
m_selectedFilePaths = selectedFilePaths;
|
||||
}
|
||||
|
||||
void AssetSelectionModel::SetSelectedFilePath(const AZStd::string& selectedFilePath)
|
||||
{
|
||||
m_selectedAssetIds.clear();
|
||||
|
||||
m_selectedFilePaths.clear();
|
||||
m_selectedFilePaths.push_back(selectedFilePath);
|
||||
}
|
||||
|
||||
void AssetSelectionModel::SetDefaultDirectory(AZStd::string_view defaultDirectory)
|
||||
{
|
||||
m_defaultDirectory = defaultDirectory;
|
||||
@@ -136,7 +166,7 @@ namespace AzToolsFramework
|
||||
|
||||
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
|
||||
compFilter->AddFilter(assetTypeFilterPtr);
|
||||
compFilter->AddFilter(ProductsNoFoldersFilter());
|
||||
compFilter->AddFilter(EntryTypeNoFoldersFilter());
|
||||
|
||||
selection.SetSelectionFilter(FilterConstType(compFilter));
|
||||
selection.SetMultiselect(multiselect);
|
||||
@@ -169,7 +199,7 @@ namespace AzToolsFramework
|
||||
|
||||
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
|
||||
compFilter->AddFilter(anyAssetTypeFilterPtr);
|
||||
compFilter->AddFilter(ProductsNoFoldersFilter());
|
||||
compFilter->AddFilter(EntryTypeNoFoldersFilter());
|
||||
|
||||
selection.SetSelectionFilter(FilterConstType(compFilter));
|
||||
selection.SetMultiselect(multiselect);
|
||||
@@ -190,7 +220,28 @@ namespace AzToolsFramework
|
||||
|
||||
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
|
||||
compFilter->AddFilter(assetGroupFilterPtr);
|
||||
compFilter->AddFilter(ProductsNoFoldersFilter());
|
||||
compFilter->AddFilter(EntryTypeNoFoldersFilter());
|
||||
|
||||
selection.SetSelectionFilter(FilterConstType(compFilter));
|
||||
selection.SetMultiselect(multiselect);
|
||||
|
||||
return selection;
|
||||
}
|
||||
|
||||
AssetSelectionModel AssetSelectionModel::SourceAssetTypeSelection(const QString& pattern, bool multiselect)
|
||||
{
|
||||
AssetSelectionModel selection;
|
||||
|
||||
RegExpFilter* patternFilter = new RegExpFilter();
|
||||
patternFilter->SetFilterPattern(pattern);
|
||||
patternFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down);
|
||||
auto patternFilterPtr = FilterConstType(patternFilter);
|
||||
|
||||
selection.SetDisplayFilter(patternFilterPtr);
|
||||
|
||||
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND);
|
||||
compFilter->AddFilter(patternFilterPtr);
|
||||
compFilter->AddFilter(EntryTypeNoFoldersFilter(AssetBrowserEntry::AssetEntryType::Source));
|
||||
|
||||
selection.SetSelectionFilter(FilterConstType(compFilter));
|
||||
selection.SetMultiselect(multiselect);
|
||||
@@ -204,7 +255,7 @@ namespace AzToolsFramework
|
||||
|
||||
CompositeFilter* compFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::OR);
|
||||
selection.SetDisplayFilter(FilterConstType(compFilter));
|
||||
selection.SetSelectionFilter(ProductsNoFoldersFilter());
|
||||
selection.SetSelectionFilter(EntryTypeNoFoldersFilter());
|
||||
selection.SetMultiselect(multiselect);
|
||||
|
||||
return selection;
|
||||
|
||||
+10
-1
@@ -44,6 +44,10 @@ namespace AzToolsFramework
|
||||
void SetSelectedAssetIds(const AZStd::vector<AZ::Data::AssetId>& selectedAssetIds);
|
||||
void SetSelectedAssetId(const AZ::Data::AssetId& selectedAssetId);
|
||||
|
||||
const AZStd::vector<AZStd::string>& GetSelectedFilePaths() const;
|
||||
void SetSelectedFilePaths(const AZStd::vector<AZStd::string>& selectedFilePaths);
|
||||
void SetSelectedFilePath(const AZStd::string& selectedFilePath);
|
||||
|
||||
void SetDefaultDirectory(AZStd::string_view defaultDirectory);
|
||||
AZStd::string_view GetDefaultDirectory() const;
|
||||
|
||||
@@ -60,6 +64,7 @@ namespace AzToolsFramework
|
||||
static AssetSelectionModel AssetTypeSelection(const char* assetTypeName, bool multiselect = false);
|
||||
static AssetSelectionModel AssetTypesSelection(const AZStd::vector<AZ::Data::AssetType>& assetTypes, bool multiselect = false);
|
||||
static AssetSelectionModel AssetGroupSelection(const char* group, bool multiselect = false);
|
||||
static AssetSelectionModel SourceAssetTypeSelection(const QString& pattern, bool multiselect = false);
|
||||
static AssetSelectionModel EverythingSelection(bool multiselect = false);
|
||||
|
||||
private:
|
||||
@@ -68,8 +73,12 @@ namespace AzToolsFramework
|
||||
// some entries like folder should always be displayed, but not always selectable, thus 2 separate filters
|
||||
FilterConstType m_selectionFilter;
|
||||
FilterConstType m_displayFilter;
|
||||
|
||||
|
||||
//! Selection can be based on asset ids (for products), or file paths (for sources)
|
||||
//! These are mututally exclusive
|
||||
AZStd::vector<AZ::Data::AssetId> m_selectedAssetIds;
|
||||
AZStd::vector<AZStd::string> m_selectedFilePaths;
|
||||
|
||||
AZStd::vector<const AssetBrowserEntry*> m_results;
|
||||
AZStd::string m_defaultDirectory;
|
||||
|
||||
|
||||
@@ -251,6 +251,40 @@ namespace AzToolsFramework
|
||||
return false;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// RegExpFilter
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
RegExpFilter::RegExpFilter()
|
||||
: m_filterPattern("")
|
||||
{
|
||||
}
|
||||
|
||||
void RegExpFilter::SetFilterPattern(const QString& filterPattern)
|
||||
{
|
||||
m_filterPattern = filterPattern;
|
||||
Q_EMIT updatedSignal();
|
||||
}
|
||||
|
||||
QString RegExpFilter::GetNameInternal() const
|
||||
{
|
||||
return m_filterPattern;
|
||||
}
|
||||
|
||||
bool RegExpFilter::MatchInternal(const AssetBrowserEntry* entry) const
|
||||
{
|
||||
// no filter pattern matches any asset
|
||||
if (m_filterPattern.isEmpty())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// entry's name matches regular expression pattern
|
||||
QRegExp regExp(m_filterPattern);
|
||||
regExp.setPatternSyntax(QRegExp::Wildcard);
|
||||
|
||||
return regExp.exactMatch(entry->GetDisplayName());
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// AssetTypeFilter
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
@@ -115,6 +115,28 @@ namespace AzToolsFramework
|
||||
QString m_filterString;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// RegExpFilter
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
//! RegExpFilter filters assets based on a regular expression pattern
|
||||
class RegExpFilter
|
||||
: public AssetBrowserEntryFilter
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
RegExpFilter();
|
||||
~RegExpFilter() override = default;
|
||||
|
||||
void SetFilterPattern(const QString& filterPattern);
|
||||
|
||||
protected:
|
||||
QString GetNameInternal() const override;
|
||||
bool MatchInternal(const AssetBrowserEntry* entry) const override;
|
||||
|
||||
private:
|
||||
QString m_filterPattern;
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// AssetTypeFilter
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
|
||||
+2
-2
@@ -37,9 +37,9 @@ namespace AzToolsFramework
|
||||
static void Reflect(AZ::ReflectContext* context);
|
||||
static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided);
|
||||
|
||||
// ReadOnlyEntityPublicNotifications overrides ...
|
||||
// ReadOnlyEntityPublicInterface overrides ...
|
||||
bool IsReadOnly(const AZ::EntityId& entityId) override;
|
||||
|
||||
|
||||
// ReadOnlyEntityQueryInterface overrides ...
|
||||
void RefreshReadOnlyState(const EntityIdList& entityIds) override;
|
||||
void RefreshReadOnlyStateForAllEntities() override;
|
||||
|
||||
@@ -50,7 +50,7 @@ namespace AzToolsFramework
|
||||
return false;
|
||||
}
|
||||
|
||||
void TraceLogger::PrepareLogFile(const AZStd::string& logFileName)
|
||||
void TraceLogger::OpenLogFile(const AZStd::string& logFileName, bool clearLogFile)
|
||||
{
|
||||
using namespace AzFramework;
|
||||
|
||||
@@ -73,7 +73,7 @@ namespace AzToolsFramework
|
||||
AZStd::string logPath;
|
||||
StringFunc::Path::Join(logDirectory.c_str(), logFileName.c_str(), logPath);
|
||||
|
||||
m_logFile.reset(aznew LogFile(logPath.c_str()));
|
||||
m_logFile.reset(aznew LogFile(logPath.c_str(), clearLogFile));
|
||||
if (m_logFile)
|
||||
{
|
||||
m_logFile->SetMachineReadable(false);
|
||||
@@ -81,7 +81,7 @@ namespace AzToolsFramework
|
||||
{
|
||||
m_logFile->AppendLog(LogFile::SEV_NORMAL, message.window.c_str(), message.message.c_str());
|
||||
}
|
||||
m_startupLogSink = {};
|
||||
m_startupLogSink.clear();
|
||||
m_logFile->FlushLog();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ namespace AzToolsFramework
|
||||
~TraceLogger();
|
||||
|
||||
//! Open log file and dump log sink into it
|
||||
void PrepareLogFile(const AZStd::string& logFileName);
|
||||
void OpenLogFile(const AZStd::string& logFileName, bool clearLogFile);
|
||||
|
||||
//! Add filter to ignore messages for windows with matching names
|
||||
void AddWindowFilter(const AZStd::string& filter);
|
||||
@@ -55,7 +55,8 @@ namespace AzToolsFramework
|
||||
AZStd::string window;
|
||||
AZStd::string message;
|
||||
};
|
||||
AZStd::vector<LogMessage> m_startupLogSink;
|
||||
|
||||
AZStd::list<LogMessage> m_startupLogSink;
|
||||
AZStd::unordered_set<AZStd::string> m_windowFilters;
|
||||
AZStd::unordered_set<AZStd::string> m_messageFilters;
|
||||
AZStd::unique_ptr<AzFramework::LogFile> m_logFile;
|
||||
|
||||
+2
-2
@@ -191,8 +191,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
m_manipulatorView->Draw(
|
||||
GetManipulatorManagerId(), managerState, GetManipulatorId(),
|
||||
{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, cameraState,
|
||||
mouseInteraction);
|
||||
ManipulatorState{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
|
||||
cameraState, mouseInteraction);
|
||||
}
|
||||
|
||||
void AngularManipulator::SetAxis(const AZ::Vector3& axis)
|
||||
|
||||
+2
-2
@@ -116,8 +116,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
m_manipulatorView->Draw(
|
||||
GetManipulatorManagerId(), managerState, GetManipulatorId(),
|
||||
{ TransformUniformScale(GetSpace()), GetNonUniformScale(), m_localStart, MouseOver() }, debugDisplay, cameraState,
|
||||
mouseInteraction);
|
||||
ManipulatorState{ TransformUniformScale(GetSpace()), GetNonUniformScale(), m_localStart, MouseOver() }, debugDisplay,
|
||||
cameraState, mouseInteraction);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -239,8 +239,8 @@ namespace AzToolsFramework
|
||||
|
||||
view->Draw(
|
||||
GetManipulatorManagerId(), managerState, GetManipulatorId(),
|
||||
{ ApplySpace(localTransform), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay, cameraState,
|
||||
mouseInteraction);
|
||||
ManipulatorState{ ApplySpace(localTransform), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
|
||||
cameraState, mouseInteraction);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -146,7 +146,7 @@ namespace AzToolsFramework
|
||||
|
||||
for (const auto& pair : m_manipulatorIdToPtrMap)
|
||||
{
|
||||
pair.second->Draw({ Interacting() }, debugDisplay, cameraState, mouseInteraction);
|
||||
pair.second->Draw(ManipulatorManagerState{ Interacting() }, debugDisplay, cameraState, mouseInteraction);
|
||||
}
|
||||
|
||||
RefreshMouseOverState(mouseInteraction.m_mousePick);
|
||||
|
||||
@@ -10,6 +10,15 @@
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
AZ::Transform ApplySpace(const AZ::Transform& localTransform, const AZ::Transform& space, const AZ::Vector3& nonUniformScale)
|
||||
{
|
||||
AZ::Transform result;
|
||||
result.SetRotation(space.GetRotation() * localTransform.GetRotation());
|
||||
result.SetTranslation(space.TransformPoint(nonUniformScale * localTransform.GetTranslation()));
|
||||
result.SetUniformScale(space.GetUniformScale() * localTransform.GetUniformScale());
|
||||
return result;
|
||||
}
|
||||
|
||||
const AZ::Transform& ManipulatorSpace::GetSpace() const
|
||||
{
|
||||
return m_space;
|
||||
@@ -32,11 +41,7 @@ namespace AzToolsFramework
|
||||
|
||||
AZ::Transform ManipulatorSpace::ApplySpace(const AZ::Transform& localTransform) const
|
||||
{
|
||||
AZ::Transform result;
|
||||
result.SetRotation(m_space.GetRotation() * localTransform.GetRotation());
|
||||
result.SetTranslation(m_space.TransformPoint(m_nonUniformScale * localTransform.GetTranslation()));
|
||||
result.SetUniformScale(m_space.GetUniformScale() * localTransform.GetUniformScale());
|
||||
return result;
|
||||
return AzToolsFramework::ApplySpace(localTransform, m_space, m_nonUniformScale);
|
||||
}
|
||||
|
||||
const AZ::Vector3& ManipulatorSpaceWithLocalPosition::GetLocalPosition() const
|
||||
|
||||
@@ -17,6 +17,8 @@ namespace AZ
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
AZ::Transform ApplySpace(const AZ::Transform& localTransform, const AZ::Transform& space, const AZ::Vector3& nonUniformScale);
|
||||
|
||||
//! Handles location for manipulators which have a global space but no local transformation.
|
||||
class ManipulatorSpace
|
||||
{
|
||||
|
||||
@@ -383,8 +383,8 @@ namespace AzToolsFramework
|
||||
debugDisplay.DrawLine(quadBoundVisual.m_corner1, quadBoundVisual.m_corner2);
|
||||
|
||||
debugDisplay.SetColor(ViewColor(manipulatorState.m_mouseOver, m_axis2Color, m_mouseOverColor).GetAsVector4());
|
||||
debugDisplay.DrawLine(quadBoundVisual.m_corner4, quadBoundVisual.m_corner1);
|
||||
debugDisplay.DrawLine(quadBoundVisual.m_corner2, quadBoundVisual.m_corner3);
|
||||
debugDisplay.DrawLine(quadBoundVisual.m_corner1, quadBoundVisual.m_corner4);
|
||||
|
||||
if (manipulatorState.m_mouseOver)
|
||||
{
|
||||
@@ -738,15 +738,16 @@ namespace AzToolsFramework
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
AZStd::unique_ptr<ManipulatorViewQuad> CreateManipulatorViewQuad(
|
||||
const PlanarManipulator& planarManipulator,
|
||||
const AZ::Vector3& axis1,
|
||||
const AZ::Vector3& axis2,
|
||||
const AZ::Color& axis1Color,
|
||||
const AZ::Color& axis2Color,
|
||||
const AZ::Vector3& offset,
|
||||
const float size)
|
||||
{
|
||||
AZStd::unique_ptr<ManipulatorViewQuad> viewQuad = AZStd::make_unique<ManipulatorViewQuad>();
|
||||
viewQuad->m_axis1 = planarManipulator.GetAxis1();
|
||||
viewQuad->m_axis2 = planarManipulator.GetAxis2();
|
||||
viewQuad->m_axis1 = axis1;
|
||||
viewQuad->m_axis2 = axis2;
|
||||
viewQuad->m_size = size;
|
||||
viewQuad->m_offset = offset;
|
||||
viewQuad->m_axis1Color = axis1Color;
|
||||
|
||||
@@ -382,7 +382,8 @@ namespace AzToolsFramework
|
||||
// Helpers to create various manipulator views.
|
||||
|
||||
AZStd::unique_ptr<ManipulatorViewQuad> CreateManipulatorViewQuad(
|
||||
const PlanarManipulator& planarManipulator,
|
||||
const AZ::Vector3& axis1,
|
||||
const AZ::Vector3& axis2,
|
||||
const AZ::Color& axis1Color,
|
||||
const AZ::Color& axis2Color,
|
||||
const AZ::Vector3& offset,
|
||||
|
||||
+2
-2
@@ -145,8 +145,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
view->Draw(
|
||||
GetManipulatorManagerId(), managerState, GetManipulatorId(),
|
||||
{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
|
||||
cameraState, mouseInteraction);
|
||||
ManipulatorState{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() },
|
||||
debugDisplay, cameraState, mouseInteraction);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -202,8 +202,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
view->Draw(
|
||||
GetManipulatorManagerId(), managerState, GetManipulatorId(),
|
||||
{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
|
||||
cameraState, mouseInteraction);
|
||||
ManipulatorState{ ApplySpace(GetLocalTransform()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() },
|
||||
debugDisplay, cameraState, mouseInteraction);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -90,8 +90,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
view->Draw(
|
||||
GetManipulatorManagerId(), managerState, GetManipulatorId(),
|
||||
{ TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay, cameraState,
|
||||
mouseInteraction);
|
||||
ManipulatorState{ TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay,
|
||||
cameraState, mouseInteraction);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -94,8 +94,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
m_manipulatorView->Draw(
|
||||
GetManipulatorManagerId(), managerState, GetManipulatorId(),
|
||||
{ TransformUniformScale(GetSpace()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() }, debugDisplay,
|
||||
cameraState, mouseInteraction);
|
||||
ManipulatorState{ TransformUniformScale(GetSpace()), GetNonUniformScale(), AZ::Vector3::CreateZero(), MouseOver() },
|
||||
debugDisplay, cameraState, mouseInteraction);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -166,8 +166,8 @@ namespace AzToolsFramework
|
||||
{
|
||||
m_manipulatorView->Draw(
|
||||
GetManipulatorManagerId(), managerState, GetManipulatorId(),
|
||||
{ TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay, cameraState,
|
||||
mouseInteraction);
|
||||
ManipulatorState{ TransformUniformScale(GetSpace()), GetNonUniformScale(), GetLocalPosition(), MouseOver() }, debugDisplay,
|
||||
cameraState, mouseInteraction);
|
||||
}
|
||||
|
||||
void SurfaceManipulator::InvalidateImpl()
|
||||
|
||||
+58
-22
@@ -19,6 +19,21 @@ namespace AzToolsFramework
|
||||
static const AZ::Color LinearManipulatorZAxisColor = AZ::Color(0.0f, 0.0f, 1.0f, 1.0f);
|
||||
static const AZ::Color SurfaceManipulatorColor = AZ::Color(1.0f, 1.0f, 0.0f, 0.5f);
|
||||
|
||||
static TranslationManipulatorsViewCreateInfo DefaultTranslationManipulatorViewCreateInfo()
|
||||
{
|
||||
TranslationManipulatorsViewCreateInfo createInfo;
|
||||
createInfo.axis1Color = LinearManipulatorXAxisColor;
|
||||
createInfo.axis2Color = LinearManipulatorYAxisColor;
|
||||
createInfo.axis3Color = LinearManipulatorZAxisColor;
|
||||
createInfo.surfaceColor = SurfaceManipulatorColor;
|
||||
createInfo.linearAxisLength = LinearManipulatorAxisLength();
|
||||
createInfo.linearConeLength = LinearManipulatorConeLength();
|
||||
createInfo.linearConeRadius = LinearManipulatorConeRadius();
|
||||
createInfo.planarAxisLength = PlanarManipulatorAxisLength();
|
||||
createInfo.surfaceRadius = SurfaceManipulatorRadius();
|
||||
return createInfo;
|
||||
}
|
||||
|
||||
TranslationManipulators::TranslationManipulators(
|
||||
const Dimensions dimensions, const AZ::Transform& worldFromLocal, const AZ::Vector3& nonUniformScale)
|
||||
: m_dimensions(dimensions)
|
||||
@@ -231,17 +246,36 @@ namespace AzToolsFramework
|
||||
}
|
||||
}
|
||||
|
||||
void TranslationManipulators::ConfigureView2d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo)
|
||||
{
|
||||
ConfigureLinearView(
|
||||
translationManipulatorViewCreateInfo.linearAxisLength, translationManipulatorViewCreateInfo.linearConeLength,
|
||||
translationManipulatorViewCreateInfo.linearConeRadius, translationManipulatorViewCreateInfo.axis1Color,
|
||||
translationManipulatorViewCreateInfo.axis2Color, translationManipulatorViewCreateInfo.axis3Color);
|
||||
ConfigurePlanarView(
|
||||
translationManipulatorViewCreateInfo.planarAxisLength, translationManipulatorViewCreateInfo.linearAxisLength,
|
||||
translationManipulatorViewCreateInfo.linearConeLength, translationManipulatorViewCreateInfo.axis1Color,
|
||||
translationManipulatorViewCreateInfo.axis2Color, translationManipulatorViewCreateInfo.axis3Color);
|
||||
}
|
||||
|
||||
void TranslationManipulators::ConfigureView3d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo)
|
||||
{
|
||||
ConfigureView2d(translationManipulatorViewCreateInfo);
|
||||
ConfigureSurfaceView(translationManipulatorViewCreateInfo.surfaceRadius, translationManipulatorViewCreateInfo.surfaceColor);
|
||||
}
|
||||
|
||||
void TranslationManipulators::ConfigureLinearView(
|
||||
const float axisLength,
|
||||
const float coneLength,
|
||||
const float coneRadius,
|
||||
const AZ::Color& axis1Color,
|
||||
const AZ::Color& axis2Color,
|
||||
const AZ::Color& axis3Color /*= AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)*/)
|
||||
{
|
||||
const AZ::Color axesColor[] = { axis1Color, axis2Color, axis3Color };
|
||||
|
||||
const auto configureLinearView =
|
||||
[lineBoundWidth = m_lineBoundWidth, coneLength = LinearManipulatorConeLength(), axisLength,
|
||||
coneRadius = LinearManipulatorConeRadius()](LinearManipulator* linearManipulator, const AZ::Color& color)
|
||||
const auto configureLinearView = [lineBoundWidth = m_lineBoundWidth, coneLength, axisLength,
|
||||
coneRadius](LinearManipulator* linearManipulator, const AZ::Color& color)
|
||||
{
|
||||
const auto lineLength = axisLength - coneLength;
|
||||
|
||||
@@ -259,25 +293,21 @@ namespace AzToolsFramework
|
||||
}
|
||||
|
||||
void TranslationManipulators::ConfigurePlanarView(
|
||||
const float planeSize,
|
||||
const float planarAxisLength,
|
||||
const float linearAxisLength,
|
||||
const float linearConeLength,
|
||||
const AZ::Color& plane1Color,
|
||||
const AZ::Color& plane2Color /*= AZ::Color(0.0f, 1.0f, 0.0f, 0.5f)*/,
|
||||
const AZ::Color& plane3Color /*= AZ::Color(0.0f, 0.0f, 1.0f, 0.5f)*/)
|
||||
{
|
||||
const AZ::Color planesColor[] = { plane1Color, plane2Color, plane3Color };
|
||||
|
||||
const float linearAxisLength = LinearManipulatorAxisLength();
|
||||
const float linearConeLength = LinearManipulatorConeLength();
|
||||
for (size_t manipulatorIndex = 0; manipulatorIndex < m_planarManipulators.size(); ++manipulatorIndex)
|
||||
{
|
||||
const auto& planarManipulator = *m_planarManipulators[manipulatorIndex];
|
||||
const AZStd::shared_ptr<ManipulatorViewQuad> manipulatorView = CreateManipulatorViewQuad(
|
||||
*m_planarManipulators[manipulatorIndex], planesColor[manipulatorIndex], planesColor[(manipulatorIndex + 1) % 3],
|
||||
(planarManipulator.GetAxis1() + planarManipulator.GetAxis2()) *
|
||||
(((linearAxisLength - linearConeLength) * 0.5f) - (planeSize * 0.5f)),
|
||||
planeSize);
|
||||
|
||||
m_planarManipulators[manipulatorIndex]->SetViews(ManipulatorViews{ manipulatorView });
|
||||
m_planarManipulators[manipulatorIndex]->SetViews(ManipulatorViews{ CreateManipulatorViewQuadForPlanarTranslationManipulator(
|
||||
planarManipulator.GetAxis1(), planarManipulator.GetAxis2(), planesColor[manipulatorIndex],
|
||||
planesColor[(manipulatorIndex + 1) % 3], linearAxisLength, linearConeLength, planarAxisLength) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,19 +355,25 @@ namespace AzToolsFramework
|
||||
void ConfigureTranslationManipulatorAppearance3d(TranslationManipulators* translationManipulators)
|
||||
{
|
||||
translationManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ());
|
||||
translationManipulators->ConfigurePlanarView(
|
||||
PlanarManipulatorAxisLength(), LinearManipulatorXAxisColor, LinearManipulatorYAxisColor, LinearManipulatorZAxisColor);
|
||||
translationManipulators->ConfigureLinearView(
|
||||
LinearManipulatorAxisLength(), LinearManipulatorXAxisColor, LinearManipulatorYAxisColor, LinearManipulatorZAxisColor);
|
||||
translationManipulators->ConfigureSurfaceView(SurfaceManipulatorRadius(), SurfaceManipulatorColor);
|
||||
translationManipulators->ConfigureView3d(DefaultTranslationManipulatorViewCreateInfo());
|
||||
}
|
||||
|
||||
void ConfigureTranslationManipulatorAppearance2d(TranslationManipulators* translationManipulators)
|
||||
{
|
||||
translationManipulators->SetAxes(AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY());
|
||||
translationManipulators->ConfigurePlanarView(
|
||||
PlanarManipulatorAxisLength(), LinearManipulatorXAxisColor, LinearManipulatorYAxisColor);
|
||||
translationManipulators->ConfigureLinearView(
|
||||
LinearManipulatorAxisLength(), LinearManipulatorXAxisColor, LinearManipulatorYAxisColor);
|
||||
translationManipulators->ConfigureView2d(DefaultTranslationManipulatorViewCreateInfo());
|
||||
}
|
||||
|
||||
AZStd::shared_ptr<ManipulatorViewQuad> CreateManipulatorViewQuadForPlanarTranslationManipulator(
|
||||
const AZ::Vector3& axis1,
|
||||
const AZ::Vector3& axis2,
|
||||
const AZ::Color& axis1Color,
|
||||
const AZ::Color& axis2Color,
|
||||
const float linearAxisLength,
|
||||
const float linearConeLength,
|
||||
const float planarAxisLength)
|
||||
{
|
||||
const AZ::Vector3 offset = (axis1 + axis2) * (((linearAxisLength - linearConeLength) * 0.5f) - (planarAxisLength * 0.5f));
|
||||
return CreateManipulatorViewQuad(axis1, axis2, axis1Color, axis2Color, offset, planarAxisLength);
|
||||
}
|
||||
} // namespace AzToolsFramework
|
||||
|
||||
+36
-6
@@ -15,6 +15,20 @@
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
//! Parameters to configure the appearance of the TranslationManipulators view(s).
|
||||
struct TranslationManipulatorsViewCreateInfo
|
||||
{
|
||||
float linearAxisLength;
|
||||
float linearConeLength;
|
||||
float linearConeRadius;
|
||||
float planarAxisLength;
|
||||
float surfaceRadius;
|
||||
AZ::Color axis1Color;
|
||||
AZ::Color axis2Color;
|
||||
AZ::Color axis3Color;
|
||||
AZ::Color surfaceColor;
|
||||
};
|
||||
|
||||
//! TranslationManipulators is an aggregation of 3 linear manipulators, 3 planar manipulators
|
||||
//! and one surface manipulator who share the same transform.
|
||||
class TranslationManipulators : public Manipulators
|
||||
@@ -23,6 +37,9 @@ namespace AzToolsFramework
|
||||
AZ_RTTI(TranslationManipulators, "{D5E49EA2-30E0-42BC-A51D-6A7F87818260}")
|
||||
AZ_CLASS_ALLOCATOR(TranslationManipulators, AZ::SystemAllocator, 0)
|
||||
|
||||
TranslationManipulators(TranslationManipulators&&) = delete;
|
||||
TranslationManipulators& operator=(TranslationManipulators&&) = delete;
|
||||
|
||||
//! How many dimensions does this translation manipulator have.
|
||||
enum class Dimensions
|
||||
{
|
||||
@@ -52,26 +69,31 @@ namespace AzToolsFramework
|
||||
|
||||
void SetAxes(const AZ::Vector3& axis1, const AZ::Vector3& axis2, const AZ::Vector3& axis3 = AZ::Vector3::CreateAxisZ());
|
||||
|
||||
void ConfigureView2d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo);
|
||||
void ConfigureView3d(const TranslationManipulatorsViewCreateInfo& translationManipulatorViewCreateInfo);
|
||||
|
||||
//! Sets the bound width to use for the line/axis of a linear manipulator.
|
||||
void SetLineBoundWidth(float lineBoundWidth);
|
||||
|
||||
private:
|
||||
void ConfigurePlanarView(
|
||||
float planeSize,
|
||||
float linearAxisLength,
|
||||
float linearConeLength,
|
||||
const AZ::Color& plane1Color,
|
||||
const AZ::Color& plane2Color = AZ::Color(0.0f, 1.0f, 0.0f, 0.5f),
|
||||
const AZ::Color& plane3Color = AZ::Color(0.0f, 0.0f, 1.0f, 0.5f));
|
||||
|
||||
void ConfigureLinearView(
|
||||
float axisLength,
|
||||
float coneLength,
|
||||
float coneRadius,
|
||||
const AZ::Color& axis1Color,
|
||||
const AZ::Color& axis2Color,
|
||||
const AZ::Color& axis3Color = AZ::Color(0.0f, 0.0f, 1.0f, 0.5f));
|
||||
|
||||
void ConfigureSurfaceView(float radius, const AZ::Color& color);
|
||||
|
||||
//! Sets the bound width to use for the line/axis of a linear manipulator.
|
||||
void SetLineBoundWidth(float lineBoundWidth);
|
||||
|
||||
private:
|
||||
AZ_DISABLE_COPY_MOVE(TranslationManipulators)
|
||||
|
||||
// Manipulators
|
||||
void ProcessManipulators(const AZStd::function<void(BaseManipulator*)>&) override;
|
||||
|
||||
@@ -131,4 +153,12 @@ namespace AzToolsFramework
|
||||
void ConfigureTranslationManipulatorAppearance3d(TranslationManipulators* translationManipulators);
|
||||
void ConfigureTranslationManipulatorAppearance2d(TranslationManipulators* translationManipulators);
|
||||
|
||||
AZStd::shared_ptr<ManipulatorViewQuad> CreateManipulatorViewQuadForPlanarTranslationManipulator(
|
||||
const AZ::Vector3& axis1,
|
||||
const AZ::Vector3& axis2,
|
||||
const AZ::Color& axis1Color,
|
||||
const AZ::Color& axis2Color,
|
||||
float linearAxisLength,
|
||||
float linearConeLength,
|
||||
float planarAxisLength);
|
||||
} // namespace AzToolsFramework
|
||||
|
||||
@@ -150,6 +150,24 @@ namespace AzToolsFramework
|
||||
return result.GetOutcome() == AZ::JsonSerializationResult::Outcomes::Success;
|
||||
}
|
||||
|
||||
// some assets may come in from the JSON serialzier with no AssetID, but have an asset hint
|
||||
// this attempts to fix up the assets using the assetHint field
|
||||
void FixUpInvalidAssets(AZ::Data::Asset<AZ::Data::AssetData>& asset)
|
||||
{
|
||||
if (!asset.GetId().IsValid() && !asset.GetHint().empty())
|
||||
{
|
||||
AZ::Data::AssetId assetId;
|
||||
AZ::Data::AssetCatalogRequestBus::BroadcastResult(
|
||||
assetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, asset.GetHint().c_str(),
|
||||
AZ::Data::s_invalidAssetType, false);
|
||||
|
||||
if (assetId.IsValid())
|
||||
{
|
||||
asset.Create(assetId, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool LoadInstanceFromPrefabDom(Instance& instance, const PrefabDom& prefabDom, LoadFlags flags)
|
||||
{
|
||||
// When entities are rebuilt they are first destroyed. As a result any assets they were exclusively holding on to will
|
||||
@@ -164,13 +182,17 @@ namespace AzToolsFramework
|
||||
entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random);
|
||||
}
|
||||
|
||||
auto tracker = AZ::Data::SerializedAssetTracker{};
|
||||
tracker.SetAssetFixUp(&FixUpInvalidAssets);
|
||||
|
||||
AZ::JsonDeserializerSettings settings;
|
||||
// The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is
|
||||
// specific for the InstanceEntityIdMapper and once for the generic JsonEntityIdMapper. Because the Json Serializer's meta
|
||||
// data has strict typing and doesn't look for inheritance both have to be explicitly added so they're found both locations.
|
||||
settings.m_metadata.Add(static_cast<AZ::JsonEntityIdSerializer::JsonEntityIdMapper*>(&entityIdMapper));
|
||||
settings.m_metadata.Add(&entityIdMapper);
|
||||
|
||||
settings.m_metadata.Add(tracker);
|
||||
|
||||
AZ::JsonSerializationResult::ResultCode result =
|
||||
AZ::JsonSerialization::Load(instance, prefabDom, settings);
|
||||
|
||||
@@ -203,13 +225,16 @@ namespace AzToolsFramework
|
||||
entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random);
|
||||
}
|
||||
|
||||
auto tracker = AZ::Data::SerializedAssetTracker{};
|
||||
tracker.SetAssetFixUp(&FixUpInvalidAssets);
|
||||
|
||||
AZ::JsonDeserializerSettings settings;
|
||||
// The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is
|
||||
// specific for the InstanceEntityIdMapper and once for the generic JsonEntityIdMapper. Because the Json Serializer's meta
|
||||
// data has strict typing and doesn't look for inheritance both have to be explicitly added so they're found both locations.
|
||||
settings.m_metadata.Add(static_cast<AZ::JsonEntityIdSerializer::JsonEntityIdMapper*>(&entityIdMapper));
|
||||
settings.m_metadata.Add(&entityIdMapper);
|
||||
settings.m_metadata.Create<AZ::Data::SerializedAssetTracker>();
|
||||
settings.m_metadata.Add(tracker);
|
||||
|
||||
AZ::JsonSerializationResult::ResultCode result =
|
||||
AZ::JsonSerialization::Load(instance, prefabDom, settings);
|
||||
@@ -246,29 +271,8 @@ namespace AzToolsFramework
|
||||
entityIdMapper.SetEntityIdGenerationApproach(InstanceEntityIdMapper::EntityIdGenerationApproach::Random);
|
||||
}
|
||||
|
||||
// some assets may come in from the JSON serialzier with no AssetID, but have an asset hint
|
||||
// this attempts to fix up the assets using the assetHint field
|
||||
auto fixUpInvalidAssets = [](AZ::Data::Asset<AZ::Data::AssetData>& asset)
|
||||
{
|
||||
if (!asset.GetId().IsValid() && !asset.GetHint().empty())
|
||||
{
|
||||
AZ::Data::AssetId assetId;
|
||||
AZ::Data::AssetCatalogRequestBus::BroadcastResult(
|
||||
assetId,
|
||||
&AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath,
|
||||
asset.GetHint().c_str(),
|
||||
AZ::Data::s_invalidAssetType,
|
||||
false);
|
||||
|
||||
if (assetId.IsValid())
|
||||
{
|
||||
asset.Create(assetId, false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
auto tracker = AZ::Data::SerializedAssetTracker{};
|
||||
tracker.SetAssetFixUp(fixUpInvalidAssets);
|
||||
tracker.SetAssetFixUp(&FixUpInvalidAssets);
|
||||
|
||||
AZ::JsonDeserializerSettings settings;
|
||||
// The InstanceEntityIdMapper is registered twice because it's used in several places during deserialization where one is
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <AzToolsFramework/ContainerEntity/ContainerEntityInterface.h>
|
||||
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
|
||||
#include <AzToolsFramework/Entity/PrefabEditorEntityOwnershipInterface.h>
|
||||
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
|
||||
#include <AzToolsFramework/Prefab/Instance/Instance.h>
|
||||
#include <AzToolsFramework/Prefab/Instance/InstanceEntityMapperInterface.h>
|
||||
#include <AzToolsFramework/Prefab/PrefabFocusNotificationBus.h>
|
||||
@@ -74,6 +75,13 @@ namespace AzToolsFramework::Prefab
|
||||
"Prefab - PrefabFocusHandler - "
|
||||
"Focus Mode Interface could not be found. "
|
||||
"Check that it is being correctly initialized.");
|
||||
|
||||
m_readOnlyEntityQueryInterface = AZ::Interface<ReadOnlyEntityQueryInterface>::Get();
|
||||
AZ_Assert(
|
||||
m_readOnlyEntityQueryInterface,
|
||||
"Prefab - PrefabFocusHandler - "
|
||||
"ReadOnly Entity Query Interface could not be found. "
|
||||
"Check that it is being correctly initialized.");
|
||||
}
|
||||
|
||||
PrefabFocusOperationResult PrefabFocusHandler::FocusOnOwningPrefab(AZ::EntityId entityId)
|
||||
@@ -186,6 +194,8 @@ namespace AzToolsFramework::Prefab
|
||||
// Close all container entities in the old path.
|
||||
CloseInstanceContainers(m_instanceFocusHierarchy);
|
||||
|
||||
AZ::EntityId previousContainerEntityId = m_focusedInstanceContainerEntityId;
|
||||
|
||||
// Do not store the container for the root instance, use an invalid EntityId instead.
|
||||
m_focusedInstanceContainerEntityId = focusedInstance->get().GetParentInstance().has_value() ? focusedInstance->get().GetContainerEntityId() : AZ::EntityId();
|
||||
m_focusedTemplateId = focusedInstance->get().GetTemplateId();
|
||||
@@ -201,6 +211,12 @@ namespace AzToolsFramework::Prefab
|
||||
m_focusModeInterface->SetFocusRoot(containerEntityId);
|
||||
}
|
||||
|
||||
// Refresh the read-only cache, if the interface is initialized.
|
||||
if (m_readOnlyEntityQueryInterface)
|
||||
{
|
||||
m_readOnlyEntityQueryInterface->RefreshReadOnlyState({ previousContainerEntityId, m_focusedInstanceContainerEntityId });
|
||||
}
|
||||
|
||||
// Refresh path variables.
|
||||
RefreshInstanceFocusList();
|
||||
RefreshInstanceFocusPath();
|
||||
|
||||
@@ -22,6 +22,7 @@ namespace AzToolsFramework
|
||||
{
|
||||
class ContainerEntityInterface;
|
||||
class FocusModeInterface;
|
||||
class ReadOnlyEntityQueryInterface;
|
||||
}
|
||||
|
||||
namespace AzToolsFramework::Prefab
|
||||
@@ -93,6 +94,7 @@ namespace AzToolsFramework::Prefab
|
||||
ContainerEntityInterface* m_containerEntityInterface = nullptr;
|
||||
FocusModeInterface* m_focusModeInterface = nullptr;
|
||||
InstanceEntityMapperInterface* m_instanceEntityMapperInterface = nullptr;
|
||||
ReadOnlyEntityQueryInterface* m_readOnlyEntityQueryInterface = nullptr;
|
||||
};
|
||||
|
||||
} // namespace AzToolsFramework::Prefab
|
||||
|
||||
@@ -918,6 +918,18 @@ namespace AzToolsFramework
|
||||
}
|
||||
}
|
||||
|
||||
bool PrefabPublicHandler::IsOwnedByProceduralPrefabInstance(AZ::EntityId entityId) const
|
||||
{
|
||||
if (InstanceOptionalReference instanceReference = m_instanceEntityMapperInterface->FindOwningInstance(entityId);
|
||||
instanceReference.has_value())
|
||||
{
|
||||
TemplateReference templateReference = m_prefabSystemComponentInterface->FindTemplate(instanceReference->get().GetTemplateId());
|
||||
return (templateReference.has_value()) && (templateReference->get().IsProcedural());
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool PrefabPublicHandler::IsInstanceContainerEntity(AZ::EntityId entityId) const
|
||||
{
|
||||
InstanceOptionalReference owningInstance = m_instanceEntityMapperInterface->FindOwningInstance(entityId);
|
||||
|
||||
@@ -54,6 +54,7 @@ namespace AzToolsFramework
|
||||
|
||||
PrefabOperationResult GenerateUndoNodesForEntityChangeAndUpdateCache(AZ::EntityId entityId, UndoSystem::URSequencePoint* parentUndoBatch) override;
|
||||
|
||||
bool IsOwnedByProceduralPrefabInstance(AZ::EntityId entityId) const override;
|
||||
bool IsInstanceContainerEntity(AZ::EntityId entityId) const override;
|
||||
bool IsLevelInstanceContainerEntity(AZ::EntityId entityId) const override;
|
||||
AZ::EntityId GetInstanceContainerEntityId(AZ::EntityId entityId) const override;
|
||||
|
||||
@@ -101,6 +101,13 @@ namespace AzToolsFramework
|
||||
*/
|
||||
virtual PrefabOperationResult GenerateUndoNodesForEntityChangeAndUpdateCache(
|
||||
AZ::EntityId entityId, UndoSystem::URSequencePoint* parentUndoBatch) = 0;
|
||||
|
||||
/**
|
||||
* Detects if an entity is owned by a procedural prefab.
|
||||
* @param entityId The entity to query.
|
||||
* @return True if the entity is owned by a procedural prefab instance, false otherwise.
|
||||
*/
|
||||
virtual bool IsOwnedByProceduralPrefabInstance(AZ::EntityId entityId) const = 0;
|
||||
|
||||
/**
|
||||
* Detects if an entity is the container entity for its owning prefab instance.
|
||||
|
||||
+6
-1
@@ -8,10 +8,12 @@
|
||||
|
||||
#include <API/ToolsApplicationAPI.h>
|
||||
#include <AzCore/Component/ComponentApplicationBus.h>
|
||||
#include <AzCore/Component/Entity.h>
|
||||
#include <AzCore/RTTI/BehaviorContext.h>
|
||||
#include <AzToolsFramework/ToolsComponents/EditorLockComponent.h>
|
||||
#include <AzToolsFramework/ToolsComponents/EditorVisibilityComponent.h>
|
||||
#include <Prefab/PrefabSystemComponentInterface.h>
|
||||
#include <Prefab/PrefabSystemScriptingHandler.h>
|
||||
#include <AzCore/Component/Entity.h>
|
||||
#include <Prefab/EditorPrefabComponent.h>
|
||||
#include <ToolsComponents/TransformComponent.h>
|
||||
|
||||
@@ -72,6 +74,9 @@ namespace AzToolsFramework::Prefab
|
||||
entities, commonRoot, &topLevelEntities);
|
||||
|
||||
auto containerEntity = AZStd::make_unique<AZ::Entity>();
|
||||
containerEntity->CreateComponent<Components::TransformComponent>();
|
||||
containerEntity->CreateComponent<Components::EditorLockComponent>();
|
||||
containerEntity->CreateComponent<Components::EditorVisibilityComponent>();
|
||||
containerEntity->CreateComponent<Prefab::EditorPrefabComponent>();
|
||||
|
||||
for (AZ::Entity* entity : topLevelEntities)
|
||||
|
||||
+11
-9
@@ -860,18 +860,20 @@ namespace AzToolsFramework
|
||||
return;
|
||||
}
|
||||
|
||||
bool isDuringUndoRedo = false;
|
||||
EBUS_EVENT_RESULT(isDuringUndoRedo, AzToolsFramework::ToolsApplicationRequests::Bus, IsDuringUndoRedo);
|
||||
if (!isDuringUndoRedo)
|
||||
bool suppressTransformChangedEvent = m_suppressTransformChangedEvent;
|
||||
// temporarily disable calling OnTransformChanged, because CheckApplyCachedWorldTransform is not guaranteed
|
||||
// to call it when m_cachedWorldTransform is identity. We send it manually later.
|
||||
m_suppressTransformChangedEvent = false;
|
||||
// When parent comes online, compute local TM from world TM.
|
||||
CheckApplyCachedWorldTransform(parentTransform->GetWorldTM());
|
||||
if (!m_initialized)
|
||||
{
|
||||
// When parent comes online, compute local TM from world TM.
|
||||
CheckApplyCachedWorldTransform(parentTransform->GetWorldTM());
|
||||
}
|
||||
else
|
||||
{
|
||||
// During undo operations, just apply our local TM.
|
||||
m_initialized = true;
|
||||
// If this is the first time this entity is being activated, manually compute OnTransformChanged
|
||||
// this can occur when either the entity first created or undo/redo command is performed
|
||||
OnTransformChanged(AZ::Transform::Identity(), parentTransform->GetWorldTM());
|
||||
}
|
||||
m_suppressTransformChangedEvent = suppressTransformChangedEvent;
|
||||
|
||||
auto& parentChildIds = GetParentTransformComponent()->m_childrenEntityIds;
|
||||
if (parentChildIds.end() == AZStd::find(parentChildIds.begin(), parentChildIds.end(), GetEntityId()))
|
||||
|
||||
@@ -242,6 +242,9 @@ namespace AzToolsFramework
|
||||
// element is used rather than a data element.
|
||||
bool m_addNonUniformScaleButton = false;
|
||||
|
||||
// Used to check whether entity was just created vs manually reactivated. Set true after OnEntityActivated is called the first time.
|
||||
bool m_initialized = false;
|
||||
|
||||
// Deprecated
|
||||
AZ::InterpolationMode m_interpolatePosition;
|
||||
AZ::InterpolationMode m_interpolateRotation;
|
||||
|
||||
+31
-6
@@ -47,6 +47,7 @@
|
||||
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
|
||||
#include <AzToolsFramework/Entity/EditorEntityHelpers.h>
|
||||
#include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
|
||||
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
|
||||
#include <AzToolsFramework/FocusMode/FocusModeInterface.h>
|
||||
#include <AzToolsFramework/ToolsComponents/ComponentAssetMimeDataContainer.h>
|
||||
#include <AzToolsFramework/ToolsComponents/ComponentMimeData.h>
|
||||
@@ -313,7 +314,7 @@ namespace AzToolsFramework
|
||||
|
||||
if (isEditorOnly)
|
||||
{
|
||||
return QIcon(QString(":/Icons/Entity_Editor_Only.svg"));
|
||||
return QIcon(QString(":/Entity/entity_editoronly.svg"));
|
||||
}
|
||||
|
||||
AZ::Entity* entity = nullptr;
|
||||
@@ -322,10 +323,10 @@ namespace AzToolsFramework
|
||||
|
||||
if (!isInitiallyActive)
|
||||
{
|
||||
return QIcon(QString(":/Icons/Entity_Not_Active.svg"));
|
||||
return QIcon(QString(":/Entity/entity_notactive.svg"));
|
||||
}
|
||||
|
||||
return QIcon(QString(":/Icons/Entity.svg"));
|
||||
return QIcon(QString(":/Entity/entity.svg"));
|
||||
}
|
||||
|
||||
QVariant EntityOutlinerListModel::GetEntityTooltip(const AZ::EntityId& id) const
|
||||
@@ -1994,9 +1995,13 @@ namespace AzToolsFramework
|
||||
, m_lockCheckBoxes(parent, "Lock", EntityOutlinerListModel::PartiallyLockedRole, EntityOutlinerListModel::LockedAncestorRole)
|
||||
{
|
||||
m_editorEntityFrameworkInterface = AZ::Interface<AzToolsFramework::EditorEntityUiInterface>::Get();
|
||||
|
||||
AZ_Assert((m_editorEntityFrameworkInterface != nullptr),
|
||||
"EntityOutlinerItemDelegate requires a EditorEntityFrameworkInterface instance on Construction.");
|
||||
|
||||
m_readOnlyEntityPublicInterface = AZ::Interface<AzToolsFramework::ReadOnlyEntityPublicInterface>::Get();
|
||||
AZ_Assert(
|
||||
(m_readOnlyEntityPublicInterface != nullptr),
|
||||
"EntityOutlinerItemDelegate requires a ReadOnlyEntityPublicInterface instance on Construction.");
|
||||
}
|
||||
|
||||
EntityOutlinerItemDelegate::CheckboxGroup::CheckboxGroup(QWidget* parent, AZStd::string prefix,
|
||||
@@ -2108,6 +2113,12 @@ namespace AzToolsFramework
|
||||
}
|
||||
|
||||
PaintEntityNameAsRichText(painter, customOption, index);
|
||||
|
||||
// Paint Read-Only icon if necessary
|
||||
if (m_readOnlyEntityPublicInterface->IsReadOnly(entityId))
|
||||
{
|
||||
PaintReadOnlyIcon(painter, option, index);
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
@@ -2166,10 +2177,10 @@ namespace AzToolsFramework
|
||||
|
||||
backgroundPath.addRect(backgroundRect);
|
||||
|
||||
QColor backgroundColor = m_hoverColor;
|
||||
QColor backgroundColor = s_hoverColor;
|
||||
if (isSelected)
|
||||
{
|
||||
backgroundColor = m_selectedColor;
|
||||
backgroundColor = s_selectedColor;
|
||||
}
|
||||
|
||||
painter->fillPath(backgroundPath, backgroundColor);
|
||||
@@ -2336,6 +2347,20 @@ namespace AzToolsFramework
|
||||
EntityOutlinerListModel::s_paintingName = false;
|
||||
}
|
||||
|
||||
void EntityOutlinerItemDelegate::PaintReadOnlyIcon(QPainter* painter, const QStyleOptionViewItem& option, [[maybe_unused]] const QModelIndex& index) const
|
||||
{
|
||||
// Build the rect that will be used to paint the icon
|
||||
QRect readOnlyRect = QRect(option.rect.topLeft() + s_readOnlyOffset, QSize(s_readOnlyRadius * 2, s_readOnlyRadius * 2));
|
||||
|
||||
painter->save();
|
||||
painter->setRenderHint(QPainter::Antialiasing, true);
|
||||
painter->setPen(Qt::NoPen);
|
||||
painter->setBrush(s_readOnlyBackgroundColor);
|
||||
painter->drawEllipse(readOnlyRect.center(), s_readOnlyRadius, s_readOnlyRadius);
|
||||
s_readOnlyIcon.paint(painter, readOnlyRect);
|
||||
painter->restore();
|
||||
}
|
||||
|
||||
QSize EntityOutlinerItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& /*index*/) const
|
||||
{
|
||||
// Get the height of a tall character...
|
||||
|
||||
+13
-2
@@ -38,6 +38,7 @@ namespace AzToolsFramework
|
||||
{
|
||||
class EditorEntityUiInterface;
|
||||
class FocusModeInterface;
|
||||
class ReadOnlyEntityPublicInterface;
|
||||
|
||||
namespace EntityOutliner
|
||||
{
|
||||
@@ -344,6 +345,9 @@ namespace AzToolsFramework
|
||||
// Paint the entity name using rich text
|
||||
void PaintEntityNameAsRichText(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
|
||||
|
||||
// Paint the read-only icon on the entity
|
||||
void PaintReadOnlyIcon(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const;
|
||||
|
||||
struct CheckboxGroup
|
||||
{
|
||||
EntityOutlinerCheckBox m_default;
|
||||
@@ -372,10 +376,17 @@ namespace AzToolsFramework
|
||||
// this is a cache, and is hence mutable
|
||||
mutable QRect m_cachedBoundingRectOfTallCharacter;
|
||||
|
||||
const QColor m_selectedColor = QColor(255, 255, 255, 45);
|
||||
const QColor m_hoverColor = QColor(255, 255, 255, 30);
|
||||
inline static const QColor s_selectedColor = QColor(255, 255, 255, 45);
|
||||
inline static const QColor s_hoverColor = QColor(255, 255, 255, 30);
|
||||
|
||||
inline static const QColor s_readOnlyBackgroundColor = QColor("#444444");
|
||||
inline static const QPoint s_readOnlyOffset = QPoint(10, 10);
|
||||
inline static const int s_readOnlyRadius = 6;
|
||||
|
||||
QIcon s_readOnlyIcon = QIcon(QString(":/Entity/readonly.svg"));
|
||||
|
||||
EditorEntityUiInterface* m_editorEntityFrameworkInterface = nullptr;
|
||||
ReadOnlyEntityPublicInterface* m_readOnlyEntityPublicInterface = nullptr;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
+11
-7
@@ -27,6 +27,7 @@
|
||||
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
|
||||
#include <AzToolsFramework/Prefab/EditorPrefabComponent.h>
|
||||
#include <AzToolsFramework/Prefab/Instance/InstanceEntityMapperInterface.h>
|
||||
#include <AzToolsFramework/Prefab/Instance/InstanceToTemplateInterface.h>
|
||||
#include <AzToolsFramework/Prefab/PrefabFocusInterface.h>
|
||||
#include <AzToolsFramework/Prefab/PrefabFocusPublicInterface.h>
|
||||
#include <AzToolsFramework/Prefab/PrefabLoaderInterface.h>
|
||||
@@ -565,9 +566,7 @@ namespace AzToolsFramework
|
||||
EditorRequestBus::BroadcastResult(position, &EditorRequestBus::Events::GetWorldPositionAtViewportCenter);
|
||||
}
|
||||
|
||||
// Instantiating from context menu always puts the instance at the root level
|
||||
auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(prefabFilePath, parentId, position);
|
||||
|
||||
if (!createPrefabOutcome.IsSuccess())
|
||||
{
|
||||
WarnUserOfError("Prefab Instantiation Error",createPrefabOutcome.GetError());
|
||||
@@ -594,15 +593,13 @@ namespace AzToolsFramework
|
||||
}
|
||||
else
|
||||
{
|
||||
// otherwise return since it needs to be inside an authored prefab
|
||||
return;
|
||||
EditorRequestBus::BroadcastResult(position, &EditorRequestBus::Events::GetWorldPositionAtViewportCenter);
|
||||
}
|
||||
|
||||
// Instantiating from context menu always puts the instance at the root level
|
||||
auto createPrefabOutcome = s_prefabPublicInterface->InstantiatePrefab(prefabAssetPath, parentId, position);
|
||||
if (!createPrefabOutcome.IsSuccess())
|
||||
{
|
||||
WarnUserOfError("Prefab Instantiation Error", createPrefabOutcome.GetError());
|
||||
WarnUserOfError("Procedural Prefab Instantiation Error", createPrefabOutcome.GetError());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1268,7 +1265,14 @@ namespace AzToolsFramework
|
||||
}
|
||||
else
|
||||
{
|
||||
s_editorEntityUiInterface->RegisterEntity(entityId, m_prefabUiHandler.GetHandlerId());
|
||||
if (s_prefabPublicInterface->IsOwnedByProceduralPrefabInstance(entityId))
|
||||
{
|
||||
s_editorEntityUiInterface->RegisterEntity(entityId, m_proceduralPrefabUiHandler.GetHandlerId());
|
||||
}
|
||||
else
|
||||
{
|
||||
s_editorEntityUiInterface->RegisterEntity(entityId, m_prefabUiHandler.GetHandlerId());
|
||||
}
|
||||
|
||||
// Register entity as a container
|
||||
s_containerEntityInterface->RegisterEntityAsContainer(entityId);
|
||||
|
||||
+10
-3
@@ -18,10 +18,11 @@
|
||||
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
|
||||
#include <AzToolsFramework/Prefab/PrefabSystemComponentInterface.h>
|
||||
#include <AzToolsFramework/UI/Prefab/LevelRootUiHandler.h>
|
||||
|
||||
#include <AzToolsFramework/UI/Prefab/PrefabIntegrationBus.h>
|
||||
#include <AzToolsFramework/UI/Prefab/PrefabIntegrationInterface.h>
|
||||
#include <AzToolsFramework/UI/Prefab/PrefabUiHandler.h>
|
||||
#include <AzToolsFramework/UI/Prefab/Procedural/ProceduralPrefabReadOnlyHandler.h>
|
||||
#include <AzToolsFramework/UI/Prefab/Procedural/ProceduralPrefabUiHandler.h>
|
||||
|
||||
#include <AzQtComponents/Components/Widgets/Card.h>
|
||||
|
||||
@@ -92,12 +93,18 @@ namespace AzToolsFramework
|
||||
void ExecuteSavePrefabDialog(TemplateId templateId, bool useSaveAllPrefabsPreference) override;
|
||||
|
||||
private:
|
||||
// Used to handle the UI for the level root
|
||||
// Used to handle the UI for the level root.
|
||||
LevelRootUiHandler m_levelRootUiHandler;
|
||||
|
||||
// Used to handle the UI for prefab entities
|
||||
// Used to handle the UI for prefab entities.
|
||||
PrefabUiHandler m_prefabUiHandler;
|
||||
|
||||
// Used to handle the UI for procedural prefab entities.
|
||||
ProceduralPrefabUiHandler m_proceduralPrefabUiHandler;
|
||||
|
||||
// Ensures entities owned by procedural prefab instances are marked as read-only correctly.
|
||||
ProceduralPrefabReadOnlyHandler m_proceduralPrefabReadOnlyHandler;
|
||||
|
||||
// Context menu item handlers
|
||||
static void ContextMenu_CreatePrefab(AzToolsFramework::EntityIdList selectedEntities);
|
||||
static void ContextMenu_InstantiatePrefab();
|
||||
|
||||
@@ -23,17 +23,6 @@ namespace AzToolsFramework
|
||||
{
|
||||
AzFramework::EntityContextId PrefabUiHandler::s_editorEntityContextId = AzFramework::EntityContextId::CreateNull();
|
||||
|
||||
const QColor PrefabUiHandler::m_backgroundColor = QColor("#444444");
|
||||
const QColor PrefabUiHandler::m_backgroundHoverColor = QColor("#5A5A5A");
|
||||
const QColor PrefabUiHandler::m_backgroundSelectedColor = QColor("#656565");
|
||||
const QColor PrefabUiHandler::m_prefabCapsuleColor = QColor("#1E252F");
|
||||
const QColor PrefabUiHandler::m_prefabCapsuleDisabledColor = QColor("#35383C");
|
||||
const QColor PrefabUiHandler::m_prefabCapsuleEditColor = QColor("#4A90E2");
|
||||
const QString PrefabUiHandler::m_prefabIconPath = QString(":/Entity/prefab.svg");
|
||||
const QString PrefabUiHandler::m_prefabEditIconPath = QString(":/Entity/prefab_edit.svg");
|
||||
const QString PrefabUiHandler::m_prefabEditOpenIconPath = QString(":/Entity/prefab_edit_open.svg");
|
||||
const QString PrefabUiHandler::m_prefabEditCloseIconPath = QString(":/Entity/prefab_edit_close.svg");
|
||||
|
||||
PrefabUiHandler::PrefabUiHandler()
|
||||
{
|
||||
m_prefabPublicInterface = AZ::Interface<Prefab::PrefabPublicInterface>::Get();
|
||||
|
||||
@@ -46,7 +46,7 @@ namespace AzToolsFramework
|
||||
void OnOutlinerItemCollapse(const QModelIndex& index) const override;
|
||||
bool OnEntityDoubleClick(AZ::EntityId entityId) const override;
|
||||
|
||||
private:
|
||||
protected:
|
||||
Prefab::PrefabFocusPublicInterface* m_prefabFocusPublicInterface = nullptr;
|
||||
Prefab::PrefabPublicInterface* m_prefabPublicInterface = nullptr;
|
||||
|
||||
@@ -56,17 +56,17 @@ namespace AzToolsFramework
|
||||
|
||||
static AzFramework::EntityContextId s_editorEntityContextId;
|
||||
|
||||
static constexpr int m_prefabCapsuleRadius = 6;
|
||||
static constexpr int m_prefabBorderThickness = 2;
|
||||
static const QColor m_backgroundColor;
|
||||
static const QColor m_backgroundHoverColor;
|
||||
static const QColor m_backgroundSelectedColor;
|
||||
static const QColor m_prefabCapsuleColor;
|
||||
static const QColor m_prefabCapsuleDisabledColor;
|
||||
static const QColor m_prefabCapsuleEditColor;
|
||||
static const QString m_prefabIconPath;
|
||||
static const QString m_prefabEditIconPath;
|
||||
static const QString m_prefabEditOpenIconPath;
|
||||
static const QString m_prefabEditCloseIconPath;
|
||||
int m_prefabCapsuleRadius = 6;
|
||||
int m_prefabBorderThickness = 2;
|
||||
QColor m_backgroundColor = QColor("#444444");
|
||||
QColor m_backgroundHoverColor = QColor("#5A5A5A");
|
||||
QColor m_backgroundSelectedColor = QColor("#656565");
|
||||
QColor m_prefabCapsuleColor = QColor("#1E252F");
|
||||
QColor m_prefabCapsuleDisabledColor = QColor("#35383C");
|
||||
QColor m_prefabCapsuleEditColor = QColor("#4A90E2");
|
||||
QString m_prefabIconPath = QString(":/Entity/prefab.svg");
|
||||
QString m_prefabEditIconPath = QString(":/Entity/prefab_edit.svg");
|
||||
QString m_prefabEditOpenIconPath = QString(":/Entity/prefab_edit_open.svg");
|
||||
QString m_prefabEditCloseIconPath = QString(":/Entity/prefab_edit_close.svg");
|
||||
};
|
||||
} // namespace AzToolsFramework
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* 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 <AzToolsFramework/UI/Prefab/Procedural/ProceduralPrefabReadOnlyHandler.h>
|
||||
|
||||
#include <AzToolsFramework/Entity/EditorEntityContextBus.h>
|
||||
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
|
||||
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
|
||||
#include <AzToolsFramework/Prefab/PrefabFocusPublicInterface.h>
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
namespace Prefab
|
||||
{
|
||||
ProceduralPrefabReadOnlyHandler::ProceduralPrefabReadOnlyHandler()
|
||||
{
|
||||
m_prefabPublicInterface = AZ::Interface<PrefabPublicInterface>::Get();
|
||||
AZ_Assert(
|
||||
m_prefabPublicInterface != nullptr,
|
||||
"ProceduralPrefabReadOnlyHandler requires a PrefabPublicInterface instance on Initialize.");
|
||||
|
||||
m_prefabFocusPublicInterface = AZ::Interface<PrefabFocusPublicInterface>::Get();
|
||||
AZ_Assert(
|
||||
m_prefabFocusPublicInterface != nullptr,
|
||||
"ProceduralPrefabReadOnlyHandler requires a PrefabFocusPublicInterface instance on Initialize.");
|
||||
|
||||
AzFramework::EntityContextId editorEntityContextId = AzFramework::EntityContextId::CreateNull();
|
||||
EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &EditorEntityContextRequests::GetEditorEntityContextId);
|
||||
|
||||
ReadOnlyEntityQueryRequestBus::Handler::BusConnect(editorEntityContextId);
|
||||
|
||||
// Refresh the whole read-only cache
|
||||
if (auto readOnlyEntityQueryInterface = AZ::Interface<ReadOnlyEntityQueryInterface>::Get())
|
||||
{
|
||||
readOnlyEntityQueryInterface->RefreshReadOnlyStateForAllEntities();
|
||||
}
|
||||
}
|
||||
|
||||
ProceduralPrefabReadOnlyHandler ::~ProceduralPrefabReadOnlyHandler()
|
||||
{
|
||||
ReadOnlyEntityQueryRequestBus::Handler::BusDisconnect();
|
||||
}
|
||||
|
||||
void ProceduralPrefabReadOnlyHandler::IsReadOnly(const AZ::EntityId& entityId, bool& isReadOnly)
|
||||
{
|
||||
if(m_prefabPublicInterface->IsOwnedByProceduralPrefabInstance(entityId))
|
||||
{
|
||||
// All entities nested inside a procedural prefabs should always be marked as read-only.
|
||||
if (!m_prefabPublicInterface->IsInstanceContainerEntity(entityId))
|
||||
{
|
||||
isReadOnly = true;
|
||||
}
|
||||
|
||||
// The container entity of a procedural prefab should only be marked as read-only when the prefab is being edited.
|
||||
if (m_prefabFocusPublicInterface->IsOwningPrefabBeingFocused(entityId))
|
||||
{
|
||||
isReadOnly = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Prefab
|
||||
} // namespace AzToolsFramework
|
||||
+43
@@ -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
|
||||
*
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <AzCore/Memory/SystemAllocator.h>
|
||||
#include <AzCore/RTTI/RTTI.h>
|
||||
|
||||
#include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityBus.h>
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
namespace Prefab
|
||||
{
|
||||
class PrefabFocusPublicInterface;
|
||||
class PrefabPublicInterface;
|
||||
|
||||
//! Ensures entities in a procedural prefab are correctly reported as read-only.
|
||||
class ProceduralPrefabReadOnlyHandler
|
||||
: public ReadOnlyEntityQueryRequestBus::Handler
|
||||
{
|
||||
public:
|
||||
AZ_CLASS_ALLOCATOR(ProceduralPrefabReadOnlyHandler, AZ::SystemAllocator, 0);
|
||||
AZ_RTTI(AzToolsFramework::ProceduralPrefabReadOnlyHandler, "{A2D72461-8CA3-45EE-81D2-4976BC0B6AE9}");
|
||||
|
||||
ProceduralPrefabReadOnlyHandler();
|
||||
~ProceduralPrefabReadOnlyHandler() override;
|
||||
|
||||
// ReadOnlyEntityQueryRequestBus overrides ...
|
||||
void IsReadOnly(const AZ::EntityId& entityId, bool& isReadOnly) override;
|
||||
|
||||
private:
|
||||
PrefabPublicInterface* m_prefabPublicInterface = nullptr;
|
||||
PrefabFocusPublicInterface* m_prefabFocusPublicInterface = nullptr;
|
||||
};
|
||||
|
||||
} // namespace Prefab
|
||||
} // namespace AzToolsFramework
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* 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 <AzToolsFramework/UI/Prefab/Procedural/ProceduralPrefabUiHandler.h>
|
||||
|
||||
#include <AzToolsFramework/Prefab/PrefabPublicInterface.h>
|
||||
|
||||
namespace AzToolsFramework
|
||||
{
|
||||
ProceduralPrefabUiHandler::ProceduralPrefabUiHandler()
|
||||
{
|
||||
m_prefabCapsuleColor = QColor("#361561");
|
||||
m_prefabCapsuleDisabledColor = QColor("#4B3455");
|
||||
m_prefabCapsuleEditColor = QColor("#361561");
|
||||
m_prefabIconPath = QString(":/Entity/prefab_edit.svg");
|
||||
m_prefabEditOpenIconPath = QString(":/Entity/prefab_edit_open_readonly.svg");
|
||||
}
|
||||
|
||||
QString ProceduralPrefabUiHandler::GenerateItemTooltip(AZ::EntityId entityId) const
|
||||
{
|
||||
if (AZ::IO::Path path = m_prefabPublicInterface->GetOwningInstancePrefabPath(entityId); !path.empty())
|
||||
{
|
||||
return QObject::tr("Double click to inspect.\n%1").arg(path.Native().data());
|
||||
}
|
||||
return QString();
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user