text
stringlengths 15
267k
|
|---|
# coding: utf-8
import unreal
def getAllProperties(object_class):
return unreal.CppLib.get_all_properties(object_class)
def printAllProperties():
obj = unreal.Actor()
object_class = obj.get_class()
for x in getAllProperties(object_class):
name = x
while len(name) < 50:
name = ' ' + name
print name + ':' + str(obj.get_editor_property(x))
# import PythonHelpers as ph
# reload(ph)
# ph.printAllProperties()
|
import json
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Dict, List, Optional, Tuple, TypedDict, Union
import unreal
######### Engine Constants #########
def get_plugin_path() -> Tuple[Path, Path, Path]:
PROJECT_FILE = Path(unreal.Paths.get_project_file_path()).resolve()
PROJECT_ROOT = PROJECT_FILE.parent
PLUGIN_ROOT = PROJECT_ROOT / 'Plugins' / PLUGIN_NAME
PLUGIN_PYTHON_ROOT = PLUGIN_ROOT / 'Content/Python'
return PROJECT_ROOT, PLUGIN_ROOT, PLUGIN_PYTHON_ROOT
PLUGIN_NAME = 'XRFeitoriaUnreal'
MATERIAL_PATHS = {
'depth': f'/{PLUGIN_NAME}/project/',
'mask': f'/{PLUGIN_NAME}/project/',
'flow': f'/{PLUGIN_NAME}/project/',
'diffuse': f'/{PLUGIN_NAME}/project/',
'normal': f'/{PLUGIN_NAME}/project/',
'metallic': f'/{PLUGIN_NAME}/project/',
'roughness': f'/{PLUGIN_NAME}/project/',
'specular': f'/{PLUGIN_NAME}/project/',
'tangent': f'/{PLUGIN_NAME}/project/',
'basecolor': f'/{PLUGIN_NAME}/project/',
'lineart': f'/{PLUGIN_NAME}/project/',
}
SHAPE_PATHS = {
'cube': '/project/',
'sphere': '/project/',
'cylinder': '/project/',
'cone': '/project/',
'plane': '/project/',
}
PROJECT_ROOT, PLUGIN_ROOT, PLUGIN_PYTHON_ROOT = get_plugin_path()
ENGINE_MAJOR_VERSION = int(unreal.SystemLibrary.get_engine_version().split('.')[0])
ENGINE_MINOR_VERSION = int(unreal.SystemLibrary.get_engine_version().split('.')[1])
DEFAULT_PATH = f'/Game/{PLUGIN_NAME}'
DEFAULT_SEQUENCE_DIR = f'{DEFAULT_PATH}/Sequences'
DEFAULT_ASSET_PATH = f'{DEFAULT_PATH}/Assets'
DEFAULT_SEQUENCE_DATA_ASSET = f'/{PLUGIN_NAME}/DefaultSequenceData'
MRQ_JOB_UPPER = 200
data_asset_suffix = '_data'
class SubSystem:
if ENGINE_MAJOR_VERSION == 5:
EditorActorSub = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
EditorLevelSub = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
EditorSub = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
EditorLevelSequenceSub = unreal.get_editor_subsystem(unreal.LevelSequenceEditorSubsystem)
EditorAssetSub = unreal.get_editor_subsystem(unreal.AssetEditorSubsystem)
MoviePipelineQueueSub = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
else:
EditorActorSub = None
EditorLevelSub = None
EditorSub = None
EditorLevelSequenceSub = None
EditorAssetSub = None
MoviePipelineQueueSub = None
######### Typing Constants #########
Vector = Tuple[float, float, float]
PathLike = Union[str, Path]
class EnumBase(str, Enum):
@classmethod
def get(cls, name_or_value: str) -> 'EnumBase':
"""Get enum member by name or value.
Args:
name_or_value (str): Name or value of the enum member.
Returns:
EnumBase: Self
"""
try:
return cls[name_or_value]
except KeyError:
for member in cls:
if member.value == name_or_value:
return member
raise ValueError(f'{name_or_value} is not supported in {cls.__name__}')
class InterpolationEnum(EnumBase):
AUTO = 'AUTO'
LINEAR = 'LINEAR'
CONSTANT = 'CONSTANT'
class ImageFileFormatEnum(EnumBase):
png = 'PNG'
bmp = 'BMP'
jpg = 'JPEG'
jpeg = 'JPEG'
exr = 'EXR'
open_exr = 'EXR'
class UnrealRenderLayerEnum(EnumBase):
"""Render layer enum of Unreal."""
img = 'img'
mask = 'mask'
depth = 'depth'
flow = 'flow'
normal = 'normal'
diffuse = 'diffuse'
metallic = 'metallic'
roughness = 'roughness'
specular = 'specular'
tangent = 'tangent'
basecolor = 'basecolor'
lineart = 'lineart'
vertices = 'vertices'
skeleton = 'skeleton'
actor_infos = 'actor_infos'
camera_params = 'camera_params'
audio = 'Audio'
@dataclass
class RenderPass:
"""Render pass model."""
render_layer: UnrealRenderLayerEnum
image_format: ImageFileFormatEnum
def __post_init__(self):
if isinstance(self.render_layer, str):
self.render_layer = UnrealRenderLayerEnum.get(self.render_layer.lower())
if isinstance(self.image_format, str):
self.image_format = ImageFileFormatEnum.get(self.image_format.lower())
@dataclass
class SequenceTransformKey:
frame: int
location: Optional[Vector] = None
rotation: Optional[Vector] = None
scale: Optional[Vector] = None
interpolation: InterpolationEnum = InterpolationEnum.CONSTANT
def __post_init__(self):
if not isinstance(self.frame, int):
raise ValueError('Frame must be an integer')
if self.location and (not isinstance(self.location, (tuple, list)) or len(self.location) != 3):
raise ValueError('Location must be a tuple of 3 floats')
if self.rotation and (not isinstance(self.rotation, (tuple, list)) or len(self.rotation) != 3):
raise ValueError('Rotation must be a tuple of 3 floats')
if self.scale and (not isinstance(self.scale, (tuple, list)) or len(self.scale) != 3):
raise ValueError('Scale must be a tuple of 3 floats')
if isinstance(self.interpolation, str):
self.interpolation = InterpolationEnum.get(self.interpolation.upper())
if self.location:
# convert meters to centimeters
self.location = [loc * 100.0 for loc in self.location]
@dataclass
class RenderJobUnreal:
@dataclass
class AntiAliasSetting:
enable: bool = False
override_anti_aliasing: bool = False
spatial_samples: int = 8
temporal_samples: int = 8
warmup_frames: int = 0
render_warmup_frame: bool = False
map_path: str
sequence_path: str
output_path: str
resolution: Tuple[int, int]
render_passes: List[RenderPass]
file_name_format: str = '{sequence_name}/{render_pass}/{camera_name}/{frame_number}'
console_variables: Dict[str, float] = field(default_factory=dict)
anti_aliasing: AntiAliasSetting = AntiAliasSetting()
export_audio: bool = False
export_transparent: bool = False
def __post_init__(self):
self.render_passes = [RenderPass(**rp) for rp in self.render_passes]
self.anti_aliasing = self.AntiAliasSetting(**self.anti_aliasing)
TransformKeys = Union[List[SequenceTransformKey], SequenceTransformKey]
# MotionFrame = {'bone_name': {'location': [x, y, z], 'rotation': [w, x, y, z]}}
# MotionFrame = {'morph_target_name': {'curve': float}}
MotionFrame = Dict[str, Dict[str, Union[float, List[float]]]]
color_type = TypedDict(
'color',
{
'name': str,
'hex': str,
'rgb': Tuple[int, int, int],
},
)
######### Constants #########
MASK_COLOR_FILE = PLUGIN_PYTHON_ROOT / 'data' / 'mask_colors.json'
mask_colors: List[color_type] = json.loads(MASK_COLOR_FILE.read_text())
|
# Copyright Epic Games, Inc. All Rights Reserved
import os
import argparse
import json
import unreal
from deadline_rpc import BaseRPC
from mrq_cli_modes import (
render_queue_manifest,
render_current_sequence,
render_queue_asset,
utils,
)
class MRQRender(BaseRPC):
"""
Class to execute deadline MRQ renders using RPC
"""
def __init__(self, *args, **kwargs):
"""
Constructor
"""
super(MRQRender, self).__init__(*args, **kwargs)
self._render_cmd = ["mrq_cli.py"]
# Keep track of the task data
self._shot_data = None
self._queue = None
self._manifest = None
self._sequence_data = None
def _get_queue(self):
"""
Render a MRQ queue asset
:return: MRQ queue asset name
"""
if not self._queue:
self._queue = self.proxy.get_job_extra_info_key_value("queue_name")
return self._queue
def _get_sequence_data(self):
"""
Get sequence data
:return: Sequence data
"""
if not self._sequence_data:
self._sequence_data = self.proxy.get_job_extra_info_key_value(
"sequence_render"
)
return self._sequence_data
def _get_serialized_pipeline(self):
"""
Get Serialized pipeline from Deadline
:return:
"""
if not self._manifest:
serialized_pipeline = os.environ.get("override_serialized_pipeline")
if not serialized_pipeline:
serialized_pipeline = self.proxy.get_job_extra_info_key_value(
"serialized_pipeline"
)
if not serialized_pipeline:
return
unreal.log(
f"Executing Serialized Pipeline: `{serialized_pipeline}`"
)
# create temp manifest folder
movieRenderPipeline_dir = os.path.join(
unreal.SystemLibrary.get_project_saved_directory(),
"MovieRenderPipeline",
"TempManifests",
)
if not os.path.exists(movieRenderPipeline_dir ):
os.makedirs(movieRenderPipeline_dir )
# create manifest file
manifest_file = unreal.Paths.create_temp_filename(
movieRenderPipeline_dir ,
prefix='TempManifest',
extension='.utxt')
unreal.log(f"Saving Manifest file `{manifest_file}`")
# Dump the manifest data into the manifest file
with open(manifest_file, "w") as manifest:
manifest.write(serialized_pipeline)
self._manifest = manifest_file
return self._manifest
def execute(self):
"""
Starts the render execution
"""
# shots are listed as a dictionary of task id -> shotnames
# i.e {"O": "my_new_shot"} or {"20", "shot_1,shot_2,shot_4"}
# Get the task data and cache it
if not self._shot_data:
self._shot_data = json.loads(
self.proxy.get_job_extra_info_key_value("shot_info")
)
# Get any output overrides
output_dir = self.proxy.get_job_extra_info_key_value(
"output_directory_override"
)
# Resolve any path mappings in the directory name. The server expects
# a list of paths, but we only ever expect one. So wrap it in a list
# if we have an output directory
if output_dir:
output_dir = self.proxy.check_path_mappings([output_dir])
output_dir = output_dir[0]
# Get the filename format
filename_format = self.proxy.get_job_extra_info_key_value(
"filename_format_override"
)
# Resolve any path mappings in the filename. The server expects
# a list of paths, but we only ever expect one. So wrap it in a list
if filename_format:
filename_format = self.proxy.check_path_mappings([filename_format])
filename_format = filename_format[0]
# get the shots for the current task
current_task_data = self._shot_data.get(str(self.current_task_id), None)
if not current_task_data:
self.proxy.fail_render("There are no task data to execute!")
return
shots = current_task_data.split(",")
if self._get_queue():
return self.render_queue(
self._get_queue(),
shots,
output_dir_override=output_dir if output_dir else None,
filename_format_override=filename_format if filename_format else None
)
if self._get_serialized_pipeline():
return self.render_serialized_pipeline(
self._get_serialized_pipeline(),
shots,
output_dir_override=output_dir if output_dir else None,
filename_format_override=filename_format if filename_format else None
)
if self._get_sequence_data():
render_data = json.loads(self._get_sequence_data())
sequence = render_data.get("sequence_name")
level = render_data.get("level_name")
mrq_preset = render_data.get("mrq_preset_name")
return self.render_sequence(
sequence,
level,
mrq_preset,
shots,
output_dir_override=output_dir if output_dir else None,
filename_format_override=filename_format if filename_format else None
)
def render_queue(
self,
queue_path,
shots,
output_dir_override=None,
filename_format_override=None
):
"""
Executes a render from a queue
:param str queue_path: Name/path of the queue asset
:param list shots: Shots to render
:param str output_dir_override: Movie Pipeline output directory
:param str filename_format_override: Movie Pipeline filename format override
"""
unreal.log(f"Executing Queue asset `{queue_path}`")
unreal.log(f"Rendering shots: {shots}")
# Get an executor instance
executor = self._get_executor_instance()
# Set executor callbacks
# Set shot finished callbacks
executor.on_individual_shot_work_finished_delegate.add_callable(
self._on_individual_shot_finished_callback
)
# Set executor finished callbacks
executor.on_executor_finished_delegate.add_callable(
self._on_job_finished
)
executor.on_executor_errored_delegate.add_callable(self._on_job_failed)
# Render queue with executor
render_queue_asset(
queue_path,
shots=shots,
user=self.proxy.get_job_user(),
executor_instance=executor,
output_dir_override=output_dir_override,
output_filename_override=filename_format_override
)
def render_serialized_pipeline(
self,
manifest_file,
shots,
output_dir_override=None,
filename_format_override=None
):
"""
Executes a render using a manifest file
:param str manifest_file: serialized pipeline used to render a manifest file
:param list shots: Shots to render
:param str output_dir_override: Movie Pipeline output directory
:param str filename_format_override: Movie Pipeline filename format override
"""
unreal.log(f"Rendering shots: {shots}")
# Get an executor instance
executor = self._get_executor_instance()
# Set executor callbacks
# Set shot finished callbacks
executor.on_individual_shot_work_finished_delegate.add_callable(
self._on_individual_shot_finished_callback
)
# Set executor finished callbacks
executor.on_executor_finished_delegate.add_callable(
self._on_job_finished
)
executor.on_executor_errored_delegate.add_callable(self._on_job_failed)
render_queue_manifest(
manifest_file,
shots=shots,
user=self.proxy.get_job_user(),
executor_instance=executor,
output_dir_override=output_dir_override,
output_filename_override=filename_format_override
)
def render_sequence(
self,
sequence,
level,
mrq_preset,
shots,
output_dir_override=None,
filename_format_override=None
):
"""
Executes a render using a sequence level and map
:param str sequence: Level Sequence name
:param str level: Level
:param str mrq_preset: MovieRenderQueue preset
:param list shots: Shots to render
:param str output_dir_override: Movie Pipeline output directory
:param str filename_format_override: Movie Pipeline filename format override
"""
unreal.log(
f"Executing sequence `{sequence}` with map `{level}` "
f"and mrq preset `{mrq_preset}`"
)
unreal.log(f"Rendering shots: {shots}")
# Get an executor instance
executor = self._get_executor_instance()
# Set executor callbacks
# Set shot finished callbacks
executor.on_individual_shot_work_finished_delegate.add_callable(
self._on_individual_shot_finished_callback
)
# Set executor finished callbacks
executor.on_executor_finished_delegate.add_callable(
self._on_job_finished
)
executor.on_executor_errored_delegate.add_callable(self._on_job_failed)
render_current_sequence(
sequence,
level,
mrq_preset,
shots=shots,
user=self.proxy.get_job_user(),
executor_instance=executor,
output_dir_override=output_dir_override,
output_filename_override=filename_format_override
)
@staticmethod
def _get_executor_instance():
"""
Gets an instance of the movie pipeline executor
:return: Movie Pipeline Executor instance
"""
return utils.get_executor_instance(False)
def _on_individual_shot_finished_callback(self, shot_params):
"""
Callback to execute when a shot is done rendering
:param shot_params: Movie pipeline shot params
"""
unreal.log("Executing On individual shot callback")
# Since MRQ cannot parse certain parameters/arguments till an actual
# render is complete (e.g. local version numbers), we will use this as
# an opportunity to update the deadline proxy on the actual frame
# details that were rendered
file_patterns = set()
# Iterate over all the shots in the shot list (typically one shot as
# this callback is executed) on a shot by shot bases.
for shot in shot_params.shot_data:
for pass_identifier in shot.render_pass_data:
# only get the first file
paths = shot.render_pass_data[pass_identifier].file_paths
# make sure we have paths to iterate on
if len(paths) < 1:
continue
# we only need the ext from the first file
ext = os.path.splitext(paths[0])[1].replace(".", "")
# Make sure we actually have an extension to use
if not ext:
continue
# Get the current job output settings
output_settings = shot_params.job.get_configuration().find_or_add_setting_by_class(
unreal.MoviePipelineOutputSetting
)
resolve_params = unreal.MoviePipelineFilenameResolveParams()
# Set the camera name from the shot data
resolve_params.camera_name_override = shot_params.shot_data[
0
].shot.inner_name
# set the shot name from the shot data
resolve_params.shot_name_override = shot_params.shot_data[
0
].shot.outer_name
# Get the zero padding configuration
resolve_params.zero_pad_frame_number_count = (
output_settings.zero_pad_frame_numbers
)
# Update the formatting of frame numbers based on the padding.
# Deadline uses # (* padding) to display the file names in a job
resolve_params.file_name_format_overrides[
"frame_number"
] = "#" * int(output_settings.zero_pad_frame_numbers)
# Update the extension
resolve_params.file_name_format_overrides["ext"] = ext
# Set the job on the resolver
resolve_params.job = shot_params.job
# Set the initialization time on the resolver
resolve_params.initialization_time = (
unreal.MoviePipelineLibrary.get_job_initialization_time(
shot_params.pipeline
)
)
# Set the shot overrides
resolve_params.shot_override = shot_params.shot_data[0].shot
combined_path = unreal.Paths.combine(
[
output_settings.output_directory.path,
output_settings.file_name_format,
]
)
# Resolve the paths
# The returned values are a tuple with the resolved paths as the
# first index. Get the paths and add it to a list
(
path,
_,
) = unreal.MoviePipelineLibrary.resolve_filename_format_arguments(
combined_path, resolve_params
)
# Make sure we are getting the right type from resolved
# arguments
if isinstance(path, str):
# Sanitize the paths
path = os.path.normpath(path).replace("\\", "/")
file_patterns.add(path)
elif isinstance(path, list):
file_patterns.update(
set(
[
os.path.normpath(p).replace("\\", "/")
for p in path
]
)
)
else:
raise RuntimeError(
f"Expected the shot file paths to be a "
f"string or list but got: {type(path)}"
)
if file_patterns:
unreal.log(f'Updating remote filenames: {", ".join(file_patterns)}')
# Update the paths on the deadline job
self.proxy.update_job_output_filenames(list(file_patterns))
def _on_job_finished(self, executor=None, success=None):
"""
Callback to execute on executor finished
"""
# TODO: add th ability to set the output directory for the task
unreal.log(f"Task {self.current_task_id} complete!")
self.task_complete = True
def _on_job_failed(self, executor, pipeline, is_fatal, error):
"""
Callback to execute on job failed
"""
unreal.log_error(f"Is fatal job error: {is_fatal}")
unreal.log_error(
f"An error occurred executing task `{self.current_task_id}`: \n\t{error}"
)
self.proxy.fail_render(error)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="This parser is used to run an mrq render with rpc"
)
parser.add_argument(
"--port", type=int, default=None, help="Port number for rpc server"
)
parser.add_argument(
"--verbose", action="store_true", help="Enable verbose logging"
)
arguments = parser.parse_args()
MRQRender(port=arguments.port, verbose=arguments.verbose)
|
import unreal
from ueGear.controlrig.paths import CONTROL_RIG_FUNCTION_PATH
from ueGear.controlrig.components import base_component, EPIC_control_01
from ueGear.controlrig.helpers import controls
class Component(base_component.UEComponent):
name = "foot_component"
mgear_component = "EPIC_foot_01"
def __init__(self):
super().__init__()
self.functions = {'construction_functions': ["construct_IK_foot"],
'forward_functions': ["forward_IK_foot"],
'backwards_functions': ['backwards_IK_foot'],
}
self.cr_variables = {}
# Control Rig Inputs
self.cr_inputs = {'construction_functions': ["parent"],
'forward_functions': ["ik_active"],
'backwards_functions': [],
}
# Control Rig Outputs
self.cr_output = {'construction_functions': [],
'forward_functions': [],
'backwards_functions': [],
}
# mGear
self.inputs = []
self.outputs = []
def create_functions(self, controller: unreal.RigVMController = None):
if controller is None:
return
# Calls the super method, which creates the comment block
super().create_functions(controller)
# Generate Function Nodes
for evaluation_path in self.functions.keys():
# Skip the forward function creation if no joints are needed to be driven
if evaluation_path == 'forward_functions' and self.metadata.joints is None:
continue
# loop over control rig function nodes
for cr_func in self.functions[evaluation_path]:
new_node_name = f"{self.name}_{cr_func}"
ue_cr_node = controller.get_graph().find_node_by_name(new_node_name)
# Create Component if it does not exist
if ue_cr_node is None:
ue_cr_ref_node = controller.add_external_function_reference_node(CONTROL_RIG_FUNCTION_PATH,
cr_func,
unreal.Vector2D(0.0, 0.0),
node_name=new_node_name)
# In Unreal, Ref Node inherits from Node
ue_cr_node = ue_cr_ref_node
self.nodes[evaluation_path].append(ue_cr_node)
else:
# if exists, add it to the nodes
self.nodes[evaluation_path].append(ue_cr_node)
unreal.log_error(f" Cannot create function {new_node_name}, it already exists")
continue
# Gets the Construction Function Node and sets the control name
func_name = self.name + "_" + self.functions['construction_functions'][0]
construct_func = base_component.get_construction_node(self, f"{func_name}")
if construct_func is None:
unreal.log_error(" Create Functions Error - Cannot find construct singleton node")
else:
# Set construction functions side
controller.set_pin_default_value(f'{func_name}.side', self.metadata.side, False)
def populate_bones(self, bones: list[unreal.RigBoneElement] = None, controller: unreal.RigVMController = None):
"""
Populates the ball joint data on the foot nodes/functions.
"""
if bones is None or len(bones) < 1:
unreal.log_error("[Bone Populate] Failed - No Bones found")
return
if controller is None:
unreal.log_error("[Bone Populate] Failed no Controller found")
return
# Ball Joint
ball_jnt = bones[0]
jnt_name = str(ball_jnt.key.name)
# Assign ball joint to the construct node
construction_node = self.nodes["construction_functions"][0]
controller.set_pin_default_value(f'{construction_node.get_name()}.ball_joint',
f'(Type=Bone, Name="{jnt_name}")',
True)
# Assign ball joint to the forward node
forward_node = self.nodes["forward_functions"][0]
controller.set_pin_default_value(f'{forward_node.get_name()}.ball_joint',
f'(Type=Bone, Name="{jnt_name}")',
True)
# Assign ball joint to the backwards node
forward_node = self.nodes["backwards_functions"][0]
controller.set_pin_default_value(f'{forward_node.get_name()}.ball_joint',
f'(Type=Bone, Name="{jnt_name}")',
True)
def _init_master_joint_node(self, controller, node_name: str, bones):
"""Creates an array node of all the bones
"""
# Creates an Item Array Node to the control rig
node = controller.add_unit_node_from_struct_path(
'/project/.RigUnit_ItemArray',
'Execute',
unreal.Vector2D(-54.908936, 204.649109),
node_name)
self.add_misc_function(node)
pin_index = 0 # stores the current pin index that is being updated
for bone in bones:
bone_name = str(bone.key.name)
# Populates the Item Array Node
controller.insert_array_pin(f'{node_name}.Items', -1, '')
controller.set_pin_default_value(f'{node_name}.Items.{str(pin_index)}',
f'(Type=Bone,Name="{bone_name}")',
True)
controller.set_pin_expansion(f'{node_name}.Items.{str(pin_index)}', True)
controller.set_pin_expansion(f'{node_name}.Items', True)
pin_index += 1
def init_input_data(self, controller: unreal.RigVMController):
pass
def _set_transform_pin(self, node_name: str, pin_name: str, transform_value: unreal.Transform, controller):
quat = transform_value.rotation
pos = transform_value.translation
controller.set_pin_default_value(f"{node_name}.{pin_name}",
f"("
f"Rotation=(X={quat.x},Y={quat.y},Z={quat.z},W={quat.w}),"
f"Translation=(X={pos.x},Y={pos.y},Z={pos.z}),"
f"Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))",
True)
# todo: refactor the guide population code here
def _set_control(self, name, transform, controller: unreal.RigVMController):
pass
# todo: refactor the guide population code here
def _populate_guide_transform(self):
pass
def populate_control_transforms(self, controller: unreal.RigVMController = None):
"""Generates the list nodes of controls names and transforms
The foot does not rely on control positions as it uses the guideTransforms to place the
locations where the foot will rotate around.
"""
space_mtx = unreal.Matrix(x_plane=[1.000000, 0.000000, 0.000000, 0.000000],
y_plane=[0.000000, 0.000000, 1.000000, 0.000000],
z_plane=[0.000000, 1.000000, 0.000000, 0.000000],
w_plane=[0.000000, 0.000000, 0.000000, 1.000000])
# Gets the construction function name
construction_func_name = self.nodes["construction_functions"][0].get_name()
for guide_name, guide_mtx in self.metadata.guide_transforms.items():
# Space Convert between Maya and Unreal
guide_mtx = guide_mtx * space_mtx
transform = guide_mtx.transform()
# Rotates the Maya transformation data
corrected_quat = unreal.Quat()
transform.rotation = corrected_quat
pin_name = None
if guide_name == "root":
pin_name = "root"
elif guide_name == "1_loc":
pin_name = "tip"
elif guide_name == "heel":
pin_name = "heel"
elif guide_name == "0_loc":
pin_name = "fk0"
elif guide_name == "outpivot":
pin_name = "outer_pivot"
elif guide_name == "inpivot":
pin_name = "inner_pivot"
# Populate the pins transform data
if pin_name is None:
continue
self._set_transform_pin(construction_func_name,
pin_name,
transform,
controller)
# Setting the transform locations, in a specific order
if len(self.metadata.controls) != 6:
raise IOError("Please Contact developer, as only 6 controls are accounted for..")
# Creates an ordered list of control transforms
ordered_ctrl_trans = [None] * 6
ordered_bounding_box = [None] * 6
ordered_colours = [None] * 6
role_order = ["heel", "tip", "roll", "bk0", "bk1", "fk0"]
for ctrl_name in self.metadata.controls:
# Use the controls.Role metadata to detect the type
ctrl_role = self.metadata.controls_role[ctrl_name]
ctrl_trans = self.metadata.control_transforms[ctrl_name]
ctrl_bb = self.metadata.controls_aabb[ctrl_name]
ctrl_colour = self.metadata.controls_colour[ctrl_name]
# rudementary way of ordering the output list
if ctrl_role == role_order[0]:
ordered_ctrl_trans[0] = ctrl_trans
ordered_bounding_box[0] = ctrl_bb
ordered_colours[0] = ctrl_colour
elif ctrl_role == role_order[1]:
ordered_ctrl_trans[1] = ctrl_trans
ordered_bounding_box[1] = ctrl_bb
ordered_colours[1] = ctrl_colour
elif ctrl_role == role_order[2]:
ordered_ctrl_trans[2] = ctrl_trans
ordered_bounding_box[2] = ctrl_bb
ordered_colours[2] = ctrl_colour
elif ctrl_role == role_order[3]:
ordered_ctrl_trans[3] = ctrl_trans
ordered_bounding_box[3] = ctrl_bb
ordered_colours[3] = ctrl_colour
elif ctrl_role == role_order[4]:
ordered_ctrl_trans[4] = ctrl_trans
ordered_bounding_box[4] = ctrl_bb
ordered_colours[4] = ctrl_colour
elif ctrl_role == role_order[5]:
ordered_ctrl_trans[5] = ctrl_trans
ordered_bounding_box[5] = ctrl_bb
ordered_colours[5] = ctrl_colour
default_values = ""
# Adds a pin to the control_transforms pin on the construction node
for trans in ordered_ctrl_trans:
quat = trans.rotation
pos = trans.translation
string_entry = (f"(Rotation=(X={quat.x},Y={quat.y},Z={quat.z},W={quat.w}), "
f"Translation=(X={pos.x},Y={pos.y},Z={pos.z}), "
f"Scale3D=(X=1.000000,Y=1.000000,Z=1.000000)),")
default_values += string_entry
# trims off the extr ','
default_values = default_values[:-1]
# Populates and resizes the pin in one go
controller.set_pin_default_value(
f"{construction_func_name}.control_transforms",
f"({default_values})",
True,
setup_undo_redo=True,
merge_undo_action=True)
self.populate_control_scale(construction_func_name, ordered_bounding_box, controller)
self.populate_control_shape_offset(construction_func_name, ordered_bounding_box, controller)
self.populate_control_colour(construction_func_name, ordered_colours, controller)
def populate_control_scale(self, node_name, bounding_boxes, controller: unreal.RigVMController):
reduce_ratio = 4.0
"""Magic number to try and get the maya control scale to be similar to that of unreal.
As the mGear uses a square and ueGear uses a cirlce.
"""
default_values = ""
for aabb in bounding_boxes:
unreal_size = [round(element / reduce_ratio, 4) for element in aabb[1]]
# rudementary way to check if the bounding box might be flat, if it is then
# the first value if applied onto the axis
if unreal_size[0] == unreal_size[1] and unreal_size[2] < 0.2:
unreal_size[2] = unreal_size[0]
elif unreal_size[1] == unreal_size[2] and unreal_size[0] < 0.2:
unreal_size[0] = unreal_size[1]
elif unreal_size[0] == unreal_size[2] and unreal_size[1] < 0.2:
unreal_size[1] = unreal_size[0]
default_values += f'(X={unreal_size[0]},Y={unreal_size[1]},Z={unreal_size[2]}),'
# trims off the extr ','
default_values = default_values[:-1]
# Populates and resizes the pin in one go
controller.set_pin_default_value(
f'{node_name}.control_sizes',
f'({default_values})',
True,
setup_undo_redo=True,
merge_undo_action=True)
def populate_control_shape_offset(self, node_name, bounding_boxes, controller: unreal.RigVMController):
"""
As some controls have there pivot at the same position as the transform, but the control is actually moved
away from that pivot point. We use the bounding box position as an offset for the control shape.
"""
default_values = ""
for aabb in bounding_boxes:
bb_center = aabb[0]
string_entry = f'(X={bb_center[0]}, Y={bb_center[1]}, Z={bb_center[2]}),'
default_values += string_entry
# trims off the extr ','
default_values = default_values[:-1]
controller.set_pin_default_value(
f'{node_name}.control_offsets',
f'({default_values})',
True,
setup_undo_redo=True,
merge_undo_action=True)
def populate_control_colour(self, node_name, ordered_colours, controller: unreal.RigVMController):
default_values = ""
for colour in ordered_colours:
default_values += f"(R={colour[0]}, G={colour[1]}, B={colour[2]}, A=1.0),"
# trims off the extr ','
default_values = default_values[:-1]
# Populates and resizes the pin in one go
controller.set_pin_default_value(
f'{node_name}.control_colours',
f"({default_values})",
True,
setup_undo_redo=True,
merge_undo_action=True)
class ManualComponent(Component):
name = "EPIC_foot_01"
def __init__(self):
super().__init__()
self.functions = {'construction_functions': ['manual_construct_IK_foot'],
'forward_functions': ['manual_forward_IK_foot'],
'backwards_functions': ['backwards_IK_foot'],
}
self.is_manual = True
# These are the roles that will be parented directly under the parent component.
self.root_control_children = ["roll", "heel"]
self.hierarchy_schematic_roles = {
"heel": ["tip"],
"tip": ["bk0"],
"bk0": ["bk1"],
"bk1": ["null_fk0"],
"null_fk0": ["fk0"]
}
# Default to fall back onto
self.default_shape = "Circle_Thick"
self.control_shape = {
"fk0": "Box_Thick",
"roll": "Box_Thick",
"heel": "Sphere_Solid",
"bk1": "Sphere_Solid",
"bk0": "Sphere_Solid"
}
# Roles that will not be generated
# This is more of a developmental ignore, as we have not implemented this part of the component yet.
self.skip_roles = []
# todo: HANDLE OUTPIVOT AND INNERPIVOT => They are not Controls
def create_functions(self, controller: unreal.RigVMController):
EPIC_control_01.ManualComponent.create_functions(self, controller)
func_name = self.name + "_" + self.functions['construction_functions'][0]
controller.set_pin_default_value(f'{func_name}.side', self.metadata.side, False)
# todo: Create Null controls and add them to the hierarhcy_schematic
def generate_manual_null(self, hierarchy_controller: unreal.RigHierarchyController):
null_names = ["foot_{side}0_fk0_inverse"]
rolls_for_trans = ["bk1"]
control_trans_to_use = []
# Finds the controls name that has the role ik. it will be used to get the
# transformation data
for search_roll in rolls_for_trans:
for control_name in self.metadata.controls:
role = self.metadata.controls_role[control_name]
if role == search_roll:
control_trans_to_use.append(control_name)
# As this null does not exist, we create a new "fake" name and add it to the control_by_role. This is done
# so the parent hierarchy can detect it.
injected_role_name = ["null_fk0"]
for i, null_meta_name in enumerate(null_names):
trans_meta_name = control_trans_to_use[i]
null_role = injected_role_name[i]
null_name = null_meta_name.format(**{"side": self.metadata.side})
trans_name = trans_meta_name.format(**{"side": self.metadata.side})
control_transform = self.metadata.control_transforms[trans_name]
# Generate the Null
new_null = controls.CR_Control(name=null_name)
new_null.set_control_type(unreal.RigElementType.NULL)
new_null.build(hierarchy_controller)
new_null.set_transform(quat_transform=control_transform)
# rig_hrc = hierarchy_controller.get_hierarchy()
self.control_by_role[null_role] = new_null
def generate_manual_controls(self, hierarchy_controller: unreal.RigHierarchyController):
"""Creates all the manual controls for the Spine"""
# Stores the controls by Name
control_table = dict()
for control_name in self.metadata.controls:
new_control = controls.CR_Control(name=control_name)
role = self.metadata.controls_role[control_name]
# Skip a control that contains a role that has any of the keywords to skip
if any([skip in role for skip in self.skip_roles]):
continue
# stored metadata values
control_transform = self.metadata.control_transforms[control_name]
control_colour = self.metadata.controls_colour[control_name]
control_aabb = self.metadata.controls_aabb[control_name]
control_offset = control_aabb[0]
# - modified for epic arm
control_scale = [control_aabb[1][2] / 4.0,
control_aabb[1][2] / 4.0,
control_aabb[1][2] / 4.0]
# Set the colour, required before build
new_control.colour = control_colour
if role not in self.control_shape.keys():
new_control.shape_name = self.default_shape
else:
new_control.shape_name = self.control_shape[role]
# Generate the Control
new_control.build(hierarchy_controller)
# Sets the controls position, and offset translation and scale of the shape
new_control.set_transform(quat_transform=control_transform)
# - Modified for epic arm
new_control.shape_transform_global(pos=control_offset,
scale=control_scale,
rotation=[90, 0, 90])
control_table[control_name] = new_control
# Stores the control by role, for loopup purposes later
self.control_by_role[role] = new_control
self.generate_manual_null(hierarchy_controller)
self.initialize_hierarchy(hierarchy_controller)
def initialize_hierarchy(self, hierarchy_controller: unreal.RigHierarchyController):
"""Performs the hierarchical restructuring of the internal components controls"""
# Parent control hierarchy using roles
for parent_role in self.hierarchy_schematic_roles.keys():
child_roles = self.hierarchy_schematic_roles[parent_role]
parent_ctrl = self.control_by_role[parent_role]
for child_role in child_roles:
child_ctrl = self.control_by_role[child_role]
hierarchy_controller.set_parent(child_ctrl.rig_key, parent_ctrl.rig_key)
def populate_control_transforms(self, controller: unreal.RigVMController = None):
construction_func_name = self.nodes["construction_functions"][0].get_name()
controls = []
nulls = []
for role_key in ["heel", "tip", "roll", "bk0", "bk1", "fk0"]:
control = self.control_by_role[role_key]
controls.append(control)
for role_key in ["null_fk0"]:
control = self.control_by_role[role_key]
nulls.append(control)
# Converts RigElementKey into a string of key data.
def update_input_plug(plug_name, control_list):
"""
Simple helper function making the plug population reusable for ik and fk
"""
control_metadata = []
for entry in control_list:
if entry.rig_key.type == unreal.RigElementType.CONTROL:
t = "Control"
if entry.rig_key.type == unreal.RigElementType.NULL:
t = "Null"
n = entry.rig_key.name
entry = f'(Type={t}, Name="{n}")'
control_metadata.append(entry)
concatinated_controls = ",".join(control_metadata)
controller.set_pin_default_value(
f'{construction_func_name}.{plug_name}',
f"({concatinated_controls})",
True,
setup_undo_redo=True,
merge_undo_action=True)
update_input_plug("controls", controls)
update_input_plug("nulls", nulls)
def forward_solve_connect(self, controller: unreal.RigVMController):
"""
Performs any custom connections between forward solve components
"""
parent_forward_node_name = self.parent_node.nodes["forward_functions"][0].get_name()
forward_node_name = self.nodes["forward_functions"][0].get_name()
controller.add_link(f'{parent_forward_node_name}.ik_active_out',
f'{forward_node_name}.ik_active')
|
# Copyright Epic Games, Inc. All Rights Reserved
"""
Thinkbox Deadline REST API service plugin used to submit and query jobs from a Deadline server
"""
# Built-in
import json
import logging
import platform
from getpass import getuser
from threading import Thread, Event
# Internal
from deadline_job import DeadlineJob
from deadline_http import DeadlineHttp
from deadline_enums import DeadlineJobState, DeadlineJobStatus, HttpRequestType
from deadline_utils import get_editor_deadline_globals
from deadline_command import DeadlineCommand
# Third-party
import unreal
logger = logging.getLogger("DeadlineService")
logger.setLevel(logging.INFO)
class _Singleton(type):
"""
Singleton metaclass for the Deadline service
"""
# ------------------------------------------------------------------------------------------------------------------
# Class Variables
_instances = {}
# ------------------------------------------------------------------------------------------------------------------
# Magic Methods
def __call__(cls, *args, **kwargs):
"""
Determines the initialization behavior of this class
"""
if cls not in cls._instances:
cls._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
# TODO: Make this a native Subsystem in the editor
class DeadlineService(metaclass=_Singleton):
"""
Singleton class to handle Deadline submissions.
We are using a singleton class as there is no need to have multiple instances of the service. This allows job
queries and submissions to be tracked by a single entity and be a source of truth on the client about all jobs
created in the current session.
"""
# ------------------------------------------------------------------------------------------------------------------
# Magic Methods
def __init__(self, host=None, auto_start_job_updates=False, service_update_interval=1.0):
"""
Deadline service class for submitting jobs to deadline and querying data from deadline
:param str host: Deadline host
:param bool auto_start_job_updates: This flag auto starts processing jobs when the service is initialized
tracked by the service
:param float service_update_interval: Interval(seconds) for job update frequency. Default is 2.0 seconds
"""
# Track a dictionary of jobs registered with the service. This dictionary contains job object instance ID and a
# reference to the job instance object and deadline job ID.
# i.e {"instance_object_id": {"object": <job class instance>, "job_id": 0001 or None}}
self._current_jobs = {}
self._submitted_jobs = {} # Similar to the current jobs, this tracks all jobs submitted
self._failed_jobs = set()
self._completed_jobs = set()
# This flag determines if the service should deregister a job when it fails on the server
self.deregister_job_on_failure = True
# Thread execution variables
self._event_thread = None
self._exit_auto_update = False
self._update_thread_event = Event()
self._service_update_interval = service_update_interval
# A timer for executing job update functions on an interval
self._event_timer_manager = self.get_event_manager()
self._event_handler = None
# Use DeadlineCommand by defaut
self._use_deadline_command = self._get_use_deadline_cmd() # True # TODO: hardcoded for testing, change to project read setting
# Get/Set service host
self._host = host or self._get_deadline_host()
# Get deadline https instance
self._http_server = DeadlineHttp(self.host)
if auto_start_job_updates:
self.start_job_updates()
# ------------------------------------------------------------------------------------------------------------------
# Public Properties
@property
def pools(self):
"""
Returns the current list of pools found on the server
:return: List of pools on the server
"""
return self._get_pools()
@property
def groups(self):
"""
Returns the current list of groups found on the server
:return: List of groups on the server
"""
return self._get_groups()
@property
def use_deadline_command(self):
"""
Returns the current value of the use deadline command flag
:return: True if the service uses the deadline command, False otherwise
"""
return self._use_deadline_command
@use_deadline_command.setter
def use_deadline_command(self, value):
"""
Sets the use deadline command flag
:param value: True if the service uses the deadline command, False otherwise
"""
self._use_deadline_command = value
@property
def host(self):
"""
Returns the server url used by the service
:return: Service url
"""
return self._host
@host.setter
def host(self, value):
"""
Set the server host on the service
:param value: host value
"""
self._host = value
# When the host service is updated, get a new connection to that host
self._http_server = DeadlineHttp(self._host)
@property
def current_jobs(self):
"""
Returns the global current jobs tracked by the service
:return: List of Jobs tracked by the service
"""
return [value["object"] for value in self._current_jobs.values()]
@property
def failed_jobs(self):
"""
Returns the failed jobs tracked by the service
:return: List of failed Jobs tracked by the service
"""
return self._failed_jobs
@property
def completed_jobs(self):
"""
Returns the completed jobs tracked by the service
:return: List of completed Jobs tracked by the service
"""
return self._completed_jobs
# ------------------------------------------------------------------------------------------------------------------
# Protected Methods
def _get_pools(self):
"""
This method updates the set of pools tracked by the service
"""
if self._get_use_deadline_cmd(): # if self._use_deadline_command:
return DeadlineCommand().get_pools()
else:
response = self.send_http_request(
HttpRequestType.GET,
"api/pools",
headers={'Content-Type': 'application/json'}
)
return json.loads(response.decode('utf-8'))
def _get_groups(self):
"""
This method updates the set of groups tracked by the service
"""
if self._get_use_deadline_cmd(): # if self._use_deadline_command:
return DeadlineCommand().get_groups()
else:
response = self.send_http_request(
HttpRequestType.GET,
"api/groups",
headers={'Content-Type': 'application/json'}
)
return json.loads(response.decode('utf-8'))
def _register_job(self, job_object, deadline_job_id=None):
"""
This method registers the job object with the service
:param DeadlineJob job_object: Deadline Job object
:param str deadline_job_id: ID of job returned from the server
"""
# Set the job Id on the job. The service
# should be allowed to set this protected property on the job object as this property should natively
# not be allowed to be set externally
job_object._job_id = deadline_job_id
job_data = {
str(id(job_object)):
{
"object": job_object,
"job_id": deadline_job_id
}
}
self._submitted_jobs.update(job_data)
self._current_jobs.update(job_data)
def _deregister_job(self, job_object):
"""
This method removes the current job object from the tracked jobs
:param DeadlineJob job_object: Deadline job object
"""
if str(id(job_object)) in self._current_jobs:
self._current_jobs.pop(str(id(job_object)), f"{job_object} could not be found")
def _update_tracked_job_by_status(self, job_object, job_status, update_job=False):
"""
This method moves the job object from the tracked list based on the current job status
:param DeadlineJob job_object: Deadline job object
:param DeadlineJobStatus job_status: Deadline job status
:param bool update_job: Flag to update the job object's status to the passed in job status
"""
# Convert the job status into the appropriate enum. This will raise an error if the status enum does not exist.
# If a valid enum is passed into this function, the enum is return
job_status = job_object.get_job_status_enum(job_status)
# If the job has an unknown status, remove it from the currently tracked jobs by the service. Note we are not
# de-registering failed jobs unless explicitly set, that's because a failed job can be re-queued and
# completed on the next try.
# So we do not want to preemptively remove this job from the tracked jobs by the service.
if job_status is DeadlineJobStatus.UNKNOWN:
self._deregister_job(job_object)
self._failed_jobs.add(job_object)
elif job_status is DeadlineJobStatus.COMPLETED:
self._deregister_job(job_object)
self._completed_jobs.add(job_object)
elif job_status is DeadlineJobStatus.FAILED:
if self.deregister_job_on_failure:
self._deregister_job(job_object)
self._failed_jobs.add(job_object)
if update_job:
job_object.job_status = job_status
# ------------------------------------------------------------------------------------------------------------------
# Public Methods
def send_http_request(self, request_type, api_url, payload=None, fields=None, headers=None, retries=0):
"""
This method is used to upload or receive data from the Deadline server.
:param HttpRequestType request_type: HTTP request verb. i.e GET/project/
:param str api_url: URL relative path queries. Example: /jobs , /pools, /jobs?JobID=0000
:param payload: Data object to POST/PUT to Deadline server
:param dict fields: Request fields. This is typically used in files and binary uploads
:param dict headers: Header data for request
:param int retries: The number of retries to attempt before failing request. Defaults to 0.
:return: JSON object response from the server
"""
# Make sure we always have the most up-to-date host
if not self.host or (self.host != self._get_deadline_host()):
self.host = self._get_deadline_host()
try:
response = self._http_server.send_http_request(
request_type,
api_url,
payload=payload,
fields=fields,
headers=headers,
retries=retries
)
except Exception as err:
raise DeadlineServiceError(f"Communication with {self.host} failed with err: \n{err}")
else:
return response
def submit_job(self, job_object):
"""
This method submits the tracked job to the Deadline server
:param DeadlineJob job_object: Deadline Job object
:returns: Deadline `JobID` if an id was returned from the server
"""
self._validate_job_object(job_object)
logger.debug(f"Submitting {job_object} to {self.host}..")
if str(id(job_object)) in self._current_jobs:
logger.warning(f"{job_object} has already been added to the service")
# Return the job ID of the submitted job
return job_object.job_id
job_id = None
job_data = job_object.get_submission_data()
# Set the job data to return the job ID on submission
job_data.update(IdOnly="true")
# Update the job data to include the user and machine submitting the job
# Update the username if one is not supplied
if "UserName" not in job_data["JobInfo"]:
# NOTE: Make sure this matches the expected naming convention by the server else the user will get
# permission errors on job submission
# Todo: Make sure the username convention matches the username on the server
job_data["JobInfo"].update(UserName=getuser())
job_data["JobInfo"].update(MachineName=platform.node())
self._validate_job_info(job_data["JobInfo"])
if self._get_use_deadline_cmd(): # if self._use_deadline_command:
# Submit the job to the Deadline server using the Deadline command
# Todo: Add support for the Deadline command
job_id = DeadlineCommand().submit_job(job_data)
else:
# Submit the job to the Deadline server using the HTTP API
try:
response = self.send_http_request(
HttpRequestType.POST,
"api/jobs",
payload=json.dumps(job_data).encode('utf-8'),
headers={'Content-Type': 'application/json'}
)
except DeadlineServiceError as exp:
logger.error(
f"An error occurred submitting {job_object} to Deadline host `{self.host}`.\n\t{str(exp)}"
)
self._failed_jobs.add(job_object)
else:
try:
response = json.loads(response.decode('utf-8'))
# If an error occurs trying to decode the json data, most likely an error occurred server side thereby
# returning a string instead of the data requested.
# Raise the decoded error
except Exception as err:
raise DeadlineServiceError(f"An error occurred getting the server dat/project/{response.decode('utf-8')}")
job_id = response.get('_id', None)
if not job_id:
logger.warning(
f"No JobId was returned from the server for {job_object}. "
f"The service will not be able to get job details for this job!"
)
else:
# Register the job with the service.
self._register_job(job_object, job_id)
logger.info(f"Submitted `{job_object.job_name}` to Deadline. JobID: {job_id}")
return job_id
def get_job_details(self, job_object):
"""
This method gets the job details for the Deadline job
:param DeadlineJob job_object: Custom Deadline job object
:return: Job details object returned from the server. Usually a Json object
"""
self._validate_job_object(job_object)
if str(id(job_object)) not in self._current_jobs:
logger.warning(
f"{job_object} is currently not tracked by the service. The job has either not been submitted, "
f"its already completed or there was a problem with the job!"
)
elif not job_object.job_id:
logger.error(
f"There is no JobID for {job_object}!"
)
else:
try:
job_details = self._http_server.get_job_details(job_object.job_id)
except (Exception, RuntimeError):
# If an error occurred, most likely the job does not exist on the server anymore. Mark the job as
# unknown
self._update_tracked_job_by_status(job_object, DeadlineJobStatus.UNKNOWN, update_job=True)
else:
# Sometimes Deadline returns a status with a parenthesis after the status indicating the number of tasks
# executing. We only care about the status here so lets split the number of tasks out.
self._update_tracked_job_by_status(job_object, job_details["Job"]["Status"].split()[0])
return job_details
def send_job_command(self, job_object, command):
"""
Send a command to the Deadline server for the job
:param DeadlineJob job_object: Deadline job object
:param dict command: Command to send to the Deadline server
:return: Returns the response from the server
"""
self._validate_job_object(job_object)
if not job_object.job_id:
raise RuntimeError("There is no Deadline job ID to send this command for.")
try:
response = self._http_server.send_job_command(
job_object.job_id,
command
)
except Exception as exp:
logger.error(
f"An error occurred getting the command result for {job_object} from Deadline host {self.host}. "
f"\n{exp}"
)
return "Fail"
else:
if response != "Success":
logger.error(f"An error occurred executing command for {job_object}. \nError: {response}")
return "Fail"
return response
def change_job_state(self, job_object, state):
"""
This modifies a submitted job's state on the Deadline server. This can be used in job orchestration. For example
a job can be submitted as suspended/pending and this command can be used to update the state of the job to
active after submission.
:param DeadlineJob job_object: Deadline job object
:param DeadlineJobState state: State to set the job
:return: Submission results
"""
self._validate_job_object(job_object)
# Validate jobs state
if not isinstance(state, DeadlineJobState):
raise ValueError(f"`{state}` is not a valid state.")
return self.send_job_command(job_object, {"Command": state.value})
def start_job_updates(self):
"""
This method starts an auto update on jobs in the service.
The purpose of this system is to allow the service to automatically update the job details from the server.
This allows you to submit a job from your implementation and periodically poll the changes on the job as the
service will continuously update the job details.
Note: This function must explicitly be called or the `auto_start_job_updates` flag must be passed to the service
instance for this functionality to happen.
"""
# Prevent the event from being executed several times in succession
if not self._event_handler:
if not self._event_thread:
# Create a thread for the job update function. This function takes the current list of jobs
# tracked by the service. The Thread owns an instance of the http connection. This allows the thread
# to have its own pool of http connections separate from the main service. A thread event is passed
# into the thread which allows the process events from the timer to reactivate the function. The
# purpose of this is to prevent unnecessary re-execution while jobs are being processed.
# This also allows the main service to stop function execution within the thread and allow it to cleanly
# exit.
# HACK: For some odd reason, passing an instance of the service into the thread seems to work as
# opposed to passing in explicit variables. I would prefer explicit variables as the thread does not
# need to have access to the entire service object
# Threading is used here as the editor runs python on the game thread. If a function call is
# executed on an interval (as this part of the service is designed to do), this will halt the editor
# every n interval to process the update event. A separate thread for processing events allows the
# editor to continue functions without interfering with the editor
# TODO: Figure out a way to have updated variables in the thread vs passing the whole service instance
self._event_thread = Thread(
target=self._update_all_jobs,
args=(self,),
name="deadline_service_auto_update_thread",
daemon=True
)
# Start the thread
self._event_thread.start()
else:
# If the thread is stopped, restart it.
if not self._event_thread.is_alive():
self._event_thread.start()
def process_events():
"""
Function ran by the tick event for monitoring function execution inside of the auto update thread.
"""
# Since the editor ticks at a high rate, this monitors the current state of the function execution in
# the update thread. When a function is done executing, this resets the event on the function.
logger.debug("Processing current jobs.")
if self._update_thread_event.is_set():
logger.debug("Job processing complete, restarting..")
# Send an event to tell the thread to start the job processing loop
self._update_thread_event.clear()
# Attach the thread executions to a timer event
self._event_timer_manager.on_timer_interval_delegate.add_callable(process_events)
# Start the timer on an interval
self._event_handler = self._event_timer_manager.start_timer(self._service_update_interval)
# Allow the thread to stop when a python shutdown is detected
unreal.register_python_shutdown_callback(self.stop_job_updates)
def stop_job_updates(self):
"""
This method stops the auto update thread. This method should be explicitly called to stop the service from
continuously updating the current tracked jobs.
"""
if self._event_handler:
# Remove the event handle to the tick event
self.stop_function_timer(self._event_timer_manager, self._event_handler)
self._event_handler = None
if self._event_thread and self._event_thread.is_alive():
# Force stop the thread
self._exit_auto_update = True
# immediately stop the thread. Do not wait for jobs to complete.
self._event_thread.join(1.0)
# Usually if a thread is still alive after a timeout, then something went wrong
if self._event_thread.is_alive():
logger.error("An error occurred closing the auto update Thread!")
# Reset the event, thread and tick handler
self._update_thread_event.set()
self._event_thread = None
def get_job_object_by_job_id(self, job_id):
"""
This method returns the job object tracked by the service based on the deadline job ID
:param job_id: Deadline job ID
:return: DeadlineJob object
:rtype DeadlineJob
"""
job_object = None
for job in self._submitted_jobs.values():
if job_id == job["job_id"]:
job_object = job["object"]
break
return job_object
# ------------------------------------------------------------------------------------------------------------------
# Static Methods
@staticmethod
def _validate_job_info(job_info):
"""
This method validates the job info dictionary to make sure
the information provided meets a specific standard
:param dict job_info: Deadline job info dictionary
:raises ValueError
"""
# validate the job info plugin settings
if "Plugin" not in job_info or (not job_info["Plugin"]):
raise ValueError("No plugin was specified in the Job info dictionary")
@staticmethod
def _get_use_deadline_cmd():
"""
Returns the deadline command flag settings from the unreal project settings
:return: Deadline command settings unreal project
"""
try:
# This will be set on the deadline editor project settings
deadline_settings = unreal.get_default_object(unreal.DeadlineServiceEditorSettings)
# Catch any other general exceptions
except Exception as exc:
unreal.log(
f"Caught Exception while getting use deadline command flag. Error: {exc}"
)
else:
return deadline_settings.deadline_command
@staticmethod
def _get_deadline_host():
"""
Returns the host settings from the unreal project settings
:return: Deadline host settings unreal project
"""
try:
# This will be set on the deadline editor project settings
deadline_settings = unreal.get_default_object(unreal.DeadlineServiceEditorSettings)
# Catch any other general exceptions
except Exception as exc:
unreal.log(
f"Caught Exception while getting deadline host. Error: {exc}"
)
else:
return deadline_settings.deadline_host
@staticmethod
def _validate_job_object(job_object):
"""
This method ensures the object passed in is of type DeadlineJob
:param DeadlineJob job_object: Python object
:raises: RuntimeError if the job object is not of type DeadlineJob
"""
# Using type checking instead of isinstance to prevent cyclical imports
if not isinstance(job_object, DeadlineJob):
raise DeadlineServiceError(f"Job is not of type DeadlineJob. Found {type(job_object)}!")
@staticmethod
def _update_all_jobs(service):
"""
This method updates current running job properties in a thread.
:param DeadlineService service: Deadline service instance
"""
# Get a Deadline http instance inside for this function. This function is expected to be executed in a thread.
deadline_http = DeadlineHttp(service.host)
while not service._exit_auto_update:
while not service._update_thread_event.is_set():
# Execute the job update properties on the job object
for job_object in service.current_jobs:
logger.debug(f"Updating {job_object} job properties")
# Get the job details for this job and update the job details on the job object. The service
# should be allowed to set this protected property on the job object as this property should
# natively not be allowed to be set externally
try:
if job_object.job_id:
job_object.job_details = deadline_http.get_job_details(job_object.job_id)
# If a job fails to get job details, log it, mark it unknown
except Exception as err:
logger.exception(f"An error occurred getting job details for {job_object}:\n\t{err}")
service._update_tracked_job_by_status(
job_object,
DeadlineJobStatus.UNKNOWN,
update_job=True
)
# Iterate over the jobs and update the tracked jobs by the service
for job in service.current_jobs:
service._update_tracked_job_by_status(job, job.job_status)
service._update_thread_event.set()
@staticmethod
def get_event_manager():
"""
Returns an instance of an event timer manager
"""
return unreal.DeadlineServiceTimerManager()
@staticmethod
def start_function_timer(event_manager, function, interval_in_seconds=2.0):
"""
Start a timer on a function within an interval
:param unreal.DeadlineServiceTimerManager event_manager: Unreal Deadline service timer manager
:param object function: Function to execute
:param float interval_in_seconds: Interval in seconds between function execution. Default is 2.0 seconds
:return: Event timer handle
"""
if not isinstance(event_manager, unreal.DeadlineServiceTimerManager):
raise TypeError(
f"The event manager is not of type `unreal.DeadlineServiceTimerManager`. Got {type(event_manager)}"
)
event_manager.on_timer_interval_delegate.add_callable(function)
return event_manager.start_timer(interval_in_seconds)
@staticmethod
def stop_function_timer(event_manager, time_handle):
"""
Stops the timer event
:param unreal.DeadlineServiceTimerManager event_manager: Service Event manager
:param time_handle: Time handle returned from the event manager
"""
event_manager.stop_timer(time_handle)
class DeadlineServiceError(Exception):
"""
General Exception class for the Deadline Service
"""
pass
def get_global_deadline_service_instance():
"""
This method returns an instance of the service from
the interpreter globals.
:return:
"""
# This behavior is a result of unreal classes not able to store python object
# directly on the class due to limitations in the reflection system.
# The expectation is that uclass's that may not be able to store the service
# as a persistent attribute on a class can use the global service instance.
# BEWARE!!!!
# Due to the nature of the DeadlineService being a singleton, if you get the
# current instance and change the host path for the service, the connection will
# change for every other implementation that uses this service
deadline_globals = get_editor_deadline_globals()
if '__deadline_service_instance__' not in deadline_globals:
deadline_globals["__deadline_service_instance__"] = DeadlineService()
return deadline_globals["__deadline_service_instance__"]
|
import json
import random
import unreal
from actor.background import load_all_backgrounds
from actor.camera import Camera
from actor.level import Level
from actor.light import PointLight
from actor.metahuman import MetaHuman
import utils.utils as utils
from utils.utils import MetaHumanAssets
from pose import generate_pose_random, generate_pose_filter
PATH_MAIN = "/project/"
NUM_ANIMATION = 600
GAP_ANIMATION = 29
keys_agregation = [{"frame": t, "camera": {}, "metahuman": {}} for t in range((NUM_ANIMATION-1)*(GAP_ANIMATION+1) + 1)]
# Initialize level sequence
level = Level()
camera = Camera()
light1 = PointLight()
light2 = PointLight()
backgrounds = load_all_backgrounds()
metahuman = MetaHuman(MetaHumanAssets.hudson)
level.add_actor(camera)
level.add_actor(light1)
level.add_actor(light2)
level.add_actor(metahuman)
for background in backgrounds:
level.add_actor(background)
light1.add_key_random(0, offset=[0., 0., 180.])
light2.add_key_random(0, offset=[0., 0., 180.])
keys_camera = camera.add_key_random(0, distance=50, offset=[0., 0., 165.])
# Generate animation
with unreal.ScopedSlowTask(NUM_ANIMATION, "Generate Animation") as slow_task:
slow_task.make_dialog(can_cancel=True)
keys_metahuman_prec = None
keys_camera_prec = None
for k in range(NUM_ANIMATION):
slow_task.enter_progress_frame(work=1.0, desc=f'Generate Animation {k}/{NUM_ANIMATION}')
if slow_task.should_cancel():
break
frame_time = k*(GAP_ANIMATION + 1)
# keys_metahuman = metahuman.add_key_random_face(frame_time)
keys_metahuman = generate_pose_random(10, 10)
metahuman.add_key(keys_metahuman, frame_time)
# keys_camera = camera.add_key_random(frame_time, distance=50, offset=[0., 0., 165.])
# light1.add_key_random(frame_time, offset=[0., 0., 180.])
# light2.add_key_random(frame_time, offset=[0., 0., 180.])
background_choice = random.choice(backgrounds)
for b in backgrounds:
b.add_key_visibility(frame_time, False)
background_choice.add_key_visibility(frame_time, True)
# keys_agregation[frame_time]['camera'] = keys_camera
keys_agregation[frame_time]['metahuman'] = keys_metahuman
if keys_metahuman_prec and keys_camera_prec:
interp_keys_metahuman = utils.linear_interp_keys(keys_metahuman_prec, keys_metahuman, GAP_ANIMATION)
interp_keys_camera = utils.linear_interp_keys(keys_camera_prec, keys_camera, GAP_ANIMATION)
frame_time_prec = (k-1)*(GAP_ANIMATION + 1) + 1
for t in range(GAP_ANIMATION):
keys_agregation[frame_time_prec + t]['metahuman'] = interp_keys_metahuman[t]
keys_agregation[frame_time_prec + t]['camera'] = interp_keys_camera[t]
keys_metahuman_prec = keys_metahuman
keys_camera_prec = keys_camera
else:
keys_metahuman_prec = keys_metahuman
keys_camera_prec = keys_camera
# Change interpolation mode to linear
camera.change_interpmode(unreal.RichCurveInterpMode.RCIM_LINEAR)
light1.change_interpmode(unreal.RichCurveInterpMode.RCIM_LINEAR)
light2.change_interpmode(unreal.RichCurveInterpMode.RCIM_LINEAR)
metahuman.change_interpmode(unreal.RichCurveInterpMode.RCIM_LINEAR)
# Save keys
with open(PATH_MAIN + "keys.json", 'w') as file:
json.dump(keys_agregation, file, indent=4)
exit()
# Export animation to fbx file
with unreal.ScopedSlowTask(NUM_ANIMATION - 1, "Export Animation") as slow_task:
slow_task.make_dialog(can_cancel=True)
for k in range(NUM_ANIMATION - 1):
slow_task.enter_progress_frame(work=1.0, desc=f'Export Animation {k}/{NUM_ANIMATION}')
if slow_task.should_cancel():
break
beg_seq = k * (GAP_ANIMATION + 1)
end_seg = (k + 1) * (GAP_ANIMATION + 1) - 1
level.export_animation_fbx(beg_seq, end_seg, metahuman, PATH_MAIN + f"fbx/animation_{beg_seq}_{end_seg}.fbx")
level.level_sequence.set_playback_start(0)
|
import unreal
actors = unreal.EditorLevelLibrary.get_selected_level_actors()
count = 0
def add_unique(e, array):
if len(array) == 0:
array.append(e)
return
found = False
for a in array:
if a.equals(e):
found = True
break
if not found:
array.append(e)
# unreal.log("x {}, y {}, z {}".format(e.translation.x, e.translation.y, e.translation.z))
for actor in actors:
level = actor.get_outer()
unreal.EditorLevelLibrary.set_current_level_by_name(level.get_path_name().split('.')[-1].split(':')[0])
levelStreaming = unreal.GameplayStatics.get_streaming_level(unreal.EditorLevelLibrary.get_editor_world(),
level.get_full_name().split(":")[0])
components = actor.get_components_by_class(unreal.HierarchicalInstancedStaticMeshComponent)
if components is None:
components = actor.get_components_by_class(unreal.InstancedStaticMeshComponent)
if components is not None:
for comp in components:
trans_array = []
static_mesh = comp.static_mesh
instance_num = comp.get_instance_count()
for i in range(instance_num):
trans = comp.get_instance_transform(i, True)
add_unique(trans, trans_array)
if trans_array:
for trans in trans_array:
new_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor,
trans.translation)
new_actor.static_mesh_component.set_static_mesh(static_mesh)
new_actor.set_actor_label("{}_{}".format(static_mesh.get_name(), count))
new_actor.set_actor_transform(trans, False, False)
count += 1
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/project/-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unreal
def delete_empty_folders(source_dir: str, include_subfolders: bool = True) -> None:
# instances of unreal classes
editor_asset_lib = unreal.EditorAssetLibrary()
deleted_folder_count: int = 0
# get all assets in source dir
assets = editor_asset_lib.list_assets(source_dir, recursive=include_subfolders, include_folder=True)
# Created filtered list of folders
folders = [asset for asset in assets if editor_asset_lib.does_directory_exist(asset)]
for folder in folders:
if not editor_asset_lib.does_directory_have_assets(folder):
editor_asset_lib.delete_directory(folder)
deleted_folder_count += 1
unreal.log(f"Empty folder {folder} was deleted")
unreal.log(f"Deleted {deleted_folder_count} empty folders")
delete_empty_folders("/project/")
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" An example script that uses the API to instantiate an HDA and then set
the ramp points of a float ramp and a color ramp.
"""
import math
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.ramp_example_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def set_parameters(in_wrapper):
print('set_parameters')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(set_parameters)
# There are two ramps: heightramp and colorramp. The height ramp is a float
# ramp. As an example we'll set the number of ramp points and then set
# each point individually
in_wrapper.set_ramp_parameter_num_points('heightramp', 6)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 0, 0.0, 0.1)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 1, 0.2, 0.6)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 2, 0.4, 1.0)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 3, 0.6, 1.4)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 4, 0.8, 1.8)
in_wrapper.set_float_ramp_parameter_point_value('heightramp', 5, 1.0, 2.2)
# For the color ramp, as an example, we can set the all the points via an
# array.
in_wrapper.set_color_ramp_parameter_points('colorramp', (
unreal.HoudiniPublicAPIColorRampPoint(position=0.0, value=unreal.LinearColor.GRAY),
unreal.HoudiniPublicAPIColorRampPoint(position=0.5, value=unreal.LinearColor.GREEN),
unreal.HoudiniPublicAPIColorRampPoint(position=1.0, value=unreal.LinearColor.RED),
))
def print_parameters(in_wrapper):
print('print_parameters')
in_wrapper.on_post_processing_delegate.remove_callable(print_parameters)
# Print the ramp points directly
print('heightramp: num points {0}:'.format(in_wrapper.get_ramp_parameter_num_points('heightramp')))
heightramp_data = in_wrapper.get_float_ramp_parameter_points('heightramp')
if not heightramp_data:
print('\tNone')
else:
for idx, point_data in enumerate(heightramp_data):
print('\t\t{0}: position={1:.6f}; value={2:.6f}; interpoloation={3}'.format(
idx,
point_data.position,
point_data.value,
point_data.interpolation
))
print('colorramp: num points {0}:'.format(in_wrapper.get_ramp_parameter_num_points('colorramp')))
colorramp_data = in_wrapper.get_color_ramp_parameter_points('colorramp')
if not colorramp_data:
print('\tNone')
else:
for idx, point_data in enumerate(colorramp_data):
print('\t\t{0}: position={1:.6f}; value={2}; interpoloation={3}'.format(
idx,
point_data.position,
point_data.value,
point_data.interpolation
))
# Print all parameter values
param_tuples = in_wrapper.get_parameter_tuples()
print('parameter tuples: {}'.format(len(param_tuples) if param_tuples else 0))
if param_tuples:
for param_tuple_name, param_tuple in param_tuples.items():
print('parameter tuple name: {}'.format(param_tuple_name))
print('\tbool_values: {}'.format(param_tuple.bool_values))
print('\tfloat_values: {}'.format(param_tuple.float_values))
print('\tint32_values: {}'.format(param_tuple.int32_values))
print('\tstring_values: {}'.format(param_tuple.string_values))
if not param_tuple.float_ramp_points:
print('\tfloat_ramp_points: None')
else:
print('\tfloat_ramp_points:')
for idx, point_data in enumerate(param_tuple.float_ramp_points):
print('\t\t{0}: position={1:.6f}; value={2:.6f}; interpoloation={3}'.format(
idx,
point_data.position,
point_data.value,
point_data.interpolation
))
if not param_tuple.color_ramp_points:
print('\tcolor_ramp_points: None')
else:
print('\tcolor_ramp_points:')
for idx, point_data in enumerate(param_tuple.color_ramp_points):
print('\t\t{0}: position={1:.6f}; value={2}; interpoloation={3}'.format(
idx,
point_data.position,
point_data.value,
point_data.interpolation
))
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Set the float and color ramps on post instantiation, before the first
# cook.
_g_wrapper.on_post_instantiation_delegate.add_callable(set_parameters)
# Print the parameter state after the cook and output creation.
_g_wrapper.on_post_processing_delegate.add_callable(print_parameters)
if __name__ == '__main__':
run()
|
# -*- coding: utf-8 -*-
import time
import unreal
from Utilities.Utils import Singleton
import random
import os
class ChameleonSketch(metaclass=Singleton):
def __init__(self, jsonPath):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.ui_names = ["SMultiLineEditableTextBox", "SMultiLineEditableTextBox_2"]
self.debug_index = 1
self.ui_python_not_ready = "IsPythonReadyImg"
self.ui_python_is_ready = "IsPythonReadyImgB"
self.ui_is_python_ready_text = "IsPythonReadyText"
print ("ChameleonSketch.Init")
def mark_python_ready(self):
print("set_python_ready call")
self.data.set_visibility(self.ui_python_not_ready, "Collapsed")
self.data.set_visibility(self.ui_python_is_ready, "Visible")
self.data.set_text(self.ui_is_python_ready_text, "Python Path Ready.")
def get_texts(self):
for name in self.ui_names:
n = self.data.get_text(name)
print(f"name: {n}")
def set_texts(self):
for name in self.ui_names:
self.data.set_text(name, ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"][random.randint(0, 5)])
def set_text_one(self):
self.data.set_text(self.ui_names[self.debug_index], ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF"][random.randint(0, 5)] )
def get_text_one(self):
print(f"name: {self.data.get_text(self.ui_names[self.debug_index])}")
def tree(self):
print(time.time())
names = []
parent_indices = []
name_to_index = dict()
for root, folders, files in os.walk(r"/project/"):
root_name = os.path.basename(root)
if root not in name_to_index:
name_to_index[root] = len(names)
parent_indices.append(-1 if not names else name_to_index[os.path.dirname(root)])
names.append(root_name)
parent_id = name_to_index[root]
for items in [folders, files]:
for item in items:
names.append(item)
parent_indices.append(parent_id)
print(len(names))
self.data.set_tree_view_items("TreeViewA", names, parent_indices)
print(time.time())
|
# UnrealEngine 5.6 Import Script - UI Icons Batch
# Run this in the UE5 Python console to import all UI icons
import unreal
def import_ui_icons():
"""Import Terminal Grounds UI icons with proper settings"""
# Get asset tools
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
editor_asset_lib = unreal.EditorAssetLibrary
# List of UI icons to import (update paths as needed)
ui_icons = [
# Damage types
{"name": "damage_ballistic", "category": "damage"},
{"name": "damage_ion", "category": "damage"},
{"name": "damage_plasma", "category": "damage"},
# Status effects
{"name": "status_heat", "category": "status"},
{"name": "status_charge", "category": "status"},
{"name": "status_emp", "category": "status"},
# Rarity tiers
{"name": "rarity_common", "category": "rarity"},
{"name": "rarity_rare", "category": "rarity"},
{"name": "rarity_legendary", "category": "rarity"},
# Map markers
{"name": "extract_marker", "category": "map"},
{"name": "map_ping", "category": "map"},
{"name": "objective_marker", "category": "map"},
]
print("=" * 60)
print("Terminal Grounds UI Icon Import")
print("=" * 60)
imported_count = 0
for icon in ui_icons:
# Construct file path (adjust base path as needed)
file_path = f"C:/project/-Grounds/project/{icon['name']}_512.png"
# Set up import task
task = unreal.AssetImportTask()
task.filename = file_path
task.destination_path = "/project/"
task.replace_existing = True
task.automated = True
task.save = True
# Configure texture settings
factory = unreal.TextureFactory()
factory.compression_settings = unreal.TextureCompressionSettings.TC_DEFAULT
# UI icons should not have mipmaps for crisp display
factory.mip_gen_settings = unreal.TextureMipGenSettings.TMGS_NO_MIPMAPS
# Set texture group for UI
factory.lod_group = unreal.TextureGroup.TEXTUREGROUP_UI
task.factory = factory
try:
# Execute import
asset_tools.import_asset_tasks([task])
# Get the imported asset
asset_path = f"{task.destination_path}/{icon['name']}_512"
imported_asset = editor_asset_lib.load_asset(asset_path)
if imported_asset:
# Add metadata tags
imported_asset.set_editor_property("asset_import_data", {
"category": icon['category'],
"resolution": "512x512",
"faction": "terminal_grounds",
"tier": "production"
})
# Apply gameplay tags
tag_name = f"UI.Icon.{icon['category'].capitalize()}.{icon['name']}"
# Save the asset
editor_asset_lib.save_asset(asset_path)
imported_count += 1
print(f"✓ Imported: {icon['name']} -> {asset_path}")
else:
print(f"✗ Failed to load: {icon['name']}")
except Exception as e:
print(f"✗ Error importing {icon['name']}: {str(e)}")
print("\n" + "=" * 60)
print(f"Import Complete: {imported_count}/{len(ui_icons)} icons imported")
print("=" * 60)
# Create material instances for different states
if imported_count > 0:
create_icon_materials()
def create_icon_materials():
"""Create material instances for icon states (normal, hover, disabled)"""
print("\nCreating icon material instances...")
# Base material path (you'll need to create this base material)
base_material_path = "/project/"
# Material instance settings
material_states = [
{"name": "Normal", "tint": (1.0, 1.0, 1.0, 1.0)},
{"name": "Hover", "tint": (1.2, 1.2, 1.2, 1.0)},
{"name": "Pressed", "tint": (0.8, 0.8, 0.8, 1.0)},
{"name": "Disabled", "tint": (0.5, 0.5, 0.5, 0.5)},
]
# Create instances for each state
for state in material_states:
instance_name = f"MI_Icon_{state['name']}"
instance_path = f"/project/{instance_name}"
# Note: Material instance creation requires the base material to exist
print(f" • Material instance: {instance_name} (tint: {state['tint']})")
print("Material setup complete!")
# Run the import
if __name__ == "__main__":
import_ui_icons()
print("\n💡 Tip: Remember to download the generated images and save them")
print(" to the correct paths before running this import script!")
|
# /project/
# @CBgameDev Optimisation Script - Log Blueprints With Tick Enabled
# /project/
import unreal
import os
EditAssetLib = unreal.EditorAssetLibrary()
# SkeletalMeshLib = unreal.BlueprintFunctionLibrary() #dont think need
TickFunctionality = unreal.TickFunction()
workingPath = "/Game/" # Using the root directory
notepadFilePath = os.path.dirname(__file__) + "//PythonOptimiseLog.txt"
allAssets = EditAssetLib.list_assets(workingPath, True, False)
selectedAssetsPath = workingPath
LogStringsArray = []
numOfOptimisations = 0
with unreal.ScopedSlowTask(len(allAssets), selectedAssetsPath) as ST:
ST.make_dialog(True)
for asset in allAssets:
_assetData = EditAssetLib.find_asset_data(asset)
_assetName = _assetData.get_asset().get_name()
_assetPathName = _assetData.get_asset().get_path_name()
_assetClassName = _assetData.get_asset().get_class().get_name()
if _assetClassName == "Blueprint":
_BlueprintAsset = unreal.Blueprint.cast(_assetData.get_asset())
unreal.TickFunction.
unreal.log(_assetData.get_asset().get_editor_property("allow_tick_before_begin_play"))
# _assetData.get_editor_property("allow_tick_before_begin_play")
# unreal.Actor.cast(_BlueprintAsset.get_default_object())
# unreal.log(_assetData.get_asset().get_default_object())
# unreal.log(unreal.Actor.cast(_assetData.get_asset()))
# EditAssetLib.load_blueprint_class(_BlueprintAsset)
# _BlueprintAsset.TickFunctionality.get_editor_property("start_with_tick_enabled")
# .get_editor_property("allow_tick_before_begin_play ")
# _BlueprintAsset.get_default_object(_assetData.get_asset()).TickFunctionality
unreal.log("is a blueprint")
LogStringsArray.append(" %s ------------> At Path: %s \n" % (_assetName, _assetPathName))
# unreal.log("Asset Name: %s Path: %s \n" % (_assetName, _assetPathName))
numOfOptimisations += 1
# new way
asset_obj = EditAssetLib.load_asset(asset)
# isTickOn = asset_obj.get_editor_property(unreal.TickFunction.get_editor_property)
# important documentation: https://docs.unrealengine.com/4.26/en-US/project/.html
if ST.should_cancel():
break
ST.enter_progress_frame(1, asset)
# Write results into a log file
# /project/
TitleOfOptimisation = "Log Blueprints With Tick Enabled"
DescOfOptimisation = "Searches the entire project for blueprints which have tick enabled and that we could consider turning off"
SummaryMessageIntro = "-- Assets With 0 References That We Could Consider Deleting --"
if unreal.Paths.file_exists(notepadFilePath): # Check if txt file already exists
os.remove(notepadFilePath) # if does remove it
# Create new txt file and run intro text
file = open(notepadFilePath, "a+") # we should only do this if have a count?
file.write("OPTIMISING SCRIPT by @CBgameDev \n")
file.write("==================================================================================================== \n")
file.write(" SCRIPT NAME: %s \n" % TitleOfOptimisation)
file.write(" DESCRIPTION: %s \n" % DescOfOptimisation)
file.write("==================================================================================================== \n \n")
if numOfOptimisations <= 0:
file.write(" -- NONE FOUND -- \n \n")
else:
for i in range(len(LogStringsArray)):
file.write(LogStringsArray[i])
# Run summary text
file.write("\n")
file.write("======================================================================================================= \n")
file.write(" SUMMARY: \n")
file.write(" %s \n" % SummaryMessageIntro)
file.write(" Found: %s \n \n" % numOfOptimisations)
file.write("======================================================================================================= \n")
file.write(" Logged to %s \n" % notepadFilePath)
file.write("======================================================================================================= \n")
file.close()
os.startfile(notepadFilePath) # Trigger the notepad file to open
|
import unreal
import unreal_uiutils
from unreal_global import *
from unreal_utils import AssetRegistryPostLoad
unreal.log("""@
####################
Init Start up Script
####################
""")
assetregistry_pretickhandle = None
def assetregistry_postload_handle(deltaTime):
"""
Run callback method after registry run to prevent crashed when create new asset at startupS
"""
unreal.log_warning("..Checking Asset Registy Status...")
if AssetRegistry.is_loading_assets():
unreal.log_warning("..Asset registy still loading...")
else:
unreal.log_warning("Asset registy ready!")
unreal.unregister_slate_post_tick_callback(assetregistry_pretickhandle)
AssetRegistryPostLoad.run_callbacks()
assetregistry_pretickhandle = unreal.register_slate_post_tick_callback(assetregistry_postload_handle)
import BlueprintLibrary
import UserInterfaces
def reload():
import importlib
importlib.reload(BlueprintLibrary)
importlib.reload(UserInterfaces)
unreal_uiutils.refresh()
|
# -*- coding: utf-8 -*-
import unreal
from Utilities.Utils import Singleton
class MinimalExample(metaclass=Singleton):
def __init__(self, json_path:str):
self.json_path = json_path
self.data:unreal.ChameleonData = unreal.PythonBPLib.get_chameleon_data(self.json_path)
self.ui_output = "InfoOutput"
self.click_count = 0
def on_button_click(self):
self.click_count += 1
self.data.set_text(self.ui_output, "Clicked {} time(s)".format(self.click_count))
|
"""
Common utilities for UE5 automation scripts
Shared functions for Movie Render Queue validation and level management
"""
import unreal
# Constants that might be shared across scripts
VALID_JOB_TYPES = ["DF", "DU", "NF", "NU"]
PANO_POINT_BLUEPRINT_PATH = "/project/"
CAMERA_BLUEPRINT_PATH = "/project/"
class UE5RenderUtils:
"""Common utilities for UE5 rendering and validation"""
def __init__(self):
# Initialize subsystems
self.les = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
self.eas = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
self.mrq_subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
# Load common classes
self.pano_point_class = unreal.load_asset("/project/").generated_class()
self.camera_class = unreal.load_asset("/project/").generated_class()
def validate_render_job(self, job: unreal.MoviePipelineExecutorJob):
"""
Validate a single render job
Args:
job: MoviePipelineExecutorJob to validate
Returns:
tuple: (is_valid, level_name, job_comment, pano_point_names)
"""
unreal.log(f"Validating job: {job.job_name}")
null_return = (False, None, None, [])
if not job:
return null_return
if not job.map:
return null_return
ln = ".".join(job.map.export_text().split(".")[:-1])
if not job.sequence.export_text() or job.sequence.export_text().strip() == "None":
unreal.log_error(f"Job {job.job_name} does not have a valid sequence. Exiting...")
return null_return
if not job.comment or job.comment.strip() not in ["DF", "DU", "NF", "NU"]:
return null_return
if self.les.load_level(ln):
unreal.log(f"Level {ln} loaded successfully")
level_name = ln.split("/")[-1]
else:
unreal.log_error(f"Failed to load level {ln}. Exiting...")
return null_return
pano_points = sorted([actor for actor in self.eas.get_all_level_actors()
if actor.get_class() == self.pano_point_class],
key=lambda a: a.get_actor_label())
pano_point_names = sorted(list({p.get_actor_label() for p in pano_points}))
# Find your camera (assuming there's one VeroCineCam in the scene)
cameras = sorted([actor for actor in self.eas.get_all_level_actors()
if actor.get_class() == self.camera_class],
key=lambda a: a.get_actor_label())
camera = cameras[0] if cameras else None
if not camera:
unreal.log_error(f"VeroCineCam not found in level {level_name}")
return null_return
return True, level_name, job.comment, pano_point_names
def validate_movie_render_queue(self):
"""
Validate if Movie Render Queue is available and ready
Returns:
bool: True if queue is valid, False otherwise
"""
null_return = False, {}, {}
if not self.mrq_subsystem:
unreal.log_error("Movie Render Queue subsystem not found. Please ensure it is enabled in the project settings.")
return null_return
pipeline_queue = self.mrq_subsystem.get_queue()
if not pipeline_queue:
unreal.log_error("Movie Render Queue is empty. Please add jobs to the queue.")
return null_return
if not pipeline_queue.get_jobs():
unreal.log_error("No jobs found in the Movie Render Queue. Please add jobs to the queue.")
return null_return
unreal.log(f"Movie Render Queue with {len(pipeline_queue.get_jobs())} jobs is being validated.")
validation_data = {"jobs": []}
job_comment_dicts = {}
job_name_level_dict = {}
for i,job in enumerate(pipeline_queue.get_jobs()):
valid, level_name, job_comment, pano_point_names = self.validate_render_job(job)
if not valid:
unreal.log_error(f"Job {job.job_name} is invalid. Please check the job settings.")
return null_return
else:
unreal.log(f"Job {job.job_name} is valid with level {level_name}, comment {job_comment}, and pano points: {len(pano_point_names)}")
if job_comment not in job_comment_dicts:
job_comment_dicts[job_comment] = []
job_comment_dicts[job_comment].append((job.job_name, pano_point_names))
validation_data["jobs"].append(
{
"job_index": i,
"job_name": job.job_name,
"pano_points": "|".join(pano_point_names)
}
)
job_name_level_dict[job.job_name] = job.map.export_text()
unreal.log(", ".join([f"{k}: {len(v)} jobs" for k, v in job_comment_dicts.items()]))
level_set_dict = {}
for job_type, jobs in job_comment_dicts.items():
for job_name, pano_points in jobs:
pano_set_string = "|".join(pano_points)
if pano_set_string not in level_set_dict:
level_set_dict[pano_set_string] = []
level_set_dict[pano_set_string].append((job_name, job_type, job_name_level_dict[job_name], pano_points))
unreal.log(", ".join([f"{v[0][0] if len(v) else 'Empty'}: {len(v)} jobs" for k, v in level_set_dict.items()]))
for k in level_set_dict:
if len(level_set_dict[k]) != 4:
unreal.log_error(f"Job set does not have exactly 4 jobs. Please ensure each level has a job for each type (DF, DU, NF, NU).")
unreal.log_error(f"Found {', '.join([v[0] for v in level_set_dict[k]])} jobs for pano set.")
return null_return
if not set(["DF", "DU", "NF", "NU"]).issubset(set([v[1] for v in level_set_dict[k]])):
unreal.log_error(f"Job set does not have all required job types (DF, DU, NF, NU). Found: {', '.join([v[1] for v in level_set_dict[k]])}")
return null_return
# Example: collect the job name for the "DF" job type in this pano set
validation_dict = {}
for k in level_set_dict:
jd = {}
for ja in level_set_dict[k]:
jd[ja[1]] = ja[0]
jd['pano_points']= k
validation_dict[jd["DF"]] = jd
return True, validation_data, level_set_dict
# Convenience functions for backward compatibility or standalone use
def validate_render_job(job: unreal.MoviePipelineExecutorJob):
"""Standalone function wrapper for validate_render_job"""
utils = UE5RenderUtils()
return utils.validate_render_job(job)
def validate_movie_render_queue():
"""Standalone function wrapper for validate_movie_render_queue"""
utils = UE5RenderUtils()
return utils.validate_movie_render_queue()
if __name__ == "__main__":
success, op, lsd = validate_movie_render_queue()
for k, v in lsd.items():
unreal.log(f"{', '.join([f'{j[0]}:{j[2]} ({j[1]})' for j in v])}")
unreal.log("__________________________________________________________")
unreal.log(op)
|
import unreal
import os
unreal.log("{ { { { { { Init Unreal } } } } } } }")
|
import os
import unreal
def import_texture(texture_source_path, destination_path):
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
# Check if the texture is already in the destination path
texture_name = texture_source_path.split('/')[-1].split('.')[0]
existing_texture = unreal.EditorAssetLibrary.load_asset(f'{destination_path}/{texture_name}')
if existing_texture:
# Delete the existing texture if present
unreal.EditorAssetLibrary.delete_asset(existing_texture.get_path_name())
# Import the texture
task = unreal.AssetImportTask()
task.filename = texture_source_path
task.destination_path = destination_path
task.automated = True
task.save = True
asset_tools.import_asset_tasks([task])
# Check if the asset was imported successfully
if task.imported_object_paths:
imported_asset_path = task.imported_object_paths[0]
texture = unreal.EditorAssetLibrary.load_asset(imported_asset_path)
if texture:
return texture
else:
unreal.log_error(f"Failed to load imported texture from {imported_asset_path}")
return None
else:
unreal.log_error(f"Failed to import texture from {texture_source_path}")
return None
def create_or_get_material(texture, material_name):
material_path = f'/project/{material_name}'
material = unreal.EditorAssetLibrary.load_asset(material_path)
if not material:
material_factory = unreal.MaterialFactoryNew()
material = unreal.AssetToolsHelpers.get_asset_tools().create_asset(material_name, '/project/', unreal.Material, material_factory)
material_editor = unreal.MaterialEditingLibrary
texture_sample_node = material_editor.create_material_expression(material, unreal.MaterialExpressionTextureSample)
texture_sample_node.texture = texture
material_editor.connect_material_property(texture_sample_node, "RGB", unreal.MaterialProperty.MP_BASE_COLOR)
unreal.EditorAssetLibrary.save_asset(material.get_path_name())
material_editor.recompile_material(material)
return material
def replace_material_on_actor(actor_name, target_material_name, new_material):
actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
actors = actor_subsystem.get_all_level_actors()
for actor in actors:
if actor.get_actor_label() == actor_name:
static_mesh_component = actor.get_component_by_class(unreal.StaticMeshComponent)
if static_mesh_component:
materials = static_mesh_component.get_materials()
for i, material in enumerate(materials):
if material.get_name() == target_material_name or material.get_name() == "M_CoverageMap":
static_mesh_component.set_material(i, new_material)
actor.modify()
return True
else:
unreal.log_error(f"L'attore {actor_name} non ha un componente StaticMesh.")
return False
unreal.log_error(f"L'attore {actor_name} non è stato trovato nella scena")
return False
# Ottieni il percorso del progetto Unreal
project_content_dir = unreal.Paths.project_content_dir()
python_scripts_path = os.path.join(project_content_dir, 'PythonScripts')
textures_path = os.path.join(python_scripts_path, 'coverage_map_high_res.png')
# Percorsi relativi
texture_source_path = textures_path
texture_destination_path = '/project/'
material_name = 'M_CoverageMap'
actor_name = 'Mappa'
target_material_name = 'itu_concrete'
# Import texture, create material and apply it to the specified material slot on the actor
texture = import_texture(texture_source_path, texture_destination_path)
if texture:
material = create_or_get_material(texture, material_name)
success = replace_material_on_actor(actor_name, target_material_name, material)
if success:
unreal.EditorLoadingAndSavingUtils.save_dirty_packages(True, True)
unreal.log(f"Material {target_material_name} on actor {actor_name} successfully replaced with new material.")
|
# coding: utf-8
import unreal
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
parser.add_argument("-debugeachsave")
args = parser.parse_args()
#print(args.vrm)
######
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
h_mod = rig.get_hierarchy_modifier()
elements = h_mod.get_selection()
print(unreal.SystemLibrary.get_engine_version())
if (unreal.SystemLibrary.get_engine_version()[0] == '5'):
c = rig.get_controller()
else:
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
mesh = rig.get_preview_mesh()
morphList = mesh.get_all_morph_target_names()
morphListWithNo = morphList[:]
morphListRenamed = []
morphListRenamed.clear()
for i in range(len(morphList)):
morphListWithNo[i] = '{}'.format(morphList[i])
print(morphListWithNo)
###### root
key = unreal.RigElementKey(unreal.RigElementType.SPACE, 'MorphControlRoot_s')
space = h_mod.get_space(key)
if (space.get_editor_property('index') < 0):
space = h_mod.add_space('MorphControlRoot_s', space_type=unreal.RigSpaceType.SPACE)
else:
space = key
a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems()
print(a)
# 配列ノード追加
values_forCurve:unreal.RigVMStructNode = []
items_forControl:unreal.RigVMStructNode = []
items_forCurve:unreal.RigVMStructNode = []
for node in n:
print(node)
print(node.get_node_title())
# set curve num
if (node.get_node_title() == 'For Loop'):
print(node)
pin = node.find_pin('Count')
print(pin)
c.set_pin_default_value(pin.get_pin_path(), str(len(morphList)))
# curve name array pin
if (node.get_node_title() == 'Select'):
print(node)
pin = node.find_pin('Values')
#print(pin)
#print(pin.get_array_size())
#print(pin.get_default_value())
values_forCurve.append(pin)
# items
if (node.get_node_title() == 'Items'):
if ("Type=Curve," in c.get_pin_default_value(node.find_pin('Items').get_pin_path())):
items_forCurve.append(node.find_pin('Items'))
else:
items_forControl.append(node.find_pin('Items'))
print(values_forCurve)
# reset controller
for e in reversed(h_mod.get_elements()):
if (e.type!= unreal.RigElementType.CONTROL):
continue
tmp = h_mod.get_control(e)
if (tmp.space_name == 'MorphControlRoot_s'):
#if (str(e.name).rstrip('_c') in morphList):
# continue
print('delete')
#print(str(e.name))
h_mod.remove_element(e)
# curve array
for v in values_forCurve:
c.clear_array_pin(v.get_pin_path())
for morph in morphList:
tmp = "{}".format(morph)
c.add_array_pin(v.get_pin_path(), default_value=tmp)
# curve controller
for morph in morphListWithNo:
name_c = "{}_c".format(morph)
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c)
try:
control = h_mod.get_control(key)
if (control.get_editor_property('index') < 0):
k = h_mod.add_control(name_c,
control_type=unreal.RigControlType.FLOAT,
space_name=space.name,
gizmo_color=[1.0, 0.0, 0.0, 1.0],
)
control = h_mod.get_control(k)
except:
k = h_mod.add_control(name_c,
control_type=unreal.RigControlType.FLOAT,
space_name=space.name,
gizmo_color=[1.0, 0.0, 0.0, 1.0],
)
control = h_mod.get_control(k)
control.set_editor_property('gizmo_visible', False)
control.set_editor_property('gizmo_enabled', False)
h_mod.set_control(control)
morphListRenamed.append(control.get_editor_property('name'))
if (args.debugeachsave == '1'):
try:
unreal.EditorAssetLibrary.save_loaded_asset(rig)
except:
print('save error')
#unreal.SystemLibrary.collect_garbage()
# curve Control array
for v in items_forControl:
c.clear_array_pin(v.get_pin_path())
for morph in morphListRenamed:
tmp = '(Type=Control,Name='
tmp += "{}".format(morph)
tmp += ')'
c.add_array_pin(v.get_pin_path(), default_value=tmp)
# curve Float array
for v in items_forCurve:
c.clear_array_pin(v.get_pin_path())
for morph in morphList:
tmp = '(Type=Curve,Name='
tmp += "{}".format(morph)
tmp += ')'
c.add_array_pin(v.get_pin_path(), default_value=tmp)
|
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import unreal
from Utilities.Utils import Singleton
import random
import re
if sys.platform == "darwin":
import webbrowser
class ChameleonGallery(metaclass=Singleton):
def __init__(self, jsonPath):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.ui_scrollbox = "ScrollBox"
self.ui_crumbname = "SBreadcrumbTrailA"
self.ui_image = "SImageA"
self.ui_image_local = "SImage_ImageFromRelativePath"
self.ui_imageB = "SImage_ImageFromPath"
self.ui_progressBar = "ProgressBarA"
self.ui_drop_target_text_box = "DropResultBox"
self.ui_python_not_ready = "IsPythonReadyImg"
self.ui_python_is_ready = "IsPythonReadyImgB"
self.ui_is_python_ready_text = "IsPythonReadyText"
self.ui_details_view = "DetailsView"
self.ui_color_block = "ColorBlock"
self.ui_button_expand_color_picker = "ButtonExpandColorPicker"
self.ui_color_picker = "ColorPicker"
self.ui_dpi_scaler = "DPIScaler"
self.imageFlagA = 0
self.imageFlagB = 0
# set data in init
self.set_random_image_data()
self.data.set_combo_box_items('CombBoxA', ['1', '3', '5'])
self.data.set_object(self.ui_details_view, self.data)
self.is_color_picker_shown = self.data.get_visibility(self.ui_color_picker) == "Visible"
self.linearColor_re = re.compile(r"\(R=([-\d.]+),G=([-\d.]+),B=([-\d.]+),A=([-\d.]+)\)")
self.tapython_version = dict(unreal.PythonBPLib.get_ta_python_version())
print("ChameleonGallery.Init")
def mark_python_ready(self):
print("mark_python_ready call")
self.data.set_visibility(self.ui_python_not_ready, "Collapsed")
self.data.set_visibility(self.ui_python_is_ready, "Visible")
self.data.set_text(self.ui_is_python_ready_text, "Python Path Ready.")
def push_breadcrumb(self):
count = self.data.get_breadcrumbs_count_string(self.ui_crumbname)
strs = "is breadcrumb tail from alice in wonder world"
label = strs.split()[count % len(strs.split())]
self.data.push_breadcrumb_string(self.ui_crumbname, label, label)
def set_random_image_data(self):
width = 64
height = 64
colors = [unreal.LinearColor(1, 1, 1, 1) if random.randint(0, 1) else unreal.LinearColor(0, 0, 0, 1) for _ in range(width * height)]
self.data.set_image_pixels(self.ui_image, colors, width, height)
def set_random_progress_bar_value(self):
self.data.set_progress_bar_percent(self.ui_progressBar,random.random())
def change_local_image(self):
self.data.set_image_from(self.ui_image_local, ["Images/ChameleonLogo_c.png", "Images/ChameleonLogo_b.png"][self.imageFlagA])
self.imageFlagA = (self.imageFlagA + 1) % 2
def change_image(self):
self.data.set_image_from_path(self.ui_imageB, ["PythonChameleonIcon_128x.png", "Icon128.png"][self.imageFlagB])
self.imageFlagB = (self.imageFlagB + 1) % 2
def change_comboBox_items(self):
offset = random.randint(1, 10)
items = [str(v+offset) for v in range(random.randint(1, 10))]
self.data.set_combo_box_items("CombBoxA", items)
def launch_other_galleries(self):
if not os.path.exists(os.path.join(os.path.dirname(__file__), 'auto_gen/border_brushes_Gallery.json')):
unreal.PythonBPLib.notification("auto-generated Galleries not exists", info_level=1)
return
gallery_paths = ['ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json'
]
bLaunch = unreal.PythonBPLib.confirm_dialog(f'Open Other {len(gallery_paths)} Galleries? You can close them with the "Close all Gallery" Button' , "Open Other Galleries", with_cancel_button=False)
if bLaunch:
with unreal.ScopedSlowTask(len(gallery_paths), "Spawn Actors") as slow_task:
slow_task.make_dialog(True)
for i, p in enumerate(gallery_paths):
slow_task.enter_progress_frame(1, f"Launch Gallery: {p}")
unreal.ChameleonData.launch_chameleon_tool(p)
def request_close_other_galleries(self):
if not os.path.exists(os.path.join(os.path.dirname(__file__), 'auto_gen/border_brushes_Gallery.json')):
unreal.PythonBPLib.notification("auto-generated Galleries not exists", info_level=1)
return
gallery_paths = ['ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json',
'ChameleonGallery/project/.json'
]
for i, p in enumerate(gallery_paths):
unreal.ChameleonData.request_close(p)
# unreal.ChameleonData.request_close('/project/.json')
exists_tools_var = [globals()[x] for x in globals() if "Utilities.Utils.Singleton" in str(type(type(globals()[x])))]
def on_drop(self, assets, assets_folders, actors):
str_for_show = ""
for items, name in zip([assets, assets_folders, actors], ["Assets:", "Assets Folders:", "Actors:"]):
if items:
str_for_show += f"{name}\n"
for item in items:
str_for_show += f"\t{item}\n"
self.data.set_text(self.ui_drop_target_text_box, str_for_show)
print(f"str_for_show: {str_for_show}")
def on_drop_func(self, *args, **kwargs):
print(f"args: {args}")
print(f"kwargs: {kwargs}")
str_for_show = ""
for name, items in kwargs.items():
if items:
str_for_show += f"{name}:\n"
for item in items:
str_for_show += f"\t{item}\n"
self.data.set_text(self.ui_drop_target_text_box, str_for_show)
def get_full_size_of_this_chameleon(self):
current_size = unreal.ChameleonData.get_chameleon_window_size(self.jsonPath)
scrollbox_offsets = self.data.get_scroll_box_offsets(self.ui_scrollbox)
height_full = scrollbox_offsets["ScrollOffsetOfEnd"] / (1.0-scrollbox_offsets["viewFraction"])
height_full += 48
print(f"delta: {height_full} - {round(height_full)}")
return current_size.x, round(height_full)
def on_button_ChangeTabSize_click(self, offset_pixel):
current_size = unreal.ChameleonData.get_chameleon_window_size(self.jsonPath)
print(f"currentSize: {current_size}")
offsets = self.data.get_scroll_box_offsets(self.ui_scrollbox)
print(offsets)
if current_size:
current_size.x += offset_pixel
unreal.ChameleonData.set_chameleon_window_size("ChameleonGallery/ChameleonGallery.json", current_size)
def on_button_FlashWindow_click(self):
unreal.ChameleonData.flash_chameleon_window("ChameleonGallery/ChameleonGallery.json")
def on_button_Snapshot_click(self):
full_size = self.get_full_size_of_this_chameleon()
print(f"try save snapshot @ {full_size}")
saved_file_path = unreal.ChameleonData.snapshot_chameleon_window(self.jsonPath, unreal.Vector2D(*full_size))
if saved_file_path:
unreal.PythonBPLib.notification(f"UI Snapshot Saved:", hyperlink_text = saved_file_path
, on_hyperlink_click_command = f'chameleon_gallery.explorer("{saved_file_path}")')
else:
unreal.PythonBPLib.notification(f"Save UI snapshot failed.", info_level = 1)
def explorer(self, file_path):
if sys.platform == "darwin":
webbrowser.open(os.path.dirname(file_path))
else:
file_path = file_path.replace("/", "\\")
subprocess.call('explorer "{}" '.format(os.path.dirname(file_path)))
def set_selected_actor_to_details_view(self):
selected = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_selected_level_actors()
if selected:
self.data.set_object(self.ui_details_view, selected[0])
else:
print("Selected None")
def on_expand_color_picker_click(self):
self.data.set_visibility(self.ui_color_picker, "Collapsed" if self.is_color_picker_shown else "Visible")
self.data.set_text(self.ui_button_expand_color_picker, "Expand ColorPicker" if self.is_color_picker_shown else "Collapse ColorPicker")
self.is_color_picker_shown = not self.is_color_picker_shown
current_size = unreal.ChameleonData.get_chameleon_window_size(self.jsonPath)
if current_size.x < 650:
current_size.x = 650
unreal.ChameleonData.set_chameleon_window_size("ChameleonGallery/ChameleonGallery.json", current_size)
def on_color_picker_commit(self, color_str):
v = [float(a) for a in self.linearColor_re.match(color_str).groups()]
self.data.set_color(self.ui_color_block, unreal.LinearColor(*v))
def change_dpi_scaler_value(self, value):
if self.tapython_version["Minor"] < 2 or(
self.tapython_version["Minor"] == 2 and self.tapython_version["Patch"] < 1
):
print("Need TAPython version >= 1.2.1")
return
self.data.set_dpi_scale(self.ui_dpi_scaler, value + 0.5)
|
# filename: list_level_actors.py
# This script lists all actors in the current level using the Editor Actor Subsystem.
import unreal
# Get all level actors using the Editor Actor Subsystem
actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
all_actors = actor_subsystem.get_all_level_actors()
# Print their names to the Output Log
print("📋 Listing all actor names in the current level:")
for actor in all_actors:
print(f" - {actor.get_name()}")
|
import unreal
import sys
sys.path.append("C:/project/-packages")
from PySide import QtCore, QtGui, QtUiTools
editor_level_lib = unreal.EditorLevelLibrary()
class SimpleGUI(QtGui.QWidget):
def __init__(self, parent=None):
super(SimpleGUI, self).__init__(parent)
# load the created ui widget
self.widget = QtUiTools.QUiLoader().load("/project/.ui")
# attach the widget to the "self" GUI
self.widget.setParent(self)
# set the UI geometry (if UI is not centered/visible)
self.widget.setGeometry(0, 0, self.widget.width(), self.widget.height())
# find the interaction elements (XML structure)
self.text_l = self.widget.findChild(QtGui.QLineEdit, "textBox_L")
self.text_r = self.widget.findChild(QtGui.QLineEdit, "textBox_R")
self.checkbox = self.widget.findChild(QtGui.QCheckBox, "checkBox")
# find and assign slider
self.slider = self.widget.findChild(QtGui.QSlider, "horizontalSlider")
self.slider.sliderMoved.connect(self.on_slide)
# find buttons and set up handlers
self.btn_ok = self.widget.findChild(QtGui.QPushButton, "okButton")
self.btn_ok.clicked.connect(self.ok_clicked)
self.btn_cancel = self.widget.findChild(QtGui.QPushButton, "cancelButton")
self.btn_cancel.clicked.connect(self.cancel_clicked)
def on_slide(self):
slider_value = self.slider.value()
# move the selected actor according to the slider value
selected_actors = editor_level_lib.get_selected_level_actors()
if len(selected_actors) > 0:
actor = selected_actors[0]
# get old transform, change y axis value and write back
new_transform = actor.get_actor_transform()
new_transform.translation.y = slider_value
actor.set_actor_transform(new_transform, True, True)
# triggered on click of okButton
def ok_clicked(self):
text_l = self.text_l.text()
text_r = self.text_r.text()
is_checked = self.checkbox.isChecked()
unreal.log("Text Left Value: {}".format(text_l))
unreal.log("Text Right Value: {}".format(text_r))
unreal.log("Checkbox Value: {}".format(is_checked))
# triggered on click of cancelButton
def cancel_clicked(self):
unreal.log("Canceled")
self.close()
# only create an instance of the GUI when it's not already running
app = None
if not QtGui.QApplication.instance():
app = QtGui.QApplication(sys.argv)
# start the GUI
main_window = SimpleGUI()
main_window.show()
|
import random
import unreal
from config.config import control_json
def clip(key_name, value):
if control_json[key_name]['type'] == 'float':
new_value = max(value, control_json[key_name]['min'])
new_value = min(value, control_json[key_name]['max'])
return(new_value)
elif control_json[key_name]['type'] == 'vec2':
new_value_x = max(value[0], control_json[key_name]['min_x'])
new_value_x = min(new_value_x, control_json[key_name]['max_x'])
new_value_y = max(value[1], control_json[key_name]['min_y'])
new_value_y = min(new_value_y, control_json[key_name]['max_y'])
return([new_value_x, new_value_y])
def key_zero(key_name):
if control_json[key_name]['type'] == 'float_switch':
return(0.0000001)
elif control_json[key_name]['type'] == 'float':
return(0.0000001)
elif control_json[key_name]['type'] == 'vec2':
return([0.0000001, 0.0000001])
def key_min(key_name):
if control_json[key_name]['type'] == 'float':
return(control_json[key_name]['min'])
elif control_json[key_name]['type'] == 'vec2':
return([control_json[key_name]['min_x'], control_json[key_name]['min_y']])
def key_max(key_name):
if control_json[key_name]['type'] == 'float':
return(control_json[key_name]['max'])
elif control_json[key_name]['type'] == 'vec2':
return([control_json[key_name]['max_x'], control_json[key_name]['max_y']])
def key_gauss(key_name, mu=0.0, sigma=0.3):
if control_json[key_name]['type'] == 'float':
value = random.gauss(mu, sigma)
value = clip(key_name, value)
return(value)
elif control_json[key_name]['type'] == 'vec2':
value_x = random.gauss(mu, sigma)
value_y = random.gauss(mu, sigma)
vec = clip(key_name, [value_x, value_y])
return(vec)
def key_uniform(key_name):
if control_json[key_name]['type'] == 'float':
min_bound = control_json[key_name]['min']
max_bound = control_json[key_name]['max']
value = random.uniform(min_bound, max_bound)
return(value)
elif control_json[key_name]['type'] == 'vec2':
min_bound_x = control_json[key_name]['min_x']
max_bound_x = control_json[key_name]['max_x']
min_bound_y = control_json[key_name]['min_y']
max_bound_y = control_json[key_name]['max_y']
value_x = random.uniform(min_bound_x, max_bound_x)
value_y = random.uniform(min_bound_y, max_bound_y)
return([value_x, value_y])
def get_key_at_t(level_sequence, face_rig, frame):
new_key = {"frame": frame, "metahuman": {}}
frame = unreal.FrameNumber(frame)
for control in control_json.keys():
if control_json[control]['type'] == 'vec2':
vec2 = unreal.ControlRigSequencerLibrary.get_local_control_rig_vector2d(level_sequence, face_rig, control, frame)
value = [vec2.x, vec2.y]
new_key["metahuman"][control] = value
elif control_json[control]['type'] == 'float':
value = unreal.ControlRigSequencerLibrary.get_local_control_rig_float(level_sequence, face_rig, control, frame)
new_key["metahuman"][control] = value
return(new_key)
def get_all_keys(level_sequence, face_rig, frame_start, frame_end):
res = []
for k in range(frame_start, frame_end + 1):
new_key = get_key_at_t(level_sequence, face_rig, k)
res.append(new_key)
return(res)
|
import unreal
AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
MaterialEditLibrary = unreal.MaterialEditingLibrary
EditorAssetLibrary = unreal.EditorAssetLibrary
"""
AssetPath = "/project/"
# Check if the Material Exists
if EditorAssetLibrary.do_assets_exist(AssetPath):
#If asset exists, make a copy
NewAssetPath = "/project/"
EditorAssetLibrary.duplicate_asset(AssetPath, NewAssetPath)
MeshPaintMaterial = EditorAssetLibrary.load_asset(NewAssetPath)
else:
#If Asset does not exist, create a new material
"""
MeshPaintMaterial = AssetTools.create_asset("M_MeshPaint", "/project/", unreal.Material, unreal.MaterialFactoryNew())
#Add texture params for each surface
base_colors = []
normals = []
orm = []
#Create Vertex Color Nodes
NodePositionX = -500
NodePositionY = -300
VertexColorNode_Color = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 10 )
VertexColorNode_Color.set_editor_property('Desc', 'Base_Color')
VertexColorNode_Normal = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 8)
VertexColorNode_Color.set_editor_property('Desc', 'Normal')
VertexColorNode_R = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 6)
VertexColorNode_Color.set_editor_property('Desc', 'R_Occusion')
VertexColorNode_G = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 4)
VertexColorNode_Color.set_editor_property('Desc', 'Roughness')
VertexColorNode_B = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionVertexColor.static_class(), NodePositionX, NodePositionY * 2)
VertexColorNode_Color.set_editor_property('Desc', 'Metalic')
#Create One minus nodes
OneMinusNodeColor = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 10)
OneMinusNodeNormal = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 8)
OneMinusNode_R = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 6)
OneMinusNode_G = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY *4)
OneMinusNode_B = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionOneMinus.static_class(), NodePositionX * 2, NodePositionY * 2)
#Create Base Color, Normal and Orm Texture Parameters
for i in range(5):
#Create Texture Params
BaseColorParam = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), NodePositionX, NodePositionY + i * 150)
NormalParam = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(),NodePositionX, NodePositionY + i * 150)
ORMParam = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(),NodePositionX, NodePositionY + i * 150)
# Set names and sample types
BaseColorParam.set_editor_property("ParameterName", unreal.Name("BaseColor_{}".format(i)))
BaseColorParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
NormalParam.set_editor_property("ParameterName", unreal.Name("Normal_{}".format(i)))
NormalParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
NormalParam.set_editor_property('sampler_type', unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL)
ORMParam.set_editor_property("ParameterName", unreal.Name("ORM_{}".format(i)))
ORMParam.set_editor_property('sampler_source', unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
ORMParam.set_editor_property('sampler_type', unreal.MaterialSamplerType.SAMPLERTYPE_LINEAR_COLOR)
#append parameters to their arrays
base_colors.append(BaseColorParam)
normals.append(NormalParam)
orm.append(ORMParam)
#define lerp arrays
base_color_lerps = []
normal_lerps = []
orm_r_lerps = []
orm_g_lerps = []
orm_b_lerps = []
for i in range(5):
base_color_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
normal_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
orm_r_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
orm_g_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
orm_b_lerp = MaterialEditLibrary.create_material_expression(MeshPaintMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), NodePositionX, NodePositionY + i * 200)
base_color_lerps.append(base_color_lerp)
normal_lerps.append(normal_lerp)
orm_r_lerps.append(orm_r_lerp)
orm_g_lerps.append(orm_g_lerp)
orm_b_lerps.append(orm_b_lerp)
#Make Base Color Connections
#Connect Base Color Params to Lerps
MaterialEditLibrary.connect_material_expressions(base_colors[0], '', base_color_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[1], '', base_color_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[2], '', base_color_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[3], '', base_color_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[4], '', base_color_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(base_colors[4], '', base_color_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNodeColor, '', base_color_lerps[0], 'Alpha')
#Connect Vertex Color Node to Base Color Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'A', OneMinusNodeColor, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'R', base_color_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'G', base_color_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'B', base_color_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'A', base_color_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(base_color_lerps[0], '', base_color_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(base_color_lerps[1], '', base_color_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(base_color_lerps[2], '', base_color_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(base_color_lerps[3], '', base_color_lerps[4], 'A')
#Connect Last Lerp to the Base Color Channel
MaterialEditLibrary.connect_material_property(base_color_lerps[4], '', unreal.MaterialProperty.MP_BASE_COLOR)
#Make Normal Map Connections
#Connect Normal Params to Lerps
MaterialEditLibrary.connect_material_expressions(normals[0], '', normal_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(normals[1], '', normal_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(normals[2], '', normal_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(normals[3], '', normal_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(normals[4], '', normal_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(normals[4], '', normal_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNodeNormal, '', normal_lerps[0], 'Alpha')
#Connect Vertex Color Node to Normal Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'A', OneMinusNodeNormal, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'R', normal_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'G', normal_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'B', normal_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_Normal, 'A', normal_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(normal_lerps[0], '', normal_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(normal_lerps[1], '', normal_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(normal_lerps[2], '', normal_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(normal_lerps[3], '', normal_lerps[4], 'A')
#Connect Last Lerp to the Base Color Channel
MaterialEditLibrary.connect_material_property(normal_lerps[4], '', unreal.MaterialProperty.MP_NORMAL)
#Make Ambient Occlusion Connections
#Connect ORM Red Channel Params to Lerps
MaterialEditLibrary.connect_material_expressions(orm[0], 'R', orm_r_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(orm[1], 'R', orm_r_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(orm[2], 'R', orm_r_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(orm[3], 'R', orm_r_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'R', orm_r_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'R', orm_r_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNode_R, '', orm_r_lerps[0], 'Alpha')
#Connect Vertex Color Node to ORM_R Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'A', OneMinusNode_R, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'R', orm_r_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'G', orm_r_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'B', orm_r_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_R, 'A', orm_r_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(orm_r_lerps[0], '', orm_r_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(orm_r_lerps[1], '', orm_r_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(orm_r_lerps[2], '', orm_r_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(orm_r_lerps[3], '', orm_r_lerps[4], 'A')
#Connect Last Lerp to the Base Color Channel
MaterialEditLibrary.connect_material_property(orm_r_lerps[4], '', unreal.MaterialProperty.MP_AMBIENT_OCCLUSION)
#Make Roughness Connections
#Connect ORM Green Channel Params to Lerps
MaterialEditLibrary.connect_material_expressions(orm[0], 'G', orm_g_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(orm[1], 'G', orm_g_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(orm[2], 'G', orm_g_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(orm[3], 'G', orm_g_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'G', orm_g_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'G', orm_g_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNode_G, '', orm_g_lerps[0], 'Alpha')
#Connect Vertex Color Node to ORM_G Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'A', OneMinusNode_G, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'R', orm_g_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'G', orm_g_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'B', orm_g_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_G, 'A', orm_g_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(orm_g_lerps[0], '', orm_g_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(orm_g_lerps[1], '', orm_g_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(orm_g_lerps[2], '', orm_g_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(orm_g_lerps[3], '', orm_g_lerps[4], 'A')
#Connect Last Lerp to the Base Color Channel
MaterialEditLibrary.connect_material_property(orm_g_lerps[4], '', unreal.MaterialProperty.MP_ROUGHNESS)
#Make Metallic Connections
#Connect ORM Blue Channel Params to Lerps
MaterialEditLibrary.connect_material_expressions(orm[0], 'B', orm_b_lerps[0], 'B')
MaterialEditLibrary.connect_material_expressions(orm[1], 'B', orm_b_lerps[1], 'B')
MaterialEditLibrary.connect_material_expressions(orm[2], 'B', orm_b_lerps[2], 'B')
MaterialEditLibrary.connect_material_expressions(orm[3], 'B', orm_b_lerps[3], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'B', orm_b_lerps[4], 'B')
MaterialEditLibrary.connect_material_expressions(orm[4], 'B', orm_b_lerps[0], 'A')
MaterialEditLibrary.connect_material_expressions(OneMinusNode_B, '', orm_b_lerps[0], 'Alpha')
#Connect Vertex Color Node to ORM_B Lerps
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'A', OneMinusNode_B, '')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'R', orm_b_lerps[1], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'G', orm_b_lerps[2], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'B', orm_b_lerps[3], 'Alpha')
MaterialEditLibrary.connect_material_expressions(VertexColorNode_B, 'A', orm_b_lerps[4], 'Alpha')
# Make Lerp Connections
MaterialEditLibrary.connect_material_expressions(orm_b_lerps[0], '', orm_b_lerps[1], 'A')
MaterialEditLibrary.connect_material_expressions(orm_b_lerps[1], '', orm_b_lerps[2], 'A')
MaterialEditLibrary.connect_material_expressions(orm_b_lerps[2], '', orm_b_lerps[3], 'A')
MaterialEditLibrary.connect_material_expressions(orm_b_lerps[3], '', orm_b_lerps[4], 'A')
#Connect Last Lerp to the Base Color Channel
MaterialEditLibrary.connect_material_property(orm_b_lerps[4], '', unreal.MaterialProperty.MP_METALLIC)
#Create Material Instance
MeshPaintInstance = AssetTools.create_asset("MeshPaintInstance", "/project/", unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew())
MeshPaintInstance.set_editor_property("Parent", MeshPaintMaterial)
#MaterialEditLibrary.update_material_instance(MeshPaintInstance)
#Save Material and Instance
EditorAssetLibrary.save_asset("/project/", True)
EditorAssetLibrary.save_asset("/project/", True)
|
import json
import time
from typing import List, Optional, Tuple, Dict
import unreal
from GLOBAL_VARS import LEVEL_INFO_JSON, EditorLevelSub, EditorSub
################################################################################
# define decorators
def loader_func(func):
def wrap_func(*args, **kwargs):
unreal.log_warning("ticking.")
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
if asset_registry.is_loading_assets():
unreal.log_warning("still loading...")
else:
unreal.log_warning("ready!")
unreal.unregister_slate_pre_tick_callback(tickhandle)
result = func(*args, **kwargs)
return result
# This function shows the execution time of
# the function object passed
tickhandle = unreal.register_slate_pre_tick_callback(wrap_func)
return wrap_func
def timer_func(func):
# This function shows the execution time of
# the function object passed
def wrap_func(*args, **kwargs):
t1 = time.time()
result = func(*args, **kwargs)
t2 = time.time()
print(
f"[TimerLogger] Function {repr(func.__name__)} executed in {(t2-t1):.4f}s"
)
return result
return wrap_func
def ue_task(function):
def wrapper(*args, **kwargs):
slow_task = args[0] # args[0] is the first argument of the function
# slow_task = args[0].slow_task # args[0] is the instance of the class
# slow_task = kwargs['slow_task']
# print(slow_task)
# True if the user has pressed Cancel in the UI
if slow_task.should_cancel():
exit()
# log the start of the task
log_info = f"[PythonLogger] Running Function: {repr(function.__name__)}"
slow_task.enter_progress_frame(1, log_info)
# print(log_info)
# run the function
result = function(*args, **kwargs)
# log the end of the task
# print(f"[PythonLogger] Function {repr(function.__name__)} finished")
return result
return wrapper
################################################################################
class loadRegistry():
"""
example_usage:
registry = loadRegistry(RenderQueue)
registry.register()
"""
def __init__(self, func) -> None:
self.tickhandle = None
self.func = func
def testing(self, deltaTime):
unreal.log_warning("ticking.")
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
if asset_registry.is_loading_assets():
unreal.log_warning("still loading...")
else:
unreal.log_warning("ready!")
unreal.unregister_slate_pre_tick_callback(self.tickhandle)
self.func()
def register(self):
self.tickhandle = unreal.register_slate_pre_tick_callback(self.testing)
unreal.log_warning("registered!")
return self.tickhandle
def check_abort(slow_task):
slow_task.enter_progress_frame(1)
if slow_task.should_cancel():
exit()
def log_msg_with_socket(PIEExecutor: unreal.MoviePipelinePIEExecutor, msg: str):
PIEExecutor.send_socket_message(msg)
print(msg)
################################################################################
# misc
def get_world() -> unreal.World:
if EditorSub:
world = EditorSub.get_editor_world()
else:
world = unreal.EditorLevelLibrary.get_editor_world()
return world
def new_world(new_level_path: str) -> bool:
if EditorLevelSub:
success = EditorLevelSub.new_level(new_level_path)
else:
success = unreal.EditorLevelLibrary().new_level(new_level_path)
return success
def get_levels(world: Optional[unreal.World]=None) -> List[unreal.Level]:
if not world:
world = get_world()
levels = unreal.EditorLevelUtils.get_levels(world)
return levels
def save_current_level() -> None:
if EditorLevelSub:
EditorLevelSub.save_current_level()
else:
unreal.EditorLevelLibrary.save_current_level()
def get_soft_object_path(path: str) -> unreal.SoftObjectPath:
path = f'{path}.{path.split("/")[-1]}'
return unreal.SoftObjectPath(path)
def get_sublevels(persistent_level_path: str) -> List[Dict]:
"""get sublevels of persistent level, this step would load the persistent level.
Args:
persistent_level_path (str): a path to the persistent level, e.g. "/project/"
Returns:
level_configs (List(Dict)): a list of level_configs (dict) containing keys of
`level_name`, `is_visible`, and `streaming_class`.
"""
asset_registry: unreal.AssetRegistry = unreal.AssetRegistryHelpers.get_asset_registry()
# load persistent level
world = unreal.EditorLoadingAndSavingUtils.load_map(persistent_level_path)
# unreal.GameplayStatics.open_level(self.get_last_loaded_world(), mapPackagePath, True, gameOverrideClassPath)
# get all sub-levels of persistent level and their config
level_configs = []
persistent_level_asset_data = asset_registry.get_asset_by_object_path(persistent_level_path)
persistent_level_name = str(persistent_level_asset_data.package_name)
level_configs.append(
{
"level_name": persistent_level_name,
"is_visible": True,
"streaming_class": "LevelStreamingAlwaysLoaded",
}
)
levels: List[unreal.Level] = unreal.EditorLevelUtils.get_levels(world)
for level in levels:
asset_data = asset_registry.get_asset_by_object_path(level.get_path_name())
sub_level_name = str(asset_data.package_name)
streaming_level = unreal.GameplayStatics.get_streaming_level(world, sub_level_name)
if streaming_level is not None:
level_configs.append(
{
"level_name": sub_level_name,
"is_visible": streaming_level.is_level_visible(),
"streaming_class": type(streaming_level).__name__,
}
)
unreal.log(level_configs)
return level_configs
def add_levels(persistent_level_path: str, new_level_path: str) -> Tuple[List, List]:
"""add levels from persistent level to the current world
Args:
persistent_level_path (str): a path to the persistent level, e.g. "/project/"
Returns:
level_visible_names (list): a list of visible level names
level_hidden_names (list): a list of hidden level names
"""
# check if persistent level exists
is_level_exist = unreal.EditorAssetLibrary.does_asset_exist(persistent_level_path)
assert is_level_exist, RuntimeError(f"Persistent level does not exist", persistent_level_path)
# get/save sub-levels as json
sublevel_json = LEVEL_INFO_JSON
level_configs = []
level_infos = {}
if sublevel_json.exists():
with open(sublevel_json) as f:
level_infos: dict = json.load(f)
if persistent_level_path in level_infos.keys():
level_configs = level_infos[persistent_level_path]
if not level_configs:
# get sublevels of persistent level, this step would load the persistent level
level_configs = get_sublevels(persistent_level_path)
# reload new levels
world = unreal.EditorLoadingAndSavingUtils.load_map(new_level_path)
level_infos[persistent_level_path] = level_configs
with open(sublevel_json, "w") as f:
json.dump(level_infos, f, indent=4)
# add persistent level and its sub levels, set visibility
level_visible_names, level_hidden_names = [], []
world = get_world()
for level_config in level_configs:
level_name: str = level_config["level_name"]
is_visible: bool = level_config["is_visible"]
streaming_class: str = level_config["streaming_class"]
streaming_class_cls = getattr(unreal, streaming_class)
streaming_level: unreal.LevelStreaming = unreal.EditorLevelUtils.add_level_to_world(world, level_name, streaming_class_cls)
assert (streaming_class_cls is not None), f"Unknown unreal class: {streaming_class}"
assert (streaming_level is not None), f"Unable to add level to the world: {level_name}"
unreal.EditorLevelUtils.set_level_visibility(streaming_level.get_loaded_level(), is_visible, False)
level_basename = level_name.rpartition("/")[-1]
if is_visible:
level_visible_names.append(level_basename)
else:
level_hidden_names.append(level_basename)
return level_visible_names, level_hidden_names
@ue_task
@timer_func
def tmp(slow_task):
time.sleep(0.01)
def task_bar():
with unreal.ScopedSlowTask(100, 'Running') as slow_task:
slow_task.make_dialog(True)
for i in range(100):
time.sleep(0.01)
check_abort(slow_task)
with unreal.ScopedSlowTask(100, 'Running') as slow_task:
slow_task.make_dialog(True)
for i in range(100):
tmp(slow_task)
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" An example script that uses the API to instantiate an HDA and then
set 2 inputs: a geometry input (a cube) and a curve input (a helix). The
inputs are set during post instantiation (before the first cook). After the
first cook and output creation (post processing) the input structure is fetched
and logged.
"""
import math
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.copy_to_curve_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_geo_asset_path():
return '/project/.Cube'
def get_geo_asset():
return unreal.load_object(None, get_geo_asset_path())
def configure_inputs(in_wrapper):
print('configure_inputs')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs)
# Create a geo input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input
geo_object = get_geo_asset()
if not geo_input.set_input_objects((geo_object, )):
# If any errors occurred, get the last error message
print('Error on geo_input: {0}'.format(geo_input.get_last_error_message()))
# copy the input data to the HDA as node input 0
in_wrapper.set_input_at_index(0, geo_input)
# We can now discard the API input object
geo_input = None
# Create a curve input
curve_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(100):
t = i / 20.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Error handling/message example: try to set geo_object on curve input
if not curve_input.set_input_objects((geo_object, )):
print('Error (example) while setting \'{0}\' on curve input: {1}'.format(
geo_object.get_name(), curve_input.get_last_error_message()
))
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Copy the input data to the HDA as node input 1
in_wrapper.set_input_at_index(1, curve_input)
# We can now discard the API input object
curve_input = None
# Check for errors on the wrapper
last_error = in_wrapper.get_last_error_message()
if last_error:
print('Error on wrapper during input configuration: {0}'.format(last_error))
def print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference))
if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput):
print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge))
print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds))
print('\t\tbExportSockets: {0}'.format(in_input.export_sockets))
print('\t\tbExportColliders: {0}'.format(in_input.export_colliders))
elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput):
print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed))
print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves))
input_objects = in_input.get_input_objects()
if not input_objects:
print('\t\tEmpty input!')
else:
print('\t\tNumber of objects in input: {0}'.format(len(input_objects)))
for idx, input_object in enumerate(input_objects):
print('\t\t\tInput object #{0}: {1}'.format(idx, input_object))
if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject):
print('\t\t\tbClosed: {0}'.format(input_object.is_closed()))
print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method()))
print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type()))
print('\t\t\tReversed: {0}'.format(input_object.is_reversed()))
print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points()))
def print_inputs(in_wrapper):
print('print_inputs')
# Unbind from the delegate
in_wrapper.on_post_processing_delegate.remove_callable(print_inputs)
# Fetch inputs, iterate over it and log
node_inputs = in_wrapper.get_inputs_at_indices()
parm_inputs = in_wrapper.get_input_parameters()
if not node_inputs:
print('No node inputs found!')
else:
print('Number of node inputs: {0}'.format(len(node_inputs)))
for input_index, input_wrapper in node_inputs.items():
print('\tInput index: {0}'.format(input_index))
print_api_input(input_wrapper)
if not parm_inputs:
print('No parameter inputs found!')
else:
print('Number of parameter inputs: {0}'.format(len(parm_inputs)))
for parm_name, input_wrapper in parm_inputs.items():
print('\tInput parameter name: {0}'.format(parm_name))
print_api_input(input_wrapper)
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Configure inputs on_post_instantiation, after instantiation, but before first cook
_g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs)
# Print the input state after the cook and output creation.
_g_wrapper.on_post_processing_delegate.add_callable(print_inputs)
if __name__ == '__main__':
run()
|
from infrastructure.logging.base_logging import BaseLogging
from infrastructure.configuration.path_manager import PathManager
import unreal
import os
class FileLogging(BaseLogging):
def log(self, message):
logFilePath = PathManager.get_file_log_path()
if unreal.Paths.file_exists(logFilePath):
os.remove(logFilePath)
unreal.log_warning("Removing file")
with open(logFilePath, "a+") as file_object:
if isinstance(message, list) and len(message) > 0:
for a in message:
file_object.write(a)
elif isinstance(message, str):
file_object.write(message)
else:
file_object.write("No message to show")
os.startfile(logFilePath)
|
"""
# Unreal Paths
* Description
A library of common core related paths for Unreal.
"""
from pathlib import Path
import unreal
# ----------Project level directories------------------------------------------
PROJECT_DIR = Path(unreal.SystemLibrary.get_project_directory())
PLUGINS_DIR = Path(PROJECT_DIR, 'Plugins')
CONTENT_DIR = Path(unreal.SystemLibrary.get_project_content_directory())
CONFIG_DIR = Path(PROJECT_DIR, 'config')
PIPELINE_CONFIG_DIR = Path(CONFIG_DIR, 'core')
# ----------Project level ini configs------------------------------------------
INI_EDITOR = Path(CONFIG_DIR, 'DefaultEditor.ini')
INI_LIGHTMASS = Path(CONFIG_DIR, 'DefaultLightmass.ini')
INI_EDITOR_SETTINGS = Path(CONFIG_DIR, 'DefaultEditorSettings.ini')
INI_ENGINE = Path(CONFIG_DIR, 'DefaultEngine.ini')
INI_GAME = Path(CONFIG_DIR, 'DefaultGame.ini')
INI_INPUT = Path(CONFIG_DIR, 'DefaultInput.ini')
|
import unreal
def CreateSequence(sequence_name, package_path='/project/'):
'''
Args:
sequence_name(str): The name of the sequence to be created
package_path(str): The location for the new sequence
Returns:
unreal.LevelSequence: The created level sequence
'''
all_actors = unreal.EditorLevelLibrary.get_all_level_actors()
# Create the sequence asset in the desired location
sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset(
sequence_name,
package_path,
unreal.LevelSequence,
unreal.LevelSequenceFactoryNew())
sequence.set_playback_end(1)
movie_scene = sequence.get_movie_scene()
for actor in all_actors:
actor_binding = sequence.add_possessable(actor)
return sequence
def LoadBlueprint(blueprint_path: str, loc: unreal.Vector = unreal.Vector(0, 0, 0),
rot: unreal.Rotator = unreal.Rotator(0, 0, 0)):
"""
Parameters
----------
blueprint_path : str
Unreal path to the blue print eg. Game/project/
loc : unreal.Vector, optional
Desired Position in absolute coordinates The default is unreal.Vector(0,0, 0).
rot : unreal.Rotator, optional
Desired Rotation The default is unreal.Rotator(0, 0, 0).
Returns
-------
actor : TYPE
Actor as defined by the blue print
"""
asset = unreal.EditorAssetLibrary.load_asset(blueprint_path)
if asset is None:
print(f"Failed to load asset at {blueprint_path}")
return None
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(asset, loc, rot)
return actor
def add_metahuman_components_to_sequence(sequence, metahuman_actor, sequence_path):
# Retrieve all components attached to the metahuman actor
unreal.log("before world")
editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
sequence_path = sequence_path
sequence_to_activate = unreal.load_asset(sequence_path)
print("under_world")
s = unreal.LevelSequenceEditorBlueprintLibrary.open_level_sequence(sequence_to_activate)
print("overworld")
# Use the new recommended method to get the editor world
world = editor_subsystem.get_editor_world()
unreal.log("world")
skeletal_mesh_components = metahuman_actor.get_components_by_class(unreal.SkeletalMeshComponent)
unreal.log("mesh")
# sequence = unreal.LevelSequenceEditorBlueprintLibrary.get_current_level_sequence()
unreal.log("sequence")
for skeletal_mesh_component in skeletal_mesh_components:
# Assuming naming convention to identify relevant skeletal meshes for control rigs
if "face" in skeletal_mesh_component.get_name().lower():
rig = unreal.load_asset('/project/')
skel = sequence.add_possessable(skeletal_mesh_component)
rig_class = rig.get_control_rig_class()
rig_track = unreal.ControlRigSequencerLibrary.find_or_create_control_rig_track(world, sequence, rig_class,
skel)
elif "body" in skeletal_mesh_component.get_name().lower():
rig = unreal.load_asset("/project/")
skel = sequence.add_possessable(skeletal_mesh_component)
rig_class = rig.get_control_rig_class()
rig_track = unreal.ControlRigSequencerLibrary.find_or_create_control_rig_track(world, sequence, rig_class,
skel)
def reset_scene(sequence_path):
"""
Deletes the specified sequence from the asset library and removes the MetaHuman actor and camera actor from the scene.
Args:
sequence_path (str): The path to the sequence asset in the asset library.
Returns:
None
"""
# Delete the sequence from the asset library
sequence_asset = unreal.EditorAssetLibrary.load_asset(sequence_path)
if sequence_asset:
unreal.EditorAssetLibrary.delete_asset(sequence_path)
print(f"Sequence '{sequence_path}' deleted from the asset library.")
else:
print(f"Sequence '{sequence_path}' not found in the asset library.")
all_actors = unreal.EditorLevelLibrary.get_all_level_actors()
for actor in all_actors:
unreal.log(actor.get_name())
if "F" in actor.get_name() or "Rig" in actor.get_name() or actor.get_class().get_name() == "CineCameraActor" or "H" in actor.get_name():
unreal.EditorLevelLibrary.destroy_actor(actor)
print(f"Deleted actor: {actor.get_name()}")
def find_delta_z(rig,sequence):
control_name = "CTRL_C_jaw"
frame_number = unreal.FrameNumber(0)
pos = unreal.ControlRigSequencerLibrary.get_control_rig_world_transform(sequence, rig, control_name, frame_number)
print(pos)
return 142.458249 - pos.translation.z
def get_file_paths(folder_path, limit=0):
file_paths = []
# Convertir le chemin du dossier en un objet Path d'Unreal Engine
assets = unreal.EditorAssetLibrary.list_assets(folder_path)
# Parcourir les assets et ajouter leurs chemins complets à la liste
asset_paths = unreal.EditorAssetLibrary.list_assets(folder_path)
cnt = 0
# Parcourir les chemins d'assets et ajouter les chemins valides à la liste
for asset_path in asset_paths:
cnt += 1
if unreal.EditorAssetLibrary.does_asset_exist(asset_path):
file_paths.append(asset_path)
if cnt == limit:
break
return file_paths
def start_over():
"""
This functions cleans up the project file:
it whipes out all existing sequences and free up the rendering queue
Usefull to make several batches in row
Returns
-------
"""
# find and delete sequences
all_sequence_path = get_file_paths("/project/")
for seq_path in all_sequence_path:
reset_scene(seq_path)
# Wipe the queue
subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
executor = unreal.MoviePipelinePIEExecutor()
queue = subsystem.get_queue()
queue.delete_all_jobs()
iden = "HN017"
start_over()
sequ_name = "test"
sequ_path = "/project/"
path = f"/project/{iden}/BP_{iden}"
MH = LoadBlueprint(path, unreal.Vector(0, 0, 0)) # place it in a row aligned with it's friends (see enumarate loop with full_run)
sequence = CreateSequence(sequ_name, sequ_path) # finally create the seuqnce
add_metahuman_components_to_sequence(sequence, MH, sequ_path + sequ_name)
rigProxies = unreal.ControlRigSequencerLibrary.get_control_rigs(sequence)
# Filter rigs for specific names
rig = [rigProxy.control_rig for rigProxy in rigProxies if
rigProxy.control_rig.get_name() in ["Face_ControlBoard_CtrlRig"]][0]
pos = find_delta_z(rig,sequence)
print(f"delta z = {pos}")
|
# -*- coding: utf-8 -*-
import unreal
from Utilities.Utils import Singleton
class MinimalExample(metaclass=Singleton):
def __init__(self, jsonPath:str):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.ui_output = "InfoOutput"
self.clickCount = 0
def on_button_click(self):
self.clickCount += 1
self.data.set_text(self.ui_output, "Clicked {} time(s)".format(self.clickCount))
|
from abc import ABC
from dataclasses import dataclass
import unreal
@dataclass
class Message(ABC):
titleOfOptimisation: str = ""
descOfOptimisation: str = ""
summaryMessageIntro: str = ""
LogStringsArray = []
def build_log_summary(self, messages: list[str]) -> list[str]:
self.LogStringsArray.clear()
self.LogStringsArray.append("OPTIMISING SCRIPT \n")
self.LogStringsArray.append("==================================================================================================== \n")
self.LogStringsArray.append(" SCRIPT NAME: %s \n" % self.titleOfOptimisation)
self.LogStringsArray.append(" DESCRIPTION: %s \n" % self.descOfOptimisation)
self.LogStringsArray.append("==================================================================================================== \n \n")
unreal.log_warning(self.titleOfOptimisation)
unreal.log_warning(self.descOfOptimisation)
if len(messages) <= 0:
self.LogStringsArray.append(" -- NONE FOUND -- \n \n")
else:
for i in messages:
self.LogStringsArray.append(i)
self.LogStringsArray.append("\n")
self.LogStringsArray.append("======================================================================================================= \n")
self.LogStringsArray.append(" SUMMARY: \n")
self.LogStringsArray.append(" %s \n" % self.summaryMessageIntro)
self.LogStringsArray.append(" Found: %s \n \n" % len(messages))
self.LogStringsArray.append("======================================================================================================= \n")
return self.LogStringsArray
@dataclass
class ValidatePowerOfTowMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Textures That Are Not Power Of Two"
self.descOfOptimisation = "Searches the entire project for textures that are not a power of two e.g. 13x64, 100x96 etc. Instead of e.g. 32x32, 128x128 512x256"
self.summaryMessageIntro = "-- Textures Which Are Not A Power Of Two --"
@dataclass
class LogTexturesAboveXSizeMessage(Message):
sizeOfTexToCheckAgainst: str = ""
def __init__(self, _sizeOfTexToCheckAgainst):
super().__init__(self)
self.sizeOfTexToCheckAgainst = _sizeOfTexToCheckAgainst
self.titleOfOptimisation = "Log Textures That Are Equal To X Size"
self.descOfOptimisation = "Searches the entire project for Textures which are equal to the size you have set. Use to help find textures which are larger than what you need them for"
self.summaryMessageIntro = "-- Textures Of Size %s --" % self.sizeOfTexToCheckAgainst
@dataclass
class LogStaticMeshNumOfMaterialsMessage(Message):
numOfMatsToCheckFor: str = ""
def __init__(self, _numOfMatsToCheckFor):
super().__init__(self)
self.numOfMatsToCheckFor = _numOfMatsToCheckFor
self.titleOfOptimisation = "LOG Static Meshes Assets With X Num Of Materials"
self.descOfOptimisation = "Searches the entire project for static mesh assets that have a material count above the value that you have set"
self.summaryMessageIntro = "-- Static Mesh Assets With Material Count Numbering >= %s --" % self.numOfMatsToCheckFor
@dataclass
class LogStaticMeshUVchannelsMessage(Message):
numOfChannelsToCheckFor: str = ""
def __init__(self, _numOfChannelsToCheckFor):
super().__init__(self)
self.numOfChannelsToCheckFor = _numOfChannelsToCheckFor
self.titleOfOptimisation = "Log Static Mesh UV Channel Count For LOD 0"
self.descOfOptimisation = "Searches the entire project for static mesh assets that have a UV channel count above the value that you have set"
self.summaryMessageIntro = "-- Static Mesh Assets With UV Channels Numbering >= %s --" % self.numOfChannelsToCheckFor
@dataclass
class LogSkelMeshesNumOfMaterialsMessage(Message):
numOfMatsToCheckFor: str = ""
def __init__(self, _numOfMatsToCheckFor):
super().__init__(self)
self.numOfMatsToCheckFor = _numOfMatsToCheckFor
self.titleOfOptimisation = "LOG Skeletal Mesh Assets With X Num Of Materials"
self.descOfOptimisation = "Searches the entire project for skeletal mesh assets that have a material count above the value that you have set"
self.summaryMessageIntro = "-- Skeletal Mesh Assets With Material Count Numbering >= %s --" % self.numOfMatsToCheckFor
@dataclass
class LogMaterialsMissingPhysMatsMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Materials With Missing Physical Materials"
self.descOfOptimisation = "Searches the entire project for materials that don't have a phys mats plugged in"
self.summaryMessageIntro = "-- Materials Without Phys Mats Plugged In --"
@dataclass
class LogMaterialsUsingTranslucencyMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Materials Using Translucency"
self.descOfOptimisation = "Searches the entire project for materials that are using Translucency (master materials only, does not check material instances)"
self.summaryMessageIntro = "-- Materials Using Translucency --"
@dataclass
class OptimiseScriptLogMaterialsUsingTwoSidedMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Materials Using Two Sided"
self.descOfOptimisation = "Searches the entire project for materials that are using Two Sided (master materials only, does not check material instances)"
self.summaryMessageIntro = "-- Materials Using Two Sided --"
@dataclass
class LogFoliageWithNoMaxDrawDistanceMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Foliage Asset With No Max Draw Distance Set"
self.descOfOptimisation = "Searches the entire project for Foliage assets which have no max draw distance set"
self.summaryMessageIntro = "-- Foliage Asset With No Max Draw Distance Set --"
@dataclass
class ParticlesWithNoLODsMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Particles With No LODs"
self.descOfOptimisation = "Searches the entire project for particles that have no LODs setup"
self.summaryMessageIntro = "-- Particles With No LODs --"
@dataclass
class SoundCueMissingAttenuationMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Sound Cues With Missing Attenuation Assets"
self.descOfOptimisation = "Searches the entire project for Sound Cues that have no attenuation plugged in and also no Attenuation override set to true"
self.summaryMessageIntro = "-- Sound Cues With No Attenuation Settings --"
@dataclass
class SoundCueMissingConcurrencyMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Sound Cues With Missing Concurrency Settings"
self.descOfOptimisation = "Searches the entire project for Sound Cues that have no concurrency asset plugged in and also no concurrency override set to true"
self.summaryMessageIntro = "-- Sound Cues With No Concurrency Settings --"
@dataclass
class SoundCueMissingSoundClassMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Sound Cues With Missing Sound Class"
self.descOfOptimisation = "Searches the entire project for Sound Cues that are missing Sound Class Asset or are using the Engines Default Sound class asset"
self.summaryMessageIntro = "-- Sound Cues With Missing Sound Class --"
@dataclass
class LogDeleteEmptyFolderMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Delete Empty Folders"
self.descOfOptimisation = "Searches the entire project for empty folders, and log or delete the folder"
self.summaryMessageIntro = "-- Folders With no content inside, consider deleting --"
@dataclass
class LogUnusedAssetMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Unused Project Assets"
self.descOfOptimisation = "Searches the entire project for assets that have 0 references, that we could consider deleting"
self.summaryMessageIntro = "-- Assets With 0 References That We Could Consider Deleting --"
@dataclass
class LogRedirectsMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Redirects"
self.descOfOptimisation = "Searches entire project for redirects that need fixing up (only logs doesnt perform the fix-up)"
self.summaryMessageIntro = "-- Redirects That Could Be Fixed Up --"
@dataclass
class LogStaticMeshesNoLodMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log No LODs On Static Meshes"
self.descOfOptimisation = "Searches the entire project for static mesh assets that do not have any LODs setup"
self.summaryMessageIntro = "-- Static Mesh Assets Which Do Not Have any LODs Setup --"
@dataclass
class LogStaticMeshesWithNoCollisionMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log No Collision Static Meshes"
self.descOfOptimisation = "Searches the entire project for static mesh assets that do not have any collision setup"
self.summaryMessageIntro = "-- Static Mesh Assets Which Do Not Have Collision --"
@dataclass
class LogSkelMeshesNoLodMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log No LODs On Skeletal Meshes"
self.descOfOptimisation = "Searches the entire project for skeletal mesh assets that do not have any LODs setup"
self.summaryMessageIntro = "-- Skeletal Mesh Assets Which Do Not Have any LODs Setup --"
@dataclass
class ImportedFilesMessage(Message):
def __init__(self):
super().__init__(self)
self.titleOfOptimisation = "Log Imported Files in folder"
self.descOfOptimisation = "Searches the folder for files that match the types to import"
self.summaryMessageIntro = "-- Imported Files --"
|
# coding: utf-8
import unreal
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
parser.add_argument("-debugeachsave")
args = parser.parse_args()
#print(args.vrm)
######
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig)
h_con = hierarchy.get_controller()
print(unreal.SystemLibrary.get_engine_version())
if (unreal.SystemLibrary.get_engine_version()[0] == '5'):
c = rig.get_controller()
else:
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
mesh = rig.get_preview_mesh()
morphList = mesh.get_all_morph_target_names()
morphListWithNo = morphList[:]
morphListRenamed = []
morphListRenamed.clear()
for i in range(len(morphList)):
morphListWithNo[i] = '{}'.format(morphList[i])
print(morphListWithNo)
while(len(hierarchy.get_bones()) > 0):
e = hierarchy.get_bones()[-1]
h_con.remove_all_parents(e)
h_con.remove_element(e)
h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton)
h_con.import_curves(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton)
dset = rig.get_editor_property('rig_graph_display_settings')
dset.set_editor_property('node_run_limit', 0)
rig.set_editor_property('rig_graph_display_settings', dset)
###### root
key = unreal.RigElementKey(unreal.RigElementType.NULL, 'MorphControlRoot_s')
space = hierarchy.find_null(key)
if (space.get_editor_property('index') < 0):
space = h_con.add_null('MorphControlRoot_s', space_type=unreal.RigSpaceType.SPACE)
else:
space = key
a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems()
print(a)
# 配列ノード追加
values_forCurve:unreal.RigVMStructNode = []
items_forControl:unreal.RigVMStructNode = []
items_forCurve:unreal.RigVMStructNode = []
for node in n:
print(node)
print(node.get_node_title())
# set curve num
if (node.get_node_title() == 'For Loop'):
print(node)
pin = node.find_pin('Count')
print(pin)
c.set_pin_default_value(pin.get_pin_path(), str(len(morphList)), True, False)
# curve name array pin
if (node.get_node_title() == 'Select'):
print(node)
pin = node.find_pin('Values')
print(pin)
print(pin.get_array_size())
print(pin.get_default_value())
values_forCurve.append(pin)
# items
if (node.get_node_title() == 'Collection from Items'):
if ("Type=Curve," in c.get_pin_default_value(node.find_pin('Items').get_pin_path())):
items_forCurve.append(node.find_pin('Items'))
if (str(c.get_pin_default_value(node.find_pin('Items').get_pin_path())).find('_ALL_Angry_c') >= 0):
items_forControl.append(node.find_pin('Items'))
print(items_forControl)
print(values_forCurve)
# reset controller
for e in reversed(hierarchy.get_controls()):
if (len(hierarchy.get_parents(e)) == 0):
continue
if (hierarchy.get_parents(e)[0].name == 'MorphControlRoot_s'):
#if (str(e.name).rstrip('_c') in morphList):
# continue
print('delete')
#print(str(e.name))
h_con.remove_element(e)
# curve array
for v in values_forCurve:
c.clear_array_pin(v.get_pin_path())
for morph in morphList:
tmp = "{}".format(morph)
c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False)
# curve controller
for morph in morphListWithNo:
name_c = "{}_c".format(morph)
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c)
settings = unreal.RigControlSettings()
settings.shape_color = [1.0, 0.0, 0.0, 1.0]
settings.control_type = unreal.RigControlType.FLOAT
try:
control = hierarchy.find_control(key)
if (control.get_editor_property('index') < 0):
k = h_con.add_control(name_c, space, settings, unreal.RigControlValue())
control = hierarchy.find_control(k)
except:
k = h_con.add_control(name_c, space, settings, unreal.RigControlValue())
control = hierarchy.find_control(k)
shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001])
hierarchy.set_control_shape_transform(k, shape_t, True)
morphListRenamed.append(control.key.name)
if (args.debugeachsave == '1'):
try:
unreal.EditorAssetLibrary.save_loaded_asset(rig)
except:
print('save error')
#unreal.SystemLibrary.collect_garbage()
# eye controller
eyeControllerTable = [
"VRM4U_EyeUD_left",
"VRM4U_EyeLR_left",
"VRM4U_EyeUD_right",
"VRM4U_EyeLR_right",
]
# eye controller
for eyeCon in eyeControllerTable:
name_c = "{}_c".format(eyeCon)
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c)
settings = unreal.RigControlSettings()
settings.shape_color = [1.0, 0.0, 0.0, 1.0]
settings.control_type = unreal.RigControlType.FLOAT
try:
control = hierarchy.find_control(key)
if (control.get_editor_property('index') < 0):
k = h_con.add_control(name_c, space, settings, unreal.RigControlValue())
control = hierarchy.find_control(k)
except:
k = h_con.add_control(name_c, space, settings, unreal.RigControlValue())
control = hierarchy.find_control(k)
shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001])
hierarchy.set_control_shape_transform(k, shape_t, True)
# curve Control array
for v in items_forControl:
c.clear_array_pin(v.get_pin_path())
for morph in morphListRenamed:
tmp = '(Type=Control,Name='
tmp += "{}".format(morph)
tmp += ')'
c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False)
# curve Float array
for v in items_forCurve:
c.clear_array_pin(v.get_pin_path())
for morph in morphList:
tmp = '(Type=Curve,Name='
tmp += "{}".format(morph)
tmp += ')'
c.add_array_pin(v.get_pin_path(), default_value=tmp, setup_undo_redo=False)
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
from . import base_server
from .base_server import BaseRPCServerThread, BaseRPCServerManager
class UnrealRPCServerThread(BaseRPCServerThread):
def thread_safe_call(self, callable_instance, *args):
"""
Implementation of a thread safe call in Unreal.
"""
return lambda *args: base_server.run_in_main_thread(callable_instance, *args)
class RPCServer(BaseRPCServerManager):
def __init__(self):
"""
Initialize the unreal rpc server, with its name and specific port.
"""
super(RPCServer, self).__init__()
self.name = 'UnrealRPCServer'
self.port = int(os.environ.get('RPC_PORT', 9998))
self.threaded_server_class = UnrealRPCServerThread
def start_server_thread(self):
"""
Starts the server thread.
"""
# TODO use a timer exposed from FTSTicker instead of slate tick, less aggressive and safer
# https://docs.unrealengine.com/4.27/en-US/project/.html?highlight=automationscheduler#unreal.AutomationScheduler
import unreal
unreal.register_slate_post_tick_callback(base_server.execute_queued_calls)
super(RPCServer, self).start_server_thread()
|
from typing import Dict, Any, Optional
import unreal
import json
def update_object(
actor_name: str,
location: Optional[Dict[str, float]] = None,
rotation: Optional[Dict[str, float]] = None,
scale: Optional[Dict[str, float]] = None,
properties: Optional[Dict[str, Any]] = None,
new_name: Optional[str] = None,
) -> Dict[str, Any]:
try:
world = unreal.get_editor_subsystem(
unreal.UnrealEditorSubsystem
).get_editor_world()
if not world:
return {"error": "No world loaded"}
all_actors = unreal.get_editor_subsystem(
unreal.EditorActorSubsystem
).get_all_level_actors()
target_actor = None
for actor in all_actors:
if actor.get_name() == actor_name or actor.get_actor_label() == actor_name:
target_actor = actor
break
if not target_actor:
return {"error": f"Actor not found: {actor_name}"}
if location:
new_location = unreal.Vector(
x=location.get("x", target_actor.get_actor_location().x),
y=location.get("y", target_actor.get_actor_location().y),
z=location.get("z", target_actor.get_actor_location().z),
)
target_actor.set_actor_location(new_location, False, False)
if rotation:
new_rotation = unreal.Rotator(
pitch=rotation.get("pitch", target_actor.get_actor_rotation().pitch),
yaw=rotation.get("yaw", target_actor.get_actor_rotation().yaw),
roll=rotation.get("roll", target_actor.get_actor_rotation().roll),
)
target_actor.set_actor_rotation(new_rotation, False)
if scale:
new_scale = unreal.Vector(
x=scale.get("x", target_actor.get_actor_scale3d().x),
y=scale.get("y", target_actor.get_actor_scale3d().y),
z=scale.get("z", target_actor.get_actor_scale3d().z),
)
target_actor.set_actor_scale3d(new_scale)
if new_name:
target_actor.set_actor_label(new_name)
if properties:
for prop_name, prop_value in properties.items():
try:
if hasattr(target_actor, prop_name):
setattr(target_actor, prop_name, prop_value)
except Exception as e:
continue
return {
"success": True,
"actor_name": target_actor.get_name(),
"actor_label": target_actor.get_actor_label(),
"class": target_actor.get_class().get_name(),
"location": {
"x": target_actor.get_actor_location().x,
"y": target_actor.get_actor_location().y,
"z": target_actor.get_actor_location().z,
},
"rotation": {
"pitch": target_actor.get_actor_rotation().pitch,
"yaw": target_actor.get_actor_rotation().yaw,
"roll": target_actor.get_actor_rotation().roll,
},
"scale": {
"x": target_actor.get_actor_scale3d().x,
"y": target_actor.get_actor_scale3d().y,
"z": target_actor.get_actor_scale3d().z,
},
}
except Exception as e:
return {"error": f"Failed to update object: {str(e)}"}
def parse_value(value_str):
import json as parse_json
if value_str and value_str != "null" and value_str.strip():
try:
return parse_json.loads(value_str)
except Exception:
return None
return None
def parse_string(value_str):
if value_str and value_str != "null" and value_str.strip():
return value_str
return None
def main():
actor_name = "${actor_name}"
location_str = """${location}"""
rotation_str = """${rotation}"""
scale_str = """${scale}"""
properties_str = """${properties}"""
new_name_str = """${new_name}"""
location = parse_value(location_str)
rotation = parse_value(rotation_str)
scale = parse_value(scale_str)
properties = parse_value(properties_str)
new_name = parse_string(new_name_str)
result = update_object(
actor_name=actor_name,
location=location,
rotation=rotation,
scale=scale,
properties=properties,
new_name=new_name,
)
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
|
import unreal
# エディタから直接呼び出せるようにするためのクラス定義
@unreal.uclass()
class AssetMoverUtility(unreal.GlobalEditorUtilityBase):
# 静的関数として、複数アセットを Imports フォルダへ移動
@unreal.ufunction(static=True)
def move_selected_assets_to_imports():
selected_assets = unreal.EditorUtilityLibrary.get_selected_assets()
if not selected_assets:
unreal.log_warning("[AutoAssetMover] No assets selected.")
return
for asset in selected_assets:
asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(asset)
asset_name = asset.get_name()
dst_path = f"/project/{asset_name}"
if unreal.EditorAssetLibrary.does_asset_exist(dst_path):
unreal.log_warning(f"[AutoAssetMover] Already exists: {dst_path}")
continue
success = unreal.EditorAssetLibrary.rename_asset(asset_path, dst_path)
if success:
unreal.log(f"[AutoAssetMover] Moved to: {dst_path}")
else:
unreal.log_error(f"[AutoAssetMover] Failed to move: {asset_path}")
# 🔽 これが大事!
# 名前付きでクラスをグローバルに公開することで、Blueprint からも呼び出せる
globals()["AssetMoverUtility"] = AssetMoverUtility
|
import unreal
from pamux_unreal_tools.utils.interface_types import *
from pamux_unreal_tools.utils.types import *
# Idea: these interfaces declaration can be used both to construct "Inputs" class and call the function from other Materials/MaterialFunctions
@material_function_interface("{asset_path_root}/project/")
def ILandscapeBaseMaterial(
albedo: TTextureObject = TTextureObject(),
colorOverlay: Vec3f = Vec3f(1.0, 1.0, 1.0),
colorOverlayIntensity: float = 1.0,
contrast: float = 0.0,
contrastVariation: float = 1.0,
roughness: TTextureObject = TTextureObject(),
roughnessIntensity: float = 1.0,
normal: TTextureObject = TTextureObject(unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL),
normalIntensity: float = 0.0,
displacement: TTextureObject = TTextureObject(),
uvParams: Vec4f = Vec4f(1.0, 1.0, 0.5, 0.5),
rotation: float = 0.0,
doTextureBomb: bool = True,
doRotationVariation: bool = False,
bombCellScale: float = 1.0,
bombPatternScale: float = 1.0,
bombRandomOffset: float = 0.0,
bombRotationVariation: float = 0.0,
opacityStrength: float = 1.0,
opacityAdd: float = 0.0,
opacityContrast: float = 1.0) -> tuple[TResult, THeight]:
pass
|
import unreal
from pamux_unreal_tools.generated.material_expression_wrappers import *
from pamux_unreal_tools.utils.asset_cache import AssetCache
class TMaterialTextures:
def __init__(self, baseColor = None, roughness = None, opacity = None, normal = None, displacement = None):
self.baseColor = baseColor
self.roughness = roughness
self.opacity = opacity
self.normal = normal
self.displacement = displacement
class TextureSampleSet:
def __init__(self, tss: TMaterialTextures):
self.baseColor = TextureSample()
self.baseColor.sampler_source.set(unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
self.baseColor.sampler_type.set(unreal.MaterialSamplerType.SAMPLERTYPE_COLOR)
self.baseColor.texture.set(AssetCache.get(tss.baseColor))
self.roughness = TextureSample()
self.roughness.sampler_source.set(unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
self.roughness.sampler_type.set(unreal.MaterialSamplerType.SAMPLERTYPE_COLOR)
self.roughness.texture.set(AssetCache.get(tss.roughness))
self.opacity = TextureSample()
self.opacity.sampler_source.set(unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
self.opacity.sampler_type.set(unreal.MaterialSamplerType.SAMPLERTYPE_LINEAR_COLOR)
self.opacity.texture.set(AssetCache.get(tss.opacity))
self.normal = TextureSample()
self.normal.sampler_source.set(unreal.SamplerSourceMode.SSM_WRAP_WORLD_GROUP_SETTINGS)
self.normal.sampler_type.set(unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL)
self.normal.texture.set(AssetCache.get(tss.normal))
|
# This script was generated with the addons Blender for UnrealEngine : https://github.com/project/-For-UnrealEngine-Addons
# It will import into Unreal Engine all the assets of type StaticMesh, SkeletalMesh, Animation and Pose
# The script must be used in Unreal Engine Editor with Python plugins : https://docs.unrealengine.com/en-US/project/
# Use this command in Unreal cmd consol: py "[ScriptLocation]\ImportSequencerScript.py"
from unittest import result
import sys
import os.path
import json
try: # TO DO: Found a better way to check that.
import unreal
except ImportError:
import unreal_engine as unreal
def CheckTasks():
if GetUnrealVersion() >= 4.20: # TO DO: EditorAssetLibrary was added in witch version exactly?
if not hasattr(unreal, 'EditorAssetLibrary'):
print('--------------------------------------------------')
print('WARNING: Editor Scripting Utilities should be activated.')
print('Edit > Plugin > Scripting > Editor Scripting Utilities.')
return False
return True
def JsonLoad(json_file):
# Changed in Python 3.9: The keyword argument encoding has been removed.
if sys.version_info >= (3, 9):
return json.load(json_file)
else:
return json.load(json_file, encoding="utf8")
def JsonLoadFile(json_file_path):
if sys.version_info[0] < 3:
with open(json_file_path, "r") as json_file:
return JsonLoad(json_file)
else:
with open(json_file_path, "r", encoding="utf8") as json_file:
return JsonLoad(json_file)
def GetUnrealVersion():
version = unreal.SystemLibrary.get_engine_version().split(".")
float_version = int(version[0]) + float(float(version[1])/100)
return float_version
def ImportAllAssets():
import string
# Prepare process import
json_data_file = 'ImportAssetData.json'
dir_path = os.path.dirname(os.path.realpath(__file__))
import_assets_data = JsonLoadFile(os.path.join(dir_path, json_data_file))
unreal_import_location = import_assets_data['unreal_import_location']
ImportedList = []
ImportFailList = []
def ValidUnrealAssetsName(filename):
# Normalizes string, removes non-alpha characters
# Asset name in Unreal use
filename = filename.replace('.', '_')
filename = filename.replace('(', '_')
filename = filename.replace(')', '_')
filename = filename.replace(' ', '_')
valid_chars = "-_%s%s" % (string.ascii_letters, string.digits)
filename = ''.join(c for c in filename if c in valid_chars)
return filename
def GetAssetByType(type):
target_assets = []
for asset in import_assets_data["assets"]:
if asset["type"] == type:
target_assets.append(asset)
return target_assets
def ImportAsset(asset_data):
counter = str(len(ImportedList)+1) + "/" + str(len(import_assets_data["assets"]))
print("Import asset " + counter + ": ", asset_data["name"])
if asset_data["type"] == "StaticMesh" or asset_data["type"] == "SkeletalMesh":
if "lod" in asset_data:
if asset_data["lod"] > 0: # Lod should not be imported here so return if lod is not 0.
return
if asset_data["type"] == "Alembic":
FileType = "ABC"
else:
FileType = "FBX"
asset_data["full_import_path"] # AssetImportPath
asset_data["fbx_path"] # fbx_file_path
asset_data["additional_tracks_path"] # additional_track_file_path
def GetAdditionalData():
if "additional_tracks_path" in asset_data:
if asset_data["additional_tracks_path"] is not None:
return JsonLoadFile(asset_data["additional_tracks_path"])
return None
additional_data = GetAdditionalData()
def ImportTask():
# New import task
# Property
if asset_data["type"] == "Animation" or asset_data["type"] == "SkeletalMesh":
find_asset = unreal.find_asset(asset_data["animation_skeleton_path"])
if isinstance(find_asset, unreal.Skeleton):
OriginSkeleton = find_asset
elif isinstance(find_asset, unreal.SkeletalMesh):
OriginSkeleton = find_asset.skeleton
else:
OriginSkeleton = None
if OriginSkeleton:
print("Setting skeleton asset: " + OriginSkeleton.get_full_name())
else:
print("Could not find skeleton at the path: " + asset_data["animation_skeleton_path"])
# docs.unrealengine.com/4.26/en-US/project/.html
task = unreal.AssetImportTask()
def GetStaticMeshImportData():
if asset_data["type"] == "StaticMesh":
return task.get_editor_property('options').static_mesh_import_data
return None
def GetSkeletalMeshImportData():
if asset_data["type"] == "SkeletalMesh":
return task.get_editor_property('options').skeletal_mesh_import_data
return None
def GetAnimationImportData():
if asset_data["type"] == "Animation":
return task.get_editor_property('options').anim_sequence_import_data
return None
def GetAlembicImportData():
if asset_data["type"] == "Alembic":
return task.get_editor_property('options')
return None
def GetMeshImportData():
if asset_data["type"] == "StaticMesh":
return GetStaticMeshImportData()
if asset_data["type"] == "SkeletalMesh":
return GetSkeletalMeshImportData()
return None
if asset_data["type"] == "Alembic":
task.filename = asset_data["abc_path"]
else:
task.filename = asset_data["fbx_path"]
task.destination_path = os.path.normpath(asset_data["full_import_path"]).replace('\\', '/')
task.automated = True
# task.automated = False #Debug for show dialog
task.save = True
task.replace_existing = True
if asset_data["type"] == "Alembic":
task.set_editor_property('options', unreal.AbcImportSettings())
else:
task.set_editor_property('options', unreal.FbxImportUI())
# Alembic
if GetAlembicImportData():
GetAlembicImportData().static_mesh_settings.set_editor_property("merge_meshes", True)
GetAlembicImportData().set_editor_property("import_type", unreal.AlembicImportType.SKELETAL)
GetAlembicImportData().conversion_settings.set_editor_property("flip_u", False)
GetAlembicImportData().conversion_settings.set_editor_property("flip_v", True)
GetAlembicImportData().conversion_settings.set_editor_property("scale", unreal.Vector(100, -100, 100))
GetAlembicImportData().conversion_settings.set_editor_property("rotation", unreal.Vector(90, 0, 0))
# Vertex color
vertex_override_color = None
vertex_color_import_option = None
if additional_data:
vertex_color_import_option = unreal.VertexColorImportOption.REPLACE # Default
if "vertex_color_import_option" in additional_data:
if additional_data["vertex_color_import_option"] == "IGNORE":
vertex_color_import_option = unreal.VertexColorImportOption.IGNORE
elif additional_data["vertex_color_import_option"] == "OVERRIDE":
vertex_color_import_option = unreal.VertexColorImportOption.OVERRIDE
elif additional_data["vertex_color_import_option"] == "REPLACE":
vertex_color_import_option = unreal.VertexColorImportOption.REPLACE
if "vertex_override_color" in additional_data:
vertex_override_color = unreal.LinearColor(
additional_data["vertex_override_color"][0],
additional_data["vertex_override_color"][1],
additional_data["vertex_override_color"][2]
)
# #################################[Change]
# unreal.FbxImportUI
# https://docs.unrealengine.com/4.26/en-US/project/.html
# Import transform
anim_sequence_import_data = GetAnimationImportData()
if anim_sequence_import_data:
anim_sequence_import_data.import_translation = unreal.Vector(0, 0, 0)
# Vertex color
if vertex_color_import_option and GetMeshImportData():
GetMeshImportData().set_editor_property('vertex_color_import_option', vertex_color_import_option)
if vertex_override_color and GetMeshImportData():
GetMeshImportData().set_editor_property('vertex_override_color', vertex_override_color.to_rgbe())
if asset_data["type"] == "Alembic":
task.get_editor_property('options').set_editor_property('import_type', unreal.AlembicImportType.SKELETAL)
else:
if asset_data["type"] == "Animation" or asset_data["type"] == "SkeletalMesh":
if OriginSkeleton:
task.get_editor_property('options').set_editor_property('Skeleton', OriginSkeleton)
else:
if asset_data["type"] == "Animation":
ImportFailList.append('Skeleton ' + asset_data["animation_skeleton_path"] + ' Not found for ' + asset_data["name"] + ' asset.')
return
else:
print("Skeleton is not set, a new skeleton asset will be created...")
if asset_data["type"] == "StaticMesh":
task.get_editor_property('options').set_editor_property('original_import_type', unreal.FBXImportType.FBXIT_STATIC_MESH)
elif asset_data["type"] == "Animation":
task.get_editor_property('options').set_editor_property('original_import_type', unreal.FBXImportType.FBXIT_ANIMATION)
else:
task.get_editor_property('options').set_editor_property('original_import_type', unreal.FBXImportType.FBXIT_SKELETAL_MESH)
if asset_data["type"] == "Animation":
task.get_editor_property('options').set_editor_property('import_materials', False)
else:
task.get_editor_property('options').set_editor_property('import_materials', True)
task.get_editor_property('options').set_editor_property('import_textures', False)
if asset_data["type"] == "Animation":
task.get_editor_property('options').set_editor_property('import_animations', True)
task.get_editor_property('options').set_editor_property('import_mesh', False)
task.get_editor_property('options').set_editor_property('create_physics_asset',False)
else:
task.get_editor_property('options').set_editor_property('import_animations', False)
task.get_editor_property('options').set_editor_property('import_mesh', True)
if "create_physics_asset" in asset_data:
task.get_editor_property('options').set_editor_property('create_physics_asset', asset_data["create_physics_asset"])
# unreal.FbxMeshImportData
if asset_data["type"] == "StaticMesh" or asset_data["type"] == "SkeletalMesh":
if "material_search_location" in asset_data:
# unreal.FbxTextureImportData
if asset_data["material_search_location"] == "Local":
task.get_editor_property('options').texture_import_data.set_editor_property('material_search_location', unreal.MaterialSearchLocation.LOCAL)
if asset_data["material_search_location"] == "UnderParent":
task.get_editor_property('options').texture_import_data.set_editor_property('material_search_location', unreal.MaterialSearchLocation.UNDER_PARENT)
if asset_data["material_search_location"] == "UnderRoot":
task.get_editor_property('options').texture_import_data.set_editor_property('material_search_location', unreal.MaterialSearchLocation.UNDER_ROOT)
if asset_data["material_search_location"] == "AllAssets":
task.get_editor_property('options').texture_import_data.set_editor_property('material_search_location', unreal.MaterialSearchLocation.ALL_ASSETS)
if asset_data["type"] == "StaticMesh":
# unreal.FbxStaticMeshImportData
task.get_editor_property('options').static_mesh_import_data.set_editor_property('combine_meshes', True)
if "auto_generate_collision" in asset_data:
task.get_editor_property('options').static_mesh_import_data.set_editor_property('auto_generate_collision', asset_data["auto_generate_collision"])
if "static_mesh_lod_group" in asset_data:
if asset_data["static_mesh_lod_group"]:
task.get_editor_property('options').static_mesh_import_data.set_editor_property('static_mesh_lod_group', asset_data["static_mesh_lod_group"])
if "generate_lightmap_u_vs" in asset_data:
task.get_editor_property('options').static_mesh_import_data.set_editor_property('generate_lightmap_u_vs', asset_data["generate_lightmap_u_vs"])
if asset_data["type"] == "SkeletalMesh" or asset_data["type"] == "Animation":
# unreal.FbxSkeletalMeshImportData
task.get_editor_property('options').skeletal_mesh_import_data.set_editor_property('import_morph_targets', True)
task.get_editor_property('options').skeletal_mesh_import_data.set_editor_property('convert_scene', True)
task.get_editor_property('options').skeletal_mesh_import_data.set_editor_property('normal_import_method', unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS_AND_TANGENTS)
# ###############[ pre import ]################
# Check is the file alredy exit
if additional_data:
if "preview_import_path" in additional_data:
task_asset_full_path = task.destination_path+"/"+additional_data["preview_import_path"]+"."+additional_data["preview_import_path"]
find_asset = unreal.find_asset(task_asset_full_path)
if find_asset:
# Vertex color
asset_import_data = find_asset.get_editor_property('asset_import_data')
if vertex_color_import_option:
asset_import_data.set_editor_property('vertex_color_import_option', vertex_color_import_option)
if vertex_override_color:
asset_import_data.set_editor_property('vertex_override_color', vertex_override_color.to_rgbe())
# ###############[ import asset ]################
print("Import task")
if asset_data["type"] == "Animation":
'''
For animation the script will import a skeletal mesh and remove after.
If the skeletal mesh alredy exist try to remove.
'''
AssetName = asset_data["name"]
AssetName = ValidUnrealAssetsName(AssetName)
AssetPath = "SkeletalMesh'"+asset_data["full_import_path"]+"/"+AssetName+"."+AssetName+"'"
if unreal.EditorAssetLibrary.does_asset_exist(AssetPath):
oldAsset = unreal.EditorAssetLibrary.find_asset_data(AssetPath)
if oldAsset.asset_class == "SkeletalMesh":
unreal.EditorAssetLibrary.delete_asset(AssetPath)
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task])
if len(task.imported_object_paths) > 0:
asset = unreal.find_asset(task.imported_object_paths[0])
else:
asset = None
if asset is None:
ImportFailList.append('Error zero imported object for: ' + asset_data["name"])
return
if asset_data["type"] == "Animation":
# For animation remove the extra mesh
p = task.imported_object_paths[0]
if type(unreal.find_asset(p)) is not unreal.AnimSequence:
animAssetName = p.split('.')[0]+'_anim.'+p.split('.')[1]+'_anim'
animAssetNameDesiredPath = p.split('.')[0]+'.'+p.split('.')[1]
animAsset = unreal.find_asset(animAssetName)
if animAsset is not None:
unreal.EditorAssetLibrary.delete_asset(p)
unreal.EditorAssetLibrary.rename_asset(animAssetName, animAssetNameDesiredPath)
asset = animAsset
else:
ImportFailList.append('animAsset ' + asset_data["name"] + ' not found for after inport: ' + animAssetName)
return
# ###############[ Post treatment ]################
asset_import_data = asset.get_editor_property('asset_import_data')
if asset_data["type"] == "StaticMesh":
if "static_mesh_lod_group" in asset_data:
if asset_data["static_mesh_lod_group"]:
asset.set_editor_property('lod_group', asset_data["static_mesh_lod_group"])
if "use_custom_light_map_resolution" in asset_data:
if asset_data["use_custom_light_map_resolution"]:
if "light_map_resolution" in asset_data:
asset.set_editor_property('light_map_resolution', asset_data["light_map_resolution"])
if "collision_trace_flag" in asset_data:
if asset_data["collision_trace_flag"] == "CTF_UseDefault":
asset.get_editor_property('body_setup').set_editor_property('collision_trace_flag', unreal.CollisionTraceFlag.CTF_USE_DEFAULT)
elif asset_data["collision_trace_flag"] == "CTF_UseSimpleAndComplex":
asset.get_editor_property('body_setup').set_editor_property('collision_trace_flag', unreal.CollisionTraceFlag.CTF_USE_SIMPLE_AND_COMPLEX)
elif asset_data["collision_trace_flag"] == "CTF_UseSimpleAsComplex":
asset.get_editor_property('body_setup').set_editor_property('collision_trace_flag', unreal.CollisionTraceFlag.CTF_USE_SIMPLE_AS_COMPLEX)
elif asset_data["collision_trace_flag"] == "CTF_UseComplexAsSimple":
asset.get_editor_property('body_setup').set_editor_property('collision_trace_flag', unreal.CollisionTraceFlag.CTF_USE_COMPLEX_AS_SIMPLE)
if asset_data["type"] == "StaticMesh":
if "generate_lightmap_u_vs" in asset_data:
asset_import_data.set_editor_property('generate_lightmap_u_vs', asset_data["generate_lightmap_u_vs"]) # Import data
unreal.EditorStaticMeshLibrary.set_generate_lightmap_uv(asset, asset_data["generate_lightmap_u_vs"]) # Build settings at lod
if asset_data["type"] == "SkeletalMesh":
asset_import_data.set_editor_property('normal_import_method', unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS_AND_TANGENTS)
# Socket
if asset_data["type"] == "SkeletalMesh":
# Import the SkeletalMesh socket(s)
sockets_to_add = additional_data["Sockets"]
skeleton = asset.get_editor_property('skeleton')
for socket in sockets_to_add:
old_socket = asset.find_socket(socket["SocketName"])
if old_socket:
# Edit socket
pass
# old_socket.relative_location = socket["Location"]
# old_socket.relative_rotation = socket["Rotation"]
# old_socket.relative_scale = socket["Scale"]
else:
# Create socket
pass
# new_socket = unreal.SkeletalMeshSocket(asset)
# new_socket.socket_name = socket["SocketName"]
# new_socket.bone_name = socket["BoneName"]
# new_socket.relative_location = socket["Location"]
# new_socket.relative_rotation = socket["Rotation"]
# new_socket.relative_scale = socket["Scale"]
# NEED UNREAL ENGINE IMPLEMENTATION IN PYTHON API.
# skeleton.add_socket(new_socket)
# Lod
if asset_data["type"] == "StaticMesh" or asset_data["type"] == "SkeletalMesh":
if asset_data["type"] == "StaticMesh":
unreal.EditorStaticMeshLibrary.remove_lods(asset) # Import the StaticMesh lod(s)
if asset_data["type"] == "SkeletalMesh" or asset_data["type"] == "StaticMesh":
def ImportStaticLod(lod_name, lod_number):
if "LevelOfDetail" in additional_data:
if lod_name in additional_data["LevelOfDetail"]:
lodTask = unreal.AssetImportTask()
lodTask.filename = additional_data["LevelOfDetail"][lod_name]
destination_path = os.path.normpath(asset_data["full_import_path"]).replace('\\', '/')
lodTask.destination_path = destination_path
lodTask.automated = True
lodTask.replace_existing = True
# Set vertex color import settings to replicate base StaticMesh's behaviour
if asset_data["type"] == "Alembic":
lodTask.set_editor_property('options', unreal.AbcImportSettings())
else:
lodTask.set_editor_property('options', unreal.FbxImportUI())
lodTask.get_editor_property('options').static_mesh_import_data.set_editor_property('vertex_color_import_option', vertex_color_import_option)
lodTask.get_editor_property('options').static_mesh_import_data.set_editor_property('vertex_override_color', vertex_override_color.to_rgbe())
print(destination_path, additional_data["LevelOfDetail"][lod_name])
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks([lodTask])
if len(lodTask.imported_object_paths) > 0:
lodAsset = unreal.find_asset(lodTask.imported_object_paths[0])
slot_replaced = unreal.EditorStaticMeshLibrary.set_lod_from_static_mesh(asset, lod_number, lodAsset, 0, True)
unreal.EditorAssetLibrary.delete_asset(lodTask.imported_object_paths[0])
def ImportSkeletalLod(lod_name, lod_number):
if "LevelOfDetail" in additional_data:
if lod_name in additional_data["LevelOfDetail"]:
# Unreal python no longer support Skeletal mesh LODS import.
pass
if asset_data["type"] == "StaticMesh":
ImportStaticLod("lod_1", 1)
ImportStaticLod("lod_2", 2)
ImportStaticLod("lod_3", 3)
ImportStaticLod("lod_4", 4)
ImportStaticLod("lod_5", 5)
elif asset_data["type"] == "SkeletalMesh":
ImportSkeletalLod("lod_1", 1)
ImportSkeletalLod("lod_2", 2)
ImportSkeletalLod("lod_3", 3)
ImportSkeletalLod("lod_4", 4)
ImportSkeletalLod("lod_5", 5)
# Vertex color
if vertex_override_color:
asset_import_data.set_editor_property('vertex_override_color', vertex_override_color.to_rgbe())
if vertex_color_import_option:
asset_import_data.set_editor_property('vertex_color_import_option', vertex_color_import_option)
# #################################[EndChange]
if asset_data["type"] == "StaticMesh" or asset_data["type"] == "SkeletalMesh":
unreal.EditorAssetLibrary.save_loaded_asset(asset)
ImportedList.append([asset, asset_data["type"]])
ImportTask()
# Process import
print('========================= Import started ! =========================')
print(import_assets_data["assets"])
# Import assets with a specific order
for asset in GetAssetByType("Alembic"):
ImportAsset(asset)
for asset in GetAssetByType("StaticMesh"):
ImportAsset(asset)
for asset in GetAssetByType("SkeletalMesh"):
ImportAsset(asset)
for asset in GetAssetByType("Animation"):
ImportAsset(asset)
print('========================= Full import completed ! =========================')
# import result
StaticMesh_ImportedList = []
SkeletalMesh_ImportedList = []
Alembic_ImportedList = []
Animation_ImportedList = []
for asset in ImportedList:
if asset[1] == 'StaticMesh':
StaticMesh_ImportedList.append(asset[0])
elif asset[1] == 'SkeletalMesh':
SkeletalMesh_ImportedList.append(asset[0])
elif asset[1] == 'Alembic':
Alembic_ImportedList.append(asset[0])
else:
Animation_ImportedList.append(asset[0])
print('Imported StaticMesh: '+str(len(StaticMesh_ImportedList)))
print('Imported SkeletalMesh: '+str(len(SkeletalMesh_ImportedList)))
print('Imported Alembic: '+str(len(Alembic_ImportedList)))
print('Imported Animation: '+str(len(Animation_ImportedList)))
print('Import failled: '+str(len(ImportFailList)))
for error in ImportFailList:
print(error)
# Select asset(s) in content browser
PathList = []
for asset in (StaticMesh_ImportedList + SkeletalMesh_ImportedList + Alembic_ImportedList + Animation_ImportedList):
PathList.append(asset.get_path_name())
unreal.EditorAssetLibrary.sync_browser_to_objects(PathList)
print('=========================')
if len(ImportFailList) > 0:
return 'Some asset(s) could not be imported.'
else:
return 'Assets imported with success !'
print("Start importing assets.")
if CheckTasks():
print(ImportAllAssets())
print("Importing assets finished.")
|
#
# Copyright(c) 2025 The SPEAR Development Team. Licensed under the MIT License <http://opensource.org/project/>.
# Copyright(c) 2022 Intel. Licensed under the MIT License <http://opensource.org/project/>.
#
import argparse
import pandas as pd
import posixpath
import spear
import spear.utils.editor_utils
import unreal
parser = argparse.ArgumentParser()
parser.add_argument("--maps_file", required=True)
parser.add_argument("--script")
args, unknown_args = parser.parse_known_args() # get unknown args to pass to inner script
level_editor_subsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem)
unreal_editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
if __name__ == "__main__":
unknown_arg_string = ""
if len(unknown_args) > 0:
unknown_arg_string = " ".join(unknown_args)
maps = pd.read_csv(args.maps_file)["maps"].tolist()
for m in maps:
spear.log("Loading map: ", m)
level_editor_subsystem.load_level(m)
editor_world_name = unreal_editor_subsystem.get_editor_world().get_name()
assert editor_world_name == posixpath.basename(m)
actors = spear.utils.editor_utils.find_actors()
spear.log(f"Loaded map: {editor_world_name} (contains {len(actors)} actors)")
if args.script is not None:
cmd = f"py {args.script} {unknown_arg_string}".strip()
spear.log("Executing command: ", cmd)
unreal.SystemLibrary.execute_console_command(unreal_editor_subsystem.get_editor_world(), cmd)
spear.log("Done.")
|
import logging
import unreal
class UnrealLogHandler(logging.Handler):
def emit(self, record):
log_entry = self.format(record)
if record.levelno >= logging.ERROR:
unreal.log_error(log_entry)
elif record.levelno >= logging.WARNING:
unreal.log_warning(log_entry)
else:
unreal.log(log_entry)
def setup_logging(name : str | None = None) -> None:
# 获取根 Logger
logger = logging.getLogger(name)
logger.setLevel(logging.INFO) # 设置日志级别
# 创建自定义的 Unreal 日志处理器
unreal_handler = UnrealLogHandler()
unreal_handler.setLevel(logging.INFO) # 设置处理器的日志级别
# 设置日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
unreal_handler.setFormatter(formatter)
# 添加处理器到 Logger
logger.addHandler(unreal_handler)
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" An example script that uses the API to instantiate an HDA and then
set 2 inputs: a geometry input (a cube) and a curve input (a helix). The
inputs are set during post instantiation (before the first cook). After the
first cook and output creation (post processing) the input structure is fetched
and logged.
"""
import math
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.copy_to_curve_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def get_geo_asset_path():
return '/project/.Cube'
def get_geo_asset():
return unreal.load_object(None, get_geo_asset_path())
def configure_inputs(in_wrapper):
print('configure_inputs')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs)
# Create a geo input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Set the input objects/assets for this input
geo_object = get_geo_asset()
if not geo_input.set_input_objects((geo_object, )):
# If any errors occurred, get the last error message
print('Error on geo_input: {0}'.format(geo_input.get_last_error_message()))
# copy the input data to the HDA as node input 0
in_wrapper.set_input_at_index(0, geo_input)
# We can now discard the API input object
geo_input = None
# Create a curve input
curve_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(100):
t = i / 20.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Error handling/message example: try to set geo_object on curve input
if not curve_input.set_input_objects((geo_object, )):
print('Error (example) while setting \'{0}\' on curve input: {1}'.format(
geo_object.get_name(), curve_input.get_last_error_message()
))
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Copy the input data to the HDA as node input 1
in_wrapper.set_input_at_index(1, curve_input)
# We can now discard the API input object
curve_input = None
# Check for errors on the wrapper
last_error = in_wrapper.get_last_error_message()
if last_error:
print('Error on wrapper during input configuration: {0}'.format(last_error))
def print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference))
if isinstance(in_input, unreal.HoudiniPublicAPIGeoInput):
print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge))
print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds))
print('\t\tbExportSockets: {0}'.format(in_input.export_sockets))
print('\t\tbExportColliders: {0}'.format(in_input.export_colliders))
elif isinstance(in_input, unreal.HoudiniPublicAPICurveInput):
print('\t\tbCookOnCurveChanged: {0}'.format(in_input.cook_on_curve_changed))
print('\t\tbAddRotAndScaleAttributesOnCurves: {0}'.format(in_input.add_rot_and_scale_attributes_on_curves))
input_objects = in_input.get_input_objects()
if not input_objects:
print('\t\tEmpty input!')
else:
print('\t\tNumber of objects in input: {0}'.format(len(input_objects)))
for idx, input_object in enumerate(input_objects):
print('\t\t\tInput object #{0}: {1}'.format(idx, input_object))
if isinstance(input_object, unreal.HoudiniPublicAPICurveInputObject):
print('\t\t\tbClosed: {0}'.format(input_object.is_closed()))
print('\t\t\tCurveMethod: {0}'.format(input_object.get_curve_method()))
print('\t\t\tCurveType: {0}'.format(input_object.get_curve_type()))
print('\t\t\tReversed: {0}'.format(input_object.is_reversed()))
print('\t\t\tCurvePoints: {0}'.format(input_object.get_curve_points()))
def print_inputs(in_wrapper):
print('print_inputs')
# Unbind from the delegate
in_wrapper.on_post_processing_delegate.remove_callable(print_inputs)
# Fetch inputs, iterate over it and log
node_inputs = in_wrapper.get_inputs_at_indices()
parm_inputs = in_wrapper.get_input_parameters()
if not node_inputs:
print('No node inputs found!')
else:
print('Number of node inputs: {0}'.format(len(node_inputs)))
for input_index, input_wrapper in node_inputs.items():
print('\tInput index: {0}'.format(input_index))
print_api_input(input_wrapper)
if not parm_inputs:
print('No parameter inputs found!')
else:
print('Number of parameter inputs: {0}'.format(len(parm_inputs)))
for parm_name, input_wrapper in parm_inputs.items():
print('\tInput parameter name: {0}'.format(parm_name))
print_api_input(input_wrapper)
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Configure inputs on_post_instantiation, after instantiation, but before first cook
_g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs)
# Print the input state after the cook and output creation.
_g_wrapper.on_post_processing_delegate.add_callable(print_inputs)
if __name__ == '__main__':
run()
|
import unreal
def delete_empty_folders():
# instances of unreal classes
editor_asset_lib = unreal.EditorAssetLibrary()
# set source dir and options
source_dir = "/Game"
include_subfolders = True
deleted = 0
# get all assets in source dir
assets = editor_asset_lib.list_assets(source_dir, recursive=include_subfolders, include_folder=True)
for asset in assets:
if editor_asset_lib.does_directory_exist(asset):
# check if folder has assets
has_assets = editor_asset_lib.does_directory_have_assets(asset)
if not has_assets:
# delete folder
editor_asset_lib.delete_directory(asset)
deleted += 1
unreal.log("Folder {} without assets was deleted".format(asset))
unreal.log("Deleted {} folders without assets".format(deleted))
|
import unreal
import json
import os
import sys
import csv
import glob
import time
#project name
project_name = ""
#csv path
csv_folder = ""
#enum path
enum_folder = ""
#enum names
enum_names = []
#use live coding
use_live_coding = False
#genrated string
genrated_str = ''
#c++ Struct Save Path
struct_save_folder = ""
def next_line(file):
file.write("\n")
# CSV 셀 값을 처리하는 함수 (TArray 타입의 경우 쉼표를 세미콜론으로 치환)
def process_csv_cell(cell_value, field_type):
# field_type의 소문자 비교: TArray<...> 인 경우
if str(field_type).lower().startswith("tarray<") and str(field_type).lower().endswith(">"):
# 쉼표(,)를 세미콜론(;)으로 치환
return cell_value.replace(",", ";")
return cell_value
#type def
def get_unreal_type(type):
str_type = str(type).lower()
if str_type.startswith("tarray<") and str_type.endswith(">"):
inner_type_str = str_type[len("tarray<"):-1].strip()
inner_unreal_type = get_unreal_type(inner_type_str)
return "TArray<" + inner_unreal_type + ">"
if str_type == "int" or str_type == "int32":
return "int32"
elif str_type == "float" or str_type == "float32":
return "float"
elif str_type == "string" or str_type == "fstring":
return "FString"
elif str_type == "bool" or str_type == "boolean":
return "bool"
elif str_type == "vector" or str_type == "vector3":
return "FVector"
elif str_type == "rotator" or str_type == "rotator":
return "FRotator"
elif str_type == "text":
return "FText"
elif str_type == "color" or str_type == "coloru8":
return "FLinearColor"
elif type in enum_names:
return "E"+type
else:
unreal.log_error(str_type + " << This type is not allowed. It will change to \'FString\'.")
return "FString"
def get_enum_data():
global enum_names
enum_files= glob.glob(os.path.join(enum_folder,"*.csv"))
print("111111")
for file in enum_files:
if os.path.basename(file).startswith("~$"):
continue
with open(file,'r') as csvfile:
csv_reader = csv.reader(csvfile)
key = ""
for row in csv_reader:
if row[1] == "":
continue
if row[1] == "!Enum":
enum_names.append(str(row[2]))
def create_struct():
global genrated_str
print("####### Data Table C++ Struct Generator Started! #######")
print("###### Target CSV Folder : " + csv_folder)
print("-")
file_list = os.listdir(csv_folder)
csv_file_list = []
for file in file_list:
if file.endswith(".csv"):
csv_file_list.append(file)
if len(csv_file_list) == 0:
unreal.log_error("Thre's no CSV file in folder : " + path.csv_folder)
sys.exit(0)
print("----------- CSV File List ------------")
print("-")
index = 1
for file in csv_file_list:
print("("+str(index)+") "+file)
index += 1
print("-")
for file in csv_file_list:
print("-")
print("::::::::::::: Start making [" + file + "] ::::::::::::::")
csv_file_path = os.path.join(csv_folder,file)
print("----------- Writing C++ Struct row Table... ------------")
print("-")
rows = []
with open(csv_file_path, 'r') as csvfile:
csv_reader = csv.reader(csvfile)
for row in csv_reader:
rows.append(row)
#행이 없다면 종료
if len(rows) == 0:
unreal.log_error("CSV row count is 0")
continue
column_name_row_index = -1
for data in rows:
print(str(data[0]).lower())
if data[0] == "TableNo" or str(data[0]).lower() == "tableno":
column_name_row_index = rows.index(data)
if column_name_row_index == -1:
unreal.log_error("Cannot found Id column")
continue
type_name_list = []
column_name_list = []
column_name_row = rows[column_name_row_index]
#데이터 이름과 변수 타입을 저장
for index, column_name in enumerate(column_name_row):
if not column_name.startswith("#"):
if str(column_name).lower() == "tableno":
continue
type_row = rows[1]
type_name_list.append(type_row[index])
column_name_list.append(column_name)
if len(type_name_list) != len(column_name_list):
print("Type name count and column name count is not correct :" + len(type_name_list)+"/"+len(column_name_list))
continue
#File Name
file_name = os.path.basename(csv_file_path)
file_name = str(file_name).split('.')[0]
struct_str = ""
struct_str += "USTRUCT(BlueprintType)\n"
struct_str += "struct F"+file_name+" : public FTableRowBase\n"
struct_str += "{\n"
struct_str += "\tGENERATED_USTRUCT_BODY()\n"
struct_str += "publi/project/"
for index,value in enumerate(column_name_list):
struct_str+="\tUPROPERTY(EditAnywhere, BlueprintReadWrite)\n"
struct_str+="\t" + get_unreal_type(type_name_list[index]) + " " + str(value)+ ";\n"
struct_str+="};\n"
genrated_str += str(struct_str)
def create_file():
with open(struct_save_folder + "/GenerateTableData.h",'w') as c_file:
c_file.writelines("# pragma once\n")
next_line(c_file)
c_file.writelines("#include \"Engine/DataTable.h\"\n")
c_file.writelines("#include \"EnumGenerateData.h\"\n")
c_file.writelines("#include \"GenerateTableData.generated.h\"\n")
next_line(c_file)
c_file.writelines(genrated_str)
next_line(c_file)
def recompile_and_reload():
# 빌드 시스템 트리거 (Live Coding 등 설정 필요)
unreal.SystemLibrary.execute_console_command(None, "LiveCoding.Compile")
unreal.log("Project modules have been reloaded.")
#Load Json file
json_file_path = unreal.SystemLibrary.get_project_directory() + "/Content/" + project_name + "/project/.json"
print(json_file_path)
if os.path.exists(json_file_path):
try:
with open(json_file_path,'r') as file:
data = json.load(file)
project_name = unreal.Paths.get_base_filename(unreal.Paths.get_project_file_path())
struct_save_folder = unreal.SystemLibrary.get_project_directory() + "Source/" + project_name + "/Data"
csv_folder = data["CSVFolderPath"]
enum_folder = data["EnumFolderPath"]
use_live_coding = data["UseLiveCoding"]
except json.JSONDecodeError as e:
print("Json Load Faile : {e}")
print("Start Generate CSV File")
get_enum_data()
create_struct()
create_file()
if use_live_coding ==True:
recompile_and_reload()
|
# unreal.AssetToolsHelpers
# https://api.unrealengine.com/project/.html
# unreal.AssetTools
# https://api.unrealengine.com/project/.html
# unreal.EditorAssetLibrary
# https://api.unrealengine.com/project/.html
# All operations can be slow. The editor should not be in play in editor mode. It will not work on assets of the type level.
# Possible Directory Paths:
# '/project/'
# '/project/'
# Possible Asset Paths:
# '/project/.MyAsset'
# '/project/'
# unreal.AssetRenameData
# https://api.unrealengine.com/project/.html
# unreal.Package
# https://api.unrealengine.com/project/.html
# unreal.EditorLoadingAndSavingUtils
# https://api.unrealengine.com/project/.html
# unreal.AssetImportTask
# https://api.unrealengine.com/project/.html
# unreal.AssetTools
# https://api.unrealengine.com/project/.html
# unreal.FbxImportUI
# https://api.unrealengine.com/project/.html
# unreal.FbxMeshImportData
# https://api.unrealengine.com/project/.html
# unreal.FbxStaticMeshImportData
# https://api.unrealengine.com/project/.html
# unreal.FbxSkeletalMeshImportData
# https://api.unrealengine.com/project/.html
# unreal.FbxAssetImportData
# https://api.unrealengine.com/project/.html
# unreal.FbxAnimSequenceImportData
# https://api.unrealengine.com/project/.html
# unreal.FBXAnimationLengthImportType
# https://api.unrealengine.com/project/.html
# unreal.LinearColor
# https://api.unrealengine.com/project/.html
# unreal.Factory
# https://api.unrealengine.com/project/.html
import unreal
# asset_path: str : Path of asset to create
# unique_name: bool : If True, will add a number at the end of the asset name until unique
# asset_class: obj unreal.Class : The asset class
# asset_factory: obj unreal.Factory : The associated factory of the class.
# return: obj : The created asset
def createGenericAsset(asset_path='', unique_name=True, asset_class=None, asset_factory=None):
if unique_name:
asset_path, asset_name = unreal.AssetToolsHelpers.get_asset_tools().create_unique_asset_name(base_package_name=asset_path, suffix='')
if not unreal.EditorAssetLibrary.does_asset_exist(asset_path=asset_path):
path = asset_path.rsplit('/', 1)[0]
name = asset_path.rsplit('/', 1)[1]
return unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=name, package_path=path, asset_class=asset_class, factory=asset_factory)
return unreal.load_asset(asset_path)
# paths: List of str : Asset paths
def showAssetsInContentBrowser(paths=[]):
unreal.EditorAssetLibrary.sync_browser_to_objects(asset_paths=paths)
# paths: List of str : Asset paths
def openAssets(paths=[]):
loaded_assets = [getPackageFromPath(x) for x in paths]
unreal.AssetToolsHelpers.get_asset_tools().open_editor_for_assets(assets=loaded_assets)
# path: str : Directory path
# return: bool : True if the operation succeeds
def createDirectory(path=''):
return unreal.EditorAssetLibrary.make_directory(directory_path=path)
# from_dir: str : Directory path to duplicate
# to_dir: str : Duplicated directory path
# return: bool : True if the operation succeeds
def duplicateDirectory(from_dir='', to_dir=''):
return unreal.EditorAssetLibrary.duplicate_directory(source_directory_path=from_dir, destination_directory_path=to_dir)
# path: str : Directory path
# return: bool : True if the operation succeeds
def deleteDirectory(path=''):
return unreal.EditorAssetLibrary.delete_directory(directory_path=path)
# path: str : Directory path
# return: bool : True if the directory exists
def directoryExist(path=''):
return unreal.EditorAssetLibrary.does_directory_exist(directory_path=path)
# from_dir: str : Directory path to rename
# to_dir: str : Renamed directory path
# return: bool : True if the operation succeeds
def renameDirectory(from_dir='', to_dir=''):
return unreal.EditorAssetLibrary.rename_directory(source_directory_path=from_dir, destination_directory_path=to_dir)
# from_path str : Asset path to duplicate
# to_path: str : Duplicated asset path
# return: bool : True if the operation succeeds
def duplicateAsset(from_path='', to_path=''):
return unreal.EditorAssetLibrary.duplicate_asset(source_asset_path=from_path, destination_asset_path=to_path)
# path: str : Asset path
# return: bool : True if the operation succeeds
def deleteAsset(path=''):
return unreal.EditorAssetLibrary.delete_asset(asset_path_to_delete=path)
# path: str : Asset path
# return: bool : True if the asset exists
def assetExist(path=''):
return unreal.EditorAssetLibrary.does_asset_exist(asset_path=path)
# from_path: str : Asset path to rename
# to_path: str : Renamed asset path
# return: bool : True if the operation succeeds
def renameAsset(from_path='', to_path=''):
return unreal.EditorAssetLibrary.rename_asset(source_asset_path=from_path, destination_asset_path=to_path)
# Note: This function will also work on assets of the type level. (But might be really slow if the level is huge)
# from_path: str : Asset path to duplicate
# to_path: str : Duplicate asset path
# show_dialog: bool : True if you want to show the confirm pop-up
# return: bool : True if the operation succeeds
def duplicateAssetDialog(from_path='', to_path='', show_dialog=True):
splitted_path = to_path.rsplit('/', 1)
asset_path = splitted_path[0]
asset_name = splitted_path[1]
if show_dialog:
return unreal.AssetToolsHelpers.get_asset_tools().duplicate_asset_with_dialog(asset_name=asset_name, package_path=asset_path, original_object=getPackageFromPath(from_path))
else:
return unreal.duplicate_asset.get_asset_tools().duplicate_asset(asset_name=asset_name, package_path=asset_path, original_object=getPackageFromPath(from_path))
# Note: This function will also work on assets of the type level. (But might be really slow if the level is huge)
# from_path: str : Asset path to rename
# to_path: str : Renamed asset path
# show_dialog: bool : True if you want to show the confirm pop-up
# return: bool : True if the operation succeeds
def renameAssetDialog(from_path='', to_path='', show_dialog=True):
splitted_path = to_path.rsplit('/', 1)
asset_path = splitted_path[0]
asset_name = splitted_path[1]
rename_data = unreal.AssetRenameData(asset=getPackageFromPath(from_path), new_package_path=asset_path, new_name=asset_name)
if show_dialog:
return unreal.AssetToolsHelpers.get_asset_tools().rename_assets_with_dialog(assets_and_names=[rename_data])
else:
return unreal.AssetToolsHelpers.get_asset_tools().rename_assets(assets_and_names=[rename_data])
# path: str : Asset path
# return: bool : True if the operation succeeds
def saveAsset(path='', force_save=True):
return unreal.EditorAssetLibrary.save_asset(asset_to_save=path, only_if_is_dirty = not force_save)
# path: str : Directory path
# return: bool : True if the operation succeeds
def saveDirectory(path='', force_save=True, recursive=True):
return unreal.EditorAssetLibrary.save_directory(directory_path=path, only_if_is_dirty=not force_save, recursive=recursive)
# path: str : Asset path
# return: obj : The loaded asset
def getPackageFromPath(path):
return unreal.load_package(name=path)
# return: obj List : The assets that need to be saved
def getAllDirtyPackages():
packages = []
for x in unreal.EditorLoadingAndSavingUtils.get_dirty_content_packages():
packages.append(x)
for x in unreal.EditorLoadingAndSavingUtils.get_dirty_map_packages():
packages.append(x)
return packages
# show_dialog: bool : True if you want to see the confirm pop-up
# return: bool : True if the operation succeeds
def saveAllDirtyPackages(show_dialog=False):
if show_dialog:
return unreal.EditorLoadingAndSavingUtils.save_dirty_packages_with_dialog(save_map_packages=True, save_content_packages=True)
else:
return unreal.EditorLoadingAndSavingUtils.save_dirty_packages(save_map_packages=True, save_content_packages=True)
# show_dialog: bool : True if you want to see the confirm pop-up
# return: bool : True if the operation succeeds
def savePackages(packages=[], show_dialog=False):
if show_dialog:
return unreal.EditorLoadingAndSavingUtils.save_packages_with_dialog(packages_to_save=packages, only_dirty=False) # only_dirty=False :
else: # looks like that it's not
return unreal.EditorLoadingAndSavingUtils.save_packages(packages_to_save=packages, only_dirty=False) # working properly at the moment
# filename: str : Windows file fullname of the asset you want to import
# destination_path: str : Asset path
# option: obj : Import option object. Can be None for assets that does not usually have a pop-up when importing. (e.g. Sound, Texture, etc.)
# return: obj : The import task object
def buildImportTask(filename='', destination_path='', options=None):
task = unreal.AssetImportTask()
task.set_editor_property('automated', True)
task.set_editor_property('destination_name', '')
task.set_editor_property('destination_path', destination_path)
task.set_editor_property('filename', filename)
task.set_editor_property('replace_existing', True)
task.set_editor_property('save', True)
task.set_editor_property('options', options)
return task
# tasks: obj List : The import tasks object. You can get them from buildImportTask()
# return: str List : The paths of successfully imported assets
def executeImportTasks(tasks=[]):
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks)
imported_asset_paths = []
for task in tasks:
for path in task.get_editor_property('imported_object_paths'):
imported_asset_paths.append(path)
return imported_asset_paths
# return: obj : Import option object. The basic import options for importing a static mesh
def buildStaticMeshImportOptions():
options = unreal.FbxImportUI()
# unreal.FbxImportUI
options.set_editor_property('import_mesh', True)
options.set_editor_property('import_textures', False)
options.set_editor_property('import_materials', False)
options.set_editor_property('import_as_skeletal', False) # Static Mesh
# unreal.FbxMeshImportData
options.static_mesh_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0))
options.static_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0))
options.static_mesh_import_data.set_editor_property('import_uniform_scale', 1.0)
# unreal.FbxStaticMeshImportData
options.static_mesh_import_data.set_editor_property('combine_meshes', True)
options.static_mesh_import_data.set_editor_property('generate_lightmap_u_vs', True)
options.static_mesh_import_data.set_editor_property('auto_generate_collision', True)
return options
# return: obj : Import option object. The basic import options for importing a skeletal mesh
def buildSkeletalMeshImportOptions():
options = unreal.FbxImportUI()
# unreal.FbxImportUI
options.set_editor_property('import_mesh', True)
options.set_editor_property('import_textures', True)
options.set_editor_property('import_materials', True)
options.set_editor_property('import_as_skeletal', True) # Skeletal Mesh
# unreal.FbxMeshImportData
options.skeletal_mesh_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0))
options.skeletal_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0))
options.skeletal_mesh_import_data.set_editor_property('import_uniform_scale', 1.0)
# unreal.FbxSkeletalMeshImportData
options.skeletal_mesh_import_data.set_editor_property('import_morph_targets', True)
options.skeletal_mesh_import_data.set_editor_property('update_skeleton_reference_pose', False)
return options
# skeleton_path: str : Skeleton asset path of the skeleton that will be used to bind the animation
# return: obj : Import option object. The basic import options for importing an animation
def buildAnimationImportOptions(skeleton_path=''):
options = unreal.FbxImportUI()
# unreal.FbxImportUI
options.set_editor_property('import_animations', True)
options.skeleton = unreal.load_asset(skeleton_path)
# unreal.FbxMeshImportData
options.anim_sequence_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0))
options.anim_sequence_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0))
options.anim_sequence_import_data.set_editor_property('import_uniform_scale', 1.0)
# unreal.FbxAnimSequenceImportData
options.anim_sequence_import_data.set_editor_property('animation_length', unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME)
options.anim_sequence_import_data.set_editor_property('remove_redundant_keys', False)
return options
# Cpp ########################################################################################################################################################################################
# return: str List : The asset paths that are currently selected
def getSelectedAssets():
return unreal.CppLib.get_selected_assets()
# asset_paths: str List : The asset paths to select
def setSelectedAssets(asset_paths=[]):
unreal.CppLib.set_selected_assets(asset_paths)
# return: str List : The folder paths that are currently selected
def getSelectedFolders():
return unreal.CppLib.get_selected_folders()
# folder_paths: str List : The asset paths to select
def setSelectedFolders(folder_paths=[]):
unreal.CppLib.set_selected_folders(folder_paths)
# return: obj List : The asset objects that are currently opened in the editor
def getAllOpenedAssets():
return unreal.CppLib.get_assets_opened_in_editor()
# asset_objects: obj List : The asset objects to close
def closeAssets(asset_objects=[]):
unreal.CppLib.close_editor_for_assets(asset_objects)
# Note: If the directory already exists, might need to restart Unreal,
# but it's not needed if the color is applied before creating the folder.
# path: str : Directory path
# color: obj unreal.LinearColor : The color to apply
def setDirectoryColor(path='', color=None):
unreal.CppLib.set_folder_color(path, color)
|
# Copyright Epic Games, Inc. All Rights Reserved
import os
import argparse
import json
import unreal
from deadline_rpc import BaseRPC
from mrq_cli_modes import (
render_queue_manifest,
render_current_sequence,
render_queue_asset,
utils,
)
class MRQRender(BaseRPC):
"""
Class to execute deadline MRQ renders using RPC
"""
def __init__(self, *args, **kwargs):
"""
Constructor
"""
super(MRQRender, self).__init__(*args, **kwargs)
self._render_cmd = ["mrq_cli.py"]
# Keep track of the task data
self._shot_data = None
self._queue = None
self._manifest = None
self._sequence_data = None
def _get_queue(self):
"""
Render a MRQ queue asset
:return: MRQ queue asset name
"""
if not self._queue:
self._queue = self.proxy.get_job_extra_info_key_value("queue_name")
return self._queue
def _get_sequence_data(self):
"""
Get sequence data
:return: Sequence data
"""
if not self._sequence_data:
self._sequence_data = self.proxy.get_job_extra_info_key_value(
"sequence_render"
)
return self._sequence_data
def _get_serialized_pipeline(self):
"""
Get Serialized pipeline from Deadline
:return:
"""
if not self._manifest:
serialized_pipeline = self.proxy.get_job_extra_info_key_value(
"serialized_pipeline"
)
if not serialized_pipeline:
return
unreal.log(
f"Executing Serialized Pipeline: `{serialized_pipeline}`"
)
# create manifest file
manifest_dir = os.path.join(
unreal.SystemLibrary.get_project_saved_directory(),
"MovieRenderPipeline",
)
if not os.path.exists(manifest_dir):
os.makedirs(manifest_dir)
manifest_file = os.path.join(manifest_dir, "QueueManifest.utxt")
unreal.log(f"Saving Manifest file `{manifest_file}`")
# Dump the manifest data into the manifest file
with open(manifest_file, "w") as manifest:
manifest.write(serialized_pipeline)
self._manifest = manifest_file
return self._manifest
def execute(self):
"""
Starts the render execution
"""
# shots are listed as a dictionary of task id -> shotnames
# i.e {"O": "my_new_shot"} or {"20", "shot_1,shot_2,shot_4"}
# Get the task data and cache it
if not self._shot_data:
self._shot_data = json.loads(
self.proxy.get_job_extra_info_key_value("shot_info")
)
# Get any output overrides
output_dir = self.proxy.get_job_extra_info_key_value(
"output_directory_override"
)
# Resolve any path mappings in the directory name. The server expects
# a list of paths, but we only ever expect one. So wrap it in a list
# if we have an output directory
if output_dir:
output_dir = self.proxy.check_path_mappings([output_dir])
output_dir = output_dir[0]
# Get the filename format
filename_format = self.proxy.get_job_extra_info_key_value(
"filename_format_override"
)
# Resolve any path mappings in the filename. The server expects
# a list of paths, but we only ever expect one. So wrap it in a list
if filename_format:
filename_format = self.proxy.check_path_mappings([filename_format])
filename_format = filename_format[0]
# get the shots for the current task
current_task_data = self._shot_data.get(str(self.current_task_id), None)
if not current_task_data:
self.proxy.fail_render("There are no task data to execute!")
return
shots = current_task_data.split(",")
if self._get_queue():
return self.render_queue(
self._get_queue(),
shots,
output_dir_override=output_dir if output_dir else None,
filename_format_override=filename_format if filename_format else None
)
if self._get_serialized_pipeline():
return self.render_serialized_pipeline(
self._get_serialized_pipeline(),
shots,
output_dir_override=output_dir if output_dir else None,
filename_format_override=filename_format if filename_format else None
)
if self._get_sequence_data():
render_data = json.loads(self._get_sequence_data())
sequence = render_data.get("sequence_name")
level = render_data.get("level_name")
mrq_preset = render_data.get("mrq_preset_name")
return self.render_sequence(
sequence,
level,
mrq_preset,
shots,
output_dir_override=output_dir if output_dir else None,
filename_format_override=filename_format if filename_format else None
)
def render_queue(
self,
queue_path,
shots,
output_dir_override=None,
filename_format_override=None
):
"""
Executes a render from a queue
:param str queue_path: Name/path of the queue asset
:param list shots: Shots to render
:param str output_dir_override: Movie Pipeline output directory
:param str filename_format_override: Movie Pipeline filename format override
"""
unreal.log(f"Executing Queue asset `{queue_path}`")
unreal.log(f"Rendering shots: {shots}")
# Get an executor instance
executor = self._get_executor_instance()
# Set executor callbacks
# Set shot finished callbacks
executor.on_individual_shot_work_finished_delegate.add_callable(
self._on_individual_shot_finished_callback
)
# Set executor finished callbacks
executor.on_executor_finished_delegate.add_callable(
self._on_job_finished
)
executor.on_executor_errored_delegate.add_callable(self._on_job_failed)
# Render queue with executor
render_queue_asset(
queue_path,
shots=shots,
user=self.proxy.get_job_user(),
executor_instance=executor,
output_dir_override=output_dir_override,
output_filename_override=filename_format_override
)
def render_serialized_pipeline(
self,
manifest_file,
shots,
output_dir_override=None,
filename_format_override=None
):
"""
Executes a render using a manifest file
:param str manifest_file: serialized pipeline used to render a manifest file
:param list shots: Shots to render
:param str output_dir_override: Movie Pipeline output directory
:param str filename_format_override: Movie Pipeline filename format override
"""
unreal.log(f"Rendering shots: {shots}")
# Get an executor instance
executor = self._get_executor_instance()
# Set executor callbacks
# Set shot finished callbacks
executor.on_individual_shot_work_finished_delegate.add_callable(
self._on_individual_shot_finished_callback
)
# Set executor finished callbacks
executor.on_executor_finished_delegate.add_callable(
self._on_job_finished
)
executor.on_executor_errored_delegate.add_callable(self._on_job_failed)
render_queue_manifest(
manifest_file,
shots=shots,
user=self.proxy.get_job_user(),
executor_instance=executor,
output_dir_override=output_dir_override,
output_filename_override=filename_format_override
)
def render_sequence(
self,
sequence,
level,
mrq_preset,
shots,
output_dir_override=None,
filename_format_override=None
):
"""
Executes a render using a sequence level and map
:param str sequence: Level Sequence name
:param str level: Level
:param str mrq_preset: MovieRenderQueue preset
:param list shots: Shots to render
:param str output_dir_override: Movie Pipeline output directory
:param str filename_format_override: Movie Pipeline filename format override
"""
unreal.log(
f"Executing sequence `{sequence}` with map `{level}` "
f"and mrq preset `{mrq_preset}`"
)
unreal.log(f"Rendering shots: {shots}")
# Get an executor instance
executor = self._get_executor_instance()
# Set executor callbacks
# Set shot finished callbacks
executor.on_individual_shot_work_finished_delegate.add_callable(
self._on_individual_shot_finished_callback
)
# Set executor finished callbacks
executor.on_executor_finished_delegate.add_callable(
self._on_job_finished
)
executor.on_executor_errored_delegate.add_callable(self._on_job_failed)
render_current_sequence(
sequence,
level,
mrq_preset,
shots=shots,
user=self.proxy.get_job_user(),
executor_instance=executor,
output_dir_override=output_dir_override,
output_filename_override=filename_format_override
)
@staticmethod
def _get_executor_instance():
"""
Gets an instance of the movie pipeline executor
:return: Movie Pipeline Executor instance
"""
return utils.get_executor_instance(False)
def _on_individual_shot_finished_callback(self, shot_params):
"""
Callback to execute when a shot is done rendering
:param shot_params: Movie pipeline shot params
"""
unreal.log("Executing On individual shot callback")
# Since MRQ cannot parse certain parameters/arguments till an actual
# render is complete (e.g. local version numbers), we will use this as
# an opportunity to update the deadline proxy on the actual frame
# details that were rendered
file_patterns = set()
# Iterate over all the shots in the shot list (typically one shot as
# this callback is executed) on a shot by shot bases.
for shot in shot_params.shot_data:
for pass_identifier in shot.render_pass_data:
# only get the first file
paths = shot.render_pass_data[pass_identifier].file_paths
# make sure we have paths to iterate on
if len(paths) < 1:
continue
# we only need the ext from the first file
ext = os.path.splitext(paths[0])[1].replace(".", "")
# Make sure we actually have an extension to use
if not ext:
continue
# Get the current job output settings
output_settings = shot_params.job.get_configuration().find_or_add_setting_by_class(
unreal.MoviePipelineOutputSetting
)
resolve_params = unreal.MoviePipelineFilenameResolveParams()
# Set the camera name from the shot data
resolve_params.camera_name_override = shot_params.shot_data[
0
].shot.inner_name
# set the shot name from the shot data
resolve_params.shot_name_override = shot_params.shot_data[
0
].shot.outer_name
# Get the zero padding configuration
resolve_params.zero_pad_frame_number_count = (
output_settings.zero_pad_frame_numbers
)
# Update the formatting of frame numbers based on the padding.
# Deadline uses # (* padding) to display the file names in a job
resolve_params.file_name_format_overrides[
"frame_number"
] = "#" * int(output_settings.zero_pad_frame_numbers)
# Update the extension
resolve_params.file_name_format_overrides["ext"] = ext
# Set the job on the resolver
resolve_params.job = shot_params.job
# Set the initialization time on the resolver
resolve_params.initialization_time = (
unreal.MoviePipelineLibrary.get_job_initialization_time(
shot_params.pipeline
)
)
# Set the shot overrides
resolve_params.shot_override = shot_params.shot_data[0].shot
combined_path = unreal.Paths.combine(
[
output_settings.output_directory.path,
output_settings.file_name_format,
]
)
# Resolve the paths
# The returned values are a tuple with the resolved paths as the
# first index. Get the paths and add it to a list
(
path,
_,
) = unreal.MoviePipelineLibrary.resolve_filename_format_arguments(
combined_path, resolve_params
)
# Make sure we are getting the right type from resolved
# arguments
if isinstance(path, str):
# Sanitize the paths
path = os.path.normpath(path).replace("\\", "/")
file_patterns.add(path)
elif isinstance(path, list):
file_patterns.update(
set(
[
os.path.normpath(p).replace("\\", "/")
for p in path
]
)
)
else:
raise RuntimeError(
f"Expected the shot file paths to be a "
f"string or list but got: {type(path)}"
)
if file_patterns:
unreal.log(f'Updating remote filenames: {", ".join(file_patterns)}')
# Update the paths on the deadline job
self.proxy.update_job_output_filenames(list(file_patterns))
def _on_job_finished(self, executor=None, success=None):
"""
Callback to execute on executor finished
"""
# TODO: add th ability to set the output directory for the task
unreal.log(f"Task {self.current_task_id} complete!")
self.task_complete = True
def _on_job_failed(self, executor, pipeline, is_fatal, error):
"""
Callback to execute on job failed
"""
unreal.log_error(f"Is fatal job error: {is_fatal}")
unreal.log_error(
f"An error occurred executing task `{self.current_task_id}`: \n\t{error}"
)
self.proxy.fail_render(error)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="This parser is used to run an mrq render with rpc"
)
parser.add_argument(
"--port", type=int, default=None, help="Port number for rpc server"
)
parser.add_argument(
"--verbose", action="store_true", help="Enable verbose logging"
)
arguments = parser.parse_args()
MRQRender(port=arguments.port, verbose=arguments.verbose)
|
import unreal
# get all selected assets from content browser
def get_selected_content_browser_assets():
editor_utility = unreal.EditorUtilityLibrary()
selected_assets = editor_utility.get_selected_assets()
return selected_assets
# generic logging for asset type
def log_asset_types(assets):
for asset in assets:
unreal.log(f"Asset {asset.get_name()} is a {type(asset)}")
# return any materials in asset list
def find_material_in_assets(assets):
for asset in assets:
if type(asset) is unreal.Material:
return asset
return None
# return any texture 2d objects in asset list
def find_textures2D_in_assets(assets):
textures = []
for asset in assets:
if type(asset) is unreal.Texture2D:
textures.append(asset)
return textures
def get_random_color():
return unreal.LinearColor(unreal.MathLibrary.rand_range(0,1), unreal.MathLibrary.rand_range(0,1), unreal.MathLibrary.rand_range(0,1))
def create_material_instance(parent_material,asset_path,new_asset_name):
#create child
version = 0
max_versions = 999
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
material_factory = unreal.MaterialInstanceConstantFactoryNew()
version_name = f"{new_asset_name}_{version:03}"
full_path = f"{asset_path}/{version_name}"
asset_exist = unreal.EditorAssetLibrary.does_asset_exist(full_path)
while version <= max_versions:
#update versions in core loop to prevent it from checking same thing over and over again
version_name = f"{new_asset_name}_{version:03}" # the {version:03} transitions the version number into a 3 digit (001,002, 003,etc.)
full_path = f"{asset_path}/{version_name}"
asset_exist = unreal.EditorAssetLibrary.does_asset_exist(full_path)
if asset_exist == True:
version += 1
unreal.log("Version already exists, updating")
else:
break #should only break when a suitable version is created
if version > max_versions:
unreal.log_error("Max versions reached")
return None
new_asset = asset_tools.create_asset(version_name, asset_path,None,material_factory)
#assign parent
unreal.MaterialEditingLibrary.set_material_instance_parent(new_asset, parent_material)
return new_asset
def create_mat_inst_for_each (material,textures):
for texture in textures:
unreal.log(f"Creating material instance for texture {texture.get_name()}")
material_asset_path = unreal.Paths.get_path(texture.get_path_name())
material_name = f"{material.get_name()}_{texture.get_name()}"
material_instance = create_material_instance (material,material_asset_path,material_name)
# Assign texture
try:
unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance, "Tex", texture)
except:
unreal.log("Tex parameter does not exist")
# Assign Color
try:
color = get_random_color()
print (f"Color is {color}")
unreal.MaterialEditingLibrary.set_material_instance_vector_parameter_value(material_instance,"Color", color)
except:
unreal.log("Base Color parameter does not exist")
# Save Asset
unreal.EditorAssetLibrary.save_asset(material_instance.get_path_name(),only_if_is_dirty = True)
# important note: will not work without a texture selected
def run():
unreal.log("Running create material instances script")
selected_assets = get_selected_content_browser_assets()
log_asset_types(selected_assets)
material = find_material_in_assets(selected_assets)
textures = find_textures2D_in_assets(selected_assets)
if not material:
unreal.log_error("No material selected")
else:
unreal.log(f"Selected material: {material.get_name()}")
if not textures:
unreal.log_error("No texture selected")
else:
unreal.log(f"{len(textures)} textures selected")
create_mat_inst_for_each(material,textures)
run()
|
import unreal
import logging
logger = logging.getLogger(__name__)
from pamux_unreal_tools.base.material_expression.material_expression_base import MaterialExpressionBase
from pamux_unreal_tools.utils.node_pos import NodePos
from pamux_unreal_tools.impl.in_socket_impl import InSocketImpl
from pamux_unreal_tools.impl.out_socket_impl import OutSocketImpl
from pamux_unreal_tools.impl.material_expression_editor_property_impl import MaterialExpressionEditorPropertyImpl
MEL = unreal.MaterialEditingLibrary
class MaterialExpressionImpl(MaterialExpressionBase):
def __init__(self, expression_class: unreal.Class, node_pos: NodePos = None) -> None:
super().__init__(expression_class, node_pos)
self.desc = MaterialExpressionEditorPropertyImpl(self, 'desc', 'str')
self.material_expression_editor_x = MaterialExpressionEditorPropertyImpl(self, 'material_expression_editor_x', 'int32')
self.material_expression_editor_y = MaterialExpressionEditorPropertyImpl(self, 'material_expression_editor_y', 'int32')
self.input = InSocketImpl(self, '', 'StructProperty')
self.output = OutSocketImpl(self, '', 'StructProperty')
def gotoRightOf(self, sourceMaterialExpression: MaterialExpressionBase):
self.material_expression_editor_x.set(sourceMaterialExpression.material_expression_editor_x.get() + NodePos.DeltaX)
|
import unreal
def get_component_handles(blueprint_asset_path):
subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem)
blueprint_asset = unreal.load_asset(blueprint_asset_path)
subobject_data_handles = subsystem.k2_gather_subobject_data_for_blueprint(blueprint_asset)
return subobject_data_handles
def get_component_objects(blueprint_asset_path):
objects = []
handles = get_component_handles(blueprint_asset_path)
for handle in handles:
data = unreal.SubobjectDataBlueprintFunctionLibrary.get_data(handle)
object = unreal.SubobjectDataBlueprintFunctionLibrary.get_object(data)
objects.append(object)
return objects
def get_component_by_class(blueprint_to_find_components, component_class_to_find):
components = []
asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(blueprint_to_find_components)
component_objects = get_component_objects(asset_path)
for each in component_objects:
compare_class = (each.__class__ == component_class_to_find)
if compare_class :
components.append(each)
return components
def get_component_by_var_name(blueprint_to_find_components : unreal.Blueprint, component_name_to_find : str) :
components = []
asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(blueprint_to_find_components)
component_objects = get_component_objects(asset_path)
for each in component_objects:
compare_name = (each.get_name()) == ( component_name_to_find + '_GEN_VARIABLE' )
if compare_name :
components.append(each)
return components
## 함수 선언부
##TestCode Start
asset_list = unreal.EditorUtilityLibrary.get_selected_assets()
asset = asset_list[0]
StaticMeshComps = get_component_by_class(asset, unreal.StaticMeshComponent)
TempComp = get_component_by_var_name(asset, 'BP_InteractionPointComponent1')
print(TempComp)
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import unreal
import flow.cmd
import unrealcmd
#-------------------------------------------------------------------------------
class Show(unrealcmd.Cmd):
""" Display the current build configuration for the current project. To
modify the configuration use the sub-commands set, clear, and edit. """
def main(self):
root = {}
context = self.get_unreal_context()
ubt = context.get_engine().get_ubt()
for config in (x for x in ubt.read_configurations() if x.exists()):
level = config.get_level()
try:
for section, name, value in config.read_values():
section = root.setdefault(section, {})
name = section.setdefault(name, [])
name.append((value, level))
except IOError as e:
self.print_warning(f"Failed loading '{config.get_path()}'")
self.print_warning(str(e))
continue
col0 = max(len(x) for x in root.keys()) if root else 0
col0 += 2
col1 = 0
for section in root.values():
n = max(len(x) for x in section.keys())
col1 = max(col1, n)
col1 += 2
def spam(n, x, decorator=None):
dots = "." * (n - len(x))
if decorator: x = decorator(x)
print(x, flow.cmd.text.grey(dots), "", end="")
self.print_info("Current configuration")
if not root:
print("There isn't any!")
for section, payload in root.items():
for name, payload in payload.items():
for value, level in payload:
value = value + " (" + level.name.title() + ")"
spam(col0, section, flow.cmd.text.cyan)
spam(col1, name, flow.cmd.text.white)
spam(0, value)
print()
self.print_info("File paths")
for config in ubt.read_configurations():
red_green = flow.cmd.text.green if config.exists() else flow.cmd.text.red
spam(10, config.get_level().name.title(), decorator=red_green)
spam(0, os.path.normpath(config.get_path()))
print()
#-------------------------------------------------------------------------------
class _SetClearBase(unrealcmd.Cmd):
section = unrealcmd.Arg(str, "Configuration section to modify")
name = unrealcmd.Arg(str, "The name of the value to change")
branch = unrealcmd.Opt(False, "Only apply changes to this branch (otherwise global)")
def _complete_schema(self, prefix):
context = self.get_unreal_context()
ubt = context.get_engine().get_ubt()
schema = ubt.get_configuration_schema()
def read_node_names():
if self.args.section: yield self.args.section
if self.args.name: yield self.args.name
if node := schema.get_node(*read_node_names()):
yield from (x.get_name() for x in node.read_children())
complete_section = _complete_schema
complete_name = _complete_schema
def _load_configuration(self):
self.print_info("Modifying build configuration")
context = self.get_unreal_context()
ubt = context.get_engine().get_ubt()
configuration = ubt.get_configuration(self.args.branch, create=True)
print("Scope:", configuration.get_level().name.title())
print("Path:", configuration.get_path())
return configuration
#-------------------------------------------------------------------------------
class _SetImpl(object):
""" Modify build configuration. """
value = unrealcmd.Arg(str, "A value to set the property to")
complete_value = _SetClearBase._complete_schema
def main(self):
section, name, value = self.args.section, self.args.name, self.args.value
configuration = self._load_configuration()
prev_value = None
try:
prev_value = configuration.get_value(section, name)
except LookupError:
pass
configuration.set_value(section, name, value)
configuration.save()
print(f"Setting '{section}.{name}' to '{value}' (was '{prev_value}')")
with flow.cmd.text.green:
print("Success")
#-------------------------------------------------------------------------------
# This exists simply to get arguments (i.e. unreal.Arg) in the correct order.
class Set(_SetClearBase, _SetImpl):
pass
#-------------------------------------------------------------------------------
class Clear(_SetClearBase):
""" Clears a value from the build configuration. """
def main(self):
section, name = self.args.section, self.args.name
configuration = self._load_configuration()
prev_value = None
try:
prev_value = configuration.get_value(section, name)
except LookupError:
pass
try:
configuration.clear_value(section, name)
configuration.save()
except LookupError as e:
self.print_error(e)
return False
print(f"Cleared '{section}.{name}' (was '{prev_value}')")
with flow.cmd.text.green:
print("Success")
#-------------------------------------------------------------------------------
class Edit(unrealcmd.Cmd):
""" Opens a build configuration in a text editor. The text editor used is
determined in the following order; $GIT_EDITOR, $P4EDITOR, system default. """
branch = unrealcmd.Opt(False, "Edit the build configuration for this branch")
def main(self):
context = self.get_unreal_context()
ubt = context.get_engine().get_ubt()
configuration = ubt.get_configuration(self.args.branch, create=True)
path = configuration.get_path()
print("Editing", path)
self.edit_file(path)
|
import unreal
# Facial
datatable: unreal.DataTable = unreal.EditorUtilityLibrary.get_selected_assets()[0]
dt_library = unreal.DataTableFunctionLibrary
row_names = dt_library.get_data_table_row_names(datatable)
for row_name in row_names:
row_data = unreal.DataTableRowHandle(datatable, row_name)
print(row_data)
|
from typing import *
from pydantic_model import SequenceKey
import unreal
from utils import *
from utils_actor import *
import math
import numpy as np
import random
################################################################################
# misc
def convert_frame_rate_to_fps(frame_rate: unreal.FrameRate) -> float:
return frame_rate.numerator / frame_rate.denominator
def get_sequence_fps(sequence: unreal.LevelSequence) -> float:
seq_fps: unreal.FrameRate = sequence.get_display_rate()
return convert_frame_rate_to_fps(seq_fps)
def get_animation_length(animation_asset: unreal.AnimSequence, seq_fps: Optional[float]=None) -> int:
anim_len = animation_asset.get_editor_property("number_of_sampled_frames")
if seq_fps:
anim_frame_rate = animation_asset.get_editor_property("target_frame_rate")
anim_frame_rate = convert_frame_rate_to_fps(anim_frame_rate)
if anim_frame_rate != seq_fps:
anim_len = round(animation_asset.get_editor_property("sequence_length") * seq_fps)
return anim_len
################################################################################
# sequencer session
def get_transform_channels_from_section(
trans_section: unreal.MovieScene3DTransformSection,
) -> List[unreal.MovieSceneScriptingChannel]:
channel_x = channel_y = channel_z = channel_roll = channel_pitch = channel_yaw = None
for channel in trans_section.get_channels():
channel: unreal.MovieSceneScriptingChannel
if channel.channel_name == "Location.X":
channel_x = channel
elif channel.channel_name == "Location.Y":
channel_y = channel
elif channel.channel_name == "Location.Z":
channel_z = channel
elif channel.channel_name == "Rotation.X":
channel_roll = channel
elif channel.channel_name == "Rotation.Y":
channel_pitch = channel
elif channel.channel_name == "Rotation.Z":
channel_yaw = channel
assert channel_x is not None
assert channel_y is not None
assert channel_z is not None
assert channel_roll is not None
assert channel_pitch is not None
assert channel_yaw is not None
return channel_x, channel_y, channel_z, channel_roll, channel_pitch, channel_yaw
def set_transform_by_section(
trans_section: unreal.MovieScene3DTransformSection,
loc: Tuple[float, float, float],
rot: Tuple[float, float, float],
key_frame: int = 0,
key_type: str = "CONSTANT",
) -> None:
"""set `loc & rot` keys to given `transform section`
Args:
trans_section (unreal.MovieScene3DTransformSection): section
loc (tuple): location key
rot (tuple): rotation key
key_frame (int): frame of the key. Defaults to 0.
key_type (str): type of the key. Defaults to 'CONSTANT'. Choices: 'CONSTANT', 'LINEAR', 'AUTO'.
"""
channel_x, channel_y, channel_z, \
channel_roll, channel_pitch, channel_yaw = get_transform_channels_from_section(trans_section)
loc_x, loc_y, loc_z = loc
rot_x, rot_y, rot_z = rot
key_frame_ = unreal.FrameNumber(key_frame)
key_type_ = getattr(unreal.MovieSceneKeyInterpolation, key_type)
channel_x.add_key(key_frame_, loc_x, interpolation=key_type_)
channel_y.add_key(key_frame_, loc_y, interpolation=key_type_)
channel_z.add_key(key_frame_, loc_z, interpolation=key_type_)
channel_roll.add_key(key_frame_, rot_x, interpolation=key_type_)
channel_pitch.add_key(key_frame_, rot_y, interpolation=key_type_)
channel_yaw.add_key(key_frame_, rot_z, interpolation=key_type_)
def set_transforms_by_section(
trans_section: unreal.MovieScene3DTransformSection,
trans_keys: List[SequenceKey],
key_type: str = "CONSTANT",
) -> None:
"""set `loc & rot` keys to given `transform section`
Args:
trans_section (unreal.MovieScene3DTransformSection): section
trans_dict (dict): keys
type (str): type of the key. Defaults to 'CONSTANT'. Choices: 'CONSTANT', 'LINEAR', 'AUTO'.
Examples:
>>> sequence = unreal.load_asset('/project/')
>>> camera_binding = sequence.add_spawnable_from_class(unreal.CameraActor)
>>> transform_track: unreal.MovieScene3DTransformTrack = camera_binding.add_track(unreal.MovieScene3DTransformTrack)
>>> transform_section: unreal.MovieScene3DTransformSection = transform_track.add_section()
>>> trans_dict = {
>>> 0: [ # time of key
>>> [500, 1500, 100], # location of key
>>> [0, 0, 30] # rotation of key
>>> ],
>>> 300: [ # multi-keys
>>> [1000, 2000, 300],
>>> [0, 0, 0]
>>> ]
>>> }
>>> set_transforms_by_section(transform_section, trans_dict)
"""
channel_x, channel_y, channel_z, \
channel_roll, channel_pitch, channel_yaw = get_transform_channels_from_section(trans_section)
key_type_ = getattr(unreal.MovieSceneKeyInterpolation, key_type)
for trans_key in trans_keys:
key_frame = trans_key.frame
loc_x, loc_y, loc_z = trans_key.location
rot_x, rot_y, rot_z = trans_key.rotation
key_time_ = unreal.FrameNumber(key_frame)
channel_x.add_key(key_time_, loc_x, interpolation=key_type_)
channel_y.add_key(key_time_, loc_y, interpolation=key_type_)
channel_z.add_key(key_time_, loc_z, interpolation=key_type_)
channel_roll.add_key(key_time_, rot_x, interpolation=key_type_)
channel_pitch.add_key(key_time_, rot_y, interpolation=key_type_)
channel_yaw.add_key(key_time_, rot_z, interpolation=key_type_)
def set_transform_by_binding(
binding: unreal.SequencerBindingProxy,
loc: Tuple[float, float, float],
rot: Tuple[float, float, float],
key_frame: int = 0,
key_type: str = "CONSTANT",
) -> None:
trans_track: unreal.MovieScene3DTransformTrack = binding.find_tracks_by_type(
unreal.MovieScene3DTransformTrack)[0]
trans_section = trans_track.get_sections()[0]
set_transform_by_section(trans_section, loc, rot, key_frame, key_type)
def set_transform_by_key(
sequence: unreal.MovieSceneSequence,
key: str,
loc: Tuple[float, float, float],
rot: Tuple[float, float, float],
key_frame: int = 0,
key_type: str = "CONSTANT",
) -> None:
binding: unreal.SequencerBindingProxy = sequence.find_binding_by_name(key)
set_transform_by_binding(binding, loc, rot, key_frame, key_type)
def add_property_bool_track_to_binding(
binding: unreal.SequencerBindingProxy,
property_name: str,
property_value: bool,
bool_track: Optional[unreal.MovieSceneBoolTrack] = None,
) -> unreal.MovieSceneBoolTrack:
if bool_track is None:
# add bool track
bool_track: unreal.MovieSceneBoolTrack = binding.add_track(unreal.MovieSceneBoolTrack)
bool_track.set_property_name_and_path(property_name, property_name)
# add bool section, and set it to extend the whole sequence
bool_section = bool_track.add_section()
bool_section.set_start_frame_bounded(0)
bool_section.set_end_frame_bounded(0)
# set key
for channel in bool_section.find_channels_by_type(unreal.MovieSceneScriptingBoolChannel):
channel.set_default(property_value)
return bool_track
def add_property_int_track_to_binding(
binding: unreal.SequencerBindingProxy,
property_name: str,
property_value: int,
int_track: Optional[unreal.MovieSceneIntegerTrack] = None,
) -> unreal.MovieSceneIntegerTrack:
if int_track is None:
# add int track
int_track: unreal.MovieSceneIntegerTrack = binding.add_track(unreal.MovieSceneIntegerTrack)
int_track.set_property_name_and_path(property_name, property_name)
# add int section, and set it to extend the whole sequence
int_section = int_track.add_section()
int_section.set_start_frame_bounded(0)
int_section.set_end_frame_bounded(0)
# set key
for channel in int_section.find_channels_by_type(unreal.MovieSceneScriptingIntegerChannel):
channel.set_default(property_value)
return int_track
def add_property_float_track_to_binding(
binding: unreal.SequencerBindingProxy,
property_name: str,
property_value: float,
float_track: Optional[unreal.MovieSceneFloatTrack] = None,
) -> unreal.MovieSceneFloatTrack:
if float_track is None:
# add float track
float_track: unreal.MovieSceneFloatTrack = binding.add_track(unreal.MovieSceneFloatTrack)
float_track.set_property_name_and_path(property_name, property_name)
# add float section, and set it to extend the whole sequence
float_section = float_track.add_section()
float_section.set_start_frame_bounded(0)
float_section.set_end_frame_bounded(0)
# set key
for channel in float_section.find_channels_by_type(unreal.MovieSceneScriptingFloatChannel):
channel.set_default(property_value)
return float_section
def add_transform_to_binding(
binding: unreal.SequencerBindingProxy,
actor_loc: Tuple[float, float, float],
actor_rot: Tuple[float, float, float],
seq_end_frame: int,
seq_start_frame: int=0,
time: int = 0,
key_type: str = "CONSTANT",
) -> unreal.MovieScene3DTransformTrack:
"""Add a transform track to the binding, and add one key at `time` to the track.
Args:
binding (unreal.SequencerBindingProxy): The binding to add the track to.
actor_loc (Tuple[float, float, float]): The location of the actor.
actor_rot (Tuple[float, float, float]): The rotation of the actor.
seq_end_frame (int): The end frame of the sequence.
seq_start_frame (int, optional): The start frame of the sequence. Defaults to 0.
time (int, optional): The time of the key. Defaults to 0.
key_type (str, optional): The type of the key. Defaults to "CONSTANT".
Returns:
transform_track (unreal.MovieScene3DTransformTrack): The transform track.
"""
transform_track: unreal.MovieScene3DTransformTrack = binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section: unreal.MovieScene3DTransformSection = transform_track.add_section()
transform_section.set_end_frame(seq_end_frame)
transform_section.set_start_frame(seq_start_frame)
set_transform_by_section(transform_section, actor_loc, actor_rot, time, key_type)
return transform_track
def add_transforms_to_binding(
binding: unreal.SequencerBindingProxy,
actor_trans_keys: List[SequenceKey],
key_type: str = "CONSTANT",
) -> unreal.MovieScene3DTransformTrack:
transform_track: unreal.MovieScene3DTransformTrack = binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section: unreal.MovieScene3DTransformSection = transform_track.add_section()
# set infinite
transform_section.set_start_frame_bounded(0)
transform_section.set_end_frame_bounded(0)
# add keys
set_transforms_by_section(transform_section, actor_trans_keys, key_type)
return transform_track
def add_animation_to_binding(
binding: unreal.SequencerBindingProxy,
animation_asset: unreal.AnimSequence,
animation_length: Optional[int]=None,
seq_fps: Optional[float]=None,
) -> None:
animation_track: unreal.MovieSceneSkeletalAnimationTrack = binding.add_track(
track_type=unreal.MovieSceneSkeletalAnimationTrack
)
animation_section: unreal.MovieSceneSkeletalAnimationSection = animation_track.add_section()
animation_length_ = get_animation_length(animation_asset, seq_fps)
if animation_length is None:
animation_length = animation_length_
if animation_length > animation_length_:
unreal.log_error(f"animation: '{animation_asset.get_name()}' length is too short, it will repeat itself!")
params = unreal.MovieSceneSkeletalAnimationParams()
params.set_editor_property("Animation", animation_asset)
animation_section.set_editor_property("Params", params)
animation_section.set_range(0, animation_length)
def get_spawnable_actor_from_binding(
sequence: unreal.MovieSceneSequence,
binding: unreal.SequencerBindingProxy,
) -> unreal.Actor:
binds = unreal.Array(unreal.SequencerBindingProxy)
binds.append(binding)
bound_objects: List[unreal.SequencerBoundObjects] = unreal.SequencerTools.get_bound_objects(
get_world(),
sequence,
binds,
sequence.get_playback_range()
)
actor = bound_objects[0].bound_objects[0]
return actor
################################################################################
# high level functions
def add_level_visibility_to_sequence(
sequence: unreal.LevelSequence,
seq_length: Optional[int]=None,
) -> None:
if seq_length is None:
seq_length = sequence.get_playback_end()
# add master track (level visibility) to sequence
level_visibility_track: unreal.MovieSceneLevelVisibilityTrack = sequence.add_master_track(unreal.MovieSceneLevelVisibilityTrack)
# add level visibility section
level_visible_section: unreal.MovieSceneLevelVisibilitySection = level_visibility_track.add_section()
level_visible_section.set_visibility(unreal.LevelVisibility.VISIBLE)
level_visible_section.set_start_frame(-1)
level_visible_section.set_end_frame(seq_length)
level_hidden_section: unreal.MovieSceneLevelVisibilitySection = level_visibility_track.add_section()
level_hidden_section.set_row_index(1)
level_hidden_section.set_visibility(unreal.LevelVisibility.HIDDEN)
level_hidden_section.set_start_frame(-1)
level_hidden_section.set_end_frame(seq_length)
return level_visible_section, level_hidden_section
def add_level_to_sequence(
sequence: unreal.LevelSequence,
persistent_level_path: str,
new_level_path: str,
seq_fps: Optional[float]=None,
seq_length: Optional[int]=None,
) -> None:
"""creating a new level which contains the persistent level as sub-levels.
`CAUTION`: this function can't support `World Partition` type level which is new in unreal 5.
No warning/error would be printed if `World partition` is used, but it will not work.
Args:
sequence (unreal.LevelSequence): _description_
persistent_level_path (str): _description_
new_level_path (str): _description_
seq_fps (Optional[float], optional): _description_. Defaults to None.
seq_length (Optional[int], optional): _description_. Defaults to None.
"""
# get sequence settings
if seq_fps is None:
seq_fps = get_sequence_fps(sequence)
if seq_length is None:
seq_length = sequence.get_playback_end()
# create a new level to place actors
success = new_world(new_level_path)
print(f"new level: '{new_level_path}' created: {success}")
assert success, RuntimeError("Failed to create level")
level_visible_names, level_hidden_names = add_levels(persistent_level_path, new_level_path)
level_visible_section, level_hidden_section = add_level_visibility_to_sequence(sequence, seq_length)
# set level visibility
level_visible_section.set_level_names(level_visible_names)
level_hidden_section.set_level_names(level_hidden_names)
# set created level as current level
world = get_world()
levels = get_levels(world)
unreal.SF_BlueprintFunctionLibrary.set_level(world, levels[0])
save_current_level()
def add_spawnable_camera_to_sequence(
sequence: unreal.LevelSequence,
camera_trans: List[SequenceKey],
camera_class: Type[unreal.CameraActor]=unreal.CameraActor,
camera_fov: float=90.,
seq_length: Optional[int]=None,
key_type: str="CONSTANT",
) -> None:
# get sequence settings
if seq_length is None:
seq_length = sequence.get_playback_end()
# create a camera actor & add it to the sequence
camera_binding = sequence.add_spawnable_from_class(camera_class)
camera_actor = get_spawnable_actor_from_binding(sequence, camera_binding)
camera_component_binding = sequence.add_possessable(camera_actor.camera_component)
camera_component_binding.set_parent(camera_binding)
# set the camera FOV
add_property_float_track_to_binding(camera_component_binding, 'FieldOfView', camera_fov)
# add master track (camera) to sequence
camera_cut_track = sequence.add_master_track(unreal.MovieSceneCameraCutTrack)
# add a camera cut track for this camera, make sure the camera cut is stretched to the -1 mark
camera_cut_section = camera_cut_track.add_section()
camera_cut_section.set_start_frame(-1)
camera_cut_section.set_end_frame(seq_length)
# set the camera cut to use this camera
camera_binding_id = unreal.MovieSceneObjectBindingID()
camera_binding_id.set_editor_property("Guid", camera_binding.get_id())
camera_cut_section.set_editor_property("CameraBindingID", camera_binding_id)
# camera_binding_id = sequence.make_binding_id(camera_binding, unreal.MovieSceneObjectBindingSpace.LOCAL)
# camera_cut_section.set_camera_binding_id(camera_binding_id)
# set the camera location and rotation
add_transforms_to_binding(camera_binding, camera_trans, key_type)
def add_spawnable_actor_to_sequence(
sequence: unreal.LevelSequence,
actor_asset: Union[unreal.SkeletalMesh, unreal.StaticMesh],
actor_trans: List[SequenceKey],
actor_id: Optional[str]=None,
actor_stencil_value: int=1,
animation_asset: Optional[unreal.AnimSequence]=None,
seq_fps: Optional[float]=None,
seq_length: Optional[int]=None,
key_type: str="CONSTANT",
) -> unreal.Actor:
# get sequence settings
if seq_fps is None:
seq_fps = get_sequence_fps(sequence)
if seq_length is None:
seq_length = get_animation_length(animation_asset, seq_fps)
# add actor to sequence
actor_binding = sequence.add_spawnable_from_instance(actor_asset)
actor = get_spawnable_actor_from_binding(sequence, actor_binding)
# mesh_component = actor.skeletal_mesh_component
mesh_component = get_actor_mesh_component(actor)
mesh_component_binding = sequence.add_possessable(mesh_component)
# set stencil value
add_property_bool_track_to_binding(mesh_component_binding, 'bRenderCustomDepth', True)
add_property_int_track_to_binding(mesh_component_binding, 'CustomDepthStencilValue', actor_stencil_value)
if actor_id:
actor_binding.set_name(actor_id)
# add transform
add_transforms_to_binding(actor_binding, actor_trans, key_type)
# add animation
if animation_asset:
add_animation_to_binding(actor_binding, animation_asset, seq_length, seq_fps)
return actor
def generate_sequence(
sequence_dir: str,
sequence_name: str,
seq_fps: float,
seq_length: int,
) -> unreal.LevelSequence:
asset_tools: unreal.AssetTools = unreal.AssetToolsHelpers.get_asset_tools() # type: ignore
new_sequence: unreal.LevelSequence = asset_tools.create_asset(
sequence_name,
sequence_dir,
unreal.LevelSequence,
unreal.LevelSequenceFactoryNew(),
)
assert (new_sequence is not None), f"Failed to create LevelSequence: {sequence_dir}, {sequence_name}"
# Set sequence config
new_sequence.set_display_rate(unreal.FrameRate(seq_fps))
new_sequence.set_playback_end(seq_length)
return new_sequence
def generate_train_box(line1, line2, z, current_frame):
x11, y11, x12, y12=line1
x21, y21, x22, y22=line2
assert(y11==y12)
assert(y21==y22)
assert(x11==x21)
assert(x12==x22)
w=math.dist([x11, y11], [x12, y12])
h=math.dist([x11, y11], [x21, y21])
interval=4000 # train interval
w_instance=int(w/interval)+2
h_instance=int(h/interval)+1
x_start=np.linspace(x11, x12, w_instance)
y_start=np.linspace(y11, y12, w_instance)
x_end=np.linspace(x21, x22, w_instance)
y_end=np.linspace(y21, y22, w_instance)
camera_trans=[]
# train
if z>25000:
pitch=-60
else:
pitch=-45
for i in range(w_instance):
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_start[i], y_start[i], z),
rotation=(0, pitch, 0)
)
)
current_frame=current_frame+h_instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_end[i], y_end[i], z),
rotation=(0, pitch, 0)
)
)
current_frame=current_frame+1
for i in range(w_instance):
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_start[i], y_start[i], z),
rotation=(0, pitch, 90)
)
)
current_frame=current_frame+h_instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_end[i], y_end[i], z),
rotation=(0, pitch, 90)
)
)
current_frame=current_frame+1
for i in range(w_instance):
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_start[i], y_start[i], z),
rotation=(0, pitch, 180)
)
)
current_frame=current_frame+h_instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_end[i], y_end[i], z),
rotation=(0, pitch, 180)
)
)
current_frame=current_frame+1
for i in range(w_instance):
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_start[i], y_start[i], z),
rotation=(0, pitch, 270)
)
)
current_frame=current_frame+h_instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_end[i], y_end[i], z),
rotation=(0, pitch, 270)
)
)
current_frame=current_frame+1
return camera_trans, current_frame
def generate_test_box(line1, line2, z, current_frame):
x11, y11, x12, y12=line1
x21, y21, x22, y22=line2
assert(y11==y12)
assert(y21==y22)
assert(x11==x21)
assert(x12==x22)
w=math.dist([x11, y11], [x12, y12])
h=math.dist([x11, y11], [x21, y21])
interval=4501 # test interval
w_instance=int(w/interval)+2
h_instance=int(h/interval)+1
x_start=np.linspace(x11, x12, w_instance)
y_start=np.linspace(y11, y12, w_instance)
x_end=np.linspace(x21, x22, w_instance)
y_end=np.linspace(y21, y22, w_instance)
camera_trans=[]
# test
for i in range(w_instance):
pitch=np.random.randint(-60,-44,size=1)
yaw=np.random.randint(0,361,size=1)
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_start[i], y_start[i], z),
rotation=(0, pitch, yaw)
)
)
current_frame=current_frame+h_instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(x_end[i], y_end[i], z),
rotation=(0, pitch, yaw)
)
)
current_frame=current_frame+1
return camera_trans, current_frame
def generate_train_line(point1, point2, z, yaw, current_frame, dense=False):
distance=math.dist(point1, point2)
if dense==True:
instance=int(distance/100)+1 # dense
else:
instance=int(distance/500)+1 # sparse
camera_trans=[]
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 0, yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 0, yaw)
)
)
current_frame=current_frame+1
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 0, 90+yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 0, 90+yaw)
)
)
current_frame=current_frame+1
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 0, 180+yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 0, 180+yaw)
)
)
current_frame=current_frame+1
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 0, 270+yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 0, 270+yaw)
)
)
current_frame=current_frame+1
# camera_trans.append(
# SequenceKey(
# frame=current_frame,
# location=(point1[0], point1[1], z),
# rotation=(0, -90, yaw)
# )
# )
# current_frame=current_frame+instance
# camera_trans.append(
# SequenceKey(
# frame=current_frame,
# location=(point2[0], point2[1], z),
# rotation=(0, -90, yaw)
# )
# )
# current_frame=current_frame+1
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 90, yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 90, yaw)
)
)
current_frame=current_frame+1
return camera_trans, current_frame
def generate_test_line(point1, point2, z, yaw, current_frame):
# for test
point1[0]=point1[0]+math.cos(math.radians(yaw))*570
point1[1]=point1[1]+math.sin(math.radians(yaw))*570
point2[0]=point2[0]-math.cos(math.radians(yaw))*570
point2[1]=point2[1]-math.sin(math.radians(yaw))*570
yaw=np.random.randint(0,90,size=1)
distance=math.dist(point1, point2)
instance = int(distance/4830)+1 # test
camera_trans=[]
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 0, yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 0, yaw)
)
)
current_frame=current_frame+1
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 0, 90+yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 0, 90+yaw)
)
)
current_frame=current_frame+1
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 0, 180+yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 0, 180+yaw)
)
)
current_frame=current_frame+1
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 0, 270+yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 0, 270+yaw)
)
)
current_frame=current_frame+1
# camera_trans.append(
# SequenceKey(
# frame=current_frame,
# location=(point1[0], point1[1], z),
# rotation=(0, -90, yaw)
# )
# )
# current_frame=current_frame+instance
# camera_trans.append(
# SequenceKey(
# frame=current_frame,
# location=(point2[0], point2[1], z),
# rotation=(0, -90, yaw)
# )
# )
# current_frame=current_frame+1
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point1[0], point1[1], z),
rotation=(0, 90, yaw)
)
)
current_frame=current_frame+instance
camera_trans.append(
SequenceKey(
frame=current_frame,
location=(point2[0], point2[1], z),
rotation=(0, 90, yaw)
)
)
current_frame=current_frame+1
return camera_trans, current_frame
def main():
from datetime import datetime
# pre-defined
level = '/project/' # the path of map.
sequence_dir = '/project/'
seq_fps = 30
current_frame=0
# exmaples for generating training set for aerial data
sequence_name='aerial_train'
fov=45
camera_trans, current_frame=generate_train_box([-100000, 0, -12000, 0], [-100000, 38000, -12000, 38000], 15000, current_frame) # block 1
# exmaples for generating testing set for aerial data
# sequence_name='aerial_test'
# fov=45
# camera_trans, current_frame=generate_test_box([-95000, 5000,-17000, 5000], [-95000, 33000, -17000, 33000], 15000, current_frame) # block 1 test
# exmaples for generating training(sparse) set for street data
# sequence_name='street_train'
# fov=90
# camera_trans=[]
# tmp_camera_trans, current_frame=generate_train_line([-85151.664062, 7755.524902], [-18491.283203, 46241.914062], 300, 30, current_frame)
# camera_trans.extend(tmp_camera_trans)
# tmp_camera_trans, current_frame=generate_train_line([-19102.925781, 46310.578125], [-10849.427734, 49813.980469], 300, 23, current_frame)
# camera_trans.extend(tmp_camera_trans)
# exmaples for generating training(dense) set for street data
# sequence_name='street_train_dense'
# fov=90
# camera_trans=[]
# tmp_camera_trans, current_frame=generate_train_line([-85151.664062, 7755.524902], [-18491.283203, 46241.914062], 300, 30, current_frame, dense=True)
# camera_trans.extend(tmp_camera_trans)
# tmp_camera_trans, current_frame=generate_train_line([-19102.925781, 46310.578125], [-10849.427734, 49813.980469], 300, 23, current_frame, dense=True)
# camera_trans.extend(tmp_camera_trans)
# exmaples for generating testing set for street data
# sequence_name='street_test'
# fov=90
# camera_trans=[]
# tmp_camera_trans, current_frame=generate_test_line([-85151.664062, 7755.524902], [-18491.283203, 46241.914062], 300, 30, current_frame)
# camera_trans.extend(tmp_camera_trans)
# tmp_camera_trans, current_frame=generate_test_line([-19102.925781, 46310.578125], [-10849.427734, 49813.980469], 300, 23, current_frame)
# camera_trans.extend(tmp_camera_trans)
seq_length=current_frame
new_sequence = generate_sequence(sequence_dir, sequence_name, seq_fps, seq_length)
add_spawnable_camera_to_sequence(
new_sequence,
camera_trans=camera_trans,
camera_class=unreal.CineCameraActor,
camera_fov=fov,
seq_length=seq_length,
key_type="LINEAR"
)
unreal.EditorAssetLibrary.save_loaded_asset(new_sequence, False)
return level, f'{sequence_dir}/{sequence_name}'
if __name__ == "__main__":
main()
|
# /project/
# @CBgameDev Optimisation Script - Log Materials Using Translucency
# /project/
import unreal
import os
EditAssetLib = unreal.EditorAssetLibrary()
workingPath = "/Game/" # Using the root directory
notepadFilePath = os.path.dirname(__file__) + "//PythonOptimiseLog.txt"
allAssets = EditAssetLib.list_assets(workingPath, True, False)
selectedAssetsPath = workingPath
LogStringsArray = []
numOfOptimisations = 0
with unreal.ScopedSlowTask(len(allAssets), selectedAssetsPath) as ST:
ST.make_dialog(True)
for asset in allAssets:
_assetData = EditAssetLib.find_asset_data(asset)
_assetName = _assetData.get_asset().get_name()
_assetPathName = _assetData.get_asset().get_path_name()
_assetClassName = _assetData.get_asset().get_class().get_name()
if _assetClassName == "Material":
_MaterialAsset = unreal.Material.cast(_assetData.get_asset())
# unreal.log(_MaterialAsset.blend_mode)
if _MaterialAsset.blend_mode == unreal.BlendMode.BLEND_TRANSLUCENT:
LogStringsArray.append(" %s ------------> At Path: %s \n" % (_assetName, _assetPathName))
# unreal.log("Asset Name: %s Path: %s \n" % (_assetName, _assetPathName))
# unreal.log("is a translucent material")
numOfOptimisations += 1
"""
# material instances have no blend mode stuff exposed atm so cant do this
elif _assetClassName == "MaterialInstanceConstant":
asset_obj = EditAssetLib.load_asset(asset)
_MaterialInstanceAsset = unreal.MaterialInstance.cast(_assetData.get_asset())
# unreal.log(_MaterialAsset.blend_mode)
if _MaterialInstanceAsset.blend_mode == unreal.BlendMode.BLEND_TRANSLUCENT:
LogStringsArray.append(" [MIC] %s ------------> At Path: %s \n" % (_assetName, _assetPathName))
# unreal.log("Asset Name: %s Path: %s \n" % (_assetName, _assetPathName))
# unreal.log("is a translucent material instance")
numOfOptimisations += 1
"""
if ST.should_cancel():
break
ST.enter_progress_frame(1, asset)
# Write results into a log file
# /project/
TitleOfOptimisation = "Log Materials Using Translucency"
DescOfOptimisation = "Searches the entire project for materials that are using Translucency (master materials only, does not check material instances)"
SummaryMessageIntro = "-- Materials Using Translucency --"
if unreal.Paths.file_exists(notepadFilePath): # Check if txt file already exists
os.remove(notepadFilePath) # if does remove it
# Create new txt file and run intro text
file = open(notepadFilePath, "a+") # we should only do this if have a count?
file.write("OPTIMISING SCRIPT by @CBgameDev \n")
file.write("==================================================================================================== \n")
file.write(" SCRIPT NAME: %s \n" % TitleOfOptimisation)
file.write(" DESCRIPTION: %s \n" % DescOfOptimisation)
file.write("==================================================================================================== \n \n")
if numOfOptimisations <= 0:
file.write(" -- NONE FOUND -- \n \n")
else:
for i in range(len(LogStringsArray)):
file.write(LogStringsArray[i])
# Run summary text
file.write("\n")
file.write("======================================================================================================= \n")
file.write(" SUMMARY: \n")
file.write(" %s \n" % SummaryMessageIntro)
file.write(" Found: %s \n \n" % numOfOptimisations)
file.write("======================================================================================================= \n")
file.write(" Logged to %s \n" % notepadFilePath)
file.write("======================================================================================================= \n")
file.close()
os.startfile(notepadFilePath) # Trigger the notepad file to open
|
from asyncio.windows_events import NULL
import unreal
def get_selected_asset_dir() -> str :
ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets()
if len(ar_asset_lists) > 0 :
str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0])
path = str_selected_asset.rsplit('/', 1)[0]
else :
path = ''
return path
# listing #
li_skeletal_meshs :list = unreal.EditorUtilityLibrary.get_selected_assets()
BP_dir :str = '/project/' # edit here when run
BP_origin :str = 'BP_Fish_Origin' # edit here when run
# listing end #
# execute #
if len(li_skeletal_meshs) > 0 :
for each in li_skeletal_meshs :
dir = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(each)
name = dir.rsplit('.',1)[1]
unreal.EditorAssetLibrary.duplicate_asset( BP_dir + '/' + BP_origin , BP_dir + '/' + 'BP_' + name )
# execute end #
# li_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
# for each in li_actors :
# SBSkeletalMeshComp = each.get_component_by_class(unreal.SBSkeletalMeshComponent)
# SBSkeletalMeshComp.set_editor_property('skeletal_mesh', li_skeletal_meshs[2])
# aa.EditorAssetLibrary.set_editor_property('skeletal_mesh', NULL)
|
import unreal
# instances of unreal classes
editor_util = unreal.EditorUtilityLibrary()
layer_sys = unreal.LayersSubsystem()
editor_filter_lib = unreal.EditorFilterLibrary()
# get the selected material and selected static mesh actors
selected_assets = editor_util.get_selected_assets()
materials = editor_filter_lib.by_class(selected_assets, unreal.Material)
if len(materials) < 1:
unreal.log_warning("Please select the to be assigned material")
else:
material = materials[0]
material_name = material.get_fname()
actors = layer_sys.get_selected_actors()
static_mesh_actors = editor_filter_lib.by_class(actors, unreal.StaticMeshActor)
for actor in static_mesh_actors:
actor_name = actor.get_fname()
#get the static mesh component and assign the material
actor_mesh_component = actor.static_mesh_component
actor_mesh_component.set_material(0, material)
unreal.log("Assigning material '{}' to actor {}".format(material_name, actor_name))
|
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 12 20:04:41 2024
@author: WillQuantique
"""
import unreal
all_actors = unreal.EditorLevelLibrary.get_all_level_actors()
# Initialize variable to store the desired skeletal mesh component
skeletal_mesh_component = None
# Loop through all objects in the level sequence
for actor in all_actors:
# Check if the actor's name contains "007"
if "007" in actor.get_name():
# Get all components of the actor
components = actor.get_components_by_class(unreal.SkeletalMeshComponent)
# Loop through all components
for component in components:
# Check if the component's name contains "Face"
if "Face" in component.get_name():
# Store the component in the variable
skeletal_mesh_component = component
break
# Check if the skeletal mesh component was found
if skeletal_mesh_component is not None:
print(f"Found the skeletal mesh component: {skeletal_mesh_component.get_name()}")
else:
print("No matching skeletal mesh component was found.")
rig.set_editor_property('skeletal_mesh', new_skeletal_mesh)
|
# coding: utf-8
from asyncio.windows_events import NULL
import unreal
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
parser.add_argument("-meta")
args = parser.parse_args()
print(args.vrm)
reg = unreal.AssetRegistryHelpers.get_asset_registry();
##
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
#rig = rigs[10]
hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig)
h_con = hierarchy.get_controller()
r_con = rig.get_controller()
graph = r_con.get_graph()
node = graph.get_nodes()
for e in hierarchy.get_controls(True):
h_con.remove_element(e)
for e in hierarchy.get_nulls(True):
h_con.remove_element(e)
boneCount = 0
for e in hierarchy.get_bones():
p = hierarchy.get_first_parent(e)
print('===')
print(e)
print(p)
t = unreal.Transform()
s = unreal.RigControlSettings()
s.shape_visible = False
v = unreal.RigControlValue()
shape_t = unreal.Transform(location=[0.0, 0.0, 0.0], rotation=[0.0, 0.0, 0.0], scale=[0.001, 0.001, 0.001])
if (boneCount == 0):
n = h_con.add_null("{}_s".format(e.name), unreal.RigElementKey(), t)
c = h_con.add_control(e.name, n, s, v)
t = hierarchy.get_global_transform(n)
hierarchy.set_global_transform(c, t, True)
hierarchy.set_control_shape_transform(c, shape_t, True)
else:
p.type = unreal.RigElementType.CONTROL
n = h_con.add_null("{}_s".format(e.name), p, t)
c = h_con.add_control(e.name, n, s, v)
t = hierarchy.get_global_transform(n)
hierarchy.set_global_transform(c, t, True)
hierarchy.set_control_shape_transform(c, shape_t, True)
if ("{}".format(e.name) == "head"):
parent = c
n = h_con.add_null("eye_l_s", parent, t)
c = h_con.add_control("eye_l", n, s, v)
t = hierarchy.get_global_transform(n)
hierarchy.set_global_transform(c, t, True)
hierarchy.set_control_shape_transform(c, shape_t, True)
n = h_con.add_null("eye_r_s", parent, t)
c = h_con.add_control("eye_r", n, s, v)
t = hierarchy.get_global_transform(n)
hierarchy.set_global_transform(c, t, True)
hierarchy.set_control_shape_transform(c, shape_t, True)
boneCount += 1
|
import unreal
""" Should be used with internal UE Python API
Replace all actors of given asset in the level by another asset, saving coords, rotation and scale"""
level_actors = unreal.EditorLevelLibrary.get_all_level_actors()
asset_to_replace_from = "/project/" \
"SM_PROP_AMB_EnergyCell_01_a.SM_PROP_AMB_EnergyCell_01_a"
asset_to_replace_to = "/project/" \
"B_WA_VaultOver_Low_AmbEnergyCell_1A.B_WA_VaultOver_Low_AmbEnergyCell_1A"
actors_to_replace = []
for actor in level_actors:
if (isinstance(actor, unreal.StaticMeshActor)):
if not actor.static_mesh_component or not actor.static_mesh_component.static_mesh:
continue
asset_path = actor.static_mesh_component.static_mesh.get_path_name()
if asset_path == asset_to_replace_from:
actors_to_replace.append(
(actor, actor.get_actor_location(), actor.get_actor_rotation(), actor.get_actor_scale3d()))
new_asset = unreal.EditorAssetLibrary.find_asset_data(asset_to_replace_to).get_asset()
for i in reversed(range(len(actors_to_replace))):
actor, loc, rot, scale = actors_to_replace[i]
unreal.EditorLevelLibrary.destroy_actor(actor)
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(new_asset, loc, rot)
actor.set_actor_scale3d(scale)
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import math
import unreal
@unreal.uclass()
class CurveInputExample(unreal.PlacedEditorUtilityBase):
# Use a FProperty to hold the reference to the API wrapper we create in
# run_curve_input_example
_asset_wrapper = unreal.uproperty(unreal.HoudiniPublicAPIAssetWrapper)
@unreal.ufunction(meta=dict(BlueprintCallable=True, CallInEditor=True))
def run_curve_input_example(self):
# Get the API instance
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
# Ensure we have a running session
if not api.is_session_valid():
api.create_session()
# Load our HDA uasset
example_hda = unreal.load_object(None, '/project/.copy_to_curve_1_0')
# Create an API wrapper instance for instantiating the HDA and interacting with it
wrapper = api.instantiate_asset(example_hda, instantiate_at=unreal.Transform())
if wrapper:
# Pre-instantiation is the earliest point where we can set parameter values
wrapper.on_pre_instantiation_delegate.add_function(self, '_set_initial_parameter_values')
# Jumping ahead a bit: we also want to configure inputs, but inputs are only available after instantiation
wrapper.on_post_instantiation_delegate.add_function(self, '_set_inputs')
# Jumping ahead a bit: we also want to print the outputs after the node has cook and the plug-in has processed the output
wrapper.on_post_processing_delegate.add_function(self, '_print_outputs')
self.set_editor_property('_asset_wrapper', wrapper)
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _set_initial_parameter_values(self, in_wrapper):
""" Set our initial parameter values: disable upvectorstart and set the scale to 0.2. """
# Uncheck the upvectoratstart parameter
in_wrapper.set_bool_parameter_value('upvectoratstart', False)
# Set the scale to 0.2
in_wrapper.set_float_parameter_value('scale', 0.2)
# Since we are done with setting the initial values, we can unbind from the delegate
in_wrapper.on_pre_instantiation_delegate.remove_function(self, '_set_initial_parameter_values')
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _set_inputs(self, in_wrapper):
""" Configure our inputs: input 0 is a cube and input 1 a helix. """
# Create an empty geometry input
geo_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIGeoInput)
# Load the cube static mesh asset
cube = unreal.load_object(None, '/project/.Cube')
# Set the input object array for our geometry input, in this case containing only the cube
geo_input.set_input_objects((cube, ))
# Set the input on the instantiated HDA via the wrapper
in_wrapper.set_input_at_index(0, geo_input)
# Create a curve input
curve_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPICurveInput)
# Create a curve wrapper/helper
curve_object = unreal.HoudiniPublicAPICurveInputObject(curve_input)
# Make it a Nurbs curve
curve_object.set_curve_type(unreal.HoudiniPublicAPICurveType.NURBS)
# Set the points of the curve, for this example we create a helix
# consisting of 100 points
curve_points = []
for i in range(100):
t = i / 20.0 * math.pi * 2.0
x = 100.0 * math.cos(t)
y = 100.0 * math.sin(t)
z = i
curve_points.append(unreal.Transform([x, y, z], [0, 0, 0], [1, 1, 1]))
curve_object.set_curve_points(curve_points)
# Set the curve wrapper as an input object
curve_input.set_input_objects((curve_object, ))
# Copy the input data to the HDA as node input 1
in_wrapper.set_input_at_index(1, curve_input)
# unbind from the delegate, since we are done with setting inputs
in_wrapper.on_post_instantiation_delegate.remove_function(self, '_set_inputs')
@unreal.ufunction(params=[unreal.HoudiniPublicAPIAssetWrapper], meta=dict(CallInEditor=True))
def _print_outputs(self, in_wrapper):
""" Print the outputs that were generated by the HDA (after a cook) """
num_outputs = in_wrapper.get_num_outputs()
print('num_outputs: {}'.format(num_outputs))
if num_outputs > 0:
for output_idx in range(num_outputs):
identifiers = in_wrapper.get_output_identifiers_at(output_idx)
print('\toutput index: {}'.format(output_idx))
print('\toutput type: {}'.format(in_wrapper.get_output_type_at(output_idx)))
print('\tnum_output_objects: {}'.format(len(identifiers)))
if identifiers:
for identifier in identifiers:
output_object = in_wrapper.get_output_object_at(output_idx, identifier)
output_component = in_wrapper.get_output_component_at(output_idx, identifier)
is_proxy = in_wrapper.is_output_current_proxy_at(output_idx, identifier)
print('\t\tidentifier: {}'.format(identifier))
print('\t\toutput_object: {}'.format(output_object.get_name() if output_object else 'None'))
print('\t\toutput_component: {}'.format(output_component.get_name() if output_component else 'None'))
print('\t\tis_proxy: {}'.format(is_proxy))
print('')
def run():
# Spawn CurveInputExample and call run_curve_input_example
curve_input_example_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(CurveInputExample.static_class(), unreal.Vector.ZERO, unreal.Rotator())
curve_input_example_actor.run_curve_input_example()
if __name__ == '__main__':
run()
|
import unreal
import os
import scripts.popUp as popUp
#########################################################################################################
# UEFileManager #
#########################################################################################################
class UEFileFunctionalities:
"""
Class for Unreal Engine file functionalities.
This class provides methods to interact with files and directories within an Unreal Engine project.
Methods:
- get_all_files_in_directory(self, directory): Get all files from a single directory (non-recursively).
- get_project_path(self): Get the project path.
- fetch_files_from_dir_in_project(self, dir, project_path): Fetch files from a directory in the project.
"""
def __init__(self):
pass
def get_all_files_in_directory(self, directory):
"""
Get all files from a single directory (non-recursively).
Args:
- directory (str): The directory path.
Returns:
- files_list (list): A list of file names in the directory.
"""
files_list = []
# Check if the directory exists
if os.path.exists(directory) and os.path.isdir(directory):
# List all files in the directory
files_list = [
f
for f in os.listdir(directory)
if os.path.isfile(os.path.join(directory, f))
]
else:
popUp.show_popup_message("UEFileManager", "Not a valid dir")
return files_list
def get_project_path(self):
"""
Get the project path.
Returns:
- project_path (str): The project path in normal Windows path form.
"""
project_path = unreal.Paths.project_dir().rstrip("/")
return project_path.split("../")[-1]
def fetch_files_from_dir_in_project(self, dir, project_path, mode="windows"):
"""
Fetch files from a directory in the project.
Args:
- dir (str): The directory path within the project.
- project_path (str): The project path.
Returns:
- files_list (list): A list of file names in the directory.
"""
# Check if the UE path exists in the project
if unreal.EditorAssetLibrary.does_directory_exist(dir + "/"):
if "/Game" in dir:
# Get the complete path in windows form
complete_path = (
"C:/" + project_path + "/Content" + dir.split("/Game")[1]
)
else:
complete_path = "C:/" + project_path + "/Content" + dir
if mode == "windows":
files = [
complete_path + "/" + file
for file in self.get_all_files_in_directory(complete_path)
]
else:
files = [
dir + file
for file in self.get_all_files_in_directory(complete_path)
]
return files
return []
|
import unreal
# instances of unreal classes
editor_asset_lib = unreal.EditorAssetLibrary()
# set source dir and options
source_dir = "/project/"
include_subfolders = True
deleted = 0
# get all assets in source dir
assets = editor_asset_lib.list_assets(source_dir, recursive=include_subfolders, include_folder=True)
folders = [asset for asset in assets if editor_asset_lib.does_directory_exist(asset)]
for folder in folders:
# check if folder has assets
has_assets = editor_asset_lib.does_directory_have_assets(folder)
if not has_assets:
# delete folder
editor_asset_lib.delete_directory(folder)
deleted += 1
unreal.log("Folder {} without assets was deleted".format(folder))
unreal.log("Deleted {} folders without assets".format(deleted))
|
# -*- coding: utf-8 -*-
import unreal
import os
from Utilities.Utils import Singleton
from Utilities.Utils import cast
import Utilities
import QueryTools
import re
import types
import collections
from .import Utils
global _r
COLUMN_COUNT = 2
class DetailData(object):
def __init__(self):
self.filter_str = ""
self.filteredIndexToIndex = []
self.hisCrumbObjsAndNames = [] #list[(obj, propertyName)]
self.attributes = None
self.filtered_attributes = None
self.plains = []
self.riches = []
self.selected = set()
def check_line_id(self, line_id, column_count):
from_line = line_id * column_count
to_line = (line_id + 1) * column_count
assert len(self.plains) == len(self.riches), "len(self.plains) != len(self.riches)"
if 0 <= from_line < len(self.plains) and 0 <= to_line <= len(self.plains):
return True
else:
unreal.log_error(f"Check Line Id Failed: {line_id}, plains: {len(self.plains)}, rich: {len(self.riches)}")
return False
def get_plain(self, line_id, column_count):
assert self.check_line_id(line_id, column_count), "check line id failed."
return self.plains[line_id * 2 : line_id * 2 + 2]
def get_rich(self, line_id, column_count):
assert self.check_line_id(line_id, column_count), "check line id failed."
return self.riches[line_id * 2: line_id * 2 + 2]
class ObjectDetailViewer(metaclass=Singleton):
def __init__(self, jsonPath):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.ui_checkbox_single_mode = "CheckBoxSingleMode"
self.ui_checkbox_compare_mode = "CheckBoxCompareMode"
self.ui_left_group = "LeftDetailGroup"
self.ui_right_group = "RightDetailGroup"
self.ui_button_refresh = "RefreshCompareButton"
self.ui_detailListLeft = "ListViewLeft"
self.ui_detailListRight = "ListViewRight"
self.ui_hisObjsBreadcrumbLeft = 'ObjectHisBreadcrumbLeft'
self.ui_hisObjsBreadcrumbRight = 'ObjectHisBreadcrumbRight'
# self.ui_headRowLeft = "HeaderRowLeft"
# self.ui_headRowRight = "HeaderRowRight"
self.ui_labelLeft = "LabelLeft"
self.ui_labelRight = "LabelRight"
self.ui_info_output = "InfoOutput"
self.ui_rightButtonsGroup = "RightButtonsGroup" # used for compare mode
self.ui_rightListGroup = "RightListGroup"
self.ui_refreshButtonGroup = "RefreshButtonGroup"
self.reset()
def on_close(self):
self.reset()
def on_map_changed(self, map_change_type_str):
# remove the reference, avoid memory leaking when load another map.
if map_change_type_str == "TearDownWorld":
self.reset(bResetParameter=False)
else:
pass # skip: LoadMap, SaveMap, NewMap
def reset(self, bResetParameter=True):
if bResetParameter:
self.showBuiltin = True
self.showOther = True
self.showProperties = True
self.showEditorProperties = True
self.showParamFunction = True
self.compareMode = False
self.left = None
self.right = None
self.leftSearchText = ""
self.rightSearchText = ""
self.left_rich = None
self.left_plain = None
self.var = None
self.diff_count = 0
self.clear_ui_info()
def clear_ui_info(self):
for text_ui in [self.ui_info_output, self.ui_labelLeft, self.ui_labelRight]:
self.data.set_text(text_ui, "")
self.data.set_list_view_multi_column_items(self.ui_detailListLeft, [], 2)
self.data.set_list_view_multi_column_items(self.ui_detailListRight, [], 2)
for ui_breadcrumb in [self.ui_hisObjsBreadcrumbRight, self.ui_hisObjsBreadcrumbLeft]:
crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb)
for i in range(crumbCount):
self.data.pop_breadcrumb_string(ui_breadcrumb)
def update_log_text(self, bRight):
bShowRight = self.compareMode
result = ""
for side_str in ["left", "right"] if bShowRight else ["left"]:
bRight = side_str != "left"
ui_breadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft
breadcrumbs = self.right.hisCrumbObjsAndNames if bRight else self.left.hisCrumbObjsAndNames
crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb)
if bRight:
result += "\t\t\t"
result += "{} crumb: {} hisObj: {}".format(side_str, crumbCount, len(breadcrumbs))
if self.compareMode:
result = f"{result}\t\t\tdiff count: {self.diff_count}"
self.data.set_text(self.ui_info_output, result)
def get_color_by(self, attr : Utils.attr_detail):
if attr.bCallable_builtin:
return "DarkTurquoise".lower()
if attr.bCallable_other:
return "RoyalBlue".lower()
if attr.bEditorProperty:
return "LimeGreen".lower()
if attr.bOtherProperty:
return "yellow"
def get_color(self, typeStr):
if typeStr == "property":
return 'white'
if typeStr == "return_type":
return 'gray'
if typeStr == "param":
return 'gray'
def get_name_with_rich_text(self, attr:Utils.attr_detail):
name_color = self.get_color_by(attr)
param_color = self.get_color("param")
return_type_color = self.get_color("return_type")
if attr.bProperty:
return "\t<RichText.{}>{}</>".format(name_color, attr.name)
else:
if attr.param_str:
return "\t<RichText.{}>{}(</><RichText.{}>{}</><RichText.{}>)</>".format(name_color, attr.name
, param_color, attr.param_str
, name_color)
else:
if attr.bCallable_other:
return "\t<RichText.{}>{}</>".format(name_color, attr.name)
else:
return "\t<RichText.{}>{}()</><RichText.{}> {}</>".format(name_color, attr.name
, return_type_color, attr.return_type_str)
def get_name_with_plain_text(self, attr:Utils.attr_detail):
if attr.bProperty:
return "\t{}".format(attr.name)
else:
if attr.param_str:
return "\t{}({})".format( attr.name, attr.param_str)
else:
if attr.bCallable_other:
return "\t{}".format( attr.name)
else:
return "\t{}() {}".format(attr.name,attr.return_type_str)
def filter(self, data:DetailData):
result = []
indices = []
for i, attr in enumerate(data.attributes):
if not self.showEditorProperties and attr.bEditorProperty:
continue
if not self.showProperties and attr.bOtherProperty:
continue
if not self.showParamFunction and attr.bHasParamFunction:
continue
if not self.showBuiltin and attr.bCallable_builtin:
continue
if not self.showOther and attr.bCallable_other:
continue
if data.filter_str:
if data.filter_str.lower() not in attr.display_result.lower() and data.filter_str not in attr.display_name.lower() :
continue
result.append(attr)
indices.append(i)
return result, indices
def show_data(self, data:DetailData, ui_listView):
flatten_list_items = []
flatten_list_items_plain = []
for i, attr in enumerate(data.filtered_attributes):
# print(f"{i}: {attr.name} {attr.display_name}, {attr.display_result} ")
attr.check()
assert attr.display_name, f"display name null {attr.display_name}"
assert isinstance(attr.display_result, str), f"display result null {attr.display_result}"
result_str = attr.display_result
if len(result_str) > 200:
result_str = result_str[:200] + "......"
flatten_list_items.extend([self.get_name_with_rich_text(attr), result_str])
flatten_list_items_plain.extend([self.get_name_with_plain_text(attr), result_str])
data.riches = flatten_list_items
data.plains = flatten_list_items_plain
data.selected.clear()
self.data.set_list_view_multi_column_items(ui_listView, flatten_list_items, 2)
def query_and_push(self, obj, propertyName, bPush, bRight): #bPush: whether add Breadcrumb nor not, call by property
if bRight:
ui_Label = self.ui_labelRight
ui_listView = self.ui_detailListRight
ui_breadcrumb = self.ui_hisObjsBreadcrumbRight
else:
ui_Label = self.ui_labelLeft
ui_listView = self.ui_detailListLeft
ui_breadcrumb = self.ui_hisObjsBreadcrumbLeft
data = self.right if bRight else self.left
data.attributes = Utils.ll(obj)
data.filtered_attributes, data.filteredIndexToIndex = self.filter(data)
self.show_data(data, ui_listView)
# set breadcrumb
if propertyName and len(propertyName) > 0:
label = propertyName
else:
if isinstance(obj, unreal.Object):
label = obj.get_name()
else:
try:
label = obj.__str__()
except TypeError:
label = f"{obj}"
if bPush: # push
# print(f"%%% push: {propertyName}, label {label}")
data.hisCrumbObjsAndNames.append((obj, propertyName))
self.data.push_breadcrumb_string(ui_breadcrumb, label, label)
self.data.set_text(ui_Label, "{} type: {}".format(label, type(obj)) )
crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb)
if bRight:
assert len(self.right.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.right.hisCrumbObjsAndNames), crumbCount)
else:
assert len(self.left.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.left.hisCrumbObjsAndNames), crumbCount)
self.update_log_text(bRight)
def clear_and_query(self, obj, bRight):
# first time query
self.data.clear_breadcrumbs_string(self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft)
if not self.right:
self.right = DetailData()
if not self.left:
self.left = DetailData()
data = self.right if bRight else self.left
data.hisCrumbObjsAndNames = [] #clear his-Object at first time query
if bRight:
assert len(self.right.hisCrumbObjsAndNames) == 0, "len(self.right.hisCrumbObjsAndNames) != 0"
else:
assert len(self.left.hisCrumbObjsAndNames) == 0, "len(self.left.hisCrumbObjsAndNames) != 0"
self.query_and_push(obj, "", bPush=True, bRight= bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight)
def update_ui_by_mode(self):
self.data.set_is_checked(self.ui_checkbox_compare_mode, self.compareMode)
self.data.set_is_checked(self.ui_checkbox_single_mode, not self.compareMode)
bCollapsed = not self.compareMode
self.data.set_collapsed(self.ui_rightButtonsGroup, bCollapsed)
self.data.set_collapsed(self.ui_right_group, bCollapsed)
self.data.set_collapsed(self.ui_button_refresh, bCollapsed)
def on_checkbox_SingleMode_Click(self, state):
self.compareMode = False
self.update_ui_by_mode()
def on_checkbox_CompareMode_Click(self, state):
self.compareMode = True
self.update_ui_by_mode()
def on_button_Refresh_click(self):
self.apply_compare_if_needed()
def on_button_SelectAsset_click(self, bRightSide):
selectedAssets = Utilities.Utils.get_selected_assets()
if len(selectedAssets) == 0:
return
self.clear_and_query(selectedAssets[0], bRightSide)
def on_button_QuerySelected_click(self, bRightSide):
# query component when any component was selected, otherwise actor
obj = Utilities.Utils.get_selected_comp()
if not obj:
obj = Utilities.Utils.get_selected_actor()
if obj:
self.clear_and_query(obj, bRightSide)
def on_drop(self, bRightSide, *args, **kwargs):
if "assets" in kwargs and kwargs["assets"]:
asset = unreal.load_asset(kwargs["assets"][0])
if asset:
self.clear_and_query(asset, bRightSide)
return
if "actors" in kwargs and kwargs["actors"]:
actor = unreal.PythonBPLib.find_actor_by_name(kwargs["actors"][0], unreal.EditorLevelLibrary.get_editor_world())
if actor:
print(actor)
self.clear_and_query(actor, bRightSide)
return
item_count = 0
for k, v in kwargs.items():
item_count += len(v)
if item_count == 0:
selected_comp = Utilities.Utils.get_selected_comp()
if selected_comp:
self.clear_and_query(selected_comp, bRightSide)
def log_r_warning(self):
unreal.log_warning("Assign the global var: '_r' with the MenuItem: 'select X --> _r' on Python Icon menu")
def on_button_Query_R_click(self, r_obj, bRightSide=False):
print("on_button_Query_R_click call")
if not r_obj:
return
self.clear_and_query(r_obj, bRightSide)
def on_list_double_click_do(self, index, bRight):
# print ("on_listview_DetailList_mouse_button_double_click {} bRight: {}".format(index, bRight))
data = self.right if bRight else self.left
typeBlacklist = [int, float, str, bool] #, types.NotImplementedType]
real_index = data.filteredIndexToIndex[index] if data.filteredIndexToIndex else index
assert 0 <= real_index < len(data.attributes)
currentObj, _ = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1]
attr_name = data.attributes[real_index].name
objResult, propertyName = self.try_get_object(data, currentObj, attr_name)
if not objResult or objResult is currentObj: # equal
return
if isinstance(objResult, str) and "skip call" in objResult.lower():
return
if type(objResult) in typeBlacklist:
return
if isinstance(objResult, collections.Iterable):
if type(objResult[0]) in typeBlacklist:
return
nextObj = objResult[0]
nextPropertyName = str(propertyName) + "[0]"
else:
nextObj = objResult
nextPropertyName = str(propertyName)
self.query_and_push(nextObj, nextPropertyName, bPush=True, bRight=bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight)
def on_listview_DetailListRight_mouse_button_double_click(self, index):
self.on_list_double_click_do(index, bRight=True)
def on_listview_DetailListLeft_mouse_button_double_click(self, index):
self.on_list_double_click_do(index, bRight=False)
def on_breadcrumbtrail_click_do(self, item, bRight):
ui_hisObjsBreadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft
data = self.right if bRight else self.left
count = self.data.get_breadcrumbs_count_string(ui_hisObjsBreadcrumb)
print ("on_breadcrumbtrail_ObjectHis_crumb_click: {} count: {} len(data.hisCrumbObjsAndNames): {}".format(item, count, len(data.hisCrumbObjsAndNames)))
while len(data.hisCrumbObjsAndNames) > count:
data.hisCrumbObjsAndNames.pop()
nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1]
if not bRight:
assert self.left.hisCrumbObjsAndNames == data.hisCrumbObjsAndNames, "self.left.hisCrumbObjsAndNames = data.hisCrumbObjsAndNames"
self.query_and_push(nextObj, name, bPush=False, bRight=False)
self.apply_compare_if_needed()
self.update_log_text(bRight=False)
def on_breadcrumbtrail_ObjectHisLeft_crumb_click(self, item):
self.on_breadcrumbtrail_click_do(item, bRight=False)
def on_breadcrumbtrail_ObjectHisRight_crumb_click(self, item):
self.on_breadcrumbtrail_click_do(item, bRight=True)
def remove_address_str(self, strIn):
return re.sub(r'\(0x[0-9,A-F]{16}\)', '', strIn)
def apply_compare_if_needed(self):
if not self.compareMode:
return
lefts = self.left.filtered_attributes if self.left.filtered_attributes else self.left.attributes
rights = self.right.filtered_attributes if self.right.filtered_attributes else self.right.attributes
if not lefts:
lefts = []
if not rights:
rights = []
leftIDs = []
rightIDs = []
for i, left_attr in enumerate(lefts):
for j, right_attr in enumerate(rights):
if right_attr.name == left_attr.name:
if right_attr.result != left_attr.result:
if isinstance(right_attr.result, unreal.Transform):
if right_attr.result.is_near_equal(left_attr.result, location_tolerance=1e-20, rotation_tolerance=1e-20, scale3d_tolerance=1e-20):
continue
leftIDs.append(i)
rightIDs.append(j)
break
self.data.set_list_view_multi_column_selections(self.ui_detailListLeft, leftIDs)
self.data.set_list_view_multi_column_selections(self.ui_detailListRight, rightIDs)
self.diff_count = len(leftIDs)
def apply_search_filter(self, text, bRight):
_data = self.right if bRight else self.left
_data.filter_str = text if len(text) else ""
_data.filtered_attributes, _data.filteredIndexToIndex = self.filter(_data)
ui_listView = self.ui_detailListRight if bRight else self.ui_detailListLeft
self.show_data(_data, ui_listView)
self.apply_compare_if_needed()
def on_searchbox_FilterLeft_text_changed(self, text):
self.apply_search_filter(text if text is not None else "", bRight=False)
def on_searchbox_FilterLeft_text_committed(self, text):
self.apply_search_filter(text if text is not None else "", bRight=False)
def on_searchbox_FilterRight_text_changed(self, text):
self.apply_search_filter(text if text is not None else "", bRight=True)
def on_searchbox_FilterRight_text_committed(self, text):
self.apply_search_filter(text if text is not None else "", bRight=True)
def apply_filter(self):
_datas = [self.left, self.right]
_isRight = [False, True]
for data, bRight in zip(_datas, _isRight):
if len(data.hisCrumbObjsAndNames) > 0:
nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames)-1]
self.query_and_push(nextObj, name, bPush=False, bRight=bRight)
self.apply_compare_if_needed()
self.update_log_text(bRight=False) #
def try_get_object(self, data, obj, name:str):
index = -1
attribute = None
for i, attr in enumerate(data.attributes):
if attr.name == name:
index = i
attribute = attr
assert index >= 0
return attribute.result, name
def ui_on_checkbox_ShowBuiltin_state_changed(self, bEnabled):
self.showBuiltin = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowOther_state_changed(self, bEnabled):
self.showOther = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowProperties_state_changed(self, bEnabled):
self.showProperties = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowEditorProperties_state_changed(self, bEnabled):
self.showEditorProperties = bEnabled
self.apply_filter()
def ui_on_checkbox_ShowParamFunction_state_changed(self, bEnabled):
self.showParamFunction = bEnabled
self.apply_filter()
def ui_on_listview_DetailList_selection_changed(self, bRight):
data = [self.left, self.right][bRight]
list_view = [self.ui_detailListLeft, self.ui_detailListRight][bRight]
selected_indices = set(self.data.get_list_view_multi_column_selection(list_view))
added = selected_indices - data.selected
de_selected = data.selected - selected_indices
for i, lineId in enumerate(added):
self.data.set_list_view_multi_column_line(list_view, lineId, data.get_plain(lineId, column_count=COLUMN_COUNT)
, rebuild_list=True if i == len(added)-1 and len(de_selected) == 0 else False)
for i, lineId in enumerate(de_selected):
self.data.set_list_view_multi_column_line(list_view, lineId, data.get_rich(lineId, column_count=COLUMN_COUNT)
, rebuild_list=True if i == len(de_selected)-1 else False)
data.selected = selected_indices
|
# coding: utf-8
import unreal
import argparse
print("VRM4U python begin")
print (__file__)
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
args = parser.parse_args()
print(args.vrm)
#print(dummy[3])
humanoidBoneList = [
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"upperChest", # 9 optional
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal", # 24
"leftThumbIntermediate",
"leftThumbDistal",
"leftIndexProximal",
"leftIndexIntermediate",
"leftIndexDistal",
"leftMiddleProximal",
"leftMiddleIntermediate",
"leftMiddleDistal",
"leftRingProximal",
"leftRingIntermediate",
"leftRingDistal",
"leftLittleProximal",
"leftLittleIntermediate",
"leftLittleDistal",
"rightThumbProximal",
"rightThumbIntermediate",
"rightThumbDistal",
"rightIndexProximal",
"rightIndexIntermediate",
"rightIndexDistal",
"rightMiddleProximal",
"rightMiddleIntermediate",
"rightMiddleDistal",
"rightRingProximal",
"rightRingIntermediate",
"rightRingDistal",
"rightLittleProximal",
"rightLittleIntermediate",
"rightLittleDistal", #54
]
humanoidBoneParentList = [
"", #"hips",
"hips",#"leftUpperLeg",
"hips",#"rightUpperLeg",
"leftUpperLeg",#"leftLowerLeg",
"rightUpperLeg",#"rightLowerLeg",
"leftLowerLeg",#"leftFoot",
"rightLowerLeg",#"rightFoot",
"hips",#"spine",
"spine",#"chest",
"chest",#"upperChest" 9 optional
"chest",#"neck",
"neck",#"head",
"chest",#"leftShoulder", # <-- upper..
"chest",#"rightShoulder",
"leftShoulder",#"leftUpperArm",
"rightShoulder",#"rightUpperArm",
"leftUpperArm",#"leftLowerArm",
"rightUpperArm",#"rightLowerArm",
"leftLowerArm",#"leftHand",
"rightLowerArm",#"rightHand",
"leftFoot",#"leftToes",
"rightFoot",#"rightToes",
"head",#"leftEye",
"head",#"rightEye",
"head",#"jaw",
"leftHand",#"leftThumbProximal",
"leftThumbProximal",#"leftThumbIntermediate",
"leftThumbIntermediate",#"leftThumbDistal",
"leftHand",#"leftIndexProximal",
"leftIndexProximal",#"leftIndexIntermediate",
"leftIndexIntermediate",#"leftIndexDistal",
"leftHand",#"leftMiddleProximal",
"leftMiddleProximal",#"leftMiddleIntermediate",
"leftMiddleIntermediate",#"leftMiddleDistal",
"leftHand",#"leftRingProximal",
"leftRingProximal",#"leftRingIntermediate",
"leftRingIntermediate",#"leftRingDistal",
"leftHand",#"leftLittleProximal",
"leftLittleProximal",#"leftLittleIntermediate",
"leftLittleIntermediate",#"leftLittleDistal",
"rightHand",#"rightThumbProximal",
"rightThumbProximal",#"rightThumbIntermediate",
"rightThumbIntermediate",#"rightThumbDistal",
"rightHand",#"rightIndexProximal",
"rightIndexProximal",#"rightIndexIntermediate",
"rightIndexIntermediate",#"rightIndexDistal",
"rightHand",#"rightMiddleProximal",
"rightMiddleProximal",#"rightMiddleIntermediate",
"rightMiddleIntermediate",#"rightMiddleDistal",
"rightHand",#"rightRingProximal",
"rightRingProximal",#"rightRingIntermediate",
"rightRingIntermediate",#"rightRingDistal",
"rightHand",#"rightLittleProximal",
"rightLittleProximal",#"rightLittleIntermediate",
"rightLittleIntermediate",#"rightLittleDistal",
]
for i in range(len(humanoidBoneList)):
humanoidBoneList[i] = humanoidBoneList[i].lower()
for i in range(len(humanoidBoneParentList)):
humanoidBoneParentList[i] = humanoidBoneParentList[i].lower()
######
reg = unreal.AssetRegistryHelpers.get_asset_registry();
## meta 取得
a = reg.get_all_assets();
for aa in a:
if (aa.get_editor_property("object_path") == args.vrm):
v:unreal.VrmAssetListObject = aa
vv = v.get_asset().vrm_meta_object
print(vv)
meta = vv
##
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
#rig = rigs[10]
h_mod = rig.get_hierarchy_modifier()
#elements = h_mod.get_selection()
#sk = rig.get_preview_mesh()
#k = sk.skeleton
#print(k)
### 全ての骨
modelBoneListAll = []
modelBoneNameList = []
for e in reversed(h_mod.get_elements()):
if (e.type != unreal.RigElementType.BONE):
h_mod.remove_element(e)
name_to_control = {"dummy_for_table" : None}
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.2, 0.2, 0.2])
for e in h_mod.get_elements():
print(e.name)
if (e.type != unreal.RigElementType.BONE):
continue
bone = h_mod.get_bone(e)
parentName = "{}".format(bone.get_editor_property('parent_name'))
#print("parent==")
#print(parentName)
cur_parentName = parentName + "_c"
name_s = "{}".format(e.name) + "_s"
name_c = "{}".format(e.name) + "_c"
space = h_mod.add_space(name_s, parent_name=cur_parentName, space_type=unreal.RigSpaceType.CONTROL)
control = h_mod.add_control(name_c,
space_name=space.name,
gizmo_color=[0.1, 0.1, 1.0, 1.0],
)
h_mod.set_initial_global_transform(space, h_mod.get_global_transform(e))
cc = h_mod.get_control(control)
cc.set_editor_property('gizmo_transform', gizmo_trans)
#cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR)
h_mod.set_control(cc)
name_to_control[name_c] = cc
c = None
try:
i = list(name_to_control.keys()).index(cur_parentName)
except:
i = -1
if (i >= 0):
c = name_to_control[cur_parentName]
if (cc != None):
if ("{}".format(e.name) in meta.humanoid_bone_table.values() ):
cc.set_editor_property('gizmo_color', unreal.LinearColor(0.1, 0.1, 1.0, 1.0))
h_mod.set_control(cc)
else:
cc.set_editor_property('gizmo_color', unreal.LinearColor(1.0, 0.1, 0.1, 1.0))
h_mod.set_control(cc)
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
# 配列ノード追加
collectionItem_forControl:unreal.RigVMStructNode = None
collectionItem_forBone:unreal.RigVMStructNode = None
for node in n:
if (node.get_node_title() == 'Items'):
#print(node.get_node_title())
#node = unreal.RigUnit_CollectionItems.cast(node)
pin = node.find_pin('Items')
print(pin.get_array_size())
print(pin.get_default_value())
if (pin.get_array_size() < 40):
continue
if 'Type=Control' in pin.get_default_value():
collectionItem_forControl = node
if 'Type=Bone' in pin.get_default_value():
collectionItem_forBone = node
#nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class())
# controller array
if (collectionItem_forControl == None):
collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute')
items_forControl = collectionItem_forControl.find_pin('Items')
c.clear_array_pin(items_forControl.get_pin_path())
if (collectionItem_forBone != None):
items_forBone = collectionItem_forBone.find_pin('Items')
c.clear_array_pin(items_forBone.get_pin_path())
for bone_h in meta.humanoid_bone_table:
bone_m = meta.humanoid_bone_table[bone_h]
try:
i = humanoidBoneList.index(bone_h.lower())
except:
i = -1
if (i >= 0):
tmp = '(Type=Bone,Name='
tmp += "{}".format(bone_m).lower()
tmp += ')'
c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp)
for e in h_mod.get_elements():
print(e.name)
if (e.type == unreal.RigElementType.CONTROL):
tmp = '(Type=Control,Name='
tmp += "{}".format(e.name)
tmp += ')'
c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
|
import unreal
editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
def get_actors_by_type(actor_type):
world = editor_subsystem.get_editor_world()
actor = unreal.GameplayStatics.get_all_actors_of_class(world, actor_type)
return actor
def get_actors_by_selection():
actor = editor_actor_subsystem.get_selected_level_actors()
return actor
def select_static_actors_by_type():
actors = get_actors_by_type(unreal.StaticMeshActor) # 通过父类unreal.Actor可以找到所有Actor
editor_actor_subsystem.set_selected_level_actors(actors)
def log_actors():
# actors = get_actors_by_type(unreal.StaticMeshActor)
actors = get_actors_by_selection()
for actor in actors:
unreal.log("-" * 100)
unreal.log(f"actor label:{actor.get_actor_label()}")
unreal.log(f"actor name:{actor.get_name()}")
unreal.log(f"actor instance name: {actor.get_fname()}")
unreal.log(f"actor path name:{actor.get_path_name()}")
unreal.log(f"actor full name: {actor.get_full_name()}")
unreal.log(f"actor owner:{actor.get_owner()}")
unreal.log(f"actor parent actor:{actor.get_parent_actor()}")
unreal.log(f"actor attach parent actor: {actor.get_attach_parent_actor}")
unreal.log(f"actor attached actors: {actor.get_attached_actors()}")
unreal.log(f"actor folder path:{actor.get_folder_path()}")
unreal.log(f"actor level:{actor.get_level()}")
unreal.log(f"actor location:{actor.get_actor_location()}")
unreal.log(f"actor rotation: {actor.get_actor_rotation()}")
unreal.log(f"actor hidden: {actor.get_editor_property('bHidden')}")
root_component = actor.get_editor_property('RootComponent')
unreal.log(f"actor root_component: {root_component}")
unreal.log(f"component visible: {root_component.get_editor_property('bVisible')}")
# root_component.set_editor_property('bVisible', False)
if __name__ == '__main__':
# select_static_actors_by_type()
log_actors()
# log_actors():
# LogPython: actor label:Cube
# LogPython: actor name:StaticMeshActor_1
# LogPython: actor instance name: StaticMeshActor_1
# LogPython: actor path name:/project/.StarterMap:PersistentLevel.StaticMeshActor_1
# LogPython: actor full name: StaticMeshActor /project/.StarterMap:PersistentLevel.StaticMeshActor_1
# LogPython: actor owner:None
# LogPython: actor parent actor:None
# LogPython: actor attach parent actor: <built-in method get_attach_parent_actor of StaticMeshActor object at 0x00000188F80283B0>
# LogPython: actor attached actors: ["/project/.StaticMeshActor'/project/.StarterMap:PersistentLevel.StaticMeshActor_2'"]
# LogPython: actor folder path:None
# LogPython: actor level:<Object '/project/.StarterMap:PersistentLevel' (0x00000B926E578400) Class 'Level'>
# LogPython: actor location:<Struct 'Vector' (0x00000188F801B3A0) {x: -1030.000000, y: 1830.000000, z: 0.000000}>
# LogPython: actor rotation: <Struct 'Rotator' (0x00000188F801B3A0) {pitch: 0.000000, yaw: 0.000000, roll: 0.000000}>
# LogPython: ----------------------------------------------------------------------------------------------------
# LogPython: actor label:Cube2
# LogPython: actor name:StaticMeshActor_2
# LogPython: actor instance name: StaticMeshActor_2
# LogPython: actor path name:/project/.StarterMap:PersistentLevel.StaticMeshActor_2
# LogPython: actor full name: StaticMeshActor /project/.StarterMap:PersistentLevel.StaticMeshActor_2
# LogPython: actor owner:None
# LogPython: actor parent actor:None
# LogPython: actor attach parent actor: <built-in method get_attach_parent_actor of StaticMeshActor object at 0x00000188F8028110>
# LogPython: actor attached actors: []
# LogPython: actor folder path:None
# LogPython: actor level:<Object '/project/.StarterMap:PersistentLevel' (0x00000B926E578400) Class 'Level'>
# LogPython: actor location:<Struct 'Vector' (0x00000188F801B3A0) {x: -1020.000000, y: 1840.000000, z: 0.000000}>
# LogPython: actor rotation: <Struct 'Rotator' (0x00000188F801B3A0) {pitch: 0.000000, yaw: 0.000000, roll: 0.000000}>
|
import random
import re
import os
import unreal
from datetime import datetime
from typing import Optional, Callable
def clean_sequencer(level_sequence):
bindings = level_sequence.get_bindings()
for b in bindings:
# b_display_name = str(b.get_display_name())
# if "Camera" not in b_display_name:
# b.remove()
b.remove()
def select_random_asset(assets_path, asset_class=None, predicate:Optional[Callable]=None):
eal = unreal.EditorAssetLibrary()
assets = eal.list_assets(assets_path)
if asset_class is not None:
filtered_assets = []
for asset in assets:
try:
asset_name = os.path.splitext(asset)[0]
if eal.find_asset_data(asset_name).asset_class_path.asset_name == asset_class:
filtered_assets.append(asset)
except:
continue
assets = filtered_assets
if predicate is not None:
filtered_assets = []
for asset in assets:
if predicate(asset):
filtered_assets.append(asset)
assets = filtered_assets
selected_asset_path = random.choice(assets)
return selected_asset_path
def spawn_actor(asset_path, location=unreal.Vector(0.0, 0.0, 0.0)):
# spawn actor into level
obj = unreal.load_asset(asset_path)
rotation = unreal.Rotator(0, 0, 0)
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(object_to_use=obj,
location=location,
rotation=rotation)
actor.set_actor_scale3d(unreal.Vector(1.0, 1.0, 1.0))
# actor.get_editor_property('render_component').set_editor_property('cast_shadow', self.add_sprite_based_shadow)
return actor
def add_animation_to_actor(spawnable_actor, animation_path):
# Get the skeleton animation track class
anim_track = spawnable_actor.add_track(unreal.MovieSceneSkeletalAnimationTrack)
# Add a new animation section
animation_section = anim_track.add_section()
# Set the skeletal animation asset
animation_asset = unreal.load_asset(animation_path)
animation_section.params.animation = animation_asset
# Set the Section Range
frame_rate = 30 # level_sequence.get_frame_rate()
start_frame = 0
end_frame = animation_asset.get_editor_property('sequence_length') * frame_rate.numerator / frame_rate.denominator
animation_section.set_range(start_frame, end_frame)
def find_relevant_assets(level_sequence):
camera_re = re.compile("SuperCineCameraActor_([0-9]+)")
target_point_re = re.compile("TargetPoint_([0-9]+)")
cameras = {}
target_points = {}
skylight = None
# hdri_backdrop = None
#all_actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_all_level_actors()
# ues = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
# current_world = ues.get_editor_world()
# bound_objects = unreal.SequencerTools().get_bound_objects(current_world, level_sequence, level_sequence.get_bindings(), level_sequence.get_playback_range())
# for b_obj in bound_objects:
# for actor1 in b_obj.bound_objects:
# print(actor1.get_name())
# if 'CineCamera' in actor1.get_name():
# camera = actor1
# break
all_actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_all_level_actors()
for actor in all_actors:
label = actor.get_actor_label()
name = actor.get_name()
# if 'HDRIBackdrop' in actor.get_name():
# hdri_backdrop = actor
camera_matches = camera_re.search(label)
target_point_matches = target_point_re.search(label)
if camera_matches is not None:
cameras[camera_matches.group(1)] = actor
if target_point_matches is not None:
target_points[target_point_matches.group(1)] = actor
if 'SkyLight' in name:
skylight = actor
# return camera, hdri_backdrop
return cameras, target_points, skylight
def random_hdri(hdri_backdrop):
selected_hdri_path = select_random_asset('/project/')
hdri_texture = unreal.load_asset(selected_hdri_path)
hdri_backdrop.set_editor_property('cubemap', hdri_texture)
def random_cubemap(skylight):
cubemap_path = select_random_asset('/project/', asset_class='TextureCube')
cubemap_asset = unreal.load_asset(cubemap_path)
if cubemap_asset is not None:
# Access the skylight component
skylight_comp = skylight.get_editor_property('light_component')
# Assign the new cubemap
skylight_comp.set_editor_property('cubemap', cubemap_asset)
# Update the skylight to apply the new cubemap
skylight_comp.recapture_sky()
def bind_camera_to_level_sequence(level_sequence, camera, character_location, start_frame=0, num_frames=0, move_radius=500):
# Get the Camera Cuts track manually
camera_cuts_track = None
for track in level_sequence.get_master_tracks():
if track.get_class() == unreal.MovieSceneCameraCutTrack.static_class():
camera_cuts_track = track
break
if camera_cuts_track is None:
print("No Camera Cuts track found.")
return
# Find the section (usually only one for camera cuts)
sections = camera_cuts_track.get_sections()
for section in sections:
if isinstance(section, unreal.MovieSceneCameraCutSection):
# Replace the camera binding
camera_binding = level_sequence.add_possessable(camera)
camera_binding_id = level_sequence.get_binding_id(camera_binding)
# Set the new camera binding to the camera cut section
section.set_camera_binding_id(camera_binding_id)
print("Camera cut updated to use:", camera.get_name())
# Add Transform Track
transform_track = camera_binding.add_track(unreal.MovieScene3DTransformTrack)
transform_section = transform_track.add_section()
transform_section.set_range(start_frame, start_frame + num_frames)
# Get transform channels
channels = transform_section.get_all_channels()
loc_x_channel = channels[0]
loc_y_channel = channels[1]
loc_z_channel = channels[2]
# Get original camera location as center point
#center_location = camera.get_actor_location()
center_location = character_location + unreal.Vector(0.0, 0.0, 100.0) # Offset to avoid ground collision
# Generate random keyframes
# frames = sorted(random.sample(range(start_frame+1, start_frame+num_frames-1), num_keyframes-2))
frames = [start_frame, start_frame+num_frames]
# Add keyframes
for frame in frames:
# Randomize location around the center within a radius
random_location = center_location + unreal.Vector(
random.uniform(-move_radius, move_radius),
random.uniform(-move_radius, move_radius),
random.uniform(-move_radius/2, move_radius/2)
)
frame_number = unreal.FrameNumber(frame)
# Add location keys
loc_x_channel.add_key(frame_number, random_location.x)
loc_y_channel.add_key(frame_number, random_location.y)
loc_z_channel.add_key(frame_number, random_location.z)
def add_actor_to_layer(actor, layer_name="character"):
layer_subsystem = unreal.get_editor_subsystem(unreal.LayersSubsystem)
# Add the actor to the specified layer, if it doesn't exist, add_actor_to_layer will create it
layer_subsystem.add_actor_to_layer(actor, layer_name)
RENDER_TIMES = 3
current_round = 0 # 全局计数
# 全局唯一时间戳,防止路径冲突
def render_one_round():
global current_round
current_round += 1
unreal.log(f"========== Start Render Round {current_round}/{RENDER_TIMES} ==========")
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
output_path = f"/project/{timestamp}\\"
level_sequence = unreal.EditorAssetLibrary.load_asset('/project/.RenderSequencer')
clean_sequencer(level_sequence)
cameras, target_points, skylight = find_relevant_assets(level_sequence)
random_keys = [k for k in cameras.keys() if k in target_points.keys()]
random_key = random.choice(random_keys)
camera = cameras[random_key]
target_point = target_points[random_key]
random_cubemap(skylight)
location = target_point.get_actor_location()
selected_skeletal_mesh_path = select_random_asset('/project/', asset_class='SkeletalMesh')
a_pose_animation_name = os.path.splitext(selected_skeletal_mesh_path)[-1] + "_Anim"
def not_a_pose_animation(asset:str):
return not asset.endswith(a_pose_animation_name)
baked_animation_directory_path = os.path.dirname(selected_skeletal_mesh_path)
selected_animation_path = select_random_asset(baked_animation_directory_path, asset_class="AnimSequence", predicate=not_a_pose_animation)
print(f"[{current_round}/{RENDER_TIMES}] Skeletal Mesh: {selected_skeletal_mesh_path}")
print(f"[{current_round}/{RENDER_TIMES}] Animation: {selected_animation_path}")
actor = spawn_actor(asset_path=selected_skeletal_mesh_path, location=location)
add_actor_to_layer(actor, layer_name="character")
spawnable_actor = level_sequence.add_spawnable_from_instance(actor)
add_animation_to_actor(spawnable_actor, animation_path=selected_animation_path)
unreal.get_editor_subsystem(unreal.EditorActorSubsystem).destroy_actor(actor)
bind_camera_to_level_sequence(level_sequence, camera, location, start_frame=0, num_frames=300, move_radius=800)
unreal.log(f"[{current_round}/{RENDER_TIMES}] Selected character and animation: {selected_skeletal_mesh_path}, {selected_animation_path}")
# 关键:把“继续下一轮”动作绑定到movie_finished回调里
render_with_callback(output_path=output_path, mode="rgb")
# 这里改写你的render函数,让它支持外部回调
def render_with_callback(output_path, start_frame=0, num_frames=0, mode="rgb"):
subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem)
pipelineQueue = subsystem.get_queue()
for job in pipelineQueue.get_jobs():
pipelineQueue.delete_job(job)
ues = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
current_world = ues.get_editor_world()
map_name = current_world.get_path_name()
job = pipelineQueue.allocate_new_job(unreal.MoviePipelineExecutorJob)
job.set_editor_property('map', unreal.SoftObjectPath(map_name))
job.set_editor_property('sequence', unreal.SoftObjectPath('/project/'))
job.author = "Voia"
job.job_name = "Synthetic Data"
if mode == 'rgb':
newConfig = unreal.load_asset("/project/")
elif mode == 'normals':
newConfig = unreal.load_asset("/project/")
else:
newConfig = unreal.load_asset("/project/")
job.set_configuration(newConfig)
outputSetting = job.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineOutputSetting)
outputSetting.output_resolution = unreal.IntPoint(1920, 1080)
outputSetting.file_name_format = "Image.{render_pass}.{frame_number}"
outputSetting.flush_disk_writes_per_shot = True
outputSetting.output_directory = unreal.DirectoryPath(path=f'{output_path}/{mode}')
use_custom_playback_range = num_frames > 0
outputSetting.use_custom_playback_range = use_custom_playback_range
outputSetting.custom_start_frame = start_frame
outputSetting.custom_end_frame = start_frame + num_frames
renderPass = job.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineDeferredPassBase)
jpg_settings = job.get_configuration().find_setting_by_class(unreal.MoviePipelineImageSequenceOutput_JPG)
job.get_configuration().remove_setting(jpg_settings)
png_settings = job.get_configuration().find_or_add_setting_by_class(unreal.MoviePipelineImageSequenceOutput_PNG)
# 可根据mode切换alpha写入
if mode == 'rgb':
png_settings.set_editor_property('write_alpha', False)
else:
png_settings.set_editor_property('write_alpha', True)
job.get_configuration().initialize_transient_settings()
error_callback = unreal.OnMoviePipelineExecutorErrored()
def movie_error(pipeline_executor, pipeline_with_error, is_fatal, error_text):
unreal.log(pipeline_executor)
unreal.log(pipeline_with_error)
unreal.log(is_fatal)
unreal.log(error_text)
error_callback.add_callable(movie_error)
# 关键:movie_finished回调自动继续渲染下一模式/下一轮
def movie_finished(pipeline_executor, success):
unreal.log('movie finished')
unreal.log(pipeline_executor)
unreal.log(success)
if mode == 'rgb':
# 渲染Normal
render_with_callback(output_path=output_path, mode="normals")
elif mode == 'normals':
# 渲染Alpha
render_with_callback(output_path=output_path, mode="rgb_alpha")
elif mode == 'rgb_alpha':
global current_round
if current_round < RENDER_TIMES:
# 自动进入下一轮
render_one_round()
else:
unreal.log("========== All renders completed. ==========")
#unreal.SystemLibrary.quit_editor()
finished_callback = unreal.OnMoviePipelineExecutorFinished()
finished_callback.add_callable(movie_finished)
unreal.log("Starting Executor")
global executor
executor = unreal.MoviePipelinePIEExecutor(subsystem)
executor.set_editor_property('on_executor_errored_delegate', error_callback)
executor.set_editor_property('on_executor_finished_delegate', finished_callback)
subsystem.render_queue_with_executor_instance(executor)
# 启动
if __name__ == '__main__':
current_round = 0
render_one_round()
|
import unreal
""" Should be used with internal UE Python API
Auto generate collision for static meshes"""
asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
asset_root_dir = '/project/'
assets = asset_reg.get_assets_by_path(asset_root_dir, recursive=True)
def set_convex_collision(static_mesh):
unreal.EditorStaticMeshLibrary.set_convex_decomposition_collisions(static_mesh, 4, 16, 100000)
unreal.EditorAssetLibrary.save_loaded_asset(static_mesh)
for asset in assets:
if asset.asset_class == "StaticMesh":
static_mesh = unreal.EditorAssetLibrary.find_asset_data(asset.object_path).get_asset()
set_convex_collision(static_mesh)
|
import unreal
from ayon_core.hosts.unreal.api.pipeline import (
ls,
replace_static_mesh_actors,
replace_skeletal_mesh_actors,
replace_geometry_cache_actors,
)
from ayon_core.pipeline import InventoryAction
def update_assets(containers, selected):
allowed_families = ["model", "rig"]
# Get all the containers in the Unreal Project
all_containers = ls()
for container in containers:
container_dir = container.get("namespace")
if container.get("family") not in allowed_families:
unreal.log_warning(
f"Container {container_dir} is not supported.")
continue
# Get all containers with same asset_name but different objectName.
# These are the containers that need to be updated in the level.
sa_containers = [
i
for i in all_containers
if (
i.get("asset_name") == container.get("asset_name") and
i.get("objectName") != container.get("objectName")
)
]
asset_content = unreal.EditorAssetLibrary.list_assets(
container_dir, recursive=True, include_folder=False
)
# Update all actors in level
for sa_cont in sa_containers:
sa_dir = sa_cont.get("namespace")
old_content = unreal.EditorAssetLibrary.list_assets(
sa_dir, recursive=True, include_folder=False
)
if container.get("family") == "rig":
replace_skeletal_mesh_actors(
old_content, asset_content, selected)
replace_static_mesh_actors(
old_content, asset_content, selected)
elif container.get("family") == "model":
if container.get("loader") == "PointCacheAlembicLoader":
replace_geometry_cache_actors(
old_content, asset_content, selected)
else:
replace_static_mesh_actors(
old_content, asset_content, selected)
unreal.EditorLevelLibrary.save_current_level()
class UpdateAllActors(InventoryAction):
"""Update all the Actors in the current level to the version of the asset
selected in the scene manager.
"""
label = "Replace all Actors in level to this version"
icon = "arrow-up"
def process(self, containers):
update_assets(containers, False)
class UpdateSelectedActors(InventoryAction):
"""Update only the selected Actors in the current level to the version
of the asset selected in the scene manager.
"""
label = "Replace selected Actors in level to this version"
icon = "arrow-up"
def process(self, containers):
update_assets(containers, True)
|
import unreal
AssetRegistry = unreal.AssetRegistryHelpers.get_asset_registry()
UtilLibrary = unreal.EditorUtilityLibrary
"""
rename_asset(asset, new_name) -> None
get_selection_set() -> Array(Actor)
get_selection_bounds() -> (origin=Vector, box_extent=Vector, sphere_radius=float)
get_selected_blueprint_classes() -> Array(type(Class))
get_selected_assets() -> Array(Object)
get_selected_asset_data() -> Array(AssetData)
get_actor_reference(path_to_actor) -> Actor
"""
AutomationScheduler = unreal.AutomationScheduler
AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
"""
rename_referencing_soft_object_paths(packages_to_check, asset_redirector_map)
rename_assets_with_dialog(assets_and_names, auto_checkout=False)
rename_assets(assets_and_names)
open_editor_for_assets(assets)
import_asset_tasks(import_tasks)
import_assets_with_dialog(destination_path)
import_assets_automated(import_data)
find_soft_references_to_object(target_object)
export_assets_with_dialog(assets_to_export, prompt_for_individual_filenames)
export_assets(assets_to_export, export_path)
duplicate_asset_with_dialog_and_title(asset_name, package_path, original_object, dialog_title)
duplicate_asset_with_dialog(asset_name, package_path, original_object)
duplicate_asset(asset_name, package_path, original_object)
create_unique_asset_name(base_package_name, suffix)
create_asset_with_dialog(asset_name, package_path, asset_class, factory, calling_context="None")
create_asset(asset_name, package_path, asset_class, factory, calling_context="None")
"""
AssetLibrary = unreal.EditorAssetLibrary
"""
sync_browser_to_objects(cls, asset_paths)
set_metadata_tag(cls, object, tag, value)
save_loaded_assets(cls, assets_to_save, only_if_is_dirty=True)
save_loaded_asset(cls, asset_to_save, only_if_is_dirty=True)
save_directory(cls, directory_path, only_if_is_dirty=True, recursive=True)
save_asset(cls, asset_to_save, only_if_is_dirty=True)
rename_loaded_asset(cls, source_asset, destination_asset_path)
rename_directory(cls, source_directory_path, destination_directory_path)
rename_asset(cls, source_asset_path, destination_asset_path)
remove_metadata_tag(cls, object, tag)
make_directory(cls, directory_path)
load_blueprint_class(cls, asset_path)
load_asset(cls, asset_path)
list_assets(cls, directory_path, recursive=True, include_folder=False)
list_asset_by_tag_value(cls, tag_name, tag_value)
get_tag_values(cls, asset_path)
get_path_name_for_loaded_asset(cls, loaded_asset)
get_metadata_tag_values(cls, object)
get_metadata_tag(cls, object, tag)
find_package_referencers_for_asset(cls, asset_path, load_assets_to_confirm=False)
find_asset_data(cls, asset_path)
duplicate_loaded_asset(cls, source_asset, destination_asset_path)
duplicate_directory(cls, source_directory_path, destination_directory_path)
duplicate_asset(cls, source_asset_path, destination_asset_path)
does_directory_have_assets(cls, directory_path, recursive=True)
does_directory_exist(cls, directory_path)
does_asset_exist(cls, asset_path)
do_assets_exist(cls, asset_paths)
delete_loaded_assets(cls, assets_to_delete)
delete_loaded_asset(cls, asset_to_delete)
delete_directory(cls, directory_path)
delete_asset(cls, asset_path_to_delete)
consolidate_assets(cls, asset_to_consolidate_to, assets_to_consolidate)
checkout_loaded_assets(cls, assets_to_checkout)
checkout_loaded_asset(cls, asset_to_checkout)
checkout_directory(cls, directory_path, recursive=True)
checkout_asset(cls, asset_to_checkout)
"""
FilterLibrary = unreal.EditorFilterLibrary
"""
Utility class to filter a list of objects. Object should be in the World Editor.
by_selection(cls, target_array, filter_type=EditorScriptingFilterType.INCLUDE)
by_level_name(cls, target_array, level_name, filter_type=EditorScriptingFilterType.INCLUDE)
by_layer(cls, target_array, layer_name, filter_type=EditorScriptingFilterType.INCLUDE)
by_id_name(cls, target_array, name_sub_string, string_match=EditorScriptingStringMatchType.CONTAINS, filter_type=EditorScriptingFilterType.INCLUDE)
by_class(cls, target_array, object_class, filter_type=EditorScriptingFilterType.INCLUDE)
by_actor_tag(cls, target_array, tag, filter_type=EditorScriptingFilterType.INCLUDE)
by_actor_label(cls, target_array, name_sub_string, string_match=EditorScriptingStringMatchType.CONTAINS, filter_type=EditorScriptingFilterType.INCLUDE, ignore_case=True)
"""
AutomationLibrary = unreal.AutomationLibrary
"""
take_high_res_screenshot(cls, res_x, res_y, filename, camera=None, mask_enabled=False, capture_hdr=False, comparison_tolerance=ComparisonTolerance.LOW, comparison_notes="")
take_automation_screenshot_of_ui(cls, world_context_object, latent_info, name, options)
take_automation_screenshot_at_camera(cls, world_context_object, latent_info, camera, name_override, notes, options)
take_automation_screenshot(cls, world_context_object, latent_info, name, notes, options)
set_scalability_quality_to_low(cls, world_context_object)
set_scalability_quality_to_epic(cls, world_context_object)
set_scalability_quality_level_relative_to_max(cls, world_context_object, value=1)
get_stat_inc_max(cls, stat_name)
get_stat_inc_average(cls, stat_name)
get_stat_exc_max(cls, stat_name)
get_stat_exc_average(cls, stat_name)
get_stat_call_count(cls, stat_name)
get_default_screenshot_options_for_rendering(cls, tolerance=ComparisonTolerance.LOW, delay=0.200000)
get_default_screenshot_options_for_gameplay(cls, tolerance=ComparisonTolerance.LOW, delay=0.200000)
enable_stat_group(cls, world_context_object, group_name)
disable_stat_group(cls, world_context_object, group_name)
automation_wait_for_loading(cls, world_context_object, latent_info)
are_automated_tests_running(cls)
add_expected_log_error(cls, expected_pattern_string, occurrences=1, exact_match=False)
"""
LevelLibrary = unreal.EditorLevelLibrary
"""
spawn_actor_from_object(object_to_use, location, rotation=[0.000000, 0.000000, 0.000000]) -> Actor
spawn_actor_from_class(actor_class, location, rotation=[0.000000, 0.000000, 0.000000]) -> Actor
set_selected_level_actors(actors_to_select) -> None
set_level_viewport_camera_info(camera_location, camera_rotation) -> None
set_current_level_by_name(level_name) -> bool
set_actor_selection_state(actor, should_be_selected) -> None
select_nothing() -> None
save_current_level() -> bool
save_all_dirty_levels() -> bool
replace_mesh_components_meshes_on_actors(actors, mesh_to_be_replaced, new_mesh) -> None
replace_mesh_components_meshes(mesh_components, mesh_to_be_replaced, new_mesh) -> None
replace_mesh_components_materials_on_actors(actors, material_to_be_replaced, new_material) -> None
replace_mesh_components_materials(mesh_components, material_to_be_replaced, new_material) -> None
pilot_level_actor(actor_to_pilot) -> None
new_level_from_template(asset_path, template_asset_path) -> bool
new_level(asset_path) -> bool
merge_static_mesh_actors(actors_to_merge, merge_options) -> StaticMeshActor or None
load_level(asset_path) -> bool
join_static_mesh_actors(actors_to_join, join_options) -> Actor
get_selected_level_actors() -> Array(Actor)
get_level_viewport_camera_info() -> (camera_location=Vector, camera_rotation=Rotator) or None
get_game_world() -> World
get_editor_world() -> World
get_all_level_actors_components() -> Array(ActorComponent)
get_all_level_actors() -> Array(Actor)
get_actor_reference(path_to_actor) -> Actor
eject_pilot_level_actor() -> None
editor_set_game_view(game_view) -> None
editor_play_simulate() -> None
editor_invalidate_viewports() -> None
destroy_actor(actor_to_destroy) -> bool
create_proxy_mesh_actor(actors_to_merge, merge_options) -> StaticMeshActor or None
convert_actors(actors, actor_class, static_mesh_package_path) -> Array(Actor)
clear_actor_selection_set() -> None
"""
SequenceBindingLibrary = unreal.MovieSceneBindingExtensions
"""
set_parent(binding, parent_binding) -> None
remove_track(binding, track_to_remove) -> None
remove(binding) -> None
is_valid(binding) -> bool
get_tracks(binding) -> Array(MovieSceneTrack)
get_possessed_object_class(binding) -> type(Class)
get_parent(binding) -> SequencerBindingProxy
get_object_template(binding) -> Object
get_name(binding) -> str
get_id(binding) -> Guid
get_display_name(binding) -> Text
get_child_possessables(binding) -> Array(SequencerBindingProxy)
find_tracks_by_type(binding, track_type) -> Array(MovieSceneTrack)
find_tracks_by_exact_type(binding, track_type) -> Array(MovieSceneTrack)
add_track(binding, track_type) -> MovieSceneTrack
"""
SequenceFolderLibrary = unreal.MovieSceneFolderExtensions
"""
set_folder_name(folder, folder_name) -> bool
set_folder_color(folder, folder_color) -> bool
remove_child_object_binding(folder, object_binding) -> bool
remove_child_master_track(folder, master_track) -> bool
remove_child_folder(target_folder, folder_to_remove) -> bool
get_folder_name(folder) -> Name
get_folder_color(folder) -> Color
get_child_object_bindings(folder) -> Array(SequencerBindingProxy)
get_child_master_tracks(folder) -> Array(MovieSceneTrack)
get_child_folders(folder) -> Array(MovieSceneFolder)
add_child_object_binding(folder, object_binding) -> bool
add_child_master_track(folder, master_track) -> bool
add_child_folder(target_folder, folder_to_add) -> bool
"""
SequencePropertyLibrary = unreal.MovieScenePropertyTrackExtensions
"""
X.set_property_name_and_path(track, property_name, property_path) -> None
X.set_object_property_class(track, property_class) -> None
X.get_unique_track_name(track) -> Name
X.get_property_path(track) -> str
X.get_property_name(track) -> Name
X.get_object_property_class(track) -> type(Class)
"""
SequenceSectionLibrary = unreal.MovieSceneSectionExtensions
"""
set_start_frame_seconds(section, start_time) -> None
set_start_frame_bounded(section, is_bounded) -> None
set_start_frame(section, start_frame) -> None
set_range_seconds(section, start_time, end_time) -> None
set_range(section, start_frame, end_frame) -> None
set_end_frame_seconds(section, end_time) -> None
set_end_frame_bounded(section, is_bounded) -> None
set_end_frame(section, end_frame) -> None
get_start_frame_seconds(section) -> float
get_start_frame(section) -> int32
get_parent_sequence_frame(section, frame, parent_sequence) -> int32
get_end_frame_seconds(section) -> float
get_end_frame(section) -> int32
get_channels(section) -> Array(MovieSceneScriptingChannel)
find_channels_by_type(section, channel_type) -> Array(MovieSceneScriptingChannel)
"""
SequenceLibrary = unreal.MovieSceneSectionExtensions
"""
set_work_range_start(sequence, start_time_in_seconds) -> None
set_work_range_end(sequence, end_time_in_seconds) -> None
set_view_range_start(sequence, start_time_in_seconds) -> None
set_view_range_end(sequence, end_time_in_seconds) -> None
set_tick_resolution(sequence, tick_resolution) -> None
set_read_only(sequence, read_only) -> None
set_playback_start_seconds(sequence, start_time) -> None
set_playback_start(sequence, start_frame) -> None
set_playback_end_seconds(sequence, end_time) -> None
set_playback_end(sequence, end_frame) -> None
set_display_rate(sequence, display_rate) -> None
make_range_seconds(sequence, start_time, duration) -> SequencerScriptingRange
make_range(sequence, start_frame, duration) -> SequencerScriptingRange
make_binding_id(master_sequence, binding, space=MovieSceneObjectBindingSpace.ROOT) -> MovieSceneObjectBindingID
locate_bound_objects(sequence, binding, context) -> Array(Object)
is_read_only(sequence) -> bool
get_work_range_start(sequence) -> float
get_work_range_end(sequence) -> float
get_view_range_start(sequence) -> float
get_view_range_end(sequence) -> float
get_timecode_source(sequence) -> Timecode
get_tick_resolution(sequence) -> FrameRate
get_spawnables(sequence) -> Array(SequencerBindingProxy)
get_root_folders_in_sequence(sequence) -> Array(MovieSceneFolder)
get_possessables(sequence) -> Array(SequencerBindingProxy)
get_playback_start_seconds(sequence) -> float
get_playback_start(sequence) -> int32
get_playback_range(sequence) -> SequencerScriptingRange
get_playback_end_seconds(sequence) -> float
get_playback_end(sequence) -> int32
get_movie_scene(sequence) -> MovieScene
get_master_tracks(sequence) -> Array(MovieSceneTrack)
get_marked_frames(sequence) -> Array(MovieSceneMarkedFrame)
get_display_rate(sequence) -> FrameRate
get_bindings(sequence) -> Array(SequencerBindingProxy)
find_next_marked_frame(sequence, frame_number, forward) -> int32
find_master_tracks_by_type(sequence, track_type) -> Array(MovieSceneTrack)
find_master_tracks_by_exact_type(sequence, track_type) -> Array(MovieSceneTrack)
find_marked_frame_by_label(sequence, label) -> int32
find_marked_frame_by_frame_number(sequence, frame_number) -> int32
find_binding_by_name(sequence, name) -> SequencerBindingProxy
delete_marked_frames(sequence) -> None
delete_marked_frame(sequence, delete_index) -> None
add_spawnable_from_instance(sequence, object_to_spawn) -> SequencerBindingProxy
add_spawnable_from_class(sequence, class_to_spawn) -> SequencerBindingProxy
add_root_folder_to_sequence(sequence, new_folder_name) -> MovieSceneFolder
add_possessable(sequence, object_to_possess) -> SequencerBindingProxy
add_master_track(sequence, track_type) -> MovieSceneTrack
add_marked_frame(sequence, marked_frame) -> int32
"""
SequenceTrackLibrary = unreal.MovieSceneTrackExtensions
"""
remove_section(track, section) -> None
get_sections(track) -> Array(MovieSceneSection)
get_display_name(track) -> Text
add_section(track) -> MovieSceneSection
"""
SequenceTools = unreal.SequencerTools
"""
render_movie(capture_settings, on_finished_callback) -> bool
is_rendering_movie() -> bool
import_fbx(world, sequence, bindings, import_fbx_settings, import_filename) -> bool
get_object_bindings(world, sequence, object, range) -> Array(SequencerBoundObjects)
get_bound_objects(world, sequence, bindings, range) -> Array(SequencerBoundObjects)
export_fbx(world, sequence, bindings, override_options, fbx_file_name) -> bool
export_anim_sequence(world, sequence, anim_sequence, binding) -> bool
cancel_movie_render() -> None
"""
LevelSequenceLibrary = unreal.LevelSequenceEditorBlueprintLibrary
"""
set_lock_level_sequence(lock) -> None
set_current_time(new_frame) -> None
play() -> None
pause() -> None
open_level_sequence(level_sequence) -> bool
is_playing() -> bool
is_level_sequence_locked() -> bool
get_current_time() -> int32
get_current_level_sequence() -> LevelSequence
close_level_sequence() -> None
"""
PathLib = unreal.Paths
"""
video_capture_dir() -> str
validate_path(path) -> (did_succeed=bool, out_reason=Text)
split(path) -> (path_part=str, filename_part=str, extension_part=str)
source_config_dir() -> str
should_save_to_user_dir() -> bool
shader_working_dir() -> str
set_project_file_path(new_game_project_file_path) -> None
set_extension(path, new_extension) -> str
screen_shot_dir() -> str
sandboxes_dir() -> str
root_dir() -> str
remove_duplicate_slashes(path) -> str
project_user_dir() -> str
project_saved_dir() -> str
project_plugins_dir() -> str
project_persistent_download_dir() -> str
project_mods_dir() -> str
project_log_dir() -> str
project_intermediate_dir() -> str
project_dir() -> str
project_content_dir() -> str
project_config_dir() -> str
profiling_dir() -> str
normalize_filename(path) -> str
normalize_directory_name(path) -> str
make_valid_file_name(string, replacement_char="") -> str
make_standard_filename(path) -> str
make_platform_filename(path) -> str
make_path_relative_to(path, relative_to) -> str or None
launch_dir() -> str
is_same_path(path_a, path_b) -> bool
is_restricted_path(path) -> bool
is_relative(path) -> bool
is_project_file_path_set() -> bool
is_drive(path) -> bool
has_project_persistent_download_dir() -> bool
get_tool_tip_localization_paths() -> Array(str)
get_restricted_folder_names() -> Array(str)
get_relative_path_to_root() -> str
get_property_name_localization_paths() -> Array(str)
get_project_file_path() -> str
get_path(path) -> str
get_invalid_file_system_chars() -> str
get_game_localization_paths() -> Array(str)
get_extension(path, include_dot=False) -> str
get_engine_localization_paths() -> Array(str)
get_editor_localization_paths() -> Array(str)
get_clean_filename(path) -> str
get_base_filename(path, remove_path=True) -> str
generated_config_dir() -> str
game_user_developer_dir() -> str
game_source_dir() -> str
game_developers_dir() -> str
game_agnostic_saved_dir() -> str
file_exists(path) -> bool
feature_pack_dir() -> str
enterprise_plugins_dir() -> str
enterprise_feature_pack_dir() -> str
enterprise_dir() -> str
engine_version_agnostic_user_dir() -> str
engine_user_dir() -> str
engine_source_dir() -> str
engine_saved_dir() -> str
engine_plugins_dir() -> str
engine_intermediate_dir() -> str
engine_dir() -> str
engine_content_dir() -> str
engine_config_dir() -> str
directory_exists(path) -> bool
diff_dir() -> str
create_temp_filename(path, prefix="", extension=".tmp") -> str
convert_to_sandbox_path(path, sandbox_name) -> str
convert_relative_path_to_full(path, base_path="") -> str
convert_from_sandbox_path(path, sandbox_name) -> str
combine(paths) -> str
collapse_relative_directories(path) -> str or None
cloud_dir() -> str
change_extension(path, new_extension) -> str
bug_it_dir() -> str
automation_transient_dir() -> str
automation_log_dir() -> str
automation_dir() -> str
"""
SystemLib = unreal.SystemLibrary
"""
unregister_for_remote_notifications() -> None
unload_primary_asset_list(primary_asset_id_list) -> None
unload_primary_asset(primary_asset_id) -> None
transact_object(object) -> None
sphere_trace_single_for_objects(world_context_object, start, end, radius, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
sphere_trace_single_by_profile(world_context_object, start, end, radius, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
sphere_trace_single(world_context_object, start, end, radius, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
sphere_trace_multi_for_objects(world_context_object, start, end, radius, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
sphere_trace_multi_by_profile(world_context_object, start, end, radius, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
sphere_trace_multi(world_context_object, start, end, radius, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
sphere_overlap_components(world_context_object, sphere_pos, sphere_radius, object_types, component_class_filter, actors_to_ignore) -> Array(PrimitiveComponent) or None
sphere_overlap_actors(world_context_object, sphere_pos, sphere_radius, object_types, actor_class_filter, actors_to_ignore) -> Array(Actor) or None
snapshot_object(object) -> None
show_platform_specific_leaderboard_screen(category_name) -> None
show_platform_specific_achievements_screen(specific_player) -> None
show_interstitial_ad() -> None
show_ad_banner(ad_id_index, show_on_bottom_of_screen) -> None
set_window_title(title) -> None
set_volume_buttons_handled_by_system(enabled) -> None
set_user_activity(user_activity) -> None
set_suppress_viewport_transition_message(world_context_object, state) -> None
set_gamepads_block_device_feedback(block) -> None
retriggerable_delay(world_context_object, duration, latent_info) -> None
reset_gamepad_assignment_to_controller(controller_id) -> None
reset_gamepad_assignments() -> None
register_for_remote_notifications() -> None
quit_game(world_context_object, specific_player, quit_preference, ignore_platform_restrictions) -> None
quit_editor() -> None
print_text(world_context_object, text="Hello", print_to_screen=True, print_to_log=True, text_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=2.000000) -> None
print_string(world_context_object, string="Hello", print_to_screen=True, print_to_log=True, text_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=2.000000) -> None
not_equal_soft_object_reference(a, b) -> bool
not_equal_soft_class_reference(a, b) -> bool
not_equal_primary_asset_type(a, b) -> bool
not_equal_primary_asset_id(a, b) -> bool
normalize_filename(filename) -> str
move_component_to(component, target_relative_location, target_relative_rotation, ease_out, ease_in, over_time, force_shortest_rotation_path, move_action, latent_info) -> None
make_literal_text(value) -> Text
make_literal_string(value) -> str
make_literal_name(value) -> Name
make_literal_int(value) -> int32
make_literal_float(value) -> float
make_literal_byte(value) -> uint8
make_literal_bool(value) -> bool
load_interstitial_ad(ad_id_index) -> None
load_class_asset_blocking(asset_class) -> type(Class)
load_asset_blocking(asset) -> Object
line_trace_single_for_objects(world_context_object, start, end, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
line_trace_single_by_profile(world_context_object, start, end, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
line_trace_single(world_context_object, start, end, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
line_trace_multi_for_objects(world_context_object, start, end, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
line_trace_multi_by_profile(world_context_object, start, end, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
line_trace_multi(world_context_object, start, end, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
launch_url(url) -> None
un_pause_timer_handle(world_context_object, handle) -> None
un_pause_timer_delegate(delegate) -> None
un_pause_timer(object, function_name) -> None
timer_exists_handle(world_context_object, handle) -> bool
timer_exists_delegate(delegate) -> bool
timer_exists(object, function_name) -> bool
set_timer_delegate(delegate, time, looping, initial_start_delay=0.000000, initial_start_delay_variance=0.000000) -> TimerHandle
set_timer(object, function_name, time, looping, initial_start_delay=0.000000, initial_start_delay_variance=0.000000) -> TimerHandle
pause_timer_handle(world_context_object, handle) -> None
pause_timer_delegate(delegate) -> None
pause_timer(object, function_name) -> None
is_valid_timer_handle(handle) -> bool
is_timer_paused_handle(world_context_object, handle) -> bool
is_timer_paused_delegate(delegate) -> bool
is_timer_paused(object, function_name) -> bool
is_timer_active_handle(world_context_object, handle) -> bool
is_timer_active_delegate(delegate) -> bool
is_timer_active(object, function_name) -> bool
invalidate_timer_handle(handle) -> (TimerHandle, handle=TimerHandle)
get_timer_remaining_time_handle(world_context_object, handle) -> float
get_timer_remaining_time_delegate(delegate) -> float
get_timer_remaining_time(object, function_name) -> float
get_timer_elapsed_time_handle(world_context_object, handle) -> float
get_timer_elapsed_time_delegate(delegate) -> float
get_timer_elapsed_time(object, function_name) -> float
clear_timer_handle(world_context_object, handle) -> None
clear_timer_delegate(delegate) -> None
clear_timer(object, function_name) -> None
clear_and_invalidate_timer_handle(world_context_object, handle) -> TimerHandle
is_valid_soft_object_reference(soft_object_reference) -> bool
is_valid_soft_class_reference(soft_class_reference) -> bool
is_valid_primary_asset_type(primary_asset_type) -> bool
is_valid_primary_asset_id(primary_asset_id) -> bool
is_valid_class(class_) -> bool
is_valid(object) -> bool
is_unattended() -> bool
is_standalone(world_context_object) -> bool
is_split_screen(world_context_object) -> bool
is_server(world_context_object) -> bool
is_screensaver_enabled() -> bool
is_packaged_for_distribution() -> bool
is_logged_in(specific_player) -> bool
is_interstitial_ad_requested() -> bool
is_interstitial_ad_available() -> bool
is_dedicated_server(world_context_object) -> bool
is_controller_assigned_to_gamepad(controller_id) -> bool
hide_ad_banner() -> None
get_volume_buttons_handled_by_system() -> bool
get_unique_device_id() -> str
get_supported_fullscreen_resolutions() -> Array(IntPoint) or None
get_soft_object_reference_from_primary_asset_id(primary_asset_id) -> Object
get_soft_class_reference_from_primary_asset_id(primary_asset_id) -> Class
get_rendering_material_quality_level() -> int32
get_rendering_detail_mode() -> int32
get_project_saved_directory() -> str
get_project_directory() -> str
get_project_content_directory() -> str
get_primary_assets_with_bundle_state(required_bundles, excluded_bundles, valid_types, force_current_state) -> Array(PrimaryAssetId)
get_primary_asset_id_list(primary_asset_type) -> Array(PrimaryAssetId)
get_primary_asset_id_from_soft_object_reference(soft_object_reference) -> PrimaryAssetId
get_primary_asset_id_from_soft_class_reference(soft_class_reference) -> PrimaryAssetId
get_primary_asset_id_from_object(object) -> PrimaryAssetId
get_primary_asset_id_from_class(class_) -> PrimaryAssetId
get_preferred_languages() -> Array(str)
get_platform_user_name() -> str
get_platform_user_dir() -> str
get_path_name(object) -> str
get_outer_object(object) -> Object
get_object_name(object) -> str
get_object_from_primary_asset_id(primary_asset_id) -> Object
get_min_y_resolution_for_ui() -> int32
get_min_y_resolution_for3d_view() -> int32
get_local_currency_symbol() -> str
get_local_currency_code() -> str
get_game_time_in_seconds(world_context_object) -> float
get_gamepad_controller_name(controller_id) -> str
get_game_name() -> str
get_game_bundle_id() -> str
get_frame_count() -> int64
get_engine_version() -> str
get_display_name(object) -> str
get_device_id() -> str
get_default_locale() -> str
get_default_language() -> str
get_current_bundle_state(primary_asset_id, force_current_state) -> Array(Name) or None
get_convenient_windowed_resolutions() -> Array(IntPoint) or None
get_console_variable_int_value(variable_name) -> int32
get_console_variable_float_value(variable_name) -> float
get_console_variable_bool_value(variable_name) -> bool
get_component_bounds(component) -> (origin=Vector, box_extent=Vector, sphere_radius=float)
get_command_line() -> str
get_class_from_primary_asset_id(primary_asset_id) -> type(Class)
get_class_display_name(class_) -> str
get_ad_id_count() -> int32
get_actor_list_from_component_list(component_list, actor_class_filter) -> Array(Actor)
get_actor_bounds(actor) -> (origin=Vector, box_extent=Vector)
force_close_ad_banner() -> None
flush_persistent_debug_lines(world_context_object) -> None
flush_debug_strings(world_context_object) -> None
execute_console_command(world_context_object, command, specific_player=None) -> None
equal_equal_soft_object_reference(a, b) -> bool
equal_equal_soft_class_reference(a, b) -> bool
equal_equal_primary_asset_type(a, b) -> bool
equal_equal_primary_asset_id(a, b) -> bool
end_transaction() -> int32
draw_debug_string(world_context_object, text_location, text, test_base_actor=None, text_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_sphere(world_context_object, center, radius=100.000000, segments=12, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_point(world_context_object, position, size, point_color, duration=0.000000) -> None
draw_debug_plane(world_context_object, plane_coordinates, location, size, plane_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_line(world_context_object, line_start, line_end, line_color, duration=0.000000, thickness=0.000000) -> None
draw_debug_frustum(world_context_object, frustum_transform, frustum_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_float_history_transform(world_context_object, float_history, draw_transform, draw_size, draw_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_float_history_location(world_context_object, float_history, draw_location, draw_size, draw_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_cylinder(world_context_object, start, end, radius=100.000000, segments=12, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_coordinate_system(world_context_object, axis_loc, axis_rot, scale=1.000000, duration=0.000000, thickness=0.000000) -> None
draw_debug_cone_in_degrees(world_context_object, origin, direction, length=100.000000, angle_width=45.000000, angle_height=45.000000, num_sides=12, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_cone(world_context_object, origin, direction, length, angle_width, angle_height, num_sides, line_color, duration=0.000000, thickness=0.000000) -> None
draw_debug_circle(world_context_object, center, radius, num_segments=12, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000, y_axis=[0.000000, 1.000000, 0.000000], z_axis=[0.000000, 0.000000, 1.000000], draw_axis=False) -> None
draw_debug_capsule(world_context_object, center, half_height, radius, rotation, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_camera(camera_actor, camera_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_box(world_context_object, center, extent, line_color, rotation=[0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_arrow(world_context_object, line_start, line_end, arrow_size, line_color, duration=0.000000, thickness=0.000000) -> None
does_implement_interface(test_object, interface) -> bool
delay(world_context_object, duration, latent_info) -> None
create_copy_for_undo_buffer(object_to_modify) -> None
convert_to_relative_path(filename) -> str
convert_to_absolute_path(filename) -> str
conv_soft_obj_path_to_soft_obj_ref(soft_object_path) -> Object
conv_soft_object_reference_to_string(soft_object_reference) -> str
conv_soft_class_reference_to_string(soft_class_reference) -> str
conv_soft_class_path_to_soft_class_ref(soft_class_path) -> Class
conv_primary_asset_type_to_string(primary_asset_type) -> str
conv_primary_asset_id_to_string(primary_asset_id) -> str
conv_interface_to_object(interface) -> Object
control_screensaver(allow_screen_saver) -> None
component_overlap_components(component, component_transform, object_types, component_class_filter, actors_to_ignore) -> Array(PrimitiveComponent) or None
component_overlap_actors(component, component_transform, object_types, actor_class_filter, actors_to_ignore) -> Array(Actor) or None
collect_garbage() -> None
capsule_trace_single_for_objects(world_context_object, start, end, radius, half_height, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
capsule_trace_single_by_profile(world_context_object, start, end, radius, half_height, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
capsule_trace_single(world_context_object, start, end, radius, half_height, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
capsule_trace_multi_for_objects(world_context_object, start, end, radius, half_height, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
capsule_trace_multi_by_profile(world_context_object, start, end, radius, half_height, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
capsule_trace_multi(world_context_object, start, end, radius, half_height, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
capsule_overlap_components(world_context_object, capsule_pos, radius, half_height, object_types, component_class_filter, actors_to_ignore) -> Array(PrimitiveComponent) or None
capsule_overlap_actors(world_context_object, capsule_pos, radius, half_height, object_types, actor_class_filter, actors_to_ignore) -> Array(Actor) or None
can_launch_url(url) -> bool
cancel_transaction(index) -> None
box_trace_single_for_objects(world_context_object, start, end, half_size, orientation, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
box_trace_single_by_profile(world_context_object, start, end, half_size, orientation, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
box_trace_single(world_context_object, start, end, half_size, orientation, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
box_trace_multi_for_objects(world_context_object, start, end, half_size, orientation, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
box_trace_multi_by_profile(world_context_object, start, end, half_size, orientation, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
box_trace_multi(world_context_object, start, end, half_size, orientation, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
box_overlap_components(world_context_object, box_pos, extent, object_types, component_class_filter, actors_to_ignore) -> Array(PrimitiveComponent) or None
box_overlap_actors(world_context_object, box_pos, box_extent, object_types, actor_class_filter, actors_to_ignore) -> Array(Actor) or None
begin_transaction(context, description, primary_object) -> int32
add_float_history_sample(value, float_history) -> DebugFloatHistory
"""
|
import os
import json
import unreal
from Utilities.Utils import Singleton
class Shelf(metaclass=Singleton):
'''
This is a demo tool for showing how to create Chamelon Tools in Python
'''
MAXIMUM_ICON_COUNT = 12
Visible = "Visible"
Collapsed = "Collapsed"
def __init__(self, jsonPath:str):
self.jsonPath = jsonPath
self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath)
self.shelf_data = self.load_data()
self.is_text_readonly = True
self.ui_drop_at_last_aka = "DropAtLast"
self.ui_drop_is_full_aka = "DropIsFull"
self.update_ui(bForce=True)
def update_ui(self, bForce=False):
visibles = [False] * Shelf.MAXIMUM_ICON_COUNT
for i, shortcut in enumerate(self.shelf_data.shortcuts):
if i >= Shelf.MAXIMUM_ICON_COUNT:
continue
self.data.set_visibility(self.get_ui_button_group_name(i), Shelf.Visible)
self.data.set_tool_tip_text(self.get_ui_button_group_name(i), self.shelf_data.shortcuts[i].get_tool_tips())
self.data.set_text(self.get_ui_text_name(i), self.shelf_data.shortcuts[i].text)
# ITEM_TYPE_PY_CMD = 1 ITEM_TYPE_CHAMELEON = 2 ITEM_TYPE_ACTOR = 3 ITEM_TYPE_ASSETS = 4 ITEM_TYPE_ASSETS_FOLDER = 5
icon_name = ["PythonTextGreyIcon_40x.png", "PythonChameleonGreyIcon_40x.png", "LitSphere_40x.png", "Primitive_40x.png", "folderIcon.png"][shortcut.drop_type-1]
if os.path.exists(os.path.join(os.path.dirname(__file__), f"Images/{icon_name}")):
self.data.set_image_from(self.get_ui_img_name(i), f"Images/{icon_name}")
else:
unreal.log_warning("file: {} not exists in this tool's folder: {}".format(f"Images/{icon_name}", os.path.join(os.path.dirname(__file__))))
visibles[i] = True
for i, v in enumerate(visibles):
if not v:
self.data.set_visibility(self.get_ui_button_group_name(i), Shelf.Collapsed)
self.lock_text(self.is_text_readonly, bForce)
bFull = len(self.shelf_data) == Shelf.MAXIMUM_ICON_COUNT
self.data.set_visibility(self.ui_drop_at_last_aka, "Collapsed" if bFull else "Visible")
self.data.set_visibility(self.ui_drop_is_full_aka, "Visible" if bFull else "Collapsed" )
def lock_text(self, bLock, bForce=False):
if self.is_text_readonly != bLock or bForce:
for i in range(Shelf.MAXIMUM_ICON_COUNT):
self.data.set_text_read_only(self.get_ui_text_name(i), bLock)
self.data.set_color_and_opacity(self.get_ui_text_name(i), [1,1,1,1] if bLock else [1,0,0,1])
self.data.set_visibility(self.get_ui_text_name(i), "HitTestInvisible" if bLock else "Visible" )
self.is_text_readonly = bLock
def get_ui_button_group_name(self, index):
return f"ButtonGroup_{index}"
def get_ui_text_name(self, index):
return f"Txt_{index}"
def get_ui_img_name(self, index):
return f"Img_{index}"
def on_close(self):
self.save_data()
def get_data_path(self):
return os.path.join(os.path.dirname(__file__), "saved_shelf.json")
def load_data(self):
saved_file_path = self.get_data_path()
if os.path.exists(saved_file_path):
return ShelfData.load(saved_file_path)
else:
return ShelfData()
def save_data(self):
# fetch text from UI
for i, shortcut in enumerate(self.shelf_data.shortcuts):
shortcut.text = self.data.get_text(self.get_ui_text_name(i))
saved_file_path = self.get_data_path()
if self.shelf_data != None:
ShelfData.save(self.shelf_data, saved_file_path)
else:
unreal.log_warning("data null")
def clear_shelf(self):
self.shelf_data.clear()
self.update_ui()
def set_item_to_shelf(self, index, shelf_item):
if index >= len(self.shelf_data):
self.shelf_data.add(shelf_item)
else:
self.shelf_data.set(index, shelf_item)
self.update_ui()
# add shortcuts
def add_py_code_shortcut(self, index, py_code):
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_PY_CMD)
shelf_item.py_cmd = py_code
shelf_item.text=py_code[:3]
self.set_item_to_shelf(index, shelf_item)
def add_chameleon_shortcut(self, index, chameleon_json):
short_name = os.path.basename(chameleon_json)
if short_name.lower().startswith("chameleon") and len(short_name) > 9:
short_name = short_name[9:]
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_CHAMELEON)
shelf_item.chameleon_json = chameleon_json
shelf_item.text = short_name[:3]
self.set_item_to_shelf(index, shelf_item)
def add_actors_shortcut(self, index, actor_names):
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ACTOR)
shelf_item.actors = actor_names
shelf_item.text = shelf_item.actors[0][:3] if shelf_item.actors else ""
shelf_item.text += str(len(shelf_item.actors))
self.set_item_to_shelf(index, shelf_item)
def add_assets_shortcut(self, index, assets):
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ASSETS)
shelf_item.assets = assets
if assets:
first_asset = unreal.load_asset(assets[0])
if first_asset:
shelf_item.text = f"{first_asset.get_name()[:3]}{str(len(shelf_item.assets)) if len(shelf_item.assets)>1 else ''}"
else:
shelf_item.text = "None"
else:
shelf_item.text = ""
self.set_item_to_shelf(index, shelf_item)
def add_folders_shortcut(self, index, folders):
shelf_item = ShelfItem(icon="", drop_type=ShelfItem.ITEM_TYPE_ASSETS_FOLDER)
shelf_item.folders = folders
if folders:
shelf_item.text = f"{(os.path.basename(folders[0]))[:3]}{str(len(folders)) if len(folders)>1 else ''}"
else:
shelf_item.text = ""
self.set_item_to_shelf(index, shelf_item)
def get_dropped_by_type(self, *args, **kwargs):
py_cmd = kwargs.get("text", "")
file_names = kwargs.get("files", None)
if file_names:
json_files = [n for n in file_names if n.lower().endswith(".json")]
chameleon_json = json_files[0] if json_files else ""
else:
chameleon_json = ""
actors = kwargs.get("actors", [])
assets = kwargs.get("assets", [])
folders = kwargs.get("assets_folders", [])
return py_cmd, chameleon_json, actors, assets, folders
def on_drop(self, id, *args, **kwargs):
print(f"OnDrop: id:{id} {kwargs}")
py_cmd, chameleon_json, actors, assets, folders = self.get_dropped_by_type(*args, **kwargs)
if py_cmd:
self.add_py_code_shortcut(id, py_cmd)
elif chameleon_json:
self.add_chameleon_shortcut(id, chameleon_json)
elif actors:
self.add_actors_shortcut(id, actors)
elif assets:
self.add_assets_shortcut(id, assets)
elif folders:
self.add_folders_shortcut(id, folders)
else:
print("Drop python snippet, chameleon json, actors or assets.")
def on_drop_last(self, *args, **kwargs):
print(f"on drop last: {args}, {kwargs}")
if len(self.shelf_data) <= Shelf.MAXIMUM_ICON_COUNT:
self.on_drop(len(self.shelf_data) + 1, *args, **kwargs)
def select_actors(self, actor_names):
actors = [unreal.PythonBPLib.find_actor_by_name(name) for name in actor_names]
unreal.PythonBPLib.select_none()
for i, actor in enumerate(actors):
if actor:
unreal.PythonBPLib.select_actor(actor, selected=True, notify=True, force_refresh= i == len(actors)-1)
def select_assets(self, assets):
exists_assets = [asset for asset in assets if unreal.EditorAssetLibrary.does_asset_exist(asset)]
unreal.PythonBPLib.set_selected_assets_by_paths(exists_assets)
def select_assets_folders(self, assets_folders):
print(f"select_assets_folders: {assets_folders}")
unreal.PythonBPLib.set_selected_folder(assets_folders)
def on_button_click(self, id):
shortcut = self.shelf_data.shortcuts[id]
if not shortcut:
unreal.log_warning("shortcut == None")
return
if shortcut.drop_type == ShelfItem.ITEM_TYPE_PY_CMD:
eval(shortcut.py_cmd)
elif shortcut.drop_type == ShelfItem.ITEM_TYPE_CHAMELEON:
unreal.ChameleonData.launch_chalemeon_tool(shortcut.chameleon_json)
elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ACTOR:
self.select_actors(shortcut.actors) # do anything what you want
elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ASSETS:
self.select_assets(shortcut.assets)
elif shortcut.drop_type == ShelfItem.ITEM_TYPE_ASSETS_FOLDER:
self.select_assets_folders(shortcut.folders)
class ShelfItem:
ITEM_TYPE_NONE = 0
ITEM_TYPE_PY_CMD = 1
ITEM_TYPE_CHAMELEON = 2
ITEM_TYPE_ACTOR = 3
ITEM_TYPE_ASSETS = 4
ITEM_TYPE_ASSETS_FOLDER = 5
def __init__(self, drop_type, icon=""):
self.drop_type = drop_type
self.icon = icon
self.py_cmd = ""
self.chameleon_json = ""
self.actors = []
self.assets = []
self.folders = []
self.text = ""
def get_tool_tips(self):
if self.drop_type == ShelfItem.ITEM_TYPE_PY_CMD:
return f"PyCmd: {self.py_cmd}"
elif self.drop_type == ShelfItem.ITEM_TYPE_CHAMELEON:
return f"Chameleon Tools: {os.path.basename(self.chameleon_json)}"
elif self.drop_type == ShelfItem.ITEM_TYPE_ACTOR:
return f"{len(self.actors)} actors: {self.actors}"
elif self.drop_type == ShelfItem.ITEM_TYPE_ASSETS:
return f"{len(self.assets)} actors: {self.assets}"
elif self.drop_type == ShelfItem.ITEM_TYPE_ASSETS_FOLDER:
return f"{len(self.folders)} folders: {self.folders}"
class ShelfData:
def __init__(self):
self.shortcuts = []
def __len__(self):
return len(self.shortcuts)
def add(self, item):
assert isinstance(item, ShelfItem)
self.shortcuts.append(item)
def set(self, index, item):
assert isinstance(item, ShelfItem)
self.shortcuts[index] = item
def clear(self):
self.shortcuts.clear()
@staticmethod
def save(shelf_data, file_path):
with open(file_path, 'w') as f:
f.write(json.dumps(shelf_data, default=lambda o: o.__dict__, sort_keys=True, indent=4))
print(f"Shelf data saved: {file_path}")
@staticmethod
def load(file_path):
if not os.path.exists(file_path):
return None
with open(file_path, 'r') as f:
content = json.load(f)
instance = ShelfData()
instance.shortcuts = []
for item in content["shortcuts"]:
shelf_item = ShelfItem(item["drop_type"], item["icon"])
shelf_item.py_cmd = item["py_cmd"]
shelf_item.chameleon_json = item["chameleon_json"]
shelf_item.text = item["text"]
shelf_item.actors = item["actors"]
shelf_item.assets = item["assets"]
shelf_item.folders = item["folders"]
instance.shortcuts.append(shelf_item)
return instance
|
# Copyright Epic Games, Inc. All Rights Reserved.
import os
import unreal
import unrealcmd
#-------------------------------------------------------------------------------
def _find_autosdk_llvm(autosdk_path):
path = f"{autosdk_path}/Host{unreal.Platform.get_host()}/project/"
best_version = None
if os.path.isdir(path):
with os.scandir(path) as dirs:
best_version = max((x.name for x in dirs if x.is_dir()), default=None)
path += f"/{best_version}/"
if not os.path.isfile(path + "bin/clang-cl.exe"):
best_version = path = None
return (best_version, path)
#-------------------------------------------------------------------------------
def _can_execute_clang():
import subprocess
try: subprocess.run(("clang-cl", "--version"), stdout=subprocess.DEVNULL)
except: return False
return True
#-------------------------------------------------------------------------------
class ClangDb(unrealcmd.Cmd):
""" Generates a Clang database (compile_commands.json). If there is an active
project then the database is generated in context of that project. By default
the editor target is used. """
target = unrealcmd.Arg("", "Target to use when generating the database")
ubtargs = unrealcmd.Arg([str], "Arguments to pass onwards to UnrealBuildTool")
platform = unrealcmd.Opt("", "Platform to build a database for")
@unrealcmd.Cmd.summarise
def _run_ubt(self, target, platform, ubt_args):
ue_context = self.get_unreal_context()
ubt = ue_context.get_engine().get_ubt()
if project := ue_context.get_project():
ubt_args = ("-Project=" + str(project.get_path()), *ubt_args)
exec_context = self.get_exec_context()
for cmd, args in ubt.read_actions(target, platform, "Development", *ubt_args):
cmd = exec_context.create_runnable(cmd, *args)
cmd.run()
ret = cmd.get_return_code()
if ret:
return ret
def main(self):
# Rough check for the presence of LLVM
self.print_info("Checking for LLVM")
autosdk_path = os.getenv("UE_SDKS_ROOT")
print("UE_SDKS_ROOT:", autosdk_path)
llvm_version, llvm_path = _find_autosdk_llvm(autosdk_path)
if llvm_version:
print("Found:", llvm_version, "at", llvm_path)
else:
print("No suitable AusoSDKs version found")
print("Trying PATH ... ", end="")
has_clang = _can_execute_clang()
print("ok" if has_clang else "nope")
if not has_clang:
self.print_warning("Unable to locate Clang binary")
ue_context = self.get_unreal_context()
# Calculate how to invoke UBT
target = self.args.target
if not target:
target = ue_context.get_target_by_type(unreal.TargetType.EDITOR)
target = target.get_name()
platform = unreal.Platform.get_host()
if self.args.platform:
platform = self.get_platform(self.args.platform).get_name()
self.print_info("Database properties")
print("Target:", target)
print("Platform:", platform)
ubt_args = (
"-allmodules",
"-Mode=GenerateClangDatabase",
*self.args.ubtargs,
)
# Run UBT
self.print_info("Running UnrealBuildTool")
ret = self._run_ubt(target, platform, ubt_args)
if ret:
return ret
# Print some information
db_path = ue_context.get_engine().get_dir() / "../compile_commands.json"
try: db_size = os.path.getsize(db_path)
except: db_size = -1
print()
self.print_info("Database details")
print("Path:", os.path.normpath(db_path))
print("Size: %.02fKB" % (db_size / 1024 / 1024))
|
import unreal
# instance of unreal classes
editor_level_lib = unreal.EditorLevelLibrary()
editor_filter_lib = unreal.EditorFilterLibrary()
# get all actors and filter down to specific elements
actors = editor_level_lib.get_all_level_actors()
static_meshes = editor_filter_lib.by_class(actors, unreal.StaticMeshActor)
reflection_cap = editor_filter_lib.by_class(actors, unreal.ReflectionCapture)
blueprints = editor_filter_lib.by_id_name(actors, "BP_")
moved = 0
# create a mapping between folder names and arrays
mapping = {
"StaticMeshActors": static_meshes,
"ReflectionCaptures": reflection_cap,
"Bluprints": blueprints
}
for folder_name in mapping:
# for every list of actors, set new folder path
for actor in mapping[folder_name]:
actor_name = actor.get_fname()
actor.set_folder_path(folder_name)
unreal.log("Moved {} into {}".format(actor_name, folder_name))
moved += 1
unreal.log("Moved {} actors into respective floders".format(moved))
|
import unreal
file_a = "/project/.fbx"
file_b = "/project/.fbx"
imported_scenes_path = "/project/"
print 'Preparing import options...'
advanced_mesh_options = unreal.DatasmithStaticMeshImportOptions()
advanced_mesh_options.set_editor_property('max_lightmap_resolution', unreal.DatasmithImportLightmapMax.LIGHTMAP_512)
advanced_mesh_options.set_editor_property('min_lightmap_resolution', unreal.DatasmithImportLightmapMin.LIGHTMAP_64)
advanced_mesh_options.set_editor_property('generate_lightmap_u_vs', True)
advanced_mesh_options.set_editor_property('remove_degenerates', True)
base_options = unreal.DatasmithImportBaseOptions()
base_options.set_editor_property('include_geometry', True)
base_options.set_editor_property('include_material', True)
base_options.set_editor_property('include_light', True)
base_options.set_editor_property('include_camera', True)
base_options.set_editor_property('include_animation', True)
base_options.set_editor_property('static_mesh_options', advanced_mesh_options)
base_options.set_editor_property('scene_handling', unreal.DatasmithImportScene.CURRENT_LEVEL)
base_options.set_editor_property('asset_options', []) # Not used
dg_options = unreal.DatasmithDeltaGenImportOptions()
dg_options.set_editor_property('merge_nodes', False)
dg_options.set_editor_property('optimize_duplicated_nodes', False)
dg_options.set_editor_property('remove_invisible_nodes', False)
dg_options.set_editor_property('simplify_node_hierarchy', False)
dg_options.set_editor_property('import_var', True)
dg_options.set_editor_property('var_path', "")
dg_options.set_editor_property('import_pos', True)
dg_options.set_editor_property('pos_path', "")
dg_options.set_editor_property('import_tml', True)
dg_options.set_editor_property('tml_path', "")
dg_options.set_editor_property('textures_dir', "")
dg_options.set_editor_property('intermediate_serialization', unreal.DatasmithDeltaGenIntermediateSerializationType.DISABLED)
dg_options.set_editor_property('colorize_materials', False)
dg_options.set_editor_property('generate_lightmap_u_vs', False)
dg_options.set_editor_property('import_animations', True)
# Direct import to scene and assets:
print 'Importing directly to scene...'
unreal.DeltaGenLibrary.import_(file_a, imported_scenes_path, base_options, None, False)
#2-stage import step 1:
print 'Parsing to scene object...'
scene = unreal.DatasmithDeltaGenSceneElement.construct_datasmith_scene_from_file(file_b, imported_scenes_path, base_options, dg_options)
print 'Resulting datasmith scene: ' + str(scene)
print '\tProduct name: ' + str(scene.get_product_name())
print '\tMesh actor count: ' + str(len(scene.get_all_mesh_actors()))
print '\tLight actor count: ' + str(len(scene.get_all_light_actors()))
print '\tCamera actor count: ' + str(len(scene.get_all_camera_actors()))
print '\tCustom actor count: ' + str(len(scene.get_all_custom_actors()))
print '\tMaterial count: ' + str(len(scene.get_all_materials()))
print '\tAnimationTimeline count: ' + str(len(scene.get_all_animation_timelines()))
print '\tVariant count: ' + str(len(scene.get_all_variants()))
# Modify one of the Timelines
# Warning: The Animation nested structure is all USTRUCTs, which are value types, and the Array accessor returns
# a copy. Meaning something like timeline[0].name = 'new_name' will set the name on the COPY of anim_nodes[0]
timelines = scene.get_all_animation_timelines()
if len(timelines) > 0:
tim_0 = timelines[0]
old_name = tim_0.name
print 'Timeline old name: ' + old_name
tim_0.name += '_MODIFIED'
modified_name = tim_0.name
print 'Anim node modified name: ' + modified_name
timelines[0] = tim_0
scene.set_all_animation_timelines(timelines)
# Check modification
new_timelines = scene.get_all_animation_timelines()
print 'Anim node retrieved modified name: ' + new_timelines[0].name
assert new_timelines[0].name == modified_name, "Node modification didn't work!"
# Restore to previous state
tim_0 = new_timelines[0]
tim_0.name = old_name
new_timelines[0] = tim_0
scene.set_all_animation_timelines(new_timelines)
# 2-stage import step 2:
print 'Importing assets and actors...'
result = scene.import_scene()
print 'Import results: '
print '\tImported actor count: ' + str(len(result.imported_actors))
print '\tImported mesh count: ' + str(len(result.imported_meshes))
print '\tImported level sequences: ' + str([a.get_name() for a in result.animations])
print '\tImported level variant sets asset: ' + str(result.level_variant_sets.get_name())
if result.import_succeed:
print 'Import succeeded!'
else:
print 'Import failed!'
|
import unreal
import os
# instances of unreal classes
editor_util = unreal.EditorUtilityLibrary()
system_lib = unreal.SystemLibrary()
editor_asset_lib = unreal.EditorAssetLibrary()
# Directory mapping
Directory_mapping = {
"ActorComponent": "\\Game\\Blueprints\\Components\\",
"AnimationBlueprint": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"AnimationSequence": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"AnimBlueprint": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"AnimMontage": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"AnimSequence": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"BehaviorTree": "\\Game\\AI\\",
"BlackboardData": "\\Game\\AI\\",
"BlendSpace": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"BlendSpace1D": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"Blueprint": "\\Game\\Blueprints\\",
"BlueprintInterface": "\\Game\\Blueprints\\",
"ControlRigBlueprint": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"CurveFloat": "\\Game\\Blueprints\\Data\\",
"CurveLinearColor": "\\Game\\Blueprints\\Data\\",
"CurveLinearColorAtlas": "\\Game\\Blueprints\\Data\\",
"CurveTable": "\\Game\\Blueprints\\Data\\",
"DataTable": "\\Game\\Blueprints\\Data\\",
"EditorUtilityBlueprint": "\\Game\\Tools\\",
"EditorUtilityWidgetBlueprint": "\\Game\\Tools\\",
"Enum": "\\Game\\Blueprints\\Data\\",
"EnvQuery": "\\Game\\AI\\",
"HDRI": "\\Game\\Other\\",
"IKRetargeter": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"IKRigDefinition": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"LevelSequence": "\\Game\\Other\\",
"LevelSnapshots": "\\Game\\Other\\",
"Material": "\\Game\\Materials\\",
"MaterialFunction": "\\Game\\Materials\\Functions\\",
"MaterialFunctionMaterialLayer": "\\Game\\Materials\\Functions\\",
"MaterialInstance": "\\Game\\Materials\\Instances\\",
"MaterialInstanceConstant": "\\Game\\Materials\\Functions\\",
"MaterialParameterCollection": "\\Game\\Materials\\Functions\\",
"MediaOutput": "\\Game\\Media\\",
"MediaPlayer": "\\Game\\Media\\",
"MediaProfile": "\\Game\\Media\\",
"MediaSource": "\\Game\\Media\\",
"MediaTexture": "\\Game\\Media\\",
"Montages": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"MorphTarget": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"NDisplayConfiguration": "\\Game\\Other\\",
"NiagaraEmitter": "\\Game\\FX\\Emitters\\",
"NiagaraFunction": "\\Game\\FX\\Functions\\",
"NiagaraSystem": "\\Game\\FX\\",
"OCIOProfile": "\\Game\\Other\\",
"ParticleSystem": "\\Game\\FX\\",
"PhysicsAsset": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"PhysicsMaterial": "\\Game\\Materials\\",
"PoseAsset": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"PostProcessMaterial": "\\Game\\Materials\\",
"RemoteControlPreset": "\\Game\\Tools\\",
"RenderTarget": "\\Game\\Materials\\Textures\\",
"Rig": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"SequencerEdits": "\\Game\\Meshes\\SkeletalMeshes\\Animations\\",
"SkeletalMesh": "\\Game\\Meshes\\SkeletalMeshes\\",
"Skeleton": "\\Game\\Meshes\\SkeletalMeshes\\",
"SoundCue": "\\Game\\Media\\Sounds\\\\",
"SoundWave": "\\Game\\Media\\Sounds\\\\",
"StaticMesh": "\\Game\\Meshes\\",
"Structure": "\\Game\\Blueprints\\Data\\",
"Texture2D": "\\Game\\Materials\\Textures\\",
"TextureCube": "\\Game\\Materials\\Textures\\",
"TextureRenderTarget2D": "\\Game\\Materials\\Textures\\",
"UserDefinedEnum": "\\Game\\Blueprints\\Data\\",
"UserDefinedStruct": "\\Game\\Blueprints\\Data\\",
"WidgetBlueprint": "\\Game\\UMG\\",
"World": "\\Game\\Maps\\"
}
# get the selected assets
selected_assets = editor_util.get_selected_assets()
num_assets = len(selected_assets)
cleaned = 0
# hard coded parent directory
parent_dir = "\\Game"
for asset in selected_assets:
# get the class instance and the clear text name
asset_name = system_lib.get_object_name(asset)
asset_class = asset.get_class()
class_name = system_lib.get_class_display_name(asset_class)
Move_to_directory = Directory_mapping.get(class_name, None)
# Assemble path to relocate assets
try:
new_path = Move_to_directory + asset_name
# new_path = os.path.join(parent_dir, class_name, asset_name)
editor_asset_lib.rename_loaded_asset(asset, new_path)
cleaned += 1
unreal.log("Cleaned up {} to {}".format(asset_name, new_path))
# unreal.log(join(parent_dir, class_name, asset_name))
except Exception as err:
unreal.log("Could not move {} to new location {}".format(asset_name, new_path))
unreal.log("Asset {} with the class {}".format(asset_name, class_name))
unreal.log("Cleaned up {} of {} assets".format(cleaned, num_assets))
|
import unreal
""" Should be used with internal UE Python API
Switch to/from nanites on static meshes"""
static_mesh_editor_subsystem = unreal.get_editor_subsystem(
unreal.StaticMeshEditorSubsystem)
# Change me!
USE_NANITES = False
asset_root_dir = '/project/'
asset_reg = unreal.AssetRegistryHelpers.get_asset_registry()
assets = asset_reg.get_assets_by_path(asset_root_dir, recursive=True)
static_mesh_data = {}
for asset in assets:
if asset.asset_class == "StaticMesh":
asset_path = asset.object_path
asset_data = unreal.EditorAssetLibrary.find_asset_data(asset_path).get_asset()
static_mesh_data[asset_path] = asset_data
for static_mesh_path, static_mesh in static_mesh_data.items():
nanite_setting = static_mesh_editor_subsystem.get_nanite_settings(static_mesh)
if nanite_setting.enabled == USE_NANITES:
print("Already done", static_mesh)
continue
print("Enabing", static_mesh)
nanite_setting.enabled = USE_NANITES
static_mesh_editor_subsystem.set_nanite_settings(static_mesh, nanite_setting, True)
unreal.EditorAssetLibrary.save_asset(static_mesh_path, False)
|
import unreal
import json
import sys
import traceback
class MCPUnrealBridge:
@staticmethod
def get_actors():
"""Get all actors in the current level"""
result = []
actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) #unreal.EditorActorSubsystem().get_editor_subsystem()
actors = actor_subsystem.get_all_level_actors()
for actor in actors:
result.append({
"name": actor.get_name(),
"class": actor.get_class().get_name(),
"location": str(actor.get_actor_location())
})
return json.dumps({"status": "success", "result": result})
@staticmethod
def get_actor_details(actor_name):
"""Get details for a specific actor by name."""
result = {}
actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) #unreal.EditorActorSubsystem().get_editor_subsystem()
actors = actor_subsystem.get_all_level_actors()
for actor in actors:
if actor.get_name() == actor_name:
result = {
"name": actor.get_name(),
"class": actor.get_class().get_name(),
"location": str(actor.get_actor_location())
}
break
if not result:
result = f"Actor not found: {actor_name}"
return json.dumps({"status": "success", "result": result})
@staticmethod
def spawn_actor(asset_path, location_x=0, location_y=0, location_z=0, rotation_x=0, rotation_y=0, rotation_z=0, scale_x=0, scale_y=0, scale_z=0):
"""Spawn a new actor in the level"""
try:
# Find the class reference
class_obj = unreal.load_asset(asset_path)
if not class_obj:
return json.dumps({"status": "error", "message": f"Asset '{asset_path}' not found"})
# Create the actor
location = unreal.Vector(float(location_x), float(location_y), float(location_z))
rotation = unreal.Rotator(rotation_x, rotation_y, rotation_z)
actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
actor = actor_subsystem.spawn_actor_from_object(class_obj, location, rotation)
if actor:
actor.set_actor_scale3d(unreal.Vector(scale_x, scale_y, scale_z))
return json.dumps({
"status": "success",
"result": f"Created {asset_path} actor named '{actor.get_name()}' at location ({location_x}, {location_y}, {location_z})"
})
else:
return json.dumps({ "status": "error", "message" : "Failed to create actor" })
except Exception as e :
return json.dumps({ "status": "error", "message" : str(e) })
@staticmethod
def modify_actor(actor_name, property_name, property_value):
"""Modify a property of an existing actor"""
try:
actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) #unreal.EditorActorSubsystem().get_editor_subsystem()
actors = actor_subsystem.get_all_level_actors()
for actor in actors:
if actor.get_name() == actor_name:
# Try to determine property type and convert value
current_value = getattr(actor, property_name, None)
if current_value is not None:
if isinstance(current_value, float):
setattr(actor, property_name, float(property_value))
elif isinstance(current_value, int):
setattr(actor, property_name, int(property_value))
elif isinstance(current_value, bool):
setattr(actor, property_name, property_value.lower() in['true', 'yes', '1'])
elif isinstance(current_value, unreal.Vector):
# Assuming format like "X,Y,Z"
x, y, z = map(float, property_value.split(','))
setattr(actor, property_name, unreal.Vector(x, y, z))
else:
# Default to string
setattr(actor, property_name, property_value)
return json.dumps({
"status": "success",
"result" : f"Modified {property_name} on {actor_name} to {property_value}"
})
else:
return json.dumps({
"status": "error",
"message" : f"Property {property_name} not found on {actor_name}"
})
return json.dumps({ "status": "error", "message" : f"Actor '{actor_name}' not found" })
except Exception as e :
return json.dumps({ "status": "error", "message" : str(e) })
@staticmethod
def get_selected_actors():
"""Get the currently selected actors in the editor"""
try:
actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) #unreal.EditorActorSubsystem().get_editor_subsystem()
selected_actors = actor_subsystem.get_selected_level_actors()
result = []
for actor in selected_actors:
result.append({
"name": actor.get_name(),
"class" : actor.get_class().get_name(),
"location" : str(actor.get_actor_location())
})
return json.dumps({ "status": "success", "result": result })
except Exception as e:
return json.dumps({ "status": "error", "message": str(e) })
@staticmethod
def set_material(actor_name, material_path):
"""Apply a material to a static mesh actor"""
try:
actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) #unreal.EditorActorSubsystem().get_editor_subsystem()
actors = actor_subsystem.get_all_level_actors()
# Find the actor
target_actor = None
for actor in actors :
if actor.get_name() == actor_name :
target_actor = actor
break
if not target_actor:
return json.dumps({ "status": "error", "message" : f"Actor '{actor_name}' not found" })
# Check if it's a static mesh actor
if not target_actor.is_a(unreal.StaticMeshActor) :
return json.dumps({
"status": "error",
"message": f"Actor '{actor_name}' is not a StaticMeshActor"
})
# Load the material
material = unreal.load_object(None, material_path)
if not material:
return json.dumps({
"status": "error",
"message": f"Material '{material_path}' not found"
})
# Get the static mesh component
static_mesh_component = target_actor.get_component_by_class(unreal.StaticMeshComponent)
if not static_mesh_component:
return json.dumps({
"status": "error",
"message" : f"No StaticMeshComponent found on actor '{actor_name}'"
})
# Set the material
static_mesh_component.set_material(0, material)
return json.dumps({
"status": "success",
"result" : f"Applied material '{material_path}' to actor '{actor_name}'"
})
except Exception as e :
return json.dumps({ "status": "error", "message" : str(e) })
@staticmethod
def delete_all_static_mesh_actors():
"""Delete all static mesh actors in the scene"""
try:
# Get the editor subsystem
editor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
# Get all actors in the current level
try:
all_actors = editor_subsystem.get_all_level_actors()
except DeprecationWarning as dw:
# do nothing
pass
# Filter for StaticMeshActors
static_mesh_actors = [actor for actor in all_actors if isinstance(actor, unreal.StaticMeshActor)]
# Print how many StaticMeshActors were found
#print(f"Found {len(static_mesh_actors)} StaticMeshActors")
# Delete all StaticMeshActors
delete_count = 0
for actor in static_mesh_actors:
actor_name = actor.get_actor_label()
success = editor_subsystem.destroy_actor(actor)
if success:
delete_count = delete_count + 1
#print(f"Deleted StaticMeshActor: {actor_name}")
#else:
#print(f"Failed to delete StaticMeshActor: {actor_name}")
return json.dumps({
"status": "success",
"result" : f"Found {len(static_mesh_actors)} StaticMeshActors. Deleted {delete_count} StaticMeshActors."
})
except Exception as e:
return json.dumps({ "status": "error", "message": str(e) })
@staticmethod
def get_project_dir():
"""Get the top level project directory"""
try:
project_dir = unreal.Paths.project_dir()
return json.dumps({
"status": "success",
"result" : f"{project_dir}"
})
except Exception as e:
return json.dumps({ "status": "error", "message": str(e) })
@staticmethod
def get_content_dir():
"""Get the content directory"""
try:
#plugins_dir = unreal.Paths.project_plugins_dir()
#saved_dir = unreal.Paths.project_saved_dir()
#config_dir = unreal.Paths.project_config_dir()
content_dir = unreal.Paths.project_content_dir()
return json.dumps({
"status": "success",
"result" : f"{content_dir}"
})
except Exception as e:
return json.dumps({ "status": "error", "message": str(e) })
@staticmethod
def find_basic_shapes():
"""Search for basic shapes for building"""
try:
# Search for the asset
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
assets = asset_registry.get_assets_by_path('/project/', recursive=True)
# Find
tile_asset_paths = []
for asset in assets:
if asset.get_class().get_name() == 'StaticMesh':
tile_asset_paths.append(str(asset.package_name))
if not tile_asset_paths:
return json.dumps({ "status": "error", "message": f"Could not find basic shapes." })
else:
return json.dumps({
"status": "success",
"result" : tile_asset_paths
})
except Exception as e:
return json.dumps({ "status": "error", "message": str(e) })
@staticmethod
def find_assets(asset_name):
"""Search for specific assets by name, like Floor, Wall, Door"""
try:
# Search for the asset
asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
assets = asset_registry.get_assets_by_path('/Game', recursive=True)
# Find
tile_asset_paths = []
asset_name_lower = asset_name.lower()
for asset in assets:
this_name = str(asset.asset_name).lower()
if asset_name_lower in this_name:
asset_data = { "asset_class": str(asset.asset_class_path.asset_name), "asset_path": str(asset.package_name)}
tile_asset_paths.append(asset_data)
if not tile_asset_paths:
return json.dumps({ "status": "error", "message": f"Could not find {asset_name} asset." })
else:
return json.dumps({
"status": "success",
"result" : tile_asset_paths
})
except Exception as e:
return json.dumps({ "status": "error", "message": str(e) })
@staticmethod
def get_asset(asset_path):
# Define the correct path to the asset
# Try to load the asset
try:
#print("Loading asset...")
static_mesh = unreal.EditorAssetLibrary.load_asset(asset_path)
#print("Asset loaded: " + str(static_mesh != None))
if static_mesh:
#print("Asset class: " + static_mesh.__class__.__name__)
# Try to spawn an actor
try:
bounds = static_mesh.get_bounds()
bounds_min = bounds.origin - bounds.box_extent
bounds_max = bounds.origin + bounds.box_extent
width = bounds.box_extent.x * 2
depth = bounds.box_extent.y * 2
height = bounds.box_extent.z * 2
# Print dimensions
#print(f"Asset: SM_Env_Tiles_05")
#print(f"Bounds Min: {bounds_min}")
#print(f"Bounds Max: {bounds_max}")
#print(f"Dimensions (width × depth × height): {width} × {depth} × {height}")
#print(f"Volume: {bounds.box_extent.x * 2 * bounds.box_extent.y * 2 * bounds.box_extent.z * 2}")
result = {"width": width, "depth": depth, "height": height, "origin_x": bounds.origin.x, "origin_y": bounds.origin.y, "origin_z": bounds.origin.z}
return json.dumps({
"status": "success",
"result" : result
})
except Exception as e:
return json.dumps({ "status": "error", "message": str(e) })
else:
return json.dumps({ "status": "error", "message": f"Asset could not be loaded." })
except Exception as e:
return json.dumps({ "status": "error", "message": f"Error loading asset: {str(e)}" })
@staticmethod
def create_grid(asset_path, grid_width, grid_length):
import math
try:
# Load the static mesh
floor_asset = unreal.EditorAssetLibrary.load_asset(asset_path)
if not floor_asset:
return json.dumps({ "status": "error", "message": f"Failed to load static mesh: {asset_path}" })
# Grid dimensions
width = int(grid_width)
length = int(grid_length)
# Get asset dimensions
bounds = floor_asset.get_bounds()
tile_width = bounds.box_extent.x * 2
tile_length = bounds.box_extent.y * 2
# Create grid of floor tiles
tiles_created = 0
for x in range(width):
for y in range(length):
# Calculate position
location = unreal.Vector(x * tile_width, y * tile_length, 0)
# Create actor using EditorLevelLibrary
try:
actor = unreal.EditorLevelLibrary.spawn_actor_from_object(
floor_asset,
location,
unreal.Rotator(0, 0, 0)
)
except DeprecationWarning as dw:
# do nothing
pass
if actor:
tiles_created += 1
actor.set_actor_label(f"FloorTile_{x}_{y}")
center_x = width // 2
center_y = length // 2
position_x = center_x * tile_width
position_y = center_y * tile_length
return json.dumps({
"status": "success",
"result" : f"Successfully created grid centered at tile location: ({center_x}, {center_y}) and world location: ({position_x}, {position_y}, 0.0))."
})
except Exception as e:
return json.dumps({ "status": "error", "message": f"Error loading asset: {str(e)}" })
@staticmethod
def create_town(town_center_x=1250, town_center_y=1250, town_width=7000, town_height=7000):
"""
Create a town using supplied assets with customizable size and position
Args:
town_center_x (float): X coordinate of the town center
town_center_y (float): Y coordinate of the town center
town_width (float): Total width of the town area
town_height (float): Total height of the town area
"""
import random
import math
#print(f"Starting to build fantasy town at ({town_center_x}, {town_center_y}) with size {town_width}x{town_height}...")
# Base paths for our assets
model_base_path = "/project/"
# Helper function to load an asset
def load_asset(asset_name):
full_path = f"{model_base_path}/{asset_name}.{asset_name}"
return unreal.EditorAssetLibrary.load_asset(full_path)
# Track placed objects for collision detection
placed_objects = []
# Helper function to check for collision with existing objects
def check_collision(new_bounds, tolerance=10.0):
"""Check if the new object bounds overlap with any existing objects"""
for obj_bounds in placed_objects:
# Check if the bounds overlap in X, Y dimensions with some tolerance
if (new_bounds["min_x"] - tolerance <= obj_bounds["max_x"] and
new_bounds["max_x"] + tolerance >= obj_bounds["min_x"] and
new_bounds["min_y"] - tolerance <= obj_bounds["max_y"] and
new_bounds["max_y"] + tolerance >= obj_bounds["min_y"]):
return True
return False
# Helper function to place an actor with collision detection
def place_actor(static_mesh, x, y, z=0, rotation_z=0, scale=(1.0, 1.0, 1.0), name=None, max_attempts=5):
if not static_mesh:
#print(f"Cannot place actor: Static mesh is invalid")
return None
editor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
# Get the bounds of the mesh
bounds = static_mesh.get_bounds()
bounds_min = bounds.origin - bounds.box_extent
bounds_max = bounds.origin + bounds.box_extent
# Calculate width, depth, height
width = bounds.box_extent.x * scale[0]
depth = bounds.box_extent.y * scale[1]
height = bounds.box_extent.z * scale[2]
# Try multiple positions if collision occurs
for attempt in range(max_attempts):
# Add small variation to position for retry attempts after the first
x_offset = 0
y_offset = 0
if attempt > 0:
jitter_range = 20.0 * attempt # Increase jitter with each attempt
x_offset = random.uniform(-jitter_range, jitter_range)
y_offset = random.uniform(-jitter_range, jitter_range)
pos_x = x + x_offset
pos_y = y + y_offset
# Calculate the bounds of the actor at this position with rotation
rad_rotation = math.radians(rotation_z)
sin_rot = math.sin(rad_rotation)
cos_rot = math.cos(rad_rotation)
# Calculate the 4 corners of the bounding box after rotation
corners = [
(pos_x - width/2, pos_y - depth/2), # Bottom-left
(pos_x + width/2, pos_y - depth/2), # Bottom-right
(pos_x + width/2, pos_y + depth/2), # Top-right
(pos_x - width/2, pos_y + depth/2) # Top-left
]
# Rotate the corners
rotated_corners = []
for corner_x, corner_y in corners:
dx = corner_x - pos_x
dy = corner_y - pos_y
rotated_x = pos_x + dx * cos_rot - dy * sin_rot
rotated_y = pos_y + dx * sin_rot + dy * cos_rot
rotated_corners.append((rotated_x, rotated_y))
# Find the extents of the rotated box
x_values = [p[0] for p in rotated_corners]
y_values = [p[1] for p in rotated_corners]
min_x = min(x_values)
max_x = max(x_values)
min_y = min(y_values)
max_y = max(y_values)
new_bounds = {
"min_x": min_x,
"max_x": max_x,
"min_y": min_y,
"max_y": max_y,
"center_x": pos_x,
"center_y": pos_y
}
# Check if this position would cause a collision
if not check_collision(new_bounds):
# No collision, so place the actor
location = unreal.Vector(pos_x, pos_y, z)
rotation = unreal.Rotator(0, 0, rotation_z)
actor = editor_subsystem.spawn_actor_from_object(static_mesh, location, rotation)
if actor:
if name:
actor.set_actor_label(name)
# Apply scale if needed
if scale != (1.0, 1.0, 1.0):
actor.set_actor_scale3d(unreal.Vector(scale[0], scale[1], scale[2]))
# Record the placed object
placed_objects.append(new_bounds)
#if attempt > 0:
# print(f"Placed {name} at alternate position after {attempt+1} attempts")
return actor
#print(f"Failed to place {name} after {max_attempts} attempts due to collisions")
return None
# Helper function to get mesh dimensions
def get_mesh_dimensions(static_mesh, scale=(1.0, 1.0, 1.0)):
if not static_mesh:
return 0, 0, 0
bounds = static_mesh.get_bounds()
width = bounds.box_extent.x * scale[0]
depth = bounds.box_extent.y * scale[1]
height = bounds.box_extent.z * scale[2]
return width, depth, height
# New helper for placing continuous walls or fences
def place_continuous_segments(mesh, start_point, end_point, z=0, rotation_offset=0, scale=(1.0, 1.0, 1.0), name_prefix="Segment", skip_indices=None):
if not mesh:
#print(f"Cannot place continuous segments: Mesh is invalid")
return []
if skip_indices is None:
skip_indices = []
# Get the dimensions of the mesh
mesh_width, mesh_depth, mesh_height = get_mesh_dimensions(mesh, scale)
# For walls/fences, we assume they extend primarily along one dimension (width)
segment_length = mesh_width
# Calculate distance and direction
start_x, start_y = start_point
end_x, end_y = end_point
dx = end_x - start_x
dy = end_y - start_y
distance = math.sqrt(dx*dx + dy*dy)
# Calculate the angle of the line
angle = math.degrees(math.atan2(dy, dx))
# Calculate number of segments needed to cover the distance
# Subtract a small overlap percentage to ensure segments connect properly
overlap_factor = 0.05 # 5% overlap to ensure no gaps
effective_segment_length = segment_length * (1 - overlap_factor)
num_segments = max(1, math.ceil(distance / effective_segment_length))
# Place segments along the line
placed_actors = []
for i in range(num_segments):
if i in skip_indices:
continue
# Calculate position along the line
t = i / num_segments
pos_x = start_x + t * dx
pos_y = start_y + t * dy
# Place the segment
actor = place_actor(mesh, pos_x, pos_y, z, angle + rotation_offset, scale, f"{name_prefix}_{i}")
if actor:
placed_actors.append(actor)
return placed_actors
try:
# Calculate the scale factor based on town size compared to the original
# Original size was approximately 700x700
width_scale = 1.0 #town_width / 700.0
height_scale = 1.0 #town_height / 700.0
# We'll use this to scale distances and positions
scale_factor = min(width_scale, height_scale) # Use the smaller scale to ensure everything fits
# STEP 1: PLACE BUILDINGS
#print("STEP 1: Placing buildings...")
# Load building assets
buildings = {
"town_hall": load_asset("Town_Hall"),
"large_house": load_asset("Large_house"),
"small_house": load_asset("Small_house"),
"baker_house": load_asset("Baker_house"),
"tavern": load_asset("Tavern"),
"witch_house": load_asset("Witch_house"),
"tower": load_asset("Tower"),
"mill": load_asset("Mill"),
"woodmill": load_asset("Woodmill"),
"forge": load_asset("Forge"),
"mine": load_asset("Mine")
}
# Check if assets loaded correctly
#for name, asset in buildings.items():
# if not asset:
# print(f"Failed to load {name}")
# Place central buildings - town hall
place_actor(buildings["town_hall"], town_center_x, town_center_y, 0, 0, name="Central_TownHall")
# Place tavern near the town center - scale the offset by our scale factor
place_actor(buildings["tavern"],
town_center_x + 800 * scale_factor,
town_center_y + 600 * scale_factor,
0, 135, name="Tavern")
# Place houses around the center - scaled based on town size
house_positions = [
# North district
(town_center_x - 1800 * scale_factor, town_center_y - 1900 * scale_factor, 45, "small_house", "North_House_1"),
(town_center_x - 2100 * scale_factor, town_center_y - 2200 * scale_factor, 30, "baker_house", "North_BakerHouse"),
(town_center_x - 1300 * scale_factor, town_center_y - 2000 * scale_factor, 15, "small_house", "North_House_2"),
# East district
(town_center_x + 2200 * scale_factor, town_center_y - 1300 * scale_factor, 270, "large_house", "East_LargeHouse"),
(town_center_x + 2400 * scale_factor, town_center_y + 1200 * scale_factor, 300, "small_house", "East_House_1"),
(town_center_x + 1900 * scale_factor, town_center_y - 1700 * scale_factor, 315, "small_house", "East_House_2"),
# South district
(town_center_x + 1300 * scale_factor, town_center_y + 2100 * scale_factor, 180, "large_house", "South_LargeHouse"),
(town_center_x - 1200 * scale_factor, town_center_y + 1950 * scale_factor, 135, "small_house", "South_House_1"),
# West district
(town_center_x - 2000 * scale_factor, town_center_y + 1100 * scale_factor, 90, "large_house", "West_LargeHouse"),
(town_center_x - 2300 * scale_factor, town_center_y + 1500 * scale_factor, 45, "small_house", "West_House_1")
]
# Place the houses
for x, y, rot, house_type, name in house_positions:
place_actor(buildings[house_type], x, y, 0, rot, name=name)
# Place special buildings
# Tower
place_actor(buildings["tower"],
town_center_x - 3000 * scale_factor,
town_center_y - 2900 * scale_factor,
0, 45, name="North_Tower")
# Witch's house in a more secluded area
place_actor(buildings["witch_house"],
town_center_x + 3000 * scale_factor,
town_center_y + 2900 * scale_factor,
0, 215, name="WitchHouse")
# Mill near water (imaginary river)
mill_x = town_center_x + 2900 * scale_factor
mill_y = town_center_y - 3000 * scale_factor
mill = place_actor(buildings["mill"], mill_x, mill_y, 0, 270, name="Watermill")
# Mill wings - need to be attached to the mill
mill_wings = load_asset("Mill_wings")
if mill and mill_wings:
place_actor(mill_wings, mill_x, mill_y, 0, 270, name="Watermill_Wings")
# Woodmill in a wooded area
woodmill_x = town_center_x - 2900 * scale_factor
woodmill_y = town_center_y - 2400 * scale_factor
place_actor(buildings["woodmill"], woodmill_x, woodmill_y, 0, 135, name="Woodmill")
woodmill_saw = load_asset("Woodmill_Saw")
if woodmill_saw:
place_actor(woodmill_saw, woodmill_x, woodmill_y, 0, 135, name="Woodmill_Saw")
# Forge
place_actor(buildings["forge"],
town_center_x + 1600 * scale_factor,
town_center_y - 1500 * scale_factor,
0, 330, name="Forge")
# Mine at the edge of town
place_actor(buildings["mine"],
town_center_x - 2900 * scale_factor,
town_center_y + 2900 * scale_factor,
0, 135, name="Mine")
#print("Buildings placed successfully")
# STEP 2: ADD NATURE ELEMENTS
#print("STEP 2: Adding trees, plants, and rocks...")
# Load nature assets
nature = {
"tree_1": load_asset("Tree_1"),
"tree_2": load_asset("Tree_2"),
"tree_4": load_asset("Tree_4"),
"pine_tree": load_asset("Pine_tree"),
"pine_tree_2": load_asset("Pine_tree_2"),
"bush_1": load_asset("Bush_1"),
"bush_2": load_asset("Bush_2"),
"fern": load_asset("Fern"),
"flowers_1": load_asset("Flowers_1"),
"flowers_2": load_asset("Flowers_2"),
"plant": load_asset("Plant"),
"rock_1": load_asset("Rock_1"),
"rock_2": load_asset("Rock_2"),
"rock_3": load_asset("Rock_3"),
"rock_4": load_asset("Rock_4"),
"stump": load_asset("Stump"),
"log": load_asset("Log"),
"mushroom_1": load_asset("Mushroom_1"),
"mushroom_2": load_asset("Mushroom_2")
}
# Create a forest area near the witch's house
forest_center_x = town_center_x + 2900 * scale_factor
forest_center_y = town_center_y + 2200 * scale_factor
forest_radius = 1500 * scale_factor
# Determine number of trees based on forest area
num_trees = int(500 * scale_factor)
# Add trees to the forest
for i in range(num_trees):
# Calculate random position within the forest area
angle = random.uniform(0, 2 * math.pi)
distance = random.uniform(0, forest_radius)
x = forest_center_x + distance * math.cos(angle)
y = forest_center_y + distance * math.sin(angle)
# Choose a random tree type
tree_type = random.choice(["tree_1", "tree_2", "tree_4", "pine_tree", "pine_tree_2"])
rot = random.uniform(0, 360)
scale = random.uniform(0.8, 1.2)
tree = place_actor(nature[tree_type], x, y, 0, rot, (scale, scale, scale), f"Forest_Tree_{i}")
# Add some undergrowth near trees if the tree was placed successfully
if tree and random.random() < 0.6:
undergrowth_type = random.choice(["bush_1", "bush_2", "fern", "mushroom_1", "mushroom_2"])
offset_x = random.uniform(-100, 100)
offset_y = random.uniform(-100, 100)
undergrowth_scale = random.uniform(0.7, 1.0)
place_actor(nature[undergrowth_type],
x + offset_x,
y + offset_y,
0,
random.uniform(0, 360),
(undergrowth_scale, undergrowth_scale, undergrowth_scale),
f"Forest_Undergrowth_{i}")
# Add scattered trees around town - scale the number by town size
scattered_trees = int(100 * scale_factor)
for i in range(scattered_trees):
angle = random.uniform(0, 2 * math.pi)
distance = random.uniform(3000, 3000) * scale_factor
x = town_center_x + distance * math.cos(angle)
y = town_center_y + distance * math.sin(angle)
# Avoid placing in the forest area
forest_dist = math.sqrt((x - forest_center_x)**2 + (y - forest_center_y)**2)
if forest_dist < forest_radius:
continue
tree_type = random.choice(["tree_1", "tree_2", "tree_4"])
rot = random.uniform(0, 360)
scale = random.uniform(0.9, 1.1)
place_actor(nature[tree_type], x, y, 0, rot, (scale, scale, scale), f"Town_Tree_{i}")
# Add some rocks scattered around
num_rocks = int(15 * scale_factor)
for i in range(num_rocks):
angle = random.uniform(0, 2 * math.pi)
distance = random.uniform(3000, 3000) * scale_factor
x = town_center_x + distance * math.cos(angle)
y = town_center_y + distance * math.sin(angle)
rock_type = random.choice(["rock_1", "rock_2", "rock_3", "rock_4"])
rot = random.uniform(0, 360)
scale = random.uniform(0.8, 1.5)
place_actor(nature[rock_type], x, y, 0, rot, (scale, scale, scale), f"Rock_{i}")
# Create gardens near houses
houses = [
(town_center_x - 2000 * scale_factor, town_center_y - 1900 * scale_factor), # North_House_1
(town_center_x - 1300 * scale_factor, town_center_y - 2000 * scale_factor), # North_House_2
(town_center_x + 2400 * scale_factor, town_center_y + 1200 * scale_factor), # East_House_1
(town_center_x - 1200 * scale_factor, town_center_y + 1950 * scale_factor), # South_House_1
]
for idx, (house_x, house_y) in enumerate(houses):
garden_x = house_x + random.uniform(200, 300)
garden_y = house_y + random.uniform(200, 300)
# Place flowers and plants in the garden
plants_per_garden = int(5 * scale_factor)
for j in range(plants_per_garden):
plant_x = garden_x + random.uniform(-100, 100)
plant_y = garden_y + random.uniform(-100, 100)
plant_type = random.choice(["flowers_1", "flowers_2", "plant", "bush_1"])
rot = random.uniform(0, 360)
place_actor(nature[plant_type], plant_x, plant_y, 0, rot, name=f"Garden_{idx}_Plant_{j}")
#print("Nature elements added successfully")
# STEP 3: CREATE FENCES
#print("STEP 3: Building fences...")
# Load fence assets
fences = {
"fence": load_asset("Fence"),
"fence_1": load_asset("Fence_1"),
"fence_2": load_asset("Fence_2"),
"stone_fence": load_asset("Stone_fence")
}
# Define garden perimeters to fence
gardens = [
{
"center": (town_center_x - 1800 * scale_factor, town_center_y - 1900 * scale_factor), # North_House_1
"size": (30 * scale_factor, 30 * scale_factor),
"fence_type": "fence",
"name": "North_House_1_Garden"
},
{
"center": (town_center_x + 2400 * scale_factor, town_center_y + 1200 * scale_factor), # East_House_1
"size": (25 * scale_factor, 30 * scale_factor),
"fence_type": "fence_1",
"name": "East_House_1_Garden"
},
{
"center": (town_center_x + 1300 * scale_factor, town_center_y + 2200 * scale_factor), # South_LargeHouse
"size": (35 * scale_factor, 35 * scale_factor),
"fence_type": "fence_2",
"name": "South_LargeHouse_Garden"
}
]
# For each garden, create a fence perimeter
for garden in gardens:
center_x, center_y = garden["center"]
width, height = garden["size"]
fence_type = garden["fence_type"]
name_prefix = garden["name"]
# Calculate the corner points of the garden
half_width = width / 2
half_height = height / 2
corners = [
(center_x - half_width, center_y - half_height), # Bottom-left
(center_x + half_width, center_y - half_height), # Bottom-right
(center_x + half_width, center_y + half_height), # Top-right
(center_x - half_width, center_y + half_height) # Top-left
]
# Build the perimeter with continuous segments
for i in range(4):
start_point = corners[i]
end_point = corners[(i + 1) % 4]
# For each side, determine if we need a gate
skip_indices = []
if i == 0: # Usually front of the garden has a gate
skip_indices = [1] # Skip middle segment for a gate
# Place continuous fence segments
place_continuous_segments(
fences[fence_type],
start_point,
end_point,
0, # z coordinate
90, # rotation offset (fences usually need to be rotated perpendicular to the line)
(1.0, 1.0, 1.0), # scale
f"{name_prefix}_Fence_{i}",
skip_indices
)
# Create a fence around the town center square
town_square = {
"center": (town_center_x, town_center_y),
"size": (90 * scale_factor, 90 * scale_factor),
"fence_type": "stone_fence",
"name": "Town_Square"
}
center_x, center_y = town_square["center"]
width, height = town_square["size"]
fence_type = town_square["fence_type"]
name_prefix = town_square["name"]
# Calculate the corner points
half_width = width / 2
half_height = height / 2
corners = [
(center_x - half_width, center_y - half_height), # Bottom-left
(center_x + half_width, center_y - half_height), # Bottom-right
(center_x + half_width, center_y + half_height), # Top-right
(center_x - half_width, center_y + half_height) # Top-left
]
# Build the perimeter with continuous segments and gates
for i in range(4):
start_point = corners[i]
end_point = corners[(i + 1) % 4]
# Create entrance gates on all sides
skip_indices = [1] # Skip middle segment for a gate
# Place continuous stone fence segments
place_continuous_segments(
fences[fence_type],
start_point,
end_point,
0, # z coordinate
90, # rotation offset
(1.0, 1.0, 1.0), # scale
f"{name_prefix}_Fence_{i}",
skip_indices
)
#print("Fences created successfully")
# STEP 4: BUILD WALLS
#print("STEP 4: Building walls...")
# Load wall assets
walls = {
"wall_1": load_asset("Wall_1"),
"wall_2": load_asset("Wall_2")
}
# Get wall dimensions for alternating walls
wall1_width, _, _ = get_mesh_dimensions(walls["wall_1"])
wall2_width, _, _ = get_mesh_dimensions(walls["wall_2"])
# Define the town perimeter for walls - use the provided town width and height
town_perimeter = {
"center": (town_center_x, town_center_y),
"size": (town_width, town_height),
"name": "Town_Wall"
}
center_x, center_y = town_perimeter["center"]
width, height = town_perimeter["size"]
name_prefix = town_perimeter["name"]
# Calculate the corner points
half_width = (width / 2) - wall1_width
half_height = (height / 2) - wall1_width
corners = [
(center_x - half_width, center_y - half_height), # Bottom-left
(center_x + half_width, center_y - half_height), # Bottom-right
(center_x + half_width, center_y + half_height), # Top-right
(center_x - half_width, center_y + half_height) # Top-left
]
# Build the perimeter with continuous wall segments
# For each side, first measure the total length and determine how many of each wall type to use
for i in range(4):
start_point = corners[i]
end_point = corners[(i + 1) % 4]
# Calculate side length
start_x, start_y = start_point
end_x, end_y = end_point
side_length = math.sqrt((end_x - start_x)**2 + (end_y - start_y)**2)
# Determine where to place gates - we'll place 1-2 gates on each side based on length
# Calculate how many walls would fit on this side
effective_wall1_length = wall1_width * 0.95 # Account for slight overlap
num_wall1_segments = math.ceil(side_length / effective_wall1_length)
# Identify gate positions - which segments to skip
gate_skip_indices = []
if num_wall1_segments > 8:
# Place two gates if the wall is long enough
gate_skip_indices = [num_wall1_segments // 3, 2 * num_wall1_segments // 3]
else:
# Otherwise just one gate in the middle
gate_skip_indices = [num_wall1_segments // 2]
# Place the wall segments using primarily wall_1 with gates
wall1_actors = place_continuous_segments(
walls["wall_1"],
start_point,
end_point,
0, # z coordinate
0, # no rotation offset for walls
(1.0, 1.0, 1.0), # scale
f"{name_prefix}_Wall1_{i}",
gate_skip_indices
)
# For each gate position, place a tower
for gate_idx in gate_skip_indices:
t = gate_idx / num_wall1_segments
pos_x = start_x + t * (end_x - start_x)
pos_y = start_y + t * (end_y - start_y)
# Calculate angle
angle = math.degrees(math.atan2(end_y - start_y, end_x - start_x))
# Place tower at gate position
tower = load_asset("Tower")
if tower:
place_actor(tower, pos_x, pos_y, 0, angle + 90, name=f"Gate_Tower_{i}_{gate_idx}")
#print("Walls built successfully")
# STEP 5: ADD FINAL DETAILS
#print("STEP 5: Adding final details and props...")
# Load remaining prop assets
props = {
"anvil": load_asset("Anvil"),
"barrel": load_asset("Barrel"),
"chest": load_asset("Chest"),
"cauldron": load_asset("Cauldron"),
"altar": load_asset("Altar"),
"well": load_asset("Well"),
"trolley": load_asset("Trolley"),
"lamppost": load_asset("Lamppost"),
"street_light": load_asset("street_light")
}
# Place a well in the town center
place_actor(props["well"], town_center_x + 150 * scale_factor, town_center_y - 150 * scale_factor, 0, 0, name="Town_Center_Well")
# Place streetlights around the town square
square_size = 90 * scale_factor
light_spacing = 30 * scale_factor
for i in range(4):
for j in range(3):
if j == 1: # Skip middle to accommodate entrances
continue
# Calculate position along each side of the square
if i == 0: # North side
x = town_center_x - square_size/2 + j * light_spacing
y = town_center_y - square_size/2
rot = 0
elif i == 1: # East side
x = town_center_x + square_size/2
y = town_center_y - square_size/2 + j * light_spacing
rot = 90
elif i == 2: # South side
x = town_center_x + square_size/2 - j * light_spacing
y = town_center_y + square_size/2
rot = 180
else: # West side
x = town_center_x - square_size/2
y = town_center_y + square_size/2 - j * light_spacing
rot = 270
light_type = "lamppost" if j % 2 == 0 else "street_light"
place_actor(props[light_type], x, y, 0, rot, name=f"Square_Light_{i}_{j}")
# Add props near the forge
forge_x = town_center_x + 600 * scale_factor
forge_y = town_center_y - 500 * scale_factor
place_actor(props["anvil"], forge_x + 50 * scale_factor, forge_y - 80 * scale_factor, 0, 45, name="Forge_Anvil")
place_actor(props["barrel"], forge_x - 70 * scale_factor, forge_y - 60 * scale_factor, 0, 0, name="Forge_Barrel")
# Add barrels and chests around the tavern
tavern_x = town_center_x + 700 * scale_factor
tavern_y = town_center_y + 600 * scale_factor
for i in range(3):
x_offset = random.uniform(-150, 150) * scale_factor
y_offset = random.uniform(-150, 150) * scale_factor
rot = random.uniform(0, 360)
place_actor(props["barrel"], tavern_x + x_offset, tavern_y + y_offset, 0, rot, name=f"Tavern_Barrel_{i}")
place_actor(props["chest"], tavern_x - 100 * scale_factor, tavern_y + 120 * scale_factor, 0, 45, name="Tavern_Chest")
# Add altar near the witch's house
witch_house_x = town_center_x + 1800 * scale_factor
witch_house_y = town_center_y + 1500 * scale_factor
place_actor(props["altar"], witch_house_x + 150 * scale_factor, witch_house_y + 100 * scale_factor, 0, 215, name="Witch_Altar")
place_actor(props["cauldron"], witch_house_x - 80 * scale_factor, witch_house_y + 120 * scale_factor, 0, 0, name="Witch_Cauldron")
# Add a trolley near the mine
mine_x = town_center_x - 2200 * scale_factor
mine_y = town_center_y + 1800 * scale_factor
place_actor(props["trolley"], mine_x + 150 * scale_factor, mine_y - 100 * scale_factor, 0, 45, name="Mine_Trolley")
# Create a path connecting major locations with Tile assets
tiles = {
"tile_1": load_asset("Tile_1"),
"tile_2": load_asset("Tile_2"),
"tile_3": load_asset("Tile_3"),
"tile_4": load_asset("Tile_4"),
"tile_5": load_asset("Tile_5"),
"tile_6": load_asset("Tile_6"),
"tile_7": load_asset("Tile_7")
}
# Define major path points - scaled based on town size
path_points = [
(town_center_x, town_center_y), # Town center
(town_center_x + 700 * scale_factor, town_center_y + 600 * scale_factor), # Tavern
(town_center_x + 600 * scale_factor, town_center_y - 500 * scale_factor), # Forge
(town_center_x - 1000 * scale_factor, town_center_y - 1700 * scale_factor), # Tower
(town_center_x + 1700 * scale_factor, town_center_y - 1200 * scale_factor), # Watermill
(town_center_x - 1800 * scale_factor, town_center_y - 400 * scale_factor), # Woodmill
(town_center_x - 2200 * scale_factor, town_center_y + 1800 * scale_factor), # Mine
(town_center_x + 1800 * scale_factor, town_center_y + 1500 * scale_factor) # Witch house
]
# Create paths between points
for i in range(len(path_points) - 1):
start_x, start_y = path_points[i]
end_x, end_y = path_points[i + 1]
# Calculate distance and direction
dx = end_x - start_x
dy = end_y - start_y
distance = math.sqrt(dx*dx + dy*dy)
# Tile spacing - scale by the town size
tile_spacing = 100 * scale_factor
num_tiles = int(distance / tile_spacing)
# Place tiles along the path
for j in range(num_tiles):
t = j / num_tiles
x = start_x + t * dx
y = start_y + t * dy
# Add some randomness to make the path look more natural
offset_x = random.uniform(-20, 20) * scale_factor
offset_y = random.uniform(-20, 20) * scale_factor
# Random tile type
tile_type = random.choice(["tile_1", "tile_2", "tile_3", "tile_4", "tile_5", "tile_6", "tile_7"])
rot = random.uniform(0, 360)
place_actor(tiles[tile_type], x + offset_x, y + offset_y, 1, rot, name=f"Path_Tile_{i}_{j}")
#print("Final details added successfully")
#print(f"Fantasy town creation complete at ({town_center_x}, {town_center_y}) with size {town_width}x{town_height}!")
return json.dumps({
"status": "success",
"result": f"Successfully created fantasy town at ({town_center_x}, {town_center_y}) with size {town_width}x{town_height}."
})
except Exception as e:
return json.dumps({ "status": "error", "message": f"Error building town: {str(e)}" })
@staticmethod
def execute_blueprint_function(blueprint_name, function_name, arguments = ""):
"""Execute a function in a Blueprint"""
try:
# Find the Blueprint asset
blueprint_asset = unreal.find_asset(blueprint_name)
if not blueprint_asset:
return json.dumps({
"status": "error",
"message" : f"Blueprint '{blueprint_name}' not found"
})
# Get the blueprint class
blueprint_class = unreal.load_class(blueprint_asset)
if not blueprint_class:
return json.dumps({
"status": "error",
"message": f"Could not load class from Blueprint '{blueprint_name}'"
})
# Get the CDO(Class Default Object)
cdo = unreal.get_default_object(blueprint_class)
# Parse arguments
parsed_args = []
if arguments:
for arg in arguments.split(','):
arg = arg.strip()
# Try to determine argument type
if arg.lower() in ['true', 'false']:
parsed_args.append(arg.lower() == 'true')
elif arg.isdigit():
parsed_args.append(int(arg))
elif arg.replace('.', '', 1).isdigit():
parsed_args.append(float(arg))
else:
parsed_args.append(arg)
# Call the function
result = getattr(cdo, function_name)(*parsed_args)
return json.dumps({
"status": "success",
"result" : f"Function '{function_name}' executed. Result: {result}"
})
except Exception as e:
return json.dumps({ "status": "error", "message": str(e) })
@staticmethod
def execute_python(code):
"""Execute arbitrary Python code in Unreal Engine"""
try:
# decode and extract dict object
#decoded = chunk.decode('utf-8', 'replace')
#stripped = decoded.strip('\'"\n\r')
replaced = code.replace('\\\\','\\').replace('\\"','"').replace("\\'","'").replace('f"\n', 'f"').replace('f\'\n', 'f\'').replace('\n"', '"').replace('\n\'', '\'')
#response = json.loads(replaced)
# save to file first
#code_file = open('code.py', 'w')
#code_file.write(code)
#code_file.close()
# read back
#code_file = open('code.py', 'r')
#code_text = code_file.read()
#code_file.close()
# check for syntax errors
try:
code_obj = compile(replaced, '<string>', 'exec')
except SyntaxError as se:
return json.dumps({
"status": "error",
"message" : f"Syntax Error executing Python code: {str(se)}",
"traceback" : traceback.format_exc()
})
except Exception as ex:
return json.dumps({
"status": "error",
"message" : f"Error executing Python code: {str(ex)}",
"traceback" : traceback.format_exc()
})
try:
# Create output capture file
output_file = open('output.txt', 'w')
error_file = open('error.txt', 'w')
# Store original stdout and stderr
original_stdout = sys.stdout
original_stderr = sys.stderr
# Redirect stdout and stderr
sys.stdout = output_file
sys.stderr = error_file
# Create a local dictionary for execution
locals_dict = { 'unreal': unreal, 'result': None }
# Execute the compiled code
exec(code_obj, globals(), locals_dict)
except AttributeError as ae:
return json.dumps({
"status": "error",
"message" : f"Attribute Error in code: {str(ae)}",
"traceback" : traceback.format_exc()
})
except Exception as ee:
return json.dumps({
"status": "error",
"message" : f"Python exec() error: {str(ee)}",
"traceback" : traceback.format_exc()
})
finally:
# close output
output_file.close()
error_file.close()
# Restore original stdout and stderr
sys.stdout = original_stdout
sys.stderr = original_stderr
# read output
read_output = open('output.txt', 'r')
result = read_output.read()
read_output.close()
# read errors
read_error = open('error.txt', 'r')
error_text = read_error.read()
read_error.close()
# Return the result if it was set
if 'result' in locals_dict and locals_dict['result'] is not None:
return json.dumps({
"status": "success",
"result" : str(locals_dict['result'])
})
elif error_text and len(error_text) > 0:
return json.dumps({
"status": "error",
"result": error_text
})
elif not result:
return json.dumps({
"status": "error",
"result": "Python code did not execute Successfully. No result set."
})
else:
return json.dumps({
"status": "success",
"result": str(result)
})
except Exception as exc:
# read error
error_msg = str(exc)
read_error = open('error.txt', 'r')
if read_error:
error_msg = read_error.read()
read_error.close()
return json.dumps({
"status": "error",
"message" : f"Python exec() error: {error_msg}",
"traceback" : traceback.format_exc()
})
# Register the bridge as a global variable
mcp_bridge = MCPUnrealBridge()
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Example script that uses unreal.ActorIterator to iterate over all
HoudiniAssetActors in the editor world, creates API wrappers for them, and
logs all of their parameter tuples.
"""
import unreal
def run():
# Get the API instance
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
# Get the editor world
editor_subsystem = None
world = None
try:
# In UE5 unreal.EditorLevelLibrary.get_editor_world is deprecated and
# unreal.UnrealEditorSubsystem.get_editor_world is the replacement,
# but unreal.UnrealEditorSubsystem does not exist in UE4
editor_subsystem = unreal.UnrealEditorSubsystem()
except AttributeError:
world = unreal.EditorLevelLibrary.get_editor_world()
else:
world = editor_subsystem.get_editor_world()
# Iterate over all Houdini Asset Actors in the editor world
for houdini_actor in unreal.ActorIterator(world, unreal.HoudiniAssetActor):
if not houdini_actor:
continue
# Print the name and label of the actor
actor_name = houdini_actor.get_name()
actor_label = houdini_actor.get_actor_label()
print(f'HDA Actor (Name, Label): {actor_name}, {actor_label}')
# Wrap the Houdini asset actor with the API
wrapper = unreal.HoudiniPublicAPIAssetWrapper.create_wrapper(world, houdini_actor)
if not wrapper:
continue
# Get all parameter tuples of the HDA
parameter_tuples = wrapper.get_parameter_tuples()
if parameter_tuples is None:
# The operation failed, log the error message
error_message = wrapper.get_last_error_message()
if error_message is not None:
print(error_message)
continue
print(f'# Parameter Tuples: {len(parameter_tuples)}')
for name, data in parameter_tuples.items():
print(f'\tParameter Tuple Name: {name}')
type_name = None
values = None
if data.bool_values:
type_name = 'Bool'
values = '; '.join(('1' if v else '0' for v in data.bool_values))
elif data.float_values:
type_name = 'Float'
values = '; '.join((f'{v:.4f}' for v in data.float_values))
elif data.int32_values:
type_name = 'Int32'
values = '; '.join((f'{v:d}' for v in data.int32_values))
elif data.string_values:
type_name = 'String'
values = '; '.join(data.string_values)
if not type_name:
print('\t\tEmpty')
else:
print(f'\t\t{type_name} Values: {values}')
if __name__ == '__main__':
run()
|
import sys
class Colors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def __print_unreal__(message, color=None):
import unreal
if color == Colors.WARNING:
unreal.log_warning(message)
elif color == Colors.FAIL:
unreal.log_error(message)
else:
unreal.log(message)
def __print_console__(message, color=None):
if color:
print(color + message + Colors.ENDC)
else:
print(message)
if "unreal" in sys.modules:
print_message = __print_unreal__
else:
print_message = __print_console__
def log(message):
print_message(message)
def success(message):
print_message(message, Colors.OKGREEN)
def warn(message):
print_message(message, Colors.WARNING)
def error(message):
print_message(message, Colors.FAIL)
|
import os
import random
import numpy as np
from PIL import Image
import unreal
import unreal_engine.utils as utils
def _generate_random_texture(size, path):
noise = np.random.rand(size, size, 3) * 255
image = np.array(noise, dtype=np.uint8)
img = Image.fromarray(image, 'RGB')
img.save(path)
def _create_material_with_texture(texture_path, material_name):
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
assetImportData = unreal.AutomatedAssetImportData()
material_asset_path = f"/project/{material_name}"
assetImportData.destination_path = material_asset_path
assetImportData.filenames = [texture_path]
assetImportData.replace_existing = True
imported_assets = asset_tools.import_assets_automated(assetImportData)
texture_asset_path = imported_assets[0].get_path_name()
texture = unreal.EditorAssetLibrary.load_asset(texture_asset_path)
texture.filter = unreal.TextureFilter.TF_NEAREST
unreal.EditorAssetLibrary.save_asset(texture_asset_path)
unreal.EditorLoadingAndSavingUtils.reload_packages([texture.get_package()])
# Create a new material asset
material_factory = unreal.MaterialFactoryNew()
material_asset = asset_tools.create_asset(material_name, material_asset_path, unreal.Material, material_factory)
# Get the material graph
# material = unreal.MaterialEditingLibrary.get_material_graph(material_asset)
material = material_asset
# Create a TextureSample node
texture_node = unreal.MaterialEditingLibrary.create_material_expression(material, unreal.MaterialExpressionTextureSample, -200, 0)
texture_node.texture = texture
# Connect the texture sample to the material's base color
unreal.MaterialEditingLibrary.connect_material_property(texture_node, 'RGBA', unreal.MaterialProperty.MP_BASE_COLOR)
# Compile the material
unreal.MaterialEditingLibrary.recompile_material(material)
return material_asset.get_path_name()
class RandomBackground():
_num_instances = 0
def __init__(self, material_path, location, rotation, scale):
mesh_asset = unreal.EditorAssetLibrary.load_asset('/project/')
self.actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.StaticMeshActor, location, rotation)
self.actor.static_mesh_component.set_static_mesh(mesh_asset)
self.actor.set_actor_scale3d(scale)
material = unreal.EditorAssetLibrary.load_asset(material_path)
self.actor.static_mesh_component.set_material(0, material)
@classmethod
def random(cls):
abs_path = os.environ["abs_path"]
abs_path_cubemap = os.path.join(abs_path, 'temp/')
img_path = os.path.join(abs_path_cubemap, f'noise_texture_{cls._num_instances}.png')
size = random.randint(4,12)
_generate_random_texture(size, img_path)
material_path = _create_material_with_texture(img_path, f'NoiseMaterial_{cls._num_instances}')
location = unreal.Vector(0, -50, 200) # XYZ coordinates
rotation = unreal.Rotator(0, 90, -90) # Pitch, Yaw, Roll
scale = unreal.Vector(4, 4, 4) # Uniform scaling
cls._num_instances += 1
return cls(material_path, location, rotation, scale)
def add_key_transform(self, t, loc, rot):
assert self.binding, "Not in a level sequencer"
utils.add_key_transform(self.binding, t, loc, rot)
def add_to_level_sequencer(self, level_sequencer):
self.binding = level_sequencer.add_possessable(self.actor)
visibility_section = self.binding.add_track(unreal.MovieSceneVisibilityTrack).add_section()
visibility_section.set_start_frame_bounded(0)
visibility_section.set_end_frame_bounded(0)
def add_key_visibility(self, t, toggle):
frame = unreal.FrameNumber(value=t)
track = self.binding.find_tracks_by_exact_type(unreal.MovieSceneVisibilityTrack)[0]
section = track.get_sections()[0]
channel = section.get_all_channels()[0]
channel.add_key(frame, toggle)
|
import unreal
print("=== CHECKING LEVEL CONTENTS ===")
try:
# Load the test level
print("Loading TestLevel...")
level_loaded = unreal.EditorLevelLibrary.load_level('/project/')
if level_loaded:
print("✓ TestLevel loaded successfully")
# Get all actors in the level
actors = unreal.EditorLevelLibrary.get_all_level_actors()
print(f"Found {len(actors)} actors in the level:")
character_found = False
for actor in actors:
actor_name = actor.get_name()
actor_class = actor.get_class().get_name()
print(f" - {actor_name} (Class: {actor_class})")
if "Warrior" in actor_class or "Character" in actor_class:
character_found = True
print(f" ✓ Found character actor!")
if not character_found:
print("✗ No character actor found in level")
print("Attempting to place character...")
# Try to spawn the character
try:
character_bp = unreal.EditorAssetLibrary.load_asset('/project/')
if character_bp:
character_class = character_bp.get_blueprint_generated_class()
if character_class:
# Spawn at origin
character_actor = unreal.EditorLevelLibrary.spawn_actor_from_class(
character_class,
unreal.Vector(0, 0, 100),
unreal.Rotator(0, 0, 0)
)
if character_actor:
print("✓ Character spawned successfully!")
unreal.EditorLevelLibrary.save_current_level()
print("✓ Level saved with character")
else:
print("✗ Failed to spawn character")
else:
print("✗ Could not get character Blueprint class")
else:
print("✗ Could not load character Blueprint")
except Exception as e:
print(f"✗ Error spawning character: {e}")
else:
print("✓ Character already present in level")
else:
print("✗ Failed to load TestLevel")
except Exception as e:
print(f"✗ ERROR: {e}")
import traceback
traceback.print_exc()
print("Exiting...")
unreal.SystemLibrary.execute_console_command(None, "exit")
|
# -*- coding: utf-8 -*-
"""Load camera from FBX."""
import unreal
from unreal import (
EditorAssetLibrary,
EditorLevelLibrary
)
from ayon_core.pipeline import AYON_CONTAINER_ID
from ayon_unreal.api import plugin
from ayon_unreal.api.pipeline import (
generate_master_level_sequence,
set_sequence_hierarchy,
create_container,
imprint,
format_asset_directory,
AYON_ROOT_DIR,
get_top_hierarchy_folder,
generate_hierarchy_path,
remove_map_and_sequence
)
class CameraLoader(plugin.Loader):
"""Load Unreal StaticMesh from FBX"""
product_types = {"camera"}
label = "Load Camera"
representations = {"fbx"}
icon = "cube"
color = "orange"
loaded_asset_dir = "{folder[path]}/{product[name]}_{version[version]}"
loaded_asset_name = "{folder[name]}_{product[name]}_{version[version]}_{representation[name]}" # noqa
@classmethod
def apply_settings(cls, project_settings):
super(CameraLoader, cls).apply_settings(
project_settings
)
cls.loaded_asset_dir = (
project_settings["unreal"]
["import_settings"]
["loaded_asset_dir"]
)
cls.loaded_asset_name = (
project_settings["unreal"]
["import_settings"]
["loaded_asset_name"]
)
def _import_camera(
self, world, sequence, bindings, import_fbx_settings, import_filename
):
ue_version = unreal.SystemLibrary.get_engine_version().split('.')
ue_major = int(ue_version[0])
ue_minor = int(ue_version[1])
if ue_major == 4 and ue_minor <= 26:
unreal.SequencerTools.import_fbx(
world,
sequence,
bindings,
import_fbx_settings,
import_filename
)
elif (ue_major == 4 and ue_minor >= 27) or ue_major == 5:
unreal.SequencerTools.import_level_sequence_fbx(
world,
sequence,
bindings,
import_fbx_settings,
import_filename
)
else:
raise NotImplementedError(
f"Unreal version {ue_major} not supported")
def imprint(
self,
folder_path,
asset_dir,
container_name,
asset_name,
representation,
folder_name,
product_type,
folder_entity,
project_name
):
data = {
"schema": "ayon:container-2.0",
"id": AYON_CONTAINER_ID,
"folder_path": folder_path,
"namespace": asset_dir,
"container_name": container_name,
"asset_name": asset_name,
"loader": str(self.__class__.__name__),
"representation": representation["id"],
"parent": representation["versionId"],
"product_type": product_type,
# TODO these should be probably removed
"asset": folder_name,
"family": product_type,
"frameStart": folder_entity["attrib"]["frameStart"],
"frameEnd": folder_entity["attrib"]["frameEnd"],
"project_name": project_name
}
imprint(f"{asset_dir}/{container_name}", data)
def _create_map_camera(self, context, path, tools, hierarchy_dir,
master_dir_name, asset_dir, asset_name):
cam_seq, master_level, level, sequences, frame_ranges = (
generate_master_level_sequence(
tools, asset_dir, asset_name,
hierarchy_dir, master_dir_name,
suffix="camera")
)
folder_entity = context["folder"]
folder_attributes = folder_entity["attrib"]
clip_in = folder_attributes.get("clipIn")
clip_out = folder_attributes.get("clipOut")
cam_seq.set_display_rate(
unreal.FrameRate(folder_attributes.get("fps"), 1.0))
cam_seq.set_playback_start(clip_in)
cam_seq.set_playback_end(clip_out + 1)
set_sequence_hierarchy(
sequences[-1], cam_seq,
frame_ranges[-1][1],
clip_in, clip_out,
[level])
settings = unreal.MovieSceneUserImportFBXSettings()
settings.set_editor_property('reduce_keys', False)
if cam_seq:
self._import_camera(
EditorLevelLibrary.get_editor_world(),
cam_seq,
cam_seq.get_bindings(),
settings,
path
)
camera_actors = unreal.GameplayStatics().get_all_actors_of_class(
EditorLevelLibrary.get_editor_world(), unreal.CameraActor)
unreal.log(f"Spawning camera: {asset_name}")
for actor in camera_actors:
actor.set_actor_label(asset_name)
# Set range of all sections
# Changing the range of the section is not enough. We need to change
# the frame of all the keys in the section.
for possessable in cam_seq.get_possessables():
for tracks in possessable.get_tracks():
for section in tracks.get_sections():
section.set_range(clip_in, clip_out + 1)
for channel in section.get_all_channels():
for key in channel.get_keys():
old_time = key.get_time().get_editor_property(
'frame_number')
old_time_value = old_time.get_editor_property(
'value')
new_time = old_time_value + (
clip_in - folder_attributes.get('frameStart')
)
key.set_time(unreal.FrameNumber(value=new_time))
return master_level
def load(self, context, name, namespace, options):
"""
Load and containerise representation into Content Browser.
This is two step process. First, import FBX to temporary path and
then call `containerise()` on it - this moves all content to new
directory and then it will create AssetContainer there and imprint it
with metadata. This will mark this path as container.
Args:
context (dict): application context
name (str): Product name
namespace (str): in Unreal this is basically path to container.
This is not passed here, so namespace is set
by `containerise()` because only then we know
real path.
data (dict): Those would be data to be imprinted. This is not used
now, data are imprinted by `containerise()`.
Returns:
list(str): list of container content
"""
# Create directory for asset and Ayon container
folder_entity = context["folder"]
folder_path = folder_entity["path"]
folder_name = folder_entity["name"]
asset_root, asset_name = format_asset_directory(
context, self.loaded_asset_dir, self.loaded_asset_name)
master_dir_name = get_top_hierarchy_folder(asset_root)
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, hierarchy_dir, container_name, _ = (
generate_hierarchy_path(
name, folder_name, asset_root, master_dir_name
)
)
path = self.filepath_from_context(context)
master_level = self._create_map_camera(
context, path, tools, hierarchy_dir,
master_dir_name, asset_dir, asset_name
)
# Create Asset Container
if not unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{container_name}"
):
create_container(
container=container_name, path=asset_dir)
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
context["representation"],
folder_name,
context["product"]["productType"],
folder_entity,
context["project"]["name"]
)
EditorLevelLibrary.save_all_dirty_levels()
EditorLevelLibrary.load_level(master_level)
# Save all assets in the hierarchy
asset_content = EditorAssetLibrary.list_assets(
hierarchy_dir, recursive=True, include_folder=False
)
for a in asset_content:
EditorAssetLibrary.save_asset(a)
return asset_content
def update(self, container, context):
# Create directory for asset and Ayon container
folder_entity = context["folder"]
folder_path = folder_entity["path"]
asset_root, asset_name = format_asset_directory(
context, self.loaded_asset_dir, self.loaded_asset_name)
master_dir_name = get_top_hierarchy_folder(asset_root)
hierarchy_dir = f"{AYON_ROOT_DIR}/{master_dir_name}"
suffix = "_CON"
tools = unreal.AssetToolsHelpers().get_asset_tools()
asset_dir, container_name = tools.create_unique_asset_name(
asset_root, suffix="")
container_name += suffix
master_level = None
if not unreal.EditorAssetLibrary.does_directory_exist(asset_dir):
EditorAssetLibrary.make_directory(asset_dir)
path = self.filepath_from_context(context)
master_level = self._create_map_camera(
context, path, tools, hierarchy_dir,
master_dir_name, asset_dir, asset_name
)
# Create Asset Container
if not unreal.EditorAssetLibrary.does_asset_exist(
f"{asset_dir}/{container_name}"
):
create_container(
container=container_name, path=asset_dir)
self.imprint(
folder_path,
asset_dir,
container_name,
asset_name,
context["representation"],
folder_entity["name"],
context["product"]["productType"],
folder_entity,
context["project"]["name"]
)
EditorLevelLibrary.save_all_dirty_levels()
EditorLevelLibrary.load_level(master_level)
# Save all assets in the hierarchy
asset_content = EditorAssetLibrary.list_assets(
hierarchy_dir, recursive=True, include_folder=False
)
for a in asset_content:
EditorAssetLibrary.save_asset(a)
def switch(self, container, context):
self.update(container, context)
def remove(self, container):
remove_map_and_sequence(container)
|
import unreal
from ueGear.controlrig.paths import CONTROL_RIG_FUNCTION_PATH
from ueGear.controlrig.components import base_component
from ueGear.controlrig.helpers import controls
class Component(base_component.UEComponent):
name = "test_FK"
mgear_component = "EPIC_control_01"
def __init__(self):
super().__init__()
self.functions = {'construction_functions': ['construct_FK_singleton'],
'forward_functions': ['forward_FK_singleton'],
'backwards_functions': ['backwards_FK_singleton'],
}
self.cr_variables = {}
# Control Rig Inputs
self.cr_inputs = {'construction_functions': ['parent'],
'forward_functions': [],
'backwards_functions': [],
}
# Control Rig Outputs
self.cr_output = {'construction_functions': ['root'],
'forward_functions': [],
'backwards_functions': [],
}
# mGear
self.inputs = []
self.outputs = []
# ---- TESTING
self.bones = []
def create_functions(self, controller: unreal.RigVMController):
if controller is None:
return
# calls the super method
super().create_functions(controller)
# Generate Function Nodes
for evaluation_path in self.functions.keys():
# Skip the forward function creation if no joints are needed to be driven
if evaluation_path == 'forward_functions' and self.metadata.joints is None:
continue
# Skip the backwards function creation if no joints are needed to be driven
if evaluation_path == 'backwards_functions' and self.metadata.joints is None:
# Checks to see if the Epic control has a backwards reference joint, as this will be used to populate
# the backwards solve so the control follows a specific bone. This bone is not a bone that was generated
# by the creation of the control, which is why it is a reference.
if "backwards_ref_jnt" in self.metadata.settings.keys():
if (self.metadata.settings["backwards_ref_jnt"] == "" or
self.metadata.settings["backwards_ref_jnt"] is None):
continue
else:
continue
for cr_func in self.functions[evaluation_path]:
new_node_name = f"{self.name}_{cr_func}"
ue_cr_node = controller.get_graph().find_node_by_name(new_node_name)
# Create Component if doesn't exist
if ue_cr_node is None:
ue_cr_ref_node = controller.add_external_function_reference_node(CONTROL_RIG_FUNCTION_PATH,
cr_func,
unreal.Vector2D(0.0, 0.0),
node_name=new_node_name)
# In Unreal, Ref Node inherits from Node
ue_cr_node = ue_cr_ref_node
else:
# if exists, add it to the nodes
self.nodes[evaluation_path].append(ue_cr_node)
unreal.log_error(f" Cannot create function {new_node_name}, it already exists")
continue
self.nodes[evaluation_path].append(ue_cr_node)
# Gets the Construction Function Node and sets the control name
construct_func = base_component.get_construction_node(self, f"{self.name}_construct_FK_singleton")
if construct_func is None:
unreal.log_error(" Create Functions Error - Cannot find construct singleton node")
controller.set_pin_default_value(construct_func.get_name() + '.control_name',
self.metadata.controls[0],
False)
# self._fit_comment(controller)
def populate_bones(self, bones: list[unreal.RigBoneElement] = None, controller: unreal.RigVMController = None):
"""
Generates the Bone array node that will be utilised by control rig to drive the component
"""
if bones is None or len(bones) > 1:
unreal.log_warning(f"[populate_bones] {self.name}: No bone provided")
return
if controller is None:
unreal.log_error(f"{self.name}: No controller provided")
return
bone_name = bones[0].key.name
if bone_name == "":
unreal.log_error(f"[populate_bones] Bone name cannot be empty:{bones}")
return
# Populates the joint pin
for evaluation_path in self.nodes.keys():
for function_node in self.nodes[evaluation_path]:
success = controller.set_pin_default_value(f'{function_node.get_name()}.joint',
f'(Type=Bone,Name="{bone_name}")', True)
if not success:
unreal.log_error(f"[populate_bones] Setting Pin failed:{function_node.get_name()}.joint << {bone_name}")
def populate_control_transforms(self, controller: unreal.RigVMController = None):
"""Updates the transform data for the controls generated, with the data from the mgear json
file.
"""
control_name = self.metadata.controls[0]
control_transform = self.metadata.control_transforms[control_name]
const_func = self.nodes['construction_functions'][0].get_name()
quat = control_transform.rotation
pos = control_transform.translation
controller.set_pin_default_value(f"{const_func}.control_world_transform",
f"(Rotation=(X={quat.x},Y={quat.y},Z={quat.z},W={quat.w}), "
f"Translation=(X={pos.x},Y={pos.y},Z={pos.z}),"
f"Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))",
True)
self.populate_control_shape_orientation(controller)
self.populate_control_scale(controller)
self.populate_control_colour(controller)
def populate_control_shape_orientation(self, controller: unreal.RigVMController = None):
"""Populates the control's shapes orientation"""
for cr_func in self.functions["construction_functions"]:
construction_node = f"{self.name}_{cr_func}"
ue_cr_node = controller.get_graph().find_node_by_name(construction_node)
controller.set_pin_default_value(f'{construction_node}.control_orientation.X',
'90.000000',
False)
def populate_control_scale(self, controller: unreal.RigVMController):
"""Calculates the size of the control from the Bounding Box"""
for cr_func in self.functions["construction_functions"]:
construction_node = f"{self.name}_{cr_func}"
control_name = self.metadata.controls[0]
aabb = self.metadata.controls_aabb[control_name]
reduce_ratio = 6.0
unreal_size = [round(element / reduce_ratio, 4) for element in aabb[1]]
for axis, value in zip(["X", "Y", "Z", ], unreal_size):
# an ugly way to ensure that the bounding box is not 100% flat,
# causing the control to be scaled flat on Z
if axis == "Z" and value <= 1.0:
value = unreal_size[0]
controller.set_pin_default_value(
f'{construction_node}.control_size.{axis}',
str(value),
False)
def populate_control_colour(self, controller):
cr_func = self.functions["construction_functions"][0]
construction_node = f"{self.name}_{cr_func}"
control_name = self.metadata.controls[0]
colour = self.metadata.controls_colour[control_name]
default_value = f"(R={colour[0]}, G={colour[1]}, B={colour[2]}, A=1.0)"
# Populates and resizes the pin in one go
controller.set_pin_default_value(
f'{construction_node}.control_colour',
f"{default_value}",
True,
setup_undo_redo=True,
merge_undo_action=True)
class ManualComponent(Component):
name = "Manual_FK_Singleton"
def __init__(self):
super().__init__()
self.functions = {'construction_functions': ['manual_construct_FK_singleton'],
'forward_functions': ['forward_FK_singleton'],
'backwards_functions': ['backwards_FK_singleton'],
}
self.is_manual = True
self.root_control_children = ["ctl"]
def create_functions(self, controller: unreal.RigVMController):
if controller is None:
return
# calls the super method and creates the comment block
base_component.UEComponent.create_functions(self, controller)
# Generate Function Nodes
for evaluation_path in self.functions.keys():
# Skip the forward function creation if no joints are needed to be driven
if evaluation_path == 'forward_functions' and self.metadata.joints is None:
continue
if evaluation_path == 'backwards_functions' and self.metadata.joints is None:
if self.metadata.settings is None:
continue
# Checks to see if the Epic control has a backwards reference joint, as this will be used to populate
# the backwards solve so the control follows a specific bone. This bone is not a bone that was generated
# by the creation of the control, which is why it is a reference.
if "backwards_ref_jnt" in self.metadata.settings.keys():
if (self.metadata.settings["backwards_ref_jnt"] == "" or
self.metadata.settings["backwards_ref_jnt"] is None):
continue
else:
continue
for cr_func in self.functions[evaluation_path]:
new_node_name = f"{self.name}_{cr_func}"
ue_cr_node = controller.get_graph().find_node_by_name(new_node_name)
# Create Component if doesn't exist
if ue_cr_node is None:
ue_cr_ref_node = controller.add_external_function_reference_node(CONTROL_RIG_FUNCTION_PATH,
cr_func,
unreal.Vector2D(0.0, 0.0),
node_name=new_node_name)
# In Unreal, Ref Node inherits from Node
ue_cr_node = ue_cr_ref_node
else:
# if exists, add it to the nodes
self.nodes[evaluation_path].append(ue_cr_node)
unreal.log_error(f" Cannot create function {new_node_name}, it already exists")
continue
self.nodes[evaluation_path].append(ue_cr_node)
def generate_manual_controls(self, hierarchy_controller):
"""Creates all the manual controls in the designated structure"""
for control_name in self.metadata.controls:
new_control = controls.CR_Control(name=control_name)
role = self.metadata.controls_role[control_name]
# stored metadata values
control_transform = self.metadata.control_transforms[control_name]
control_colour = self.metadata.controls_colour[control_name]
control_aabb = self.metadata.controls_aabb[control_name]
control_offset = control_aabb[0]
control_scale = [control_aabb[1][0] / 4.0,
control_aabb[1][1] / 4.0,
control_aabb[1][2] / 4.0]
# Set the colour, required before build
new_control.colour = control_colour
new_control.shape_name = "RoundedSquare_Thick"
# Generate the Control
new_control.build(hierarchy_controller)
# Sets the controls position, and offset translation and scale of the shape
new_control.set_transform(quat_transform=control_transform)
new_control.shape_transform_global(pos=control_offset,
scale=control_scale,
rotation=[90, 0, 0])
# Stores the control by role, for loopup purposes later
self.control_by_role[role] = new_control
def populate_control_transforms(self, controller: unreal.RigVMController = None):
construction_func_name = self.nodes["construction_functions"][0].get_name()
controls = []
for role_key in self.control_by_role.keys():
control = self.control_by_role[role_key]
controls.append(control)
def update_input_plug(plug_name, control_list):
"""
Simple helper function making the plug population reusable for ik and fk
"""
for entry in control_list:
if entry.rig_key.type == unreal.RigElementType.CONTROL:
t = "Control"
if entry.rig_key.type == unreal.RigElementType.NULL:
t = "Null"
n = entry.rig_key.name
entry = f'(Type={t}, Name="{n}")'
controller.set_pin_default_value(
f'{construction_func_name}.{plug_name}',
f"{entry}",
True,
setup_undo_redo=True,
merge_undo_action=True)
update_input_plug("control", controls)
def init_input_data(self, controller: unreal.RigVMController):
"""Overloading the input of nodes, as a post process. This can be a handy function when needing to perform
a minor adjustment."""
# Looks to see if the Epic_Control requires a backwards reference joint, if one has been populated and no
# current joint exists for the component, then we populate the joint and the control.
backwards_nodes = self.nodes['backwards_functions']
if backwards_nodes and "backwards_ref_jnt" in self.metadata.settings.keys():
backwards_node_name = backwards_nodes[0].get_name()
ref_joint = self.metadata.settings["backwards_ref_jnt"]
if ref_joint is None or ref_joint == "":
return
control_name = self.control_by_role["ctl"].rig_key.name
controller.set_pin_default_value(
f'{backwards_node_name}.joint',
f'(Type=Bone,Name="{ref_joint}")',
True,
setup_undo_redo=True,
merge_undo_action=True)
controller.set_pin_default_value(
f'{backwards_node_name}.control',
f'(Type=Control,Name="{control_name}")',
True,
setup_undo_redo=True,
merge_undo_action=True)
|
# coding: utf-8
import unreal
import argparse
print("VRM4U python begin")
print (__file__)
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
args = parser.parse_args()
print(args.vrm)
#print(dummy[3])
humanoidBoneList = [
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"upperChest", # 9 optional
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal", # 24
"leftThumbIntermediate",
"leftThumbDistal",
"leftIndexProximal",
"leftIndexIntermediate",
"leftIndexDistal",
"leftMiddleProximal",
"leftMiddleIntermediate",
"leftMiddleDistal",
"leftRingProximal",
"leftRingIntermediate",
"leftRingDistal",
"leftLittleProximal",
"leftLittleIntermediate",
"leftLittleDistal",
"rightThumbProximal",
"rightThumbIntermediate",
"rightThumbDistal",
"rightIndexProximal",
"rightIndexIntermediate",
"rightIndexDistal",
"rightMiddleProximal",
"rightMiddleIntermediate",
"rightMiddleDistal",
"rightRingProximal",
"rightRingIntermediate",
"rightRingDistal",
"rightLittleProximal",
"rightLittleIntermediate",
"rightLittleDistal", #54
]
humanoidBoneParentList = [
"", #"hips",
"hips",#"leftUpperLeg",
"hips",#"rightUpperLeg",
"leftUpperLeg",#"leftLowerLeg",
"rightUpperLeg",#"rightLowerLeg",
"leftLowerLeg",#"leftFoot",
"rightLowerLeg",#"rightFoot",
"hips",#"spine",
"spine",#"chest",
"chest",#"upperChest" 9 optional
"chest",#"neck",
"neck",#"head",
"chest",#"leftShoulder", # <-- upper..
"chest",#"rightShoulder",
"leftShoulder",#"leftUpperArm",
"rightShoulder",#"rightUpperArm",
"leftUpperArm",#"leftLowerArm",
"rightUpperArm",#"rightLowerArm",
"leftLowerArm",#"leftHand",
"rightLowerArm",#"rightHand",
"leftFoot",#"leftToes",
"rightFoot",#"rightToes",
"head",#"leftEye",
"head",#"rightEye",
"head",#"jaw",
"leftHand",#"leftThumbProximal",
"leftThumbProximal",#"leftThumbIntermediate",
"leftThumbIntermediate",#"leftThumbDistal",
"leftHand",#"leftIndexProximal",
"leftIndexProximal",#"leftIndexIntermediate",
"leftIndexIntermediate",#"leftIndexDistal",
"leftHand",#"leftMiddleProximal",
"leftMiddleProximal",#"leftMiddleIntermediate",
"leftMiddleIntermediate",#"leftMiddleDistal",
"leftHand",#"leftRingProximal",
"leftRingProximal",#"leftRingIntermediate",
"leftRingIntermediate",#"leftRingDistal",
"leftHand",#"leftLittleProximal",
"leftLittleProximal",#"leftLittleIntermediate",
"leftLittleIntermediate",#"leftLittleDistal",
"rightHand",#"rightThumbProximal",
"rightThumbProximal",#"rightThumbIntermediate",
"rightThumbIntermediate",#"rightThumbDistal",
"rightHand",#"rightIndexProximal",
"rightIndexProximal",#"rightIndexIntermediate",
"rightIndexIntermediate",#"rightIndexDistal",
"rightHand",#"rightMiddleProximal",
"rightMiddleProximal",#"rightMiddleIntermediate",
"rightMiddleIntermediate",#"rightMiddleDistal",
"rightHand",#"rightRingProximal",
"rightRingProximal",#"rightRingIntermediate",
"rightRingIntermediate",#"rightRingDistal",
"rightHand",#"rightLittleProximal",
"rightLittleProximal",#"rightLittleIntermediate",
"rightLittleIntermediate",#"rightLittleDistal",
]
for i in range(len(humanoidBoneList)):
humanoidBoneList[i] = humanoidBoneList[i].lower()
for i in range(len(humanoidBoneParentList)):
humanoidBoneParentList[i] = humanoidBoneParentList[i].lower()
######
reg = unreal.AssetRegistryHelpers.get_asset_registry();
## meta 取得
a = reg.get_all_assets();
for aa in a:
if (aa.get_editor_property("object_path") == args.vrm):
v:unreal.VrmAssetListObject = aa
vv = v.get_asset().vrm_meta_object
print(vv)
meta = vv
##
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
#rig = rigs[10]
h_mod = rig.get_hierarchy_modifier()
#elements = h_mod.get_selection()
#sk = rig.get_preview_mesh()
#k = sk.skeleton
#print(k)
### 全ての骨
modelBoneListAll = []
modelBoneNameList = []
for e in reversed(h_mod.get_elements()):
if (e.type != unreal.RigElementType.BONE):
h_mod.remove_element(e)
name_to_control = {"dummy_for_table" : None}
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.2, 0.2, 0.2])
for e in h_mod.get_elements():
print(e.name)
if (e.type != unreal.RigElementType.BONE):
continue
bone = h_mod.get_bone(e)
parentName = "{}".format(bone.get_editor_property('parent_name'))
#print("parent==")
#print(parentName)
cur_parentName = parentName + "_c"
name_s = "{}".format(e.name) + "_s"
name_c = "{}".format(e.name) + "_c"
space = h_mod.add_space(name_s, parent_name=cur_parentName, space_type=unreal.RigSpaceType.CONTROL)
control = h_mod.add_control(name_c,
space_name=space.name,
gizmo_color=[0.1, 0.1, 1.0, 1.0],
)
h_mod.set_initial_global_transform(space, h_mod.get_global_transform(e))
cc = h_mod.get_control(control)
cc.set_editor_property('gizmo_transform', gizmo_trans)
#cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR)
h_mod.set_control(cc)
name_to_control[name_c] = cc
c = None
try:
i = list(name_to_control.keys()).index(cur_parentName)
except:
i = -1
if (i >= 0):
c = name_to_control[cur_parentName]
if (cc != None):
if ("{}".format(e.name) in meta.humanoid_bone_table.values() ):
cc.set_editor_property('gizmo_color', unreal.LinearColor(0.1, 0.1, 1.0, 1.0))
h_mod.set_control(cc)
else:
cc.set_editor_property('gizmo_color', unreal.LinearColor(1.0, 0.1, 0.1, 1.0))
h_mod.set_control(cc)
c = rig.controller
g = c.get_graph()
n = g.get_nodes()
# 配列ノード追加
collectionItem_forControl:unreal.RigVMStructNode = None
collectionItem_forBone:unreal.RigVMStructNode = None
for node in n:
if (node.get_node_title() == 'Items'):
#print(node.get_node_title())
#node = unreal.RigUnit_CollectionItems.cast(node)
pin = node.find_pin('Items')
print(pin.get_array_size())
print(pin.get_default_value())
if (pin.get_array_size() < 40):
continue
if 'Type=Control' in pin.get_default_value():
collectionItem_forControl = node
if 'Type=Bone' in pin.get_default_value():
collectionItem_forBone = node
#nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class())
# controller array
if (collectionItem_forControl == None):
collectionItem_forControl = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute')
items_forControl = collectionItem_forControl.find_pin('Items')
c.clear_array_pin(items_forControl.get_pin_path())
if (collectionItem_forBone != None):
items_forBone = collectionItem_forBone.find_pin('Items')
c.clear_array_pin(items_forBone.get_pin_path())
for bone_h in meta.humanoid_bone_table:
bone_m = meta.humanoid_bone_table[bone_h]
try:
i = humanoidBoneList.index(bone_h.lower())
except:
i = -1
if (i >= 0):
tmp = '(Type=Bone,Name='
tmp += "{}".format(bone_m).lower()
tmp += ')'
c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp)
for e in h_mod.get_elements():
print(e.name)
if (e.type == unreal.RigElementType.CONTROL):
tmp = '(Type=Control,Name='
tmp += "{}".format(e.name)
tmp += ')'
c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp)
|
import unreal
from mca.ue import pyunreal as pue
class AssetDefinitions:
def __init__(self, *args, **kwargs):
self._dict = {unreal.SkeletalMesh: pue.PySkelMesh}
def __getattr__(self, name):
def func(*args, **kwargs):
resp = {unreal.SkeletalMesh: pue.PySkelMesh}[args[0]] # Decide which responder to use (example)
return kwargs.get(name, None) # Call the function on the responder
return func
df = AssetDefinitions()
jkl = df.getattr(unreal.SkeletalMesh)
print(jkl)
defi = AssetDefinitions()
get_attr = defi.func(unreal.SkeletalMesh)
_dict = {unreal.SkeletalMesh: pue.PySkelMesh}
print(_dict.get(unreal.SkeletalMesh))
class RandomResponder(object):
choices = [A, B, C]
@classmethod
def which(cls):
return random.choice(cls.choices)
def __getattr__(self, attr):
return getattr(self.which(), attr)
import random
class RandomResponder(object):
choices = [unreal.SkeletalMesh]
@classmethod
def which(cls):
return random.choice(cls.choices)
def __getattr__(self, attr):
# we define a function that actually gets called
# which takes up the first positional argument,
# the rest are left to args and kwargs
def doCall(which, *args, **kwargs):
# get the attribute of the appropriate one, call with passed args
return getattr(self.choices[which], attr)(*args, **kwargs)
return doCall
df = RandomResponder.which()
print(df)
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import unreal
""" Example script for instantiating an asset, cooking it and baking an
individual output object.
"""
_g_wrapper = None
def get_test_hda_path():
return '/project/.pig_head_subdivider_v01'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def on_post_process(in_wrapper):
print('on_post_process')
# Print details about the outputs and record the first static mesh we find
sm_index = None
sm_identifier = None
# in_wrapper.on_post_processing_delegate.remove_callable(on_post_process)
num_outputs = in_wrapper.get_num_outputs()
print('num_outputs: {}'.format(num_outputs))
if num_outputs > 0:
for output_idx in range(num_outputs):
identifiers = in_wrapper.get_output_identifiers_at(output_idx)
output_type = in_wrapper.get_output_type_at(output_idx)
print('\toutput index: {}'.format(output_idx))
print('\toutput type: {}'.format(output_type))
print('\tnum_output_objects: {}'.format(len(identifiers)))
if identifiers:
for identifier in identifiers:
output_object = in_wrapper.get_output_object_at(output_idx, identifier)
output_component = in_wrapper.get_output_component_at(output_idx, identifier)
is_proxy = in_wrapper.is_output_current_proxy_at(output_idx, identifier)
print('\t\tidentifier: {}'.format(identifier))
print('\t\toutput_object: {}'.format(output_object.get_name() if output_object else 'None'))
print('\t\toutput_component: {}'.format(output_component.get_name() if output_component else 'None'))
print('\t\tis_proxy: {}'.format(is_proxy))
print('')
if (output_type == unreal.HoudiniOutputType.MESH and
isinstance(output_object, unreal.StaticMesh)):
sm_index = output_idx
sm_identifier = identifier
# Bake the first static mesh we found to the CB
if sm_index is not None and sm_identifier is not None:
print('baking {}'.format(sm_identifier))
success = in_wrapper.bake_output_object_at(sm_index, sm_identifier)
print('success' if success else 'failed')
# Delete the instantiated asset
in_wrapper.delete_instantiated_asset()
global _g_wrapper
_g_wrapper = None
def run():
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Bind to the on post processing delegate (after a cook and after all
# outputs have been generated in Unreal)
_g_wrapper.on_post_processing_delegate.add_callable(on_post_process)
if __name__ == '__main__':
run()
|
# unreal.EditorLevelLibrary
# https://api.unrealengine.com/project/.html
# unreal.GameplayStatics
# https://api.unrealengine.com/project/.html
# unreal.Actor
# https://api.unrealengine.com/project/.html
import unreal
import PythonHelpers
# use_selection: bool : True if you want to get only the selected actors
# actor_class: class unreal.Actor : The class used to filter the actors. Can be None if you do not want to use this filter
# actor_tag: str : The tag used to filter the actors. Can be None if you do not want to use this filter
# world: obj unreal.World : The world you want to get the actors from. If None, will get the actors from the currently open world.
# return: obj List unreal.Actor : The actors
def getAllActors(use_selection=False, actor_class=None, actor_tag=None, world=None):
world = world if world is not None else unreal.EditorLevelLibrary.get_editor_world() # Make sure to have a valid world
if use_selection:
selected_actors = getSelectedActors()
class_actors = selected_actors
if actor_class:
class_actors = [x for x in selected_actors if PythonHelpers.cast(x, actor_class)]
tag_actors = class_actors
if actor_tag:
tag_actors = [x for x in selected_actors if x.actor_has_tag(actor_tag)]
return [x for x in tag_actors]
elif actor_class:
actors = unreal.GameplayStatics.get_all_actors_of_class(world, actor_class)
tag_actors = actors
if actor_tag:
tag_actors = [x for x in actors if x.actor_has_tag(actor_tag)]
return [x for x in tag_actors]
elif actor_tag:
tag_actors = unreal.GameplayStatics.get_all_actors_with_tag(world, actor_tag)
return [x for x in tag_actors]
else:
actors = unreal.GameplayStatics.get_all_actors_of_class(world, unreal.Actor)
return [x for x in actors]
# path: str : Blueprint class path
# actor_location: obj unreal.Vector : The actor location
# actor_rotation: obj unreal.Rotator : The actor rotation
# actor_location: obj unreal.Vector : The actor scale
# world: obj unreal.World : The world in which you want to spawn the actor. If None, will spawn in the currently open world.
# properties: dict : The properties you want to set before the actor is spawned. These properties will be taken into account in the Construction Script
# return: obj unreal.Actor : The spawned actor
def spawnBlueprintActor(path='', actor_location=None, actor_rotation=None, actor_scale=None, world=None, properties={}):
actor_class = unreal.EditorAssetLibrary.load_blueprint_class(path)
actor_transform = unreal.Transform(actor_location, actor_rotation, actor_scale)
world = world if world is not None else unreal.EditorLevelLibrary.get_editor_world() # Make sure to have a valid world
# Begin Spawn
actor = unreal.GameplayStatics.begin_spawning_actor_from_class(world_context_object=world, actor_class=actor_class, spawn_transform=actor_transform, no_collision_fail=True)
# Edit Properties
for x in properties:
actor.set_editor_property(x, properties[x])
# Complete Spawn
unreal.GameplayStatics.finish_spawning_actor(actor=actor, spawn_transform=actor_transform)
return actor
# return: obj List unreal.Actor : The selected actors in the world
def getSelectedActors():
return unreal.EditorLevelLibrary.get_selected_level_actors()
# Note: Will always clear the selection before selecting.
# actors_to_select: obj List unreal.Actor : The actors to select.
def selectActors(actors_to_select=[]):
unreal.EditorLevelLibrary.set_selected_level_actors(actors_to_select)
|
"""
# Unreal Import
* Description:
Import functions for assets into unreal.
* Notes:
Most import option values are currently hard-coded but could easily be hooked up to UI.
* UE Path types:
!Seriously, why does UE have so many path types?
Display Name & Asset Name = AssetName
Path Name & Object Path = /project/.AssetName
Package Path = /project/
Package Name = /project/
"""
import collections
from dataclasses import dataclass
from functools import partial
from typing import cast
from typing import Optional
from typing import TypeVar
from pathlib import Path
import unreal
from lucid.unreal import short
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Import options and task fat structs
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
class ImportAssetOptions(object):
"""Lucid import options - The import settings used when importing an asset
into the engine.
An ImportAssetOptions is a component of 'ImportTaskOptions' and used to
define the asset type specific attributes on import.
"""
@dataclass
class ImportSMOptions(ImportAssetOptions):
"""Lucid Options object used to define how a static mesh will be imported
into the engine.
"""
loc: unreal.Vector = (0.0, 0.0, 0.0)
rot: unreal.Rotator = (0.0, 0.0, 0.0)
scale: float = 1.0
merge: bool = True
remove_degenerates: bool = False
generate_lightmaps: bool = True
auto_gen_collisions: bool = True
normal_gen_method: short.fbx_normal_gen_method = short.fbx_normal_mikk_t_space
normal_import_method: short.fbx_normal_imp_method = short.fbx_import_normals_tangents
one_convex_hull: bool = False
@dataclass
class ImportSKOptions(ImportAssetOptions):
"""Lucid options object used to define how a skeletal mesh will be imported
into the engine.
"""
skeleton: Optional[unreal.Skeleton] = None
loc: unreal.Vector = (0.0, 0.0, 0.0)
rot: unreal.Rotator = (0.0, 0.0, 0.0)
scale: float = 1.0
create_physics_asset: bool = False
import_morph_targets: bool = True
preserve_smoothing_groups: bool = True
convert_scene: bool = True
normal_gen_method: short.fbx_normal_gen_method = short.fbx_normal_mikk_t_space
normal_import_method: short.fbx_normal_imp_method = short.fbx_import_normals_tangents
@dataclass
class ImportAnimOptions(ImportAssetOptions):
"""Lucid options object used to define how an animation will be imported
into the engine.
"""
skeleton: unreal.Skeleton
fps: int = 30
loc: unreal.Vector = (0.0, 0.0, 0.0)
rot: unreal.Rotator = (0.0, 0.0, 0.0)
scale: float = 1.0
convert_scene: bool = True
del_morph_targets: bool = False
@dataclass
class ImportTextureOptions(ImportAssetOptions):
"""Lucid options object used to define how a texture will be imported
into the engine.
"""
compression_override: int = 0
"""Override value for the texture compression settings.
If non-zero, this value will be used instead of the default compression
settings inferred from the source file name suffix. Defaults to 0.
"""
T_ImportAssetOptions = TypeVar('T_ImportAssetOptions', bound=ImportAssetOptions)
@dataclass
class ImportTaskOptions(object):
"""Lucid Options object used to define an unreal.AssetImportTask."""
options: T_ImportAssetOptions
source_path: Path
destination_package_path: str
import_name: str = ''
reimport: bool = True
def import_static_mesh(task: ImportTaskOptions) -> str:
"""
Imports a static mesh asset into Unreal Engine.
Args:
task (ImportTaskOptions): The task options defining how to import the
static mesh.
Returns:
str: The path name of the imported asset.
"""
fbx_ui_options = _import_sm_options(task.options)
static_mesh = _import_task(task, fbx_ui_options)
asset_task = _execute_import_tasks([static_mesh])
return asset_task[0]
def import_skeletal_mesh(task: ImportTaskOptions) -> str:
"""
Imports a skeletal mesh asset into Unreal Engine.
Args:
task (ImportTaskOptions): The task options defining how to import the
static mesh.
Returns:
str: The path name of the imported asset.
"""
fbx_ui_options = _import_sk_options(task.options)
skeletal_mesh = _import_task(task, fbx_ui_options)
asset_task = _execute_import_tasks([skeletal_mesh])
return asset_task[0]
def import_animation(task: ImportTaskOptions) -> str:
"""
Imports a skeletal mesh animation into Unreal Engine.
Args:
task (ImportTaskOptions): The task options defining how to import the
static mesh.
Returns:
str: The path name of the imported asset.
"""
fbx_ui_options = _import_anim_options(task.options)
anim = _import_task(task, fbx_ui_options)
anim_task = _execute_import_tasks([anim])
return anim_task[0]
def import_texture(task: ImportTaskOptions) -> str:
"""
Imports a texture asset into Unreal Engine from the given source file path.
Notes:
The compression settings for the imported texture are set based on the suffix of the source
file name, unless a compression_override value is provided.
The following suffixes are recognized:
- '_BC' : sRGB color space
- '_N' : normal map
- '_ORM': non-sRGB color space
- other : default compression settings
Args:
task (ImportTaskOptions): The task options defining how to import the
static mesh.
Returns:
str: The path name of the imported asset.
"""
file_name = task.source_path.as_posix().split('/')[-1].split('.')[0]
texture = _import_task(task)
unreal_path = _execute_import_tasks([texture])[0]
asset = unreal.load_asset(str(unreal_path))
# Texture type settings
compression_val = task.options.compression_override
if compression_val:
asset.set_editor_property('compression_settings', unreal.TextureCompressionSettings.cast(compression_val))
else:
if file_name.endswith('_BC'):
asset.set_editor_property('srgb', True)
elif file_name.endswith('_N'):
asset.set_editor_property('compression_settings', unreal.TextureCompressionSettings.TC_NORMALMAP)
elif file_name.endswith('_ORM'):
asset.set_editor_property('srgb', False)
else:
asset.set_editor_property('compression_settings', unreal.TextureCompressionSettings.TC_DEFAULT)
unreal.EditorAssetLibrary.save_asset(unreal_path, True)
return unreal_path
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Import task declaration and execution
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def _import_task(
task: ImportTaskOptions,
options: Optional[unreal.FbxImportUI] = None
) -> unreal.AssetImportTask:
"""
Sets the import task settings when importing an asset.
Args:
task (ImportTaskOptions): The task options defining how to import the
static mesh.
Returns:
unreal.AssetImportTask: The asset import task with the specified settings.
"""
ue_task = unreal.AssetImportTask()
# Task settings
ue_task.set_editor_property('automated', True)
ue_task.set_editor_property('destination_name', task.import_name)
ue_task.set_editor_property('destination_path', task.destination_package_path)
ue_task.set_editor_property('filename', task.source_path.as_posix())
ue_task.set_editor_property('replace_existing', task.reimport)
ue_task.set_editor_property('save', True)
# Additional settings
ue_task.set_editor_property('options', options)
return ue_task
def _execute_import_tasks(import_tasks: list[unreal.AssetImportTask]) -> list:
"""
Imports a single asset from disk in Unreal.
Args:
import_tasks (unreal.AssetImportTask): The import task settings for the asset to
be imported. Function will convert list[unreal.AssetImportTask] to
unreal.Array(unreal.AssetImportTask).
Returns:
list: The file paths of the imported assets.
"""
is_reload = []
tasks = unreal.Array(unreal.AssetImportTask)
for i in import_tasks:
# Convert list of import tasks to unreal.Array of import tasks
# and mark the pre-existing assets as re-imported for log.
tasks.append(i)
unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks)
asset_paths = []
for i in import_tasks:
paths = cast(collections.Iterable, i.get_editor_property('imported_object_paths'))
for path in paths:
asset_paths.append(path)
if not path.split('.')[0] in is_reload:
unreal.log_warning(f'\nImported: {path}\n')
else:
unreal.log_warning(f'\nReImported: {path}s\n')
return asset_paths
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Import options by import type
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
def _import_sm_options(options: ImportSMOptions) -> unreal.FbxImportUI:
"""
Creates the import options for static meshes.
Args:
options (ImportSMOptions): The import options object with static mesh
editor properties.
Returns:
unreal.FbxImportUI: The import options for the static mesh.
"""
ui_options = unreal.FbxImportUI()
# FBX generic import data
ui_options.set_editor_property('import_mesh', True)
ui_options.set_editor_property('import_textures', True)
ui_options.set_editor_property('import_materials', True)
ui_options.set_editor_property('import_as_skeletal', False)
ui_options.set_editor_property('import_animations', False)
ui_options.set_editor_property('create_physics_asset', False)
# FBX mesh import data
_set_property = partial(short.set_staticmesh_property, ui_options)
_set_property('import_translation', options.loc)
_set_property('import_rotation', options.rot)
_set_property('import_uniform_scale', options.scale)
_set_property('combine_meshes', options.merge)
_set_property('remove_degenerates', options.remove_degenerates)
_set_property('generate_lightmap_u_vs', options.generate_lightmaps)
_set_property('auto_generate_collision', options.auto_gen_collisions)
_set_property('convert_scene', True)
_set_property('force_front_x_axis', False)
_set_property('convert_scene_unit', False)
_set_property('normal_generation_method', options.normal_gen_method)
_set_property('normal_import_method', options.normal_import_method)
_set_property('one_convex_hull_per_ucx', options.one_convex_hull)
_set_property('transform_vertex_to_absolute', True)
_set_property('build_reversed_index_buffer', True)
unreal.log('IMPORTING STATIC MESH')
return ui_options
def _import_sk_options(options: ImportSKOptions) -> unreal.FbxImportUI:
"""
Creates the import options for skeletal meshes.
Args:
options (ImportSKOptions): The task options defining how to import the
skeletal mesh.
Returns:
unreal.FbxImportUI: The import options for the skeletal mesh.
"""
ui_options = unreal.FbxImportUI()
# Fbx generic import data
ui_options.set_editor_property('import_mesh', True)
ui_options.set_editor_property('import_textures', True)
ui_options.set_editor_property('import_materials', True)
ui_options.set_editor_property('import_as_skeletal', True)
ui_options.set_editor_property('import_animations', False)
ui_options.set_editor_property('create_physics_asset', options.create_physics_asset)
# Fbx skeletal import data
_set_property = partial(short.set_skel_property, ui_options)
_set_property('import_translation', options.loc)
_set_property('import_rotation', options.rot)
_set_property('import_uniform_scale', options.scale)
_set_property('import_morph_targets', options.import_morph_targets)
_set_property('use_t0_as_ref_pose', True)
_set_property('preserve_smoothing_groups', options.preserve_smoothing_groups)
_set_property('import_meshes_in_bone_hierarchy', True)
_set_property('threshold_position', 0.00002)
_set_property('threshold_tangent_normal', 0.00002)
_set_property('threshold_uv', 0.000977)
_set_property('convert_scene', options.convert_scene)
_set_property('force_front_x_axis', False)
_set_property('convert_scene_unit', False)
_set_property('transform_vertex_to_absolute', True)
_set_property('normal_generation_method', options.normal_gen_method)
_set_property('normal_import_method', options.normal_import_method)
# Skeleton for imported mesh, if none specified, import skeleton in fbx
if options.skeleton:
ui_options.skeleton = options.skeleton
unreal.log('IMPORTING SKEL MESH')
return ui_options
def _import_anim_options(options: ImportAnimOptions) -> unreal.FbxImportUI:
"""
Import options for skel mesh animations. Will import skeleton in fbx if none provided.
Args:
options (ImportAnimOptions): The task options defining how to import the
animation.
Returns:
unreal.FbxImportUI: The import options for the skeletal mesh animation.
"""
ui_options = unreal.FbxImportUI()
# Fbx generic import data
ui_options.set_editor_property('import_animations', True)
ui_options.set_editor_property('import_materials', False)
ui_options.set_editor_property('import_textures', False)
ui_options.set_editor_property('create_physics_asset', False)
if options.skeleton:
ui_options.set_editor_property('import_mesh', False)
ui_options.skeleton = options.skeleton
else:
ui_options.set_editor_property('import_mesh', True)
short.set_skel_property(ui_options, 'import_morph_targets', True)
if options.fps != 30:
short.set_anim_property(ui_options, 'use_default_sample_rate', False)
else:
short.set_anim_property(ui_options, 'use_default_sample_rate', True)
_set_property = partial(short.set_skel_property, ui_options)
# Fbx skel mesh import data
_set_property('import_translation', options.loc)
_set_property('import_rotation', options.rot)
_set_property('import_uniform_scale', options.scale)
_set_property('convert_scene', options.convert_scene)
_set_property('force_front_x_axis', False)
_set_property('convert_scene_unit', False)
_set_property('import_meshes_in_bone_hierarchy', True)
# Fbx anim sequence import data
_set_property('delete_existing_morph_target_curves', options.del_morph_targets)
_set_property('import_custom_attribute', True)
_set_property('import_bone_tracks', True)
_set_property('custom_sample_rate', options.fps)
_set_property('do_not_import_curve_with_zero', True)
_set_property('remove_redundant_keys', True)
_set_property('animation_length', unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME)
unreal.log('IMPORTING SKELETAL MESH ANIMATION')
return ui_options
|
import unreal
asset_name = "MyAwesomeBPActorClass"
package_path = "/project/"
factory = unreal.BlueprintFactory()
factory.set_editor_property("ParentClass", unreal.Actor)
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
my_new_asset = asset_tools.create_asset(asset_name, package_path, None, factory)
assetSubsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
assetSubsystem.save_loaded_asset(my_new_asset)
|
# -*- coding: utf-8 -*-
"""
copy asset reference to clipboard
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
__author__ = 'timmyliang'
__email__ = '[email protected]'
__date__ = '2021-04-09 09:27:23'
import unreal
from Qt import QtWidgets
util_lib = unreal.EditorUtilityLibrary
def main():
path_list = [asset.get_path_name() for asset in util_lib.get_selected_assets()]
path = "\n".join(path_list)
cb = QtWidgets.QApplication.clipboard()
cb.clear(mode=cb.Clipboard)
cb.setText(path, mode=cb.Clipboard)
if __name__ == '__main__':
main()
|
import unreal
AssetRegistry = unreal.AssetRegistryHelpers.get_asset_registry()
UtilLibrary = unreal.EditorUtilityLibrary
"""
rename_asset(asset, new_name) -> None
get_selection_set() -> Array(Actor)
get_selection_bounds() -> (origin=Vector, box_extent=Vector, sphere_radius=float)
get_selected_blueprint_classes() -> Array(type(Class))
get_selected_assets() -> Array(Object)
get_selected_asset_data() -> Array(AssetData)
get_actor_reference(path_to_actor) -> Actor
"""
AutomationScheduler = unreal.AutomationScheduler
AssetTools = unreal.AssetToolsHelpers.get_asset_tools()
"""
rename_referencing_soft_object_paths(packages_to_check, asset_redirector_map)
rename_assets_with_dialog(assets_and_names, auto_checkout=False)
rename_assets(assets_and_names)
open_editor_for_assets(assets)
import_asset_tasks(import_tasks)
import_assets_with_dialog(destination_path)
import_assets_automated(import_data)
find_soft_references_to_object(target_object)
export_assets_with_dialog(assets_to_export, prompt_for_individual_filenames)
export_assets(assets_to_export, export_path)
duplicate_asset_with_dialog_and_title(asset_name, package_path, original_object, dialog_title)
duplicate_asset_with_dialog(asset_name, package_path, original_object)
duplicate_asset(asset_name, package_path, original_object)
create_unique_asset_name(base_package_name, suffix)
create_asset_with_dialog(asset_name, package_path, asset_class, factory, calling_context="None")
create_asset(asset_name, package_path, asset_class, factory, calling_context="None")
"""
AssetLibrary = unreal.EditorAssetLibrary
"""
sync_browser_to_objects(cls, asset_paths)
set_metadata_tag(cls, object, tag, value)
save_loaded_assets(cls, assets_to_save, only_if_is_dirty=True)
save_loaded_asset(cls, asset_to_save, only_if_is_dirty=True)
save_directory(cls, directory_path, only_if_is_dirty=True, recursive=True)
save_asset(cls, asset_to_save, only_if_is_dirty=True)
rename_loaded_asset(cls, source_asset, destination_asset_path)
rename_directory(cls, source_directory_path, destination_directory_path)
rename_asset(cls, source_asset_path, destination_asset_path)
remove_metadata_tag(cls, object, tag)
make_directory(cls, directory_path)
load_blueprint_class(cls, asset_path)
load_asset(cls, asset_path)
list_assets(cls, directory_path, recursive=True, include_folder=False)
list_asset_by_tag_value(cls, tag_name, tag_value)
get_tag_values(cls, asset_path)
get_path_name_for_loaded_asset(cls, loaded_asset)
get_metadata_tag_values(cls, object)
get_metadata_tag(cls, object, tag)
find_package_referencers_for_asset(cls, asset_path, load_assets_to_confirm=False)
find_asset_data(cls, asset_path)
duplicate_loaded_asset(cls, source_asset, destination_asset_path)
duplicate_directory(cls, source_directory_path, destination_directory_path)
duplicate_asset(cls, source_asset_path, destination_asset_path)
does_directory_have_assets(cls, directory_path, recursive=True)
does_directory_exist(cls, directory_path)
does_asset_exist(cls, asset_path)
do_assets_exist(cls, asset_paths)
delete_loaded_assets(cls, assets_to_delete)
delete_loaded_asset(cls, asset_to_delete)
delete_directory(cls, directory_path)
delete_asset(cls, asset_path_to_delete)
consolidate_assets(cls, asset_to_consolidate_to, assets_to_consolidate)
checkout_loaded_assets(cls, assets_to_checkout)
checkout_loaded_asset(cls, asset_to_checkout)
checkout_directory(cls, directory_path, recursive=True)
checkout_asset(cls, asset_to_checkout)
"""
FilterLibrary = unreal.EditorFilterLibrary
"""
Utility class to filter a list of objects. Object should be in the World Editor.
by_selection(cls, target_array, filter_type=EditorScriptingFilterType.INCLUDE)
by_level_name(cls, target_array, level_name, filter_type=EditorScriptingFilterType.INCLUDE)
by_layer(cls, target_array, layer_name, filter_type=EditorScriptingFilterType.INCLUDE)
by_id_name(cls, target_array, name_sub_string, string_match=EditorScriptingStringMatchType.CONTAINS, filter_type=EditorScriptingFilterType.INCLUDE)
by_class(cls, target_array, object_class, filter_type=EditorScriptingFilterType.INCLUDE)
by_actor_tag(cls, target_array, tag, filter_type=EditorScriptingFilterType.INCLUDE)
by_actor_label(cls, target_array, name_sub_string, string_match=EditorScriptingStringMatchType.CONTAINS, filter_type=EditorScriptingFilterType.INCLUDE, ignore_case=True)
"""
AutomationLibrary = unreal.AutomationLibrary
"""
take_high_res_screenshot(cls, res_x, res_y, filename, camera=None, mask_enabled=False, capture_hdr=False, comparison_tolerance=ComparisonTolerance.LOW, comparison_notes="")
take_automation_screenshot_of_ui(cls, world_context_object, latent_info, name, options)
take_automation_screenshot_at_camera(cls, world_context_object, latent_info, camera, name_override, notes, options)
take_automation_screenshot(cls, world_context_object, latent_info, name, notes, options)
set_scalability_quality_to_low(cls, world_context_object)
set_scalability_quality_to_epic(cls, world_context_object)
set_scalability_quality_level_relative_to_max(cls, world_context_object, value=1)
get_stat_inc_max(cls, stat_name)
get_stat_inc_average(cls, stat_name)
get_stat_exc_max(cls, stat_name)
get_stat_exc_average(cls, stat_name)
get_stat_call_count(cls, stat_name)
get_default_screenshot_options_for_rendering(cls, tolerance=ComparisonTolerance.LOW, delay=0.200000)
get_default_screenshot_options_for_gameplay(cls, tolerance=ComparisonTolerance.LOW, delay=0.200000)
enable_stat_group(cls, world_context_object, group_name)
disable_stat_group(cls, world_context_object, group_name)
automation_wait_for_loading(cls, world_context_object, latent_info)
are_automated_tests_running(cls)
add_expected_log_error(cls, expected_pattern_string, occurrences=1, exact_match=False)
"""
LevelLibrary = unreal.EditorLevelLibrary
"""
spawn_actor_from_object(object_to_use, location, rotation=[0.000000, 0.000000, 0.000000]) -> Actor
spawn_actor_from_class(actor_class, location, rotation=[0.000000, 0.000000, 0.000000]) -> Actor
set_selected_level_actors(actors_to_select) -> None
set_level_viewport_camera_info(camera_location, camera_rotation) -> None
set_current_level_by_name(level_name) -> bool
set_actor_selection_state(actor, should_be_selected) -> None
select_nothing() -> None
save_current_level() -> bool
save_all_dirty_levels() -> bool
replace_mesh_components_meshes_on_actors(actors, mesh_to_be_replaced, new_mesh) -> None
replace_mesh_components_meshes(mesh_components, mesh_to_be_replaced, new_mesh) -> None
replace_mesh_components_materials_on_actors(actors, material_to_be_replaced, new_material) -> None
replace_mesh_components_materials(mesh_components, material_to_be_replaced, new_material) -> None
pilot_level_actor(actor_to_pilot) -> None
new_level_from_template(asset_path, template_asset_path) -> bool
new_level(asset_path) -> bool
merge_static_mesh_actors(actors_to_merge, merge_options) -> StaticMeshActor or None
load_level(asset_path) -> bool
join_static_mesh_actors(actors_to_join, join_options) -> Actor
get_selected_level_actors() -> Array(Actor)
get_level_viewport_camera_info() -> (camera_location=Vector, camera_rotation=Rotator) or None
get_game_world() -> World
get_editor_world() -> World
get_all_level_actors_components() -> Array(ActorComponent)
get_all_level_actors() -> Array(Actor)
get_actor_reference(path_to_actor) -> Actor
eject_pilot_level_actor() -> None
editor_set_game_view(game_view) -> None
editor_play_simulate() -> None
editor_invalidate_viewports() -> None
destroy_actor(actor_to_destroy) -> bool
create_proxy_mesh_actor(actors_to_merge, merge_options) -> StaticMeshActor or None
convert_actors(actors, actor_class, static_mesh_package_path) -> Array(Actor)
clear_actor_selection_set() -> None
"""
SequenceBindingLibrary = unreal.MovieSceneBindingExtensions
"""
set_parent(binding, parent_binding) -> None
remove_track(binding, track_to_remove) -> None
remove(binding) -> None
is_valid(binding) -> bool
get_tracks(binding) -> Array(MovieSceneTrack)
get_possessed_object_class(binding) -> type(Class)
get_parent(binding) -> SequencerBindingProxy
get_object_template(binding) -> Object
get_name(binding) -> str
get_id(binding) -> Guid
get_display_name(binding) -> Text
get_child_possessables(binding) -> Array(SequencerBindingProxy)
find_tracks_by_type(binding, track_type) -> Array(MovieSceneTrack)
find_tracks_by_exact_type(binding, track_type) -> Array(MovieSceneTrack)
add_track(binding, track_type) -> MovieSceneTrack
"""
SequenceFolderLibrary = unreal.MovieSceneFolderExtensions
"""
set_folder_name(folder, folder_name) -> bool
set_folder_color(folder, folder_color) -> bool
remove_child_object_binding(folder, object_binding) -> bool
remove_child_master_track(folder, master_track) -> bool
remove_child_folder(target_folder, folder_to_remove) -> bool
get_folder_name(folder) -> Name
get_folder_color(folder) -> Color
get_child_object_bindings(folder) -> Array(SequencerBindingProxy)
get_child_master_tracks(folder) -> Array(MovieSceneTrack)
get_child_folders(folder) -> Array(MovieSceneFolder)
add_child_object_binding(folder, object_binding) -> bool
add_child_master_track(folder, master_track) -> bool
add_child_folder(target_folder, folder_to_add) -> bool
"""
SequencePropertyLibrary = unreal.MovieScenePropertyTrackExtensions
"""
X.set_property_name_and_path(track, property_name, property_path) -> None
X.set_object_property_class(track, property_class) -> None
X.get_unique_track_name(track) -> Name
X.get_property_path(track) -> str
X.get_property_name(track) -> Name
X.get_object_property_class(track) -> type(Class)
"""
SequenceSectionLibrary = unreal.MovieSceneSectionExtensions
"""
set_start_frame_seconds(section, start_time) -> None
set_start_frame_bounded(section, is_bounded) -> None
set_start_frame(section, start_frame) -> None
set_range_seconds(section, start_time, end_time) -> None
set_range(section, start_frame, end_frame) -> None
set_end_frame_seconds(section, end_time) -> None
set_end_frame_bounded(section, is_bounded) -> None
set_end_frame(section, end_frame) -> None
get_start_frame_seconds(section) -> float
get_start_frame(section) -> int32
get_parent_sequence_frame(section, frame, parent_sequence) -> int32
get_end_frame_seconds(section) -> float
get_end_frame(section) -> int32
get_channels(section) -> Array(MovieSceneScriptingChannel)
find_channels_by_type(section, channel_type) -> Array(MovieSceneScriptingChannel)
"""
SequenceLibrary = unreal.MovieSceneSectionExtensions
"""
set_work_range_start(sequence, start_time_in_seconds) -> None
set_work_range_end(sequence, end_time_in_seconds) -> None
set_view_range_start(sequence, start_time_in_seconds) -> None
set_view_range_end(sequence, end_time_in_seconds) -> None
set_tick_resolution(sequence, tick_resolution) -> None
set_read_only(sequence, read_only) -> None
set_playback_start_seconds(sequence, start_time) -> None
set_playback_start(sequence, start_frame) -> None
set_playback_end_seconds(sequence, end_time) -> None
set_playback_end(sequence, end_frame) -> None
set_display_rate(sequence, display_rate) -> None
make_range_seconds(sequence, start_time, duration) -> SequencerScriptingRange
make_range(sequence, start_frame, duration) -> SequencerScriptingRange
make_binding_id(master_sequence, binding, space=MovieSceneObjectBindingSpace.ROOT) -> MovieSceneObjectBindingID
locate_bound_objects(sequence, binding, context) -> Array(Object)
is_read_only(sequence) -> bool
get_work_range_start(sequence) -> float
get_work_range_end(sequence) -> float
get_view_range_start(sequence) -> float
get_view_range_end(sequence) -> float
get_timecode_source(sequence) -> Timecode
get_tick_resolution(sequence) -> FrameRate
get_spawnables(sequence) -> Array(SequencerBindingProxy)
get_root_folders_in_sequence(sequence) -> Array(MovieSceneFolder)
get_possessables(sequence) -> Array(SequencerBindingProxy)
get_playback_start_seconds(sequence) -> float
get_playback_start(sequence) -> int32
get_playback_range(sequence) -> SequencerScriptingRange
get_playback_end_seconds(sequence) -> float
get_playback_end(sequence) -> int32
get_movie_scene(sequence) -> MovieScene
get_master_tracks(sequence) -> Array(MovieSceneTrack)
get_marked_frames(sequence) -> Array(MovieSceneMarkedFrame)
get_display_rate(sequence) -> FrameRate
get_bindings(sequence) -> Array(SequencerBindingProxy)
find_next_marked_frame(sequence, frame_number, forward) -> int32
find_master_tracks_by_type(sequence, track_type) -> Array(MovieSceneTrack)
find_master_tracks_by_exact_type(sequence, track_type) -> Array(MovieSceneTrack)
find_marked_frame_by_label(sequence, label) -> int32
find_marked_frame_by_frame_number(sequence, frame_number) -> int32
find_binding_by_name(sequence, name) -> SequencerBindingProxy
delete_marked_frames(sequence) -> None
delete_marked_frame(sequence, delete_index) -> None
add_spawnable_from_instance(sequence, object_to_spawn) -> SequencerBindingProxy
add_spawnable_from_class(sequence, class_to_spawn) -> SequencerBindingProxy
add_root_folder_to_sequence(sequence, new_folder_name) -> MovieSceneFolder
add_possessable(sequence, object_to_possess) -> SequencerBindingProxy
add_master_track(sequence, track_type) -> MovieSceneTrack
add_marked_frame(sequence, marked_frame) -> int32
"""
SequenceTrackLibrary = unreal.MovieSceneTrackExtensions
"""
remove_section(track, section) -> None
get_sections(track) -> Array(MovieSceneSection)
get_display_name(track) -> Text
add_section(track) -> MovieSceneSection
"""
SequenceTools = unreal.SequencerTools
"""
render_movie(capture_settings, on_finished_callback) -> bool
is_rendering_movie() -> bool
import_fbx(world, sequence, bindings, import_fbx_settings, import_filename) -> bool
get_object_bindings(world, sequence, object, range) -> Array(SequencerBoundObjects)
get_bound_objects(world, sequence, bindings, range) -> Array(SequencerBoundObjects)
export_fbx(world, sequence, bindings, override_options, fbx_file_name) -> bool
export_anim_sequence(world, sequence, anim_sequence, binding) -> bool
cancel_movie_render() -> None
"""
LevelSequenceLibrary = unreal.LevelSequenceEditorBlueprintLibrary
"""
set_lock_level_sequence(lock) -> None
set_current_time(new_frame) -> None
play() -> None
pause() -> None
open_level_sequence(level_sequence) -> bool
is_playing() -> bool
is_level_sequence_locked() -> bool
get_current_time() -> int32
get_current_level_sequence() -> LevelSequence
close_level_sequence() -> None
"""
PathLib = unreal.Paths
"""
video_capture_dir() -> str
validate_path(path) -> (did_succeed=bool, out_reason=Text)
split(path) -> (path_part=str, filename_part=str, extension_part=str)
source_config_dir() -> str
should_save_to_user_dir() -> bool
shader_working_dir() -> str
set_project_file_path(new_game_project_file_path) -> None
set_extension(path, new_extension) -> str
screen_shot_dir() -> str
sandboxes_dir() -> str
root_dir() -> str
remove_duplicate_slashes(path) -> str
project_user_dir() -> str
project_saved_dir() -> str
project_plugins_dir() -> str
project_persistent_download_dir() -> str
project_mods_dir() -> str
project_log_dir() -> str
project_intermediate_dir() -> str
project_dir() -> str
project_content_dir() -> str
project_config_dir() -> str
profiling_dir() -> str
normalize_filename(path) -> str
normalize_directory_name(path) -> str
make_valid_file_name(string, replacement_char="") -> str
make_standard_filename(path) -> str
make_platform_filename(path) -> str
make_path_relative_to(path, relative_to) -> str or None
launch_dir() -> str
is_same_path(path_a, path_b) -> bool
is_restricted_path(path) -> bool
is_relative(path) -> bool
is_project_file_path_set() -> bool
is_drive(path) -> bool
has_project_persistent_download_dir() -> bool
get_tool_tip_localization_paths() -> Array(str)
get_restricted_folder_names() -> Array(str)
get_relative_path_to_root() -> str
get_property_name_localization_paths() -> Array(str)
get_project_file_path() -> str
get_path(path) -> str
get_invalid_file_system_chars() -> str
get_game_localization_paths() -> Array(str)
get_extension(path, include_dot=False) -> str
get_engine_localization_paths() -> Array(str)
get_editor_localization_paths() -> Array(str)
get_clean_filename(path) -> str
get_base_filename(path, remove_path=True) -> str
generated_config_dir() -> str
game_user_developer_dir() -> str
game_source_dir() -> str
game_developers_dir() -> str
game_agnostic_saved_dir() -> str
file_exists(path) -> bool
feature_pack_dir() -> str
enterprise_plugins_dir() -> str
enterprise_feature_pack_dir() -> str
enterprise_dir() -> str
engine_version_agnostic_user_dir() -> str
engine_user_dir() -> str
engine_source_dir() -> str
engine_saved_dir() -> str
engine_plugins_dir() -> str
engine_intermediate_dir() -> str
engine_dir() -> str
engine_content_dir() -> str
engine_config_dir() -> str
directory_exists(path) -> bool
diff_dir() -> str
create_temp_filename(path, prefix="", extension=".tmp") -> str
convert_to_sandbox_path(path, sandbox_name) -> str
convert_relative_path_to_full(path, base_path="") -> str
convert_from_sandbox_path(path, sandbox_name) -> str
combine(paths) -> str
collapse_relative_directories(path) -> str or None
cloud_dir() -> str
change_extension(path, new_extension) -> str
bug_it_dir() -> str
automation_transient_dir() -> str
automation_log_dir() -> str
automation_dir() -> str
"""
SystemLib = unreal.SystemLibrary
"""
unregister_for_remote_notifications() -> None
unload_primary_asset_list(primary_asset_id_list) -> None
unload_primary_asset(primary_asset_id) -> None
transact_object(object) -> None
sphere_trace_single_for_objects(world_context_object, start, end, radius, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
sphere_trace_single_by_profile(world_context_object, start, end, radius, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
sphere_trace_single(world_context_object, start, end, radius, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
sphere_trace_multi_for_objects(world_context_object, start, end, radius, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
sphere_trace_multi_by_profile(world_context_object, start, end, radius, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
sphere_trace_multi(world_context_object, start, end, radius, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
sphere_overlap_components(world_context_object, sphere_pos, sphere_radius, object_types, component_class_filter, actors_to_ignore) -> Array(PrimitiveComponent) or None
sphere_overlap_actors(world_context_object, sphere_pos, sphere_radius, object_types, actor_class_filter, actors_to_ignore) -> Array(Actor) or None
snapshot_object(object) -> None
show_platform_specific_leaderboard_screen(category_name) -> None
show_platform_specific_achievements_screen(specific_player) -> None
show_interstitial_ad() -> None
show_ad_banner(ad_id_index, show_on_bottom_of_screen) -> None
set_window_title(title) -> None
set_volume_buttons_handled_by_system(enabled) -> None
set_user_activity(user_activity) -> None
set_suppress_viewport_transition_message(world_context_object, state) -> None
set_gamepads_block_device_feedback(block) -> None
retriggerable_delay(world_context_object, duration, latent_info) -> None
reset_gamepad_assignment_to_controller(controller_id) -> None
reset_gamepad_assignments() -> None
register_for_remote_notifications() -> None
quit_game(world_context_object, specific_player, quit_preference, ignore_platform_restrictions) -> None
quit_editor() -> None
print_text(world_context_object, text="Hello", print_to_screen=True, print_to_log=True, text_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=2.000000) -> None
print_string(world_context_object, string="Hello", print_to_screen=True, print_to_log=True, text_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=2.000000) -> None
not_equal_soft_object_reference(a, b) -> bool
not_equal_soft_class_reference(a, b) -> bool
not_equal_primary_asset_type(a, b) -> bool
not_equal_primary_asset_id(a, b) -> bool
normalize_filename(filename) -> str
move_component_to(component, target_relative_location, target_relative_rotation, ease_out, ease_in, over_time, force_shortest_rotation_path, move_action, latent_info) -> None
make_literal_text(value) -> Text
make_literal_string(value) -> str
make_literal_name(value) -> Name
make_literal_int(value) -> int32
make_literal_float(value) -> float
make_literal_byte(value) -> uint8
make_literal_bool(value) -> bool
load_interstitial_ad(ad_id_index) -> None
load_class_asset_blocking(asset_class) -> type(Class)
load_asset_blocking(asset) -> Object
line_trace_single_for_objects(world_context_object, start, end, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
line_trace_single_by_profile(world_context_object, start, end, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
line_trace_single(world_context_object, start, end, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
line_trace_multi_for_objects(world_context_object, start, end, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
line_trace_multi_by_profile(world_context_object, start, end, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
line_trace_multi(world_context_object, start, end, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
launch_url(url) -> None
un_pause_timer_handle(world_context_object, handle) -> None
un_pause_timer_delegate(delegate) -> None
un_pause_timer(object, function_name) -> None
timer_exists_handle(world_context_object, handle) -> bool
timer_exists_delegate(delegate) -> bool
timer_exists(object, function_name) -> bool
set_timer_delegate(delegate, time, looping, initial_start_delay=0.000000, initial_start_delay_variance=0.000000) -> TimerHandle
set_timer(object, function_name, time, looping, initial_start_delay=0.000000, initial_start_delay_variance=0.000000) -> TimerHandle
pause_timer_handle(world_context_object, handle) -> None
pause_timer_delegate(delegate) -> None
pause_timer(object, function_name) -> None
is_valid_timer_handle(handle) -> bool
is_timer_paused_handle(world_context_object, handle) -> bool
is_timer_paused_delegate(delegate) -> bool
is_timer_paused(object, function_name) -> bool
is_timer_active_handle(world_context_object, handle) -> bool
is_timer_active_delegate(delegate) -> bool
is_timer_active(object, function_name) -> bool
invalidate_timer_handle(handle) -> (TimerHandle, handle=TimerHandle)
get_timer_remaining_time_handle(world_context_object, handle) -> float
get_timer_remaining_time_delegate(delegate) -> float
get_timer_remaining_time(object, function_name) -> float
get_timer_elapsed_time_handle(world_context_object, handle) -> float
get_timer_elapsed_time_delegate(delegate) -> float
get_timer_elapsed_time(object, function_name) -> float
clear_timer_handle(world_context_object, handle) -> None
clear_timer_delegate(delegate) -> None
clear_timer(object, function_name) -> None
clear_and_invalidate_timer_handle(world_context_object, handle) -> TimerHandle
is_valid_soft_object_reference(soft_object_reference) -> bool
is_valid_soft_class_reference(soft_class_reference) -> bool
is_valid_primary_asset_type(primary_asset_type) -> bool
is_valid_primary_asset_id(primary_asset_id) -> bool
is_valid_class(class_) -> bool
is_valid(object) -> bool
is_unattended() -> bool
is_standalone(world_context_object) -> bool
is_split_screen(world_context_object) -> bool
is_server(world_context_object) -> bool
is_screensaver_enabled() -> bool
is_packaged_for_distribution() -> bool
is_logged_in(specific_player) -> bool
is_interstitial_ad_requested() -> bool
is_interstitial_ad_available() -> bool
is_dedicated_server(world_context_object) -> bool
is_controller_assigned_to_gamepad(controller_id) -> bool
hide_ad_banner() -> None
get_volume_buttons_handled_by_system() -> bool
get_unique_device_id() -> str
get_supported_fullscreen_resolutions() -> Array(IntPoint) or None
get_soft_object_reference_from_primary_asset_id(primary_asset_id) -> Object
get_soft_class_reference_from_primary_asset_id(primary_asset_id) -> Class
get_rendering_material_quality_level() -> int32
get_rendering_detail_mode() -> int32
get_project_saved_directory() -> str
get_project_directory() -> str
get_project_content_directory() -> str
get_primary_assets_with_bundle_state(required_bundles, excluded_bundles, valid_types, force_current_state) -> Array(PrimaryAssetId)
get_primary_asset_id_list(primary_asset_type) -> Array(PrimaryAssetId)
get_primary_asset_id_from_soft_object_reference(soft_object_reference) -> PrimaryAssetId
get_primary_asset_id_from_soft_class_reference(soft_class_reference) -> PrimaryAssetId
get_primary_asset_id_from_object(object) -> PrimaryAssetId
get_primary_asset_id_from_class(class_) -> PrimaryAssetId
get_preferred_languages() -> Array(str)
get_platform_user_name() -> str
get_platform_user_dir() -> str
get_path_name(object) -> str
get_outer_object(object) -> Object
get_object_name(object) -> str
get_object_from_primary_asset_id(primary_asset_id) -> Object
get_min_y_resolution_for_ui() -> int32
get_min_y_resolution_for3d_view() -> int32
get_local_currency_symbol() -> str
get_local_currency_code() -> str
get_game_time_in_seconds(world_context_object) -> float
get_gamepad_controller_name(controller_id) -> str
get_game_name() -> str
get_game_bundle_id() -> str
get_frame_count() -> int64
get_engine_version() -> str
get_display_name(object) -> str
get_device_id() -> str
get_default_locale() -> str
get_default_language() -> str
get_current_bundle_state(primary_asset_id, force_current_state) -> Array(Name) or None
get_convenient_windowed_resolutions() -> Array(IntPoint) or None
get_console_variable_int_value(variable_name) -> int32
get_console_variable_float_value(variable_name) -> float
get_console_variable_bool_value(variable_name) -> bool
get_component_bounds(component) -> (origin=Vector, box_extent=Vector, sphere_radius=float)
get_command_line() -> str
get_class_from_primary_asset_id(primary_asset_id) -> type(Class)
get_class_display_name(class_) -> str
get_ad_id_count() -> int32
get_actor_list_from_component_list(component_list, actor_class_filter) -> Array(Actor)
get_actor_bounds(actor) -> (origin=Vector, box_extent=Vector)
force_close_ad_banner() -> None
flush_persistent_debug_lines(world_context_object) -> None
flush_debug_strings(world_context_object) -> None
execute_console_command(world_context_object, command, specific_player=None) -> None
equal_equal_soft_object_reference(a, b) -> bool
equal_equal_soft_class_reference(a, b) -> bool
equal_equal_primary_asset_type(a, b) -> bool
equal_equal_primary_asset_id(a, b) -> bool
end_transaction() -> int32
draw_debug_string(world_context_object, text_location, text, test_base_actor=None, text_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_sphere(world_context_object, center, radius=100.000000, segments=12, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_point(world_context_object, position, size, point_color, duration=0.000000) -> None
draw_debug_plane(world_context_object, plane_coordinates, location, size, plane_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_line(world_context_object, line_start, line_end, line_color, duration=0.000000, thickness=0.000000) -> None
draw_debug_frustum(world_context_object, frustum_transform, frustum_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_float_history_transform(world_context_object, float_history, draw_transform, draw_size, draw_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_float_history_location(world_context_object, float_history, draw_location, draw_size, draw_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_cylinder(world_context_object, start, end, radius=100.000000, segments=12, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_coordinate_system(world_context_object, axis_loc, axis_rot, scale=1.000000, duration=0.000000, thickness=0.000000) -> None
draw_debug_cone_in_degrees(world_context_object, origin, direction, length=100.000000, angle_width=45.000000, angle_height=45.000000, num_sides=12, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_cone(world_context_object, origin, direction, length, angle_width, angle_height, num_sides, line_color, duration=0.000000, thickness=0.000000) -> None
draw_debug_circle(world_context_object, center, radius, num_segments=12, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000, y_axis=[0.000000, 1.000000, 0.000000], z_axis=[0.000000, 0.000000, 1.000000], draw_axis=False) -> None
draw_debug_capsule(world_context_object, center, half_height, radius, rotation, line_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_camera(camera_actor, camera_color=[0.000000, 0.000000, 0.000000, 0.000000], duration=0.000000) -> None
draw_debug_box(world_context_object, center, extent, line_color, rotation=[0.000000, 0.000000, 0.000000], duration=0.000000, thickness=0.000000) -> None
draw_debug_arrow(world_context_object, line_start, line_end, arrow_size, line_color, duration=0.000000, thickness=0.000000) -> None
does_implement_interface(test_object, interface) -> bool
delay(world_context_object, duration, latent_info) -> None
create_copy_for_undo_buffer(object_to_modify) -> None
convert_to_relative_path(filename) -> str
convert_to_absolute_path(filename) -> str
conv_soft_obj_path_to_soft_obj_ref(soft_object_path) -> Object
conv_soft_object_reference_to_string(soft_object_reference) -> str
conv_soft_class_reference_to_string(soft_class_reference) -> str
conv_soft_class_path_to_soft_class_ref(soft_class_path) -> Class
conv_primary_asset_type_to_string(primary_asset_type) -> str
conv_primary_asset_id_to_string(primary_asset_id) -> str
conv_interface_to_object(interface) -> Object
control_screensaver(allow_screen_saver) -> None
component_overlap_components(component, component_transform, object_types, component_class_filter, actors_to_ignore) -> Array(PrimitiveComponent) or None
component_overlap_actors(component, component_transform, object_types, actor_class_filter, actors_to_ignore) -> Array(Actor) or None
collect_garbage() -> None
capsule_trace_single_for_objects(world_context_object, start, end, radius, half_height, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
capsule_trace_single_by_profile(world_context_object, start, end, radius, half_height, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
capsule_trace_single(world_context_object, start, end, radius, half_height, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
capsule_trace_multi_for_objects(world_context_object, start, end, radius, half_height, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
capsule_trace_multi_by_profile(world_context_object, start, end, radius, half_height, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
capsule_trace_multi(world_context_object, start, end, radius, half_height, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
capsule_overlap_components(world_context_object, capsule_pos, radius, half_height, object_types, component_class_filter, actors_to_ignore) -> Array(PrimitiveComponent) or None
capsule_overlap_actors(world_context_object, capsule_pos, radius, half_height, object_types, actor_class_filter, actors_to_ignore) -> Array(Actor) or None
can_launch_url(url) -> bool
cancel_transaction(index) -> None
box_trace_single_for_objects(world_context_object, start, end, half_size, orientation, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
box_trace_single_by_profile(world_context_object, start, end, half_size, orientation, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
box_trace_single(world_context_object, start, end, half_size, orientation, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> HitResult or None
box_trace_multi_for_objects(world_context_object, start, end, half_size, orientation, object_types, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
box_trace_multi_by_profile(world_context_object, start, end, half_size, orientation, profile_name, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
box_trace_multi(world_context_object, start, end, half_size, orientation, trace_channel, trace_complex, actors_to_ignore, draw_debug_type, ignore_self, trace_color=[0.000000, 0.000000, 0.000000, 0.000000], trace_hit_color=[0.000000, 0.000000, 0.000000, 0.000000], draw_time=5.000000) -> Array(HitResult) or None
box_overlap_components(world_context_object, box_pos, extent, object_types, component_class_filter, actors_to_ignore) -> Array(PrimitiveComponent) or None
box_overlap_actors(world_context_object, box_pos, box_extent, object_types, actor_class_filter, actors_to_ignore) -> Array(Actor) or None
begin_transaction(context, description, primary_object) -> int32
add_float_history_sample(value, float_history) -> DebugFloatHistory
"""
|
import unreal
@unreal.uclass()
class EditorUtils(unreal.EditorUtilityLibrary):
pass
@unreal.uclass()
class EditorUtilsLib(unreal.BlueprintFunctionLibrary):
@unreal.ufunction(params=[str], static=True, meta=dict(Category="Editor Utils lib"))
def move_selected(dir):
selected_assets = EditorUtils.get_selected_assets()
if len(selected_assets) == 0:
unreal.log_warning("No asset selected")
for n, asset in enumerate(selected_assets):
unreal.log("selected asset {}:".format(n+1))
unreal.log(asset.get_full_name())
unreal.log(asset.get_name())
unreal.log(asset.get_path_name())
unreal.log(asset.get_class().get_name())
unreal.log(asset.get_class())
unreal.log("##############################")
prefix = ""
# pattern matching (switch) introduced in python 3.10
if isinstance(asset, unreal.EditorUtilityWidgetBlueprint):
prefix = "UW"
elif isinstance(asset, unreal.Blueprint):
prefix = "BP"
elif isinstance(asset, unreal.Material):
prefix = "M"
elif isinstance(asset, unreal.MaterialInstance):
prefix = "MI"
target_path_name = "/".join(("/Game", dir, "_".join((prefix, asset.get_name()))))
unreal.EditorAssetLibrary.rename_asset(asset.get_path_name(), target_path_name)
@unreal.ufunction(params=[int], static=True, meta=dict(Category="Editor Utils lib"))
def create_blueprint(count):
for i in range(count):
# if we try to create an asset at a certain folder that doesn't exists
# unreal will automatically catch that and create the folder structure
bp_name = "MyPlayerController{}".format(i)
bp_path = "/project/"
# assets are created through factories
factory = unreal.BlueprintFactory()
# we need to set the parent in the factory
# note that also factory derives from object
factory.set_editor_property("ParentClass", unreal.PlayerController)
asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
asset = asset_tools.create_asset(bp_name, bp_path, None, factory)
# much faster to change than in c++ no need to recompile anything :)
unreal.EditorAssetLibrary.save_loaded_asset(asset)
unreal.log("Imported PyEditorUtils")
|
import unreal
import sys
sys.path.append('Z:/project/')
import lib_narrs
|
# -*- coding: utf-8 -*-
# =======================================================================================================#
# ContentBrowserで選択しているMaterialInstanceの「Parameter.py」で指定したScalarParameterの値を上書きする#
# =======================================================================================================#
import unreal
# ---------------------------#
# GlobalEditorUtilityのクラス#
# ---------------------------#
@unreal.uclass()
class GEditUtil(unreal.GlobalEditorUtilityBase):
pass
@unreal.uclass()
class MatEditLib(unreal.MaterialEditingLibrary):
pass
# ------------------------------------------------------------------------------#
# Dictで作られたパラメーターの一覧から代入するScalarParameterValue型の配列を作成#
# ------------------------------------------------------------------------------#
def set_scalar_parameter(pnd, mi):
mel = MatEditLib()
pnd_keys = pnd.keys()
for key in pnd_keys:
# 指定したScalarParameterの値を指定した値にする
value = mel.set_material_instance_scalar_parameter_value(mi, unreal.Name(key), pnd[key])
# RetValがFalseなら編集できなかったというログはいてるけど、実際は絶対Falseなので、これ不要
if not value:
print("Failed set_material_instance_scalar_parameter_value MI = " + mi.get_name() + " Name = " + key + "")
def set_selected_scalar_parameter(pnd):
util = GEditUtil()
asset_list = util.get_selected_asset()
# 選択しているアセットをFor分で回して、MaterialInstanceだったら、指定したScalarParameterを指定した値にする
for asset in asset_list:
asset_name = asset.get_name()
if type(asset) != unreal.MaterialInstanceConstant:
print("Error:Selected [" + asset_name + "] is Not MaterialInstanceAsset.")
continue
material_instance = unreal.MaterialInstanceConstant.cast(asset)
set_scalar_parameter(pnd, material_instance)
print("Edit MaterialParameterValue that " + asset_name + "has.")
|
import unreal
@unreal.ustruct()
class AssetExportData(unreal.StructBase):
"""
Struct that contains data related with exported assets
"""
name = unreal.uproperty(str)
path = unreal.uproperty(str)
asset_type = unreal.uproperty(str)
fbx_file = unreal.uproperty(str)
|
"""This clicker was created to automate clicking actions to restore hundreds of corrupted blueprints,
caused by bad Unreal Python API implementation"""
import json
import pyperclip
import pyautogui
import time
import keyboard
with open("C:/project/ Projects/project/.json", "r") as f:
package_paths = json.load(f)
# mode = "weapon"
mode = "accessory_or_weapon_mod"
def move_and_click(x, y, button="left", ctrl=False, shift=False, alt=False):
"""
Moves the mouse to (x, y) and performs a click with optional key modifiers.
:param x: X-coordinate
:param y: Y-coordinate
:param button: "left" or "right" mouse button
:param ctrl: Hold Ctrl key
:param shift: Hold Shift key
:param alt: Hold Alt key
"""
# Move the mouse to the position
pyautogui.moveTo(x, y, duration=0)
# Press modifier keys if needed
if ctrl:
keyboard.press('ctrl')
if shift:
keyboard.press('shift')
if alt:
keyboard.press('alt')
# Perform the click
pyautogui.click(button=button)
# Release modifier keys
if ctrl:
keyboard.release('ctrl')
if shift:
keyboard.release('shift')
if alt:
keyboard.release('alt')
def get_code_for_asset_open(package_path):
return f"""
import unreal
asset = unreal.EditorAssetLibrary.load_asset("{package_path}")
a = unreal.AssetEditorSubsystem()
a.open_editor_for_assets([asset])
"""
def perform_ctrl_v():
keyboard.press('ctrl')
keyboard.press('v')
keyboard.release('ctrl')
keyboard.release('v')
# Allow to switch to Unreal
time.sleep(3)
for package_path in package_paths:
code_for_asset_open = get_code_for_asset_open(package_path)
# Switch to Unreal "Output Log" tab
move_and_click(219, 55, button="left")
# Select input box for python code
move_and_click(475, 1008, button="left")
# Paste and execute python code for opening asset
pyperclip.copy(code_for_asset_open)
perform_ctrl_v()
keyboard.press('enter')
keyboard.release('enter')
# Wait 3 seconds for asset open
time.sleep(3)
# Copy equipment fragment class
move_and_click(1402, 435, button="right", shift=True)
# Restore defaults for first fragment
move_and_click(1874, 362, button="left")
if mode == "weapon":
# Open sub-tab
move_and_click(62, 401, button="left")
# Paste equipment fragment class
move_and_click(1402, 435, button="left", shift=True)
elif mode == "accessory_or_weapon_mod":
# Select fragment dropout
move_and_click(987, 361, button="left")
# Select equipment fragment class
move_and_click(1052, 463, button="left")
# Open sub-tab
move_and_click(62, 401, button="left")
# Paste equipment fragment class
move_and_click(1402, 435, button="left", shift=True)
# Compile
move_and_click(180, 96, button="left")
# Wait 1 sec
time.sleep(1)
# Save
move_and_click(40, 96, button="left")
# Close blueprint
move_and_click(848, 49, button="left")
|
# Copyright (c) <2021> Side Effects Software Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. The name of Side Effects Software may not be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
# NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
""" Example script using the API to instantiate an HDA and set a landscape
input.
"""
import unreal
_g_wrapper = None
def get_test_hda_path():
return '/project/.hilly_landscape_erode_1_0'
def get_test_hda():
return unreal.load_object(None, get_test_hda_path())
def load_map():
return unreal.EditorLoadingAndSavingUtils.load_map('/project/.LandscapeInputExample')
def get_landscape():
return unreal.EditorLevelLibrary.get_actor_reference('PersistentLevel.Landscape_0')
def configure_inputs(in_wrapper):
print('configure_inputs')
# Unbind from the delegate
in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs)
# Create a landscape input
landscape_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPILandscapeInput)
# Send landscapes as heightfields
landscape_input.landscape_export_type = unreal.HoudiniLandscapeExportType.HEIGHTFIELD
# Keep world transform
landscape_input.keep_world_transform = True
# Set the input objects/assets for this input
landscape_object = get_landscape()
landscape_input.set_input_objects((landscape_object, ))
# copy the input data to the HDA as node input 0
in_wrapper.set_input_at_index(0, landscape_input)
# We can now discard the API input object
landscape_input = None
def print_api_input(in_input):
print('\t\tInput type: {0}'.format(in_input.__class__))
print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform))
if isinstance(in_input, unreal.HoudiniPublicAPILandscapeInput):
print('\t\tbLandscapeAutoSelectComponent: {0}'.format(in_input.landscape_auto_select_component))
print('\t\tbLandscapeExportLighting: {0}'.format(in_input.landscape_export_lighting))
print('\t\tbLandscapeExportMaterials: {0}'.format(in_input.landscape_export_materials))
print('\t\tbLandscapeExportNormalizedUVs: {0}'.format(in_input.landscape_export_normalized_u_vs))
print('\t\tbLandscapeExportSelectionOnly: {0}'.format(in_input.landscape_export_selection_only))
print('\t\tbLandscapeExportTileUVs: {0}'.format(in_input.landscape_export_tile_u_vs))
print('\t\tbLandscapeExportType: {0}'.format(in_input.landscape_export_type))
input_objects = in_input.get_input_objects()
if not input_objects:
print('\t\tEmpty input!')
else:
print('\t\tNumber of objects in input: {0}'.format(len(input_objects)))
for idx, input_object in enumerate(input_objects):
print('\t\t\tInput object #{0}: {1}'.format(idx, input_object))
def print_inputs(in_wrapper):
print('print_inputs')
# Unbind from the delegate
in_wrapper.on_post_processing_delegate.remove_callable(print_inputs)
# Fetch inputs, iterate over it and log
node_inputs = in_wrapper.get_inputs_at_indices()
parm_inputs = in_wrapper.get_input_parameters()
if not node_inputs:
print('No node inputs found!')
else:
print('Number of node inputs: {0}'.format(len(node_inputs)))
for input_index, input_wrapper in node_inputs.items():
print('\tInput index: {0}'.format(input_index))
print_api_input(input_wrapper)
if not parm_inputs:
print('No parameter inputs found!')
else:
print('Number of parameter inputs: {0}'.format(len(parm_inputs)))
for parm_name, input_wrapper in parm_inputs.items():
print('\tInput parameter name: {0}'.format(parm_name))
print_api_input(input_wrapper)
def run():
# Load the example map
load_map()
# get the API singleton
api = unreal.HoudiniPublicAPIBlueprintLib.get_api()
global _g_wrapper
# instantiate an asset with auto-cook enabled
_g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform())
# Configure inputs on_post_instantiation, after instantiation, but before first cook
_g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs)
# Print the input state after the cook and output creation.
_g_wrapper.on_post_processing_delegate.add_callable(print_inputs)
if __name__ == '__main__':
run()
|
# Standard library imports
import sys
import re
import time
import json
import os
import logging
import threading
from pathlib import Path
import importlib
# Third party imports
from PySide6 import QtWidgets, QtGui, QtCore
import unreal
# Local application imports
from export_performance import (
run_anim_sequence_export,
run_identity_level_sequence_export,
run_meta_human_level_sequence_export
)
import export_performance
importlib.reload(export_performance)
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Constants (default values)
DEFAULT_CONFIG = {
'MAX_RETRIES': 3,
'RETRY_DELAY': 5,
'MAX_WORKERS': 1, # Set to 1 to avoid multithreading issues
}
# Add this constant at the top of the file with the other constants
MOCAP_BASE_PATH = "/project/"
METAHUMAN_BASE_PATH = "/project/"
def get_config_path():
"""Return the path to the configuration file."""
home_dir = Path.home()
return home_dir / '.unreal_batch_processor_config.json'
def load_config():
"""Load configuration from file or create default if not exists."""
config = DEFAULT_CONFIG.copy()
config_path = get_config_path()
if config_path.exists():
try:
with open(config_path, 'r') as config_file:
loaded_config = json.load(config_file)
config.update(loaded_config)
logger.info(f"Configuration loaded from {config_path}")
except json.JSONDecodeError:
logger.error(f"Error parsing the configuration file at {config_path}. Using default values.")
except Exception as e:
logger.error(f"An error occurred while loading the configuration: {str(e)}. Using default values.")
else:
logger.warning(f"Configuration file not found at {config_path}. Using default values.")
# Create default config file
try:
with open(config_path, 'w') as config_file:
json.dump(DEFAULT_CONFIG, config_file, indent=4)
logger.info(f"Created default configuration file at {config_path}")
except Exception as e:
logger.error(f"Failed to create default configuration file: {str(e)}")
return config
# Load configuration
CONFIG = load_config()
# Use CONFIG values
MAX_RETRIES = CONFIG['MAX_RETRIES']
RETRY_DELAY = CONFIG['RETRY_DELAY']
MAX_WORKERS = CONFIG['MAX_WORKERS']
class ProgressDialog(QtWidgets.QDialog):
def __init__(self, parent=None, actor_character_mapping=None):
super().__init__(parent)
# Make dialog non-modal
self.setModal(False)
self.actor_character_mapping = actor_character_mapping or {} # Store the mapping
self.setWindowTitle("Processing")
self.setGeometry(300, 300, 1200, 500)
self.setStyleSheet("QDialog { background-color: #2b2b2b; color: #ffffff; }")
# Set window flags to allow movement and stay on top
self.setWindowFlags(
QtCore.Qt.Window |
QtCore.Qt.WindowMinimizeButtonHint |
QtCore.Qt.WindowMaximizeButtonHint |
QtCore.Qt.WindowCloseButtonHint |
QtCore.Qt.WindowStaysOnTopHint
)
layout = QtWidgets.QVBoxLayout(self)
# Batch progress bar
self.batch_progress_bar = QtWidgets.QProgressBar()
self.batch_progress_bar.setStyleSheet("""
QProgressBar {
border: 2px solid grey;
border-radius: 5px;
text-align: center;
}
QProgressBar::chunk {
background-color: #4CAF50;
width: 10px;
margin: 0.5px;
}
""")
layout.addWidget(QtWidgets.QLabel("Batch Progress:"))
layout.addWidget(self.batch_progress_bar)
self.status_label = QtWidgets.QLabel("Processing...")
layout.addWidget(self.status_label)
# Progress table with column sizing
self.progress_table = QtWidgets.QTableView()
self.progress_model = QtGui.QStandardItemModel()
self.progress_model.setHorizontalHeaderLabels([
"Folder",
"Character",
"Slate",
"Sequence",
"Actor",
"Take",
"Process Status",
"Export Status",
"Error"
])
# Set up the table view
self.progress_table.setModel(self.progress_model)
# Set column widths
self.progress_table.setColumnWidth(0, 250) # Folder
self.progress_table.setColumnWidth(1, 100) # Character
self.progress_table.setColumnWidth(2, 80) # Slate
self.progress_table.setColumnWidth(3, 100) # Sequence
self.progress_table.setColumnWidth(4, 100) # Actor
self.progress_table.setColumnWidth(5, 80) # Take
self.progress_table.setColumnWidth(6, 120) # Process Status
self.progress_table.setColumnWidth(7, 120) # Export Status
self.progress_table.setColumnWidth(8, 200) # Error
# Enable horizontal scrolling and stretch last section
self.progress_table.setHorizontalScrollMode(QtWidgets.QAbstractItemView.ScrollPerPixel)
self.progress_table.horizontalHeader().setStretchLastSection(True)
# Style the table
self.progress_table.setStyleSheet("""
QTableView {
background-color: #3b3b3b;
color: white;
gridline-color: #555555;
border: none;
}
QHeaderView::section {
background-color: #2b2b2b;
color: white;
padding: 5px;
border: 1px solid #555555;
}
QTableView::item {
padding: 5px;
}
QTableView::item:selected {
background-color: #4b4b4b;
}
""")
layout.addWidget(self.progress_table)
# Buttons and log area
# self.cancel_button = QtWidgets.QPushButton("Cancel")
# self.cancel_button.setStyleSheet("QPushButton { background-color: #f44336; color: white; }")
# layout.addWidget(self.cancel_button)
self.log_text = QtWidgets.QTextEdit()
self.log_text.setReadOnly(True)
self.log_text.setMinimumHeight(100)
layout.addWidget(self.log_text)
self.save_log_button = QtWidgets.QPushButton("Save Log")
self.save_log_button.clicked.connect(self.save_log)
layout.addWidget(self.save_log_button)
self.close_button = QtWidgets.QPushButton("Close")
self.close_button.setStyleSheet("""
QPushButton {
background-color: #3b3b3b;
color: white;
}
QPushButton:disabled {
background-color: #707070;
color: #a0a0a0;
}
""")
self.close_button.setEnabled(False) # Disabled initially
self.close_button.clicked.connect(self.close)
layout.addWidget(self.close_button)
self.cancelled = False
# self.cancel_button.clicked.connect(self.cancel)
def set_batch_progress(self, value):
self.batch_progress_bar.setValue(value)
def set_status(self, text):
self.status_label.setText(text)
def cancel(self):
# Comment out entire cancel method since it's not being used
pass
# self.cancelled = True
# self.status_label.setText("Cancelling...")
def add_item(self, folder_name, item_name):
"""Add item to progress dialog."""
row_position = self.progress_model.rowCount()
# Clean up folder name to show from Mocap forward
if "Mocap" in str(folder_name):
mocap_index = str(folder_name).find("Mocap")
folder_name = str(folder_name)[mocap_index:]
# Convert item_name to string and get just the filename if it's a path
if '/' in str(item_name):
item_name = str(item_name).split('/')[-1]
# Remove '_Performance' suffix if present
if item_name.endswith('_Performance'):
item_name = item_name[:-11]
# Parse the item name to extract components
name_components = AssetProcessor.extract_name_variable(item_name)
logger.info(f"Parsed components for {item_name}: {name_components}")
# Create items for each column
folder_item = QtGui.QStandardItem(str(folder_name))
if name_components:
# Standard format components
character_item = QtGui.QStandardItem(str(name_components.get('character', '')))
slate_item = QtGui.QStandardItem(str(name_components.get('slate', '')))
sequence_item = QtGui.QStandardItem(str(name_components.get('sequence', '')))
# Only display the actor associated with the character
character = name_components.get('character', '').lower()
actor_text = ''
# Use character mapping regardless of single/project/ actor format
if character in self.actor_character_mapping:
actor_text = self.actor_character_mapping[character].capitalize()
else:
# Fallback to first actor if no mapping found
actor_text = str(name_components.get('actor1' if name_components.get('is_dual_actor') or name_components.get('is_triple_actor') else 'actor', ''))
actor_item = QtGui.QStandardItem(actor_text)
# Just use take without subtake
take = str(name_components.get('take', '')).split('_')[0] # Remove subtake if present
take_item = QtGui.QStandardItem(take)
else:
# Fallback handling
parts = item_name.split('_')
character_item = QtGui.QStandardItem(parts[0] if len(parts) > 0 else '')
slate_item = QtGui.QStandardItem(parts[1] if len(parts) > 1 else '')
sequence_item = QtGui.QStandardItem(parts[2] if len(parts) > 2 else '')
actor_item = QtGui.QStandardItem(parts[3] if len(parts) > 3 else '')
take = parts[4] if len(parts) > 4 else ''
take_item = QtGui.QStandardItem(f"{take}")
logger.warning(f"Failed to parse name components for: {item_name}")
# Add the row with all columns
self.progress_model.insertRow(row_position)
self.progress_model.setItem(row_position, 0, folder_item)
self.progress_model.setItem(row_position, 1, character_item)
self.progress_model.setItem(row_position, 2, slate_item)
self.progress_model.setItem(row_position, 3, sequence_item)
self.progress_model.setItem(row_position, 4, actor_item)
self.progress_model.setItem(row_position, 5, take_item)
self.progress_model.setItem(row_position, 6, QtGui.QStandardItem("Waiting")) # Process Status
self.progress_model.setItem(row_position, 7, QtGui.QStandardItem("Waiting")) # Export Status
self.progress_model.setItem(row_position, 8, QtGui.QStandardItem("")) # Error
# Debug log for verification
logger.info(f"Added row {row_position}: {[self.progress_model.item(row_position, i).text() for i in range(9)]}")
def update_item_progress(self, index, status, error="", progress_type='processing'):
"""Update progress for a specific item."""
try:
if progress_type == 'processing':
status_item = self.progress_model.item(index, 6) # Process Status column
if status_item:
status_item.setText(status)
elif progress_type == 'exporting':
status_item = self.progress_model.item(index, 7) # Export Status column
if status_item:
status_item.setText(status)
if error:
error_item = self.progress_model.item(index, 8) # Error column
if error_item:
current_error = error_item.text()
new_error = f"{current_error}\n{error}" if current_error else error
error_item.setText(new_error)
self.update_overall_progress()
# Update the log text with detailed progress (avoid duplicates)
log_entry = f"Asset {index + 1}: {status}{' - ' + error if error else ''}"
current_log = self.log_text.toPlainText()
if log_entry not in current_log:
self.log_text.append(log_entry)
logger.info(log_entry)
except Exception as e:
logger.error(f"Error updating progress: {str(e)}")
def update_overall_progress(self):
"""Update the overall progress and enable close button when all items are processed."""
total_items = self.progress_model.rowCount()
completed_items = 0
# Count items that are either Complete or Failed in both processing and exporting
for i in range(total_items):
process_status = self.progress_model.item(i, 6).text()
export_status = self.progress_model.item(i, 7).text()
# Consider an item complete if:
# 1. Both statuses are either "Complete" or "Failed", or
# 2. Processing status is "Failed" (no need to wait for export in this case)
if (process_status == "Failed" or
(process_status in ["Complete", "Failed"] and
export_status in ["Complete", "Failed"])):
completed_items += 1
progress_percentage = (completed_items / total_items) * 100 if total_items > 0 else 0
self.batch_progress_bar.setValue(int(progress_percentage))
# Enable close button and update style when all items are processed
if completed_items == total_items:
self.close_button.setEnabled(True)
self.close_button.setStyleSheet("""
QPushButton {
background-color: #007ACC; /* Microsoft Visual Studio Code blue */
color: white;
}
QPushButton:hover {
background-color: #005999; /* Darker shade for hover */
}
""")
#self.cancel_button.setEnabled(False)
def save_log(self):
file_name, _ = QtWidgets.QFileDialog.getSaveFileName(
self, "Save Log File", "", "Text Files (*.txt);;All Files (*)"
)
if file_name:
with open(file_name, 'w') as f:
f.write(self.log_text.toPlainText())
logger.info(f"Log saved to {file_name}")
class MetaHumanHelper:
# Update to include both base paths
LEGACY_MHID_PATH = "/project/"
METAHUMAN_BASE_PATH = "/project/"
# Update LEGACY_ACTORS to prefer 'bev' over 'beverly'
LEGACY_ACTORS = {
'bev', # Barb character (primary)
'ralph', # Tiny character
'lewis', 'luis', # Tim character
'erwin', # Andre character
'mark' # Flike character
}
# Update MHID_MAPPING to handle Lewis/Luis correctly
MHID_MAPPING = {
# Legacy actors (using old path)
'bev': f'{LEGACY_MHID_PATH}/MHID_Bev.MHID_Bev',
'barb': f'{LEGACY_MHID_PATH}/MHID_Bev.MHID_Bev',
'ralph': f'{LEGACY_MHID_PATH}/MHID_Ralph.MHID_Ralph',
'tim': f'{LEGACY_MHID_PATH}/MHID_Luis.MHID_Luis', # Default Tim mapping to Luis
'tim_mark': f'{LEGACY_MHID_PATH}/MHID_Mark.MHID_Mark', # Special case for Tim played by Mark
'lewis': f'{LEGACY_MHID_PATH}/MHID_Luis.MHID_Luis', # Map Lewis to Luis MHID
'luis': f'{LEGACY_MHID_PATH}/MHID_Luis.MHID_Luis',
'erwin': f'{LEGACY_MHID_PATH}/MHID_Erwin.MHID_Erwin',
'mark': f'{LEGACY_MHID_PATH}/MHID_Mark.MHID_Mark',
# Character mappings
'tiny': f'{LEGACY_MHID_PATH}/MHID_Ralph.MHID_Ralph',
'tim_lewis': f'{LEGACY_MHID_PATH}/MHID_Luis.MHID_Luis', # Map Tim_Lewis to Luis
'tim_luis': f'{LEGACY_MHID_PATH}/MHID_Luis.MHID_Luis',
'andre': f'{LEGACY_MHID_PATH}/MHID_Erwin.MHID_Erwin',
'flike': f'{LEGACY_MHID_PATH}/MHID_Mark.MHID_Mark',
# New pipeline actors
'michael': f'{METAHUMAN_BASE_PATH}/project/.MHID_Michael',
'mike': f'{METAHUMAN_BASE_PATH}/project/.MHID_Mike',
'ricardo': f'{METAHUMAN_BASE_PATH}/project/.MHID_Ricardo',
'robert': f'{METAHUMAN_BASE_PATH}/project/.MHID_Robert',
'therese': f'{METAHUMAN_BASE_PATH}/project/.MHID_Therese',
'clara': f'{METAHUMAN_BASE_PATH}/project/.MHID_Clara',
# Character mappings
'skeezer': f'{METAHUMAN_BASE_PATH}/project/.MHID_Michael',
'doctor': f'{METAHUMAN_BASE_PATH}/project/.MHID_Ricardo',
'paroleofficer': f'{METAHUMAN_BASE_PATH}/project/.MHID_Robert',
'sonia': f'{METAHUMAN_BASE_PATH}/project/.MHID_Therese',
'shell': f'{METAHUMAN_BASE_PATH}/project/.MHID_Deborah',
# Update Shell/Deborah mappings (remove clara mapping)
'deborah': f'{METAHUMAN_BASE_PATH}/project/.MHID_Deborah',
'debbie': f'{METAHUMAN_BASE_PATH}/project/.MHID_Deborah',
# Keep Clara as fallback
'clara': f'{METAHUMAN_BASE_PATH}/project/.MHID_Clara',
# Update Shell/project/ mappings
'shell_deborah': f'{METAHUMAN_BASE_PATH}/project/.MHID_Deborah',
'shell_clara': f'{METAHUMAN_BASE_PATH}/project/.MHID_Clara',
'shell': f'{METAHUMAN_BASE_PATH}/project/.MHID_Deborah', # Default to Deborah
'deborah': f'{METAHUMAN_BASE_PATH}/project/.MHID_Deborah',
'debbie': f'{METAHUMAN_BASE_PATH}/project/.MHID_Deborah',
'clara': f'{METAHUMAN_BASE_PATH}/project/.MHID_Clara',
# Add Hurricane/Tori mappings
'hurricane': f'{METAHUMAN_BASE_PATH}/project/.MHID_Tori',
'tori': f'{METAHUMAN_BASE_PATH}/project/.MHID_Tori',
}
# Update SKELETAL_MESH_MAPPING to match MHID_MAPPING changes
SKELETAL_MESH_MAPPING = {
# Legacy actors (using old path)
'bev': f'{LEGACY_MHID_PATH}/SK_MHID_Bev.SK_MHID_Bev',
'barb': f'{LEGACY_MHID_PATH}/SK_MHID_Bev.SK_MHID_Bev',
'ralph': f'{LEGACY_MHID_PATH}/SK_MHID_Ralph.SK_MHID_Ralph',
'tim': f'{LEGACY_MHID_PATH}/SK_MHID_Luis.SK_MHID_Luis', # Default Tim mapping to Luis
'tim_mark': f'{LEGACY_MHID_PATH}/SK_MHID_Mark.SK_MHID_Mark', # Special case for Tim played by Mark
'lewis': f'{LEGACY_MHID_PATH}/SK_MHID_Luis.SK_MHID_Luis', # Map Lewis to Luis skeletal mesh
'luis': f'{LEGACY_MHID_PATH}/SK_MHID_Luis.SK_MHID_Luis',
'erwin': f'{LEGACY_MHID_PATH}/SK_MHID_Erwin.SK_MHID_Erwin',
'mark': f'{LEGACY_MHID_PATH}/SK_MHID_Mark.SK_MHID_Mark',
# Character mappings
'tiny': f'{LEGACY_MHID_PATH}/SK_MHID_Ralph.SK_MHID_Ralph',
'tim_lewis': f'{LEGACY_MHID_PATH}/SK_MHID_Luis.SK_MHID_Luis', # Map Tim_Lewis to Luis
'tim_luis': f'{LEGACY_MHID_PATH}/SK_MHID_Luis.SK_MHID_Luis',
'andre': f'{LEGACY_MHID_PATH}/SK_MHID_Erwin.SK_MHID_Erwin',
'flike': f'{LEGACY_MHID_PATH}/SK_MHID_Mark.SK_MHID_Mark',
# New pipeline actors
'michael': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Michael',
'mike': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Mike',
'ricardo': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Ricardo',
'robert': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Robert',
'therese': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Therese',
'clara': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Clara',
# Character mappings
'skeezer': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Michael',
'doctor': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Ricardo',
'paroleofficer': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Robert',
'sonia': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Therese',
'shell': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Deborah',
# Update Shell/Deborah mappings (remove clara mapping)
'deborah': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Deborah',
'debbie': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Deborah',
# Keep Clara as fallback
'clara': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Clara',
# Update Shell/project/ mappings
'shell_deborah': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Deborah',
'shell_clara': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Clara',
'shell': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Deborah', # Default to Deborah
'deborah': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Deborah',
'debbie': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Deborah',
'clara': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Clara',
# Add Hurricane/Tori mappings
'hurricane': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Tori',
'tori': f'{METAHUMAN_BASE_PATH}/project/.SK_MHID_Tori',
}
@staticmethod
def is_legacy_actor(actor_name: str) -> bool:
"""Check if the actor/character uses the legacy MHID path."""
return actor_name.lower() in MetaHumanHelper.LEGACY_ACTORS
@staticmethod
def find_matching_identity(character_name, actor_name=None):
"""Find matching MHID for given character name, handling special cases."""
character_lower = character_name.lower()
actor_lower = actor_name.lower() if actor_name else None
# Special case handling for Tim character
if character_lower == 'tim' and actor_lower == 'mark':
logger.info(f"Special case: Tim played by Mark - using Mark's MHID")
return MetaHumanHelper.MHID_MAPPING.get('tim_mark')
# Special case handling for Shell character
if character_lower == 'shell' and actor_lower:
if 'clara' in actor_lower:
logger.info(f"Special case: Shell played by Clara - using Clara's MHID")
return MetaHumanHelper.MHID_MAPPING.get('shell_clara')
elif any(name in actor_lower for name in ['deborah', 'debbie']):
logger.info(f"Special case: Shell played by Deborah - using Deborah's MHID")
return MetaHumanHelper.MHID_MAPPING.get('shell_deborah')
# Regular character mapping
mhid_path = MetaHumanHelper.MHID_MAPPING.get(character_lower)
if mhid_path:
if MetaHumanHelper.is_legacy_actor(character_lower):
logger.info(f"Using legacy MHID path for {character_name}")
else:
logger.info(f"Using new pipeline MHID path for {character_name}")
return mhid_path
logger.warning(f"No matching MHID found for character: {character_name}")
logger.warning(f"Available MHID mappings: {list(MetaHumanHelper.MHID_MAPPING.keys())}")
return None
@staticmethod
def process_shot(performance_asset, progress_callback, completion_callback, error_callback):
"""Process a MetaHuman performance shot using synchronous operations."""
if not performance_asset:
error_callback("Invalid performance asset provided")
return False
try:
performance_asset.set_blocking_processing(True)
progress_callback("Processing", 'processing')
start_pipeline_error = performance_asset.start_pipeline()
if start_pipeline_error == unreal.StartPipelineErrorType.NONE:
# Since we're using blocking processing, we can proceed directly
# The set_blocking_processing(True) call will wait until processing is complete
progress_callback("Complete", 'processing')
# Start the export process immediately after processing
return MetaHumanHelper.export_shot(performance_asset, progress_callback, completion_callback, error_callback)
else:
error_msg = f"Pipeline start error: {start_pipeline_error}"
error_callback(error_msg)
progress_callback("Failed", 'processing')
return False
except Exception as e:
error_callback(f"Processing error: {str(e)}")
progress_callback("Failed", 'processing')
return False
@staticmethod
def export_shot(performance_asset, progress_callback, completion_callback, error_callback):
"""Export a processed MetaHuman performance to animation sequence."""
try:
progress_callback("Starting Export", 'exporting')
# Extract name components for folder structure
asset_name = performance_asset.get_name()
# Remove any subtake from asset name
asset_name = '_'.join(asset_name.split('_')[0:-1]) if '_' in asset_name else asset_name
# Get the identity name and find corresponding skeletal mesh
identity = performance_asset.get_editor_property("identity")
identity_name = identity.get_name().lower() if identity else None
if identity_name and identity_name.startswith('mhid_'):
identity_name = identity_name[5:]
# Get the target skeletal mesh path
target_mesh_path = MetaHumanHelper.SKELETAL_MESH_MAPPING.get(identity_name)
if not target_mesh_path:
error_msg = f"No skeletal mesh mapping found for character: {identity_name}"
error_callback(error_msg)
progress_callback("Failed", 'exporting')
return False
# Load the skeletal mesh asset
target_skeletal_mesh = unreal.load_asset(target_mesh_path)
if not target_skeletal_mesh:
error_msg = f"Failed to load skeletal mesh at path: {target_mesh_path}"
error_callback(error_msg)
progress_callback("Failed", 'exporting')
return False
# Get the sequence-specific export path from metadata
sequence_path = unreal.EditorAssetLibrary.get_metadata_tag(
performance_asset,
"sequence_export_path"
)
if not sequence_path:
error_msg = "No sequence export path found in metadata"
error_callback(error_msg)
progress_callback("Failed", 'exporting')
return False
# Create export settings
export_settings = unreal.MetaHumanPerformanceExportAnimationSettings()
export_settings.set_editor_property("show_export_dialog", False)
export_settings.set_editor_property("package_path", sequence_path)
export_settings.set_editor_property("asset_name", f"AS_Face_{asset_name}") # Ensure AS_Face_ prefix
export_settings.set_editor_property("enable_head_movement", False)
export_settings.set_editor_property("export_range", unreal.PerformanceExportRange.PROCESSING_RANGE)
export_settings.set_editor_property("target_skeleton_or_skeletal_mesh", target_skeletal_mesh)
export_settings.set_editor_property("auto_save_anim_sequence", True)
# Export the animation sequence
progress_callback("Exporting Animation", 'exporting')
anim_sequence = unreal.MetaHumanPerformanceExportUtils.export_animation_sequence(
performance_asset,
export_settings
)
if anim_sequence:
progress_callback("Complete", 'exporting')
completion_callback()
return True
else:
error_callback("Animation sequence export failed")
progress_callback("Failed", 'exporting')
return False
except Exception as e:
error_callback(f"Export error: {str(e)}")
progress_callback("Failed", 'exporting')
return False
class BatchProcessor(QtCore.QObject):
progress_updated = QtCore.Signal(int, str, str, str)
processing_finished = QtCore.Signal()
error_occurred = QtCore.Signal(str)
def __init__(self):
super().__init__()
self.asset_processor = AssetProcessor()
self.helper = MetaHumanHelper()
self.all_capture_data = []
self.is_folder = True
self.current_index = 0
# Get editor asset subsystem
self.editor_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem)
def run_batch_process(self, selections, is_folder=True):
"""Initialize and start the batch processing"""
logger.info("Starting batch process...")
self.all_capture_data = selections if isinstance(selections, list) else []
self.is_folder = is_folder
self.current_index = 0
if not self.all_capture_data:
logger.error(f"Invalid selections type: {type(selections)}")
return
logger.info(f"Processing {len(self.all_capture_data)} assets")
# Process first asset
QtCore.QTimer.singleShot(0, self._process_next_asset)
def _process_next_asset(self):
"""Process next asset in queue"""
try:
if self.current_index >= len(self.all_capture_data):
self.processing_finished.emit()
return
capture_data_asset = self.all_capture_data[self.current_index]
self.progress_updated.emit(self.current_index, "Processing", "", 'processing')
# Create performance asset
performance_asset = self.asset_processor.create_performance_asset(
capture_data_asset.package_name,
"/project/-Data/"
)
if not performance_asset:
self.progress_updated.emit(self.current_index, "Failed", "Failed to create performance asset", 'processing')
self.current_index += 1
QtCore.QTimer.singleShot(0, self._process_next_asset)
return
# Process the shot
success = self.helper.process_shot(
performance_asset,
lambda status, progress_type='processing':
self.progress_updated.emit(self.current_index, status, "", progress_type),
lambda: self._on_shot_complete(self.current_index),
lambda error: self._on_shot_error(self.current_index, error)
)
if not success:
self.progress_updated.emit(self.current_index, "Failed", "Failed to process shot", 'processing')
self.current_index += 1
QtCore.QTimer.singleShot(0, self._process_next_asset)
except Exception as e:
logger.error(f"Error processing asset: {str(e)}")
self.progress_updated.emit(self.current_index, "Failed", str(e), 'processing')
self.current_index += 1
QtCore.QTimer.singleShot(0, self._process_next_asset)
def _on_shot_complete(self, index):
"""Handle shot completion"""
self.progress_updated.emit(index, "Complete", "", 'processing')
self.current_index += 1
QtCore.QTimer.singleShot(0, self._process_next_asset)
def _on_shot_error(self, index, error):
"""Handle shot error"""
self.progress_updated.emit(index, "Failed", error, 'processing')
self.current_index += 1
QtCore.QTimer.singleShot(0, self._process_next_asset)
class AssetProcessor:
def __init__(self):
self.asset_registry = unreal.AssetRegistryHelpers.get_asset_registry()
self.asset_tools = unreal.AssetToolsHelpers.get_asset_tools()
# Update the name patterns to include all actor formats
self.name_patterns = [
# Quad actor pattern (4 actors)
r"^(?:(\w+)_)?(S\d+)_(\d+)_(\w+)_(\w+)_(\w+)_(\w+)_(\d+)(?:_\d+)?$",
# Triple actor pattern (3 actors)
r"^(?:(\w+)_)?(S\d+)_(\d+)_(\w+)_(\w+)_(\w+)_(\d+)(?:_\d+)?$",
# Dual actor pattern (2 actors)
r"^(?:(\w+)_)?(S\d+)_(\d+)_(\w+)_(\w+)_(\d+)(?:_\d+)?$",
# Single actor pattern (1 actor)
r"^(?:(\w+)_)?(S\d+)_(\d+)_(\w+)_(\d+)(?:_\d+)?$",
# TT format pattern
r"^TT-(\w+)-(\d+)_(\d+)$"
]
# Updated actor to character mapping
self.actor_character_mapping = {
# Legacy actors to characters
'bev': 'barb', # Primary mapping for Barb
'beverly': 'barb', # Alternative mapping
'ralph': 'tiny',
'lewis': 'tim',
'luis': 'tim',
'erwin': 'andre', # Erwin actor maps to Andre character
'mark': 'flike',
'robert': 'paroleofficer',
'robert': 'parole',
# Reverse mappings (character to actor)
'barb': 'bev', # Maps to bev (not beverly)
'tiny': 'ralph',
'tim': 'lewis',
'andre': 'erwin', # Andre character maps to Erwin actor
'flike': 'mark',
'parole': 'robert', # Added: parole character maps to robert actor
'paroleofficer': 'robert', # Both parole and paroleofficer map to robert
# New pipeline mappings remain unchanged
'michael': 'skeezer',
'mike': 'skeezer',
'ricardo': 'doctor',
'therese': 'sonia',
'clara': 'shell',
# New pipeline reverse mappings remain unchanged
'skeezer': 'michael',
'doctor': 'ricardo',
'sonia': 'therese',
'shell': 'clara',
# Update Shell/Deborah mappings (remove clara mapping)
'deborah': 'shell',
'debbie': 'shell',
# Keep Clara as fallback
'clara': 'shell',
# Add Hurricane/Tori mapping
'hurricane': 'Tori',
'tori': 'Tori'
}
def get_available_folders(self):
logger.info("Fetching available folders...")
full_paths = self.asset_registry.get_sub_paths(MOCAP_BASE_PATH, recurse=True)
# Filter and clean paths to only show from "Mocap" forward
cleaned_paths = []
for path in full_paths:
if "Mocap" in path:
# Find the index of "Mocap" in the path
mocap_index = path.find("Mocap")
# Get everything from "Mocap" forward
cleaned_path = path[mocap_index:]
if self.folder_has_capture_data(path): # Still check using full path
cleaned_paths.append(cleaned_path)
logger.info(f"Found {len(cleaned_paths)} folders with capture data")
return cleaned_paths
def folder_has_capture_data(self, folder):
search_filter = unreal.ARFilter(
package_paths=[folder],
class_names=["FootageCaptureData"],
recursive_paths=True
)
return bool(self.asset_registry.get_assets(search_filter))
def get_capture_data_assets(self, folder):
"""Get all capture data assets from a folder."""
logger.info(f"Searching for assets in folder: {folder}")
# Ensure the folder path is properly formatted
folder_path = str(folder)
# Remove base path prefix if it exists
if folder_path.startswith(f'{MOCAP_BASE_PATH}/'):
folder_path = folder_path[len(f'{MOCAP_BASE_PATH}/'):]
# Add the proper base path prefix
folder_path = f"{MOCAP_BASE_PATH}/{folder_path.strip('/')}"
logger.info(f"Searching with formatted path: {folder_path}")
search_filter = unreal.ARFilter(
package_paths=[folder_path],
class_names=["FootageCaptureData"],
recursive_paths=True, # Enable recursive search
recursive_classes=True
)
try:
assets = self.asset_registry.get_assets(search_filter)
logger.info(f"Found {len(assets)} assets in {folder_path}")
# Log each found asset for debugging
for asset in assets:
logger.info(f"Found asset: {asset.package_name}")
if not assets:
# Try alternative path format
alt_folder_path = folder_path.replace(MOCAP_BASE_PATH, '/Game/')
logger.info(f"Trying alternative path: {alt_folder_path}")
search_filter.package_paths = [alt_folder_path]
assets = self.asset_registry.get_assets(search_filter)
logger.info(f"Found {len(assets)} assets with alternative path")
return assets
except Exception as e:
logger.error(f"Error getting assets: {str(e)}")
return []
def get_all_capture_data_assets(self):
"""Get all capture data assets in the project."""
logger.info("Fetching all capture data assets...")
# Create filter for FootageCaptureData assets
asset_filter = unreal.ARFilter(
class_names=["FootageCaptureData"],
package_paths=[MOCAP_BASE_PATH],
recursive_paths=True,
recursive_classes=True
)
# Get assets using the filter
assets = self.asset_registry.get_assets(asset_filter)
# Clean up asset display names and paths
cleaned_assets = []
for asset in assets:
if asset:
# Get the full path
full_path = str(asset.package_path)
# Find the index of "Mocap" in the path
if "Mocap" in full_path:
mocap_index = full_path.find("Mocap")
# Set a cleaned display path from "Mocap" forward
display_path = full_path[mocap_index:]
# Create a wrapper object that maintains the original asset but shows cleaned path
class AssetWrapper:
def __init__(self, original_asset, display_path):
self._asset = original_asset
self.display_path = display_path
def __getattr__(self, attr):
return getattr(self._asset, attr)
def get_display_path(self):
return self.display_path
wrapped_asset = AssetWrapper(asset, display_path)
cleaned_assets.append(wrapped_asset)
logger.info(f"Found {len(cleaned_assets)} capture data assets")
return cleaned_assets
@staticmethod
def extract_name_variable(asset_name: str) -> dict:
"""Extract variables from asset name with support for all naming patterns."""
# Clean up the name
if asset_name.endswith('_Performance'):
asset_name = asset_name[:-11]
asset_name = asset_name.rstrip('_')
logger.info(f"Extracting name components from: {asset_name}")
# Define patterns for all formats
patterns = [
# Quad actor pattern (4 actors)
# Example: Barb_S063_0290_Erwin_Beverly_Clara_Mike_010_10
r'^(?P<character>[^_]+)_S(?P<slate>\d+)_(?P<sequence>\d+)_(?P<actor1>[^_]+)_(?P<actor2>[^_]+)_(?P<actor3>[^_]+)_(?P<actor4>[^_]+)_(?P<take>\d+)(?:_(?P<subtake>\d+))?$',
# Triple actor pattern (3 actors)
# Example: Barb_S063_0290_Erwin_Beverly_Clara_010_10
r'^(?P<character>[^_]+)_S(?P<slate>\d+)_(?P<sequence>\d+)_(?P<actor1>[^_]+)_(?P<actor2>[^_]+)_(?P<actor3>[^_]+)_(?P<take>\d+)(?:_(?P<subtake>\d+))?$',
# Dual actor pattern (2 actors)
# Example: Barb_S063_0290_Erwin_Beverly_010_10
r'^(?P<character>[^_]+)_S(?P<slate>\d+)_(?P<sequence>\d+)_(?P<actor1>[^_]+)_(?P<actor2>[^_]+)_(?P<take>\d+)(?:_(?P<subtake>\d+))?$',
# Single actor pattern (1 actor)
# Example: Barb_S063_0290_Erwin_010_10
r'^(?P<character>[^_]+)_S(?P<slate>\d+)_(?P<sequence>\d+)_(?P<actor1>[^_]+)_(?P<take>\d+)(?:_(?P<subtake>\d+))?$'
]
# Try each pattern
for i, pattern in enumerate(patterns):
logger.info(f"Trying pattern {i + 1}: {pattern}")
match = re.match(pattern, asset_name)
if match:
components = match.groupdict()
logger.info(f"Pattern {i + 1} matched! Raw components: {components}")
# Fix the erwin/andre naming issue
# If 'erwin' is in the character spot, replace it with 'andre'
if components.get('character', '').lower() == 'erwin':
components['character'] = 'andre'
logger.info("Corrected character 'erwin' to 'andre'")
# Set actor count flags
components['is_quad_actor'] = bool('actor4' in components and components['actor4'])
components['is_triple_actor'] = bool('actor3' in components and components['actor3'] and not components.get('actor4'))
components['is_dual_actor'] = bool('actor2' in components and components['actor2'] and not components.get('actor3'))
components['is_single_actor'] = bool('actor1' in components and not components.get('actor2'))
logger.info(f"Actor format flags - Quad: {components['is_quad_actor']}, "
f"Triple: {components['is_triple_actor']}, "
f"Dual: {components['is_dual_actor']}, "
f"Single: {components['is_single_actor']}")
# Store all actor names in a list for easy access
components['all_actors'] = []
if components.get('actor4'):
components['all_actors'] = [
components['actor1'],
components['actor2'],
components['actor3'],
components['actor4']
]
logger.info(f"Quad actor format detected: {components['all_actors']}")
elif components.get('actor3'):
components['all_actors'] = [
components['actor1'],
components['actor2'],
components['actor3']
]
logger.info(f"Triple actor format detected: {components['all_actors']}")
elif components.get('actor2'):
components['all_actors'] = [
components['actor1'],
components['actor2']
]
logger.info(f"Dual actor format detected: {components['all_actors']}")
else:
components['all_actors'] = [components['actor1']]
logger.info(f"Single actor format detected: {components['all_actors']}")
# Pad numbers to ensure consistent formatting
if components.get('slate'):
components['slate'] = components['slate'].zfill(4)
if components.get('sequence'):
components['sequence'] = components['sequence'].zfill(4)
if components.get('take'):
components['take'] = components['take'].zfill(3)
logger.info(f"Final processed components: {components}")
return components
# If no pattern matches, log the failure and details about the name
logger.warning(f"No pattern matched for asset name: {asset_name}")
logger.debug(f"Name parts: {asset_name.split('_')}")
return None
def get_available_identities(self):
logger.info("Fetching available identities...")
search_filter = unreal.ARFilter(
package_paths=["/project/"],
class_names=["MetaHumanIdentity"],
recursive_paths=True
)
assets = self.asset_registry.get_assets(search_filter)
# Convert Name objects to strings
return {str(asset.asset_name): str(asset.package_name) for asset in assets}
def find_matching_identity(self, capture_data_name):
"""
Find matching identity based on character name, handling actor-character relationships.
"""
available_identities = self.get_available_identities()
logger.info(f"Available identities: {available_identities}")
name_components = self.extract_name_variable(capture_data_name)
if not name_components:
logger.error(f"Could not parse capture data name: {capture_data_name}")
return None
# Get the character name (this is who we want to process)
character = name_components.get('character', '').lower().strip()
# Find the actor name for this character
actor_name = self.actor_character_mapping.get(character, character)
logger.info(f"Mapped character '{character}' to actor '{actor_name}'")
# Look for matching identity using actor name
expected_mhid = f"MHID_{actor_name.capitalize()}"
logger.info(f"Looking for MHID match: {expected_mhid}")
# Look for matching identity
for identity_name, identity_path in available_identities.items():
identity_name = str(identity_name).lower()
if identity_name.startswith("mhid_"):
identity_actor = identity_name[5:].lower().strip()
logger.info(f"Comparing {actor_name} with {identity_actor}")
if actor_name == identity_actor:
logger.info(f"Found matching identity: {identity_path}")
return identity_path
logger.warning(f"No matching identity found for character: {character} (Actor: {actor_name})")
logger.warning(f"Expected MHID name would be: {expected_mhid}")
return None
# Add this at the class level of AssetProcessor
SEQUENCE_MAPPING = {
# Format: 'shot_number': ('parent_sequence_folder', 'shot_code')
'0010': ('0010_Prologue', 'PRO'),
'0020': ('0020_The_Effigy', 'EFF'),
'0030': ('0030_Parole_Officer_Visit', 'POV'),
'0040': ('0040_Andre_Work', 'ANW'),
'0050': ('0050_Barb_Shell_Pool_Time', 'BSP'),
'0060': ('0060_Barb_Shell_Kitchen_Toast', 'BSK'),
'0070': ('0070_Walking_To_Flike', 'WTF'),
'0080': ('0080_Meeting_Flike', 'MEF'),
'0090': ('0090_Speaking_To_Tim', 'STT'),
'0100': ('0100_Back_Alley_Walk', 'BAW'),
'0110': ('0110_SoniaX_Ad', 'SXA'),
'0120': ('0120_Andre_Bike_Ride', 'ABR'),
'0130': ('0130_Flike_Vets', 'FLV'),
'0140': ('0140_Barb_Shell_Meet_Tiny', 'BST'),
'0150': ('0150_Andre_Eating', 'ANE'),
'0160': ('0160_Hurricane_Twerking', 'HUT'),
'0170': ('0170_Pray_Leprechaun', 'PRL'),
'0180': ('0180_Andre_Thinking', 'ANT'),
'0190': ('0190_Andre_Refuses_Job', 'ARJ'),
'0200': ('0200_Doctor_Visit', 'DRV'),
'0210': ('0210_Flikes_Tap_Dance', 'FTP'),
'0220': ('0220_Whore_House_Inspection', 'WHI'),
'0230': ('0230_Andre_Stargazing', 'AST'),
'0240': ('0240_Molotov_Walk', 'MOW'),
'0250': ('0250_Molotov_Cocktail', 'MOC'),
'0260': ('0260_Picking_Up_Tim', 'PUT'),
'0270': ('0270_Andre_Listens_Heart', 'ALH'),
'0280': ('0280_Andre_Takes_Job', 'ATJ'),
'0290': ('0290_Barb_Shell_Meet_Andre', 'BMA'),
'0300': ('0300_Andre_Self_Reflects', 'ASR'),
'0310': ('0310_Basketball_Match', 'BBM'),
'0320': ('0320_Tims_House', 'TMH'),
'0330': ('0330_Andre_Runs_Home', 'ARH'),
'0340': ('0340_Barb_Shell_Celebrate', 'BSC'),
'0350': ('0350_Flike_Raps', 'FLR'),
'0360': ('0360_Sonia_Limo_Ride', 'SLR'),
'0370': ('0370_Andre_Sonia', 'ASO'),
'0380': ('0380_Flike_Molotov_Cocktail', 'FMC'),
'0390': ('0390_The_Fairy_Costume', 'TFC'),
'0400': ('0400_Barb_Shell_Dance', 'BSD'),
'0410': ('0410_Andres_Death', 'ADE'),
'0420': ('0420_Flikes_Fire_Dance', 'FFD'),
'0430': ('0430_Andres_Burial', 'ABU'),
'0440': ('0440_Andre_at_Church', 'AAC')
}
def get_sequence_folder(self, sequence_number: str) -> tuple:
"""
Get the parent sequence folder and shot code for a given sequence number.
Returns tuple of (parent_folder, shot_code)
"""
# Find the parent sequence number (first 3 digits + 0)
parent_seq = sequence_number[:3] + '0'
if parent_seq in self.SEQUENCE_MAPPING:
parent_folder, shot_code = self.SEQUENCE_MAPPING[parent_seq]
return parent_folder, shot_code
else:
logger.warning(f"No mapping found for sequence {sequence_number}, using default structure")
return (f"{parent_seq}_Unknown", "UNK")
def create_performance_asset(self, path_to_capture_data: str, save_performance_location: str) -> unreal.MetaHumanPerformance:
"""Create performance asset with new folder structure."""
try:
capture_data_asset = unreal.load_asset(path_to_capture_data)
if not capture_data_asset:
raise ValueError(f"Failed to load capture data asset at {path_to_capture_data}")
capture_data_name = capture_data_asset.get_name()
name_components = self.extract_name_variable(capture_data_name)
if not name_components:
raise ValueError(f"Could not parse name components from {capture_data_name}")
logger.info(f"Creating performance asset with components: {name_components}")
character = name_components.get('character', 'Unknown').lower()
sequence = name_components.get('sequence', '0000')
take = name_components.get('take', '000')
# Get the mapped actor for this character
mapped_actor = self.actor_character_mapping.get(character, character)
logger.info(f"Character '{character}' is mapped to actor '{mapped_actor}'")
# Get sequence folder structure
sequence_padded = sequence.zfill(4)
parent_folder, shot_code = self.get_sequence_folder(sequence_padded)
# Build the new folder paths
base_path = f"/project/{parent_folder}/{sequence_padded}_{shot_code}_MAIN"
mha_path = f"{base_path}/MHA-DATA/{take}/{character}"
performance_path = f"{mha_path}/MHP"
# Create the performance asset name using only the mapped actor
performance_asset_name = f"Face_{character}_S{name_components['slate']}_{sequence}_{mapped_actor}_{take}_Performance"
logger.info(f"Creating performance asset: {performance_asset_name}")
# Create the performance asset
performance_asset = self.asset_tools.create_asset(
asset_name=performance_asset_name,
package_path=performance_path,
asset_class=unreal.MetaHumanPerformance,
factory=unreal.MetaHumanPerformanceFactoryNew()
)
if not performance_asset:
raise ValueError(f"Failed to create performance asset {performance_asset_name}")
# Set properties and metadata
identity_asset = self._get_identity_asset(name_components)
performance_asset.set_editor_property("identity", identity_asset)
performance_asset.set_editor_property("footage_capture_data", capture_data_asset)
# Store export paths in metadata - Single character folder
export_path = f"{mha_path}"
unreal.EditorAssetLibrary.set_metadata_tag(
performance_asset,
"sequence_export_path",
export_path
)
# Update the animation sequence name format using only the mapped actor
anim_sequence_name = f"AS_Face_{character}_S{name_components['slate']}_{sequence}_{mapped_actor}_{take}"
# Store the animation sequence name in metadata
unreal.EditorAssetLibrary.set_metadata_tag(
performance_asset,
"animation_sequence_name",
anim_sequence_name
)
# Save and return the asset
unreal.EditorAssetLibrary.save_loaded_asset(performance_asset)
return performance_asset
except Exception as e:
logger.error(f"Error creating performance asset: {str(e)}")
raise
def _get_identity_asset(self, name_components):
"""Get the appropriate identity asset based on actor information."""
try:
# Debug logging for incoming components
logger.info(f"Starting _get_identity_asset with components: {name_components}")
if not name_components:
raise ValueError("No name components provided")
# Get the character name first
character = name_components.get('character', '')
if not character:
raise ValueError("No character found in name components")
character = character.lower()
# Determine which actor we should use based on the format
actor_name = None
if name_components.get('is_quad_actor'):
logger.info("Quad actor format detected")
actor_name = name_components.get('actor1', '').lower()
logger.info(f"Using first actor: {actor_name}")
elif name_components.get('is_triple_actor'):
logger.info("Triple actor format detected")
actor_name = name_components.get('actor1', '').lower()
logger.info(f"Using first actor: {actor_name}")
elif name_components.get('is_dual_actor'):
logger.info("Dual actor format detected")
actor_name = name_components.get('actor1', '').lower()
logger.info(f"Using first actor: {actor_name}")
else:
logger.info("Single actor format detected")
actor_name = name_components.get('actor', '').lower()
if not actor_name:
actor_name = name_components.get('actor1', '').lower()
logger.info(f"Using actor: {actor_name}")
if not actor_name:
raise ValueError(f"No actor name found in components: {name_components}")
logger.info(f"Processing character: {character}, actor: {actor_name}")
# First try to get the MHID with both character and actor information
identity_path = MetaHumanHelper.find_matching_identity(character, actor_name)
if not identity_path:
error_msg = f"No MHID found for {actor_name} ({character} character)"
logger.error(error_msg)
raise ValueError(error_msg)
logger.info(f"Using MHID path: {identity_path}")
identity_asset = unreal.load_asset(identity_path)
if not identity_asset:
error_msg = f"Failed to load MHID at path: {identity_path}"
logger.error(error_msg)
raise ValueError(error_msg)
return identity_asset
except Exception as e:
logger.error(f"Error in _get_identity_asset: {str(e)}")
logger.error(f"Name components: {name_components}")
raise
class UnifiedSelectionDialog(QtWidgets.QDialog):
"""Dialog for selecting either folders or individual capture data assets."""
def __init__(self, available_folders, capture_data_assets, parent=None):
super().__init__(parent)
self.setWindowTitle("Select Items for Batch Processing")
self.setGeometry(300, 300, 500, 400)
self.setStyleSheet("""
QDialog {
background-color: #2b2b2b;
color: #ffffff;
}
QTreeWidget {
background-color: #3b3b3b;
color: #ffffff;
border: 1px solid #555555;
}
QTreeWidget::item {
padding: 4px;
}
QTreeWidget::item:hover {
background-color: #4b4b4b;
}
QTreeWidget::item:selected {
background-color: #555555;
}
QRadioButton {
color: white;
padding: 5px;
}
QRadioButton::indicator {
width: 13px;
height: 13px;
}
""")
layout = QtWidgets.QVBoxLayout(self)
# Add radio buttons for selection type
self.radio_layout = QtWidgets.QHBoxLayout()
self.folder_radio = QtWidgets.QRadioButton("Folders")
self.asset_radio = QtWidgets.QRadioButton("Capture Data Assets")
self.folder_radio.setChecked(True)
self.radio_layout.addWidget(self.folder_radio)
self.radio_layout.addWidget(self.asset_radio)
layout.addLayout(self.radio_layout)
# Connect radio buttons
self.folder_radio.toggled.connect(self.switch_view)
self.asset_radio.toggled.connect(self.switch_view)
# Add search functionality
search_layout = QtWidgets.QHBoxLayout()
search_label = QtWidgets.QLabel("Search:")
search_label.setStyleSheet("color: white;")
self.search_input = QtWidgets.QLineEdit()
self.search_input.setStyleSheet("""
QLineEdit {
background-color: #3b3b3b;
color: white;
border: 1px solid #555555;
padding: 4px;
}
""")
self.search_input.textChanged.connect(self.filter_tree)
search_layout.addWidget(search_label)
search_layout.addWidget(self.search_input)
layout.addLayout(search_layout)
# Create tree widget
self.tree = QtWidgets.QTreeWidget()
self.tree.setHeaderLabel("Available Items")
self.tree.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection) # Disable selection highlighting
layout.addWidget(self.tree)
# Add "Select All" checkbox
self.select_all_checkbox = QtWidgets.QCheckBox("Select All")
self.select_all_checkbox.setStyleSheet("color: white;")
self.select_all_checkbox.stateChanged.connect(self.toggle_all_items)
layout.insertWidget(2, self.select_all_checkbox) # Insert after search box
# Store data
self.available_folders = available_folders
self.capture_data_assets = capture_data_assets
# Populate initial view (folders)
self.populate_folders()
# Add buttons
button_layout = QtWidgets.QHBoxLayout()
self.ok_button = QtWidgets.QPushButton("OK")
self.cancel_button = QtWidgets.QPushButton("Cancel")
for btn in [self.ok_button, self.cancel_button]:
btn.setStyleSheet("""
QPushButton {
background-color: #3b3b3b;
color: white;
border: 1px solid #555555;
padding: 5px 15px;
}
QPushButton:hover {
background-color: #4b4b4b;
}
""")
button_layout.addWidget(self.ok_button)
button_layout.addWidget(self.cancel_button)
layout.addLayout(button_layout)
# Connect buttons
self.ok_button.clicked.connect(self.accept)
self.cancel_button.clicked.connect(self.reject)
# Modify tree widget selection mode based on radio button state
self.folder_radio.toggled.connect(self.update_selection_mode)
self.asset_radio.toggled.connect(self.update_selection_mode)
# Set initial selection mode
self.update_selection_mode()
def switch_view(self):
"""Switch between folder and asset view based on radio selection."""
self.tree.clear()
if self.folder_radio.isChecked():
self.populate_folders()
else:
self.populate_assets()
def populate_folders(self):
"""Populate the tree with folder hierarchy."""
tree_dict = {}
for folder_path in self.available_folders:
# Clean path to start from Mocap
clean_path = folder_path
if "Mocap" in clean_path:
mocap_index = clean_path.find("Mocap")
clean_path = clean_path[mocap_index:]
parts = clean_path.strip('/').split('/')
current_dict = tree_dict
current_path = []
for part in parts:
current_path.append(part)
if '/'.join(current_path) not in current_dict:
current_dict['/'.join(current_path)] = {}
current_dict = current_dict['/'.join(current_path)]
self._create_tree_items(tree_dict, self.tree, is_folder=True)
def populate_assets(self):
"""Populate the tree with capture data assets."""
tree_dict = {}
for asset in self.capture_data_assets:
if not asset:
continue
path = str(asset.package_path)
# Clean path to start from Mocap
if "Mocap" in path:
mocap_index = path.find("Mocap")
path = path[mocap_index:]
parts = path.strip('/').split('/')
current_dict = tree_dict
current_path = []
for part in parts:
current_path.append(part)
path_key = '/'.join(current_path)
if path_key not in current_dict:
current_dict[path_key] = {'__assets__': []}
current_dict = current_dict[path_key]
current_dict['__assets__'].append(asset)
self._create_tree_items(tree_dict, self.tree, is_folder=False)
def _create_tree_items(self, tree_dict, parent_item, is_folder):
"""Recursively create tree items from dictionary with checkboxes."""
sorted_items = []
for path, content in tree_dict.items():
if path == '__assets__':
sorted_assets = sorted(content, key=lambda x: str(x.asset_name).lower())
for asset in sorted_assets:
display_name = str(asset.asset_name)
if "Mocap" in display_name:
mocap_index = display_name.find("Mocap")
display_name = display_name[mocap_index:]
sorted_items.append(('asset', display_name, asset))
else:
display_name = path.split('/')[-1]
sorted_items.append(('folder', display_name, (path, content)))
sorted_items.sort(key=lambda x: x[1].lower())
for item_type, display_name, data in sorted_items:
if item_type == 'asset':
item = QtWidgets.QTreeWidgetItem([display_name])
item.setData(0, QtCore.Qt.UserRole, data)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(0, QtCore.Qt.Unchecked)
else:
path, content = data
item = QtWidgets.QTreeWidgetItem([display_name])
if is_folder:
item.setData(0, QtCore.Qt.UserRole, path)
item.setFlags(item.flags() | QtCore.Qt.ItemIsUserCheckable)
item.setCheckState(0, QtCore.Qt.Unchecked)
if isinstance(parent_item, QtWidgets.QTreeWidget):
parent_item.addTopLevelItem(item)
else:
parent_item.addChild(item)
if item_type == 'folder' and content:
self._create_tree_items(content, item, is_folder)
def toggle_all_items(self, state):
"""Toggle all checkboxes based on Select All state."""
def set_check_state(item):
if item.flags() & QtCore.Qt.ItemIsUserCheckable:
item.setCheckState(0, state)
for i in range(item.childCount()):
set_check_state(item.child(i))
for i in range(self.tree.topLevelItemCount()):
set_check_state(self.tree.topLevelItem(i))
def get_selected_items(self):
"""Return checked folders or assets based on current mode."""
def get_checked_items(item):
checked_items = []
if item.flags() & QtCore.Qt.ItemIsUserCheckable and item.checkState(0) == QtCore.Qt.Checked:
data = item.data(0, QtCore.Qt.UserRole)
if data:
checked_items.append(data)
for i in range(item.childCount()):
checked_items.extend(get_checked_items(item.child(i)))
return checked_items
checked_items = []
for i in range(self.tree.topLevelItemCount()):
checked_items.extend(get_checked_items(self.tree.topLevelItem(i)))
if not checked_items:
return None
return {
'type': 'folder' if self.folder_radio.isChecked() else 'asset',
'data': checked_items
}
def update_selection_mode(self):
"""Update tree selection mode is no longer needed with checkboxes"""
pass # Remove previous selection mode logic
def filter_tree(self, filter_text):
"""Filter the tree based on search text."""
def show_all_items(item):
"""Show all items in the tree."""
item.setHidden(False)
for i in range(item.childCount()):
show_all_items(item.child(i))
def filter_item(item, text):
"""Filter items based on search text."""
if not text: # If search text is empty, show everything
show_all_items(item)
return True
if text.lower() in item.text(0).lower():
item.setHidden(False)
parent = item.parent()
while parent:
parent.setHidden(False)
parent = parent.parent()
return True
child_match = False
for i in range(item.childCount()):
if filter_item(item.child(i), text):
child_match = True
item.setHidden(not child_match)
return child_match
# Apply filtering to all top-level items
for i in range(self.tree.topLevelItemCount()):
filter_item(self.tree.topLevelItem(i), filter_text)
class BatchProcessorUI(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.processor = BatchProcessor()
self.progress_dialog = None
self.show_selection_dialog()
def show_selection_dialog(self):
"""Show unified selection dialog immediately."""
try:
available_folders = self.processor.asset_processor.get_available_folders()
capture_data_assets = self.processor.asset_processor.get_all_capture_data_assets()
if not available_folders and not capture_data_assets:
QtWidgets.QMessageBox.warning(self, "No Items", "No folders or capture data assets were found.")
return
dialog = UnifiedSelectionDialog(available_folders, capture_data_assets, self)
if dialog.exec_():
selected_items = dialog.get_selected_items()
if selected_items:
self.confirm_and_start_processing(selected_items['data'], is_folder=(selected_items['type'] == 'folder'))
else:
QtWidgets.QMessageBox.warning(self, "No Selection", "Please select items to process.")
except Exception as e:
logger.error(f"Error in item selection: {str(e)}")
QtWidgets.QMessageBox.critical(self, "Error", f"An error occurred while selecting items: {str(e)}")
def confirm_and_start_processing(self, selections, is_folder):
selection_type = "folders" if is_folder else "capture data assets"
reply = QtWidgets.QMessageBox.question(self, 'Start Batch Process',
f"Are you sure you want to start batch processing for {len(selections)} {selection_type}?",
QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.Yes:
self.start_processing(selections, is_folder)
def start_processing(self, selections, is_folder):
# Create new progress dialog for each batch with the actor mapping
self.progress_dialog = ProgressDialog(
self,
actor_character_mapping=self.processor.asset_processor.actor_character_mapping
)
self.progress_dialog.show()
# Clear any existing connections
try:
self.processor.progress_updated.disconnect()
self.processor.processing_finished.disconnect()
self.processor.error_occurred.disconnect()
except:
pass
# Connect signals
self.processor.progress_updated.connect(self.update_progress)
self.processor.processing_finished.connect(self.on_processing_finished)
self.processor.error_occurred.connect(self.show_error_dialog)
# Prepare the progress dialog items
total_assets = []
if is_folder:
logger.info(f"Processing folders: {selections}")
for folder in selections:
logger.info(f"Getting assets from folder: {folder}")
try:
# Ensure we're using the full game path
folder_path = str(folder)
if "Mocap" in folder_path:
mocap_index = folder_path.find("Mocap")
folder_path = "/project/" + folder_path[mocap_index:]
logger.info(f"Searching in path: {folder_path}")
# Get all assets in the folder
assets = unreal.EditorAssetLibrary.list_assets(folder_path, recursive=True)
logger.info(f"Found {len(assets)} total assets in folder")
# Filter for FootageCaptureData assets
for asset_path in assets:
try:
asset = unreal.load_asset(asset_path)
if asset and asset.get_class().get_name() == "FootageCaptureData":
# Create a wrapper object that matches the expected interface
class AssetWrapper:
def __init__(self, asset, path):
self.asset = asset
self.package_name = path
self.asset_name = asset.get_name()
self.package_path = '/'.join(path.split('/')[:-1])
def get_name(self):
return self.asset_name
wrapped_asset = AssetWrapper(asset, asset_path)
total_assets.append(wrapped_asset)
# Get clean folder name for display
display_folder = folder_path
if "Mocap" in display_folder:
mocap_index = display_folder.find("Mocap")
display_folder = display_folder[mocap_index:]
self.progress_dialog.add_item(display_folder, asset.get_name())
logger.info(f"Added asset {asset.get_name()} from {display_folder}")
except Exception as asset_e:
logger.error(f"Error processing asset {asset_path}: {str(asset_e)}")
continue
except Exception as e:
logger.error(f"Error processing folder {folder}: {str(e)}")
continue
else:
total_assets = []
for asset in selections:
if asset is None:
logger.warning("Skipping None asset in selections")
continue
try:
# Verify asset has required attributes
asset_name = str(asset.asset_name) if hasattr(asset, 'asset_name') else str(asset.get_name())
package_path = str(asset.package_path) if hasattr(asset, 'package_path') else str(asset.get_path_name())
if not asset_name or not package_path:
logger.error(f"Invalid asset found - Name: {asset_name}, Path: {package_path}")
continue
total_assets.append(asset)
self.progress_dialog.add_item(package_path, asset_name)
logger.info(f"Added individual asset {asset_name} to progress dialog")
except Exception as e:
logger.error(f"Error processing individual asset: {str(e)}")
continue
# Update the total count in the progress dialog
total_count = len(total_assets)
logger.info(f"Total assets to process: {total_count}")
if total_count == 0:
error_msg = "No assets found in selected folders."
logger.error(error_msg)
QtWidgets.QMessageBox.warning(self, "No Assets", error_msg)
self.progress_dialog.close()
return
# Start processing with the collected assets
QtCore.QTimer.singleShot(0, lambda: self.processor.run_batch_process(total_assets, False))
def update_progress(self, index, status, error="", progress_type='processing'):
if self.progress_dialog:
self.progress_dialog.update_item_progress(index, status, error, progress_type)
logger.info(f"Progress updated - Index: {index}, Status: {status}, Type: {progress_type}")
def on_processing_finished(self):
# Remove the popup message and replace with bold log entry
if self.progress_dialog:
self.progress_dialog.log_text.append("<b>Batch processing has finished.</b>")
logger.info("Batch processing has finished.")
def show_error_dialog(self, error_message):
QtWidgets.QMessageBox.critical(self, "Error", error_message)
def update_log_level(self, level):
logging.getLogger().setLevel(level)
def show_help(self):
help_text = """
Batch Processor Help:
1. Select Folders: Choose the folders containing assets to process.
2. Select Capture Data: Choose individual capture data assets to process.
3. Log Level: Choose the verbosity of logging.
4. Progress Dialog: Shows processing progress and allows cancellation.
5. Save Log: Export the processing log for troubleshooting.
For more information, please refer to the user manual.
"""
QtWidgets.QMessageBox.information(self, "Help", help_text)
def closeEvent(self, event):
reply = QtWidgets.QMessageBox.question(self, 'Exit',
"Are you sure you want to exit?",
QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.No)
if reply == QtWidgets.QMessageBox.Yes:
# Comment out cancel processing call
# self.processor.cancel_processing()
event.accept()
else:
event.ignore()
class ProcessingDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(ProcessingDialog, self).__init__(parent)
self.setWindowTitle("Processing")
self.setModal(True)
self.setMinimumWidth(300)
self.is_processing = True
# Create layout
layout = QtWidgets.QVBoxLayout(self)
# Add progress label
self.progress_label = QtWidgets.QLabel("Processing...")
layout.addWidget(self.progress_label)
# Add progress bar
self.progress_bar = QtWidgets.QProgressBar()
self.progress_bar.setRange(0, 0) # Indeterminate progress
layout.addWidget(self.progress_bar)
# Style the dialog
self.setStyleSheet("""
QDialog {
background-color: #2b2b2b;
color: #ffffff;
}
QLabel {
color: #ffffff;
}
QProgressBar {
border: 2px solid grey;
border-radius: 5px;
text-align: center;
color: #ffffff;
}
QProgressBar::chunk {
background-color: #4CAF50;
width: 10px;
margin: 0.5px;
}
""")
def closeEvent(self, event):
"""Override close event to prevent premature closing"""
if self.is_processing:
# If processing is ongoing, show confirmation dialog
reply = QtWidgets.QMessageBox.question(
self,
'Confirm Exit',
'Processing is still in progress. Are you sure you want to cancel?',
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.No
)
if reply == QtWidgets.QMessageBox.Yes:
event.accept()
else:
# User decided to continue processing
event.ignore()
else:
# If not processing, allow normal close
event.accept()
def update_progress(self, message, status):
"""Update progress status and handle completion"""
self.progress_label.setText(message)
if status == 'complete':
self.is_processing = False
self.accept() # Close dialog when complete
elif status == 'failed':
self.is_processing = False
self.reject() # Close dialog on failure
else:
self.is_processing = True
def closeEvent(self, event):
"""Override close event to prevent premature closing"""
if self.is_processing:
# If processing is ongoing, show confirmation dialog
reply = QtWidgets.QMessageBox.question(
self,
'Confirm Exit',
'Processing is still in progress. Are you sure you want to cancel?',
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.No
)
if reply == QtWidgets.QMessageBox.Yes:
# Comment out cancelled flag
# self.cancelled = True
event.accept()
else:
# User decided to continue processing
event.ignore()
else:
# If not processing, allow normal close
event.accept()
def update_progress(self, message, status):
"""Update progress status and handle completion"""
self.progress_label.setText(message)
if status == 'complete':
self.is_processing = False
self.accept() # Close dialog when complete
elif status == 'failed':
self.is_processing = False
self.reject() # Close dialog on failure
else:
self.is_processing = True
def run():
app = QtWidgets.QApplication.instance()
if not app:
app = QtWidgets.QApplication(sys.argv)
# Create and show the selection dialog directly
global ui
ui = BatchProcessorUI()
# Define the tick function
def tick(delta_time):
app.processEvents()
return True
# Keep global references
global tick_handle
tick_handle = unreal.register_slate_post_tick_callback(tick)
class KeepAlive:
pass
global keep_alive
keep_alive = KeepAlive()
keep_alive.ui = ui
keep_alive.tick_handle = tick_handle
if __name__ == "__main__":
run()
|
# coding: utf-8
import unreal
import argparse
print("VRM4U python begin")
print (__file__)
parser = argparse.ArgumentParser()
parser.add_argument("-vrm")
parser.add_argument("-rig")
parser.add_argument("-meta")
args = parser.parse_args()
print(args.vrm)
#print(dummy[3])
humanoidBoneList = [
"hips",
"leftUpperLeg",
"rightUpperLeg",
"leftLowerLeg",
"rightLowerLeg",
"leftFoot",
"rightFoot",
"spine",
"chest",
"upperChest", # 9 optional
"neck",
"head",
"leftShoulder",
"rightShoulder",
"leftUpperArm",
"rightUpperArm",
"leftLowerArm",
"rightLowerArm",
"leftHand",
"rightHand",
"leftToes",
"rightToes",
"leftEye",
"rightEye",
"jaw",
"leftThumbProximal", # 24
"leftThumbIntermediate",
"leftThumbDistal",
"leftIndexProximal",
"leftIndexIntermediate",
"leftIndexDistal",
"leftMiddleProximal",
"leftMiddleIntermediate",
"leftMiddleDistal",
"leftRingProximal",
"leftRingIntermediate",
"leftRingDistal",
"leftLittleProximal",
"leftLittleIntermediate",
"leftLittleDistal",
"rightThumbProximal",
"rightThumbIntermediate",
"rightThumbDistal",
"rightIndexProximal",
"rightIndexIntermediate",
"rightIndexDistal",
"rightMiddleProximal",
"rightMiddleIntermediate",
"rightMiddleDistal",
"rightRingProximal",
"rightRingIntermediate",
"rightRingDistal",
"rightLittleProximal",
"rightLittleIntermediate",
"rightLittleDistal", #54
]
humanoidBoneParentList = [
"", #"hips",
"hips",#"leftUpperLeg",
"hips",#"rightUpperLeg",
"leftUpperLeg",#"leftLowerLeg",
"rightUpperLeg",#"rightLowerLeg",
"leftLowerLeg",#"leftFoot",
"rightLowerLeg",#"rightFoot",
"hips",#"spine",
"spine",#"chest",
"chest",#"upperChest" 9 optional
"chest",#"neck",
"neck",#"head",
"chest",#"leftShoulder", # <-- upper..
"chest",#"rightShoulder",
"leftShoulder",#"leftUpperArm",
"rightShoulder",#"rightUpperArm",
"leftUpperArm",#"leftLowerArm",
"rightUpperArm",#"rightLowerArm",
"leftLowerArm",#"leftHand",
"rightLowerArm",#"rightHand",
"leftFoot",#"leftToes",
"rightFoot",#"rightToes",
"head",#"leftEye",
"head",#"rightEye",
"head",#"jaw",
"leftHand",#"leftThumbProximal",
"leftThumbProximal",#"leftThumbIntermediate",
"leftThumbIntermediate",#"leftThumbDistal",
"leftHand",#"leftIndexProximal",
"leftIndexProximal",#"leftIndexIntermediate",
"leftIndexIntermediate",#"leftIndexDistal",
"leftHand",#"leftMiddleProximal",
"leftMiddleProximal",#"leftMiddleIntermediate",
"leftMiddleIntermediate",#"leftMiddleDistal",
"leftHand",#"leftRingProximal",
"leftRingProximal",#"leftRingIntermediate",
"leftRingIntermediate",#"leftRingDistal",
"leftHand",#"leftLittleProximal",
"leftLittleProximal",#"leftLittleIntermediate",
"leftLittleIntermediate",#"leftLittleDistal",
"rightHand",#"rightThumbProximal",
"rightThumbProximal",#"rightThumbIntermediate",
"rightThumbIntermediate",#"rightThumbDistal",
"rightHand",#"rightIndexProximal",
"rightIndexProximal",#"rightIndexIntermediate",
"rightIndexIntermediate",#"rightIndexDistal",
"rightHand",#"rightMiddleProximal",
"rightMiddleProximal",#"rightMiddleIntermediate",
"rightMiddleIntermediate",#"rightMiddleDistal",
"rightHand",#"rightRingProximal",
"rightRingProximal",#"rightRingIntermediate",
"rightRingIntermediate",#"rightRingDistal",
"rightHand",#"rightLittleProximal",
"rightLittleProximal",#"rightLittleIntermediate",
"rightLittleIntermediate",#"rightLittleDistal",
]
for i in range(len(humanoidBoneList)):
humanoidBoneList[i] = humanoidBoneList[i].lower()
for i in range(len(humanoidBoneParentList)):
humanoidBoneParentList[i] = humanoidBoneParentList[i].lower()
######
reg = unreal.AssetRegistryHelpers.get_asset_registry();
##
rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints()
print(rigs)
for r in rigs:
s:str = r.get_path_name()
ss:str = args.rig
if (s.find(ss) < 0):
print("no rig")
else:
rig = r
#rig = rigs[10]
hierarchy = unreal.ControlRigBlueprintLibrary.get_hierarchy(rig)
h_con = hierarchy.get_controller()
#elements = h_con.get_selection()
#sk = rig.get_preview_mesh()
#k = sk.skeleton
#print(k)
#print(sk.bone_tree)
#
#kk = unreal.RigElementKey(unreal.RigElementType.BONE, "hipssss");
#kk.name = ""
#kk.type = 1;
#print(h_con.get_bone(kk))
#print(h_con.get_elements())
### 全ての骨
modelBoneListAll = []
modelBoneNameList = []
#for e in reversed(h_con.get_elements()):
# if (e.type != unreal.RigElementType.BONE):
# h_con.remove_element(e)
for e in hierarchy.get_bones():
if (e.type == unreal.RigElementType.BONE):
modelBoneListAll.append(e)
modelBoneNameList.append("{}".format(e.name).lower())
# else:
# h_con.remove_element(e)
print(modelBoneListAll[0])
#exit
#print(k.get_editor_property("bone_tree")[0].get_editor_property("translation_retargeting_mode"))
#print(k.get_editor_property("bone_tree")[0].get_editor_property("parent_index"))
#unreal.select
#vrmlist = unreal.VrmAssetListObject
#vrmmeta = vrmlist.vrm_meta_object
#print(vrmmeta.humanoid_bone_table)
#selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors()
#selected_static_mesh_actors = unreal.EditorFilterLibrary.by_class(selected_actors,unreal.StaticMeshActor.static_class())
#static_meshes = np.array([])
## meta 取得
reg = unreal.AssetRegistryHelpers.get_asset_registry();
a = reg.get_all_assets();
if (args.meta):
for aa in a:
if (aa.get_editor_property("object_path") == args.meta):
v:unreal.VrmMetaObject = aa
vv = aa.get_asset()
if (vv == None):
for aa in a:
if (aa.get_editor_property("object_path") == args.vrm):
v:unreal.VrmAssetListObject = aa
vv = v.get_asset().vrm_meta_object
print(vv)
meta = vv
#v:unreal.VrmAssetListObject = None
#if (True):
# a = reg.get_assets_by_path(args.vrm)
# a = reg.get_all_assets();
# for aa in a:
# if (aa.get_editor_property("object_path") == args.vrm):
# v:unreal.VrmAssetListObject = aa
#v = unreal.VrmAssetListObject.cast(v)
#print(v)
#unreal.VrmAssetListObject.vrm_meta_object
#meta = v.vrm_meta_object()
#meta = unreal.EditorFilterLibrary.by_class(asset,unreal.VrmMetaObject.static_class())
print (meta)
#print(meta[0].humanoid_bone_table)
### モデル骨のうち、ヒューマノイドと同じもの
### 上の変換テーブル
humanoidBoneToModel = {"" : ""}
humanoidBoneToModel.clear()
### modelBoneでループ
#for bone_h in meta.humanoid_bone_table:
for bone_h_base in humanoidBoneList:
bone_h = None
for e in meta.humanoid_bone_table:
if ("{}".format(e).lower() == bone_h_base):
bone_h = e;
break;
print("{}".format(bone_h))
if (bone_h==None):
continue
bone_m = meta.humanoid_bone_table[bone_h]
try:
i = modelBoneNameList.index(bone_m.lower())
except:
i = -1
if (i < 0):
continue
if ("{}".format(bone_h).lower() == "upperchest"):
continue;
humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m).lower()
if ("{}".format(bone_h).lower() == "chest"):
#upperchestがあれば、これの次に追加
bh = 'upperchest'
print("upperchest: check begin")
for e in meta.humanoid_bone_table:
if ("{}".format(e).lower() != 'upperchest'):
continue
bm = "{}".format(meta.humanoid_bone_table[e]).lower()
if (bm == ''):
continue
humanoidBoneToModel[bh] = bm
humanoidBoneParentList[10] = "upperchest"
humanoidBoneParentList[12] = "upperchest"
humanoidBoneParentList[13] = "upperchest"
print("upperchest: find and insert parent")
break
print("upperchest: check end")
parent=None
control_to_mat={None:None}
count = 0
### 骨名からControlへのテーブル
name_to_control = {"dummy_for_table" : None}
print("loop begin")
###### root
key = unreal.RigElementKey(unreal.RigElementType.NULL, 'root_s')
space = hierarchy.find_null(key)
if (space.get_editor_property('index') < 0):
space = h_con.add_null('root_s', space_type=unreal.RigSpaceType.SPACE)
else:
space = key
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, 'root_c')
control = hierarchy.find_control(key)
if (control.get_editor_property('index') < 0):
control = h_con.add_control('root_c',
space_name=space.name,
gizmo_color=[1.0, 0.0, 0.0, 1.0],
)
else:
control = key
h_con.set_parent(control, space)
parent = control
setting = h_con.get_control_settings(control)
setting.shape_visible = False
h_con.set_control_settings(control, setting)
for ee in humanoidBoneToModel:
element = humanoidBoneToModel[ee]
humanoidBone = ee
modelBoneNameSmall = element
# 対象の骨
#modelBoneNameSmall = "{}".format(element.name).lower()
#humanoidBone = modelBoneToHumanoid[modelBoneNameSmall];
boneNo = humanoidBoneList.index(humanoidBone)
print("{}_{}_{}__parent={}".format(modelBoneNameSmall, humanoidBone, boneNo,humanoidBoneParentList[boneNo]))
# 親
if count != 0:
parent = name_to_control[humanoidBoneParentList[boneNo]]
# 階層作成
bIsNew = False
name_s = "{}_s".format(humanoidBone)
key = unreal.RigElementKey(unreal.RigElementType.NULL, name_s)
space = hierarchy.find_null(key)
if (space.get_editor_property('index') < 0):
space = h_con.add_space(name_s, space_type=unreal.RigSpaceType.SPACE)
bIsNew = True
else:
space = key
name_c = "{}_c".format(humanoidBone)
key = unreal.RigElementKey(unreal.RigElementType.CONTROL, name_c)
control = hierarchy.find_control(key)
if (control.get_editor_property('index') < 0):
control = h_con.add_control(name_c,
space_name=space.name,
gizmo_color=[1.0, 0.0, 0.0, 1.0],
)
#h_con.get_control(control).gizmo_transform = gizmo_trans
if (24<=boneNo & boneNo<=53):
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.1, 0.1, 0.1])
else:
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1])
if (17<=boneNo & boneNo<=18):
gizmo_trans = unreal.Transform([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1, 1, 1])
cc = h_con.get_control(control)
cc.set_editor_property('gizmo_transform', gizmo_trans)
cc.set_editor_property('control_type', unreal.RigControlType.ROTATOR)
h_con.set_control(cc)
#h_con.set_control_value_transform(control,gizmo_trans)
bIsNew = True
else:
control = key
if (bIsNew == True):
h_con.set_parent(control, space)
# テーブル登録
name_to_control[humanoidBone] = control
print(humanoidBone)
# ロケータ 座標更新
# 不要な上層階層を考慮
gTransform = hierarchy.get_global_transform(modelBoneListAll[modelBoneNameList.index(modelBoneNameSmall)])
if count == 0:
bone_initial_transform = gTransform
else:
#bone_initial_transform = h_con.get_initial_transform(element)
bone_initial_transform = gTransform.multiply(control_to_mat[parent].inverse())
hierarchy.set_global_transform(space, gTransform, True)
control_to_mat[control] = gTransform
# 階層修正
h_con.set_parent(space, parent)
count += 1
if (count >= 500):
break
|
import unreal
#import re
def get_bp_c_by_name(__bp_dir:str):
__bp_c = __bp_dir + '_C'
return __bp_c
def get_bp_mesh_comp (__bp_c:str) :
#source_mesh = ue.load_asset(__mesh_dir)
loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c)
bp_c_obj = unreal.get_default_object(loaded_bp_c)
loaded_comp = bp_c_obj.get_editor_property('Mesh')
return loaded_comp
def get_bp_capsule_comp (__bp_c:str) :
#source_mesh = ue.load_asset(__mesh_dir)
loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c)
bp_c_obj = unreal.get_default_object(loaded_bp_c)
loaded_comp = bp_c_obj.get_editor_property('CapsuleComponent')
return loaded_comp
def get_bp_comp_by_name (__bp_c, __seek: str) :
#source_mesh = ue.load_asset(__mesh_dir)
loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c)
bp_c_obj = unreal.get_default_object(loaded_bp_c)
loaded_comp = bp_c_obj.get_editor_property(__seek)
return loaded_comp
ar_asset_lists = []
ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets()
print (ar_asset_lists[0])
str_selected_asset = ''
if len(ar_asset_lists) > 0 :
str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0])
#str_selected_asset = str(ar_asset_lists[0])
#print(str_selected_asset)
path = str_selected_asset.rsplit('/', 1)[0] + '/'
name = str_selected_asset.rsplit('/', 1)[1]
name = name.rsplit('.', 1)[1]
BaseBP: str = '/project/'
BaseAnimBP: str = '/project/'
Basepath: str = path
assetPath: str = Basepath + '/project/'
'''BP setting start'''
BPPath: str = Basepath + '/Blueprints/' + name + "_Blueprint"
AnimBPPath: str = Basepath + '/Blueprints/' + name + "_AnimBP"
#SkeletonPath = Basepath + name + "_Skeleton"
Skeleton = ar_asset_lists[0].skeleton
asset_bp = unreal.EditorAssetLibrary.duplicate_asset(BaseBP,BPPath)
AnimBP = unreal.EditorAssetLibrary.duplicate_asset(BaseAnimBP,AnimBPPath)
AnimBP.set_editor_property("target_skeleton", Skeleton)
# BPPath_C = get_bp_c_by_name(BPPath)
# BP_mesh_comp = get_bp_mesh_comp_by_name(BPPath_C, 'Mesh')
# BP_mesh_comp.set_editor_property('skeletal_mesh',ar_asset_lists[0])
# BP_mesh_comp.set_editor_property('anim_class', loaded_a)
# '''BP setting end'''
# BP Component Setting Start #
_bp_ = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(asset_bp)
_abp_ = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(AnimBP)
_bp_c = get_bp_c_by_name(_bp_)
_abp_c = get_bp_c_by_name(_abp_)
loaded_abp = unreal.EditorAssetLibrary.load_blueprint_class(_abp_c)
bp_mesh_comp = get_bp_mesh_comp(_bp_c)
bp_mesh_comp.set_editor_property('skeletal_mesh',ar_asset_lists[0])
bp_mesh_comp.set_editor_property('anim_class', loaded_abp)
# BP Component Setting End #
#test code #
# bp_capsule_comp = get_bp_capsule_comp(_bp_c)
# bp_capsule_comp = get_bp_comp_by_name(_bp_c,'CapsuleComponent')
# half_height = bp_capsule_comp.get_editor_property('capsule_half_height')
|
import unreal
projectPath = unreal.Paths.project_dir()
content_path = unreal.Paths.project_content_dir()
path_split = projectPath.split('/')
wip_folder_name = path_split[len(path_split)-3] + '_WIP'
path_split[len(path_split)-3] = wip_folder_name
wip_path = '/'.join(path_split)
wip_folder = wip_path
source_folder = content_path
texture_folder = wip_path + 'Game/'
desired_size = 2024
print('WIP Folder:', wip_folder)
print('Source Folder:', source_folder)
print('Texture Folder:', texture_folder)
print('Desired Size:', desired_size)
|
"""
Test script to create an actor in Unreal Engine.
"""
import unreal
# Create a new actor (static mesh) at origin
actor_location = unreal.Vector(0, 0, 0)
actor_rotation = unreal.Rotator(0, 0, 0)
actor = unreal.EditorLevelLibrary.spawn_actor_from_class(
unreal.StaticMeshActor,
actor_location,
actor_rotation
)
# Set the actor name
actor.set_actor_label("TestCube")
# Set the mesh to a cube
mesh_path = "/project/.Cube"
mesh = unreal.EditorAssetLibrary.load_asset(mesh_path)
actor.static_mesh_component.set_static_mesh(mesh)
# Print the result
print(f"Created actor: {actor.get_name()}")
# Return a result object
result = {
"status": "success",
"message": f"Created actor: {actor.get_name()}",
"actor_name": actor.get_name(),
"actor_label": actor.get_actor_label(),
"location": [0, 0, 0]
}
# This string will be captured by the MCP system
str(result)
|
#coding:utf-8
import unreal
import sys
sys.path.append('C:/project/-packages')
from PySide import QtGui, QtUiTools, QtCore
import UE_AssembleTool
reload(UE_AssembleTool)
UI_FILE_FULLNAME = r"\\ftdytool.hytch.com\FTDY\hq_tool\software\Unreal Engine\PythonProject\UE_PipelineTool\Assemble\UE_AssembleTool_UI.ui"
UI_OPTION_FULLNAME = r"\\ftdytool.hytch.com\FTDY\hq_tool\software\Unreal Engine\PythonProject\UE_PipelineTool\Assemble\UE_AssembleOption_UI.ui"
class UE_AssembleTool_UI(QtGui.QDialog):
def __init__(self, parent=None):
super(UE_AssembleTool_UI, self).__init__(parent)
self.aboutToClose = None # This is used to stop the tick when the window is closed
self.widget = QtUiTools.QUiLoader().load(UI_FILE_FULLNAME)
self.widget.setParent(self)
self.setGeometry(100,100,350,320)
self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
self.file_dialog = None
self.option_window = None
# layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.widget)
layout.setSpacing(0)
layout.setContentsMargins(0,0,0,0)
self.setLayout(layout)
self.button1 = self.widget.findChild(QtGui.QPushButton, "pushButton_1")
self.button2 = self.widget.findChild(QtGui.QPushButton, "pushButton_2")
self.button3 = self.widget.findChild(QtGui.QPushButton, "pushButton_3")
self.button4 = self.widget.findChild(QtGui.QPushButton, "pushButton_4")
self.button1.clicked.connect(self.path_pop_up)
self.button2.setEnabled(0)
self.button3.setEnabled(0)
self.button4.setEnabled(0)
def closeEvent(self, event):
# 把自身传入函数引用从opened列表里面删除并关闭UI,但是并没有从内存中删除??
if self.aboutToClose:
self.aboutToClose(self)
print "UI deleted"
event.accept()
def eventTick(self, delta_seconds):
self.myTick(delta_seconds)
def myTick(self, delta_seconds):
print delta_seconds
def path_pop_up(self):
self.file_dialog = QtGui.QFileDialog()
self.file_dialog.setFileMode(QtGui.QFileDialog.ExistingFiles)
self.file_dialog.setNameFilter("FBX files (*.fbx)")
self.file_dialog.filesSelected.connect(self.option_pop_up)
self.file_dialog.show()
def option_pop_up(self, fbx_files):
self.option_window = QtUiTools.QUiLoader().load(UI_OPTION_FULLNAME)
self.option_window.show()
button = self.option_window.findChild(QtGui.QPushButton, "pushButton")
button.clicked.connect(lambda: self.exec_assemble(fbx_files))
def exec_assemble(self, fbx_files):
combo = self.option_window.findChild(QtGui.QComboBox, "comboBox")
line = self.option_window.findChild(QtGui.QLineEdit, "lineEdit")
spin = self.option_window.findChild(QtGui.QDoubleSpinBox, "doubleSpinBox")
type = combo.currentText()
path = line.text()
scale = spin.value()
self.option_window.close()
if not path:
path = "/project/"
UE_AssembleTool.assemble_fbx_asset(fbx_files, path, import_type=type, assemble_scale_factor=scale)
print fbx_files, path, type, scale
|
import unreal
MEL = unreal.MaterialEditingLibrary
from pamux_unreal_tools.base.material_expression.material_expression_sockets_base import InSocket, OutSocket
from pamux_unreal_tools.base.material_expression.material_expression_base_base import MaterialExpressionBaseBase
class InSocketImpl(InSocket):
def __init__(self, material_expression: MaterialExpressionBaseBase, name: str, type: str) -> None:
super().__init__(material_expression, name, type)
def comesFrom(self, param) -> bool:
if isinstance(param, OutSocket):
return self.__comesFrom_OutSocket(param)
if isinstance(param, MaterialExpressionBaseBase):
return self.__comesFrom_MaterialExpressionBase(param)
raise Exception("Don't know how to call comesFrom for type: " + str(param))
def __comesFrom_OutSocket(self, sourceOutSocket: OutSocket) -> bool:
if hasattr(sourceOutSocket, "rt") and sourceOutSocket.rt is not None:
return self.comesFrom(sourceOutSocket.rt)
return self.__comesFrom_impl(sourceOutSocket.material_expression, sourceOutSocket.name)
def __comesFrom_MaterialExpressionBase(self, sourceMaterialExpression: MaterialExpressionBaseBase) -> bool:
return self.__comesFrom_impl(sourceMaterialExpression, "")
def __comesFrom_impl(self, sourceMaterialExpression: MaterialExpressionBaseBase, sourceOutSocketName: str) -> bool:
self.material_expression.gotoRightOf(sourceMaterialExpression)
return MEL.connect_material_expressions(sourceMaterialExpression.unrealAsset, sourceOutSocketName, self.material_expression.unrealAsset, self.name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.