text
stringlengths
15
267k
# coding: utf-8 from asyncio.windows_events import NULL from platform import java_ver import unreal import time 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) with unreal.ScopedSlowTask(1, "Convert Bone") as slow_task_root: slow_task_root.make_dialog() 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() def checkAndSwapPinBoneToContorl(pin): subpins = pin.get_sub_pins() #print(subpins) if (len(subpins) != 2): return; typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') #if (typePin==None or namePin==None): if (typePin==None): return; #if (typePin.get_default_value() == '' or namePin.get_default_value() == ''): if (typePin.get_default_value() == ''): return; if (typePin.get_default_value() != 'Bone'): return; #print(typePin.get_default_value() + ' : ' + namePin.get_default_value()) r_con.set_pin_default_value(typePin.get_pin_path(), 'Control', True, False) #print('swap end') #end check pin bonePin = None controlPin = None with unreal.ScopedSlowTask(1, "Replace Bone") as slow_task: slow_task.make_dialog() while(len(hierarchy.get_bones()) > 0): e = hierarchy.get_bones()[-1] h_con.remove_all_parents(e) h_con.import_bones(unreal.ControlRigBlueprintLibrary.get_preview_mesh(rig).skeleton) ## with unreal.ScopedSlowTask(1, "Replace Bone to Controller") as slow_task: slow_task.make_dialog() for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): if (pin.get_array_size() > 40): # long bone list typePin = pin.get_sub_pins()[0].find_sub_pin('Type') if (typePin != None): if (typePin.get_default_value() == 'Bone'): bonePin = pin continue if (typePin.get_default_value() == 'Control'): if ('Name="pelvis"' in r_con.get_pin_default_value(n.find_pin('Items').get_pin_path())): controlPin = pin continue for item in pin.get_sub_pins(): checkAndSwapPinBoneToContorl(item) else: checkAndSwapPinBoneToContorl(pin) for e in hierarchy.get_controls(): tmp = "{}".format(e.name) if (tmp.endswith('_ctrl') == False): continue if (tmp.startswith('thumb_0') or tmp.startswith('index_0') or tmp.startswith('middle_0') or tmp.startswith('ring_0') or tmp.startswith('pinky_0')): print('') else: continue c = hierarchy.find_control(e) #print(e.name) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) ttt = unreal.Transform(location=[0.0, 0.0, 2.0], rotation=[0.0, 0.0, 90.0], scale=[0.03, 0.03, 0.25]) hierarchy.set_control_shape_transform(e, ttt, True) ''' shape = c.get_editor_property('shape') init = shape.get_editor_property('initial') #init = shape.get_editor_property('current') local = init.get_editor_property('local') local = ttt init.set_editor_property('local', local) gl = init.get_editor_property('global_') gl = ttt init.set_editor_property('global_', gl) shape.set_editor_property('initial', init) shape.set_editor_property('current', init) c.set_editor_property('shape', shape) ''' ### swapBoneTable = [ ["root",""], ["pelvis","hips"], ["spine_01","spine"], ["spine_02","chest"], ["spine_03","upperChest"], ["clavicle_l","leftShoulder"], ["upperArm_L","leftUpperArm"], ["lowerarm_l","leftLowerArm"], ["hand_L","leftHand"], ["index_01_l","leftIndexProximal"], ["index_02_l","leftIndexIntermediate"], ["index_03_l","leftIndexDistal"], ["middle_01_l","leftMiddleProximal"], ["middle_02_l","leftMiddleIntermediate"], ["middle_03_l","leftMiddleDistal"], ["pinky_01_l","leftLittleProximal"], ["pinky_02_l","leftLittleIntermediate"], ["pinky_03_l","leftLittleDistal"], ["ring_01_l","leftRingProximal"], ["ring_02_l","leftRingIntermediate"], ["ring_03_l","leftRingDistal"], ["thumb_01_l","leftThumbProximal"], ["thumb_02_l","leftThumbIntermediate"], ["thumb_03_l","leftThumbDistal"], ["lowerarm_twist_01_l",""], ["upperarm_twist_01_l",""], ["clavicle_r","rightShoulder"], ["upperArm_R","rightUpperArm"], ["lowerarm_r","rightLowerArm"], ["hand_R","rightHand"], ["index_01_r","rightIndexProximal"], ["index_02_r","rightIndexIntermediate"], ["index_03_r","rightIndexDistal"], ["middle_01_r","rightMiddleProximal"], ["middle_02_r","rightMiddleIntermediate"], ["middle_03_r","rightMiddleDistal"], ["pinky_01_r","rightLittleProximal"], ["pinky_02_r","rightLittleIntermediate"], ["pinky_03_r","rightLittleDistal"], ["ring_01_r","rightRingProximal"], ["ring_02_r","rightRingIntermediate"], ["ring_03_r","rightRingDistal"], ["thumb_01_r","rightThumbProximal"], ["thumb_02_r","rightThumbIntermediate"], ["thumb_03_r","rightThumbDistal"], ["lowerarm_twist_01_r",""], ["upperarm_twist_01_r",""], ["neck_01","neck"], ["head","head"], ["thigh_L","leftUpperLeg"], ["calf_l","leftLowerLeg"], ["calf_twist_01_l",""], ["foot_L","leftFoot"], ["ball_l","leftToes"], ["thigh_twist_01_l",""], ["thigh_R","rightUpperLeg"], ["calf_r","rightLowerLeg"], ["calf_twist_01_r",""], ["foot_R","rightFoot"], ["ball_r","rightToes"], ["thigh_twist_01_r",""], ["index_metacarpal_l",""], ["index_metacarpal_r",""], ["middle_metacarpal_l",""], ["middle_metacarpal_r",""], ["ring_metacarpal_l",""], ["ring_metacarpal_r",""], ["pinky_metacarpal_l",""], ["pinky_metacarpal_r",""], #custom ["eye_l", "leftEye"], ["eye_r", "rightEye"], ] 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 ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(swapBoneTable)): swapBoneTable[i][0] = swapBoneTable[i][0].lower() swapBoneTable[i][1] = swapBoneTable[i][1].lower() ### 全ての骨 modelBoneElementList = [] modelBoneNameList = [] for e in hierarchy.get_bones(): if (e.type == unreal.RigElementType.BONE): modelBoneElementList.append(e) modelBoneNameList.append("{}".format(e.name)) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: #print(aa.get_editor_property("package_name")) #print(aa.get_editor_property("asset_name")) if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() break if (vv == None): for aa in a: if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object break meta = vv # Backwards Bone Names allBackwardsNode = [] def r_nodes(node): b = False try: allBackwardsNode.index(node) except: b = True if (b == True): allBackwardsNode.append(node) linknode = node.get_linked_source_nodes() for n in linknode: r_nodes(n) linknode = node.get_linked_target_nodes() for n in linknode: r_nodes(n) for n in node: if (n.get_node_title() == 'Backwards Solve'): r_nodes(n) #print(len(allBackwardsNode)) #print(len(node)) def boneOverride(pin): subpins = pin.get_sub_pins() if (len(subpins) != 2): return typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None): return if (namePin==None): return controlName = namePin.get_default_value() if (controlName==''): return if (controlName.endswith('_ctrl')): return if (controlName.endswith('_space')): return r_con.set_pin_default_value(typePin.get_pin_path(), 'Bone', True, False) table = [i for i in swapBoneTable if i[0]==controlName] if (len(table) == 0): # use node or no control return if (table[0][0] == 'root'): metaTable = "{}".format(hierarchy.get_bones()[0].name) else: metaTable = meta.humanoid_bone_table.get(table[0][1]) if (metaTable == None): metaTable = 'None' r_con.set_pin_default_value(namePin.get_pin_path(), metaTable, True, False) #for e in meta.humanoid_bone_table: for n in allBackwardsNode: pins = n.get_pins() for pin in pins: if (pin.is_array()): # finger 無変換チェック linknode = n.get_linked_target_nodes() if (len(linknode) == 1): if (linknode[0].get_node_title()=='At'): continue for p in pin.get_sub_pins(): boneOverride(p) else: boneOverride(pin) #sfsdjfkasjk ### 骨名対応表。Humanoid名 -> Model名 humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() humanoidBoneToMannequin = {"" : ""} humanoidBoneToMannequin.clear() # humanoidBone -> modelBone のテーブル作る for searchHumanoidBone in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == searchHumanoidBone): bone_h = e; break; if (bone_h==None): # not found continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m) except: i = -1 if (i < 0): # no bone continue humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m) #humanoidBoneToMannequin["{}".format(bone_h).lower()] = "{}".format(bone_m).lower(bone_h) #print(humanoidBoneToModel) #print(bonePin) #print(controlPin) if (bonePin != None and controlPin !=None): r_con.clear_array_pin(bonePin.get_pin_path()) r_con.clear_array_pin(controlPin.get_pin_path()) #c.clear_array_pin(v.get_pin_path()) #tmp = '(Type=Control,Name=' #tmp += "{}".format('aaaaa') #tmp += ')' #r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp) with unreal.ScopedSlowTask(len(swapBoneTable), "Replace Name") as slow_task: slow_task.make_dialog() for e in swapBoneTable: slow_task.enter_progress_frame(1) try: i = 0 humanoidBoneToModel[e[1]] except: i = -1 if (i < 0): # no bone continue #e[0] -> grayman #e[1] -> humanoid #humanoidBoneToModel[e[1]] -> modelBone bone = unreal.RigElementKey(unreal.RigElementType.BONE, humanoidBoneToModel[e[1]]) space = unreal.RigElementKey(unreal.RigElementType.NULL, "{}_s".format(e[0])) #print('aaa') #print(bone) #print(space) #p = hierarchy.get_first_parent(humanoidBoneToModel[result[0][1]]) t = hierarchy.get_global_transform(bone) #print(t) hierarchy.set_global_transform(space, t, True) if (bonePin != None and controlPin !=None): tmp = '(Type=Control,Name=' tmp += "{}".format(e[0]) tmp += ')' r_con.add_array_pin(controlPin.get_pin_path(), default_value=tmp, setup_undo_redo=False) tmp = '(Type=Bone,Name=' tmp += "\"{}\"".format(humanoidBoneToModel[e[1]]) tmp += ')' r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp, setup_undo_redo=False) # for bone name space namePin = bonePin.get_sub_pins()[-1].find_sub_pin('Name') r_con.set_pin_default_value(namePin.get_pin_path(), "{}".format(humanoidBoneToModel[e[1]]), True, False) # skip invalid bone, controller # disable node def disableNode(toNoneNode): print(toNoneNode) pins = toNoneNode.get_pins() for pin in pins: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue print(f'DisablePin {typePin.get_default_value()} : {namePin.get_default_value()}') # control key = unreal.RigElementKey(unreal.RigElementType.CONTROL, "{}".format(namePin.get_default_value())) # disable node r_con.set_pin_default_value(namePin.get_pin_path(), 'None', True, False) if (typePin.get_default_value() == 'Control'): #disable control if (hierarchy.contains(key) == True): settings = h_con.get_control_settings(key) if ("5." in unreal.SystemLibrary.get_engine_version()): if ("5.0." in unreal.SystemLibrary.get_engine_version()): settings.set_editor_property('shape_enabled', False) else: settings.set_editor_property('shape_visible', False) else: settings.set_editor_property('shape_enabled', False) ttt = hierarchy.get_global_control_shape_transform(key, True) ttt.scale3d.set(0.001, 0.001, 0.001) hierarchy.set_control_shape_transform(key, ttt, True) h_con.set_control_settings(key, settings) for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): continue else: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue if (typePin.get_default_value() != 'Bone'): continue if (namePin.is_u_object() == True): continue if (len(n.get_linked_source_nodes()) > 0): continue key = unreal.RigElementKey(unreal.RigElementType.BONE, namePin.get_default_value()) if (hierarchy.contains(key) == True): continue print(f'disable linked node from {typePin.get_default_value()} : {namePin.get_default_value()}') for toNoneNode in n.get_linked_target_nodes(): disableNode(toNoneNode) # for n in node: # pins = n.get_pins() # for pin in pins: # if (pin.is_array()): # continue # else: # typePin = pin.find_sub_pin('Type') # namePin = pin.find_sub_pin('Name') # if (typePin == None): # continue # if (typePin.get_default_value() == 'Bone'): # bonePin = pin # continue # if (typePin.get_default_value() == 'Control'): # if ('Name="pelvis"' in r_con.get_pin_default_value(n.find_pin('Items').get_pin_path())): # controlPin = pin # continue # for item in pin.get_sub_pins(): # checkAndSwapPinBoneToContorl(item) # checkAndSwapPinBoneToContorl(pin) ## morph # -vrm vrm -rig rig -debugeachsave 0 #args.vrm #args.rig command = 'VRM4U_CreateMorphTargetControllerUE5.py ' + '-vrm ' + args.vrm + ' -rig ' + args.rig + ' -debugeachsave 0' print(command) unreal.PythonScriptLibrary.execute_python_command(command) unreal.ControlRigBlueprintLibrary.recompile_vm(rig)
import unreal def create_spline_mesh_blueprint(): # Load original Blueprint unreal.log("Loading original Blueprint...") original_blueprint_path = "/project/" # replace this with the path to your original Blueprint blueprint_path = "/project/" original_blueprint = unreal.EditorAssetLibrary.load_asset(original_blueprint_path) # Duplicate the original Blueprint unreal.log("Creating new Blueprint by duplicating original Blueprint...") blueprint = unreal.EditorAssetLibrary.duplicate_asset(original_blueprint_path, blueprint_path) blueprint_generated_class = unreal.EditorAssetLibrary.get_blueprint_generated_class(blueprint) # Add a Spline Component to the Blueprint unreal.log("Adding Spline Component to Blueprint...") spline_component = blueprint_generated_class.add_component_uninitialized("SplineComponent", "/project/.SplineComponent") spline_component.set_editor_property("Mobility", unreal.ComponentMobility.STATIC) # Create an array of public variables to define the meshes meshes_to_spawn = ["Mesh1", "Mesh2", "Mesh3", "Mesh4", "Mesh5", "Mesh6", "Mesh7", "Mesh8", "Mesh9", "Mesh10", "Mesh11", "Mesh12", "Mesh13", "Mesh14", "Mesh15", "Mesh16", "Mesh17", "Mesh18", "Mesh19", "Mesh20"] # Iterate over the public variables and add them as public Static Mesh Components to the Blueprint for mesh_name in meshes_to_spawn: mesh_component = blueprint_generated_class.add_component_uninitialized("StaticMeshComponent", "/project/.StaticMeshComponent") mesh_component.set_editor_property("Mobility", unreal.ComponentMobility.STATIC) mesh_variable_name = "Mesh_" + mesh_name mesh_variable_path = "Meshes." + mesh_variable_name mesh_component.set_editor_property("StaticMesh", unreal.EditorAssetLibrary.get_editor_property(blueprint_generated_class, mesh_variable_path)) mesh_component.set_editor_property("CollisionEnabled", unreal.CollisionEnabledType.NO_COLLISION) spline_component.add_instance_component(mesh_component) # Save the Blueprint unreal.log("Saving Blueprint...") unreal.EditorAssetLibrary.save_loaded_asset(blueprint) # Log the Blueprint path blueprint_path = unreal.EditorAssetLibrary.get_asset_path(blueprint) unreal.log("Blueprint created successfully: {}".format(blueprint_path)) # Execute the function to create the Blueprint create_spline_mesh_blueprint()
# 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 class ProcessHDA(object): """ An object that wraps async processing of an HDA (instantiating, cooking/project/ an HDA), with functions that are called at the various stages of the process, that can be overridden by subclasses for custom funtionality: - on_failure() - on_complete(): upon successful completion (could be PostInstantiation if auto cook is disabled, PostProcessing if auto bake is disabled, or after PostAutoBake if auto bake is enabled. - on_pre_instantiation(): before the HDA is instantiated, a good place to set parameter values before the first cook. - on_post_instantiation(): after the HDA is instantiated, a good place to set/configure inputs before the first cook. - on_post_auto_cook(): right after a cook - on_pre_process(): after a cook but before output objects have been created/processed - on_post_processing(): after output objects have been created - on_post_auto_bake(): after outputs have been baked Instantiate the processor via the constructor and then call the activate() function to start the asynchronous process. """ def __init__( self, houdini_asset, instantiate_at=unreal.Transform(), parameters=None, node_inputs=None, parameter_inputs=None, world_context_object=None, spawn_in_level_override=None, enable_auto_cook=True, enable_auto_bake=False, bake_directory_path="", bake_method=unreal.HoudiniEngineBakeOption.TO_ACTOR, remove_output_after_bake=False, recenter_baked_actors=False, replace_previous_bake=False, delete_instantiated_asset_on_completion_or_failure=False): """ Instantiates an HDA in the specified world/level. Sets parameters and inputs supplied in InParameters, InNodeInputs and parameter_inputs. If bInEnableAutoCook is true, cooks the HDA. If bInEnableAutoBake is true, bakes the cooked outputs according to the supplied baking parameters. This all happens asynchronously, with the various output pins firing at the various points in the process: - PreInstantiation: before the HDA is instantiated, a good place to set parameter values before the first cook (parameter values from ``parameters`` are automatically applied at this point) - PostInstantiation: after the HDA is instantiated, a good place to set/configure inputs before the first cook (inputs from ``node_inputs`` and ``parameter_inputs`` are automatically applied at this point) - PostAutoCook: right after a cook - PreProcess: after a cook but before output objects have been created/processed - PostProcessing: after output objects have been created - PostAutoBake: after outputs have been baked - Completed: upon successful completion (could be PostInstantiation if auto cook is disabled, PostProcessing if auto bake is disabled, or after PostAutoBake if auto bake is enabled). - Failed: If the process failed at any point. Args: houdini_asset (HoudiniAsset): The HDA to instantiate. instantiate_at (Transform): The Transform to instantiate the HDA with. parameters (Map(Name, HoudiniParameterTuple)): The parameters to set before cooking the instantiated HDA. node_inputs (Map(int32, HoudiniPublicAPIInput)): The node inputs to set before cooking the instantiated HDA. parameter_inputs (Map(Name, HoudiniPublicAPIInput)): The parameter-based inputs to set before cooking the instantiated HDA. world_context_object (Object): A world context object for identifying the world to spawn in, if spawn_in_level_override is null. spawn_in_level_override (Level): If not nullptr, then the HoudiniAssetActor is spawned in that level. If both spawn_in_level_override and world_context_object are null, then the actor is spawned in the current editor context world's current level. enable_auto_cook (bool): If true (the default) the HDA will cook automatically after instantiation and after parameter, transform and input changes. enable_auto_bake (bool): If true, the HDA output is automatically baked after a cook. Defaults to false. bake_directory_path (str): The directory to bake to if the bake path is not set via attributes on the HDA output. bake_method (HoudiniEngineBakeOption): The bake target (to actor vs blueprint). @see HoudiniEngineBakeOption. remove_output_after_bake (bool): If true, HDA temporary outputs are removed after a bake. Defaults to false. recenter_baked_actors (bool): Recenter the baked actors to their bounding box center. Defaults to false. replace_previous_bake (bool): If true, on every bake replace the previous bake's output (assets + actors) with the new bake's output. Defaults to false. delete_instantiated_asset_on_completion_or_failure (bool): If true, deletes the instantiated asset actor on completion or failure. Defaults to false. """ super(ProcessHDA, self).__init__() self._houdini_asset = houdini_asset self._instantiate_at = instantiate_at self._parameters = parameters self._node_inputs = node_inputs self._parameter_inputs = parameter_inputs self._world_context_object = world_context_object self._spawn_in_level_override = spawn_in_level_override self._enable_auto_cook = enable_auto_cook self._enable_auto_bake = enable_auto_bake self._bake_directory_path = bake_directory_path self._bake_method = bake_method self._remove_output_after_bake = remove_output_after_bake self._recenter_baked_actors = recenter_baked_actors self._replace_previous_bake = replace_previous_bake self._delete_instantiated_asset_on_completion_or_failure = delete_instantiated_asset_on_completion_or_failure self._asset_wrapper = None self._cook_success = False self._bake_success = False @property def asset_wrapper(self): """ The asset wrapper for the instantiated HDA processed by this node. """ return self._asset_wrapper @property def cook_success(self): """ True if the last cook was successful. """ return self._cook_success @property def bake_success(self): """ True if the last bake was successful. """ return self._bake_success @property def houdini_asset(self): """ The HDA to instantiate. """ return self._houdini_asset @property def instantiate_at(self): """ The transform the instantiate the asset with. """ return self._instantiate_at @property def parameters(self): """ The parameters to set on on_pre_instantiation """ return self._parameters @property def node_inputs(self): """ The node inputs to set on on_post_instantiation """ return self._node_inputs @property def parameter_inputs(self): """ The object path parameter inputs to set on on_post_instantiation """ return self._parameter_inputs @property def world_context_object(self): """ The world context object: spawn in this world if spawn_in_level_override is not set. """ return self._world_context_object @property def spawn_in_level_override(self): """ The level to spawn in. If both this and world_context_object is not set, spawn in the editor context's level. """ return self._spawn_in_level_override @property def enable_auto_cook(self): """ Whether to set the instantiated asset to auto cook. """ return self._enable_auto_cook @property def enable_auto_bake(self): """ Whether to set the instantiated asset to auto bake after a cook. """ return self._enable_auto_bake @property def bake_directory_path(self): """ Set the fallback bake directory, for if output attributes do not specify it. """ return self._bake_directory_path @property def bake_method(self): """ The bake method/target: for example, to actors vs to blueprints. """ return self._bake_method @property def remove_output_after_bake(self): """ Remove temporary HDA output after a bake. """ return self._remove_output_after_bake @property def recenter_baked_actors(self): """ Recenter the baked actors at their bounding box center. """ return self._recenter_baked_actors @property def replace_previous_bake(self): """ Replace previous bake output on each bake. For the purposes of this node, this would mostly apply to .uassets and not actors. """ return self._replace_previous_bake @property def delete_instantiated_asset_on_completion_or_failure(self): """ Whether or not to delete the instantiated asset after Complete is called. """ return self._delete_instantiated_asset_on_completion_or_failure def activate(self): """ Activate the process. This will: - instantiate houdini_asset and wrap it as asset_wrapper - call on_failure() for any immediate failures - otherwise bind to delegates from asset_wrapper so that the various self.on_*() functions are called as appropriate Returns immediately (does not block until cooking/processing is complete). Returns: (bool): False if activation failed. """ # Get the API instance houdini_api = unreal.HoudiniPublicAPIBlueprintLib.get_api() if not houdini_api: # Handle failures: this will unbind delegates and call on_failure() self._handle_on_failure() return False # Create an empty API asset wrapper self._asset_wrapper = unreal.HoudiniPublicAPIAssetWrapper.create_empty_wrapper(houdini_api) if not self._asset_wrapper: # Handle failures: this will unbind delegates and call on_failure() self._handle_on_failure() return False # Bind to the wrapper's delegates for instantiation, cooking, baking # etc events self._asset_wrapper.on_pre_instantiation_delegate.add_callable( self._handle_on_pre_instantiation) self._asset_wrapper.on_post_instantiation_delegate.add_callable( self._handle_on_post_instantiation) self._asset_wrapper.on_post_cook_delegate.add_callable( self._handle_on_post_auto_cook) self._asset_wrapper.on_pre_process_state_exited_delegate.add_callable( self._handle_on_pre_process) self._asset_wrapper.on_post_processing_delegate.add_callable( self._handle_on_post_processing) self._asset_wrapper.on_post_bake_delegate.add_callable( self._handle_on_post_auto_bake) # Begin the instantiation process of houdini_asset and wrap it with # self.asset_wrapper if not houdini_api.instantiate_asset_with_existing_wrapper( self.asset_wrapper, self.houdini_asset, self.instantiate_at, self.world_context_object, self.spawn_in_level_override, self.enable_auto_cook, self.enable_auto_bake, self.bake_directory_path, self.bake_method, self.remove_output_after_bake, self.recenter_baked_actors, self.replace_previous_bake): # Handle failures: this will unbind delegates and call on_failure() self._handle_on_failure() return False return True def _unbind_delegates(self): """ Unbinds from self.asset_wrapper's delegates (if valid). """ if not self._asset_wrapper: return self._asset_wrapper.on_pre_instantiation_delegate.add_callable( self._handle_on_pre_instantiation) self._asset_wrapper.on_post_instantiation_delegate.add_callable( self._handle_on_post_instantiation) self._asset_wrapper.on_post_cook_delegate.add_callable( self._handle_on_post_auto_cook) self._asset_wrapper.on_pre_process_state_exited_delegate.add_callable( self._handle_on_pre_process) self._asset_wrapper.on_post_processing_delegate.add_callable( self._handle_on_post_processing) self._asset_wrapper.on_post_bake_delegate.add_callable( self._handle_on_post_auto_bake) def _check_wrapper(self, wrapper): """ Checks that wrapper matches self.asset_wrapper. Logs a warning if it does not. Args: wrapper (HoudiniPublicAPIAssetWrapper): the wrapper to check against self.asset_wrapper Returns: (bool): True if the wrappers match. """ if wrapper != self._asset_wrapper: unreal.log_warning( '[UHoudiniPublicAPIProcessHDANode] Received delegate event ' 'from unexpected asset wrapper ({0} vs {1})!'.format( self._asset_wrapper.get_name() if self._asset_wrapper else '', wrapper.get_name() if wrapper else '' ) ) return False return True def _handle_on_failure(self): """ Handle any failures during the lifecycle of the process. Calls self.on_failure() and then unbinds from self.asset_wrapper and optionally deletes the instantiated asset. """ self.on_failure() self._unbind_delegates() if self.delete_instantiated_asset_on_completion_or_failure and self.asset_wrapper: self.asset_wrapper.delete_instantiated_asset() def _handle_on_complete(self): """ Handles completion of the process. This can happen at one of three stages: - After on_post_instantiate(), if enable_auto_cook is False. - After on_post_auto_cook(), if enable_auto_cook is True but enable_auto_bake is False. - After on_post_auto_bake(), if both enable_auto_cook and enable_auto_bake are True. Calls self.on_complete() and then unbinds from self.asset_wrapper's delegates and optionally deletes the instantiated asset. """ self.on_complete() self._unbind_delegates() if self.delete_instantiated_asset_on_completion_or_failure and self.asset_wrapper: self.asset_wrapper.delete_instantiated_asset() def _handle_on_pre_instantiation(self, wrapper): """ Called during pre_instantiation. Sets ``parameters`` on the HDA and calls self.on_pre_instantiation(). """ if not self._check_wrapper(wrapper): return # Set any parameters specified for the HDA if self.asset_wrapper and self.parameters: self.asset_wrapper.set_parameter_tuples(self.parameters) self.on_pre_instantiation() def _handle_on_post_instantiation(self, wrapper): """ Called during post_instantiation. Sets inputs (``node_inputs`` and ``parameter_inputs``) on the HDA and calls self.on_post_instantiation(). Completes execution if enable_auto_cook is False. """ if not self._check_wrapper(wrapper): return # Set any inputs specified when the node was created if self.asset_wrapper: if self.node_inputs: self.asset_wrapper.set_inputs_at_indices(self.node_inputs) if self.parameter_inputs: self.asset_wrapper.set_input_parameters(self.parameter_inputs) self.on_post_instantiation() # If not set to auto cook, complete execution now if not self.enable_auto_cook: self._handle_on_complete() def _handle_on_post_auto_cook(self, wrapper, cook_success): """ Called during post_cook. Sets self.cook_success and calls self.on_post_auto_cook(). Args: cook_success (bool): True if the cook was successful. """ if not self._check_wrapper(wrapper): return self._cook_success = cook_success self.on_post_auto_cook(cook_success) def _handle_on_pre_process(self, wrapper): """ Called during pre_process. Calls self.on_pre_process(). """ if not self._check_wrapper(wrapper): return self.on_pre_process() def _handle_on_post_processing(self, wrapper): """ Called during post_processing. Calls self.on_post_processing(). Completes execution if enable_auto_bake is False. """ if not self._check_wrapper(wrapper): return self.on_post_processing() # If not set to auto bake, complete execution now if not self.enable_auto_bake: self._handle_on_complete() def _handle_on_post_auto_bake(self, wrapper, bake_success): """ Called during post_bake. Sets self.bake_success and calls self.on_post_auto_bake(). Args: bake_success (bool): True if the bake was successful. """ if not self._check_wrapper(wrapper): return self._bake_success = bake_success self.on_post_auto_bake(bake_success) self._handle_on_complete() def on_failure(self): """ Called if the process fails to instantiate or fails to start a cook. Subclasses can override this function implement custom functionality. """ pass def on_complete(self): """ Called if the process completes instantiation, cook and/or baking, depending on enable_auto_cook and enable_auto_bake. Subclasses can override this function implement custom functionality. """ pass def on_pre_instantiation(self): """ Called during pre_instantiation. Subclasses can override this function implement custom functionality. """ pass def on_post_instantiation(self): """ Called during post_instantiation. Subclasses can override this function implement custom functionality. """ pass def on_post_auto_cook(self, cook_success): """ Called during post_cook. Subclasses can override this function implement custom functionality. Args: cook_success (bool): True if the cook was successful. """ pass def on_pre_process(self): """ Called during pre_process. Subclasses can override this function implement custom functionality. """ pass def on_post_processing(self): """ Called during post_processing. Subclasses can override this function implement custom functionality. """ pass def on_post_auto_bake(self, bake_success): """ Called during post_bake. Subclasses can override this function implement custom functionality. Args: bake_success (bool): True if the bake was successful. """ pass
import unreal import importlib from Lib import __lib_topaz__ as topaz from Lib import __lib_stelle__ as stelle importlib.reload(topaz) importlib.reload(stelle) __all__ = ['get_all_leveL_actors','assetValidator','bulk_renamer','spine_breaker','unused_asset_notifier'] def get_all_leveL_actors() -> list[unreal.Actor]: #리스트로 선택된 액터 리턴 actors = unreal.EditorLevelLibrary.get_all_level_actors() return actors def assetValidator(folder_path : str) -> list[str] : #Returns a list of assets that are too long need_to_return = [] assets = topaz.get_assets_in_folder(folder_path) for asset in assets: file_len = len(asset) if file_len > 235 : need_to_return.append(asset) print('Asset Name : ' + asset + ' is too long. Please rename it.' + ' Length : ' + str(file_len) ) return need_to_return def bulk_renamer(asset_path_list : str) -> None: for i in asset_path_list: #print(i) if '_BaseColor' in i: newName = i.replace('_BaseColor','_D') elif '_Normal' in i: newName = i.replace('_Normal','_N') elif '_OcclusionRoughnessMetallic' in i: newName = i.replace('_OcclusionRoughnessMetallic','_ORM') else: newName = i unreal.EditorAssetLibrary.rename_asset(i,newName) print('Renamed ' + i + ' to ' + newName) def spine_breaker(): all_actors = get_all_leveL_actors() for actor in all_actors: if actor.get_class() == unreal.StaticMeshActor() : print('staticmeshactor') elif actor.get_class() == unreal.blueprint() : print('blueprint') #spine_breaker(topaz.get_selected_level_actor()) def unused_asset_notifier(workingPath : str) -> list[str]: #검증 덜됨 need_to_return = [] @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass editorAssetLib = GetEditorAssetLibrary(); allAssets = editorAssetLib.list_assets(workingPath, True, False) if (len(allAssets) > 0): for asset in allAssets: deps = editorAssetLib.find_package_referencers_for_asset(asset, False) if (len(deps) == 0): print (">>>%s" % asset) need_to_return.append(asset) return need_to_return def get_all_textures_in_folder (working_path : str) -> list[unreal.Texture2D]: need_to_return = [] @unreal.uclass() class GetEditorAssetLibrary(unreal.EditorAssetLibrary): pass editorAssetLib = GetEditorAssetLibrary(); allAssets : list[str] = editorAssetLib.list_assets(working_path, True, False) if (len(allAssets) > 0): for asset in allAssets: loaded_asset = editorAssetLib.load_asset(asset) #print(loaded_asset.__class__) if loaded_asset.__class__ == unreal.Texture2D: #print('yes') need_to_return.append(loaded_asset) print(str(len(need_to_return)) + ' textures found') return need_to_return ## Todo : get only Selected Sublevel actors def get_actors_selected_sublevel () -> list[unreal.Actor]: ## WIP selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors() return selected_actors ###Initialised message when loaded ### unreal.log('archeron initialised...')
import unreal import argparse import json def get_scriptstruct_by_node_name(node_name): control_rig_blueprint = unreal.load_object(None, '/project/') rig_vm_graph = control_rig_blueprint.get_model() nodes = rig_vm_graph.get_nodes() for node in nodes: if node.get_node_path() == node_name: return node.get_script_struct() last_construction_link = 'PrepareForExecution' def create_construction(bone_name): global last_construction_link control_name = bone_name + '_ctrl' get_bone_transform_node_name = "RigUnit_Construction_GetTransform_" + bone_name set_control_transform_node_name = "RigtUnit_Construction_SetTransform_" + control_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(137.732236, -595.972187), get_bone_transform_node_name) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_bone_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.bInitial', 'True') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Type', 'Bone', True) rig_controller.set_node_selection([get_bone_transform_node_name]) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(526.732236, -608.972187), set_control_transform_node_name) except Exception as e: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(526.732236, -608.972187), set_control_transform_node_name) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_control_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bInitial', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Type', 'Control', True) try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Value') except: try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py, line 45: rig_controller.add_link(): " + str(e)) rig_controller.set_node_position_by_name(set_control_transform_node_name, unreal.Vector2D(512.000000, -656.000000)) rig_controller.add_link(last_construction_link + '.ExecuteContext', set_control_transform_node_name + '.ExecuteContext') last_construction_link = set_control_transform_node_name last_backward_solver_link = 'InverseExecution.ExecuteContext' def create_backward_solver(bone_name): global last_backward_solver_link control_name = bone_name + '_ctrl' get_bone_transform_node_name = "RigUnit_BackwardSolver_GetTransform_" + bone_name set_control_transform_node_name = "RigtUnit_BackwardSolver_SetTransform_" + control_name #rig_controller.add_link('InverseExecution.ExecuteContext', 'RigUnit_SetTransform_3.ExecuteContext') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-636.574629, -1370.167943), get_bone_transform_node_name) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_bone_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Type', 'Bone', True) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(-190.574629, -1378.167943), set_control_transform_node_name) except: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(-190.574629, -1378.167943), set_control_transform_node_name) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_control_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bInitial', 'False') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Type', 'Control', True) #rig_controller.set_pin_default_value(set_control_transform_node_name + '.Transform', '(Rotation=(X=0.000000,Y=0.000000,Z=0.000000,W=-1.000000),Translation=(X=0.551784,Y=-0.000000,Z=72.358307),Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))', True) try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Value') except: try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py, line 84: rig_controller.add_link(): " + str(e)) rig_controller.add_link(last_backward_solver_link, set_control_transform_node_name + '.ExecuteContext') last_backward_solver_link = set_control_transform_node_name + '.ExecuteContext' def create_control(bone_name): control_name = bone_name + '_ctrl' default_setting = unreal.RigControlSettings() default_setting.shape_name = 'Box_Thin' default_setting.control_type = unreal.RigControlType.EULER_TRANSFORM default_value = hierarchy.make_control_value_from_euler_transform( unreal.EulerTransform(scale=[1, 1, 1])) key = unreal.RigElementKey(type=unreal.RigElementType.BONE, name=bone_name) rig_control_element = hierarchy.find_control(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name)) control_key = rig_control_element.get_editor_property('key') print(rig_control_element) if control_key.get_editor_property('name') != "": control_key = rig_control_element.get_editor_property('key') else: try: control_key = hierarchy_controller.add_control(control_name, unreal.RigElementKey(), default_setting, default_value, True, True) except: control_key = hierarchy_controller.add_control(control_name, unreal.RigElementKey(), default_setting, default_value, True) transform = hierarchy.get_global_transform(key, True) hierarchy.set_control_offset_transform(control_key, transform, True) if bone_name in control_list: create_direct_control(bone_name) elif bone_name in effector_list: create_effector(bone_name) create_construction(bone_name) create_backward_solver(bone_name) effector_get_transform_widget_height = 0 def create_direct_control(bone_name): global next_forward_execute global effector_get_transform_widget_height #effector_get_transform_widget_height += 250 control_name = bone_name + '_ctrl' get_control_transform_node_name = "RigUnit_DirectControl_GetTransform_" + bone_name set_bone_transform_node_name = "RigtUnit_DirectControl_SetTransform_" + control_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(101.499447, -244.500249), get_control_transform_node_name) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_control_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Type', 'Control', True) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) except: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_bone_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bInitial', 'False') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Type', 'Bone', True) try: rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Value') except: try: rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py: rig_controller.add_Link(): " + str(e)) rig_controller.add_link(next_forward_execute, set_bone_transform_node_name + '.ExecuteContext') next_forward_execute = set_bone_transform_node_name + '.ExecuteContext' # def create_preferred_angle_control(bone_name): # global next_forward_execute # global effector_get_transform_widget_height # #effector_get_transform_widget_height += 250 # control_name = bone_name + '_ctrl' # get_control_transform_node_name = "RigUnit_PreferredAngle_GetTransform_" + bone_name # set_bone_transform_node_name = "RigtUnit_PreferredAngle_SetTransform_" + control_name # rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(101.499447, -244.500249), get_control_transform_node_name) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item', '(Type=Bone)') # rig_controller.set_pin_expansion(get_control_transform_node_name + '.Item', True) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Space', 'GlobalSpace') # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Name', control_name, True) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Type', 'Control', True) # try: # rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) # except: # set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") # rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item', '(Type=Bone,Name="None")') # rig_controller.set_pin_expansion(set_bone_transform_node_name + '.Item', False) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Space', 'GlobalSpace') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bInitial', 'False') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Weight', '1.000000') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bPropagateToChildren', 'True') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Name', bone_name, True) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Type', 'Bone', True) # try: # rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Value') # except: # try: # rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Transform') # except Exception as e: # print("ERROR: CreateControlRig.py: rig_controller.add_Link(): " + str(e)) # rig_controller.add_link(next_forward_execute, set_bone_transform_node_name + '.ExecuteContext') # next_forward_execute = set_bone_transform_node_name + '.ExecuteContext' def create_effector(bone_name): global effector_get_transform_widget_height effector_get_transform_widget_height += 250 control_name = bone_name + '_ctrl' get_transform_name = control_name + '_RigUnit_GetTransform' pin_name = rig_controller.insert_array_pin('PBIK.Effectors', -1, '') print(pin_name) rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-122.733358, effector_get_transform_widget_height), get_transform_name) rig_controller.set_pin_default_value(get_transform_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_transform_name + '.Item', True) rig_controller.set_pin_default_value(get_transform_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_transform_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(get_transform_name + '.Item.Type', 'Control', True) rig_controller.set_node_selection([get_transform_name]) rig_controller.add_link(get_transform_name + '.Transform', pin_name + '.Transform') rig_controller.set_pin_default_value(pin_name + '.Bone', bone_name, False) if(bone_name in guide_list): rig_controller.set_pin_default_value(pin_name + '.StrengthAlpha', '0.200000', False) parser = argparse.ArgumentParser(description = 'Creates a Control Rig given a SkeletalMesh') parser.add_argument('--skeletalMesh', help='Skeletal Mesh to Use') parser.add_argument('--dtuFile', help='DTU File to use') args = parser.parse_args() asset_name = args.skeletalMesh.split('.')[1] + '_CR' package_path = args.skeletalMesh.rsplit('/', 1)[0] blueprint = unreal.load_object(name = package_path + '/' + asset_name , outer = None) if not blueprint: blueprint = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=asset_name, package_path=package_path, asset_class=unreal.ControlRigBlueprint, factory=unreal.ControlRigBlueprintFactory()) #blueprint = unreal.load_object(name = '/project/.NewControlRigBlueprint', outer = None) if blueprint: # Turn off notifications or each change will compile the RigVM blueprint.suspend_notifications(True) library = blueprint.get_local_function_library() library_controller = blueprint.get_controller(library) hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() rig_controller = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() #rig_controller.set_node_selection(['RigUnit_BeginExecution']) hierarchy_controller.import_bones_from_asset(args.skeletalMesh, 'None', True, False, True) # Remove Existing Nodes graph = rig_controller.get_graph() node_count = len(graph.get_nodes()) while node_count > 0: rig_controller.remove_node(graph.get_nodes()[-1]) node_count = node_count - 1 # Create Full Body IK Node rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_BeginExecution', 'Execute', unreal.Vector2D(22.229613, 60.424645), 'BeginExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PrepareForExecution', 'Execute', unreal.Vector2D(-216.659278, -515.130927), 'PrepareForExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_InverseExecution', 'Execute', unreal.Vector2D(-307.389434, -270.395477), 'InverseExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PBIK', 'Execute', unreal.Vector2D(370.599976, 42.845032), 'PBIK') rig_controller.set_pin_default_value('PBIK.Settings', '(Iterations=20,MassMultiplier=1.000000,MinMassMultiplier=0.200000,bStartSolveFromInputPose=True)') rig_controller.set_pin_expansion('PBIK.Settings', False) rig_controller.set_pin_default_value('PBIK.Debug', '(DrawScale=1.000000)') rig_controller.set_pin_expansion('PBIK.Debug', False) rig_controller.set_node_selection(['PBIK']) rig_controller.set_pin_default_value('PBIK.Root', 'hip', False) rig_controller.insert_array_pin('PBIK.BoneSettings', -1, '') rig_controller.set_pin_default_value('PBIK.BoneSettings.0.Bone', 'pelvis', False) rig_controller.set_pin_default_value('PBIK.BoneSettings.0.RotationStiffness', '0.900000', False) rig_controller.set_pin_default_value('PBIK.BoneSettings.0.PositionStiffness', '0.900000', False) next_forward_execute = 'BeginExecution.ExecuteContext' #rig_controller.add_link('BeginExecution.ExecuteContext', 'PBIK.ExecuteContext') # Get Bone list for character dtu_data = json.load(open(args.dtuFile.replace('\"', ''))) limits = dtu_data['LimitData'] bones_in_dtu = ['root'] for bone_limits in limits.values(): bone_limit_name = bone_limits[0] #print(bone_limit_name) bones_in_dtu.append(bone_limit_name) # Create Effectors, order matters. Child controls should be after Parent Control effector_list = ['pelvis', 'l_foot', 'r_foot', 'spine4', 'l_hand', 'r_hand'] # G9 effector_list+= ['chestUpper', 'head', 'lFoot', 'rFoot', 'lHand', 'rHand'] #G8 effector_list = [bone for bone in effector_list if bone in bones_in_dtu] #print(effector_list) # These controls are mid chain and don't have full weight guide_list = ['l_shin', 'r_shin', 'l_forearm', 'r_forearm'] # G9 guide_list+= ['lShin', 'rShin', 'lForearmBend', 'rForearmBend'] # G8 guide_list = [bone for bone in guide_list if bone in bones_in_dtu] # These controls are for bones that shouldn't move much on their own, but user can rotate them suggested_rotation_list = ['l_shoulder', 'r_shoulder'] # G9 suggested_rotation_list+= ['lCollar', 'rCollar'] # G8 suggested_rotation_list = [bone for bone in suggested_rotation_list if bone in bones_in_dtu] # This is for controls outside of Full Body IK control_list = ['root', 'hip'] control_list = [bone for bone in control_list if bone in bones_in_dtu] for effector_name in control_list + effector_list + guide_list: create_control(effector_name) parent_list = { 'root':['hip', 'l_foot', 'r_foot', 'l_shin', 'r_shin', 'lFoot', 'rFoot', 'lShin', 'rShin'], 'hip':['pelvis'], 'pelvis':['spine4', 'chestUpper'], 'spine4':['head', 'l_hand', 'r_hand', 'l_forearm', 'r_forearm'], 'chestUpper':['head', 'lHand', 'rHand', 'lForearmBend', 'rForearmBend'] } for parent_bone, child_bone_list in parent_list.items(): if not parent_bone in bones_in_dtu: continue filtered_child_bone_list = [bone for bone in child_bone_list if bone in bones_in_dtu] for child_bone in child_bone_list: hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name= child_bone + '_ctrl'), unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name= parent_bone + '_ctrl'), True) hierarchy.set_local_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=child_bone + '_ctrl'), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,-0.000000],scale=[1.000000,1.000000,1.000000]), True, True) skeletal_mesh = unreal.load_object(name = args.skeletalMesh, outer = None) skeletal_mesh_import_data = skeletal_mesh.get_editor_property('asset_import_data') skeletal_mesh_force_front_x = skeletal_mesh_import_data.get_editor_property('force_front_x_axis') stiff_limits = ['l_shoulder', 'r_shoulder'] stiff_limits+= ['lCollar', 'rCollar'] exclude_limits = ['root', 'hip', 'pelvis'] for bone_limits in limits.values(): # Get the name of the bone bone_limit_name = bone_limits[0] # Add twist bones to the exlude list if 'twist' in bone_limit_name.lower(): exluded_bone_settings = rig_controller.insert_array_pin('PBIK.ExcludedBones', -1, '') rig_controller.set_pin_default_value(exluded_bone_settings, bone_limit_name, False) # Get the bone limits bone_limit_x_min = bone_limits[2] bone_limit_x_max = bone_limits[3] bone_limit_y_min = bone_limits[4] * -1.0 bone_limit_y_max = bone_limits[5] * -1.0 bone_limit_z_min = bone_limits[6] * -1.0 bone_limit_z_max = bone_limits[7] * -1.0 # update the axis if force front was used (facing right) if skeletal_mesh_force_front_x: bone_limit_y_min = bone_limits[2] * -1.0 bone_limit_y_max = bone_limits[3] * -1.0 bone_limit_z_min = bone_limits[4] * -1.0 bone_limit_z_max = bone_limits[5] * -1.0 bone_limit_x_min = bone_limits[6] bone_limit_x_max = bone_limits[7] if not bone_limit_name in exclude_limits: #if not bone_limit_name == "l_shin": continue limit_bone_settings = rig_controller.insert_array_pin('PBIK.BoneSettings', -1, '') rig_controller.set_pin_default_value(limit_bone_settings + '.Bone', bone_limit_name, False) x_delta = abs(bone_limit_x_max - bone_limit_x_min) y_delta = abs(bone_limit_y_max - bone_limit_y_min) z_delta = abs(bone_limit_z_max - bone_limit_z_min) if(x_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Locked', False) elif (x_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Free', False) if(y_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Locked', False) elif (y_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Free', False) if(z_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Locked', False) elif (z_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Free', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Limited', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Limited', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Limited', False) # It feels like Min\Max angel aren't the actual extents, but the amount of rotation allowed. So they shoudl be 0 to abs(min, max) # I think there's a bug if a min rotation is more negative than max is positive, the negative gets clamped to the relative positive. rig_controller.set_pin_default_value(limit_bone_settings + '.MinX', str(min(bone_limit_x_max, bone_limit_x_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxX', str(max(bone_limit_x_max, abs(bone_limit_x_min))), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MinY', str(min(bone_limit_y_max, bone_limit_y_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxY', str(max(bone_limit_y_max, abs(bone_limit_y_min))), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MinZ', str(min(bone_limit_z_max, bone_limit_z_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxZ', str(max(bone_limit_z_max, abs(bone_limit_z_min))), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinX', str(min(bone_limit_z_max, bone_limit_z_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxX', str(max(bone_limit_z_max, bone_limit_z_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinY', str(min(bone_limit_x_max, bone_limit_x_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxY', str(max(bone_limit_x_max, bone_limit_x_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinZ', str(min(bone_limit_y_max, bone_limit_y_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxZ', str(max(bone_limit_y_max, bone_limit_y_min)), False) if bone_limit_name in stiff_limits: rig_controller.set_pin_default_value(limit_bone_settings + '.PositionStiffness', '0.800000', False) rig_controller.set_pin_default_value(limit_bone_settings + '.RotationStiffness', '0.800000', False) # Figure out preferred angles, the primary angle is the one that turns the furthest from base pose rig_controller.set_pin_default_value(limit_bone_settings + '.bUsePreferredAngles', 'true', False) x_max_rotate = max(abs(bone_limit_x_min), abs(bone_limit_x_max)) y_max_rotate = max(abs(bone_limit_y_min), abs(bone_limit_y_max)) z_max_rotate = max(abs(bone_limit_z_min), abs(bone_limit_z_max)) #print(bone_limit_name, x_max_rotate, y_max_rotate, z_max_rotate) if bone_limit_name in suggested_rotation_list: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', "0.0", False) rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', "0.0", False) rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', "0.0", False) create_control(bone_limit_name) to_euler_name = "Preferred_Angles_To_Euler_" + bone_limit_name get_transform_name = "Preferred_Angles_GetRotator_" + bone_limit_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetControlRotator', 'Execute', unreal.Vector2D(-344.784477, 4040.400172), get_transform_name) rig_controller.set_pin_default_value(get_transform_name + '.Space', 'GlobalSpace') #rig_controller.set_pin_default_value(get_transform_name + '.bInitial', 'False') rig_controller.set_pin_default_value(get_transform_name + '.Control', bone_limit_name + '_ctrl', True) #rig_controller.set_pin_default_value(get_transform_name + '.Item.Type', 'Control', True) #rig_controller.add_unit_node_from_struct_path('/project/.RigVMFunction_MathQuaternionToEuler', 'Execute', unreal.Vector2D(9.501237, 4176.400172), to_euler_name) #rig_controller.add_link(get_transform_name + '.Transform.Rotation', to_euler_name + '.Value') rig_controller.add_link(get_transform_name + '.Rotator.Roll', limit_bone_settings + '.PreferredAngles.X') rig_controller.add_link(get_transform_name + '.Rotator.Pitch', limit_bone_settings + '.PreferredAngles.Y') rig_controller.add_link(get_transform_name + '.Rotator.Yaw', limit_bone_settings + '.PreferredAngles.Z') else: limit_divider = 1.0 if x_max_rotate > y_max_rotate and x_max_rotate > z_max_rotate: if abs(bone_limit_x_min) > abs(bone_limit_x_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', str(bone_limit_x_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', str(bone_limit_x_max / limit_divider), False) if y_max_rotate > x_max_rotate and y_max_rotate > z_max_rotate: if abs(bone_limit_y_min) > abs(bone_limit_y_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', str(bone_limit_y_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', str(bone_limit_y_max / limit_divider), False) if z_max_rotate > x_max_rotate and z_max_rotate > y_max_rotate: if abs(bone_limit_z_min) > abs(bone_limit_z_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', str(bone_limit_z_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', str(bone_limit_z_max / limit_divider), False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.Bone', 'pelvis', False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.RotationStiffness', '0.900000', False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.PositionStiffness', '0.900000', False) # Attach the node to execute rig_controller.add_link(next_forward_execute, 'PBIK.ExecuteContext') unreal.ControlRigBlueprintLibrary.set_preview_mesh(blueprint, skeletal_mesh) # Turn on notifications and force a recompile blueprint.suspend_notifications(False) unreal.ControlRigBlueprintLibrary.recompile_vm(blueprint) #rig_controller.add_link('RigUnit_BeginExecution.ExecuteContext', 'PBIK.ExecuteContext')
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 """
# Copyright Epic Games, Inc. All Rights Reserved. import os import unreal import flow.cmd from peafour import P4 import subprocess as sp from pathlib import Path #------------------------------------------------------------------------------- class _Collector(object): def __init__(self): self._dirs = [] self._careful_dirs = [] self._pinned_files = set() def get_pinned_count(self): return len(self._pinned_files) def add_dir(self, path, *, remove_carefully=False): (self._careful_dirs if remove_carefully else self._dirs).append(path) def pin_file(self, path): path = str(path.resolve()) self._pinned_files.add(path.lower()) def read_careful_dirs(self): return (x for x in self._careful_dirs) def dispatch(self, actuator): actuator.begin() for dir in self._dirs: actuator.remove_dir(dir) for dir in self._careful_dirs: for item in (x for x in dir.rglob("*") if x.is_file()): key = str(item.resolve()).lower() if key not in self._pinned_files: actuator.remove_file(item) actuator.end() #------------------------------------------------------------------------------- class _DryRun(object): def _spam(self): mb_size = format(self._bytes // 1024 // 1024, ",") + "MB" print("%d files to remove (%s)" % (self._count, mb_size), end="\r") def begin(self): self._bytes = 0 self._count = 0 self._breakdown = {} def remove_dir(self, path): for item in (x for x in path.rglob("*") if x.is_file()): self.remove_file(item) def remove_file(self, path): self._bytes += path.stat().st_size self._count += 1 if self._count % 493: self._spam() def end(self): self._spam() print() #------------------------------------------------------------------------------- class _Cleaner(object): def __init__(self, work_dir): self._work_dir = work_dir def __del__(self): if self._dir_count: print(f"Launching background rmdir for {self._rubbish_dir}") else: print("Skipping background rmdir. No major directories to remove") if os.name == "nt": sp.Popen( ("cmd.exe", "/c", "rd", "/project/", str(self._rubbish_dir)), stdout=sp.DEVNULL, stderr=sp.DEVNULL ) pass else: if self._rubbish_dir.is_dir() and self._rubbish_dir != "/": # paranoia! sp.Popen( ("rm", "-rf", str(self._rubbish_dir)), stdout=sp.DEVNULL, stderr=sp.DEVNULL) def _spam(self): print(f"Moved {self._dir_count} directories, {self._file_count} files removed", end="\r", flush=True) def begin(self): rubbish_dir = self._work_dir / ".ushell_clean" rubbish_dir.mkdir(parents=True, exist_ok=True) self._rubbish_dir = rubbish_dir self._dir_count = 0 self._file_count = 0 print(f"Moving directories to {self._rubbish_dir.name} and removing unversioned files") def remove_dir(self, path): dest_name = "%08x_%016x_%s_%s" % (os.getpid(), id(path), path.parent.name, path.name) try: path.rename(str(self._rubbish_dir / dest_name)) self._dir_count += 1 self._spam() except OSError as e: print("WARNING:", e) def remove_file(self, item): item.chmod(0o666) item.unlink() self._file_count += 1 self._spam() def end(self): if self._file_count or self._dir_count: print() #------------------------------------------------------------------------------- class Clean(flow.cmd.Cmd): """ Cleans intermediate and temporary files from an Unreal Engine branch. The following sub-directories of .uproject, .uplugin, and Engine/ are cleaned up; Intermediate - Removed entirely DerivedDataCache - Removed entirely Binaries - Unversioned files are removed Saved - All sub-directories except --savedkeeps=... (see below) Only a subset of sub-directories of Saved/ are removed. Any directories that match --savedkeeps's comma-separated list are not removed. For example, to clean everything excepted Saved/StagedBuilds/ and Saved/Profiling/; .p4 clean --savedkeeps=StagedBuilds,Profiling "StagedBuilds,Profiling" is the default value for --savedkeeps. If --allsaved is given then all of Saved/ will be removed. Note that the removal happens in two stages. First directories are moved into .ushell_clean/ in the root of the branch. This directory is then removed in the background after `.p4 clean` exits.""" dryrun = flow.cmd.Opt(False, "Do nothing except reports statistics") allsaved = flow.cmd.Opt(False, "Completely clean Saved/ directories") savedkeeps = flow.cmd.Opt("Profiling,StagedBuilds", "Comma-separated list of Saved/ sub-directories to keep") def _append_saved(self, collector, saved_dir): if self.args.allsaved: collector.add_dir(saved_dir) return for sub_dir in (x for x in saved_dir.glob("*") if x.is_dir()): if sub_dir.name.lower() not in self._saved_keeps: collector.add_dir(sub_dir) def _detect_locked_files(self, root_dir): proc = sp.Popen( ("wmic.exe", "process", "get", "executablepath"), stdout=sp.PIPE, stderr=sp.DEVNULL ) ret = False for line in proc.stdout.readlines(): line = line.strip().decode() if line and Path(line).parent.is_relative_to(root_dir): ret = line break proc.stdout.close() proc.wait() return ret def main(self): self._saved_keeps = {x.strip().lower() for x in self.args.savedkeeps.split(",")} ue_context = unreal.Context(os.getcwd()) branch = ue_context.get_branch(must_exist=True) engine_dir = ue_context.get_engine().get_dir() if os.name == "nt": self.print_info("Checking running processes") if running_exe := self._detect_locked_files(branch.get_dir()): raise RuntimeError(f"Not cleaning because '{running_exe}' is running") return False self.print_info("Finding directories and files to clean") root_dirs = [ engine_dir, *(x for x in engine_dir.glob("Programs/*") if x.is_dir()), ] print("Enumerating...", end="") rg_args = ( "rg", "--files", "--path-separator=/", "--no-ignore", "-g*.uplugin", "-g*.uproject", str(branch.get_dir()), ) rg = sp.Popen(rg_args, stdout=sp.PIPE, stderr=sp.DEVNULL) for line in rg.stdout.readlines(): path = Path(line.decode().rstrip()).parent root_dirs.append(path) rg.wait() print("\r", len(root_dirs), " uproject/uplugin roots found", sep="") collector = _Collector() clean_handlers = { "Intermediate" : lambda x,y: x.add_dir(y), "DerivedDataCache" : lambda x,y: x.add_dir(y), "Binaries" : lambda x,y: x.add_dir(y, remove_carefully=True), "Saved" : self._append_saved, } for root_dir in root_dirs: for dir_name, clean_handler in clean_handlers.items(): candidate = root_dir / dir_name if candidate.is_dir(): clean_handler(collector, candidate) # Ask Perforce which files shouldn't be deleted print("Asking Perforce what's synced...", end="", flush=True) specs = (str(x) + "/..." for x in collector.read_careful_dirs()) p4_have = P4.have(specs) for item in p4_have.read(on_error=False): path = Path(item.path) collector.pin_file(path) print("done (", collector.get_pinned_count(), " files)", sep="") if self.args.dryrun: collector.dispatch(_DryRun()) return self.print_info("Cleaning") actuator = _Cleaner(branch.get_dir()) collector.dispatch(actuator) #------------------------------------------------------------------------------- class Reset(flow.cmd.Cmd): """ Reconciles a branch to make it match the depot. Use with caution; this is a destructive action and involes removing and rewriting files! """ thorough = flow.cmd.Opt(False, "Compare digests instead of file-modified time") def _get_reset_paths(self): try: ue_context = unreal.Context(os.getcwd()) if not (branch := ue_context.get_branch()): return None except EnvironmentError: return None root_dir = branch.get_dir() ret = { # root_dir / "*", # to much scope to go wrong here and it's so few files root_dir / "Template/...", root_dir / "Engine/...", } for uproj_path in branch.read_projects(): ret.add(uproj_path.parent.absolute() / "...") return ret def main(self): # Confirm the user wants to really do a reset self.print_warning("Destructive action!") if self.is_interactive(): while True: c = input("Are you sure you want to continue [yn] ?") if c.lower() == "y": break if c.lower() == "n": return False # Run the reconcile args = ("reconcile", "-wade",) if not self.args.thorough: args = (*args, "--modtime") if reset_paths := self._get_reset_paths(): args = (*args, *(str(x) for x in reset_paths)) exec_context = self.get_exec_context() cmd = exec_context.create_runnable("p4", *args) return cmd.run()
""" Auto-report system for MagicOptimizer plugin. Sends issue reports to Cloudflare Worker endpoint for GitHub issue creation. """ import os import json import time from datetime import datetime from typing import Optional, Tuple, Dict, Any import sys try: import urllib.request import urllib.parse import urllib.error HTTP_AVAILABLE = True except ImportError: HTTP_AVAILABLE = False try: import unreal UE_AVAILABLE = True except ImportError: UE_AVAILABLE = False class AutoReporter: """Handles automatic issue reporting to Cloudflare Worker endpoint.""" def __init__(self, worker_url: str = None): """ Initialize the auto-reporter. Args: worker_url: Cloudflare Worker endpoint URL. If None, will try to get from environment. """ self.worker_url = worker_url or os.environ.get('MAGICOPTIMIZER_WORKER_URL') if not self.worker_url: # Default to a placeholder - should be configured via environment self.worker_url = "https://your-worker.your-subdomain.workers.dev/report" self.plugin_version = self._get_plugin_version() self.project_name = self._get_project_name() self.user_id = self._get_user_id() def _get_plugin_version(self) -> str: """Get the current plugin version.""" try: if UE_AVAILABLE and hasattr(unreal, 'MagicOptimizer'): # Try to get version from plugin module return getattr(unreal.MagicOptimizer, 'version', 'unknown') except Exception: pass # Fallback to environment or default return os.environ.get('MAGICOPTIMIZER_VERSION', '1.0.0') def _get_project_name(self) -> str: """Get the current project name.""" try: if UE_AVAILABLE and hasattr(unreal, 'Paths'): project_path = unreal.Paths.get_project_file_path() if project_path: return os.path.splitext(os.path.basename(project_path))[0] except Exception: pass # Fallback to environment or current directory return os.environ.get('MAGICOPTIMIZER_PROJECT', os.path.basename(os.getcwd())) def _get_user_id(self) -> str: """Get a user identifier (anonymized).""" try: if UE_AVAILABLE and hasattr(unreal, 'Paths'): # Use project saved directory as a stable identifier saved_dir = unreal.Paths.project_saved_dir() if saved_dir: # Create a hash of the project path for anonymity import hashlib return hashlib.md5(saved_dir.encode()).hexdigest()[:8] except Exception: pass # Fallback to environment or default return os.environ.get('MAGICOPTIMIZER_USER_ID', 'unknown') def _gather_system_info(self) -> Dict[str, Any]: """Gather system and environment information.""" info = { 'timestamp': datetime.now().isoformat(), 'plugin_version': self.plugin_version, 'project_name': self.project_name, 'user_id': self.user_id, 'platform': 'unknown', 'ue_version': 'unknown', 'python_version': f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}", } try: if UE_AVAILABLE: # Get UE version if hasattr(unreal, 'Engine'): info['ue_version'] = getattr(unreal.Engine, 'get_version', lambda: 'unknown')() # Get platform if hasattr(unreal, 'PlatformMisc'): info['platform'] = getattr(unreal.PlatformMisc, 'get_platform_name', lambda: 'unknown')() except Exception: pass return info def _gather_logs(self, max_lines: int = 1000) -> str: """Gather recent logs for the report.""" try: log_path = os.environ.get('MAGICOPTIMIZER_LOG') if not log_path or not os.path.exists(log_path): return "No log file available" with open(log_path, 'r', encoding='utf-8') as f: lines = f.readlines() # Get last N lines recent_lines = lines[-max_lines:] if len(lines) > max_lines else lines return ''.join(recent_lines) except Exception as e: return f"Error reading logs: {e}" def _gather_knowledge_data(self) -> Dict[str, Any]: """Gather knowledge base data if available.""" try: kb_dir = os.path.join( os.environ.get('MAGICOPTIMIZER_SAVED_DIR', 'Saved'), 'MagicOptimizer', 'Knowledge' ) if not os.path.exists(kb_dir): return {} data = {} # Get events.jsonl events_path = os.path.join(kb_dir, 'events.jsonl') if os.path.exists(events_path): with open(events_path, 'r', encoding='utf-8') as f: lines = f.readlines() data['recent_events'] = lines[-50:] if len(lines) > 50 else lines # Get any CSV files csv_files = [f for f in os.listdir(kb_dir) if f.endswith('.csv')] if csv_files: data['available_csvs'] = csv_files return data except Exception: return {} def send_error_report(self, error_type: str, error_message: str, context: str = "", include_logs: bool = True, include_knowledge: bool = True) -> Tuple[bool, str, Optional[str]]: """ Send an error report to the Cloudflare Worker. Args: error_type: Type/category of the error error_message: Detailed error message context: Additional context information include_logs: Whether to include log files include_knowledge: Whether to include knowledge base data Returns: Tuple of (success, message, issue_url) """ if not HTTP_AVAILABLE: return False, "HTTP libraries not available", None try: # Prepare the report data report_data = { 'type': 'error', 'error_type': error_type, 'error_message': error_message, 'context': context, 'system_info': self._gather_system_info() } # Add logs if requested if include_logs: report_data['logs'] = self._gather_logs() # Add knowledge data if requested if include_knowledge: report_data['knowledge'] = self._gather_knowledge_data() # Create multipart form data boundary = f"----MagicOptimizer{int(time.time())}" # Build the multipart payload payload_parts = [] # Add JSON metadata metadata = { 'title': f"[{error_type}] {error_message[:100]}...", 'description': f"**Error Type:** {error_type}\n\n**Error Message:** {error_message}\n\n**Context:** {context}\n\n**System Info:** {json.dumps(report_data['system_info'], indent=2)}", 'labels': ['auto-report', 'error', error_type.lower()], 'project': self.project_name, 'plugin_version': self.plugin_version } payload_parts.append(f"--{boundary}") payload_parts.append('Content-Disposition: form-data; name="metadata"') payload_parts.append('Content-Type: application/json') payload_parts.append("") payload_parts.append(json.dumps(metadata)) # Add full report data payload_parts.append(f"--{boundary}") payload_parts.append('Content-Disposition: form-data; name="report"') payload_parts.append('Content-Type: application/json') payload_parts.append("") payload_parts.append(json.dumps(report_data)) # Add logs as separate file if present if include_logs and 'logs' in report_data: payload_parts.append(f"--{boundary}") payload_parts.append('Content-Disposition: form-data; name="logs"; filename="plugin_logs.txt"') payload_parts.append('Content-Type: text/plain') payload_parts.append("") payload_parts.append(report_data['logs']) # Add knowledge data as separate file if present if include_knowledge and 'knowledge' in report_data: payload_parts.append(f"--{boundary}") payload_parts.append('Content-Disposition: form-data; name="knowledge"; filename="knowledge_data.json"') payload_parts.append('Content-Type: application/json') payload_parts.append("") payload_parts.append(json.dumps(report_data['knowledge'])) payload_parts.append(f"--{boundary}--") payload_parts.append("") # Join all parts payload = "\r\n".join(payload_parts).encode('utf-8') # Prepare the request headers = { 'Content-Type': f'multipart/form-data; boundary={boundary}', 'Content-Length': str(len(payload)), 'User-Agent': f'MagicOptimizer/{self.plugin_version}' } # Send the request req = urllib.request.Request( self.worker_url, data=payload, headers=headers, method='POST' ) with urllib.request.urlopen(req, timeout=30) as response: response_data = response.read().decode('utf-8') response_code = response.getcode() if response_code == 200: try: result = json.loads(response_data) if result.get('success'): issue_url = result.get('issue_url') return True, "Report sent successfully", issue_url else: return False, f"Worker error: {result.get('message', 'Unknown error')}", None except json.JSONDecodeError: return False, f"Invalid response from worker: {response_data}", None else: return False, f"HTTP {response_code}: {response_data}", None except urllib.error.URLError as e: return False, f"Network error: {e.reason}", None except urllib.error.HTTPError as e: return False, f"HTTP error {e.code}: {e.reason}", None except Exception as e: return False, f"Unexpected error: {e}", None def send_optimization_report(self, phase: str, profile: str, assets_processed: int, assets_modified: int, success: bool, duration_seconds: float, context: str = "") -> Tuple[bool, str, Optional[str]]: """ Send an optimization report to the Cloudflare Worker. Args: phase: Optimization phase (audit, recommend, apply, verify) profile: Profile used for optimization assets_processed: Number of assets processed assets_modified: Number of assets modified success: Whether the optimization was successful duration_seconds: How long the optimization took context: Additional context information Returns: Tuple of (success, message, issue_url) """ if not HTTP_AVAILABLE: return False, "HTTP libraries not available", None try: # Prepare the report data report_data = { 'type': 'optimization', 'phase': phase, 'profile': profile, 'assets_processed': assets_processed, 'assets_modified': assets_modified, 'success': success, 'duration_seconds': duration_seconds, 'context': context, 'system_info': self._gather_system_info() } # Create multipart form data boundary = f"----MagicOptimizer{int(time.time())}" # Build the multipart payload payload_parts = [] # Add JSON metadata status_emoji = "✅" if success else "❌" metadata = { 'title': f"{status_emoji} {phase.title()} Phase - {profile}", 'description': f"**Phase:** {phase}\n**Profile:** {profile}\n**Assets Processed:** {assets_processed}\n**Assets Modified:** {assets_modified}\n**Success:** {success}\n**Duration:** {duration_seconds:.2f}s\n\n**Context:** {context}\n\n**System Info:** {json.dumps(report_data['system_info'], indent=2)}", 'labels': ['auto-report', 'optimization', phase.lower(), profile.lower()], 'project': self.project_name, 'plugin_version': self.plugin_version } payload_parts.append(f"--{boundary}") payload_parts.append('Content-Disposition: form-data; name="metadata"') payload_parts.append('Content-Type: application/json') payload_parts.append("") payload_parts.append(json.dumps(metadata)) # Add full report data payload_parts.append(f"--{boundary}") payload_parts.append('Content-Disposition: form-data; name="report"') payload_parts.append('Content-Type: application/json') payload_parts.append("") payload_parts.append(json.dumps(report_data)) # Join all parts payload = "\r\n".join(payload_parts).encode('utf-8') # Prepare the request headers = { 'Content-Type': f'multipart/form-data; boundary={boundary}', 'Content-Length': str(len(payload)), 'User-Agent': f'MagicOptimizer/{self.plugin_version}' } # Send the request req = urllib.request.Request( self.worker_url, data=payload, headers=headers, method='POST' ) with urllib.request.urlopen(req, timeout=30) as response: response_data = response.read().decode('utf-8') response_code = response.getcode() if response_code == 200: try: result = json.loads(response_data) if result.get('success'): issue_url = result.get('issue_url') return True, "Report sent successfully", issue_url else: return False, f"Worker error: {result.get('message', 'Unknown error')}", None except json.JSONDecodeError: return False, f"Invalid response from worker: {response_data}", None else: return False, f"HTTP {response_code}: {response_data}", None except urllib.error.URLError as e: return False, f"Network error: {e.reason}", None except urllib.error.HTTPError as e: return False, f"HTTP error {e.code}: {e.reason}", None except Exception as e: return False, f"Unexpected error: {e}", None # Global instance _auto_reporter = None def get_auto_reporter() -> Optional[AutoReporter]: """Get the global auto-reporter instance.""" global _auto_reporter if _auto_reporter is None: _auto_reporter = AutoReporter() return _auto_reporter def send_error_report(error_type: str, error_message: str, context: str = "") -> Tuple[bool, str, Optional[str]]: """Convenience function to send an error report.""" reporter = get_auto_reporter() if reporter: return reporter.send_error_report(error_type, error_message, context) return False, "Auto-reporter not available", None def send_optimization_report(phase: str, profile: str, assets_processed: int, assets_modified: int, success: bool, duration_seconds: float, context: str = "") -> Tuple[bool, str, Optional[str]]: """Convenience function to send an optimization report.""" reporter = get_auto_reporter() if reporter: return reporter.send_optimization_report(phase, profile, assets_processed, assets_modified, success, duration_seconds, context) return False, "Auto-reporter not available", None
# coding: utf-8 import unreal import argparse parser = argparse.ArgumentParser() parser.add_argument("-rigSrc") parser.add_argument("-rigDst") args = parser.parse_args() #print(args.vrm) ###### ## rig 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); for aa in a: if (aa.get_editor_property("object_path") == args.rigSrc): rigSrc = aa.get_asset() if (aa.get_editor_property("object_path") == args.rigDst): rigDst = aa.get_asset() print(rigSrc) print(rigDst) modSrc = rigSrc.get_hierarchy_modifier() modDst = rigDst.get_hierarchy_modifier() conSrc = rigSrc.controller conDst = rigDst.controller graSrc = conSrc.get_graph() graDst = conDst.get_graph() modDst.initialize() print(rig[3]) meta = vv rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] h_mod = rig.get_hierarchy_modifier() elements = h_mod.get_selection() c = rig.controller g = c.get_graph() n = g.get_nodes() print(n) #c.add_branch_node() #c.add_array_pin() a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() print(a) # 配列ノード追加 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=Bone' in pin.get_default_value(): collectionItem_forBone= node if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = 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()) # bone array if (collectionItem_forBone == None): collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) ## h_mod rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] h_mod = rig.get_hierarchy_modifier() ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); 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 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) #print(bone_m) tmp = '(Type=Control,Name=' tmp += "{}".format(bone_h).lower() + '_c' tmp += ')' c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) #print(bone_h) #for e in h_mod.get_elements(): # 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) # print(e.name) # if (e.type == unreal.RigElementType.BONE): # tmp = '(Type=Bone,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) # print(e.name) #print(i.get_all_pins_recursively()) #ii:unreal.RigUnit_CollectionItems = n[1] #pp = ii.get_editor_property('Items') #print(pp) #print(collectionItem.get_all_pins_recursively()[0]) #i.get_editor_property("Items") #c.add_array_pin("Execute") # arrayを伸ばす #i.get_all_pins_recursively()[0].get_pin_path() #c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)') #rig = rigs[10]
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. import os import unreal # Required imports from deadline.unreal_submitter.submitter import ( UnrealRenderOpenJobSubmitter, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job import ( UgsRenderUnrealOpenJob, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_step import ( UgsRenderUnrealOpenJobStep, UnrealOpenJobStepParameterDefinition, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_environment import ( UgsLaunchEditorUnrealOpenJobEnvironment, UgsSyncCmfUnrealOpenJobEnvironment, ) from deadline.unreal_logger import get_logger logger = get_logger() # Add default location of predefined YAML templates to env to allow OpenJob entities # load them without declaring full path to templates if "OPENJD_TEMPLATES_DIRECTORY" not in os.environ: os.environ["OPENJD_TEMPLATES_DIRECTORY"] = ( f"{os.path.dirname(os.path.dirname(__file__))}" f"/project/" ) def main(): # Create Submitter for Render OpenJobs in silent mode (without UI notifications) render_job_submitter = UnrealRenderOpenJobSubmitter(silent_mode=True) # Get jobs from Render Queue or you can create your own queue = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem).get_queue() # From each MRQ job create Render Unreal OpenJob for job in queue.get_jobs(): default_render_job = UgsRenderUnrealOpenJob( # Set single Render step steps=[ UgsRenderUnrealOpenJobStep( extra_parameters=[ # Override ChunkSize parameter value UnrealOpenJobStepParameterDefinition("ChunkSize", "INT", [10]) ] ) ], # Set environments exactly in that order: # 1. Environment for syncing UGS workspace before render # 2. Environment for launch UE environments=[ UgsSyncCmfUnrealOpenJobEnvironment(), UgsLaunchEditorUnrealOpenJobEnvironment(), ], # Set MRQ Job to retrieve render data and OpenJob overrides from mrq_job=job, ) # Add Render Unreal OpenJob to submission queue render_job_submitter.add_job(default_render_job) # Sumit jobs and log their IDs submitted_job_ids = render_job_submitter.submit_jobs() for job_id in submitted_job_ids: logger.info(f"Job submitted: {job_id}") if __name__ == "__main__": main()
import unreal cameras: list[unreal.CameraActor] sorted_cameras = sorted(cameras, key=lambda camera: camera.get_actor_label().lower())
# 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()
import unreal import numpy as np import random import os import json import re import time NUM_VARIATIONS = 10 np.random.seed(None) def natural_sort_key(s): return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)] def get_candidate_blocks(bool_map, block_size): candidate_blocks = [] for i in range(bool_map.shape[0] - block_size): for j in range(bool_map.shape[1] - block_size): sub_map = bool_map[int(i - block_size / 2):int(i + block_size / 2), int(j - block_size / 2):int(j + block_size / 2)] if sub_map.shape[0] != 0 and sub_map.shape[1] != 0 and np.all(sub_map): candidate_blocks.append((i, j)) # print(f"Found empty space at ({i},{j})") return candidate_blocks def update_bool_map(bool_map, block_size, block_position, width=None, height=None): i, j = block_position assert bool_map[int(i - block_size / 2):int(i + block_size / 2), int(j - block_size / 2):int(j + block_size / 2)].all() bool_map[int(i - 2 * block_size / 2):int(i + 2 * block_size / 2), int(j - 2 * block_size / 2):int(j + 2 * block_size / 2)] = False return bool_map def define_offset_and_path(): offset = { 'mug': [ [[0, 0, 0, 1], [0, 0, 0]], # 0 [[0, 0, 0, 0.7], [0, 0, 0]], # 1 [[0, 0, 0, 0.05], [0, 0, 0]], # 2 [[0, 0, 0, 0.03], [0, 0, 0]], # 3 [[0, 0, 0, 0.0015], [0, 0, 0]], # 4 [[0, 0, 0, 0.6], [0, 0, 0]], # 5 [[0, 0, 0, 0.035], [0, 0, 0]], # 6 [[0, 0, 0, 0.02], [0, 0, 0]], # 7 [[0, 0, 0, 1], [0, 0, 0]], # 8 [[0, 0, 0, 0.5], [0, 0, 0]], # 9 ], 'apple': [ [[0, 0, 0, 0.6], [0, 0, 0]], # 0 [[0, 0, 0, 1], [0, 0, 0]], # 1 [[0, 0, 0, 0.15], [0, 0, 0]], # 2 [[0, 0, 0, 1], [0, 0, 0]], # 3 [[0, 0, 0, 1], [0, 0, 0]], # 4 [[0, 0, 0, 1], [0, 0, 0]], # 5 [[0, 0, 0, 0.03], [0, 0, 0]], # 6 [[0, 0, 0, 1], [0, 0, 0]], # 7 [[0, 0, 0, 0.001], [0, 0, 0]], # 8 [[0, 0, 0, 0.15], [0, 0, 0]], # 9 ], 'notebook': [ [[0, 0, 0, 0.05], [0, 0, 0]], # 0 [[0, 0, 0, 0.4], [0, 0, 0]], # 1 [[0, 0, 0, 1], [0, 0, 0]], # 2 [[0, 0, 0, 0.7], [0, 0, 0]], # 3 [[0, 0, 0, 0.5], [0, 0, 0]], # 4 [[0, 0, 0, 1], [0, 0, 0]], # 5 [[0, 0, 0, 0.5], [0, 0, 0]], # 6 [[0, 0, 0, 0.7], [0, 0, 0]], # 7 [[0, 0, 0, 0.8], [0, 0, 0]], # 8 [[0, 0, 0, 0.7], [0, 0, 0]], # 9 ], 'clock': [ [[0, 0, 0, 0.0007], [0, 0, 180]], # 0 [[0, 0, 0, 1], [0, 0, 0]], # 1 [[0, 0, 0, 0.03], [0, 0, 180]], # 2 [[0, 0, 0, 0.01], [0, 0, 0]], # 3 [[0, 0, 0, 0.5], [0, 0, 0]], # 4 [[0, 0, 0, 0.035], [0, 0, 180]], # 5 [[0, 0, 0, 0.9], [0, 0, 0]], # 6 [[0, 0, 0, 0.4], [0, 0, 90]], # 7 [[0, 0, 0, 6], [0, 0, 90]], # 8 [[0, 0, 0, 2], [0, 0, 90]], # 9 ] } # print(len(offset['notebook'])) for i in range(NUM_VARIATIONS): offset['notebook'][i][0] = [item * 1.5 for item in offset['notebook'][i][0]] objects = [ "mug", "notebook", "apple", ] father_path = "/project/" object_path_list = { 'mug': [], 'notebook': [], 'apple': [] } for this_object in objects: object_root = father_path + this_object for i in range(NUM_VARIATIONS): object_path = object_root + "/" + "variation" + str(i) + "/" + this_object + str(i) + "." + this_object + str(i) object_path_list[this_object].append(object_path) return objects, object_path_list, offset def get_object_actor_dict(objects, actors): object_actor_dict = {} for object in objects: object_actor_dict[object] = {} for actor in actors: if actor.get_actor_label()[:-1] in objects: for object in objects: if object in actor.get_actor_label(): object_actor_dict[object][actor.get_actor_label()] = actor return object_actor_dict def main(): # time.sleep(120) objects, object_path_list, offset = define_offset_and_path() save_path = "/project/" obj_rest_point = unreal.Vector(500, 500, 0) obj_rest_rotator = unreal.Rotator(0, 0, 0) editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) world = editor_subsystem.get_editor_world() # 0. retrieve all the actors editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) actors = editor_actor_subsystem.get_all_level_actors() camera_location_list = [ [-120, 0, 200], [120, 0, 200], [0, -61, 220], [0, 61, 220], [-120, -60, 190], [120, 60, 190], [-120, 60, 190], [120, -60, 190] ] camera_rotation_list = [ [0, -51, 0], [0, -51, 180], [0, -65, 90], [0, -65, -90], [0, -50, 30], [0, -50, -150], [0, -50, -30], [0, -50, 150] ] camera_actors = {} apple = [] coffee_mug = [] note_book = [] capture_component = [] RTs = [] object_actor_dict = get_object_actor_dict(objects, actors) light_actor = None for actor in actors: if "camera" in actor.get_actor_label(): camera_actors[actor.get_actor_label()] = actor if "DirectionalLight" in actor.get_actor_label(): light_actor = actor # print(object_actor_dict) for i in range(8): this_cc = camera_actors[f'camera{i}'].get_component_by_class(unreal.SceneCaptureComponent2D) this_cc.set_editor_property("bCaptureEveryFrame", True) # this_cc.set_editor_property("b_enable_post_processing", True) pp_settings = this_cc.get_editor_property("post_process_settings") pp_settings.override_dynamic_global_illumination_method = True pp_settings.override_reflection_method = True # bloom pp_settings.override_bloom_method = True pp_settings.override_tone_curve_amount = True this_cc.set_editor_property("post_process_settings", pp_settings) capture_component.append(this_cc) RTs.append(capture_component[i].texture_target) # set camera location and rotation existed_episodes = sorted(os.listdir(save_path), key=natural_sort_key) episodes = 1 counter = 0 for episode_idx in range(episodes): # if episode_idx < len(existed_episodes) - 5: # 重新生成最后一几个,防止不全 # continue # print(f"Episode {episode_idx}") # set camera location and rotation for i in range(8): camera_actors[f'camera{i}'].set_actor_location_and_rotation(unreal.Vector(*camera_location_list[i]), unreal.Rotator(*camera_rotation_list[i]), False, False) # set object location and rotation for object in objects: for i in range(NUM_VARIATIONS): object_actor_dict[object][f'{object}{i}'].set_actor_location_and_rotation(obj_rest_point, obj_rest_rotator, False, False) # logic on what objects should on the table num_in_table = np.random.randint(1, 4) objects_in_scene = np.random.choice(objects, num_in_table, replace=False) objects_to_show = [] for object in objects_in_scene: id_in_table = np.random.randint(0, NUM_VARIATIONS) objects_to_show.append([object, id_in_table, object_actor_dict[object][f'{object}{id_in_table}']]) # name, id, actor # logic of placing objects on the table limits = [[-90, 90], [-40, 40]] height = 77 bool_map = np.bool_(np.ones((180, 80))) bool_map[:25, :] = False bool_map[-25:, :] = False bool_map[:, :10] = False bool_map[:, -10:] = False block_size = 18 record = { 'mug': 0, 'notebook': 0, 'apple': 0 } for actor in objects_to_show: this_offset = offset[actor[0]][actor[1]] location_offset = this_offset[0][:3] rotation_offset = this_offset[1] scale_offset = this_offset[0][3] candidate_blocks = get_candidate_blocks(bool_map, block_size) if candidate_blocks: block_position = random.choice(candidate_blocks) bool_map = update_bool_map(bool_map, block_size, block_position) scale = scale_offset * np.random.choice([0.8, 1, 1.2]) x = block_position[0] + limits[0][0] + location_offset[0] * scale y = block_position[1] + limits[1][0] + location_offset[1] * scale z = height + location_offset[2] * scale actor[2].set_actor_location_and_rotation(unreal.Vector(x, y, z), unreal.Rotator(*rotation_offset), False, False) actor[2].set_actor_scale3d(unreal.Vector(scale, scale, scale)) # print(actor[0]) record[actor[0]] += 1 print(f"Placed {actor[0]} {actor[1]} at ({x}, {y}, {z})") else: print("No empty space") episode_idx -= 1 continue # raise ValueError("No empty space") # actor[2].set_actor_location_and_rotation(obj_rest_point + unreal.Vector(*location_offset), obj_rest_rotator + unreal.Rotator(*rotation_offset), False, False) time.sleep(0.1) # take a snapshot folder_path = f'{save_path}/episode_{episode_idx}' for i, RT in enumerate(RTs): light_actor.set_actor_location_and_rotation(unreal.Vector(*camera_location_list[i]), unreal.Rotator(*camera_rotation_list[i]), False, False) capture_component[i].capture_scene() unreal.RenderingLibrary.export_render_target(world, RT, folder_path, f'camera_{i}.png') with open(os.path.join(folder_path, 'info.json'), 'w') as f: json.dump(record, f) counter += 1 unreal.SystemLibrary.collect_garbage() main()
# Copyright Epic Games, Inc. All Rights Reserved. import os import unreal import subprocess from pathlib import Path #------------------------------------------------------------------------------- class Debugger(unreal.Debugger): name = "Visual Studio" def _debug(self, exec_context, cmd, *args): cmd = exec_context.create_runnable(cmd, *args) cmd.launch(suspended=True, new_term=True) pid = cmd.get_pid() try: if not self._attach(pid): cmd.kill() except: cmd.kill() raise def _attach(self, pid, transport=None, host_ip=None): engine = self.get_unreal_context().get_engine() engine_dir = engine.get_dir() import vs.dte for instance in vs.dte.running(): candidate = instance.get_sln_path() if candidate and engine_dir.is_relative_to(Path(candidate).parent): if instance.attach(pid, transport, host_ip): break else: # There's nothing to fallback if a fancy debugger is supposed to be used if transport: return False ret = subprocess.run(("vsjitdebugger.exe", "-p", str(pid))) if ret.returncode: return False if not transport: vs.dte.resume_process(pid) return True
# Copyright Epic Games, Inc. All Rights Reserved. import unreal # This example is designed to show you how to create a Movie Graph Configuration asset, # and add several settings nodes, configure settings on them, and then wire the nodes # together into a graph. This is finally saved as a package in the Content Browser, # so you can pick it in the Movie Render Queue UI (after converting a job to use the graph) # # USAGE: # - Requires the "Python Editor Script Plugin" to be enabled in your project. # # Open the Python interactive console and use: # import MovieGraphCreateConfigExample # MovieGraphCreateConfigExample.CreateBasicConfig() # OR # MovieGraphCreateConfigExample.CreateIntermediateConfig() # OR # MovieGraphCreateConfigExample.CreateAdvancedConfig() # # NOTES: # # - Currently the "Select" nodes are not exposed to the Python API due to their complexity. # They internally use dynamic data types which makes it difficult to expose to Python. def ConvertJobToGraph_Internal(graph_config): subsystem = unreal.get_editor_subsystem(unreal.MoviePipelineQueueSubsystem) pipelineQueue = subsystem.get_queue() if(len(pipelineQueue.get_jobs()) == 0): unreal.log_error("Open the Window > Movie Render Queue and add at least one job to use this example.") return None job = pipelineQueue.get_jobs()[0] # This converts the job to use the Graph Configuration asset for rendering, # instead of the standard MoviePipelinePrimaryConfig. Note that unlike the old # system, the new one doesn't currently support "internal" configs (ie: the # old system had SetPresetOrigin and SetConfiguration, using SetConfiguration # would copy the asset into the internal configuration, while SetPresetOrigin # was used to link to assets on disk. The new system only ever supports assets # on disk, and is similar to calling SetPresetOrigin in the old system). job.set_graph_preset(graph_config) return job def CreateBasicConfig_Internal(config_asset_name): asset_directory = "/project/" # Clean up in case the package was already created (since this is sample code). Normally you'd want to do something like unreal.editor_asset_library.load_asset("/project/") # if you wanted to edit an existing asset. Because this example is about creating assets, we're going to just delete it if it exists. if unreal.EditorAssetLibrary.does_asset_exist(asset_directory + config_asset_name): unreal.EditorAssetLibrary.delete_asset(asset_directory + config_asset_name) # Create a new UMovieGraphConfig asset in a package (inside the /project/ folder). If you used "unreal.MovieGraphConfigFactory()" instead of "None" # it would copy the template specified in the Project Settings. This sample uses a totally blank asset for consistency since we don't know what users will have # set up in their project settings. graph_config = unreal.AssetToolsHelpers.get_asset_tools().create_asset(config_asset_name, asset_directory, unreal.MovieGraphConfig, None) # We're going to add the basic nodes to the graph that are required for simple renders - a render pass, an output format (png), a configured output directory, etc. output_setting_node = graph_config.create_node_by_class(unreal.MovieGraphGlobalOutputSettingNode) # For each setting you want to actually override with a given node, you need to set the override_ flag to True. output_setting_node.override_output_resolution = True output_setting_node.output_resolution = unreal.MovieGraphLibrary.named_resolution_from_profile("720p (HD)") # Create the png setting node png_setting_node = graph_config.create_node_by_class(unreal.MovieGraphImageSequenceOutputNode_PNG) # Find the output node (which comes with every graph), only the output node is considered during graph traversal, # so if nothing is connected to the output node, no nodes will be traversed. output_node = graph_config.get_output_node() # Connect the output settings node to our PNG node. A settings node that only uses default pins # (which are shown unlabeled in the editor UI) uses an empty pin name for the pins. graph_config.add_labeled_edge(output_setting_node, "", png_setting_node, "") # Now connect the png node to our output node graph_config.add_labeled_edge(png_setting_node, "", output_node, "Globals") # Now we can create a render layer. The globals tab could technically be used here instead, but for the sake of a more comprehensive example, we # show the slightly more complicated setup since it better teaches a real graph. output_new_branch = graph_config.add_output() output_new_branch.set_member_name("main_branch") # Now we're going to create a few more nodes. The Deferred Renderer node (so this branch knows what type of render to produce), # and a Render Layer node (so that the system knows to consider this branch for rendering) deferred_renderer_node = graph_config.create_node_by_class(unreal.MovieGraphDeferredRenderPassNode) render_layer_node = graph_config.create_node_by_class(unreal.MovieGraphRenderLayerNode) # If you wanted to change the name that shows up in the {render layer} tokens, we use the name found in the render layer node, not the branch name. render_layer_node.override_layer_name = True render_layer_node.layer_name = "main_layer" # Connect the deferred renderer node to the layer name node graph_config.add_labeled_edge(deferred_renderer_node, "", render_layer_node, "") # Now connect the layer name node to the branch we created earlier so it actually gets considered during evaluation. graph_config.add_labeled_edge(render_layer_node, "", output_node, "main_branch") # If you want to use this graph as a sub-graph in another graph, you need to connect # the pins through to the Inputs node, so we'll do that here. input_new_branch = graph_config.add_input() input_new_branch.set_member_name("main_branch") graph_config.add_labeled_edge(graph_config.get_input_node(), "Globals", output_setting_node, "") graph_config.add_labeled_edge(graph_config.get_input_node(), "main_branch", deferred_renderer_node, "") # Now save the asset to disk. unreal.EditorAssetLibrary.save_asset(asset_directory + config_asset_name) return graph_config def ApplyIntermediateConfigChanges_Internal(graph_config): # This example is going to show how to create "override" nodes, which are just second copies of # nodes that are further downstream in the example with their override fields also set. Then, # we will expose a specific property on that node and drive it with a graph variable, but also # showcase editing the job itself to drive that value. # Graph networks are too complex to simplify traversal, so you have to actually traverse each node # and consider what to do at each node. To do this, you get a Node, and then you get either it's Input # or Output pins, and then you can examine the edges connected to that pin, which give you the other end's pin, # and thus the next node in the chain. globals_pin_on_output = graph_config.get_output_node().get_input_pin("Globals") nodes_connected_to_globals_pin = globals_pin_on_output.get_connected_nodes() # Disconnect the first node from the Output's Globals pin. There should only be one node connected # in this example. first_node = nodes_connected_to_globals_pin[0] graph_config.remove_labeled_edge(first_node, "", graph_config.get_output_node(), "Globals") # Create a new node and connect it to the pins on either side... new_output_node = graph_config.create_node_by_class(unreal.MovieGraphGlobalOutputSettingNode) graph_config.add_labeled_edge(first_node, "", new_output_node, "") graph_config.add_labeled_edge(new_output_node, "", graph_config.get_output_node(), "Globals") # Specify that we want this new output node to override resolution new_output_node.override_output_resolution = True # Now, instead of hard-coding the resolution we want this override node to use, we want to expose the output # resolution pin into the graph so that we can connect things to it. Note that this uses the non-pythonified # variable name. Creating variables for use in graphs is a bit tricky right now as the underlying system can't # be easily exposed to Python. So we use a bit of a roundabout API - you start with a exposed property/pin, # and then let the internal system create a variable for you that has the correct setup to be connected to # that pin. # This exposes the OutputResolution property as a pin on the node in the graph. Note that you still need to check # bOverrideOutputResolution = True for the underlying system to decide to use that value. new_output_node.toggle_promote_property_to_pin("OutputResolution") # Request a new variable to be created of the right type to connect it to the OutputResolution node. # It will try to use the third argument (CustomOutputRes) as the name, but will ensure variable names are # unique so the returned name may not match (if a variable already existed). new_variable = graph_config.add_variable("CustomOutputRes") new_variable.set_value_type(unreal.MovieGraphValueType.STRUCT, unreal.MovieGraphNamedResolution.static_struct()) # Now we can set a value for this variable. The node itself has been configured for 720p so we'll choose # a different default. We use export_text() to turn the FMovieGraphNamedResolution into a string representation, and then # set the variable via set_value_serialized_string due to not allowing typed structs in Python. There exists # other set_value_<foo> functions for POD types. new_variable.set_value_serialized_string(unreal.MovieGraphLibrary.named_resolution_from_size(640, 480).export_text()) # We have a node with the "OutputResolution" pin exposed, and we have a variable we want to drive it with. We need to # create another node on the graph and wire them together. new_variable_node = graph_config.create_node_by_class(unreal.MovieGraphVariableNode) # Associate this new variable node with the variable it should read from. new_variable_node.set_variable(new_variable) # Finally, wire the two nodes together. We use get_member_name() here instead of "CustomOutputRes", because we can't guarantee # that the variable was created with the suggested name earlier (ie: if there was a conflicting variable name already). graph_config.add_labeled_edge(new_variable_node, new_variable.get_member_name(), new_output_node, "OutputResolution") # To showcase the next thing, we're going to take a job from the Queue UI, and convert it to use a Graph Config, # and assign it to use our graph config. This will now create a copy of the variables from the graph config job, # which you can then set values on (such as an artist deciding to override it on the job and using a new value). job = ConvertJobToGraph_Internal(graph_config) if(job): # You can optionally override the values on a job, in case artists want to make top-level edits to the config # without actually editing the config assets. Like with individual nodes, you have to flag that you want to override # the value (without it, it will just use the default specified in the graph above, 640x480.) job_override_variables = job.get_or_create_variable_overrides(graph_config); job_override_variables.set_variable_assignment_enable_state(new_variable, True) job_override_variables.set_value_serialized_string(new_variable, unreal.MovieGraphLibrary.named_resolution_from_profile("1080p (FHD)").export_text()) def DeleteIntermediateConfigChanges_Internal(graph_config): # This function undoes the changes done by ApplyIntermediateConfigChanges_Internal. You generally wouldn't # write a script like this, but we want the examples to showcase how to delete variables, nodes, etc. as well # instead of just constructing graphs. all_graph_variables = graph_config.get_variables() # This just assumes the name was created as designed, which it should in our example case (the only reason it would have # a different name than intended is if there was a conflicting variable name when originally created.) for variable in all_graph_variables: if variable.get_member_name() == "CustomOutputRes": # Make sure to use get_member_name here and not get_name (which gets the internal object name) graph_config.delete_member(variable) break # Deleting the member variable also deleted any nodes that use the variable, so no need to clean that up. But we'll remove # the Output Node that we had added with the OutputResolution pin exposed. globals_pin_on_output = graph_config.get_output_node().get_input_pin("Globals") nodes_connected_to_globals_pin = globals_pin_on_output.get_connected_nodes() # The API only returns a list of nodes directly connected to the pin (not the whole hierarchy), so we need to # run this query again on the node we're about to delete to figure out what was connected to it. nodes_connected_to_output_node = nodes_connected_to_globals_pin[0].get_input_pin("").get_connected_nodes() # Delete the first node (which should be the Output Node), which will also delete the connected edges. graph_config.remove_node(nodes_connected_to_globals_pin[0]) # We now need to link the second node in the chain (a .png sequence in this example) back to the Globals pin on the outputs, # to keep graph connectivity. graph_config.add_labeled_edge(nodes_connected_to_output_node[0], "", graph_config.get_output_node(), "Globals") def ApplyAdvancedConfigChanges_Internal(graph_config): # We're going to create a second render pass which is gated by a branch node that can be controlled # from the top level job (whether or not to include the given render pass). output_pt_branch = graph_config.add_output() output_pt_branch.set_member_name("path_tracer") # Create a branch node, then create a variable in the graph to drive it. branch_node = graph_config.create_node_by_class(unreal.MovieGraphBranchNode) graph_config.add_labeled_edge(branch_node, "", graph_config.get_output_node(), "path_tracer") use_pt_variable = graph_config.add_variable("AddPathTracerPass") use_pt_variable.set_value_type(unreal.MovieGraphValueType.BOOL) use_pt_node = graph_config.create_node_by_class(unreal.MovieGraphVariableNode) use_pt_node.set_variable(use_pt_variable) # Set the default value of the variable to True use_pt_variable.set_value_bool(True) # Connect the variable node to the branch node. graph_config.add_labeled_edge(use_pt_node, "AddPathTracerPass", branch_node, "Condition") # Create a matching inputs for pass-through input_with_pt = graph_config.add_input() input_with_pt.set_member_name("with_pt") input_no_pt = graph_config.add_input() input_no_pt.set_member_name("no_pt") pt_renderer_node = graph_config.create_node_by_class(unreal.MovieGraphPathTracedRenderPassNode) render_layer_node = graph_config.create_node_by_class(unreal.MovieGraphRenderLayerNode) render_layer_node.layer_name = "PathTracer" graph_config.add_labeled_edge(graph_config.get_input_node(), "with_pt", pt_renderer_node, "") graph_config.add_labeled_edge(pt_renderer_node, "", render_layer_node, "") # Wire both of these to the branch node graph_config.add_labeled_edge(render_layer_node, "", branch_node, "True") graph_config.add_labeled_edge(graph_config.get_input_node(), "no_pt", branch_node, "False") def CreateBasicConfig(): # The basic config example just makes a simple single-layer minimal example. CreateBasicConfig_Internal("BasicConfig") def CreateIntermediateConfig(): # The intermediate config creates a basic config, then takes some of the node properties and exposes them # as pins, and then drives those pins from user variables. basic_config = CreateBasicConfig_Internal("IntermediateConfig") ApplyIntermediateConfigChanges_Internal(basic_config) unreal.EditorAssetLibrary.save_loaded_asset(basic_config) def CreateAdvancedConfig(): # The advance config creates a basic config, applies the intermediate config changes, then un-applies them simply for the sake # of showing how to remove things from graphs as well. basic_config = CreateBasicConfig_Internal("AdvanceConfig") ApplyIntermediateConfigChanges_Internal(basic_config) DeleteIntermediateConfigChanges_Internal(basic_config) # Now apply the advance changes to the config, ie: branching. ApplyAdvancedConfigChanges_Internal(basic_config) unreal.EditorAssetLibrary.save_loaded_asset(basic_config)
""" Organizes nodes into the graph editor """ # mca python imports # software specific imports import unreal # mca python imports from mca.common import log from mca.ue.rigging.controlrig import cr_pins, cr_comment logger = log.MCA_LOGGER GROUP_TYPES = ['input', 'main', 'output'] class GridNode: """ Information about a node in the Control Rig grid """ def __init__(self, node, grid_size=None): self.node = node self.grid_size = grid_size @property def size(self): """ Returns the grid size of a node, based on 128x128 blocks. :return: Returns the grid size of a node, based on 128x128 blocks. :rtype: list(int) """ grid_size = self.grid_size if not grid_size: grid_size = self.node.get_grid_size() if not grid_size[0] or not grid_size[1]: logger.warning(f'No Grid Size found for {self.get_fname}') return [1, 1] return grid_size def get_fname(self): """ Returns the string node name. :return: Returns the string representation of the node name. :rtype: str """ return str(self.node.get_fname()) @property def unit_size(self): """ Returns the actual size of the grid node, based on 128x128 blocks. :return: Returns the actual size of the grid node, based on 128x128 blocks. ex: [1, 1] == [128, 128] :rtype: list[int] """ if not self.size: return [128, 128] return [self.size[0] * 128, self.size[1] * 128] class CommentNodeSize: """ Tracks the size of the comment node based on the size of the rows and columns. """ def __init__(self, data=None): self.data = data if not self.data: self.data = {'rows': {}, 'columns': {}} # Actual sizes of the rows and columns def add_row(self, row, size): """ Adds a row and its size to the comment node size. It keeps track of each row size, so we can calculate the longest row. :param int row: the row number :param int size: The actual size of the row. """ if not self.data['rows'].get(row, None): self.data['rows'].update({row: size}) else: old_size = self.data['rows'].get(row, 0) self.data['rows'].update({row: old_size + size}) def add_column(self, group_type, column, size): """ Adds a column and its size to the comment node size. It keeps track of each column size, so we can calculate the longest row. :param str group_type: The type of the column. Either 'input' or 'output' or 'main'. :param int column: the column number :param int size: The actual size of the column. """ if group_type not in self.data['columns'].keys(): self.data['columns'].update({group_type: {}}) if not self.data['columns'][group_type].get(column, None): self.data['columns'][group_type].update({column: size}) else: old_size = self.data['columns'][group_type].get(column, 0) self.data['columns'][group_type].update({column: old_size + size}) def longest_column(self): """ Returns the longest column. :return: Returns the longest column. :rtype: int """ longest_column = 0 for group_type in GROUP_TYPES: if not group_type in self.data['columns'].keys(): continue for column, size in self.data['columns'][group_type].items(): if size > longest_column: longest_column = size return longest_column def longest_row(self): """ Returns the longest row. :return: Returns the longest row. :rtype: int """ longest_row = 0 for row, size in self.data['rows'].items(): if size > longest_row: longest_row = size return longest_row class GridNodeCollection: """ This organizes a collection of nodes that all relate together. Organizes nodes into a grid. There are 3 "group types" of nodes: input, main, and output. The nodes are organized into columns and rows based on the group type. We use a Comment node to track the size of all the nodes. """ def __init__(self, control_rig, main_node, controller=None): self.control_rig = control_rig self.comment_node_size = CommentNodeSize() self.node = GridNode(main_node) self.grid_buffer = 128 self.grid_list = self.start_grid_list() self.controller = controller if not self.controller: self.controller = main_node.cr_controller self.comment_node = None def start_grid_list(self): """ Adds the first main node to the grid list. :return: Returns the master list of all the nodes in the grid for this collection :rtype: list(dict) """ grid_list = [] item = self.node position = self.get_main_position(self.node.unit_size, [0, 0]) item_dict = {} item_dict.update({item: {}}) item_dict[item].update({'position': position}) item_dict[item].update({'size': item.unit_size}) item_dict[item].update({'row_column': [0, 0]}) grid_list.append(item_dict) self.comment_node_size.add_row(row=0, size=item.unit_size[0]) self.comment_node_size.add_column(group_type=GROUP_TYPES[1], column=0, size=item.unit_size[1]) return grid_list def add_grid_node(self, node, group_type, row_column=(0, 0)): """ adds a node to the grid list, which organizes it into a column and row based on the group type. :param FRAG Node node: A node that is part of the collection and is related to the main node. :param str group_type: The type of the node. Either 'input' or 'output' or 'main'. :param list(int) row_column: The row and column of the node in the grid. """ item = GridNode(node) item_dict = {} item_dict.update({item: {}}) if group_type == GROUP_TYPES[0]: position = self.get_input_position(item.unit_size, row_column) item_dict[item].update({'position': position}) item_dict[item].update({'size': item.unit_size}) item_dict[item].update({'row_column': row_column}) self.grid_list.append(item_dict) self.comment_node_size.add_row(row=row_column[0], size=item.unit_size[0]) self.comment_node_size.add_column(group_type=GROUP_TYPES[0], column=row_column[1], size=item.unit_size[1]) elif group_type == GROUP_TYPES[-1]: position = self.get_output_position(item.unit_size, row_column) item_dict[item].update({'position': position}) item_dict[item].update({'size': item.unit_size}) item_dict[item].update({'row_column': row_column}) self.grid_list.append(item_dict) self.comment_node_size.add_row(row=row_column[0], size=item.unit_size[0]) self.comment_node_size.add_column(group_type=GROUP_TYPES[-1], column=row_column[1], size=item.unit_size[1]) elif group_type == GROUP_TYPES[1]: position = self.get_main_position(item.unit_size, row_column) item_dict[item].update({'position': position}) item_dict[item].update({'size': item.unit_size}) item_dict[item].update({'row_column': row_column}) self.grid_list.append(item_dict) self.comment_node_size.add_row(row=row_column[0], size=item.unit_size[0]) self.comment_node_size.add_column(group_type=GROUP_TYPES[1], column=row_column[1], size=item.unit_size[1]) else: logger.warning(f'Invalid Grid Position: {group_type}') return def get_input_position(self, unit_size, row_column): """ Returns the position of an input node in the grid. :param list[int] unit_size: The size of the actual input node :param list[int] list(int) row_column: The row and column of the node in the grid. :return: Returns the position of the input node in the grid. :rtype: list(int) """ row = row_column[0] + 1 column = row_column[1] unit_x = (unit_size[0] * (row * -1)) + (self.grid_buffer * -1) if column == 0: unit_y = unit_size[1] * column else: unit_y = (unit_size[1] * column) return [unit_x, unit_y] def get_main_position(self, unit_size, row_column): """ Returns the position of the main node in the grid. :param list[int] unit_size: The size of the actual main node :param list(int) row_column: The row and column of the node in the grid. :return: Returns the position of the main node in the grid. :rtype: list(int) """ if row_column[0] == 0: unit_x = unit_size[0] * row_column[0] else: unit_x = (unit_size[0] * (row_column[0] * -1)) + self.grid_buffer if row_column[1] == 0: unit_y = unit_size[1] * row_column[1] else: unit_y = (unit_size[1] * row_column[1]) return [unit_x, unit_y] def get_output_position(self, unit_size, row_column): """ Returns the position of the output node in the grid. :param list[int] unit_size: The size of the actual main node :param list(int) row_column: The row and column of the node in the grid. :return: Returns the position of the output node in the grid. :rtype: list(int) """ start_x = self.node.unit_size[0] row = row_column[0] + 1 column = row_column[1] if row == 0: unit_x = unit_size[0] * row + (self.grid_buffer + start_x) else: unit_x = (unit_size[0] * row) + (self.grid_buffer + start_x) if column == 0: unit_y = unit_size[1] * column else: unit_y = (unit_size[1] * column) return [unit_x, unit_y] def get_a_position(self, node): """ Returns the position of the node in the grid. :param FRAG Node node: The node to get the position :return: Returns the position of the node in the grid. :rtype: list(int) """ if isinstance(node, cr_pins.PinsBase): logger.warning(f'Invalid node. {node}') return node_name = node.get_fname() for item in self.grid_list: grid_item = list(item.keys())[0] position = item[grid_item].get('position', None) if grid_item.get_fname() == node.get_fname(): return position def set_all_positions(self): """ Sets all the positions of the nodes in the collection, but not the comment node. """ for item in self.grid_list: grid_item = list(item.keys())[0] position = item[grid_item].get('position', None) grid_item.node.set_position(position) def add_comment_node(self, comment_text, color=(0.000000, 0.000000, 0.000000, 1.000000), side='center', region='comment'): """ Creates a comment node in the graph connected to this node. :param str comment_text: Visible Text in the comment node :param list[float] color: four float num,bers representing RGBA :return: Returns the created comment node :rtype: RigVMCommentNode """ position = self.comment_position() size = self.comment_size() nodes = [] for item in self.grid_list: nodes.append(list(item.keys())[0].get_fname()) comment_node = cr_comment.CommentNode.spawn(control_rig=self.control_rig, controller=self.controller, comment_text=comment_text, node_list=nodes, position=[position[0], position[1]], size=[size[0], size[1]], color=color, side=side, region=region) comment_node = GridNode(comment_node) comment_dict = {} comment_dict.update({comment_node: {}}) comment_dict[comment_node].update({'position': position}) comment_dict[comment_node].update({'size': comment_node.unit_size}) self.comment_node = comment_dict return comment_node def get_box_positions(self): """ Returns the actual position of the node. :return: Returns the actual position of the node. :rtype: list(float) """ positions = [] # [+x, +y, -x, -y] pos_x = 0 pos_y = 0 neg_x = 0 neg_y = 0 for item in self.grid_list: position = item[list(item.keys())[0]].get('position', None) positions.append(position) for pos in positions: if pos[0] > pos_x: pos_x = pos[0] if pos[0] < neg_x: neg_x = pos[0] if pos[1] > pos_y: pos_y = pos[1] if pos[1] < neg_y: neg_y = pos[1] return [pos_x, pos_y, neg_x, neg_y] def comment_size(self): """ Returns the size of the comment node. :return: returns the size of the comment node. :rtype: list(int) """ row = self.comment_node_size.longest_row() column = self.comment_node_size.longest_column() return [row, column] def comment_position(self): """ Returns the position of the comment node. :return: Returns the position of the comment node :rtype: list(float) """ box_positions = self.get_box_positions() return [box_positions[2] - 70, box_positions[3] - 70] def move_collection(self, position=(0, 0)): """ Moves the collection to the specified position. It is based on the comment node position. :param list(int) position: New position of the collection """ comment_node = list(self.comment_node.keys())[0] comment_position = self.comment_node[list(self.comment_node.keys())[0]].get('position', None) comment_position_x = comment_position[0] comment_position_y = comment_position[1] if not position: logger.warning(f'Invalid position. {position}, There might not be a comment node.') return self.comment_node[comment_node].update({'position': position}) comment_node.node.set_position(position=[position[0], position[1]]) for item in self.grid_list: grid_item = list(item.keys())[0] item_pos_x = item[grid_item].get('position', None)[0] item_pos_y = item[grid_item].get('position', None)[1] if item_pos_x is None or item_pos_y is None: logger.warning('Not Moving! A Value is missing') continue dif_x = abs(comment_position_x - item_pos_x) dif_y = abs(comment_position_y - item_pos_y) new_position_x = position[0] + dif_x new_position_y = position[1] + dif_y item[grid_item].update({'position': [new_position_x, new_position_y]}) logger.warning(f'Moving {grid_item.get_fname()} to {new_position_x}, {new_position_y}') self.set_all_positions()
import unreal import json """ Should be used with internal UE API in later versions of UE Auto assign materials to the corresponding meshes according to data from materials_props.json, which was collected by ReferencesCollectorMaterial.py""" with open("C:/project/ Projects/project/" "MaterialAutoAssign/project/.json", "r") as f: mesh_to_material_references = json.load(f) with open("C:/project/ Projects/project/" "MaterialAutoAssign/project/.json", "r") as f: material_rename_data = json.load(f) def set_static_mesh_material(static_mesh, material_path_, material_index_): material_asset = unreal.EditorAssetLibrary.load_asset(material_path_) static_mesh.set_material(material_index_, material_asset) def set_skeletal_mesh_material(skeletal_mesh, material_path_, slot_name_): skeletal_mesh_materials = skeletal_mesh.materials new_material_array = unreal.Array(unreal.SkeletalMaterial) for material_iter in skeletal_mesh_materials: slot_name_iter = material_iter.get_editor_property("material_slot_name") if str(slot_name_iter).lower() == slot_name_.lower(): new_material_iter = unreal.SkeletalMaterial() new_material_asset = unreal.EditorAssetLibrary.load_asset(material_path_) new_material_iter.set_editor_property("material_slot_name", slot_name_iter) new_material_iter.set_editor_property("material_interface", new_material_asset) new_material_array.append(new_material_iter) else: new_material_array.append(material_iter) skeletal_mesh.set_editor_property("materials", new_material_array) # CHANGE ME STATIC_MESH = True filter_path = "/project/" mesh_to_material_references = {k: v for k, v in mesh_to_material_references.items() if k.startswith(filter_path)} print(len(mesh_to_material_references)) c = 0 # CHANGE ME: slice of dict items! (is meant for performance) for asset_path, slot_names_to_material_paths in list(mesh_to_material_references.items()): c += 1 if c % 100 == 0: with open("C:/project/ Projects/project/" "MaterialAutoAssign/project/.txt", "w") as f: f.write(f"Counter: {c}") print(asset_path) asset_path = asset_path.replace("/Content/", "/Game/").replace(".uasset", "") # Lower-case slot names slot_names_to_material_paths = {k.lower(): v for k, v in slot_names_to_material_paths.items()} if unreal.EditorAssetLibrary.does_asset_exist(asset_path): asset = unreal.EditorAssetLibrary.load_asset(asset_path) if STATIC_MESH: filter_class = unreal.StaticMesh else: filter_class = unreal.SkeletalMesh if not unreal.EditorFilterLibrary.by_class([asset], filter_class): continue print(f"Got {'static' if STATIC_MESH else 'skeletal'} mesh", asset_path) if STATIC_MESH: static_mesh_component = unreal.StaticMeshComponent() static_mesh_component.set_static_mesh(asset) material_slot_names = unreal.StaticMeshComponent.get_material_slot_names(static_mesh_component) for slot_name in material_slot_names: slot_name = str(slot_name) material_index = static_mesh_component.get_material_index(slot_name) if slot_name.lower() in slot_names_to_material_paths: material_path = slot_names_to_material_paths[slot_name.lower()] material_path = material_rename_data.get(material_path, material_path) else: print( f"WarningSevere: {asset_path}: slot name {slot_name.lower()} not found among " f"{slot_names_to_material_paths}") material_path = "/project/" if not unreal.EditorAssetLibrary.does_asset_exist(material_path): print(f"WarningSevere: {asset_path}: Material {material_path} not found") material_path = "/project/" set_static_mesh_material(asset, material_path, material_index) else: for slot_name, material_path in slot_names_to_material_paths.items(): if not unreal.EditorAssetLibrary.does_asset_exist(material_path): print(f"WarningSevere: {asset_path}: Material {material_path} not found") material_path = "/project/" set_skeletal_mesh_material(asset, material_path, slot_name) else: print(f"Warning: Asset {asset_path} not found")
# coding: utf-8 from asyncio.windows_events import NULL from platform import java_ver 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() def checkAndSwapPinBoneToContorl(pin): subpins = pin.get_sub_pins() #print(subpins) if (len(subpins) != 2): return; typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') #if (typePin==None or namePin==None): if (typePin==None): return; #if (typePin.get_default_value() == '' or namePin.get_default_value() == ''): if (typePin.get_default_value() == ''): return; if (typePin.get_default_value() != 'Bone'): return; print(typePin.get_default_value() + ' : ' + namePin.get_default_value()) r_con.set_pin_default_value(typePin.get_pin_path(), 'Control', True, False) print('swap end') #end check pin bonePin = None controlPin = None 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) ## for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): if (pin.get_array_size() > 40): # long bone list typePin = pin.get_sub_pins()[0].find_sub_pin('Type') if (typePin != None): if (typePin.get_default_value() == 'Bone'): bonePin = pin continue if (typePin.get_default_value() == 'Control'): if ('Name="pelvis"' in r_con.get_pin_default_value(n.find_pin('Items').get_pin_path())): controlPin = pin continue for item in pin.get_sub_pins(): checkAndSwapPinBoneToContorl(item) else: checkAndSwapPinBoneToContorl(pin) for e in hierarchy.get_controls(): tmp = "{}".format(e.name) if (tmp.endswith('_ctrl') == False): continue if (tmp.startswith('thumb_0') or tmp.startswith('index_0') or tmp.startswith('middle_0') or tmp.startswith('ring_0') or tmp.startswith('pinky_0')): print('') else: continue c = hierarchy.find_control(e) print(e.name) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) ttt = unreal.Transform(location=[0.0, 0.0, 2.0], rotation=[0.0, 0.0, 90.0], scale=[0.03, 0.03, 0.25]) hierarchy.set_control_shape_transform(e, ttt, True) ''' shape = c.get_editor_property('shape') init = shape.get_editor_property('initial') #init = shape.get_editor_property('current') local = init.get_editor_property('local') local = ttt init.set_editor_property('local', local) gl = init.get_editor_property('global_') gl = ttt init.set_editor_property('global_', gl) shape.set_editor_property('initial', init) shape.set_editor_property('current', init) c.set_editor_property('shape', shape) ''' ### swapBoneTable = [ ["Root",""], ["Pelvis","hips"], ["spine_01","spine"], ["spine_02","chest"], ["spine_03","upperChest"], ["clavicle_l","leftShoulder"], ["UpperArm_L","leftUpperArm"], ["lowerarm_l","leftLowerArm"], ["Hand_L","leftHand"], ["index_01_l","leftIndexProximal"], ["index_02_l","leftIndexIntermediate"], ["index_03_l","leftIndexDistal"], ["middle_01_l","leftMiddleProximal"], ["middle_02_l","leftMiddleIntermediate"], ["middle_03_l","leftMiddleDistal"], ["pinky_01_l","leftLittleProximal"], ["pinky_02_l","leftLittleIntermediate"], ["pinky_03_l","leftLittleDistal"], ["ring_01_l","leftRingProximal"], ["ring_02_l","leftRingIntermediate"], ["ring_03_l","leftRingDistal"], ["thumb_01_l","leftThumbProximal"], ["thumb_02_l","leftThumbIntermediate"], ["thumb_03_l","leftThumbDistal"], ["lowerarm_twist_01_l",""], ["upperarm_twist_01_l",""], ["clavicle_r","rightShoulder"], ["UpperArm_R","rightUpperArm"], ["lowerarm_r","rightLowerArm"], ["Hand_R","rightHand"], ["index_01_r","rightIndexProximal"], ["index_02_r","rightIndexIntermediate"], ["index_03_r","rightIndexDistal"], ["middle_01_r","rightMiddleProximal"], ["middle_02_r","rightMiddleIntermediate"], ["middle_03_r","rightMiddleDistal"], ["pinky_01_r","rightLittleProximal"], ["pinky_02_r","rightLittleIntermediate"], ["pinky_03_r","rightLittleDistal"], ["ring_01_r","rightRingProximal"], ["ring_02_r","rightRingIntermediate"], ["ring_03_r","rightRingDistal"], ["thumb_01_r","rightThumbProximal"], ["thumb_02_r","rightThumbIntermediate"], ["thumb_03_r","rightThumbDistal"], ["lowerarm_twist_01_r",""], ["upperarm_twist_01_r",""], ["neck_01","neck"], ["head","head"], ["Thigh_L","leftUpperLeg"], ["calf_l","leftLowerLeg"], ["calf_twist_01_l",""], ["Foot_L","leftFoot"], ["ball_l","leftToes"], ["thigh_twist_01_l",""], ["Thigh_R","rightUpperLeg"], ["calf_r","rightLowerLeg"], ["calf_twist_01_r",""], ["Foot_R","rightFoot"], ["ball_r","rightToes"], ["thigh_twist_01_r",""], ["index_metacarpal_l",""], ["index_metacarpal_r",""], ["middle_metacarpal_l",""], ["middle_metacarpal_r",""], ["ring_metacarpal_l",""], ["ring_metacarpal_r",""], ["pinky_metacarpal_l",""], ["pinky_metacarpal_r",""], #custom ["eye_l", "leftEye"], ["eye_r", "rightEye"], ] 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 ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(swapBoneTable)): swapBoneTable[i][0] = swapBoneTable[i][0].lower() swapBoneTable[i][1] = swapBoneTable[i][1].lower() ### 全ての骨 modelBoneElementList = [] modelBoneNameList = [] for e in hierarchy.get_bones(): if (e.type == unreal.RigElementType.BONE): modelBoneElementList.append(e) modelBoneNameList.append("{}".format(e.name)) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: print(aa.get_editor_property("package_name")) print(aa.get_editor_property("asset_name")) if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() break if (vv == None): for aa in a: if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object break meta = vv # Backwards Bone Names allBackwardsNode = [] def r_nodes(node): b = False try: allBackwardsNode.index(node) except: b = True if (b == True): allBackwardsNode.append(node) linknode = node.get_linked_source_nodes() for n in linknode: r_nodes(n) linknode = node.get_linked_target_nodes() for n in linknode: r_nodes(n) for n in node: if (n.get_node_title() == 'Backwards Solve'): r_nodes(n) print(len(allBackwardsNode)) print(len(node)) def boneOverride(pin): subpins = pin.get_sub_pins() if (len(subpins) != 2): return typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None): return if (namePin==None): return controlName = namePin.get_default_value() if (controlName==''): return if (controlName.endswith('_ctrl')): return if (controlName.endswith('_space')): return r_con.set_pin_default_value(typePin.get_pin_path(), 'Bone', True, False) table = [i for i in swapBoneTable if i[0]==controlName] if (len(table) == 0): # use node or no control return if (table[0][0] == 'root'): metaTable = "{}".format(hierarchy.get_bones()[0].name) else: metaTable = meta.humanoid_bone_table.get(table[0][1]) if (metaTable == None): metaTable = 'None' #print(table[0][1]) #print('<<') #print(controlName) #print('<<<') #print(metaTable) r_con.set_pin_default_value(namePin.get_pin_path(), metaTable, True, False) #for e in meta.humanoid_bone_table: for n in allBackwardsNode: pins = n.get_pins() for pin in pins: if (pin.is_array()): # finger 無変換チェック linknode = n.get_linked_target_nodes() if (len(linknode) == 1): if (linknode[0].get_node_title()=='At'): continue for p in pin.get_sub_pins(): boneOverride(p) else: boneOverride(pin) #sfsdjfkasjk ### 骨名対応表。Humanoid名 -> Model名 humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() humanoidBoneToMannequin = {"" : ""} humanoidBoneToMannequin.clear() # humanoidBone -> modelBone のテーブル作る for searchHumanoidBone in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == searchHumanoidBone): bone_h = e; break; if (bone_h==None): # not found continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m) except: i = -1 if (i < 0): # no bone continue humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m) #humanoidBoneToMannequin["{}".format(bone_h).lower()] = "{}".format(bone_m).lower(bone_h) #print(humanoidBoneToModel) #print(bonePin) #print(controlPin) if (bonePin != None and controlPin !=None): r_con.clear_array_pin(bonePin.get_pin_path()) r_con.clear_array_pin(controlPin.get_pin_path()) #c.clear_array_pin(v.get_pin_path()) #tmp = '(Type=Control,Name=' #tmp += "{}".format('aaaaa') #tmp += ')' #r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp) for e in swapBoneTable: try: i = 0 humanoidBoneToModel[e[1]] except: i = -1 if (i < 0): # no bone continue #e[0] -> grayman #e[1] -> humanoid #humanoidBoneToModel[e[1]] -> modelBone bone = unreal.RigElementKey(unreal.RigElementType.BONE, humanoidBoneToModel[e[1]]) space = unreal.RigElementKey(unreal.RigElementType.NULL, "{}_s".format(e[0])) #print('aaa') #print(bone) #print(space) #p = hierarchy.get_first_parent(humanoidBoneToModel[result[0][1]]) t = hierarchy.get_global_transform(bone) #print(t) hierarchy.set_global_transform(space, t, True) if (bonePin != None and controlPin !=None): tmp = '(Type=Control,Name=' tmp += "{}".format(e[0]) tmp += ')' r_con.add_array_pin(controlPin.get_pin_path(), default_value=tmp, setup_undo_redo=False) tmp = '(Type=Bone,Name=' tmp += "\"{}\"".format(humanoidBoneToModel[e[1]]) tmp += ')' r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp, setup_undo_redo=False) # for bone name space namePin = bonePin.get_sub_pins()[-1].find_sub_pin('Name') r_con.set_pin_default_value(namePin.get_pin_path(), "{}".format(humanoidBoneToModel[e[1]]), True, False) # skip invalid bone, controller # disable node def disableNode(toNoneNode): print(toNoneNode) print("gfgf") pins = toNoneNode.get_pins() for pin in pins: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue print(f'DisablePin {typePin.get_default_value()} : {namePin.get_default_value()}') # control key = unreal.RigElementKey(unreal.RigElementType.CONTROL, "{}".format(namePin.get_default_value())) # disable node r_con.set_pin_default_value(namePin.get_pin_path(), 'None', True, False) if (typePin.get_default_value() == 'Control'): #disable control if (hierarchy.contains(key) == True): settings = h_con.get_control_settings(key) if ("5.1." in unreal.SystemLibrary.get_engine_version()): settings.set_editor_property('shape_visible', False) else: settings.set_editor_property('shape_enabled', False) h_con.set_control_settings(key, settings) for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): continue else: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue if (typePin.get_default_value() != 'Bone'): continue if (namePin.is_u_object() == True): continue if (len(n.get_linked_source_nodes()) > 0): continue key = unreal.RigElementKey(unreal.RigElementType.BONE, namePin.get_default_value()) if (hierarchy.contains(key) == True): continue print(f'disable linked node from {typePin.get_default_value()} : {namePin.get_default_value()}') for toNoneNode in n.get_linked_target_nodes(): disableNode(toNoneNode) ## morph # -vrm vrm -rig rig -debugeachsave 0 #args.vrm #args.rig command = 'VRM4U_CreateMorphTargetControllerUE5.py ' + '-vrm ' + args.vrm + ' -rig ' + args.rig + ' -debugeachsave 0' print(command) unreal.PythonScriptLibrary.execute_python_command(command) unreal.ControlRigBlueprintLibrary.recompile_vm(rig)
import unreal import os def create_project_folders(): # instances of unreal classes editor_util = unreal.EditorAssetLibrary() system_lib = unreal.SystemLibrary() folder_path = "/Game/" folder_name = "NewFolder" full_folder_path = folder_path + folder_name try: editor_util.make_directory(full_folder_path) unreal.log("Folder created successfully at {}".format(folder_path)) except OSError as e: unreal.log("Error creating folder at {} : {}".format(folder_path, e)) create_project_folders()
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 def add_metadata_to_assets(target_folder, metadata_entries): asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() assets = asset_registry.get_assets_by_path(target_folder, recursive=True) for asset in assets: add_metadata_to_asset(asset.package_name, metadata_entries) unreal.log("Metadata added to all assets in folder: " + target_folder) def add_metadata_to_asset(asset_path, metadata_entries): loaded_asset = unreal.EditorAssetLibrary.load_asset(asset_path) if loaded_asset: for key, value in metadata_entries.items(): unreal.EditorAssetLibrary.set_metadata_tag(loaded_asset, key, value) #unreal.EditorAssetLibrary.save_asset(asset_path) unreal.log(f"Metadata added to asset: {asset_path}") else: unreal.log_error(f"Asset not found: {asset_path}") def get_all_metadata(asset_path): loaded_asset = unreal.EditorAssetLibrary.load_asset(asset_path) if loaded_asset: metadata_keys = unreal.EditorAssetLibrary.get_metadata_tag_values(loaded_asset) if metadata_keys: unreal.log(f"Metadata for asset {asset_path}:") for key in metadata_keys: value = unreal.EditorAssetLibrary.get_metadata_tag(loaded_asset, key) unreal.log(f"{key}: {value}") else: unreal.log_warning(f"No metadata found for asset: {asset_path}") else: unreal.log_error(f"Asset not found: {asset_path}") def remove_metadata_from_assets(target_folder, metadata_keys): asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() assets = asset_registry.get_assets_by_path(target_folder, recursive=True) for asset in assets: remove_metadata_from_asset(asset.package_name, metadata_keys) unreal.log("Metadata removed from all assets in folder: " + target_folder) def remove_metadata_from_asset(asset_path, metadata_keys): loaded_asset = unreal.EditorAssetLibrary.load_asset(asset_path) if loaded_asset: for key in metadata_keys: unreal.EditorAssetLibrary.remove_metadata_tag(loaded_asset, key) #unreal.EditorAssetLibrary.save_asset(asset_path) unreal.log(f"Metadata removed from asset: {asset_path}") else: unreal.log_error(f"Asset not found: {asset_path}") def clear_metadata(asset_path): loaded_asset = unreal.EditorAssetLibrary.load_asset(asset_path) if loaded_asset: metadata_keys = unreal.EditorAssetLibrary.get_metadata_tag_values(loaded_asset) if metadata_keys: for key in metadata_keys: unreal.EditorAssetLibrary.remove_metadata_tag(loaded_asset, key) #unreal.EditorAssetLibrary.save_asset(asset_path) unreal.log(f"All metadata cleared from asset: {asset_path}") else: unreal.log_warning(f"No metadata found to clear in asset: {asset_path}") else: unreal.log_error(f"Asset not found: {asset_path}")
import unreal def get_selected_content_browser_assets(): # https://docs.unrealengine.com/5.0/en-US/project/.html?highlight=editorutilitylibrary#unreal.EditorUtilityLibrary editor_utility = unreal.EditorUtilityLibrary() selected_assets = editor_utility.get_selected_assets() return selected_assets def generate_new_name_for_asset(asset): rename_config = { "prefixes_per_type": [ { "type": unreal.MaterialInstance, "prefix": "MI_" }, { "type": unreal.Material, "prefix": "M_" }, { "type": unreal.Texture, "prefix": "T_" }, { "type": unreal.NiagaraSystem, "prefix": "NS_" }, { "type": unreal.ParticleSystem, "prefix": "C_" } ] } name = asset.get_name() print(f"Asset {name} is a {type(asset)}") for i in range(len(rename_config["prefixes_per_type"])): prefix_config = rename_config["prefixes_per_type"][i] prefix = prefix_config["prefix"] asset_type = prefix_config["type"] if isinstance(asset, asset_type) and not name.startswith(prefix): return prefix + name # Type not important for us return name def rename_assets(assets): for i in range(len(assets)): asset = assets[i] old_name = asset.get_name() asset_old_path = asset.get_path_name() asset_folder = unreal.Paths.get_path(asset_old_path) new_name = generate_new_name_for_asset(asset) new_path = asset_folder + "/" + new_name if new_name == old_name: print(f"Ignoring {old_name} as it already has the correct name") continue print(f"Renaming {old_name} to {new_name}...") rename_success = unreal.EditorAssetLibrary.rename_asset(asset_old_path, new_path) if not rename_success: unreal.log_error("Could not rename: " + asset_old_path) def run(): selected_assets = get_selected_content_browser_assets() rename_assets(selected_assets) 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())
import unreal def layout_selected_actors(x_spacing=300, z_spacing=300): """Layout selected actors in the level with specified spacing and reset their rotation.""" selected_actors = unreal.EditorLevelLibrary.get_selected_level_actors() if not selected_actors: unreal.log_error("No actors selected in the level.") return start_location = unreal.Vector(0, 0, 0) assets_per_row = 6 # Number of actors per row for index, actor in enumerate(selected_actors): row = index // assets_per_row col = index % assets_per_row new_location = unreal.Vector( start_location.x + col * x_spacing, start_location.y, start_location.z + row * z_spacing ) actor.set_actor_location(new_location, False, True) # Reset actor rotation to (0, 0, 0) new_rotation = unreal.Rotator(0, 0, 0) actor.set_actor_rotation(new_rotation, False) unreal.log("Actors have been laid out and their rotation reset successfully.") # Run the layout function layout_selected_actors()
import random import json import unreal from math import cos, sin from functools import partial from multiprocessing import Process import time control_json = {} with open('/project/.json', 'r') as file: control_json = json.load(file) control_json_filter = {} with open('/project/.json', 'r') as file: control_json_filter = json.load(file) class CtrlRigAssets: body_rig = unreal.load_asset('/project/.MetaHuman_ControlRig') face_rig_simple = unreal.load_asset('/project/.simple_face_CtrlRig') face_rig = unreal.load_asset('/project/.Face_ControlBoard_CtrlRig') class MetaHumanAssets: hudson = '/project/.BP_Hudson' jake = '/project/.BP_jake' jake_id = '/project/.BP_jake_id' def export_animation_fbx(animation_asset, filename): export_options = unreal.FbxExportOption() export_options.ascii = False export_options.collision = False export_options.export_local_time = False export_options.export_morph_targets = False export_options.export_preview_mesh = True export_options.fbx_export_compatibility = unreal.FbxExportCompatibility.FBX_2013 export_options.force_front_x_axis = False export_options.level_of_detail = False export_options.map_skeletal_motion_to_root = True export_options.vertex_color = False export_task = unreal.AssetExportTask() export_task.set_editor_property("object", animation_asset) export_task.set_editor_property("automated", True) export_task.set_editor_property("options", export_options) export_task.set_editor_property("filename", filename) export_task.set_editor_property("exporter", unreal.AnimSequenceExporterFBX()) unreal.Exporter.run_asset_export_task(export_task) def change_interpmode(binding, mode): for track in binding.get_tracks(): param_section = track.get_sections()[0] for c in param_section.get_channels(): for key in c.get_keys(): key.set_interpolation_mode(mode) def clip_uniform(a): return(max(min(a, 1.), -1.)) # take old keys, new_keys, gap_num return list of n(=gap_num-1) in-between keys by interpolation def linear_interp_keys(old_keys, new_keys, gap_num): interpolation_virtual = lambda y0, y1, t: (1-t/(gap_num+1))*y0 + t/(gap_num+1)*y1 res = [{} for t in range(gap_num)] for key in old_keys: old_key = old_keys[key] new_key = new_keys[key] if isinstance(old_key, list): num_e = len(old_key) for t in range(1, gap_num + 1): res[t-1][key] = [0]*num_e for k in range(num_e): interpolation = partial(interpolation_virtual, old_key[k], new_key[k]) for t in range(1, gap_num + 1): val_interp = interpolation(t) res[t-1][key][k] = val_interp elif isinstance(old_key, float): interpolation = partial(interpolation_virtual, old_key, new_key) for t in range(1, gap_num + 1): val_interp = interpolation(t) res[t-1][key] = val_interp return res def add_key_controller_metahuman_fast(binding, keys, t, value=1.0): track = binding.get_tracks()[0] frame = unreal.FrameNumber(value=t) for channel in track.get_sections()[0].get_all_channels(): channel_name = str(channel.channel_name) value = None if '.X' in channel_name: channel_name = channel_name.split('.')[0] if channel_name in keys: value = keys[channel_name][0] elif '.Y' in channel_name: channel_name = channel_name.split('.')[0] if channel_name in keys: value = keys[channel_name][1] else: if channel_name in keys: value = keys[channel_name] if isinstance(channel, unreal.MovieSceneScriptingFloatChannel) and value: key = channel.add_key(frame, value, interpolation=unreal.MovieSceneKeyInterpolation.LINEAR) def add_key_controller_metahuman(level_sequence, control_rig, keys, t): frame = unreal.FrameNumber(value=t) print(keys) for (key, data) in keys.items(): key_name = unreal.Name(key) control_rig.select_control(key_name) if isinstance(data, float): unreal.ControlRigSequencerLibrary.set_local_control_rig_float(level_sequence, control_rig, key_name, frame, data) elif isinstance(data, list): vec = unreal.Vector2D(x=data[0], y=data[1]) unreal.ControlRigSequencerLibrary.set_local_control_rig_vector2d(level_sequence, control_rig, key_name, frame, vec) def add_key_controller_metahuman_multi(level_sequence, control_rig, keys, t, num_process=1): num_keys = len(keys.items()) n = num_keys // num_process list_items = list(keys.items()) list_keys = [] for i in range(0, num_keys, n): list_keys.append(list_items[i:i + n]) processes = [] for key_items in list_keys: dict_key = dict(key_items) p_thread = Process(target=add_key_controller_metahuman, args=(level_sequence, control_rig, dict_key, t)) processes.append(p_thread) p_thread.start() for p_thread in processes: p_thread.join() def add_keys_controller_metahuman(level_sequence, control_rig, keys, ts): frames = [] for t in ts: frame = unreal.FrameNumber(value=t) frames.append(frame) for (key, data) in keys.items(): key_name = unreal.Name(key) control_rig.select_control(key_name) if isinstance(data[0], float): unreal.ControlRigSequencerLibrary.set_local_control_rig_floats(level_sequence, control_rig, key_name, frames, data) elif isinstance(data[0], list): vecs = [unreal.Vector2D(x=vec[0], y=vec[1]) for vec in data] unreal.ControlRigSequencerLibrary.set_local_control_rig_vector2_ds(level_sequence, control_rig, key_name, frames, vecs) def filter_keys(keys): for key in control_json: if control_json[key]['type'] == 'vec2': value = control_json[key] min_x, max_x = value['min_x'], value['max_x'] min_y, max_y = value['min_y'], value['max_y'] if key in keys: keys[key][0] = max(min(keys[key][0], max_x), min_x) keys[key][1] = max(min(keys[key][1], max_y), min_y) elif control_json[key]['type'] == 'float': value = control_json[key] min_v, max_v = value['min'], value['max'] if key in keys: keys[key] = max(min(keys[key], max_v), min_v) return(keys) def add_key_controller_metahuman_random(level_sequence, control_rig, t, interpolation=None): frame = unreal.FrameNumber(value=t) keys = {} for c in control_json.keys(): control_rig.select_control(c) control_type = control_json[c]['type'] if 'teeth' not in c: if control_type == 'float': value = clip_uniform(random.uniform(-1, 1)) control_min = control_json[c]['min'] if control_min == 0.0: value = abs(value) unreal.ControlRigSequencerLibrary.set_local_control_rig_float(level_sequence, control_rig, c, frame, value) keys[c] = value elif control_type == 'vec2': x = clip_uniform(random.uniform(-1, 1)) y = clip_uniform(random.uniform(-1, 1)) control_min_x = control_json[c]['min_x'] control_min_y = control_json[c]['min_y'] if control_min_x == 0.0: x = abs(x) if control_min_y == 0.0: y = abs(y) vec2 = unreal.Vector2D(x=x, y=y) unreal.ControlRigSequencerLibrary.set_local_control_rig_vector2d(level_sequence, control_rig, c, frame, vec2) keys[c] = [x, y] return(keys) def add_key_sync_binding(binding, t, value=1.0): track = binding.get_tracks()[0] frame = unreal.FrameNumber(value=t) for channel in track.get_sections()[0].get_all_channels(): if isinstance(channel, unreal.MovieSceneScriptingFloatChannel): key = channel.add_key(frame, value) key.set_interpolation_mode(unreal.RichCurveInterpMode.RCIM_CONSTANT) # generate_anim use/need current Sequencer def generate_animation_metahuman_face(level_sequence, binding, skeletal_mesh=None): editor_system = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) world = editor_system.get_editor_world() newAnim = unreal.AnimSequence() anim_export_options = unreal.AnimSeqExportOption() anim_export_options.export_transforms = True anim_export_options.evaluate_all_skeletal_mesh_components = True if skeletal_mesh: newAnim.set_preview_skeletal_mesh(skeletal_mesh) unreal.SequencerTools.export_anim_sequence(world, level_sequence, newAnim, anim_export_options, binding, False) return(newAnim) def update_cut_track_section(level_sequence, start_frame_num=0, end_frame_num=0): camera_cut_track = level_sequence.find_master_tracks_by_type(unreal.MovieSceneCameraCutTrack)[0] camera_cut_section = camera_cut_track.get_sections()[0] camera_cut_section.set_start_frame(start_frame_num) camera_cut_section.set_end_frame(end_frame_num) def add_metahuman(level_sequence, metahuman): editor_system = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) world = editor_system.get_editor_world() level_sequence.add_possessable(metahuman) binding_face = None # for unknown reason, adding control rig to body is causing unreal editor to crash # binding_body = None component_body = None component_face = None control_rig_face = None control_rig_body = None for component in metahuman.root_component.get_children_components(True): if component.get_name() == "Face": binding_face = level_sequence.add_possessable(component) component_face = component if component.get_name() == "Body": # binding_body = level_sequence.add_possessable(component) component_body = component unreal.ControlRigSequencerLibrary.find_or_create_control_rig_track(world, level_sequence, CtrlRigAssets.face_rig.get_control_rig_class(), binding_face) # unreal.ControlRigSequencerLibrary.find_or_create_control_rig_track(self.world, self.level_sequence, CtrlRigAssets.body_rig.get_control_rig_class(), self.binding_body) rig_proxies = unreal.ControlRigSequencerLibrary.get_control_rigs(level_sequence) for rig in rig_proxies: if rig.control_rig.get_name() == "Face_ControlBoard_CtrlRig": control_rig_face = rig.control_rig if rig.control_rig.get_name() == "MetaHuman_ControlRig": control_rig_body = rig.control_rig return(control_rig_face, binding_face, component_face, control_rig_body, None, component_body) def add_key_transform(binding, loc, rot, t): """ channels[0], channels[1], channels[2] = pos(x,y,z) channels[3], channels[4], channels[5] = rot(x,y,z) """ frame = unreal.FrameNumber(value=t) transform_track = binding.find_tracks_by_exact_type(unreal.MovieScene3DTransformTrack)[0] transform_section = transform_track.get_sections()[0] channels = transform_section.get_all_channels() for i in range(3): channels[i].add_key(frame, loc[i]) channels[i + 3].add_key(frame, rot[i]) def add_transformable(level_sequence, actor): binding = level_sequence.add_possessable(actor) transform_section = binding.add_track(unreal.MovieScene3DTransformTrack).add_section() transform_section.set_start_frame_bounded(0) transform_section.set_end_frame_bounded(0) return(binding) def add_hidden(level_sequence, actor): binding = level_sequence.add_possessable(actor) visibility_section = binding.add_track(unreal.MovieSceneVisibilityTrack).add_section() visibility_section.set_start_frame_bounded(0) visibility_section.set_end_frame_bounded(0) return(binding) def add_visibility_track(binding): visibility_section = 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(binding, t, toggle): frame = unreal.FrameNumber(value=t) track = 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) def add_camera(level_sequence, camera, manual_focus=34.): spawnable_camera_binding = level_sequence.add_possessable(camera) transform_section_camera = spawnable_camera_binding.add_track(unreal.MovieScene3DTransformTrack).add_section() transform_section_camera.set_start_frame_bounded(0) transform_section_camera.set_end_frame_bounded(0) camera_cut_track = level_sequence.add_master_track(unreal.MovieSceneCameraCutTrack) camera_cut_section = camera_cut_track.add_section() camera_cut_section.set_start_frame(0) camera_cut_section.set_end_frame(10) camera_cut_section.set_editor_property("CameraBindingID", spawnable_camera_binding.get_binding_id()) camera_component = camera.get_cine_camera_component() filmbacksetting = unreal.CameraFilmbackSettings(sensor_width=24, sensor_height=32) camera_component.filmback = filmbacksetting camera_component.focus_settings.manual_focus_distance = manual_focus camera_component_binding = level_sequence.add_possessable(camera_component) camera_component_binding.set_parent(spawnable_camera_binding) focal_length_track = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) focal_length_track.set_property_name_and_path('CurrentFocalLength', 'CurrentFocalLength') focal_length_section = focal_length_track.add_section() focal_length_section.set_start_frame_bounded(0) focal_length_section.set_end_frame_bounded(0) focus_distance_track = camera_component_binding.add_track(unreal.MovieSceneFloatTrack) focus_distance_track.set_property_name_and_path('ManualFocusDistance', 'FocusSettings.ManualFocusDistance') focus_distance_section = focus_distance_track.add_section() focus_distance_section.set_start_frame_bounded(0) focus_distance_section.set_end_frame_bounded(0) return(focus_distance_section, spawnable_camera_binding) def export_video(level_sequence, path, callback): capture_settings = unreal.AutomatedLevelSequenceCapture() capture_settings.set_image_capture_protocol_type(unreal.load_class(None, "/project/.ImageSequenceProtocol_JPG")) capture_settings.level_sequence_asset = unreal.SoftObjectPath(level_sequence.get_path_name()) capture_settings.settings.overwrite_existing = True capture_settings.settings.resolution.res_x = 240 capture_settings.settings.resolution.res_y = 320 capture_settings.settings.cinematic_mode = True capture_settings.settings.allow_movement = True # capture_settings.settings.use_path_tracer = True capture_settings.settings.enable_texture_streaming = False capture_settings.warm_up_frame_count = 10 capture_settings.delay_before_shot_warm_up = 10 capture_settings.settings.output_directory = unreal.DirectoryPath(path) unreal.SequencerTools.render_movie(capture_settings, callback) def spherical_coordinates(r, phi, theta): x = r * sin(phi) * cos(theta) y = r * sin(phi) * sin(theta) z = r * cos(phi) return([x, y, z])
# coding: utf-8 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) #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] h_mod = rig.get_hierarchy_modifier() #elements = h_mod.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_mod.get_bone(kk)) #print(h_mod.get_elements()) ### 全ての骨 modelBoneListAll = [] modelBoneNameList = [] #for e in reversed(h_mod.get_elements()): # if (e.type != unreal.RigElementType.BONE): # h_mod.remove_element(e) for e in h_mod.get_elements(): if (e.type == unreal.RigElementType.BONE): modelBoneListAll.append(e) modelBoneNameList.append("{}".format(e.name).lower()) # else: # h_mod.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.SPACE, 'root_s') space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.add_space('root_s', space_type=unreal.RigSpaceType.SPACE) else: space = key key = unreal.RigElementKey(unreal.RigElementType.CONTROL, 'root_c') control = h_mod.get_control(key) if (control.get_editor_property('index') < 0): control = h_mod.add_control('root_c', space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) else: control = key h_mod.reparent_element(control, space) parent = control cc = h_mod.get_control(control) cc.set_editor_property('gizmo_visible', False) h_mod.set_control(cc) 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.SPACE, name_s) space = h_mod.get_space(key) if (space.get_editor_property('index') < 0): space = h_mod.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 = h_mod.get_control(key) if (control.get_editor_property('index') < 0): control = h_mod.add_control(name_c, space_name=space.name, gizmo_color=[1.0, 0.0, 0.0, 1.0], ) #h_mod.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_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) #h_mod.set_control_value_transform(control,gizmo_trans) bIsNew = True else: control = key if (bIsNew == True): h_mod.reparent_element(control, space) # テーブル登録 name_to_control[humanoidBone] = control print(humanoidBone) # ロケータ 座標更新 # 不要な上層階層を考慮 gTransform = h_mod.get_global_transform(modelBoneListAll[modelBoneNameList.index(modelBoneNameSmall)]) if count == 0: bone_initial_transform = gTransform else: #bone_initial_transform = h_mod.get_initial_transform(element) bone_initial_transform = gTransform.multiply(control_to_mat[parent].inverse()) h_mod.set_initial_transform(space, bone_initial_transform) control_to_mat[control] = gTransform # 階層修正 h_mod.reparent_element(space, parent) count += 1 if (count >= 500): break
import unreal import os # instances of unreal classes editor_util = unreal.EditorUtilityLibrary() system_lib = unreal.SystemLibrary() editor_asset_lib = unreal.EditorAssetLibrary() asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() assets = asset_reg.get_assets_by_path(directory_text) # 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\\" } num_assets = len(assets) cleaned = 0 # hard coded parent directory parent_dir = "\\Game" for asset in assets: # get the class instance and the clear text name asset_object = asset.get_asset() asset_name = system_lib.get_object_name(asset_object) asset_class = asset_object.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_object, 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 @unreal.uclass() class MyEditorUtility(unreal.GlobalEditorUtilityBase): pass selectedActors = MyEditorUtility().get_selection_set() for actor in selectedActors: unreal.log(actor.get_name()) if actor.actor_has_tag("tagOne"): unreal.log("[1]") if actor.actor_has_tag("tagTwo"): unreal.log("[2]") pass unreal.log("Clear")
# Create Virtuos Menu # Nguyen PHi Hung import unreal_uiutils from unreal_utils import AssetRegistryPostLoad import unreal def extend_editor(): # Create standard menu entry me_reloadbutton = unreal_uiutils.create_menu_button( name="ReloadBtn", label="Reload", command_string="import importlib; import unreal_startup; importlib.reload(unreal_startup); unreal_startup.reload()", ) me_quitbutton = unreal_uiutils.create_menu_button( name="QuitUnrealBtn", label="Quit Unreal", command_string="SystemLib.quit_editor()", ) # This create a button on toolboard tb_reloadbutton = unreal_uiutils.create_toolbar_button( name="ReloadBtn", label="PyReload", command_string="import importlib; import unreal_startup; importlib.reload(unreal_startup); unreal_startup.reload()", ) # This create a drop down button on toolboard tb_combobutton = unreal_uiutils.create_toolbar_combo_button( "comboBtn", "python.tools" ) #TODO: Find out where it is possible to register a new context menu for combo button # create submenu in 'File' Menu and register menu entry created above pythonsubmenu = unreal_uiutils.extend_mainmenu_item( "File", "PythonTools", "PythonTools", "Python Tools" ) pythonsubmenu.add_section("python.file.menu", "Python Tools") pythonsubmenu.add_menu_entry("python.file.menu", me_reloadbutton) pythonsubmenu.add_menu_entry("python.file.menu", me_quitbutton) # Create Standalone Menu and register menu entry created above new_mainmenu = unreal_uiutils.extend_mainmenu("Python", "Python") section = new_mainmenu.add_section("python.menu", "Python Tools") new_mainmenu.add_menu_entry("python.menu", me_reloadbutton) new_mainmenu.add_menu_entry("python.menu", me_quitbutton) new_entry = unreal.ToolMenuEntryExtensions.init_menu_entry( new_mainmenu.menu_name, "submenu", "Test Sub Menu", "nothing here", unreal.ToolMenuStringCommandType.COMMAND, "command", "", ) print(f"Script Object: {new_entry.script_object}") # Extend Asset Context Menu sub_asset_context_menu = unreal_uiutils.extend_toolmenu(unreal_uiutils.get_asset_context_menu(), "PythonAssetContextMenu", "Python Asset Actions") sub_asset_context_menu.add_section("python.assetmenu", "Tools") action_sampleassetprint = unreal_uiutils.create_menu_button( name="SampleAssetTool", label="Print Selected Assets", command_string='print(UtilLibrary.get_selected_assets())', ) sub_asset_context_menu.add_menu_entry("python.assetmenu", action_sampleassetprint) # Extend Asset Context Menu - Only show for Level Sequence Asset sequence_contextmenu = unreal_uiutils.get_sequence_asset_context_menu() sub_sequence_context_menu = unreal_uiutils.extend_toolmenu(sequence_contextmenu, "PythonSequenceContextMenu", "Python Sequence Actions") sub_sequence_context_menu.add_section("python.sequencemenu", "Tools") action_samplesequenceprint = unreal_uiutils.create_menu_button( name="SampleSequenceTool", label="Print Selected Assets", command_string='print(UtilLibrary.get_selected_assets())', ) sub_sequence_context_menu.add_menu_entry("python.sequencemenu", action_samplesequenceprint) # Extend Actor Context Menu actor_context_menu = unreal_uiutils.get_actor_context_menu() actor_context_menu.add_section("python.actoractions", "Python Tools") #!NOTE: The submenu can only be seen when right click in viewport and not the outliner sub_actor_context_menu = actor_context_menu.add_sub_menu(actor_context_menu.menu_name, "python.actoractions", "PythonActorContextMenu", "Python Actor Actions") # is_sub_actor_context_menu_registered = unreal.ToolMenus.get().is_menu_registered(sub_actor_context_menu.menu_name) # if not is_sub_actor_context_menu_registered: # unreal.ToolMenus.get().register_menu(sub_actor_context_menu.menu_name, actor_context_menu.menu_name) # print("{} - is registered {}".format(sub_actor_context_menu.menu_name, is_sub_actor_context_menu_registered)) sub_actor_context_menu.add_section("python.actormenu", "Tools") action_sampleactorprint = unreal_uiutils.create_menu_button( name="SampleActorTool", label="Print Selected Actor", command_string='print(LevelLibrary.get_selected_level_actors())', ) sub_actor_context_menu.add_menu_entry("python.actormenu", action_sampleactorprint) # actor_context_menu.add_menu_entry("python.actoractions", action_sampleactorprint) # AssetRegistryPostLoad.register_callback(extend_editor) extend_editor()
# Copyright Epic Games, Inc. All Rights Reserved. import os import sys import unreal import unrealcmd import unreal.cmdline from pathlib import Path #------------------------------------------------------------------------------- def _get_ip(): import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(("172.31.255.255", 1)) ret = s.getsockname()[0] except: ret = "127.0.0.1" finally: s.close() return ret #------------------------------------------------------------------------------- class _Attachable(object): attach = unrealcmd.Opt(False, "Attach a debugger to the launched process") def _get_debugger(self, name=None): name = name or os.getenv("USHELL_DEBUGGER") name = name or ("vs" if os.name == "nt" else "lldb") dbg_py_path = Path(__file__).parent.parent / f"debuggers/{name}.py" try: import importlib.util spec = importlib.util.spec_from_file_location("", dbg_py_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) debugger_class = getattr(module, "Debugger", None) return debugger_class(self.get_unreal_context()) except Exception as e: raise RuntimeError(f"Failed to load debugger '{dbg_py_path}' ({e})") def attach_to(self, pid, *, transport=None, host_ip=None): debugger = self._get_debugger() return debugger.attach(pid, transport, host_ip) def debug(self, cmd, *args): debugger = self._get_debugger() exec_context = self.get_exec_context() return debugger.debug(exec_context, cmd, *args) #------------------------------------------------------------------------------- class _RunCmd(unrealcmd.Cmd): _variant = unrealcmd.Arg("development", "Build variant to launch") runargs = unrealcmd.Arg([str], "Arguments passed on to the process being launched") build = unrealcmd.Opt(False, "Build the target prior to running it") def _build(self, target, variant, platform): if target.get_type() == unreal.TargetType.EDITOR: build_cmd = ("_build", "editor", variant) else: platform = platform or unreal.Platform.get_host() build_cmd = ("_build", "target", target.get_name(), platform, variant) import subprocess ret = subprocess.run(build_cmd) if ret.returncode: raise SystemExit(ret.returncode) def get_binary_path(self, target, platform=None): ue_context = self.get_unreal_context() if isinstance(target, str): target = ue_context.get_target_by_name(target) else: target = ue_context.get_target_by_type(target) if self.args.build: self._build(target, self.args.variant, platform) variant = unreal.Variant.parse(self.args.variant) if build := target.get_build(variant, platform): if build := build.get_binary_path(): return build raise EnvironmentError(f"No {self.args.variant} build found for target '{target.get_name()}'") #------------------------------------------------------------------------------- class Editor(_RunCmd, _Attachable, unrealcmd.MultiPlatformCmd): """ Launches the editor """ noproject = unrealcmd.Opt(False, "Start the editor without specifying a project") variant = _RunCmd._variant def main(self): self.use_all_platforms() ue_context = self.get_unreal_context() binary_path = self.get_binary_path(unreal.TargetType.EDITOR) args = (*unreal.cmdline.read_ueified(*self.args.runargs),) if (project := ue_context.get_project()) and not self.args.noproject: args = (project.get_path(), *args) wants_terminal = "-stdout" in (x.lower() for x in self.args.runargs) if wants_terminal and binary_path.suffix == "exe": binary_path = binary_path[:-4] binary_path += "-Cmd.exe" if self.args.attach: self.debug(binary_path, *args) return exec_context = self.get_exec_context() editor = exec_context.create_runnable(str(binary_path), *args); if wants_terminal or not self.is_interactive() or os.name != "nt": import uelogprinter printer = uelogprinter.Printer() printer.run(editor) return editor.get_return_code() else: editor.launch() #------------------------------------------------------------------------------- class Commandlet(_RunCmd, _Attachable, unrealcmd.MultiPlatformCmd): """ Runs a commandlet """ commandlet = unrealcmd.Arg(str, "Name of the commandlet to run") variant = _RunCmd._variant def complete_commandlet(self, prefix): ue_context = self.get_unreal_context() for dot_h in ue_context.glob("Source/project/*.h"): if "Commandlet.h" in dot_h.name: yield dot_h.name[:-12] def main(self): self.use_all_platforms() binary_path = self.get_binary_path(unreal.TargetType.EDITOR) if binary_path.suffix == ".exe": binary_path = binary_path.parent / (binary_path.stem + "-Cmd.exe") args = ( "-run=" + self.args.commandlet, *unreal.cmdline.read_ueified(*self.args.runargs), ) if project := self.get_unreal_context().get_project(): args = (project.get_path(), *args) if self.args.attach: self.debug(str(binary_path), *args) return exec_context = self.get_exec_context() cmd = exec_context.create_runnable(str(binary_path), *args); if not self.is_interactive(): cmd.run() else: import uelogprinter printer = uelogprinter.Printer() printer.run(cmd) return cmd.get_return_code() #------------------------------------------------------------------------------- class _ProgramTarget(_RunCmd, _Attachable, unrealcmd.MultiPlatformCmd): def _main_impl(self): self.use_all_platforms() binary_path = self.get_binary_path(self.args.target) args = (*unreal.cmdline.read_ueified(*self.args.runargs),) if self.args.attach: self.debug(str(binary_path), *args) return launch_kwargs = {} if not sys.stdout.isatty(): launch_kwargs = { "silent" : True } exec_context = self.get_exec_context() runnable = exec_context.create_runnable(str(binary_path), *args); runnable.launch(**launch_kwargs) return True if runnable.is_gui() else runnable.wait() #------------------------------------------------------------------------------- class Program(_ProgramTarget): """ Launches the specified program """ program = unrealcmd.Arg(str, "Name of the program to run") variant = _RunCmd._variant def complete_program(self, prefix): ue_context = self.get_unreal_context() for depth in ("*", "*/*"): for target_cs in ue_context.glob(f"Source/Programs/{depth}/*.Target.cs"): yield target_cs.name[:-10] def main(self): self.args.target = self.args.program return self._main_impl() #------------------------------------------------------------------------------- class Target(_ProgramTarget): """ Runs a name target on the host platform. """ target = unrealcmd.Arg(str, "Name of the target to run") variant = _RunCmd._variant def complete_target(self, prefix): #seen = set() #for name, _ in self.get_unreal_context().read_targets(): #if name not in seen: #seen.add(name) #yield name pass def main(self): return self._main_impl() #------------------------------------------------------------------------------- class _Runtime(_RunCmd, _Attachable): """ When using --attach to debug to a process running on a devkit it is expected that the Visual Studio solution is already open (i.e. '.sln open' has been run prior to '.run ... --attach'). """ platform = unrealcmd.Arg("", "Platform to run on") variant = _RunCmd._variant trace = unrealcmd.Opt((False, ""), "Add command line argument to trace to development host") cooked = unrealcmd.Opt(False, "Use cooked data instead of staged data (local only)") onthefly = unrealcmd.Opt(False, "Add the -filehostip= argument.") binpath = unrealcmd.Opt("", "Override the binary that is launched") datadir = unrealcmd.Opt("", "Use and alternative staged/packaged directory") def _main_impl(self, target_type): ue_context = self.get_unreal_context() platform = self.args.platform if not platform: platform = unreal.Platform.get_host() platform = self.get_platform(platform) platform_name = platform.get_name() project = ue_context.get_project() if not project: raise EnvironmentError(f"An active project is required to launch a {target_type.name.lower()} instance") cook_form = platform.get_cook_form(target_type.name.lower()) stage_dir = project.get_dir() / f"Saved/StagedBuilds/{cook_form}" # Allow the user to override the data directory used. if self.args.datadir: if self.args.cooked: self.print_warning("Ignoring --cooked because --datadir was given") self.args.cooked = False stage_dir = Path(self.args.datadir).absolute() if not stage_dir.is_dir(): self.print_error(f"Directory {stage_dir} does not exist") return False if not (stage_dir / "Engine").is_dir(): self.print_warning(f"An Engine/ directory is expected in '{stage_dir}'") # I probably shouldn't do this, but some platforms need this file to be # able to run with data served from the host PC. But I want to be explicit # and clear what command line arguments are given # Find the file in a manner that maintains case. cmdline_txt = None maybe_names = ( "UECommandLine.txt", "uecommandline.txt", "UE4CommandLine.txt", "ue4commandline.txt", ) for maybe_name in maybe_names: cmdline_txt = stage_dir / maybe_name if not cmdline_txt.is_file(): continue cmdline_txt = cmdline_txt.resolve() # corrects case on Windows dest_txt = cmdline_txt.parent / (cmdline_txt.stem + "_old_ushell.txt") if not dest_txt.is_file(): cmdline_txt.rename(dest_txt) break else: cmdline_txt = None if cmdline_txt is not None: cmdline_txt.open("wb").close() # Get the path to the binary to execute if self.args.binpath: binary_path = Path(self.args.binpath).resolve() if not binary_path.is_file(): raise ValueError(f"Binary not found; '{binary_path}'") else: binary_path = self.get_binary_path(target_type, platform_name) # The user can opt-in to using cooked data instead of staged data if self.args.cooked: stage_dir = None if platform.get_name() != unreal.Platform.get_host(): raise ValueError(f"The '--cooked' option may only be used when launching on {unreal.Platform.get_host()}") # Validate data directories if stage_dir: if not stage_dir.is_dir(): suffix = "Client" if target_type == unreal.TargetType.CLIENT else "" stage_dir = project.get_dir() / f"Saved/StagedBuilds/{platform_name}{suffix}/" if not stage_dir.is_dir(): raise EnvironmentError(f"No staged data found for '{cook_form}'") else: cook_dir = project.get_dir() / f"Saved/Cooked/{cook_form}/" if not cook_dir.is_dir(): sandboxed = next((x for x in self.args.runargs if "-sandbox=" in x), None) if sandboxed: self.print_warning(f"No cooked data found for '{cook_form}'") else: raise EnvironmentError(f"No cooked data found for '{cook_form}'") # Condition command line with -filehostip has_filehostip = False for arg in self.args.runargs: if "-filehostip" in arg.lower(): has_filehostip = True break else: if self.args.onthefly: self.args.runargs = (*self.args.runargs, "-filehostip=" + _get_ip()) has_filehostip = True # The project argument. project_arg = project.get_name() if not has_filehostip: project_arg = f"../../../{project_arg}/{project_arg}.uproject" # Build arguments args = ( project_arg, *unreal.cmdline.read_ueified(*self.args.runargs), ) if not self.args.cooked: args = (*args, "-pak") if self.args.trace is not False: args = (*args, "-tracehost=" + _get_ip()) if self.args.trace: args = (*args, "-trace=" + self.args.trace) # Launch the runtime stage_dir = str(stage_dir) + "/" if stage_dir else "" exec_context = self.get_exec_context() instance = platform.launch(exec_context, stage_dir, str(binary_path), args) if not instance: raise RuntimeError("An error occurred while launching.") # Attach a debugger if self.args.attach: if type(instance) is tuple: attach_ok = False pid, devkit_ip = instance # If there is no devkit involved we can try and use if devkit_ip == None: attach_ok = self.attach_to(pid) # Otherwise we're using VS to attach and that's only on Windows elif vs_transport := getattr(platform, "vs_transport", None): print("Attaching to", pid, "on", devkit_ip, "with", vs_transport) attach_ok = self.attach_to(pid, transport=vs_transport, host_ip=devkit_ip) # Tell the user stuff if attach_ok: print("Debugger attached successfully") else: self.print_warning("Unable to attach a debugger") return self.print_warning(f"--attach is not currently supported on {platform.get_name()}") #------------------------------------------------------------------------------- class Game(_Runtime): """ Launches the game runtime. """ def complete_platform(self, prefix): yield from super().complete_platform(prefix) yield "editor" @unrealcmd.Cmd.summarise def main(self): if self.args.platform == "editor": editor = Editor() editor._channel = self._channel args = (self.args.variant, "--", *self.args.runargs, "-game") if self.args.build: args = ("--build", *args) if self.args.attach: args = ("--attach", *args) return editor.invoke(args) return self._main_impl(unreal.TargetType.GAME) #------------------------------------------------------------------------------- class Client(_Runtime): """ Launches the game client. """ @unrealcmd.Cmd.summarise def main(self): return self._main_impl(unreal.TargetType.CLIENT) #------------------------------------------------------------------------------- class Server(_Runtime): """ Launches the server binary. """ complete_platform = ("win64", "linux") @unrealcmd.Cmd.summarise def main(self): self.args.runargs = (*self.args.runargs, "-log", "-unattended") return self._main_impl(unreal.TargetType.SERVER)
import csv import os import unreal def modify_csv_data(csv_file_path, output_folder): modified_csv_file_path = os.path.join(output_folder, 'coverage_map_modified.csv') with open(csv_file_path, 'r') as csv_file: reader = csv.DictReader(csv_file) fieldnames = reader.fieldnames rows = list(reader) # Modifica i valori delle colonne x, y, z for row in rows: row['x'] = float(row['x']) * 100 row['y'] = float(row['y']) * 100 row['z'] = float(row['z']) * 100 # Scrivi i dati modificati in un nuovo file CSV with open(modified_csv_file_path, 'w', newline='') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) return modified_csv_file_path def reimport_data_table(data_table_path, csv_file_path): # Trova l'asset della data table unreal.log(f"Tentativo di caricamento dell'asset della data table da: {data_table_path}") data_table_asset = unreal.EditorAssetLibrary.load_asset(data_table_path) if not data_table_asset: unreal.log_error(f"Data table {data_table_path} non trovata.") return False # Verifica che l'asset caricato sia una DataTable if not isinstance(data_table_asset, unreal.DataTable): unreal.log_error(f"L'asset {data_table_path} non è una DataTable.") return False # Leggi il contenuto del file CSV with open(csv_file_path, 'r') as csv_file: csv_content = csv_file.read() # Riempie la DataTable con i dati del CSV success = unreal.DataTableFunctionLibrary.fill_data_table_from_csv_string(data_table_asset, csv_content) if success: unreal.EditorAssetLibrary.save_loaded_asset(data_table_asset) unreal.log(f"Reimportazione della data table {data_table_path} completata con successo.") return True else: unreal.log_error(f"Reimportazione della data table {data_table_path} fallita.") 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') # Percorsi dell'asset della data table e del file CSV data_table_path = '/project/' # Assicurati che il percorso sia corretto original_csv_file_path = os.path.join(python_scripts_path, 'coverage_map.csv') # Percorso del file CSV originale # Modifica i valori del file CSV modified_csv_file_path = modify_csv_data(original_csv_file_path, python_scripts_path) # Esegui la reimportazione reimport_data_table(data_table_path, modified_csv_file_path)
import unreal # https://docs.unrealengine.com/5.0/en-US/project/.html?highlight=vector#unreal.Vector v1 = unreal.Vector(0, 1, 0) v2 = unreal.Vector(1, 0, 0) v3 = v1.cross(v2) print(v3)
""" Static Mesh Level Placement Script for Unreal Engine ----------------------------------------- This script is the eighth step in the Undini procedural generation pipeline: 1. Export splines from Unreal Engine (000_export_splines_as_json.py) 2. Export GenZone meshes from UE (010_export_gz_to_mod.py) 3. Process building data in Houdini (100_headless_topnet_PCGHD.py) 4. Import CSV files back into Unreal Engine (110_reimport_datatable.py) 5. Create PCG graphs in Unreal Engine (120_create_pcg_graph.py) 6. Generate sidewalks and roads in Houdini (200_headless_topnet_SWR.py) 7. Import sidewalk and road meshes into Unreal Engine (210_reimport_SM.py) 8. Add sidewalks and roads to the level (this script) This script finds all static meshes with names matching the specified iteration number pattern and adds them to the current level in organized folders. Usage: From Python in Unreal Engine: ```python import add_SM_sidewalks_and_roads_to_level add_SM_sidewalks_and_roads_to_level(iteration_number=5) ``` Or run directly: ``` python 220_add_SM_to_lvl.py ``` """ import unreal import os def add_SM_sidewalks_and_roads_to_level(iteration_number=1): """ Adds sidewalk and road static meshes to the current level for a specific iteration. Args: iteration_number (int): The iteration number to use when finding assets. This should match the iteration used in the previous pipeline steps. Returns: bool: True if assets were added successfully, False otherwise. This finds all static meshes with names starting with 'sidewalks_{iteration_number}_piece_' and 'road_{iteration_number}_piece_', then adds them to the level in organized folders. """ # Get the asset registry to search for meshes asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() editor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) # Define names and folders for organizing actors in the level sidewalk_folder = "Sidewalks" road_folder = "Roads" # Simple debug log function with emoji indicators for better readability def debug_log(msg, level="info"): """Log a message with appropriate level and emoji indicator""" if level == "info": unreal.log(f"ℹ️ {msg}") elif level == "success": unreal.log(f"✅ {msg}") elif level == "warning": unreal.log_warning(f"⚠️ {msg}") elif level == "error": unreal.log_error(f"❌ {msg}") else: unreal.log(f"🔍 {msg}") # Debug level # Set up asset registry filter to find static meshes debug_log(f"Starting search for sidewalks and roads for iteration {iteration_number}", "info") try: ar_filter = unreal.ARFilter( class_names=["StaticMesh"], recursive_classes=True, recursive_paths=True ) # Get all static mesh assets debug_log("Querying asset registry for all static meshes...", "debug") asset_data_list = asset_registry.get_assets(ar_filter) debug_log(f"Found {len(asset_data_list)} total static meshes in the project", "debug") # Define prefixes for this iteration sidewalk_prefix = f"sidewalks_{iteration_number}_piece_" road_prefix = f"road_{iteration_number}_piece_" debug_log(f"Looking for assets with prefixes:", "debug") debug_log(f" • Sidewalks: '{sidewalk_prefix}'", "debug") debug_log(f" • Roads: '{road_prefix}'", "debug") # Filter assets by name prefix sidewalk_assets = [a for a in asset_data_list if str(a.asset_name).startswith(sidewalk_prefix)] road_assets = [a for a in asset_data_list if str(a.asset_name).startswith(road_prefix)] # Log what we found with appropriate emoji indicators if sidewalk_assets: debug_log(f"Found {len(sidewalk_assets)} sidewalk pieces for iteration {iteration_number}", "success") else: debug_log(f"No sidewalk pieces found for iteration {iteration_number}", "warning") if road_assets: debug_log(f"Found {len(road_assets)} road pieces for iteration {iteration_number}", "success") else: debug_log(f"No road pieces found for iteration {iteration_number}", "warning") except Exception as e: debug_log(f"Error searching for assets: {str(e)}", "error") return False # Helper function to spawn an actor and put it in the right folder def spawn_and_folder(asset_data, folder_name): """ Spawn a static mesh actor in the level and organize it in a folder. Args: asset_data: The asset data object from the asset registry folder_name: The folder to place the actor in Returns: The spawned actor or None if unsuccessful """ # Get the asset path and load it asset_path = str(asset_data.package_name) asset_name = str(asset_data.asset_name) debug_log(f"Loading asset: {asset_path}", "debug") try: # Load the asset asset = unreal.EditorAssetLibrary.load_asset(asset_path) # Check if the asset was loaded successfully if not asset: debug_log(f"Couldn't find the asset: {asset_path}. Is it in the right place?", "error") return None # Spawn a new StaticMeshActor at the origin debug_log(f"Spawning actor for {asset_name}", "debug") actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, unreal.Vector(0, 0, 0), unreal.Rotator(0, 0, 0) ) if not actor: debug_log(f"Failed to spawn actor for: {asset_path}", "error") return None # Get the static mesh component and assign our mesh to it static_mesh_comp = actor.get_component_by_class(unreal.StaticMeshComponent) if static_mesh_comp: static_mesh_comp.set_static_mesh(asset) # Set the folder and name actor.set_folder_path(folder_name) actor.set_actor_label(asset_name, mark_dirty=True) debug_log(f"Added '{asset_name}' to level in folder '{folder_name}'", "success") return actor else: debug_log(f"No StaticMeshComponent found on actor: {actor.get_name()}", "error") # Clean up the actor since we couldn't set the mesh actor.destroy_actor() return None except Exception as e: debug_log(f"Error spawning actor for {asset_name}: {str(e)}", "error") return None # Check if we found any assets if not sidewalk_assets and not road_assets: debug_log(f"No sidewalk or road pieces found for iteration {iteration_number}", "warning") debug_log("Make sure you've completed these steps first:", "warning") debug_log(" 1. Generated sidewalks and roads in Houdini (200_headless_topnet_SWR.py)", "warning") debug_log(" 2. Imported the FBX files into Unreal Engine (210_reimport_SM.py)", "warning") return False # Track success and failure counts total_success = 0 total_processed = 0 # Add all the sidewalk pieces to the level if sidewalk_assets: debug_log(f"\n🛠 Adding {len(sidewalk_assets)} sidewalk pieces to the level...", "info") for i, asset_data in enumerate(sidewalk_assets): debug_log(f"Processing sidewalk piece {i+1}/{len(sidewalk_assets)}: {asset_data.asset_name}", "debug") actor = spawn_and_folder(asset_data, sidewalk_folder) total_processed += 1 if actor: total_success += 1 # Add all the road pieces to the level if road_assets: debug_log(f"\n🛠 Adding {len(road_assets)} road pieces to the level...", "info") for i, asset_data in enumerate(road_assets): debug_log(f"Processing road piece {i+1}/{len(road_assets)}: {asset_data.asset_name}", "debug") actor = spawn_and_folder(asset_data, road_folder) total_processed += 1 if actor: total_success += 1 # Show a summary of what we did debug_log(f"\n📊 Summary", "info") debug_log(f" • Successfully placed: {total_success} of {total_processed} actors", "info") debug_log(f" • Success rate: {(total_success/max(1, total_processed))*100:.1f}%", "info") if total_success < total_processed: debug_log("Some actors couldn't be placed. Check the log above for details.", "warning") else: debug_log(f"All sidewalks and roads for iteration {iteration_number} were added to the level!", "success") # Visual separator for the end of the script debug_log("\n" + "-" * 80, "info") return total_success > 0 # ====================================================================== # Main Execution # ====================================================================== # Run the function when this script is executed directly if __name__ == "__main__": debug_log("🚀 Starting Static Mesh placement process...", "info") debug_log("This is the eighth step in the Undini procedural generation pipeline.", "info") debug_log("It adds the sidewalks and roads to the current level.", "info") # You can modify this parameter for testing iteration_number = 5 # Change this as needed # Call the main function result = add_SM_sidewalks_and_roads_to_level(iteration_number=iteration_number) # Report the results if result: debug_log(f"\n🎉 Placement process completed successfully!", "success") else: debug_log(f"\n⚠️ No meshes were placed. Check the log above for details.", "warning")
import unreal import os def reimport_datatables(iteration_number=None, csv_dir=None): """ Import or reimport CSV files as DataTables in Unreal Engine This is the fourth step in the Undini procedural generation pipeline: 1. First, we export splines from Unreal Engine (000_export_splines_as_json.py) 2. Then, we export GenZone meshes from UE (010_export_gz_to_mod.py) 3. Next, we process those inputs in Houdini to generate building data (100_headless_topnet_PCGHD.py) 4. Now, we import the generated CSV files back into Unreal Engine as DataTables The script takes the CSV files generated by Houdini (mesh and material data) and imports them as DataTables in Unreal Engine. These DataTables will be used by the PCG system to generate procedural buildings in the level. Args: iteration_number (int, optional): The iteration number to use for file naming. Defaults to 0. csv_dir (str, optional): Directory containing the CSV files. If None, uses a default path. Returns: int: 1 if all imports were successful, 0 if any failed """ # Set up our parameters with sensible defaults if not provided if iteration_number is None: iteration_number = 0 print("ℹ️ No iteration number provided, using default: 0") else: print(f"ℹ️ Using provided iteration number: {iteration_number}") if csv_dir is None: # Calculate the default CSV directory based on the script location # This follows the same path structure as in the manager script workspace_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) csv_dir = os.path.join(workspace_root, '03_GenDatas', 'Dependancies', 'PCG_HD', 'Out', 'CSV') print(f"ℹ️ No CSV directory provided, using default: {csv_dir}") else: print(f"ℹ️ Using provided CSV directory: {csv_dir}") # Make sure the CSV directory exists if not os.path.exists(csv_dir): print(f"⚠️ Warning: CSV directory does not exist: {csv_dir}") print(" Creating directory...") try: os.makedirs(csv_dir, exist_ok=True) print(f"✅ Created directory: {csv_dir}") except Exception as e: print(f"❌ Error creating directory: {str(e)}") return 0 # Define the UE paths for our assets # These are the same paths used throughout the pipeline ue_base_path = "/project/" # Define the CSV imports with the iteration number # Each import specifies the source CSV file, destination in UE, asset name, and template to use csv_imports = [ { "csv_file": os.path.join(csv_dir, f"mesh_{iteration_number}.csv"), "destination_path": ue_base_path, "asset_name": f"mesh_{iteration_number}", "template_path": f"{ue_base_path}/mesh_template", "description": "Mesh data for procedural buildings" }, { "csv_file": os.path.join(csv_dir, f"mat_{iteration_number}.csv"), "destination_path": ue_base_path, "asset_name": f"mat_{iteration_number}", "template_path": f"{ue_base_path}/mat_template", "description": "Material data for procedural buildings" } ] print("\n📚 PROCESSING DATATABLES 📚") print(f"Using iteration number: {iteration_number}") print(f"Looking for CSV files in: {csv_dir}") print(f"Will import to Unreal path: {ue_base_path}") # Check if the CSV files exist before we start missing_files = [] for import_data in csv_imports: if not os.path.exists(import_data["csv_file"]): missing_files.append(import_data["csv_file"]) if missing_files: print(f"\n⚠️ Warning: The following CSV files are missing:") for file in missing_files: print(f" - {file}") print("Will attempt to import only the files that exist.") else: print(f"\n✅ All required CSV files found.") # Get references to the Unreal Engine editor libraries we need print("\n🔍 Getting Unreal Engine editor libraries...") editor_lib = unreal.EditorAssetLibrary asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # Keep track of our progress success_count = 0 # Process each CSV file to import as a DataTable for import_data in csv_imports: try: # Extract the import data csv_file = import_data["csv_file"] destination_path = import_data["destination_path"] asset_name = import_data["asset_name"] template_path = import_data["template_path"] description = import_data.get("description", "") full_asset_path = f"{destination_path}/{asset_name}" print(f"\n📂 Processing: {asset_name} ({description})") print(f" Source: {csv_file}") print(f" Destination: {full_asset_path}") # Skip if CSV file doesn't exist if not os.path.exists(csv_file): print(f"❌ Error: CSV file not found at {csv_file}") print(" Skipping this import and continuing with the next one.") continue # Check if we're creating a new asset or updating an existing one asset_exists = editor_lib.does_asset_exist(full_asset_path) if asset_exists: print(f"ℹ️ Asset already exists - will perform a reimport") else: print(f"ℹ️ Asset does not exist - will create a new DataTable") # Get the row structure from the template DataTable print(f"Looking for template at: {template_path}") row_struct = None if editor_lib.does_asset_exist(template_path): template_dt = editor_lib.load_asset(template_path) if template_dt and isinstance(template_dt, unreal.DataTable): row_struct = template_dt.get_editor_property("row_struct") if row_struct: print(f"✅ Found row struct from template: {row_struct.get_name()}") if not row_struct: print(f"❌ Error: Could not find a valid row struct for {asset_name}") print(" This usually means the template DataTable doesn't exist or is invalid.") print(" Make sure you have a valid template at: {template_path}") continue # Now let's set up the import task print("Setting up CSV import task...") task = unreal.AssetImportTask() task.filename = csv_file task.destination_path = destination_path task.destination_name = asset_name task.replace_existing = asset_exists task.automated = True # Don't show any UI task.save = True # Save the asset after import # Create and configure a CSV import factory csv_factory = unreal.CSVImportFactory() # Configure the import settings import_settings = unreal.CSVImportSettings() import_settings.import_type = unreal.CSVImportType.ECSV_DATA_TABLE # Different versions of UE use different property names for the row struct # We'll try all known variations to ensure compatibility try: # Try the property name for newer UE versions print("Trying newer UE property name: data_table_row_type") import_settings.data_table_row_type = row_struct except AttributeError: try: # Try the property name for older UE versions print("Trying older UE property name: import_row_struct") import_settings.import_row_struct = row_struct except AttributeError: # If both fail, we'll try setting it directly on the factory print("Using direct factory property setting for row struct") # Note: This might not work on all UE versions, but it's a last resort # Apply the import settings to the factory csv_factory.set_editor_property("automated_import_settings", import_settings) # Assign the factory to our task task.factory = csv_factory # Now let's perform the actual import print(f"\n📥 {'Reimporting' if asset_exists else 'Importing'} {asset_name}...") result = asset_tools.import_asset_tasks([task]) # Check if the import was successful if result and len(result) > 0: print(f"✅ Successfully {'reimported' if asset_exists else 'imported'} DataTable {asset_name}") success_count += 1 # Verify the asset exists after import if editor_lib.does_asset_exist(full_asset_path): # Try to get some info about the imported DataTable try: dt = editor_lib.load_asset(full_asset_path) if isinstance(dt, unreal.DataTable): row_count = len(dt.get_row_names()) print(f" DataTable contains {row_count} rows") except Exception as e: # Not critical if this fails, just informational print(f" Could not get row count: {str(e)}") else: print(f"⚠️ Warning: Asset reported as imported but not found at {full_asset_path}") else: # The import might have succeeded even if result is empty (UE quirk) if editor_lib.does_asset_exist(full_asset_path): print(f"✅ Import appears successful for {asset_name} - asset exists in Content Browser") success_count += 1 else: print(f"⚠️ Import process completed for {asset_name} but asset not found - check for errors") except Exception as e: print(f"❌ Error processing {import_data['asset_name']}: {str(e)}") # Print more detailed error information to help with debugging import traceback print(f" Error details: {traceback.format_exc()}") print(" Continuing with next import...") # Print a summary of what we did print(f"\n📊 IMPORT/REIMPORT SUMMARY 📊") print(f"{'=' * 40}") print(f"Total DataTables to process: {len(csv_imports)}") print(f"Successfully processed: {success_count}") print(f"Failed: {len(csv_imports) - success_count}") print(f"{'=' * 40}") # Return a success code based on whether all imports succeeded if success_count == len(csv_imports): print(f"🎉 All DataTable imports completed successfully!") print(f"The next step is to create PCG graphs in Unreal Engine using these DataTables.") return 1 elif success_count > 0: print(f"⚠️ Some DataTable imports failed. Check the log above for details.") print(f"You may still be able to proceed with the pipeline using the successful imports.") return 0 else: print(f"❌ All DataTable imports failed. Please fix the issues before continuing.") print(f"Common issues include:") print(f" • Missing CSV files from Houdini export") print(f" • Missing template DataTables in Unreal Engine") print(f" • Incorrect file paths or permissions") return 0
import unreal AssetTools = unreal.AssetToolsHelpers.get_asset_tools() MaterialEditLibrary = unreal.MaterialEditingLibrary EditorAssetLibrary = unreal.EditorAssetLibrary MeshMaterial = AssetTools.create_asset("M_MeshPaint", "/project/", unreal.Material, unreal.MaterialFactoryNew()) # Add texture parameter nodes for each surface base_colors = [] normals = [] orms = [] # Create a Vertex Color node VertexColorNode_Color = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), 0, -300) VertexColorNode_Normal = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), 0, -400) # Create a Vertex Color node for each ORM channel VertexColorNode_ORM_R = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), 0, -150) VertexColorNode_ORM_G = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), 0, 0) VertexColorNode_ORM_B = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionVertexColor.static_class(), 0, 150) # Create a 1-x nodes for each channel so that the texures from 5 to 1 can loop OneMinusNodeColor = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -300) OneMinusNodeNormal = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -400) OneMinusNode_R = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -500) OneMinusNode_G = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -600) OneMinusNode_B = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionOneMinus.static_class(), 0, -600) for i in range(5): # Create base color, normal, and ORM texture parameter nodes BaseColorParam = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), -384, -300 + i * 150) NormalParam = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), -384 + 300, -300 + i * 150) OrmParam = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionTextureSampleParameter2D.static_class(), -384 + 600, -300 + i * 150) # Set names and other properties for the nodes BaseColorParam.set_editor_property("ParameterName", unreal.Name("BaseColor_{}".format(i))) NormalParam.set_editor_property("ParameterName", unreal.Name("Normal_{}".format(i))) OrmParam.set_editor_property("ParameterName", unreal.Name("ORM_{}".format(i))) base_colors.append(BaseColorParam) normals.append(NormalParam) orms.append(OrmParam) # Create lerp nodes for the base color, normals, and orms 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(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192, -300 + i * 150) normal_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192 + 300, -300 + i * 150) orm_r_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192 + 600, -300 + i * 150) orm_g_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192 + 600, -300 + i * 150 + 200) orm_b_lerp = MaterialEditLibrary.create_material_expression(MeshMaterial, unreal.MaterialExpressionLinearInterpolate.static_class(), -192 + 600, -300 + i * 150 + 400) 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) # Connect texture parameters to lerp nodes for i in range(5): MaterialEditLibrary.connect_material_expressions(base_colors[i], '', base_color_lerps[i], 'B') #MaterialEditLibrary.connect_material_expressions(base_colors[i + 1], '', base_color_lerps[i], 'B') MaterialEditLibrary.connect_material_expressions(normals[i], '', normal_lerps[i], 'A') MaterialEditLibrary.connect_material_expressions(normals[i + 1], '', normal_lerps[i], 'B') # ORM connections MaterialEditLibrary.connect_material_expressions(orms[i], 'R', orm_r_lerps[i], 'A') MaterialEditLibrary.connect_material_expressions(orms[i + 1], 'R', orm_r_lerps[i], 'B') MaterialEditLibrary.connect_material_expressions(orms[i], 'G', orm_g_lerps[i], 'A') MaterialEditLibrary.connect_material_expressions(orms[i + 1], 'G', orm_g_lerps[i], 'B') MaterialEditLibrary.connect_material_expressions(orms[i], 'B', orm_b_lerps[i], 'A') MaterialEditLibrary.connect_material_expressions(orms[i + 1], 'B', orm_b_lerps[i], 'B') if i > 0: MaterialEditLibrary.connect_material_expressions(base_color_lerps[i - 1], '', base_color_lerps[i], 'Alpha') MaterialEditLibrary.connect_material_expressions(normal_lerps[i - 1], '', normal_lerps[i], 'Alpha') MaterialEditLibrary.connect_material_expressions(orm_r_lerps[i - 1], '', orm_r_lerps[i], 'Alpha') MaterialEditLibrary.connect_material_expressions(orm_g_lerps[i - 1], '', orm_g_lerps[i], 'Alpha') MaterialEditLibrary.connect_material_expressions(orm_b_lerps[i - 1], '', orm_b_lerps[i], 'Alpha') #Special Connections for Base Color MaterialEditLibrary.connect_material_expressions(base_colors[4], '', base_color_lerps[0], 'A') MaterialEditLibrary.connect_material_expressions(OneMinusNodeColor, '', base_color_lerps[0], 'Alpha') # Connect the Vertex Color node to the alpha input of base color and normal lerps MaterialEditLibrary.connect_material_expressions(VertexColorNode_Color, 'A', OneMinusNodeColor, '') # Connect the individual Vertex Color nodes to the alpha input of ORM lerps MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_R, 'R', orm_r_lerps[i], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_G, 'G', orm_g_lerps[i], 'Alpha') MaterialEditLibrary.connect_material_expressions(VertexColorNode_ORM_B, 'B', orm_b_lerps[i], 'Alpha') #Connect Result of each network to its channel MaterialEditLibrary.connect_material_property(base_color_lerps[-1], "", unreal.MaterialProperty.MP_BASE_COLOR) MaterialEditLibrary.connect_material_property(normal_lerps[-1], "", unreal.MaterialProperty.MP_NORMAL) MaterialEditLibrary.connect_material_property(orm_r_lerps[-1], "", unreal.MaterialProperty.MP_AMBIENT_OCCLUSION) MaterialEditLibrary.connect_material_property(orm_g_lerps[-1], "", unreal.MaterialProperty.MP_ROUGHNESS) MaterialEditLibrary.connect_material_property(orm_b_lerps[-1], "", unreal.MaterialProperty.MP_METALLIC)
# -*- coding: utf-8 -*- """ 设置 skeletalmesh 的 reduction 属性 """ from __future__ import division from __future__ import print_function from __future__ import absolute_import __author__ = 'timmyliang' __email__ = 'user@example.com' __date__ = '2021-07-19 21:24:27' import unreal # NOTES(timmyliang) 选择一个模型修改 (mesh,) = unreal.EditorUtilityLibrary.get_selected_assets() infos = mesh.get_editor_property("lod_info") info = infos[0] reduction_settings = info.get_editor_property("reduction_settings") verts = unreal.SkeletalMeshTerminationCriterion.SMTC_NUM_OF_VERTS # NOTES(timmyliang) 修改 Termination Criterion 为 vertices reduction_settings.set_editor_property("termination_criterion",verts) # NOTES(timmyliang) reduction_settings.set_editor_property("num_of_vert_percentage",0.2) info.set_editor_property("reduction_settings",reduction_settings) infos[0] = info mesh.set_editor_property("lod_info",infos)
import unreal from .char_asset_common import * from dataclasses import dataclass WIDGET_BP_PATH = '/project/.EUW_CharMarker' @dataclass class CharacterData: is_character: bool = False character_level: str = "" def button_on_confirmed(eus : unreal.EditorUtilitySubsystem, tab_id, widget_instance : unreal.EditorUtilityWidget, selected_assets : unreal.SkeletalMesh, trans : unreal.ScopedEditorTransaction): check_box_is_character : unreal.CheckBox = widget_instance.get_editor_property('CheckBoxIsCharacter') combo_box_character_level : unreal.ComboBoxString = widget_instance.get_editor_property('ComboBoxCharacterLevel') char_data = CharacterData( is_character=check_box_is_character.is_checked(), character_level=combo_box_character_level.get_selected_option() ) msg = "" if check_box_is_character and combo_box_character_level: for asset in selected_assets: esl = unreal.EditorAssetLibrary() if char_data.is_character: esl.set_metadata_tag(asset, 'SK.IsCharacter', "1") esl.set_metadata_tag(asset, 'SK.Character.Level', char_data.character_level) msg += f"资产 '{asset.get_name()}' 已被标记为 '角色', 且角色等级为 '{char_data.character_level}' \n" else: esl.set_metadata_tag(asset, 'SK.IsCharacter', "0") esl.set_metadata_tag(asset, 'SK.Character.Level', "NonCharacter") msg += f"资产 '{asset.get_name()}' 已被标记为 '非角色' \n" unreal.EditorDialog.show_message( title="角色标记成功", message=msg, message_type=unreal.AppMsgType.OK ) else: unreal.log_warning(f"[CharMarker] Some widgets are missing") trans.cancel() eus.close_tab_by_id(tab_id) def button_on_cancelled(eus : unreal.EditorUtilitySubsystem, tab_id): eus.close_tab_by_id(tab_id) def mark_character_assets(): global WIDGET_BP_PATH eul = unreal.EditorUtilityLibrary() selected_assets = eul.get_selected_assets() # check if the skeletal mesh asset for asset in selected_assets: if not isinstance(asset, unreal.SkeletalMesh): unreal.EditorDialog.show_message( title="角色标记失败", message=f"资产 '{asset.get_name()}' 不是一个有效的骨骼网格", message_type=unreal.AppMsgType.OK ) exit() # spawn the widget with unreal.ScopedEditorTransaction("Char Marker") as trans: widget_bp = unreal.EditorAssetLibrary.load_asset(WIDGET_BP_PATH) if not widget_bp: unreal.EditorDialog.show_message( title="角色标记失败", message=f"无法加载蓝图: {WIDGET_BP_PATH}", message_type=unreal.AppMsgType.OK ) trans.cancel() exit() eus = unreal.get_editor_subsystem(unreal.EditorUtilitySubsystem) widget_instance, tab_id = eus.spawn_and_register_tab_and_get_id(widget_bp) # get the ButtonConfirm widget try: button_confirm : unreal.Button= widget_instance.get_editor_property('ButtonConfirm') button_cancel : unreal.Button = widget_instance.get_editor_property('ButtonCancel') # function closure and binding if button_confirm and button_cancel: def confirm_handler(): button_on_confirmed(eus, tab_id, widget_instance, selected_assets, trans) button_confirm.on_clicked.add_callable(confirm_handler) def cancel_handler(): button_on_cancelled(eus, tab_id) button_cancel.on_clicked.add_callable(cancel_handler) else: unreal.log_warning(f"[CharMarker] Some widgets missing") trans.cancel() except Exception as e: trans.cancel()
import unreal import time anim_seqs = unreal.EditorUtilityLibrary.get_selected_assets() # 현재 열려 있는 레벨 시퀀스를 얻습니다. level_sequence:unreal.LevelSequence = unreal.LevelSequenceEditorBlueprintLibrary.get_current_level_sequence() def get_anim_section(): for binding in level_sequence.get_bindings(): # print(binding) for track in binding.get_tracks(): if isinstance(track, unreal.MovieSceneSkeletalAnimationTrack): skeletal_animation_sections = track.get_sections() print(track) #print(track) print(skeletal_animation_sections[0].params.animation) ## anim asset section return skeletal_animation_sections[0] def on_render_movie_finished(success): print("Movie has finished rendering. Python can now invoke another movie render if needed. Sucess: " + str(success)) is_rendering_movie = unreal.SequencerTools.is_rendering_movie() for anim_seq in anim_seqs: section = get_anim_section() section.params.animation = anim_seq directory_path:str = 'E:/temp/' + anim_seq.get_name() sequencer_asset_path = '/project/.SQ_ENVCHECk' capture_settings = unreal.AutomatedLevelSequenceCapture() capture_settings.level_sequence_asset = unreal.SoftObjectPath(sequencer_asset_path) capture_settings.set_image_capture_protocol_type(unreal.load_class(None, "/project/.ImageSequenceProtocol_PNG")) capture_settings.settings.resolution.res_x = 256 capture_settings.settings.resolution.res_y = 256 capture_settings.settings.output_directory = unreal.DirectoryPath(directory_path) capture_settings.settings.use_custom_frame_rate = True capture_settings.settings.custom_frame_rate = unreal.FrameRate(12,1) capture_settings.warm_up_frame_count = 3.0 capture_settings.delay_before_warm_up = 1.0 capture_settings.delay_before_shot_warm_up = 1.0 on_finished_callback = unreal.OnRenderMovieStopped() on_finished_callback.bind_callable(on_render_movie_finished) print("Rendering to movie...") unreal.SequencerTools.render_movie(capture_settings, on_finished_callback) #time.sleep(15) print('----script end') # @Todo : 캡처 Await 걸기
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 chameleon_json: self.add_chameleon_shortcut(id, chameleon_json) elif py_cmd: self.add_py_code_shortcut(id, py_cmd) 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_chameleon_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
# 本脚本主要用于重新合并选中的 static mesh。 # 说明: # 1. 本脚本是基于 export_glb.py 修改的 # 2. 由于某些 uasset 直接导出 glb 会出错(ue默认导出设置)。所以有了本脚本,针对 error list 中的 uasset,先进行合并处理,之后再统一使用命令行导出 # 操作步骤: # 1. 修改基础变量 # 2. 选中需要被合并的 static mesh,执行本脚本即可 # 变量说明: # 1. error_list:需要本重新合并的列表 # 2. save_path:合并后的模型存储位置 import unreal import os import pandas as pd error_list = pd.read_csv(r"D:/project/.csv") save_path = r"/project/" merge_setting = unreal.MeshMergingSettings() merge_setting.pivot_point_at_zero = True merge_options = unreal.MergeStaticMeshActorsOptions( destroy_source_actors = False, spawn_merged_actor = False, mesh_merging_settings = merge_setting ) selectionAssets = unreal.EditorUtilityLibrary().get_selected_assets() asset_paths = [item.get_path_name() for item in selectionAssets] for asset_path in asset_paths: asset = unreal.EditorAssetLibrary.load_asset(asset_path.split('.')[0]) if asset.get_name().replace("SM_",'').replace('_','.') in error_list['File Name'].values: actor = unreal.EditorActorSubsystem().spawn_actor_from_object(asset, unreal.Vector(0, 0, 0), unreal.Rotator(0, 0, 180)) actor_name = "Merge_" + actor.get_actor_label() actor_path = os.path.join(save_path, actor_name) if isinstance(actor, unreal.StaticMeshActor): merge_options.base_package_name = actor_path # The package path you want to save to merge_actor = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem).merge_static_mesh_actors([actor],merge_options) actor.destroy_actor()
# coding: utf-8 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) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", "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", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() ###### 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 print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller()#rig.controller else: c = rig.controller g = c.get_graph() n = g.get_nodes() print(n) #c.add_branch_node() #c.add_array_pin() a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() # print(a) # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items' or node.get_node_title() == 'Collection from 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=Bone' in pin.get_default_value(): collectionItem_forBone= node if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) ## 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 # 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()) # bone array if (collectionItem_forBone == None): collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) ## h_mod rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] print(items_forControl) print(items_forBone) humanoidBoneTable = {"dummy" : "dummy"} humanoidBoneTable.clear() for h in meta.humanoid_bone_table: bone_h = "{}".format(h).lower() bone_m = "{}".format(meta.humanoid_bone_table[h]).lower() try: i = list(humanoidBoneTable.values()).index(bone_m) except: i = -1 if (bone_h!="" and bone_m!="" and i==-1): humanoidBoneTable[bone_h] = bone_m for bone_h in humanoidBoneList: bone_m = humanoidBoneTable.get(bone_h, None) if bone_m == None: continue #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): if (True): tmp = '(Type=Bone,Name=' #tmp += "{}".format(bone_m).lower() tmp += bone_m tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) #print(bone_m) tmp = '(Type=Control,Name=' #tmp += "{}".format(bone_h).lower() + '_c' tmp += bone_h + '_c' tmp += ')' #print(c) c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) #print(bone_h) #for e in h_mod.get_elements(): # 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) # print(e.name) # if (e.type == unreal.RigElementType.BONE): # tmp = '(Type=Bone,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) # print(e.name) #print(i.get_all_pins_recursively()) #ii:unreal.RigUnit_CollectionItems = n[1] #pp = ii.get_editor_property('Items') #print(pp) #print(collectionItem.get_all_pins_recursively()[0]) #i.get_editor_property("Items") #c.add_array_pin("Execute") # arrayを伸ばす #i.get_all_pins_recursively()[0].get_pin_path() #c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)') #rig = rigs[10]
# Transfer a folder of images into the Unreal Editor Sequencer. # Author: Atom # This script will scan a folder for image files with a specific file extension. # A companion mesh will be generated for each file found in the folder. # A material will be assigned to the mesh linking the image. # (c) 2020 Atom # 10/project/ import unreal import os, re, platform, random import struct, imghdr # ------------------------------------------------------------------------------ # Constants/Controls # Sequence time in seconds SEQUENCE_LENGTH = 12 LOC_CHANNELS = [ 'Location.X', 'Location.Y', 'Location.Z', ] ROT_CHANNELS = 'Rotation.X', 'Rotation.Y', 'Rotation.Z', ] SCALE_CHANNELS = 'Scale.X', 'Scale.Y', 'Scale.Z', ] # ------------------------------------------------------------------------------ # Unreal Editor Sequencer functions. def add_actor_to_sequence(target_sequence, actor): """ Add the specified actor into the target sequence with keys :param unreal.MovieSceneSequence target_sequence: The sequence to add to :param unreal.Actor actor: The image to be added :return: """ frame_rate = target_sequence.get_display_rate() frame_rate = frame_rate.numerator / frame_rate.denominator # Fetch actor transform values. actor_location = actor.get_actor_location() actor_location = [actor_location.x, actor_location.y, actor_location.z] actor_rotation = actor.get_actor_rotation() actor_rotation = [actor_rotation.roll, actor_rotation.pitch, actor_rotation.yaw] actor_size = actor.get_actor_relative_scale3d() #get_actor_scale3d() actor_size = [actor_size.x,actor_size.y,actor_size.z] sequence = target_sequence.add_possessable(actor) transform_track = sequence.add_track(unreal.MovieScene3DTransformTrack) new_section = transform_track.add_section() new_section.set_range_seconds(0, SEQUENCE_LENGTH) # Drop down a single keyframe. channels = new_section.get_channels() for channel in channels: channel_name = channel.get_name() if channel_name in LOC_CHANNELS: # Key location chanel channel_index = LOC_CHANNELS.index(channel_name) channel.add_key( unreal.FrameNumber(0), actor_location[channel_index], interpolation=unreal.MovieSceneKeyInterpolation.LINEAR #AUTO, BREAK, CONSTANT, LINEAR, USER. ) if channel_name in ROT_CHANNELS: # Key location chanel channel_index = ROT_CHANNELS.index(channel_name) channel.add_key( unreal.FrameNumber(0), actor_rotation[channel_index], interpolation=unreal.MovieSceneKeyInterpolation.LINEAR ) if channel_name in SCALE_CHANNELS: channel_index = SCALE_CHANNELS.index(channel_name) channel.add_key( unreal.FrameNumber(0), actor_size[channel_index], interpolation=unreal.MovieSceneKeyInterpolation.LINEAR ) ''' channel.add_key( unreal.FrameNumber(SEQUENCE_LENGTH * frame_rate), adjusted_location[channel_index], interpolation=unreal.MovieSceneKeyInterpolation.LINEAR ) ''' def create_new_level_sequence(new_level_sequence_path, new_level_sequence_name): """ Create a new level sequence in engine :param str new_level_sequence_path: the new level sequence target directory :param str new_level_sequence_name: name of the new level to be created :return: The new level sequence if it was created, or None if it failed :rtype: unreal.LevelSequence | NoneType """ asset_tools = unreal.AssetToolsHelpers.get_asset_tools() return asset_tools.create_asset( asset_name=new_level_sequence_name, package_path=new_level_sequence_path, asset_class=unreal.LevelSequence, factory=unreal.LevelSequenceFactoryNew() ) def returnValidUnrealMaterialName(passedItem): # Replace any illegal characters for names here. s = re.sub("^0-9a-zA-Z\.]+", "_", passedItem) s = s.replace(".","_") return s def get_image_size(file_path): """ Return (width, height) for a given img file content - no external dependencies except the os and struct modules from core """ with open(file_path, 'rb') as fhandle: head = fhandle.read(24) if len(head) != 24: return if imghdr.what(file_path) == 'png': check = struct.unpack('>i', head[4:8])[0] if check != 0x0d0a1a0a: return width, height = struct.unpack('>ii', head[16:24]) elif imghdr.what(file_path) == 'gif': width, height = struct.unpack('<HH', head[6:10]) elif imghdr.what(file_path) == 'jpeg': try: fhandle.seek(0) # Read 0xff next size = 2 ftype = 0 while not 0xc0 <= ftype <= 0xcf: fhandle.seek(size, 1) byte = fhandle.read(1) while ord(byte) == 0xff: byte = fhandle.read(1) ftype = ord(byte) size = struct.unpack('>H', fhandle.read(2))[0] - 2 # We are at a SOFn block fhandle.seek(1, 1) # Skip `precision' byte. height, width = struct.unpack('&gt;HH', fhandle.read(4)) except Exception: #IGNORE:W0703 return else: return return width, height def returnFilesLike(passedFolderName, passedFileExtension = ".jpg"): result = ] #print passedFolderName for file in os.listdir(passedFolderName): if file.endswith(passedFileExtension): result.append(os.path.join(passedFolderName,file)) return result def importListOfImageMaps(passedList, passedTargetFolder): lst_texture2D = ] data = unreal.AutomatedAssetImportData() data.set_editor_property('destination_path', passedTargetFolder) # Unreal game folder. data.set_editor_property('filenames', passedList) lst_texture2D = unreal.AssetToolsHelpers.get_asset_tools().import_assets_automated(data) return lst_texture2D def createNewImageMapOpaqueMaterial(passedAssetPath, passedMaterialName, passedDiffuseTexture, passedNormalTexture, passedDiffuseColor, passedSpec, passedRough): # Create a material. assetTools = unreal.AssetToolsHelpers.get_asset_tools() mf = unreal.MaterialFactoryNew() mat_closure = assetTools.create_asset("M_%s" % passedMaterialName, passedAssetPath, unreal.Material, mf) mat_closure.set_editor_property("blend_mode", unreal.BlendMode.BLEND_TRANSLUCENT) #BLEND_TRANSLUCENT, BLEND_OPAQUE, BLEND_MASKED # Make a texture diffuse node. if passedDiffuseTexture!=None: # Add an image node. ts_node_diffuse = unreal.MaterialEditingLibrary.create_material_expression(mat_closure,unreal.MaterialExpressionTextureSample,-384,-200) ts_node_diffuse.texture = passedDiffuseTexture unreal.MaterialEditingLibrary.connect_material_property(ts_node_diffuse, "RGB", unreal.MaterialProperty.MP_BASE_COLOR) unreal.MaterialEditingLibrary.connect_material_property(ts_node_diffuse, "A", unreal.MaterialProperty.MP_OPACITY) else: # Add a color constant node. ts_node_diffuse = unreal.MaterialEditingLibrary.create_material_expression(mat_closure,unreal.MaterialExpressionConstant3Vector,-384,-200) value = unreal.LinearColor(float(passedDiffuseColor[0]),float(passedDiffuseColor[1]),float(passedDiffuseColor[2]),1.0) ts_node_diffuse.set_editor_property("constant", value) unreal.MaterialEditingLibrary.connect_material_property(ts_node_diffuse, "", unreal.MaterialProperty.MP_BASE_COLOR) # Make a texture normal node. if passedNormalTexture!=None: ts_node_normal = unreal.MaterialEditingLibrary.create_material_expression(mat_closure,unreal.MaterialExpressionTextureSample,-384,200) unreal.MaterialEditingLibrary.connect_material_property(ts_node_normal, "RGB", unreal.MaterialProperty.MP_NORMAL) # Change this sampler color sample type to work with normal types. ts_node_normal.sampler_type = unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL ts_node_normal.texture = passedNormalTexture # Make a constant float node. ts_node_roughness = unreal.MaterialEditingLibrary.create_material_expression(mat_closure,unreal.MaterialExpressionConstant,-125,150) ts_node_roughness.set_editor_property('R', passedRough) unreal.MaterialEditingLibrary.connect_material_property(ts_node_roughness, "", unreal.MaterialProperty.MP_ROUGHNESS) # Make a constant float node. ts_node_specular = unreal.MaterialEditingLibrary.create_material_expression(mat_closure,unreal.MaterialExpressionConstant,-125,50) ts_node_specular.set_editor_property('R', passedSpec) unreal.MaterialEditingLibrary.connect_material_property(ts_node_specular, "", unreal.MaterialProperty.MP_SPECULAR) unreal.MaterialEditingLibrary.recompile_material(mat_closure) return mat_closure def imagesToPlanes (passedPath, passedType, passedMaterialPath, passedTexturePath): lst_files = returnFilesLike(passedPath, passedType) if len(lst_files): as_cube = True # Make a new sequence to stage new candidates. local_path = os.path.dirname(passedMaterialPath) print local_path new_sequence = create_new_level_sequence(local_path, 'FolderToSequence') print new_sequence # Collect list of image files associated with this folder. lst_textures = importListOfImageMaps(lst_files, texture_path) #should match the length of list_files. for i,file in enumerate(lst_files): depth = i * 25.0 thickness = 0.0005 w,h = get_image_size(file) # Create a map file asset for each image in our list. local_name = os.path.basename(file) local_name_only = os.path.splitext(local_name)[0] shader_name = returnValidUnrealMaterialName("%s" % local_name_only) mesh_name = returnValidUnrealMaterialName("SM_iap_%s" % local_name_only) # Defaults for new material. reflection_weight = 0.1 reflection_roughness = 0.23 diffuse_color = [0.18,0.18,0.18] temp_material = createNewImageMapOpaqueMaterial(passedMaterialPath, shader_name, lst_textures*, None, diffuse_color, reflection_weight, reflection_roughness) # Make a static mesh plane. ell = unreal.EditorLevelLibrary eal = unreal.EditorAssetLibrary mesh_actor = ell.spawn_actor_from_class(unreal.StaticMeshActor.static_class(), unreal.Vector(depth, 0, 100), unreal.Rotator(0, 0, 0)) mesh_actor.set_actor_label(mesh_name) mesh_comp = mesh_actor.get_component_by_class(unreal.StaticMeshComponent.static_class()) if as_cube: temp_mesh = eal.load_asset("StaticMesh'/project/.Cube'") # Assume asset is created at default scale of 1.0. else: temp_mesh = eal.load_asset("StaticMesh'/project/.Plane'") # Assume asset is created at default scale of 1.0. mesh_comp.set_static_mesh(temp_mesh) mesh_comp.set_editor_property("override_materials", [temp_material]) if w != -1: # Guestimate from brief file header review. mesh_comp.set_editor_property("relative_scale3d", unreal.Vector(thickness, w*0.001, h*0.001)) else: # Default to 16:9. mesh_comp.set_editor_property("relative_scale3d", unreal.Vector(thickness, 1.6, 0.9)) # Set the aspect ratio of image here # Add this mesh to the sequencer. add_actor_to_sequence(new_sequence, mesh_actor) else: print"This combination %s].%s] produces no results." % (passedPath, passedType) # Program begins here. asset_path = "/Game" # Select which disk folder to scan. n = 3 if n==1: folder_path = r'/project/' extension = ".png" material_path = "%s/project/" % asset_path texture_path = "%s/project/" % asset_path if n==2: folder_path = r'/project/' extension = ".jpg" material_path = "%s/project/" % asset_path texture_path = "%s/project/" % asset_path if n==3: folder_path = r'/project/' extension = ".png" material_path = "%s/project/" % asset_path texture_path = "%s/project/" % asset_path if n==4: # Add your own path here and set n=4 pass imagesToPlanes (folder_path,extension,material_path,texture_path) print "Folder to Sequencer complete."
#레벨에서 선택된 액터들중 BP를 가져오고 그 BP안에 모든 SMcomp가 비어있다면 삭제, 하나라도 있으면 삭제X import unreal from Lib import __lib_topaz__ as topaz import importlib importlib.reload(topaz) all_actors = unreal.EditorLevelLibrary.get_selected_level_actors() for actor in all_actors: actor_class = actor.get_class() if isinstance(actor_class, unreal.BlueprintGeneratedClass): actor_components = actor.get_components_by_class(unreal.ActorComponent) has_static_mesh_component = False all_empty = True #초기 True설정 for component in actor_components: if isinstance(component, unreal.StaticMeshComponent): has_static_mesh_component = True static_mesh = component.static_mesh #SM없으면 패스 if static_mesh is None: pass elif static_mesh != None : #SM있으면 all_empty = False로 all_empty = False if not has_static_mesh_component: all_empty = False if all_empty == True : print("Blueprint Actor:", actor.get_actor_label(), "<<<") unreal.EditorLevelLibrary.destroy_actor(actor) else: pass
import sys import os import unreal from langchain_community.llms import LlamaCpp SCRIPT_DIR = os.path.join(unreal.Paths.project_plugins_dir(), "MinesweeperMind", "Content", "Scripts") if SCRIPT_DIR not in sys.path: sys.path.append(SCRIPT_DIR) unreal.log(f"Added {SCRIPT_DIR} to Python module search path.") try: from llm_manager import LLMManager except ModuleNotFoundError as e: unreal.log_error(f"Failed to import llm_manager: {e}") class MinesweeperAgent: """Loads and keeps the LLM in memory for Minesweeper decisions.""" def __init__(self): unreal.log("Initializing Minesweeper Agent LLM...") self.llm_manager = LLMManager() self.model_path = self.llm_manager.get_model_path() self.llm = LlamaCpp( model_path=self.model_path, n_gpu_layers=1, n_batch=512, n_ctx=2048, f16_kv=True, verbose=True, ) unreal.log("LLM successfully loaded into RAM.") def test_llm(): """Send a test request to the LLM and log the response.""" unreal.log("Testing LLM with sample query...") generator = GameDimensionGenerator() test_query = "Create an expert level Minesweeper grid." result = generator.generate_dimensions(test_query) unreal.log(f"LLM Response: {result}") if __name__ == "__main__": agent = MinesweeperAgent()
# Replaces all materials used in the scene with those materials with the same label placed in a new folder # Usefull when all the existing materials need to be replaced with new ones import unreal old_mat_path = "/project/" # Path to old material assets new_mat_path = "/project/" # Path to new material assets # Get all static mesh actors in the scene actor_list = unreal.EditorLevelLibrary.get_all_level_actors() actor_list = unreal.EditorFilterLibrary.by_class(actor_list, unreal.StaticMeshActor.static_class()) # Find all the assets on the "old" folder mat_list=unreal.EditorAssetLibrary.list_assets(old_mat_path, recursive=False, include_folder=False) for i in range(0, len(mat_list)): old_material = unreal.EditorAssetLibrary.load_asset(mat_list[i]) if old_material is None: print "The old material can't be loaded" quit() mat_name = mat_list[i].split('/')[-1].split('.')[-1] # Get material name from asset # In the 'new' folder, find the material that has the same name as the old material new_material = unreal.EditorAssetLibrary.load_asset(new_mat_path+'/'+mat_name) if new_material is None: print "The new material can't be loaded" quit() else: print new_material # Replace materials unreal.EditorLevelLibrary.replace_mesh_components_materials_on_actors(actor_list, old_material, new_material)
# coding: utf-8 import unreal import random # return: int : The index of the active viewport def getActiveViewportIndex(): return unreal.CppLib.get_active_viewport_index() # viewport_index: int : The index of the viewport you want to affect # location: obj unreal.Vector : The viewport location # rotation: obj unreal.Rotator : The viewport rotation def setViewportLocationAndRotation(viewport_index=1, location=unreal.Vector(), rotation=unreal.Rotator()): unreal.CppLib.set_viewport_location_and_rotation(viewport_index, location, rotation) # viewport_index: int : The index of the viewport you want to affect # actor: obj unreal.Actor : The actor you want to snap to def snapViewportToActor(viewport_index=1, actor=None): setViewportLocationAndRotation(viewport_index, actor.get_actor_location(), actor.get_actor_rotation()) def setViewportLocationAndRotation_EXAMPLE(): viewport_index = getActiveViewportIndex() setViewportLocationAndRotation(viewport_index, unreal.Vector(0.0, 0.0, 0.0), unreal.Rotator(0.0, 90.0, 0.0)) def snapViewportToActor_EXAMPLE(): actors_in_world = unreal.GameplayStatics.get_all_actors_of_class(unreal.EditorLevelLibrary.get_editor_world(), unreal.Actor) random_actor_in_world = actors_in_world[random.randrange(len(actors_in_world))] viewport_index = getActiveViewportIndex() snapViewportToActor(viewport_index, random_actor_in_world) # import EditorFunction_4 as ef # reload(ef) # ef.setViewportLocationAndRotation_EXAMPLE() # ef.snapViewportToActor_EXAMPLE()
import unreal selected_assets = unreal.EditorLevelLibrary.get_selected_level_actors() for actor in selected_assets: if isinstance(actor, unreal.StaticMeshActor): # Actor의 모든 컴포넌트 가져오기 actor_components = actor.get_components_by_class(unreal.ActorComponent) for comp in actor_components: # InstancedStaticMeshComponent인 경우 if isinstance(comp, unreal.InstancedStaticMeshComponent): comp_name = comp.get_name() mat_len = comp.get_num_materials() for i in range(mat_len): comp_mat = comp.get_material(i) print(comp_name, '>>>>>', comp_mat) elif isinstance(actor.get_class(), unreal.BlueprintGeneratedClass) : actor_components = actor.get_components_by_class(unreal.ActorComponent) for comp in actor_components: if isinstance(comp, unreal.StaticMeshComponent) or isinstance(comp, unreal.InstancedStaticMeshComponent) : print(comp.get_name(),'>>>>') else: pass
import unreal import os # 本脚本用于:将当前选中的asset加载进场景中,然后绕Z轴旋转180°,最后合并成一个新的static mesh,并保存到指定路径下 # 修改save_path变量,执行即可 save_path = r"/project/" merge_setting = unreal.MeshMergingSettings() merge_setting.pivot_point_at_zero = True merge_options = unreal.MergeStaticMeshActorsOptions( destroy_source_actors = False, spawn_merged_actor = False, mesh_merging_settings = merge_setting ) selectionAssets = unreal.EditorUtilityLibrary().get_selected_assets() asset_paths = [item.get_path_name() for item in selectionAssets] for asset_path in asset_paths: asset = unreal.EditorAssetLibrary.load_asset(asset_path.split('.')[0]) if asset and isinstance(asset, unreal.StaticMesh): actor = unreal.EditorActorSubsystem().spawn_actor_from_object(asset, unreal.Vector(0, 0, 0), unreal.Rotator(0, 0, 180)) actor.set_actor_rotation(unreal.Rotator(0, 0, 180), False) else: actor = None unreal.log("Asset is not a Static Mesh") actor_name = "Merge_180_" + actor.get_actor_label() actor_path = os.path.join(save_path, actor_name) if isinstance(actor, unreal.StaticMeshActor): merge_options.base_package_name = actor_path # The package path you want to save to merge_actor = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem).merge_static_mesh_actors([actor],merge_options) actor.destroy_actor() unreal.log("旋转180°!Merge完毕!")
import unreal __all__ = ['get_component_handles','get_component_objects','get_component_by_class', 'get_component_by_var_name','get_selected_assets','get_selected_asset','get_selected_level_actors','get_selected_level_actor','cutoff_nanite_tri', 'set_actor_tag_by_class','get_materials_from_staticmesh','is_translucent_exist','get_assets_in_folder','get_asset_filepath','get_cooked_dir','disable_ray_tracing', 'get_asset_from_static_mesh_actor','get_textures_list_from_materials','get_all_texture_assets_from_material_instance','get_actor_bound_size','set_texture_size_by_bound', 'log'] def __test__(): unreal.log('Topaz Test') def get_component_handles(blueprint_asset_path) -> unreal.Subsystem : ## 사용안해도됨, 다음 함수에서 호출해서 사용하는 함수, 핸들러 직접 물고싶으면 쓰셈 subsystem : unreal.Subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) blueprint_asset : unreal.Blueprint = unreal.load_asset(blueprint_asset_path) subobject_data_handles : unreal.Subsystem = subsystem.k2_gather_subobject_data_for_blueprint(blueprint_asset) return subobject_data_handles def get_component_objects(blueprint_asset_path : str) -> list[unreal.Object] : ## 컴포넌트 무식하게 다 긁어줌 objects : list[unreal.SubobjectDataSubsystem] = [] # init handles : unreal.SubobjectDataHandle = 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 : unreal.Blueprint, component_class_to_find : unreal.Class) -> list[unreal.Object] : ## 컴포넌트중에 클래스 맞는것만 리턴해줌 ''' Use Case : topaz.get_component_by_class([블루프린트(어셋)], [찾을 컴포넌트 클래스]) 주의점 : unreal.StaticMesh 등과 같은 어셋 오브젝트가 아니라 unreal.StaticMeshComponent 등과 같은 컴포넌트 오브젝트를 넣어야 합니다. ''' components = [] asset_path : list[str] = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(blueprint_to_find_components) component_objects : list[unreal.Class] = get_component_objects(asset_path) for each in component_objects: compare_class : bool = (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 def get_selected_assets(get_path : bool = False) -> list[unreal.Object]: #리스트로 선택된 오브젝트 리턴 ''' ## Use Case boo : list[unreal.objectbase_] = topaz.get_selected_assets() boo : list[unreal.objectbase_] = topaz.get_selected_assets(False) boo : list[str] = topaz.get_selected_assets(True) ''' assets = unreal.EditorUtilityLibrary.get_selected_assets() if get_path : asset_paths = [] for asset in assets : asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(asset) asset_paths.append(asset_path) return asset_paths else : return assets def get_selected_asset(get_path : bool = False) -> unreal.Object: #단일 선택 오브젝트 리턴 ''' ## Use Case boo : unreal.objectbase_ = topaz.get_selected_asset() boo : unreal.objectbase_ = topaz.get_selected_asset(False) boo : str = topaz.get_selected_asset(True) ''' if get_path : assets = get_selected_assets(True) else : assets = get_selected_assets(False) if len(assets) > 0: return assets[0] else: return None def get_selected_level_actors() -> list[unreal.Actor]: #리스트로 선택된 액터 리턴 actors = unreal.EditorLevelLibrary.get_selected_level_actors() return actors def get_selected_level_actor() -> unreal.Actor: #단일 액터 리턴 actors = get_selected_level_actors() if len(actors) > 0: return actors[0] else: return None def cutoff_nanite_tri(_static_mesh_ : unreal.StaticMesh) -> float : #나나이트가 특정 트라이 이상일때 나나이트 트라이 퍼센테이지 리턴해줌, legacy if _static_mesh_ is not None : tri = _static_mesh_.get_num_triangles(0) apprx_nanite_tri = tri * 27 if apprx_nanite_tri > 1000000 : __desired_triangle_percentage__ = 0.09 else : __desired_triangle_percentage__ = 0.25 return __desired_triangle_percentage__ def set_actor_tag_by_class(actor : unreal.Actor, seek_class : unreal.Class, desired_tag : str) : #액터에 태그 추가 actor_tags = actor.tags print(actor.get_class()) if desired_tag not in actor_tags : if actor.__class__ == seek_class : print('Tag Added') actor_tags.append(desired_tag) actor.set_actor_tags(actor_tags) else : print('Tag Not Added') def get_materials_from_staticmesh (static_mesh : unreal.StaticMesh, only_blend_mode : bool ) -> list[unreal.MaterialInterface] : #스태틱메쉬에서 메테리얼 리스트로 리턴 materials = [] blendmodes = [] for i in range(static_mesh.get_num_sections(0)): materials.append(static_mesh.get_material(i)) blendmodes.append(static_mesh.get_material(i).get_blend_mode()) if only_blend_mode : return blendmodes else : return materials def is_translucent_exist(blendmodes : list[unreal.BlendMode]) -> bool : #트랜스루센트가 있는지 확인 for blendmode in blendmodes : if blendmode == unreal.BlendMode.BLEND_TRANSLUCENT : return True return False def get_assets_in_folder(folder_path : str) -> list[str]: #폴더안에 있는 에셋들 리스트로 리턴 assets = unreal.EditorAssetLibrary.list_assets(folder_path, True, False) return assets def get_asset_filepath(asset : unreal.Object) -> str: #에셋파일 경로 리턴 asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(asset) return asset_path def get_cooked_dir () -> str : #Saved 디렉토리 리턴 saved_dir = unreal.Paths.project_saved_dir() cooked_dir = saved_dir + 'Cooked/Windows' print(cooked_dir) return cooked_dir def disable_ray_tracing(static_mesh : unreal.StaticMesh) -> None : #레이트레이싱 끄기 is_ray_tracing = static_mesh.get_editor_property('support_ray_tracing') if is_ray_tracing : static_mesh.set_editor_property('support_ray_tracing', False) print(static_mesh.get_editor_property('support_ray_tracing')) def get_asset_from_static_mesh_actor (actor : unreal.Actor) -> unreal.StaticMesh : #액터에서 스태틱메쉬 리턴 static_mesh = actor.static_mesh_component.static_mesh return static_mesh def get_textures_list_from_materials(materials : list[unreal.MaterialInterface]) -> list[unreal.Texture] : #메테리얼에서 텍스쳐 리스트로 리턴 textures = [] for material in materials : for i in range(material.get_num_texture_parameters()): textures.append(material.get_texture_parameter_name(i)) return textures def get_actor_bound_size(actor : unreal.Actor) -> float : #액터 바운드 사이즈를 퓨어하게 리턴 bound = actor.get_actor_bounds(False, True) pure_bound = bound[0] distance = pure_bound.distance(bound[1]) length = pure_bound.length() print('distance = ' + str(distance)) print('length = ' + str(length)) return distance def set_texture_size_by_bound(bound_size : float, texture : unreal.Texture ) -> None : #텍스쳐 사이즈 바운드 사이즈로 설정 size_small : float = 100.0 size_medium : float = 1000.0 size_large : float = 10000.0 print(bound_size) if bound_size < size_small : # in case of small size actor texture.set_editor_property('max_texture_size', 512) elif bound_size >= size_small and bound_size < size_medium : # in case of medium size actor texture.set_editor_property('max_texture_size', 1024) elif bound_size >= size_medium and bound_size < size_large : # in case of large size actor texture.set_editor_property('max_texture_size', 2048) else : # in case of huge size actor texture.set_editor_property('max_texture_size', 2048) print('Size is too large, but maximum texture size is set to 2048') def get_all_texture_assets_from_material_instance(material_instance : unreal.MaterialInstance) -> list[unreal.Texture] : #메테리얼 인스턴스에서 텍스쳐 리스트로 리턴 textures = [] for i in range(material_instance.get_num_texture_parameters()): textures.append(material_instance.get_texture_parameter_name(i)) return textures def export_staticmesh_to_fbx( static_mesh : unreal.StaticMesh, fbx_file_path : str): #staticMeshExporter exportTask = unreal.AssetExportTask() exportTask.automated = True exportTask.filename = fbx_file_path exportTask.object = static_mesh exportTask.options = unreal.FbxExportOption() exportTask.prompt = False fbxExporter = unreal.StaticMeshExporterFBX() exportTask.exporter = fbxExporter fbxExporter.run_asset_export_task(exportTask) return True def reimport_texture ( texture_asset: unreal.Texture2D, tga_file_path : str) : #textureReimporter importTask = unreal.AssetImportTask() importTask.automated = True importTask.filename = tga_file_path importTask.destination_path = unreal.Paths.project_content_dir() importTask.replace_existing = True importTask.save = True importTask.factory = unreal.TextureFactory() importTask.options = unreal.TextureFactory() textureFactory = unreal.TextureFactory() importTask.factory = textureFactory textureFactory.run_asset_import_task(importTask) return True class export_texture_task : def __init__(self) : pass def png (self, texture_asset : unreal.Texture2D, file_path : str) : #textureExporter exportTask = unreal.AssetExportTask() exportTask.automated = True exportTask.filename = file_path exportTask.object = texture_asset exportTask.options = unreal.TextureExporterPNG() exportTask.prompt = False Exporter = unreal.TextureExporterPNG() exportTask.exporter = Exporter Exporter.run_asset_export_task(exportTask) return True def tga (self, texture_asset : unreal.Texture2D, file_path : str) : #textureExporter exportTask = unreal.AssetExportTask() exportTask.automated = True exportTask.filename = file_path exportTask.object = texture_asset exportTask.options = unreal.TextureExporterTGA() exportTask.prompt = False Exporter = unreal.TextureExporterTGA() exportTask.exporter = Exporter Exporter.run_asset_export_task(exportTask) return True def jpeg (self, texture_asset : unreal.Texture2D, file_path : str) : #textureExporter exportTask = unreal.AssetExportTask() exportTask.automated = True exportTask.filename = file_path exportTask.object = texture_asset exportTask.options = unreal.TextureExporterJPEG() exportTask.prompt = False Exporter = unreal.TextureExporterJPEG() exportTask.exporter = Exporter Exporter.run_asset_export_task(exportTask) return True def exr (self, texture_asset : unreal.Texture2D, file_path : str) : exportTask = unreal.AssetExportTask() exportTask.automated = True exportTask.filename = file_path exportTask.object = texture_asset exportTask.options = unreal.TextureExporterEXR() exportTask.prompt = False Exporter = unreal.TextureExporterEXR() exportTask.exporter = Exporter Exporter.run_asset_export_task(exportTask) return True def expoert_selected_asset (asset : unreal.Object, destination : str) : asset_path : str = asset.get_path_name() unreal.AssetToolsHelpers.get_asset_tools().export_to_disk(asset_path, destination) return True ###Initialised message when loaded ### unreal.log('Topaz initialised...')
''' File: Author: Date: Description: Base script that will take x HighResShot2 screenshots of the Unreal Editor at different camera locations then return the camera to the starting HOME point. Actions are based on the '.register_slate_post_tick_callback()' method to create a new asynchronous process, where the '.tick()' method mimics a separate thread (NOTE: UE4 scripting does not support multi-threading, this meerly ACTS like a multi-thread. Other Notes: Do not use time.sleep(). It will throw everything off ''' import unreal class MoveCamera(object): def __init__(self, iterations): # Threading setup self.frame_count = 0 self.ticks_per_action = 5 self.max_count = iterations*self.ticks_per_action # Camera setup self.cam = None self.cam_scene = None self.cam_home = unreal.Vector(x=0, y=0, z=0) self.get_cam_info() def get_cam_info(self): self.cam = unreal.EditorLevelLibrary.get_selected_level_actors() self.cam_scene = self.cam[0].scene_component self.cam_home = unreal.Vector(x=-150, y=-60, z=150) print(f"HOME Camera location: {self.cam_home}") def start(self): if self.frame_count != 0: print("Please wait until first call is done.") else: self.slate_post_tick_handle = \ unreal.register_slate_post_tick_callback(self.tick) self.frame_count = 0 print("Test") def tick(self, delta_time: float): print(self.frame_count) # Potentially end the thread if self.frame_count > self.max_count: # End tick and any changes unreal.unregister_slate_post_tick_callback( self.slate_post_tick_handle) ####################################################### # Perform Actions at ticks ####################################################### # 1) Reset at end of actions if self.frame_count == self.max_count: # Reset before the end of the thread self.teleport_camera_home(home=self.cam_home) # 2) Move camera then take a snapshot elif self.frame_count % self.ticks_per_action == 0: self.take_HighResShot2() self.teleport_camera(_x=self.cam_home.x + 0*self.frame_count, _y=self.cam_home.y + 0*self.frame_count, _z=self.cam_home.z + 20*self.frame_count) self.frame_count += 1 ####################################################### # CineCameraActor Methods ####################################################### def take_HighResShot2(self): print("***** Take screenshot of current Editor") unreal.SystemLibrary.execute_console_command( unreal.EditorLevelLibrary.get_editor_world(), "HighResShot 2") def teleport_camera(self, _x, _y, _z): # Move first self.cam_scene.set_world_location(new_location=[_x, _y, _z], sweep=False, teleport=True) current_loc = self.cam_scene.get_world_location() print(f"ALTERED Camera location: {current_loc}") def teleport_camera_home(self, home): print("*** Return camera to HOME position ***") self.teleport_camera(_x=home.x, _y=home.y, _z=home.z) test1 = MoveCamera(3) test1.start()
import textwrap import unreal import sys from typing import Dict, Any import os import uuid import time import traceback # Assuming a logging module similar to your example from utils import logging as log def execute_script(script_file, output_file, error_file, status_file): """Execute a Python script with output and error redirection.""" with open(output_file, 'w') as output_file_handle, open(error_file, 'w') as error_file_handle: original_stdout = sys.stdout original_stderr = sys.stderr sys.stdout = output_file_handle sys.stderr = error_file_handle success = True try: with open(script_file, 'r') as f: exec(f.read()) except Exception as e: traceback.print_exc() success = False finally: sys.stdout = original_stdout sys.stderr = original_stderr with open(status_file, 'w') as f: f.write('1' if success else '0') def get_log_line_count(): """ Get the current line count of the Unreal log file """ try: log_path = os.path.join(unreal.Paths.project_log_dir(), "Unreal.log") if os.path.exists(log_path): with open(log_path, 'r', encoding='utf-8', errors='ignore') as f: return sum(1 for _ in f) return 0 except Exception as e: log.log_error(f"Error getting log line count: {str(e)}") return 0 def get_recent_unreal_logs(start_line=None): """ Retrieve recent Unreal Engine log entries to provide context for errors Args: start_line: Optional line number to start from (to only get new logs) Returns: String containing log entries or None if logs couldn't be accessed """ try: log_path = os.path.join(unreal.Paths.project_log_dir(), "Unreal.log") if os.path.exists(log_path): with open(log_path, 'r', encoding='utf-8', errors='ignore') as f: if start_line is None: # Legacy behavior - get last 20 lines lines = f.readlines() return "".join(lines[-20:]) else: # Skip to the starting line for i, _ in enumerate(f): if i >= start_line - 1: break # Get all new lines new_lines = f.readlines() return "".join(new_lines) if new_lines else "No new log entries generated" return None except Exception as e: log.log_error(f"Error getting recent logs: {str(e)}") return None def handle_execute_python(command: Dict[str, Any]) -> Dict[str, Any]: """ Handle a command to execute a Python script in Unreal Engine Args: command: The command dictionary containing: - script: The Python code to execute as a string - force: Optional boolean to bypass safety checks (default: False) Returns: Response dictionary with success/failure status and output if successful """ try: script = command.get("script") force = command.get("force", False) if not script: log.log_error("Missing required parameter for execute_python: script") return {"success": False, "error": "Missing required parameter: script"} log.log_command("execute_python", f"Script: {script[:50]}...") # Get log line count before execution log_start_line = get_log_line_count() destructive_keywords = [ "unreal.EditorAssetLibrary.delete_asset", "unreal.EditorLevelLibrary.destroy_actor", "unreal.save_package", "os.remove", "shutil.rmtree", "file.write", "unreal.EditorAssetLibrary.save_asset" ] is_destructive = any(keyword in script for keyword in destructive_keywords) if is_destructive and not force: log.log_warning("Potentially destructive script detected") return { "success": False, "error": ("This script may involve destructive actions (e.g., deleting or saving files) " "not explicitly requested. Please confirm with 'Yes, execute it' or set force=True.") } temp_dir = os.path.join(unreal.Paths.project_saved_dir(), "Temp", "PythonExec") if not os.path.exists(temp_dir): os.makedirs(temp_dir) script_file = os.path.join(temp_dir, f"script_{uuid.uuid4().hex}.py") output_file = os.path.join(temp_dir, "output.txt") error_file = os.path.join(temp_dir, "error.txt") status_file = os.path.join(temp_dir, "status.txt") # Normalize user script indentation and write to file dedented_script = textwrap.dedent(script).strip() with open(script_file, 'w') as f: f.write(dedented_script) # Execute using the wrapper execute_script(script_file, output_file, error_file, status_file) time.sleep(0.5) # Allow execution to complete output = "" error = "" success = False if os.path.exists(output_file): with open(output_file, 'r') as f: output = f.read() if os.path.exists(error_file): with open(error_file, 'r') as f: error = f.read() if os.path.exists(status_file): with open(status_file, 'r') as f: success = f.read().strip() == "1" for file in [script_file, output_file, error_file, status_file]: if os.path.exists(file): os.remove(file) # Enhanced error handling for common Unreal API issues if not success and error: if "set_world_location() required argument 'sweep'" in error: error += "\n\nHINT: The set_world_location() method requires a 'sweep' parameter. Try: set_world_location(location, sweep=False)" elif "set_world_location() required argument 'teleport'" in error: error += "\n\nHINT: The set_world_location() method requires 'teleport' parameter. Try: set_world_location(location, sweep=False, teleport=False)" elif "set_actor_location() required argument 'teleport'" in error: error += "\n\nHINT: The set_actor_location() method requires a 'teleport' parameter. Try: set_actor_location(location, sweep=False, teleport=False)" # Get only new log entries recent_logs = get_recent_unreal_logs(log_start_line) if recent_logs: error += "\n\nNew Unreal logs during executio/project/" + recent_logs if success: # Get only new log entries for successful execution as well recent_logs = get_recent_unreal_logs(log_start_line) if recent_logs: output += "\n\nNew Unreal logs during executio/project/" + recent_logs log.log_result("execute_python", True, f"Script executed with output: {output}") return {"success": True, "output": output} else: log.log_error(f"Script execution failed with error: {error}") return {"success": False, "error": error if error else "Execution failed without specific error", "output": output} except Exception as e: log.log_error(f"Error handling execute_python: {str(e)}", include_traceback=True) return {"success": False, "error": str(e)} finally: for file in [script_file, output_file, error_file, status_file]: if os.path.exists(file): try: os.remove(file) except: pass def handle_execute_unreal_command(command: Dict[str, Any]) -> Dict[str, Any]: """ Handle a command to execute an Unreal Engine console command Args: command: The command dictionary containing: - command: The Unreal Engine console command to execute - force: Optional boolean to bypass safety checks (default: False) Returns: Response dictionary with success/failure status and output if successful """ script_file = None output_file = None error_file = None try: cmd = command.get("command") force = command.get("force", False) if not cmd: log.log_error("Missing required parameter for execute_unreal_command: command") return {"success": False, "error": "Missing required parameter: command"} if cmd.strip().lower().startswith("py "): log.log_error("Attempted to run a Python script with execute_unreal_command") return { "success": False, "error": ("Use 'execute_python' command to run Python scripts instead of 'execute_unreal_command' with 'py'. " "For example, send {'type': 'execute_python', 'script': 'your_code_here'}.") } log.log_command("execute_unreal_command", f"Command: {cmd}") # Get log line count before execution log_start_line = get_log_line_count() destructive_keywords = ["delete", "save", "quit", "exit", "restart"] is_destructive = any(keyword in cmd.lower() for keyword in destructive_keywords) if is_destructive and not force: log.log_warning("Potentially destructive command detected") return { "success": False, "error": ("This command may involve destructive actions (e.g., deleting or saving). " "Please confirm with 'Yes, execute it' or set force=True.") } # Execute the command world = unreal.EditorLevelLibrary.get_editor_world() unreal.SystemLibrary.execute_console_command(world, cmd) # Add a short delay to allow logs to be captured time.sleep(1.0) # Slightly longer delay to ensure logs are written # Get new log entries generated during command execution recent_logs = get_recent_unreal_logs(log_start_line) output = f"Command '{cmd}' executed successfully" if recent_logs: output += "\n\nRelated Unreal log/project/" + recent_logs log.log_result("execute_unreal_command", True, f"Command '{cmd}' executed") return {"success": True, "output": output} except Exception as e: # Get new log entries to provide context for the error recent_logs = get_recent_unreal_logs(log_start_line) if 'log_start_line' in locals() else None error_msg = f"Error executing command: {str(e)}" if recent_logs: error_msg += "\n\nUnreal logs around the time of erro/project/" + recent_logs log.log_error(f"Error handling execute_unreal_command: {str(e)}", include_traceback=True) return {"success": False, "error": error_msg}
import unreal def trace_screen(): start, rotation = unreal.EditorLevelLibrary.get_level_viewport_camera_info() end = start + rotation.get_forward_vector() * 10000.0 actors = unreal.EditorLevelLibrary.get_all_level_actors() result = unreal.SystemLibrary.line_trace_single(unreal.EditorLevelLibrary.get_editor_world(), start, end, unreal.TraceTypeQuery.TRACE_TYPE_QUERY1, True, [], unreal.DrawDebugTrace.FOR_DURATION, True, unreal.LinearColor(1.0, 0.0, 0.0, 1.0), unreal.LinearColor(0.0, 1.0, 0.0, 1.0)) return result def spawnActor(path, location): actor_class = unreal.EditorAssetLibrary.load_blueprint_class(path) actor_location = location actor_rotation = unreal.Rotator(0.0, 0.0, 0.0) unreal.EditorLevelLibrary.spawn_actor_from_class( actor_class, actor_location, actor_rotation) result = trace_screen() if result: loc = result.to_tuple()[5] path = '/project/' spawnActor(path, loc) unreal.log('Gen Road Edge Decal Successfully!') else: unreal.log_warning('No Location Found for Generation!')
# -*- coding: utf-8 -*- """ Created on Mon Apr 22 11:37:07 2024 @author: WillQuantique """ import unreal def Render(u_level_file, u_level_seq_file, u_preset_file, job_name:str, subsystem): """ Parameters ---------- u_level_file : Unreal path Path to level u_level_seq_file : Unreal path Path to sequence u_preset_file : Unreal path Path to movie render presets Returns ------- None. """ executor = unreal.MoviePipelinePIEExecutor() queue = subsystem.get_queue() queue.delete_all_jobs() # config render job with movie pipeline config job = queue.allocate_new_job(unreal.MoviePipelineExecutorJob) job.job_name = job_name job.map = unreal.SoftObjectPath(u_level_file) job.sequence = unreal.SoftObjectPath(u_level_seq_file) preset = unreal.EditorAssetLibrary.find_asset_data(u_preset_file).get_asset() job.set_configuration(preset) subsystem.render_queue_with_executor_instance(executor)
import unreal import json import os # Texture suffix mapping to material properties and sampler types TEXTURE_USAGE_MAP = { 'bsm': {'input': unreal.MaterialProperty.MP_BASE_COLOR, 'sampler_type': unreal.MaterialSamplerType.SAMPLERTYPE_COLOR}, 'Base': {'input': unreal.MaterialProperty.MP_BASE_COLOR, 'sampler_type': unreal.MaterialSamplerType.SAMPLERTYPE_COLOR}, 'Norm': {'input': unreal.MaterialProperty.MP_NORMAL, 'sampler_type': unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL}, 'nrm': {'input': unreal.MaterialProperty.MP_NORMAL, 'sampler_type': unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL}, 'rough':{'input': unreal.MaterialProperty.MP_ROUGHNESS, 'sampler_type': unreal.MaterialSamplerType.SAMPLERTYPE_LINEAR_COLOR}, 'metal':{'input': unreal.MaterialProperty.MP_METALLIC, 'sampler_type': unreal.MaterialSamplerType.SAMPLERTYPE_LINEAR_COLOR}, 'ao': {'input': unreal.MaterialProperty.MP_AMBIENT_OCCLUSION, 'sampler_type': unreal.MaterialSamplerType.SAMPLERTYPE_LINEAR_COLOR}, } def create_material_with_textures(material_name, texture_names, material_path='/project/'): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() factory = unreal.MaterialFactoryNew() material_asset_path = f"{material_path}/{material_name}" if unreal.EditorAssetLibrary.does_asset_exist(material_asset_path): material = unreal.EditorAssetLibrary.load_asset(material_asset_path) print(f"✏️ Editing existing material: {material_name}") else: material = asset_tools.create_asset(material_name, material_path, unreal.Material, factory) print(f"✨ Created new material: {material_name}") # Create nodes from textures for tex_name in texture_names: try: texture_asset_path = f"/project/{tex_name}" texture = unreal.load_asset(texture_asset_path) if not texture: print(f"❌ Texture not found: {texture_asset_path}") continue texture_sample = unreal.MaterialEditingLibrary.create_material_expression(material, unreal.MaterialExpressionTextureSample) texture_sample.texture = texture # Guess the suffix suffix = tex_name.split('_')[-1].lower() usage = TEXTURE_USAGE_MAP.get(suffix) if not usage: print(f"⚠️ Could not determine material input for {tex_name}") unreal.MaterialEditingLibrary.delete_material_expression(material, texture_sample) continue texture_sample.sampler_type = usage['sampler_type'] try: unreal.MaterialEditingLibrary.connect_material_property(texture_sample, '', usage['input']) print(f"🔗 Connected '{tex_name}' to {usage['input'].name} with sampler {usage['sampler_type'].name}") except Exception as e: print(f"🚫 Failed to connect '{tex_name}': {e}") unreal.MaterialEditingLibrary.delete_material_expression(material, texture_sample) except Exception as e: print(f"❌ Error processing texture {tex_name}: {e}") unreal.MaterialEditingLibrary.recompile_material(material) unreal.EditorAssetLibrary.save_loaded_asset(material) print("📂 Material saved.") def find_referenced_textures(json_file): with open(json_file, 'r') as file: data = json.load(file) def search_for_textures(obj): if isinstance(obj, dict): for key, value in obj.items(): if key == 'ReferencedTextures' and isinstance(value, list): print(f"🔍 Found 'ReferencedTextures' ({len(value)} textures):") textures = [] for texture in value: path = texture.get('ObjectPath', '') base_name = os.path.splitext(os.path.basename(path))[0] print(f" - {texture.get('ObjectName', 'Unknown')} | {path}") textures.append(base_name) return textures result = search_for_textures(value) if result: return result elif isinstance(obj, list): for item in obj: result = search_for_textures(item) if result: return result return [] return search_for_textures(data) # Change this path to your actual JSON file json_path = r"/project/.json" material_name = "M_Cable_Color_Tiling" print(f"📄 Checking: {os.path.basename(json_path)}") textures = find_referenced_textures(json_path) if textures: create_material_with_textures(material_name, textures) else: print("⚠️ No textures found in JSON.")
# Should be used with internal UE API in later versions of UE """ Auto create materials of Layout System based on data from materials_layout.json """ import re import unreal import os import json DO_OVERWRITE_EXISTING_MATERIALS = True with open("C:/project/ Projects/project/" "MaterialAutoAssign/project/.json", "r") as f: materials_data = json.load(f) # CHANGE ME EC_PARENT_MATERIAL = "/project/.M_Eldar01" # CHANGE ME MY_PARENT_MATERIAL = "/project/" MATERIAL_LOC_PREFIX = "D:/project/" MATERIAL_FILTER_PREFIX = "/project/" materials_data = {k: v for k, v in materials_data.items() if "Parent" in v and EC_PARENT_MATERIAL in v["Parent"]} def set_material_instance_texture(material_instance_asset, material_parameter, texture_path): if texture_path is None: return if not unreal.EditorAssetLibrary.does_asset_exist(texture_path): unreal.log_warning("Can't find texture: " + texture_path) return False tex_asset = unreal.EditorAssetLibrary.find_asset_data(texture_path).get_asset() return unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance_asset, material_parameter, tex_asset) base_material = unreal.EditorAssetLibrary.find_asset_data(MY_PARENT_MATERIAL) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() def create_material_instance(material_path, parameters_names_to_values): print(" ".join([str(x) for x in parameters_names_to_values.values()])) material_instance_name = os.path.basename(material_path) material_instance_folder = os.path.dirname(material_path) if unreal.EditorAssetLibrary.does_asset_exist(material_path): print(f"Warning: {material_path} already exists") if DO_OVERWRITE_EXISTING_MATERIALS: # material_instance_asset = unreal.EditorAssetLibrary.find_asset_data(material_path).get_asset() unreal.EditorAssetLibrary.delete_asset(material_path) else: return material_instance_asset = asset_tools.create_asset(material_instance_name, material_instance_folder, unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew()) unreal.MaterialEditingLibrary.set_material_instance_parent(material_instance_asset, base_material.get_asset()) for parameter_name, parameter_value in parameters_names_to_values.items(): set_material_instance_texture(material_instance_asset, parameter_name, parameter_value) unreal.EditorAssetLibrary.save_asset(material_path) asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() def get_texture_data(material_data): result = {} texture_data_key = None for k, v in material_data.items(): if k.startswith("TextureParameterValues"): texture_data_key = k for _, data in material_data[texture_data_key].items(): result_key = data["ParameterName"] result_value = data["ParameterValue"] result_value = re.search(r"Texture2D'(?P<path>[/a-zA-Z0-9_-]+)\.[a-zA-Z0-9_-]+'", result_value) if not result_value: raise ValueError(f"{data['ParameterValue']} doesn't match regex") result_value = result_value.group("path") result_value = result_value.replace("/project/", "/Game/") result[result_key] = result_value return result for material_path, material_data in materials_data.items(): material_game_path = material_path.replace(MATERIAL_LOC_PREFIX, "/Game/").replace(".json", "") if not material_path.startswith(MATERIAL_FILTER_PREFIX): continue texture_data = get_texture_data(material_data) texture_data = {k: v.replace("/project/", "/Game/") for k, v in texture_data.items()} ec_opaque_parameter_data = {"BaseColor": texture_data.get("Base Color", None), "Normal": texture_data.get("Normal Map", None), "Roughness": texture_data.get("Roughness Map", None), "Metal": texture_data.get("Metallic Map", None), "Specular": None} ec_opaque_masked_parameter_data = {"BaseColor": texture_data.get("Base Color", None), "Normal": texture_data.get("Normal Map", None), "Roughness": texture_data.get("Roughness Map", None), "Metal": texture_data.get("Metallic Map", None), "OpacityMask": texture_data.get("Opacity Map", None)} vertex_parameter_data = { "Base Color 1": texture_data.get("Base Color_A", None), "Base Color 2": texture_data.get("Base Color_B", None), "Metallic 1": texture_data.get("Metallic_A", None), "Metallic 2": texture_data.get("Metallic_B", None), "Normal 1": texture_data.get("Normal_A", None), "Normal 2": texture_data.get("Normal_B", None), "Roughness 1": texture_data.get("R_A", None), "Roughness 2": texture_data.get("R_B", None) } ec_bodypart_parameter_data = { "BaseColor": None, "Mask": texture_data.get("Color_Mask", None), "Metal": texture_data.get("Metallic", None), "Roughness": texture_data.get("Roughness", None), "Normal": texture_data.get("Normal_Map", None) } ec_sm_unique_parameter_data = { "BaseColor": texture_data.get("Base_Color", None), "Mask": texture_data.get("Color_Mask", None), "Metal": texture_data.get("Metallic", None), "Roughness": texture_data.get("Roughness", None), "Normal": texture_data.get("Normal_Map", None) } create_material_instance(material_game_path, ec_sm_unique_parameter_data)
# -*- coding: utf-8 -*- """ Module that contains the mca decorators at a base python level """ # mca python imports import ast import contextlib from collections import namedtuple import os import pathlib import sys import traceback from io import StringIO # Qt imports from PySide2.QtCore import Qt from PySide2.QtWidgets import QApplication, QSplitter, QMessageBox, QFileDialog from PySide2.QtGui import QIcon # software specific imports # mca python imports from mca.common.pyqt import common_windows from mca.common.utils import dcc_util, strings from mca.common.pyqt import syntax_highlighter from mca.ue.tools.scripteditor import output_text from mca.ue.tools.scripteditor.seutils import script_editor_utils from mca.ue.tools.scripteditor.codeeditor import code_editor # from mca.ue.tools.scripteditor.codeeditor.highlighter import py_highlight try: import unreal RUNNING_IN_UNREAL = True except: RUNNING_IN_UNREAL = False WINDOW = None CONFIG_PATH = script_editor_utils.get_local_prefs_file('unreal') class MATScriptEditor(common_windows.MCAMainWindow): VERSION = '1.0.0' def __init__(self, parent=None): root_path = os.path.dirname(os.path.realpath(__file__)) ui_path = os.path.join(root_path, 'ui', 'script_editor.ui') super().__init__(title='Script Editor', ui_path=ui_path, version=MATScriptEditor.VERSION, style='incrypt', parent=parent) ICONS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'resources', 'icons') CLEAR_ALL_ICON = QIcon(os.path.join(ICONS_PATH, 'clearAll')) CLEAR_HISTORY_ICON = QIcon(os.path.join(ICONS_PATH, 'clearHistory')) CLEAR_INPUT_ICON = QIcon(os.path.join(ICONS_PATH, 'clearInput')) EXECUTE_ICON = QIcon(os.path.join(ICONS_PATH, 'execute')) EXECUTE_ALL_ICON = QIcon(os.path.join(ICONS_PATH, 'executeAll')) self.ui.ui_run_all_btn.setIcon(EXECUTE_ALL_ICON) self.ui.ui_run_sel_btn.setIcon(EXECUTE_ICON) self.ui.ui_clear_script_btn.setIcon(CLEAR_INPUT_ICON) self.ui.ui_clear_log_btn.setIcon(CLEAR_HISTORY_ICON) self.ui.ui_clear_both_btn.setIcon(CLEAR_ALL_ICON) self.output_log = output_text.OutputTextWidget(self) self.splitter = QSplitter() self.splitter.setOrientation(Qt.Vertical) self.ui.output_vl.addWidget(self.splitter) self.splitter.addWidget(self.output_log) self.splitter.addWidget(self.ui.ui_tab_widget) self.ui_tabs = list() self.ui_tab_highlighters = list() self.register_traceback() self.load_tabs() QApplication.activeWindow() #################################### # Signals #################################### self.ui.ui_run_all_btn.clicked.connect(self.execute) self.ui.ui_run_sel_btn.clicked.connect(self.execute_sel) #self.ui.ui_tab_widget.returnPressed.connect(self.execute_sel) self.ui.ui_clear_log_btn.clicked.connect(self.clear_log) self.ui.ui_clear_script_btn.clicked.connect(self.clear_script) self.ui.ui_clear_both_btn.clicked.connect(self.clear_all) # self.ui.ui_save_action.triggered.connect(self.save_script) # self.ui.ui_open_action.triggered.connect(self.open_script) self.ui.actionTabs_to_Spaces.triggered.connect(self.convert_all_to_spaces) self.ui.actionSpaces_to_Tabs.triggered.connect(self.convert_all_to_tabs) self.ui.ui_tab_widget.tabBarClicked.connect(self.add_tab) self.ui.ui_tab_widget.tabCloseRequested.connect(self.remove_tab) #################################### # Slots #################################### def register_traceback(self): """ Link Unreal traceback """ def custom_traceback(exc_type, exc_value, exc_traceback=None): message = 'Error: {}: {}\n'.format(exc_type, exc_value) if exc_traceback: format_exception = traceback.format_tb(exc_traceback) for line in format_exception: message += line self.output_log.update_logger(message, 'error') sys.excepthook = custom_traceback def load_configs(self): """ During startup, load python script config file and initialize tab gui """ if not os.path.exists(CONFIG_PATH): self.load_tabs() return with open(CONFIG_PATH, 'r') as f: tab_configs = list() tab_config_dicts = ast.literal_eval(f.read()) for tab_config_dict in tab_config_dicts: tab_config = TabConfig(**tab_config_dict) tab_configs.append(tab_config) self.load_tabs(tab_configs) def load_tabs(self, tab_configs=None): """ Initialize python script tab gui from config object :param tab_configs: TabConfig. dataclass object storing python tab info """ folder = self.get_local_folder() files = os.listdir(path=folder) tabs = [os.path.join(folder, x) for x in files if pathlib.Path(x).suffix == '.py'] if not tabs: self.insert_tab(0, '', 'Python') #tab_configs = [TabConfig(0, 'Python', True, '')] return active_index = 0 for x, tab in enumerate(tabs): with open(tab, 'r') as f: file_name = os.path.basename(tab).split('.')[0] output = f.read() index = self.ui.ui_tab_widget.count() - 1 self.insert_tab(index, output, 'Python') self.ui_tabs.insert(index, file_name) self.ui.ui_tab_widget.setCurrentIndex(active_index) def insert_tab(self, index, command, label, guid=None): """ Insert a python tab into the tab widget :param index: int. tab index to insert :param command: str. python script command to add to the inserted tab :param label: str. title/label of the tab inserted """ script_edit = code_editor.CodeEditor() if not guid: guid = strings.generate_guid() script_edit.setObjectName(guid) self.ui_tabs.insert(index, guid) script_edit.setPlainText(command) highlight = syntax_highlighter.PythonHighlighter(script_edit.document()) self.ui.ui_tab_widget.insertTab(index, script_edit, label) self.ui_tab_highlighters.append(highlight) self.ui_tabs.append(script_edit) self.ui.ui_tab_widget.setCurrentIndex(index) def convert_all_to_spaces(self): """ Converts all the PlainTextWidget's tabs to spaces """ self.ui.ui_tab_widget.currentWidget().convert_all_to_spaces() def convert_all_to_tabs(self): """ Converts all the PlainTextWidget's spaces to tabs """ self.ui.ui_tab_widget.currentWidget().convert_all_to_tabs() def execute(self): """ Send all command in script area for mya to execute """ self.save_script() command = self.ui.ui_tab_widget.currentWidget().toPlainText() if RUNNING_IN_UNREAL: output = unreal.PythonScriptLibrary.execute_python_command_ex( python_command=command, execution_mode=unreal.PythonCommandExecutionMode.EXECUTE_FILE, file_execution_scope=unreal.PythonFileExecutionScope.PUBLIC ) self.output_log.update_logger(f"{command}") if not output: self.output_log.update_logger(f'print({command})') return self.send_formatted_output(output) else: with stdoutIO() as s: exec(command) output = s.getvalue() self.output_log.update_logger(f"{command}") self.send_basic_formatted_output(output) def execute_sel(self): """ Send selected command in script area for mya to execute """ self.save_script() command = self.ui.ui_tab_widget.currentWidget().textCursor().selection().toPlainText() if RUNNING_IN_UNREAL: output = unreal.PythonScriptLibrary.execute_python_command_ex( python_command=command, execution_mode=unreal.PythonCommandExecutionMode.EXECUTE_FILE, file_execution_scope=unreal.PythonFileExecutionScope.PUBLIC ) self.output_log.update_logger(f"{command}") # self.output_log.update_logger(f"{output}") # if not output or not output[1]: # output = unreal.PythonScriptLibrary.execute_python_command_ex( # python_command=f'print({command})', # execution_mode=unreal.PythonCommandExecutionMode.EXECUTE_FILE, # file_execution_scope=unreal.PythonFileExecutionScope.PUBLIC # ) self.send_formatted_output(output) else: with stdoutIO() as s: exec(command) output = s.getvalue() self.output_log.update_logger(f"{command}") self.send_basic_formatted_output(output) def send_formatted_output(self, output): """ Update ui field with messages """ if not output: return result, log_entries = output for entry in log_entries: if entry.type != unreal.PythonLogOutputType.INFO: self.output_log.update_logger(entry.output, 'error') else: self.output_log.update_logger(entry.output, 'info') def send_basic_formatted_output(self, output): """ Update ui field with messages """ if not output: return self.output_log.update_logger(output, 'info') def clear_log(self): """ Clear history logging area """ self.output_log.clear() def clear_script(self): self.ui.ui_tab_widget.currentWidget().setPlainText('') def clear_all(self): self.clear_script() self.clear_log() # endregion # region Tab Operation def add_tab(self, index): """ Add a python tab when 'Add' tab button is clicked """ if index == self.ui.ui_tab_widget.count() - 1: self.insert_tab(index, '', 'Python') def remove_tab(self, index): """ Remove a python tab :param index: int. removal tab index """ msg_box = QMessageBox(QMessageBox.Question, '', 'Delete the Current Tab?', QMessageBox.Yes | QMessageBox.No) usr_choice = msg_box.exec() if usr_choice == QMessageBox.Yes: if index != self.ui.ui_tab_widget.count() - 1: self.ui.ui_tab_widget.removeTab(index) self.ui.ui_tab_widget.setCurrentIndex(index-1) self.ui_tabs.remove(index) def open_script_dialog(self): """ Open python file to script edit area """ path = QFileDialog.getOpenFileName( parent=None, caption="Open Script", dir='', filter="*.py")[0] if not path: return with open(path, 'r') as f: file_name = os.path.basename(path) output = f.read() index = self.ui.ui_tab_widget.count() - 1 self.insert_tab(index, output, file_name) def save_script_dialog(self): """ Save script edit area as a python file """ path = QFileDialog.getSaveFileName( parent=None, caption="Save Script As...", dir='', filter="*.py")[0] if not path: return command = self.ui.ui_tab_widget.currentWidget().toPlainText() with open(path, 'w') as f: f.write(command) def save_script(self): folder = self.get_local_folder() idx = self.ui.ui_tab_widget.currentIndex() command = self.ui.ui_tab_widget.currentWidget().toPlainText() guid = self.ui_tabs[idx] file_name = os.path.join(folder, f'{guid}.py') with open(file_name, 'w') as f: f.write(command) def get_local_folder(self): app = dcc_util.application() folder = script_editor_utils.create_local_prefs_folder(app.lower()) return folder class TabConfig(namedtuple('TabConfig', ['index', 'label', 'active', 'command'])): """ Dataclass to store python script information in the tabs :param index: int. script tab index within the tab widget :param label: str. script tab title label :param active: bool. whether this tab is set to active (current) only one tab is allowed to be active :param command: str. script in the tab """ __slots__ = () @contextlib.contextmanager def stdoutIO(stdout=None): old = sys.stdout if stdout is None: stdout = StringIO() sys.stdout = stdout yield stdout sys.stdout = old def script_editor_cmd(): global WINDOW app = None if not QApplication.instance(): app = QApplication(sys.argv) try: window = WINDOW or MATScriptEditor() if RUNNING_IN_UNREAL: unreal.parent_external_window_to_slate(int(window.winId())) #if app: sys.exit(app.exec_()) except Exception as e: print(e)
# 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 instantiates an HDA that contains a TOP network. After the HDA itself has cooked (in on_post_process) we iterate over all TOP networks in the HDA and print their paths. Auto-bake is then enabled for PDG and the TOP networks are cooked. """ import os import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.pdg_pighead_grid_2_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def get_hda_directory(): """ Attempt to get the directory containing the .hda files. This is /project/. In newer versions of UE we can use ``unreal.SystemLibrary.get_system_path(asset)``, in older versions we manually construct the path to the plugin. Returns: (str): the path to the example hda directory or ``None``. """ if hasattr(unreal.SystemLibrary, 'get_system_path'): return os.path.dirname(os.path.normpath( unreal.SystemLibrary.get_system_path(get_test_hda()))) else: plugin_dir = os.path.join( os.path.normpath(unreal.Paths.project_plugins_dir()), 'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda' ) if not os.path.exists(plugin_dir): plugin_dir = os.path.join( os.path.normpath(unreal.Paths.engine_plugins_dir()), 'Runtime', 'HoudiniEngine', 'Content', 'Examples', 'hda' ) if not os.path.exists(plugin_dir): return None return plugin_dir def delete_instantiated_asset(): global _g_wrapper if _g_wrapper: result = _g_wrapper.delete_instantiated_asset() _g_wrapper = None return result else: return False def on_pre_instantiation(in_wrapper): print('on_pre_instantiation') # Set the hda_directory parameter to the directory that contains the # example .hda files hda_directory = get_hda_directory() print('Setting "hda_directory" to {0}'.format(hda_directory)) in_wrapper.set_string_parameter_value('hda_directory', hda_directory) # Cook the HDA (not PDG yet) in_wrapper.recook() def on_post_bake(in_wrapper, success): # in_wrapper.on_post_bake_delegate.remove_callable(on_post_bake) print('bake complete ... {}'.format('success' if success else 'failed')) def on_post_process(in_wrapper): print('on_post_process') # in_wrapper.on_post_processing_delegate.remove_callable(on_post_process) # Iterate over all PDG/TOP networks and nodes and log them print('TOP networks:') for network_path in in_wrapper.get_pdgtop_network_paths(): print('\t{}'.format(network_path)) for node_path in in_wrapper.get_pdgtop_node_paths(network_path): print('\t\t{}'.format(node_path)) # Enable PDG auto-bake (auto bake TOP nodes after they are cooked) in_wrapper.set_pdg_auto_bake_enabled(True) # Bind to PDG post bake delegate (called after all baking is complete) in_wrapper.on_post_pdg_bake_delegate.add_callable(on_post_bake) # Cook the specified TOP node in_wrapper.pdg_cook_node('topnet1', 'HE_OUT_PIGHEAD_GRID') def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset, disabling auto-cook of the asset _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False) # Bind to the on pre instantiation delegate (before the first cook) and # set parameters _g_wrapper.on_pre_instantiation_delegate.add_callable(on_pre_instantiation) # 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()
from typing import Any, Dict, List, NoReturn, Optional, Tuple, Type, Union import unreal import utils_actor from constants import ( DEFAULT_SEQUENCE_DATA_ASSET, DEFAULT_SEQUENCE_DIR, ENGINE_MAJOR_VERSION, ENGINE_MINOR_VERSION, MotionFrame, SequenceTransformKey, SubSystem, TransformKeys, data_asset_suffix, ) from utils import add_levels, get_levels, get_soft_object_path, get_world, new_world, save_current_level EditorLevelSequenceSub = SubSystem.EditorLevelSequenceSub EditorAssetSub = SubSystem.EditorAssetSub EditorLevelSub = SubSystem.EditorLevelSub ################################################################################ # misc def duplicate_binding(binding: unreal.SequencerBindingProxy) -> None: """For opening sequencer editor use `unreal.LevelSequenceEditorBlueprintLib rary.open_level_sequence(unreal.LevelSequence)` to open.""" exported_txt = EditorLevelSequenceSub.copy_bindings([binding]) EditorLevelSequenceSub.paste_bindings(exported_txt, unreal.MovieScenePasteBindingsParams()) # TODO: the event track would be lost after pasting, need to fix it def get_binding_id(binding: unreal.SequencerBindingProxy) -> unreal.MovieSceneObjectBindingID: """Get the MovieSceneObjectBindingID from a SequencerBindingProxy. Args: binding (unreal.SequencerBindingProxy): The SequencerBindingProxy object. Returns: unreal.MovieSceneObjectBindingID: The MovieSceneObjectBindingID extracted from the binding. """ binding_id = unreal.MovieSceneObjectBindingID() binding_id.set_editor_property('Guid', binding.binding_id) return binding_id 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: float = 30.0) -> int: if ENGINE_MAJOR_VERSION == 5: # animation fps == sequence fps # TODO: check if this is true 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: unreal.log_warning( f'anim fps {anim_frame_rate} != seq fps {seq_fps}, this would cause animation interpolation.' ) anim_len = animation_asset.get_editor_property('number_of_sampled_frames') elif ENGINE_MAJOR_VERSION == 4: anim_len = round(animation_asset.get_editor_property('sequence_length') * seq_fps) return anim_len ################################################################################ # sequencer session def find_binding_by_name(sequence: unreal.LevelSequence, name: str) -> unreal.SequencerBindingProxy: binding = sequence.find_binding_by_name(name=name) if binding.sequence is not None: return binding for binding in sequence.get_bindings(): binding: unreal.MovieSceneBindingProxy if binding.get_name() == name: return binding raise RuntimeError(f'Failed to find binding: {name}') def find_binding_by_class( sequence: unreal.LevelSequence, actor_class: Type[unreal.Actor] ) -> Optional[unreal.MovieSceneBindingProxy]: """Finds a Sequencer binding for the specified actor class in the given Level Sequence. Args: sequence (unreal.LevelSequence): The Level Sequence to search for the binding. actor_class (Type[unreal.Actor]): The class of the actor to find or create the binding for. Returns: Optional[unreal.MovieSceneBindingProxy]: The Sequencer binding for the actor class, or None if not found. """ bound_objects: List[unreal.SequencerBoundObjects] = unreal.SequencerTools.get_bound_objects( get_world(), sequence, sequence.get_bindings(), sequence.get_playback_range() ) for bound_object in bound_objects: if len(bound_object.bound_objects) == 0: continue if bound_object.bound_objects[0].static_class() == actor_class.static_class(): return bound_object.binding_proxy return None def find_or_create_binding_by_class( sequence: unreal.LevelSequence, actor_class: Type[unreal.Actor], spawn_in_sequence: bool = True ) -> unreal.MovieSceneBindingProxy: """Finds or creates a Sequencer binding for the specified actor class in the given Level Sequence. Args: sequence (unreal.LevelSequence): The Level Sequence to search for the binding. actor_class (Type[unreal.Actor]): The class of the actor to find or create the binding for. spawn_in_sequence (bool, optional): Whether to spawn the actor in the sequence if it doesn't exist. If False, the actor will be spawned in the world but not in the sequence. Defaults to True. Returns: unreal.MovieSceneBindingProxy: The Sequencer binding for the actor class. """ binding = find_binding_by_class(sequence, actor_class) if binding is not None: return binding if spawn_in_sequence: return sequence.add_spawnable_from_class(actor_class) else: return sequence.add_possessable(actor_class) def get_time(sequence: unreal.LevelSequence, frame: int) -> unreal.FrameNumber: """Initialize a FrameNumber from the given time and then convert it to a FrameTime with no sub-frame. Keys can only exist on whole FrameNumbers. And transform from our Display Rate to the internal tick resolution. Note: equals to multiply 800 """ time_as_frame_time = unreal.FrameTime(unreal.FrameNumber(frame)) frame_time = unreal.TimeManagementLibrary.transform_time( time_as_frame_time, sequence.get_display_rate(), sequence.get_tick_resolution() ) return unreal.FrameNumber(frame_time.frame_number.value) def get_value_from_channel(channel: unreal.MovieSceneScriptingFloatChannel) -> float: # XXX: hardcode for first key key: unreal.MovieSceneScriptingDoubleAsFloatKey = channel.get_keys()[0] return key.get_value() 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, ) = ( channel_scale_x, channel_scale_y, channel_scale_z, ) = (None, None, None) for channel in trans_section.get_all_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 elif channel.channel_name == 'Scale.X': channel_scale_x = channel elif channel.channel_name == 'Scale.Y': channel_scale_y = channel elif channel.channel_name == 'Scale.Z': channel_scale_z = 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 assert channel_scale_x is not None assert channel_scale_y is not None assert channel_scale_z is not None return ( channel_x, channel_y, channel_z, channel_roll, channel_pitch, channel_yaw, channel_scale_x, channel_scale_y, channel_scale_z, ) def set_transforms_by_section( trans_section: unreal.MovieScene3DTransformSection, trans_keys: Union[Dict, SequenceTransformKey, List[SequenceTransformKey], List[Dict]], ) -> None: """Set `loc & rot` keys to given `transform section` Args: trans_section (unreal.MovieScene3DTransformSection): section trans_keys (Union[SequenceTransformKey, List[SequenceTransformKey]]): transform keys, contains frame, location, rotation and interpolation 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() ... set_transforms_by_section(transform_section, [ ... SequenceTransformKey(frame=0, location=(0, 0, 0), rotation=(0, 0, 0), interpolation='CONSTANT'), ... ]) """ ( channel_x, channel_y, channel_z, channel_roll, channel_pitch, channel_yaw, channel_scale_x, channel_scale_y, channel_scale_z, ) = get_transform_channels_from_section(trans_section) if not isinstance(trans_keys, (list, tuple)): trans_keys = [trans_keys] if isinstance(trans_keys[0], dict): trans_keys = [SequenceTransformKey(**k) for k in trans_keys] for trans_key in trans_keys: trans_key: SequenceTransformKey key_frame = trans_key.frame key_type = trans_key.interpolation.value key_type_ = getattr(unreal.MovieSceneKeyInterpolation, key_type) key_time_ = unreal.FrameNumber(key_frame) if trans_key.location: loc_x, loc_y, loc_z = trans_key.location 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_) if trans_key.rotation: rot_x, rot_y, rot_z = trans_key.rotation 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_) if trans_key.scale: scale_x, scale_y, scale_z = trans_key.scale channel_scale_x.add_key(key_time_, scale_x, interpolation=key_type_) channel_scale_y.add_key(key_time_, scale_y, interpolation=key_type_) channel_scale_z.add_key(key_time_, scale_z, interpolation=key_type_) def set_animation_by_section( animation_section: unreal.MovieSceneSkeletalAnimationSection, animation_asset: unreal.SkeletalMesh, animation_length: Optional[int] = None, seq_fps: int = 30, ) -> None: 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 add_property_bool_track_to_binding( binding: unreal.SequencerBindingProxy, property_name: str, property_value: bool, ) -> Tuple[unreal.MovieSceneBoolTrack, unreal.MovieSceneBoolSection]: # 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.get_channels_by_type(unreal.MovieSceneScriptingBoolChannel): channel.set_default(property_value) return bool_track, bool_section def add_property_int_track_to_binding( binding: unreal.SequencerBindingProxy, property_name: str, property_value: int, ) -> Tuple[unreal.MovieSceneIntegerTrack, unreal.MovieSceneIntegerSection]: # 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.get_channels_by_type(unreal.MovieSceneScriptingIntegerChannel): channel.set_default(property_value) return int_track, int_section def add_property_string_track_to_binding( binding: unreal.SequencerBindingProxy, property_name: str, property_value: Union[str, Dict[int, str]], ) -> Tuple[unreal.MovieSceneStringTrack, unreal.MovieSceneStringSection]: # add string track string_track: unreal.MovieSceneStringTrack = binding.add_track(unreal.MovieSceneStringTrack) string_track.set_property_name_and_path(property_name, property_name) # add int section, and set it to extend the whole sequence string_section = string_track.add_section() string_section.set_start_frame_bounded(0) string_section.set_end_frame_bounded(0) # set key for channel in string_section.get_channels_by_type(unreal.MovieSceneScriptingStringChannel): channel: unreal.MovieSceneScriptingStringChannel if isinstance(property_value, str): channel.set_default(property_value) elif isinstance(property_value, dict): for key_frame, value in property_value.items(): channel.add_key(unreal.FrameNumber(key_frame), value) return string_track, string_section def add_property_float_track_to_binding( binding: unreal.SequencerBindingProxy, property_name: str, property_value: float, ) -> Tuple[unreal.MovieSceneFloatTrack, unreal.MovieSceneFloatSection]: # 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.get_channels_by_type(unreal.MovieSceneScriptingFloatChannel): channel.set_default(property_value) return float_section, float_section def add_or_find_transform_track_to_binding( binding: unreal.SequencerBindingProxy, ) -> Tuple[unreal.MovieScene3DTransformTrack, unreal.MovieScene3DTransformSection]: # find transform track transform_track = binding.find_tracks_by_type(unreal.MovieScene3DTransformTrack) if len(transform_track) > 0: transform_track = transform_track[0] transform_section = transform_track.get_sections()[0] return transform_track, transform_section 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) return transform_track, transform_section def add_or_find_anim_track_to_binding( binding: unreal.SequencerBindingProxy, ) -> Tuple[unreal.MovieSceneSkeletalAnimationTrack, unreal.MovieSceneSkeletalAnimationSection]: animation_track = binding.find_tracks_by_type(unreal.MovieSceneSkeletalAnimationTrack) if len(animation_track) > 0: animation_track = animation_track[0] animation_section = animation_track.get_sections()[0] return animation_track, animation_section animation_track: unreal.MovieSceneSkeletalAnimationTrack = binding.add_track( track_type=unreal.MovieSceneSkeletalAnimationTrack ) animation_section: unreal.MovieSceneSkeletalAnimationSection = animation_track.add_section() # set infinite animation_section.set_start_frame_bounded(0) animation_section.set_end_frame_bounded(0) return animation_track, animation_section def add_transforms_to_binding( binding: unreal.SequencerBindingProxy, actor_trans_keys: Union[SequenceTransformKey, List[SequenceTransformKey]], ): _, transform_section = add_or_find_transform_track_to_binding(binding) # add keys set_transforms_by_section(transform_section, actor_trans_keys) def add_animation_to_binding( binding: unreal.SequencerBindingProxy, animation_asset: unreal.AnimSequence, animation_length: Optional[int] = None, seq_fps: Optional[float] = None, ) -> None: _, animation_section = add_or_find_anim_track_to_binding(binding) set_animation_by_section(animation_section, animation_asset, animation_length, seq_fps) def add_fk_motion_to_binding(binding: unreal.SequencerBindingProxy, motion_data: List[MotionFrame]) -> None: """Add FK motion to the given actor binding. Args: binding (unreal.SequencerBindingProxy): The binding of actor in sequence to add FK motion to. motion_data (List[MotionFrame]): The FK motion data. """ rig_track: unreal.MovieSceneControlRigParameterTrack = ( unreal.ControlRigSequencerLibrary.find_or_create_control_rig_track( world=get_world(), level_sequence=binding.sequence, control_rig_class=unreal.FKControlRig, binding=binding, ) ) rig_section: unreal.MovieSceneControlRigParameterSection = rig_track.get_section_to_key() # Note: assert bone_name is now achieved in function `xf_runner.SequenceUnreal.spawn_actor_with_keys` and `xf_runner.SequenceUnreal.spawn_actor` # param_names = list(rig_section.get_parameter_names()) # for bone_name, bone_data in motion_data[0].items(): # if 'curve' in bone_data.keys(): # bone_name = f'{bone_name}_CURVE_CONTROL' # else: # bone_name = f'{bone_name}_CONTROL' # assert bone_name in param_names, RuntimeError(f'bone name: {bone_name} not in param names: {param_names}') if ENGINE_MAJOR_VERSION == 5 and ENGINE_MINOR_VERSION < 2: msg = 'FKRigExecuteMode is not supported in < UE5.2, may cause unexpected result using FK motion.' unreal.log_warning(msg) else: rig_proxies = unreal.ControlRigSequencerLibrary.get_control_rigs(binding.sequence) for rig_proxy in rig_proxies: # TODO: judge if the track belongs to this actor unreal.ControlRigSequencerLibrary.set_control_rig_apply_mode( rig_proxy.control_rig, unreal.ControlRigFKRigExecuteMode.ADDITIVE ) def get_transform_from_bone_data(bone_data: Dict[str, List[float]]): quat: Tuple[float, float, float, float] = bone_data.get('rotation') location: Tuple[float, float, float] = bone_data.get('location', (0, 0, 0)) # default location is (0, 0, 0) # HACK: convert space location = [location[0] * 100, -location[1] * 100, location[2] * 100] # cm -> m, y -> -y quat = (-quat[1], quat[2], -quat[3], quat[0]) # (w, x, y, z) -> (-x, y, -z, w) transform = unreal.Transform(location=location, rotation=unreal.Quat(*quat).rotator()) return transform for frame, motion_frame in enumerate(motion_data): for bone_name, bone_data in motion_frame.items(): # TODO: set key type to STATIC if 'curve' in bone_data.keys(): rig_section.add_scalar_parameter_key( parameter_name=f'{bone_name}_CURVE_CONTROL', time=get_time(binding.sequence, frame), value=bone_data['curve'], ) else: rig_section.add_transform_parameter_key( parameter_name=f'{bone_name}_CONTROL', time=get_time(binding.sequence, frame), value=get_transform_from_bone_data(bone_data), ) 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(Sequence.START_FRAME) 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(Sequence.START_FRAME) 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.XF_BlueprintFunctionLibrary.set_level(world, levels[0]) save_current_level() def add_camera_to_sequence( sequence: unreal.LevelSequence, camera: unreal.CameraActor, camera_transform_keys: Optional[Union[SequenceTransformKey, List[SequenceTransformKey]]] = None, camera_fov: float = 90.0, camera_aspect_ratio: float = 16.0 / 9.0, seq_length: Optional[int] = None, ) -> unreal.CameraActor: if seq_length is None: seq_length = sequence.get_playback_end() # ------- add camera to seq ------ # camera_binding = sequence.add_possessable(camera) camera_track: unreal.MovieScene3DTransformTrack = camera_binding.add_track(unreal.MovieScene3DTransformTrack) # type: ignore camera_section: unreal.MovieScene3DTransformSection = camera_track.add_section() # type: ignore camera_section.set_start_frame(Sequence.START_FRAME) camera_section.set_end_frame(seq_length) camera_component_binding = sequence.add_possessable(camera.camera_component) camera_component_binding.set_parent(camera_binding) # set the camera FOV fov_track, fov_section = add_property_float_track_to_binding(camera_component_binding, 'FieldOfView', camera_fov) # set the camera aspect ratio aspect_ratio_track, aspect_ratio_section = add_property_float_track_to_binding( camera_component_binding, 'AspectRatio', camera_aspect_ratio ) # ------- add master track ------- # camera_cut_track: unreal.MovieSceneCameraCutTrack = sequence.add_master_track(unreal.MovieSceneCameraCutTrack) # type: ignore # add a camera cut track for this camera # make sure the camera cut is stretched to the Sequence.START_FRAME mark camera_cut_section: unreal.MovieSceneCameraCutSection = camera_cut_track.add_section() # type: ignore camera_cut_section.set_start_frame(Sequence.START_FRAME) camera_cut_section.set_end_frame(seq_length) # set the camera cut to use this camera # camera_cut_section.set_camera_binding_id(camera_binding.get_binding_id()) camera_cut_section.set_camera_binding_id(get_binding_id(camera_binding)) # ------- add transform track ------- # transform_track, transform_section = add_or_find_transform_track_to_binding(camera_binding) if camera_transform_keys: # set the camera location and rotation add_transforms_to_binding(camera_binding, camera_transform_keys) return { 'camera': { 'binding': camera_binding, 'self': camera, }, 'camera_component': { 'binding': camera_component_binding, 'self': camera.camera_component, }, 'fov': {'track': fov_track, 'section': fov_section}, 'aspect_ratio': {'track': aspect_ratio_track, 'section': aspect_ratio_section}, 'transform': {'track': transform_track, 'section': transform_section}, } def add_spawnable_camera_to_sequence( sequence: unreal.LevelSequence, camera_name: str, camera_transform_keys: Optional[Union[SequenceTransformKey, List[SequenceTransformKey]]] = None, camera_class: Type[unreal.CameraActor] = unreal.CameraActor, camera_fov: float = 90.0, camera_aspect_ratio: float = 16.0 / 9.0, seq_length: Optional[int] = None, ) -> unreal.CameraActor: """Add a camera actor to the sequence. Args: sequence (unreal.LevelSequence): a loaded sequence. camera_name (str): name of the camera actor to set. camera_transform_keys (Optional[Union[SequenceTransformKey, List[SequenceTransformKey]]], optional): transform keys of the camera actor. Defaults to None. camera_class (Type[unreal.CameraActor], optional): the camera actor class to spawn. Defaults to unreal.CameraActor. camera_fov (float, optional): Filed of view of the camera. Defaults to 90.0. camera_aspect_ratio (float, optional): Aspect ratio of the camera. Defaults to 16.0 / 9.0. seq_length (Optional[int], optional): Sequence length. Defaults to None. Returns: unreal.CameraActor: _description_ """ # get sequence settings if seq_length is None: seq_length = sequence.get_playback_end() # ---------- add camera ---------- # # create a camera actor & add it to the sequence camera_binding = sequence.add_spawnable_from_class(camera_class) camera_actor: unreal.CameraActor = get_spawnable_actor_from_binding(sequence, camera_binding) camera_binding.set_name(camera_name) camera_actor.set_actor_label(camera_name) camera_component_binding = sequence.add_possessable(camera_actor.camera_component) camera_component_binding.set_parent(camera_binding) # set the camera FOV fov_track, fov_section = add_property_float_track_to_binding(camera_component_binding, 'FieldOfView', camera_fov) # set the camera aspect ratio aspect_ratio_track, aspect_ratio_section = add_property_float_track_to_binding( camera_component_binding, 'AspectRatio', camera_aspect_ratio ) # ------- add master track ------- # # add master track (camera) to sequence # camera_cut_track = sequence.add_track(unreal.MovieSceneCameraCutTrack) camera_cut_track: unreal.MovieSceneCameraCutTrack = sequence.add_master_track(unreal.MovieSceneCameraCutTrack) # add a camera cut track for this camera, make sure the camera cut is stretched to the Sequence.START_FRAME mark camera_cut_section: unreal.MovieSceneCameraCutSection = camera_cut_track.add_section() camera_cut_section.set_start_frame(Sequence.START_FRAME) 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) # camera_cut_section.set_camera_binding_id(camera_binding.get_binding_id()) camera_cut_section.set_camera_binding_id(get_binding_id(camera_binding)) # ------- add transform track ------- # transform_track, transform_section = add_or_find_transform_track_to_binding(camera_binding) if camera_transform_keys: # set the camera location and rotation add_transforms_to_binding(camera_binding, camera_transform_keys) return { 'camera': { 'binding': camera_binding, 'self': camera_actor, }, 'camera_component': { 'binding': camera_component_binding, 'self': camera_actor.camera_component, }, 'fov': {'track': fov_track, 'section': fov_section}, 'aspect_ratio': {'track': aspect_ratio_track, 'section': aspect_ratio_section}, 'transform': {'track': transform_track, 'section': transform_section}, } def add_actor_to_sequence( sequence: unreal.LevelSequence, actor: unreal.Actor, actor_transform_keys: Optional[Union[SequenceTransformKey, List[SequenceTransformKey]]] = None, actor_stencil_value: int = 1, animation_asset: Optional[unreal.AnimSequence] = None, motion_data: Optional[List[MotionFrame]] = None, seq_fps: Optional[float] = None, seq_length: Optional[int] = None, ) -> Dict[str, Any]: # get sequence settings if seq_fps is None: seq_fps = get_sequence_fps(sequence) if seq_length is None: if animation_asset: seq_length = get_animation_length(animation_asset, seq_fps) if motion_data: seq_length = len(motion_data) else: seq_length = sequence.get_playback_end() # ------- add actor to seq ------ # actor_binding = sequence.add_possessable(actor) # mesh_component = actor.skeletal_mesh_component mesh_component = utils_actor.get_actor_mesh_component(actor) mesh_component_binding = sequence.add_possessable(mesh_component) # set stencil value custom_depth_track, custom_depth_section = add_property_bool_track_to_binding( mesh_component_binding, 'bRenderCustomDepth', True ) stencil_value_track, stencil_value_section = add_property_int_track_to_binding( mesh_component_binding, 'CustomDepthStencilValue', actor_stencil_value ) # add animation if animation_asset: add_animation_to_binding(actor_binding, animation_asset, seq_length, seq_fps) # add motion data (FK / ControlRig) if motion_data: add_fk_motion_to_binding(actor_binding, motion_data) # ------- add transform track ------- # transform_track, transform_section = add_or_find_transform_track_to_binding(actor_binding) if actor_transform_keys: add_transforms_to_binding(actor_binding, actor_transform_keys) return { 'actor': {'binding': actor_binding, 'self': actor}, 'transform': {'track': transform_track, 'section': transform_section}, # "animation": {"track": animation_track, "section": animation_section}, 'mesh_component': { 'binding': mesh_component_binding, 'self': mesh_component, 'custom_depth': {'track': custom_depth_track, 'section': custom_depth_section}, 'stencil_value': {'track': stencil_value_track, 'section': stencil_value_section}, }, } def add_spawnable_actor_to_sequence( sequence: unreal.LevelSequence, actor_name: str, actor_asset: Union[unreal.SkeletalMesh, unreal.StaticMesh], animation_asset: Optional[unreal.AnimSequence] = None, motion_data: Optional[List[MotionFrame]] = None, actor_transform_keys: Optional[Union[SequenceTransformKey, List[SequenceTransformKey]]] = None, actor_stencil_value: int = 1, seq_fps: Optional[float] = None, seq_length: Optional[int] = None, ) -> Dict[str, Any]: # get sequence settings if seq_fps is None: seq_fps = get_sequence_fps(sequence) if seq_length is None: if animation_asset: seq_length = get_animation_length(animation_asset, seq_fps) if motion_data: seq_length = len(motion_data) else: seq_length = sequence.get_playback_end() # add actor to sequence actor_binding = sequence.add_spawnable_from_instance(actor_asset) actor: unreal.Actor = get_spawnable_actor_from_binding(sequence, actor_binding) actor_binding.set_name(actor_name) actor.set_actor_label(actor_name) # mesh_component = actor.skeletal_mesh_component mesh_component = utils_actor.get_actor_mesh_component(actor) mesh_component_binding = sequence.add_possessable(mesh_component) # set stencil value custom_depth_track, custom_depth_section = add_property_bool_track_to_binding( mesh_component_binding, 'bRenderCustomDepth', True ) stencil_value_track, stencil_value_section = add_property_int_track_to_binding( mesh_component_binding, 'CustomDepthStencilValue', actor_stencil_value ) # add animation if animation_asset: add_animation_to_binding(actor_binding, animation_asset, seq_length, seq_fps) # add motion data (FK / ControlRig) if motion_data: add_fk_motion_to_binding(actor_binding, motion_data) # ------- add transform track ------- # transform_track, transform_section = add_or_find_transform_track_to_binding(actor_binding) if actor_transform_keys: add_transforms_to_binding(actor_binding, actor_transform_keys) return { 'actor': {'binding': actor_binding, 'self': actor}, 'transform': {'track': transform_track, 'section': transform_section}, # "animation": {"track": animation_track, "section": animation_section}, 'mesh_component': { 'binding': mesh_component_binding, 'self': mesh_component, 'custom_depth': {'track': custom_depth_track, 'section': custom_depth_section}, 'stencil_value': {'track': stencil_value_track, 'section': stencil_value_section}, }, } def add_audio_to_sequence( sequence: unreal.LevelSequence, audio_asset: unreal.SoundWave, start_frame: Optional[int] = None, end_frame: Optional[int] = None, ) -> Dict[str, Any]: fps = get_sequence_fps(sequence) # ------- add audio track ------- # audio_track: unreal.MovieSceneAudioTrack = sequence.add_track(unreal.MovieSceneAudioTrack) audio_section: unreal.MovieSceneAudioSection = audio_track.add_section() audio_track.set_display_name(audio_asset.get_name()) # ------- set start frame ------- # if start_frame is None: start_frame = 0 # ------- set end frame ------- # if end_frame is None: duration = audio_asset.get_editor_property('duration') end_frame = start_frame + int(duration * fps) audio_section.set_end_frame(end_frame=end_frame) audio_section.set_start_frame(start_frame=start_frame) # ------- set audio ------- # audio_section.set_sound(audio_asset) return {'audio_track': {'track': audio_track, 'section': audio_section}} def generate_sequence( sequence_dir: str, sequence_name: str, seq_fps: Optional[float] = None, seq_length: Optional[int] = None, ) -> 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 if seq_fps: new_sequence.set_display_rate(unreal.FrameRate(seq_fps)) if seq_length: new_sequence.set_playback_end(seq_length) return new_sequence def get_camera_param(camera: unreal.CameraActor) -> Dict[str, Any]: """Get camera parameters. Args: camera (unreal.CameraActor): The camera actor. Returns: Dict[str, Any]: A dictionary containing the camera parameters. """ return { 'location': camera.get_actor_location().to_tuple(), 'rotation': camera.get_actor_rotation().to_tuple(), 'fov': camera.camera_component.get_editor_property('FieldOfView'), } def get_actor_param(actor: unreal.Actor) -> Dict[str, Any]: """Get actor parameters. Args: actor (unreal.Actor): The actor. Returns: Dict[str, Any]: A dictionary containing the actor parameters. """ stencil_value = utils_actor.get_actor_mesh_component(actor).get_editor_property('custom_depth_stencil_value') return { 'location': actor.get_actor_location().to_tuple(), 'rotation': actor.get_actor_rotation().to_tuple(), 'scale': actor.get_actor_scale3d().to_tuple(), 'mask_color': utils_actor.get_mask_color(stencil_value=stencil_value), 'stencil_value': stencil_value, } class Sequence: map_path = None sequence_path = None sequence_data_asset: unreal.DataAsset = None # contains sequence_path and map_path sequence: unreal.LevelSequence = None # TODO: make this work # Currently if there's value in bindings and exited accidentally, the value will be kept and cause error bindings: Dict[str, Dict[str, Any]] = {} START_FRAME = -1 def __init__(self) -> NoReturn: raise Exception('Sequence (XRFeitoriaUnreal/Python) should not be instantiated') def __del__(self) -> NoReturn: # TODO: when error was raised from spawn_xxx, the sequence is not closed, which would cause unable to delete the sequence asset del self.map_path del self.sequence_path del self.sequence del self.sequence_data_asset del self.bindings @classmethod def save(cls) -> None: if cls.sequence is not None: unreal.EditorAssetLibrary.save_loaded_asset(cls.sequence, False) @classmethod def close(cls) -> None: if cls.sequence is not None: unreal.LevelSequenceEditorBlueprintLibrary.close_level_sequence() unreal.EditorAssetLibrary.save_asset(cls.sequence_path) # XXX: save the sequence asset del cls.sequence cls.map_path = None cls.sequence_path = None cls.sequence = None cls.bindings = {} @classmethod def open( cls, map_path: str, seq_path: str, ) -> None: assert unreal.EditorAssetLibrary.does_asset_exist(map_path), f'Map `{map_path}` does not exist' assert unreal.EditorAssetLibrary.does_asset_exist( seq_path, ), f'Sequence `{seq_path}` does not exist' unreal.EditorLoadingAndSavingUtils.load_map(map_path) cls.map_path = map_path cls.sequence_path = seq_path cls.sequence: unreal.LevelSequence = unreal.load_asset(cls.sequence_path) @classmethod def new( cls, seq_name: str, map_path: 'Optional[str]' = None, seq_dir: 'Optional[str]' = None, seq_fps: 'Optional[float]' = None, seq_length: 'Optional[int]' = None, replace: bool = False, ) -> str: """Create a new sequence. Args: seq_name (str): name of the sequence. map_path (Optional[str], optional): path of the map asset. Defaults to None. When None, the current map will be used. seq_dir (Optional[str], optional): path of the sequence asset. Defaults to None. seq_fps (Optional[float], optional): FPS of the sequence. Defaults to None. seq_length (Optional[int], optional): length of the sequence. Defaults to None. replace (bool, optional): whether to replace the sequence if it already exists. Defaults to False. Returns: str: path of the data asset of sequence data, containing sequence_path and map_path. """ if map_path is None or map_path == '' or map_path == 'None': map_path = EditorLevelSub.get_current_level().get_path_name().split('.')[0] assert unreal.EditorAssetLibrary.does_asset_exist(map_path), f'Map `{map_path}` does not exist' if seq_dir is None: seq_dir = DEFAULT_SEQUENCE_DIR seq_path = f'{seq_dir}/{seq_name}' data_asset_path = f'{seq_path}{data_asset_suffix}' if unreal.EditorAssetLibrary.does_asset_exist(seq_path) or unreal.EditorAssetLibrary.does_asset_exist( data_asset_path ): if replace: unreal.EditorAssetLibrary.delete_asset(seq_path) unreal.EditorAssetLibrary.delete_asset(data_asset_path) else: raise Exception(f'Sequence `{seq_path}` already exists, use `replace=True` to replace it') unreal.EditorLoadingAndSavingUtils.load_map(map_path) cls.map_path = map_path cls.sequence = generate_sequence( sequence_dir=seq_dir, sequence_name=seq_name, seq_fps=seq_fps, seq_length=seq_length, ) cls.sequence_path = seq_path cls.sequence_data_asset = cls.new_data_asset( asset_path=data_asset_path, map_path=cls.map_path, sequence_path=cls.sequence_path, ) return data_asset_path @classmethod def show(cls) -> None: assert cls.sequence is not None, 'Sequence not initialized' unreal.LevelSequenceEditorBlueprintLibrary.open_level_sequence(cls.sequence) unreal.LevelSequenceEditorBlueprintLibrary.set_current_time(0) @staticmethod def new_data_asset( asset_path: str, sequence_path: str, map_path: str, ) -> unreal.DataAsset: """Create a new data asset of sequence data. Args: asset_path (str): path of the data asset. sequence_path (str): path of the sequence asset. map_path (str): path of the map asset. Returns: unreal.DataAsset: the created data asset. Notes: SequenceData Properties: - "SequencePath": str - "MapPath": str """ # maybe `unreal.EditorAssetLibrary.load_blueprint_class` unreal.EditorAssetLibrary.duplicate_asset( source_asset_path=DEFAULT_SEQUENCE_DATA_ASSET, destination_asset_path=asset_path, ) if not unreal.EditorAssetLibrary.does_asset_exist(asset_path): raise RuntimeError(f'Failed to create data asset: {asset_path}') asset = unreal.load_asset(asset_path) assert asset is not None, f'Failed to create data asset: {asset_path}' asset.set_editor_property('SequencePath', get_soft_object_path(sequence_path)) asset.set_editor_property('MapPath', get_soft_object_path(map_path)) unreal.EditorAssetLibrary.save_asset(asset_path) return asset @staticmethod def get_data_asset_info(data_asset_path: str) -> Tuple[str, str]: """Get sequence path and map path from data asset. Args: data_asset_path (str): path of the data asset. """ seq_data_asset = unreal.load_asset(data_asset_path) assert seq_data_asset is not None, f'Failed to load data asset: {data_asset_path}' seq_path = seq_data_asset.get_editor_property('SequencePath').export_text() map_path = seq_data_asset.get_editor_property('MapPath').export_text() return seq_path.split('.')[0], map_path.split('.')[0] @classmethod def set_camera_cut_playback(cls, start_frame: Optional[int] = None, end_frame: Optional[int] = None) -> None: """Set the camera cut playback. Args: start_frame (Optional[int], optional): start frame of the camera cut playback. Defaults to None. end_frame (Optional[int], optional): end frame of the camera cut playback. Defaults to None. Raises: AssertionError: If the sequence is not initialized. """ assert cls.sequence is not None, 'Sequence not initialized' camera_tracks = cls.sequence.find_master_tracks_by_type(unreal.MovieSceneCameraCutTrack) for camera_track in camera_tracks: for section in camera_track.get_sections(): if start_frame: section.set_start_frame(start_frame) if end_frame: section.set_end_frame(end_frame) @classmethod def set_playback(cls, start_frame: Optional[int] = None, end_frame: Optional[int] = None) -> None: """Set the playback range for the sequence. Args: start_frame (Optional[int]): The start frame of the playback range. Defaults to None. end_frame (Optional[int]): The end frame of the playback range. Defaults to None. Raises: AssertionError: If the sequence is not initialized. """ assert cls.sequence is not None, 'Sequence not initialized' master_tracks = cls.sequence.get_tracks() if start_frame: cls.START_FRAME = start_frame cls.sequence.set_playback_start(start_frame=start_frame) for master_track in master_tracks: for section in master_track.get_sections(): section.set_start_frame(start_frame) if end_frame: cls.sequence.set_playback_end(end_frame=end_frame) for master_track in master_tracks: for section in master_track.get_sections(): section.set_end_frame(end_frame) @classmethod def get_playback(cls) -> Tuple[int, int]: """Get the playback range of the sequence. Returns: Tuple[int, int]: The start frame and end frame of the playback range. """ assert cls.sequence is not None, 'Sequence not initialized' return cls.sequence.get_playback_start(), cls.sequence.get_playback_end() # ------ add actor and camera -------- # @classmethod def add_camera( cls, camera_name: str, transform_keys: 'Optional[TransformKeys]' = None, fov: float = 90.0, aspect_ratio: float = 16.0 / 9.0, spawnable: bool = False, ): """Spawn a camera in sequence. Args: transform_keys (Optional[TransformKeys], optional): List of transform keys. Defaults to None. fov (float, optional): Field of view of camera. Defaults to 90.0. camera_name (str, optional): Name of camera to set in sequence. Defaults to "Camera". """ assert cls.sequence is not None, 'Sequence not initialized' if spawnable: bindings = add_spawnable_camera_to_sequence( sequence=cls.sequence, camera_name=camera_name, camera_transform_keys=transform_keys, camera_fov=fov, camera_aspect_ratio=aspect_ratio, ) cls.bindings[camera_name] = bindings else: camera = utils_actor.get_actor_by_name(camera_name) bindings = add_camera_to_sequence( sequence=cls.sequence, camera=camera, camera_transform_keys=transform_keys, camera_fov=fov, camera_aspect_ratio=aspect_ratio, ) cls.bindings[camera_name] = bindings @classmethod def add_actor( cls, actor_name: str, actor: 'Optional[Union[str, unreal.Actor]]' = None, transform_keys: 'Optional[TransformKeys]' = None, stencil_value: int = 1, animation_asset: 'Optional[Union[str, unreal.AnimSequence]]' = None, motion_data: 'Optional[List[MotionFrame]]' = None, ) -> None: """Spawn an actor in sequence. Args: actor_name (str): The name of the actor. actor (Optional[Union[str, unreal.Actor]]): actor path (e.g. '/project/') / loaded asset (via `unreal.load_asset('/project/')`) transform_keys (Optional[TransformKeys]): List of transform keys. Defaults to None. stencil_value (int): Stencil value of actor, used for specifying the mask color for this actor (mask id). Defaults to 1. animation_asset (Optional[Union[str, unreal.AnimSequence]]): animation path (e.g. '/project/') / loaded asset (via `unreal.load_asset('/project/')`). Can be None which means no animation. motion_data (Optional[List[MotionFrame]]): The motion data used for FK animation. Raises: AssertionError: If `cls.sequence` is not initialized. AssertionError: If `animation_asset` and `motion_data` are both provided. Only one can be provided. """ assert cls.sequence is not None, 'Sequence not initialized' if animation_asset and isinstance(animation_asset, str): animation_asset = unreal.load_asset(animation_asset) if isinstance(actor, str): actor = unreal.load_asset(actor) if actor: bindings = add_spawnable_actor_to_sequence( sequence=cls.sequence, actor_name=actor_name, actor_asset=actor, animation_asset=animation_asset, motion_data=motion_data, actor_transform_keys=transform_keys, actor_stencil_value=stencil_value, ) cls.bindings[actor_name] = bindings else: actor = utils_actor.get_actor_by_name(actor_name) bindings = add_actor_to_sequence( sequence=cls.sequence, actor=actor, actor_transform_keys=transform_keys, actor_stencil_value=stencil_value, animation_asset=animation_asset, motion_data=motion_data, ) cls.bindings[actor_name] = bindings @classmethod def add_audio( cls, audio_asset: Union[str, unreal.SoundWave], start_frame: Optional[int] = None, end_frame: Optional[int] = None, ): """Spawn an audio in sequence. Args: audio_asset (Union[str, unreal.SoundWave]): audio path (e.g. '/project/') / loaded asset (via `unreal.load_asset('/project/')`) start_frame (Optional[int], optional): start frame of the audio. Defaults to None. end_frame (Optional[int], optional): end frame of the audio. Defaults to None. Raises: AssertionError: If `cls.sequence` is not initialized. """ assert cls.sequence is not None, 'Sequence not initialized' if isinstance(audio_asset, str): audio_asset = unreal.load_asset(audio_asset) bindings = add_audio_to_sequence( sequence=cls.sequence, audio_asset=audio_asset, start_frame=start_frame, end_frame=end_frame ) cls.bindings[audio_asset.get_name()] = bindings @classmethod def add_annotator( cls, save_dir: str, resolution: Tuple[int, int], export_vertices: bool, export_skeleton: bool, ): actor_binding = find_binding_by_class(cls.sequence, unreal.Annotator) if actor_binding is not None: actor_binding.remove() actor_binding = cls.sequence.add_spawnable_from_class(unreal.Annotator) add_property_bool_track_to_binding( binding=actor_binding, property_name='bSaveVerticesPosition', property_value=export_vertices ) add_property_bool_track_to_binding( binding=actor_binding, property_name='bSaveSkeletonPosition', property_value=export_skeleton ) add_property_string_track_to_binding( binding=actor_binding, property_name='DirectorySequence', property_value=save_dir ) add_property_int_track_to_binding(binding=actor_binding, property_name='Width', property_value=resolution[0]) add_property_int_track_to_binding(binding=actor_binding, property_name='Height', property_value=resolution[1]) def test(): Sequence.open('/project/', '/project/') Sequence.save_camera_params(save_dir='E:/tmp') if __name__ == '__main__': Sequence.open('/project/', '/project/') Sequence.new('/project/', 'test1') Sequence.spawn_camera(transform_keys=SequenceTransformKey(frame=0, location=(0, 0, 0), rotation=(0, 0, 0))) Sequence.spawn_actor( '/project/', transform_keys=SequenceTransformKey(frame=0, location=(0, 0, 0), rotation=(0, 0, 0)), ) Sequence.open('/project/', '/project/') Sequence.new('/project/', 'test1') Sequence.spawn_camera(transform_keys=SequenceTransformKey(frame=0, location=(0, 0, 0), rotation=(0, 0, 0))) Sequence.spawn_actor( '/project/', transform_keys=SequenceTransformKey(frame=0, location=(0, 0, 0), rotation=(0, 0, 0)), )
# -*- coding: utf-8 -*- import ast import collections from abc import ABC import unreal import ayon_api from .pipeline import ( create_publish_instance, imprint, ls_inst, UNREAL_VERSION ) from .lib import remove_loaded_asset from ayon_core.lib import ( BoolDef, UILabelDef, ) from ayon_core.pipeline import ( AutoCreator, Creator, LoaderPlugin, CreatorError, CreatedInstance, discover_loader_plugins, loaders_from_representation, load_container, AYON_CONTAINER_ID ) class UnrealCreateLogic(): """Universal class for logic that Unreal creators could inherit from.""" root = "/project/" suffix = "_INS" @staticmethod def get_cached_instances(shared_data): """Cache instances for Creators to shared data. Create `unreal_cached_subsets` key when needed in shared data and fill it with all collected instances from the scene under its respective creator identifiers. If legacy instances are detected in the scene, create `unreal_cached_legacy_subsets` there and fill it with all legacy subsets under product_type as a key. Args: Dict[str, Any]: Shared data. Return: Dict[str, Any]: Shared data dictionary. """ if shared_data.get("unreal_cached_subsets") is None: unreal_cached_subsets = collections.defaultdict(list) unreal_cached_legacy_subsets = collections.defaultdict(list) for instance in ls_inst(): creator_id = instance.get("creator_identifier") if creator_id: unreal_cached_subsets[creator_id].append(instance) else: product_type = instance.get("product_type") unreal_cached_legacy_subsets[product_type].append(instance) shared_data["unreal_cached_subsets"] = unreal_cached_subsets shared_data["unreal_cached_legacy_subsets"] = ( unreal_cached_legacy_subsets ) return shared_data def _default_collect_instances(self): # cache instances if missing self.get_cached_instances(self.collection_shared_data) for instance in self.collection_shared_data[ "unreal_cached_subsets"].get(self.identifier, []): # Unreal saves metadata as string, so we need to convert it back instance['creator_attributes'] = ast.literal_eval( instance.get('creator_attributes', '{}')) instance['publish_attributes'] = ast.literal_eval( instance.get('publish_attributes', '{}')) instance['members'] = ast.literal_eval( instance.get('members', '[]')) instance['families'] = ast.literal_eval( instance.get('families', '[]')) instance['active'] = ast.literal_eval( instance.get('active', '')) created_instance = CreatedInstance.from_existing(instance, self) self._add_instance_to_context(created_instance) def _default_update_instances(self, update_list): for created_inst, changes in update_list: instance_node = created_inst.get("instance_path", "") if not instance_node: unreal.log_warning( f"Instance node not found for {created_inst}") continue new_values = { key: changes[key].new_value for key in changes.changed_keys } imprint( instance_node, new_values ) def _default_remove_instances(self, instances): for instance in instances: instance_node = instance.data.get("instance_path", "") if instance_node: unreal.EditorAssetLibrary.delete_asset(instance_node) self._remove_instance_from_context(instance) def create_unreal(self, product_name, instance_data, pre_create_data): try: instance_name = f"{product_name}{self.suffix}" pub_instance = create_publish_instance(instance_name, self.root) instance_data["product_name"] = product_name instance_data["instance_path"] = f"{self.root}/{instance_name}" instance = CreatedInstance( self.product_type, product_name, instance_data, self) self._add_instance_to_context(instance) pub_instance.set_editor_property('add_external_assets', True) assets = pub_instance.get_editor_property('asset_data_external') ar = unreal.AssetRegistryHelpers.get_asset_registry() for member in pre_create_data.get("members", []): obj = ar.get_asset_by_object_path(member).get_asset() assets.add(obj) imprint(f"{self.root}/{instance_name}", instance.data_to_store()) return instance except Exception as exc: raise CreatorError(f"Creator error: {exc}") from exc class UnrealBaseAutoCreator(AutoCreator, UnrealCreateLogic): """Base class for Unreal auto creator plugins.""" settings_category = "unreal" def collect_instances(self): return self._default_collect_instances() def update_instances(self, update_list): return self._default_update_instances(update_list) def remove_instances(self, instances): return self._default_remove_instances(instances) class UnrealBaseCreator(UnrealCreateLogic, Creator): """Base class for Unreal creator plugins.""" settings_category = "unreal" def create(self, subset_name, instance_data, pre_create_data): self.create_unreal(subset_name, instance_data, pre_create_data) def collect_instances(self): return self._default_collect_instances() def update_instances(self, update_list): return self._default_update_instances(update_list) def remove_instances(self, instances): return self._default_remove_instances(instances) class UnrealAssetCreator(UnrealBaseCreator): """Base class for Unreal creator plugins based on assets.""" def create(self, product_name, instance_data, pre_create_data): """Create instance of the asset. Args: product_name (str): Name of the product. instance_data (dict): Data for the instance. pre_create_data (dict): Data for the instance. Returns: CreatedInstance: Created instance. """ try: # Check if instance data has members, filled by the plugin. # If not, use selection. if not pre_create_data.get("members"): pre_create_data["members"] = [] if pre_create_data.get("use_selection"): utilib = unreal.EditorUtilityLibrary sel_objects = utilib.get_selected_assets() pre_create_data["members"] = [ a.get_path_name() for a in sel_objects] super(UnrealAssetCreator, self).create( product_name, instance_data, pre_create_data) except Exception as exc: raise CreatorError(f"Creator error: {exc}") from exc def get_pre_create_attr_defs(self): return [ BoolDef("use_selection", label="Use selection", default=True) ] class UnrealActorCreator(UnrealBaseCreator): """Base class for Unreal creator plugins based on actors.""" def create(self, product_name, instance_data, pre_create_data): """Create instance of the asset. Args: product_name (str): Name of the product. instance_data (dict): Data for the instance. pre_create_data (dict): Data for the instance. Returns: CreatedInstance: Created instance. """ try: if UNREAL_VERSION.major == 5: world = unreal.UnrealEditorSubsystem().get_editor_world() else: world = unreal.EditorLevelLibrary.get_editor_world() # Check if the level is saved if world.get_path_name().startswith("/Temp/"): raise CreatorError( "Level must be saved before creating instances.") # Check if instance data has members, filled by the plugin. # If not, use selection. if not instance_data.get("members"): actor_subsystem = unreal.EditorActorSubsystem() sel_actors = actor_subsystem.get_selected_level_actors() selection = [a.get_path_name() for a in sel_actors] instance_data["members"] = selection instance_data["level"] = world.get_path_name() super(UnrealActorCreator, self).create( product_name, instance_data, pre_create_data) except Exception as exc: raise CreatorError(f"Creator error: {exc}") from exc def get_pre_create_attr_defs(self): return [ UILabelDef("Select actors to create instance from them."), ] class Loader(LoaderPlugin, ABC): """This serves as skeleton for future Ayon specific functionality""" pass class LayoutLoader(Loader): """Load Layout from a JSON file""" product_types = {"layout"} representations = {"json"} label = "Load Layout" icon = "code-fork" color = "orange" loaded_layout_dir = "{folder[path]}/{product[name]}" loaded_layout_name = "{folder[name]}_{product[name]}_{version[version]}" remove_loaded_assets = False @staticmethod def _get_fbx_loader(loaders, family): name = "" if family in ['rig', 'skeletalMesh']: name = "SkeletalMeshFBXLoader" elif family in ['model', 'staticMesh']: name = "StaticMeshFBXLoader" elif family == 'camera': name = "CameraLoader" if name == "": return None for loader in loaders: if loader.__name__ == name: return loader return None @staticmethod def _get_abc_loader(loaders, family): name = "" if family in ['rig', 'skeletalMesh']: name = "SkeletalMeshAlembicLoader" elif family in ['model', 'staticMesh']: name = "StaticMeshAlembicLoader" elif family in ["animation"]: name = "AnimationAlembicLoader" if name == "": return None for loader in loaders: if loader.__name__ == name: return loader return None def _transform_from_basis(self, transform, basis, unreal_import=False): """Transform a transform from a basis to a new basis.""" # Get the basis matrix basis_matrix = unreal.Matrix( basis[0], basis[1], basis[2], basis[3] ) transform_matrix = unreal.Matrix( transform[0], transform[1], transform[2], transform[3] ) new_transform = None if unreal_import: new_transform = transform_matrix * basis_matrix else: new_transform = ( basis_matrix.get_inverse() * transform_matrix * basis_matrix) return new_transform.transform() def _get_repre_entities_by_version_id(self, project_name, data, repre_extension, force_loaded=False): version_ids = { element.get("version") for element in data if element.get("representation") } version_ids.discard(None) output = collections.defaultdict(list) if not version_ids: return output # Extract extensions from data with backward compatibility for "ma" extensions = { element.get("extension", "ma") for element in data if element.get("representation") } # Update extensions based on the force_loaded flag updated_extensions = set() for ext in extensions: if not force_loaded or repre_extension == "json": if ext == "ma": updated_extensions.update({"fbx", "abc"}) else: updated_extensions.add(ext) else: updated_extensions.update({repre_extension}) repre_entities = ayon_api.get_representations( project_name, representation_names=updated_extensions, version_ids=version_ids, fields={"id", "versionId", "name"} ) for repre_entity in repre_entities: version_id = repre_entity["versionId"] output[version_id].append(repre_entity) return output def imprint( self, context, folder_path, folder_name, loaded_assets, asset_dir, asset_name, container_name, project_name, hierarchy_dir=None ): data = { "schema": "ayon:container-2.0", "id": AYON_CONTAINER_ID, "asset": folder_name, "folder_path": folder_path, "namespace": asset_dir, "container_name": container_name, "asset_name": asset_name, "loader": str(self.__class__.__name__), "representation": context["representation"]["id"], "parent": context["representation"]["versionId"], "family": context["product"]["productType"], "loaded_assets": loaded_assets, "project_name": project_name } if hierarchy_dir is not None: data["master_directory"] = hierarchy_dir imprint( "{}/{}".format(asset_dir, container_name), data) def _load_assets(self, instance_name, repre_id, product_type, repr_format): all_loaders = discover_loader_plugins() loaders = loaders_from_representation( all_loaders, repre_id) loader = None if repr_format == 'fbx': loader = self._get_fbx_loader(loaders, product_type) elif repr_format == 'abc': loader = self._get_abc_loader(loaders, product_type) if not loader: if repr_format == "ma": msg = ( f"No valid {product_type} loader found for {repre_id} ({repr_format}), " f"consider using {product_type} loader (fbx/abc) instead." ) self.log.warning(msg) else: self.log.error( f"No valid loader found for {repre_id} " f"({repr_format}) " f"{product_type}") return import_options = { "layout": True } assets = load_container( loader, repre_id, namespace=instance_name, options=import_options ) return assets def _remove_Loaded_asset(self, container): """ Delete the layout. First, check if the assets loaded with the layout are used by other layouts. If not, delete the assets. """ if self.remove_loaded_assets: remove_asset_confirmation_dialog = unreal.EditorDialog.show_message( "The removal of the loaded assets", "The layout will be removed. Do you want to delete all associated assets as well?", unreal.AppMsgType.YES_NO) if (remove_asset_confirmation_dialog == unreal.AppReturnType.YES): remove_loaded_asset(container)
# coding: utf-8 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) humanoidBoneList = [ "hips", "leftUpperLeg", "rightUpperLeg", "leftLowerLeg", "rightLowerLeg", "leftFoot", "rightFoot", "spine", "chest", "upperChest", "neck", "head", "leftShoulder", "rightShoulder", "leftUpperArm", "rightUpperArm", "leftLowerArm", "rightLowerArm", "leftHand", "rightHand", "leftToes", "rightToes", "leftEye", "rightEye", "jaw", "leftThumbProximal", "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", ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() ###### 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 print(unreal.SystemLibrary.get_engine_version()) if (unreal.SystemLibrary.get_engine_version()[0] == '5'): c = rig.get_controller()#rig.controller else: c = rig.controller g = c.get_graph() n = g.get_nodes() print(n) #c.add_branch_node() #c.add_array_pin() a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() # print(a) # 配列ノード追加 collectionItem_forControl:unreal.RigVMStructNode = None collectionItem_forBone:unreal.RigVMStructNode = None for node in n: if (node.get_node_title() == 'Items' or node.get_node_title() == 'Collection from 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=Bone' in pin.get_default_value(): collectionItem_forBone= node if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = node #nn = unreal.EditorFilterLibrary.by_class(n,unreal.RigUnit_CollectionItems.static_class()) ## 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 # 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()) # bone array if (collectionItem_forBone == None): collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) ## h_mod rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] print(items_forControl) print(items_forBone) humanoidBoneTable = {"dummy" : "dummy"} humanoidBoneTable.clear() for h in meta.humanoid_bone_table: bone_h = "{}".format(h).lower() bone_m = "{}".format(meta.humanoid_bone_table[h]).lower() try: i = list(humanoidBoneTable.values()).index(bone_m) except: i = -1 if (bone_h!="" and bone_m!="" and i==-1): humanoidBoneTable[bone_h] = bone_m for bone_h in humanoidBoneList: bone_m = humanoidBoneTable.get(bone_h, None) if bone_m == None: continue #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): if (True): tmp = '(Type=Bone,Name=' #tmp += "{}".format(bone_m).lower() tmp += bone_m tmp += ')' c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) #print(bone_m) tmp = '(Type=Control,Name=' #tmp += "{}".format(bone_h).lower() + '_c' tmp += bone_h + '_c' tmp += ')' #print(c) c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) #print(bone_h) #for e in h_mod.get_elements(): # 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) # print(e.name) # if (e.type == unreal.RigElementType.BONE): # tmp = '(Type=Bone,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) # print(e.name) #print(i.get_all_pins_recursively()) #ii:unreal.RigUnit_CollectionItems = n[1] #pp = ii.get_editor_property('Items') #print(pp) #print(collectionItem.get_all_pins_recursively()[0]) #i.get_editor_property("Items") #c.add_array_pin("Execute") # arrayを伸ばす #i.get_all_pins_recursively()[0].get_pin_path() #c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)') #rig = rigs[10]
import unreal selected_assets = unreal.EditorUtilityLibrary.get_selected_assets() for asset in selected_assets: data=asset.get_editor_property('asset_import_data').extract_filenames() print(data)
# -*- 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))
import unreal texture_tga = r"/project/-12-20_09-57-53.png" sound_wav = r"/project/.mp3" # sound_wav = "" def importMyAssets(): texture_task = buildImportTask(texture_tga,'/project/') # sound_task = buildImportTask(sound_wav,'/project/') executeImportTasks([texture_task]) def buildImportTask(filename,destionation_path): task = unreal.AssetImportTask() task.set_editor_property('automated',True) task.set_editor_property('destination_name','') task.set_editor_property('destination_path',destionation_path) task.set_editor_property('filename',filename) task.set_editor_property('replace_existing',True) task.set_editor_property('save',True) task.set_editor_property('test',True) return task` def executeImportTasks(tasks): print "tasks",tasks tool = unreal.AssetToolsHelpers.get_asset_tools() tool.import_asset_tasks(tasks) # for task in tasks: # for path in task.get_editor_property('imported_object_paths'): # print 'Imported: %s' % path # import AssetFunctions # reload(AssetFunctions) # AssetFunctions.importMyAssets() ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_post_init', '_wrapper_meta_data', 'automated', 'cast', 'destination_name', 'destination_path', 'factory', 'filename', 'get_class', 'get_default_object', 'get_editor_property', 'get_fname', 'get_full_name', 'get_name', 'get_outer', 'get_outermost', 'get_path_name', 'get_typed_outer', 'get_world', 'imported_object_paths', 'modify', 'options', 'rename', 'replace_existing', 'result', 'save', 'set_editor_property', 'static_class']
import unreal import pyblish.api class CollectInstanceMembers(pyblish.api.InstancePlugin): """ Collect members of instance. This collector will collect the assets for the families that support to have them included as External Data, and will add them to the instance as members. """ order = pyblish.api.CollectorOrder + 0.1 hosts = ["unreal"] families = ["camera", "staticMesh", "uasset"] label = "Collect Instance Members" def process(self, instance): """Collect members of instance.""" self.log.info("Collecting instance members") ar = unreal.AssetRegistryHelpers.get_asset_registry() inst_path = instance.data.get('instance_path') inst_name = inst_path.split('/')[-1] pub_instance = ar.get_asset_by_object_path( f"{inst_path}.{inst_name}").get_asset() if not pub_instance: self.log.error(f"{inst_path}.{inst_name}") raise RuntimeError(f"Instance {instance} not found.") if not pub_instance.get_editor_property("add_external_assets"): # No external assets in the instance return assets = pub_instance.get_editor_property('asset_data_external') members = [asset.get_path_name() for asset in assets] self.log.debug(f"Members: {members}") instance.data["members"] = members
# coding: utf-8 from asyncio.windows_events import NULL from platform import java_ver 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() def checkAndSwapPinBoneToContorl(pin): subpins = pin.get_sub_pins() #print(subpins) if (len(subpins) != 2): return; typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') #if (typePin==None or namePin==None): if (typePin==None): return; #if (typePin.get_default_value() == '' or namePin.get_default_value() == ''): if (typePin.get_default_value() == ''): return; if (typePin.get_default_value() != 'Bone'): return; print(typePin.get_default_value() + ' : ' + namePin.get_default_value()) r_con.set_pin_default_value(typePin.get_pin_path(), 'Control', True, False) print('swap end') #end check pin bonePin = None controlPin = None 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) ## for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): if (pin.get_array_size() > 40): # long bone list typePin = pin.get_sub_pins()[0].find_sub_pin('Type') if (typePin != None): if (typePin.get_default_value() == 'Bone'): bonePin = pin continue if (typePin.get_default_value() == 'Control'): if ('Name="pelvis"' in r_con.get_pin_default_value(n.find_pin('Items').get_pin_path())): controlPin = pin continue for item in pin.get_sub_pins(): checkAndSwapPinBoneToContorl(item) else: checkAndSwapPinBoneToContorl(pin) for e in hierarchy.get_controls(): tmp = "{}".format(e.name) if (tmp.endswith('_ctrl') == False): continue if (tmp.startswith('thumb_0') or tmp.startswith('index_0') or tmp.startswith('middle_0') or tmp.startswith('ring_0') or tmp.startswith('pinky_0')): print('') else: continue c = hierarchy.find_control(e) print(e.name) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) #ttt = unreal.RigComputedTransform(transform=[[0.0, 0.0, 2.0], [90.0, 0.0, 0.0], [0.03, 0.03, 0.25]]) ttt = unreal.Transform(location=[0.0, 0.0, 2.0], rotation=[0.0, 0.0, 90.0], scale=[0.03, 0.03, 0.25]) hierarchy.set_control_shape_transform(e, ttt, True) ''' shape = c.get_editor_property('shape') init = shape.get_editor_property('initial') #init = shape.get_editor_property('current') local = init.get_editor_property('local') local = ttt init.set_editor_property('local', local) gl = init.get_editor_property('global_') gl = ttt init.set_editor_property('global_', gl) shape.set_editor_property('initial', init) shape.set_editor_property('current', init) c.set_editor_property('shape', shape) ''' ### swapBoneTable = [ ["Root",""], ["Pelvis","hips"], ["spine_01","spine"], ["spine_02","chest"], ["spine_03","upperChest"], ["clavicle_l","leftShoulder"], ["UpperArm_L","leftUpperArm"], ["lowerarm_l","leftLowerArm"], ["Hand_L","leftHand"], ["index_01_l","leftIndexProximal"], ["index_02_l","leftIndexIntermediate"], ["index_03_l","leftIndexDistal"], ["middle_01_l","leftMiddleProximal"], ["middle_02_l","leftMiddleIntermediate"], ["middle_03_l","leftMiddleDistal"], ["pinky_01_l","leftLittleProximal"], ["pinky_02_l","leftLittleIntermediate"], ["pinky_03_l","leftLittleDistal"], ["ring_01_l","leftRingProximal"], ["ring_02_l","leftRingIntermediate"], ["ring_03_l","leftRingDistal"], ["thumb_01_l","leftThumbProximal"], ["thumb_02_l","leftThumbIntermediate"], ["thumb_03_l","leftThumbDistal"], ["lowerarm_twist_01_l",""], ["upperarm_twist_01_l",""], ["clavicle_r","rightShoulder"], ["UpperArm_R","rightUpperArm"], ["lowerarm_r","rightLowerArm"], ["Hand_R","rightHand"], ["index_01_r","rightIndexProximal"], ["index_02_r","rightIndexIntermediate"], ["index_03_r","rightIndexDistal"], ["middle_01_r","rightMiddleProximal"], ["middle_02_r","rightMiddleIntermediate"], ["middle_03_r","rightMiddleDistal"], ["pinky_01_r","rightLittleProximal"], ["pinky_02_r","rightLittleIntermediate"], ["pinky_03_r","rightLittleDistal"], ["ring_01_r","rightRingProximal"], ["ring_02_r","rightRingIntermediate"], ["ring_03_r","rightRingDistal"], ["thumb_01_r","rightThumbProximal"], ["thumb_02_r","rightThumbIntermediate"], ["thumb_03_r","rightThumbDistal"], ["lowerarm_twist_01_r",""], ["upperarm_twist_01_r",""], ["neck_01","neck"], ["head","head"], ["Thigh_L","leftUpperLeg"], ["calf_l","leftLowerLeg"], ["calf_twist_01_l",""], ["Foot_L","leftFoot"], ["ball_l","leftToes"], ["thigh_twist_01_l",""], ["Thigh_R","rightUpperLeg"], ["calf_r","rightLowerLeg"], ["calf_twist_01_r",""], ["Foot_R","rightFoot"], ["ball_r","rightToes"], ["thigh_twist_01_r",""], ["index_metacarpal_l",""], ["index_metacarpal_r",""], ["middle_metacarpal_l",""], ["middle_metacarpal_r",""], ["ring_metacarpal_l",""], ["ring_metacarpal_r",""], ["pinky_metacarpal_l",""], ["pinky_metacarpal_r",""], #custom ["eye_l", "leftEye"], ["eye_r", "rightEye"], ] 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 ] for i in range(len(humanoidBoneList)): humanoidBoneList[i] = humanoidBoneList[i].lower() for i in range(len(swapBoneTable)): swapBoneTable[i][0] = swapBoneTable[i][0].lower() swapBoneTable[i][1] = swapBoneTable[i][1].lower() ### 全ての骨 modelBoneElementList = [] modelBoneNameList = [] for e in hierarchy.get_bones(): if (e.type == unreal.RigElementType.BONE): modelBoneElementList.append(e) modelBoneNameList.append("{}".format(e.name)) ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); if (args.meta): for aa in a: print(aa.get_editor_property("package_name")) print(aa.get_editor_property("asset_name")) if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.meta): v:unreal.VrmMetaObject = aa vv = aa.get_asset() break if (vv == None): for aa in a: if ((unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("package_name"))+"."+unreal.StringLibrary.conv_name_to_string(aa.get_editor_property("asset_name"))) == unreal.StringLibrary.conv_name_to_string(args.meta)): #if (aa.get_editor_property("object_path") == args.vrm): v:unreal.VrmAssetListObject = aa vv = v.get_asset().vrm_meta_object break meta = vv # Backwards Bone Names allBackwardsNode = [] def r_nodes(node): b = False try: allBackwardsNode.index(node) except: b = True if (b == True): allBackwardsNode.append(node) linknode = node.get_linked_source_nodes() for n in linknode: r_nodes(n) linknode = node.get_linked_target_nodes() for n in linknode: r_nodes(n) for n in node: if (n.get_node_title() == 'Backwards Solve'): r_nodes(n) print(len(allBackwardsNode)) print(len(node)) def boneOverride(pin): subpins = pin.get_sub_pins() if (len(subpins) != 2): return typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None): return if (namePin==None): return controlName = namePin.get_default_value() if (controlName==''): return if (controlName.endswith('_ctrl')): return if (controlName.endswith('_space')): return r_con.set_pin_default_value(typePin.get_pin_path(), 'Bone', True, False) table = [i for i in swapBoneTable if i[0]==controlName] if (len(table) == 0): # use node or no control return if (table[0][0] == 'root'): metaTable = "{}".format(hierarchy.get_bones()[0].name) else: metaTable = meta.humanoid_bone_table.get(table[0][1]) if (metaTable == None): metaTable = 'None' #print(table[0][1]) #print('<<') #print(controlName) #print('<<<') #print(metaTable) r_con.set_pin_default_value(namePin.get_pin_path(), metaTable, True, False) #for e in meta.humanoid_bone_table: for n in allBackwardsNode: pins = n.get_pins() for pin in pins: if (pin.is_array()): # finger 無変換チェック linknode = n.get_linked_target_nodes() if (len(linknode) == 1): if (linknode[0].get_node_title()=='At'): continue for p in pin.get_sub_pins(): boneOverride(p) else: boneOverride(pin) #sfsdjfkasjk ### 骨名対応表。Humanoid名 -> Model名 humanoidBoneToModel = {"" : ""} humanoidBoneToModel.clear() humanoidBoneToMannequin = {"" : ""} humanoidBoneToMannequin.clear() # humanoidBone -> modelBone のテーブル作る for searchHumanoidBone in humanoidBoneList: bone_h = None for e in meta.humanoid_bone_table: if ("{}".format(e).lower() == searchHumanoidBone): bone_h = e; break; if (bone_h==None): # not found continue bone_m = meta.humanoid_bone_table[bone_h] try: i = modelBoneNameList.index(bone_m) except: i = -1 if (i < 0): # no bone continue humanoidBoneToModel["{}".format(bone_h).lower()] = "{}".format(bone_m) #humanoidBoneToMannequin["{}".format(bone_h).lower()] = "{}".format(bone_m).lower(bone_h) #print(humanoidBoneToModel) #print(bonePin) #print(controlPin) if (bonePin != None and controlPin !=None): r_con.clear_array_pin(bonePin.get_pin_path()) r_con.clear_array_pin(controlPin.get_pin_path()) #c.clear_array_pin(v.get_pin_path()) #tmp = '(Type=Control,Name=' #tmp += "{}".format('aaaaa') #tmp += ')' #r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp) for e in swapBoneTable: try: i = 0 humanoidBoneToModel[e[1]] except: i = -1 if (i < 0): # no bone continue #e[0] -> grayman #e[1] -> humanoid #humanoidBoneToModel[e[1]] -> modelBone bone = unreal.RigElementKey(unreal.RigElementType.BONE, humanoidBoneToModel[e[1]]) space = unreal.RigElementKey(unreal.RigElementType.NULL, "{}_s".format(e[0])) #print('aaa') #print(bone) #print(space) #p = hierarchy.get_first_parent(humanoidBoneToModel[result[0][1]]) t = hierarchy.get_global_transform(bone) #print(t) hierarchy.set_global_transform(space, t, True) if (bonePin != None and controlPin !=None): tmp = '(Type=Control,Name=' tmp += "{}".format(e[0]) tmp += ')' r_con.add_array_pin(controlPin.get_pin_path(), default_value=tmp, setup_undo_redo=False) tmp = '(Type=Bone,Name=' tmp += "\"{}\"".format(humanoidBoneToModel[e[1]]) tmp += ')' r_con.add_array_pin(bonePin.get_pin_path(), default_value=tmp, setup_undo_redo=False) # for bone name space namePin = bonePin.get_sub_pins()[-1].find_sub_pin('Name') r_con.set_pin_default_value(namePin.get_pin_path(), "{}".format(humanoidBoneToModel[e[1]]), True, False) # skip invalid bone, controller # disable node def disableNode(toNoneNode): print(toNoneNode) print("gfgf") pins = toNoneNode.get_pins() for pin in pins: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue print(f'DisablePin {typePin.get_default_value()} : {namePin.get_default_value()}') # control key = unreal.RigElementKey(unreal.RigElementType.CONTROL, "{}".format(namePin.get_default_value())) # disable node r_con.set_pin_default_value(namePin.get_pin_path(), 'None', True, False) if (typePin.get_default_value() == 'Control'): #disable control if (hierarchy.contains(key) == True): settings = h_con.get_control_settings(key) if ("5.1." in unreal.SystemLibrary.get_engine_version()): settings.set_editor_property('shape_visible', False) else: settings.set_editor_property('shape_enabled', False) h_con.set_control_settings(key, settings) for n in node: pins = n.get_pins() for pin in pins: if (pin.is_array()): continue else: typePin = pin.find_sub_pin('Type') namePin = pin.find_sub_pin('Name') if (typePin==None or namePin==None): continue if (typePin.get_default_value() != 'Bone'): continue if (namePin.is_u_object() == True): continue if (len(n.get_linked_source_nodes()) > 0): continue key = unreal.RigElementKey(unreal.RigElementType.BONE, namePin.get_default_value()) if (hierarchy.contains(key) == True): continue print(f'disable linked node from {typePin.get_default_value()} : {namePin.get_default_value()}') for toNoneNode in n.get_linked_target_nodes(): disableNode(toNoneNode) ## morph # -vrm vrm -rig rig -debugeachsave 0 #args.vrm #args.rig command = 'VRM4U_CreateMorphTargetControllerUE5.py ' + '-vrm ' + args.vrm + ' -rig ' + args.rig + ' -debugeachsave 0' print(command) unreal.PythonScriptLibrary.execute_python_command(command) unreal.ControlRigBlueprintLibrary.recompile_vm(rig)
import unreal import os import getpass watermark_config = unreal.WatermarkConfigEditor() def get_should_add_metadata_on_import(): return watermark_config.get_editor_property("bAutoAddMetadataOnImport") def get_company_name(): if(watermark_config.get_editor_property("bShouldAddCompanyName")): return watermark_config.get_editor_property("CompanyName") else: return None def get_game_name(): return unreal.SystemLibrary.get_game_name() def get_author(): user_name = unreal.SystemLibrary.get_platform_user_name() git_user = os.popen('git config --get user.name').read().strip() return git_user if git_user else user_name if user_name else getpass.getuser() def get_folders_to_exclude(): return watermark_config.get_editor_property("FoldersToExclude") def get_metadata_to_add(asset_path): loaded_asset = unreal.EditorAssetLibrary.load_asset(asset_path) metadata_to_add = {"Author": get_author()} if loaded_asset: stored_company = unreal.EditorAssetLibrary.get_metadata_tag(loaded_asset, "CompanyName") if not stored_company and get_company_name(): metadata_to_add["CompanyName"] = get_company_name() last_used_project = unreal.EditorAssetLibrary.get_metadata_tag(loaded_asset, "LastUsedInProject") if not last_used_project: metadata_to_add["LastUsedInProject"] = get_game_name() return metadata_to_add
""" ########################################## d8888 888 .d8888b. 888 d88888 888 d88P Y88b888 d88P888 888 888 888888 d88P 888.d8888b .d8888b .d88b. 888888888 888 .d88b. 8888b. 88888b. .d88b. 888d888 d88P 88888K 88K d8P Y8b888 888 888d8P Y8b "88b888 "88bd8P Y8b888P" d88P 888"Y8888b."Y8888b.88888888888 888 88888888888888.d888888888 88888888888888 d8888888888 X88 X88Y8b. Y88b. Y88b d88P888Y8b. 888 888888 888Y8b. 888 d88P 888 88888P' 88888P' "Y8888 "Y888 "Y8888P" 888 "Y8888 "Y888888888 888 "Y8888 888 Wipe your mod's (unused) assets. Saves package size and sanity. Requires the "Python Editor Scripting" plugin to be enabled in UE4. To run: 0. Right click your mod's folder, click "Audit Assets", click "View Options" -> "Export to CSV" (save as "Report.csv" in your Downloads folder) 1. Open the "Output Log" 2. Switch to "Python" mode 3. Enter the full path to this script and hit the Enter key 4. Select your mod from the list of mods 5. Highlight all assets you'd like to remove 6. Press "Remove Selected Assets" and be prepared to wait a looooong time (depending on the total # assets to remove) ########################################## """ from Tkinter import * import tkFileDialog as fd import tkMessageBox as messagebox import ntpath import posixpath import csv import unreal import atexit import json import os import traceback import atexit from glob import glob from copy import copy string = unreal.StringLibrary.conv_name_to_string asset_lib = unreal.EditorAssetLibrary() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() level_lib = unreal.EditorLevelLibrary() asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() editor_subsystem = unreal.AssetEditorSubsystem() # Massive help from @mechamogera from Ricoh: # https://qiita-com.translate.goog/project/ DEFAULT_REPORT_NAME = "Report.csv" # Credit <3: https://its401.com/project/ def slate_deco(func): def wrapper(self, single=True, *args, **kwargs): if single: for win in QtWidgets.QApplication.topLevelWidgets(): if win is self: continue elif self.__class__.__name__ in str(type(win)): win.deleteLater() win.close() # NOTE https://forums.unrealengine.com/unreal-engine/unreal-studio/1526501 unreal.parent_external_window_to_slate(self.winId()) return func(self, *args, **kwargs) return wrapper class Assets: # Exclude assets in these paths exclusions = [ "/engine/", "/script/", "/game/", "/content/", "/niagara/" ] # Specifically include files in these # paths (overturns exclusions) inclusions = [ "/project/" ] def __init__(self, mod_path=None, max_depth=10, skip_exclusions=True, skip_internal_assets=True, exclusions=None, inclusions=None): if mod_path: self.set_mod_path(mod_path) else: self.mod_path = None self.maps_dir = None self.max_depth = max_depth self.skip_exclusions = skip_exclusions self.skip_internal_assets = skip_internal_assets if exclusions: self.exclusions += [e.lower() for e in exclusions] if inclusions: self.inclusions += [i.lower() for i in inclusions] self.dependencies = dict() def set_mod_path(self, mod_path): self.mod_path = str("/" + mod_path + "/").replace("//", "/") self.maps_dir = "{}/Maps/".format(mod_path).replace("//", "/") def find_assets(self): # Discover default Downloads dir where report should be stored documents_dir = unreal.SystemLibrary.get_platform_user_dir() downloads_dir = documents_dir.replace("Documents", "Downloads") # Ask user to select the file if it doesn't exist as DEFAULT_REPORT_NAME report_file_path = ntpath.join(downloads_dir, DEFAULT_REPORT_NAME) if not ntpath.isfile(report_file_path): report_file_path = fd.askopenfilename( title="Please select your AssetManager report.", initialdir=downloads_dir, filetypes=( ('AssetManager Report', 'Report.csv'), ('All files', '*.*') ) ) unused_assets = set() used_assets = set() with open(report_file_path) as f: reader = csv.DictReader(f) for row in reader: asset_path = posixpath.join(row["Path"], row["Name"]) if int(row["TotalUsage"]) > 0: used_assets.add(asset_path) else: unused_assets.add(asset_path) # Store these asset paths (replace any existing paths stored) self.used = used_assets self.unused = unused_assets # Return used and unused asset paths to caller return self.used, self.unused def remove(self, assets): asset_lib = unreal.EditorAssetLibrary() # Remove these assets from our Unreal project current_asset = "" with unreal.ScopedSlowTask(len(assets), current_asset) as task: task.make_dialog(True) for asset in assets: current_asset = asset asset_lib.delete_asset(asset) if task.should_cancel(): break task.enter_progress_frame(1, current_asset) def add(self, dependency_dict, dependency_path, used_by): # Add this asset to the list if we specified we wanted to add it, # or it's not an asset internal to the project if not self.skip_internal_assets or not dependency_path.lower().startswith(self.mod_path.lower()): if dependency_path not in dependency_dict: dependency_dict[dependency_path] = {} if used_by not in dependency_dict[dependency_path]: dependency_dict[dependency_path][used_by] = 0 dependency_dict[dependency_path][used_by] += 1 def get_list_dependencies(self, asset_data, depth=0): # Return if we're past the max_depth specified if depth > self.max_depth: return None asset_package_name = asset_data.get_editor_property("package_name") option = unreal.AssetRegistryDependencyOptions() dependencies = asset_registry.get_dependencies(asset_package_name, option) dependency_dict = {} unused_assets = set() if dependencies: for dependency in dependencies: dependency_path = string(dependency) # Skip any excluded package paths if self.skip_exclusions: if not dependency_path.lower().startswith(tuple(self.inclusions)) \ and dependency_path.lower().startswith(tuple(self.exclusions)): continue try: dependency_asset = unreal.EditorAssetLibrary.find_asset_data(dependency) # Attempt to add this asset to our dict self.add(dependency_dict, dependency_path, used_by=string(asset_package_name)) # Get asset deps dep_list, unused_deps = self.get_list_dependencies(dependency_asset, depth + 1) # Add unused deps to unused_assets unused_assets.update(unused_deps) # If there are no deps for our current mod path, # add to unused assets. # dep_list = asset_lib.find_package_referencers_for_asset(dependency_asset) if not dep_list or not [x for x in dep_list if self.mod_path in x]: unused_assets.add(dependency_path) continue # Add all valid asset deps for dep in dep_list: if not dep: continue self.add(dependency_dict, string(dep), used_by=dependency_path) except: pass return dependency_dict, unused_assets def get_map_assets(self): dependency_dict = {} # if level_lib.load_level(self.maps_dir + "/" + self.mod_path.strip("/")): components = level_lib.get_all_level_actors_components() for component in components: asset_paths = component.get_editor_property("asset_user_data") print(asset_paths) for asset_path in asset_paths: try: asset_data = asset_lib.find_asset_data(asset_path) except Exception: print(traceback.format_exc()) for k, v in self.get_list_dependencies(asset_data).items(): for kk, vv in v.items(): dependency_dict[k][kk] += vv return dependency_dict def get_package_assets(self): dependency_dict = {} # Get all assets in the selected mod path assets = asset_registry.get_assets_by_path( self.mod_path.rstrip("/"), recursive=True, include_only_on_disk_assets=False) if not assets: return {} # Create scoped dialog in UE4 to let the user know we're doing stuff with unreal.ScopedSlowTask(len(assets), "Retrieving asset dependencies ...") as task: task.make_dialog(True) # Iterate over assets, getting the dependencies of each for asset in assets: used, _ = self.get_list_dependencies(asset) for k, v in used.items(): for kk, vv in v.items(): if not k in dependency_dict: dependency_dict[k] = {} if not kk in dependency_dict[k]: dependency_dict[k][kk] = 0 dependency_dict[k][kk] += vv # Allow users to cancel if task.should_cancel(): break # Progress our task progress by 1 task.enter_progress_frame(1, asset.get_full_name()) self.dependencies = dependency_dict # Return a dictionary of dependency:usages return dependency_dict def get_package_references(self, package_path): dependency_dict = {} assets = asset_registry.get_assets_by_path( package_path, recursive=True, include_only_on_disk_assets=False) print("[*] Total assets to check: {}".format(len(assets))) for asset_data in assets: used_assets, unused_assets = self.get_list_dependencies(asset_data) for k, v in used_assets.items(): for kk, vv in v.items(): #if not self.mod_path.lower() in kk.lower(): # continue if not k in dependency_dict: dependency_dict[k] = {} if not kk in dependency_dict[k]: dependency_dict[k][kk] = 0 dependency_dict[k][kk] += vv return dependency_dict, unused_assets def get_unused_assets(self, package_path): assets = asset_registry.get_assets_by_path( package_path, recursive=True, include_only_on_disk_assets=False) print("[*] Total assets to check: {}".format(len(assets))) unused_assets = set() for asset_data in assets: _, unused = self.get_list_dependencies(asset_data) unused_assets.update(unused) return unused_assets def get_mod_paths(self): project_root_dir = unreal.SystemLibrary.get_project_directory() mods_dir = os.path.join(project_root_dir, "Mods") mod_directories = set() def convert_to_sandbox_path(p): return p.replace(mods_dir, "").replace("\\", "/") for mod_dir in glob(os.path.join(mods_dir, "*")): if os.path.isdir(mod_dir): mod_directories.add(convert_to_sandbox_path(ntpath.join(mods_dir, mod_dir))) return sorted(list(mod_directories)) class CustomToplevel(Toplevel): def __init__(self, parent, root, *args, **kwargs): Toplevel.__init__(self, parent, *args, **kwargs) self.root = root self.attributes('-topmost', 'true') def destroy(self): self.root.focus_set() Toplevel.destroy(self) class ScrollableFrame(Frame): def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, *args, **kwargs) canvas = Canvas(self) scrollbar = Scrollbar(self, orient="vertical", command=canvas.yview) self.scrollable_frame = Frame(canvas) self.scrollable_frame.bind( "<Configure>", lambda e: canvas.configure( scrollregion=canvas.bbox("all") ) ) Label(self.scrollable_frame, text=" "*500).pack(expand=False, fill="x") self.scrollable_frame.pack(expand=True, fill="both") self.pack(expand=True, fill="both") canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw") canvas.configure(yscrollcommand=scrollbar.set) canvas.pack(side=LEFT, fill="both", expand=True) scrollbar.pack(side=RIGHT, fill="y") class FancyTextbox(Text): def __init__(self, parent, app, *args, **kwargs): Text.__init__(self, parent, *args, **kwargs) self.app = app self.popup_menu = Menu(self, tearoff=0) self.popup_menu.add_command(label="Copy All", command=self.copy_all) self.popup_menu.add_command(label="Refresh", command=self.refresh) self.bind("<Button-3>", self.popup) # Button-2 on Aqua def popup(self, event): try: self.popup_menu.tk_popup(event.x_root, event.y_root, 0) finally: self.popup_menu.grab_release() def copy_all(self): self.app.root.clipboard_clear() self.app.root.clipboard_append(self.get(1.0, END)) def refresh(self): self.selection_set(0, END) class DependencyList(Label): def __init__(self, parent, app, referencers, *args, **kwargs): Label.__init__(self, parent, *args, **kwargs) self.app = app self.listbox = Listbox(parent, selectmode="extended") if "font" not in kwargs: self.listbox.config(font=self.app.main_font) def on_right_click(event): self.listbox.selection_clear(0, END) self.listbox.bind("<Button-3><ButtonRelease-3>", on_right_click) # self.listbox.bind("<<ListboxSelect>>", ) self.add_referencers(referencers) def add_referencers(self, referencers): # Add referencers for asset_path, times_referencd in referencers.items(): self.listbox.insert(END, asset_path) def get_selected(self): return [self.listbox.get(i) for i in self.listbox.curselection()] def select_all(self): self.listbox.select_set(0, END) class App: def __init__(self): # Get asset data self.assets = Assets() # Create root window self.title = "AssetCleaner" self.root = Tk() self.root.title(self.title) self.root.geometry("800x800") self.main_font = ("Helvatical bold", 8) self.setup_filter() self.setup_asset_list() self.setup_menu() # Add file open button self.btn = Button(self.root, text="Remove Selected Assets", command=self.remove_selected) self.btn.config(font=self.main_font) self.btn.pack(expand=False, fill="x") # Setup tick to handle Unreal ticks to update the UI self.tick_handle = None self.tick_time = 0 self.tick_handle = unreal.register_slate_post_tick_callback(self.tick) # Ensure we tell Unreal know we're exiting and want to # unregister from the Slate tick function atexit.register(self.unregister_tick) def tick(self, delta_seconds): self.tick_time += delta_seconds if not self.running: unreal.unregister_slate_post_tick_callback(self.tick_handle) return # Only tick ~60 FPS if self.tick_time > 0.016: try: self.root.update_idletasks() self.root.update() except Exception: unreal.unregister_slate_post_tick_callback(self.tick_handle) self.tick_time = 0 # Tell the Unreal Editor we're no longer handling ticks def unregister_tick(): self.running = False # unreal.unregister_slate_post_tick_callback(self.tick_handle) def run(self): self.find_assets() self.running = True if not self.assets.mod_path: self.display_mod_path_selection() def on_filter_text_changed(self, string_var): if not "last_show_command" in dir(self): self.last_show_command = self.show_unused self.last_show_command(string_var) def show_dependencies(self): if not self.assets.dependencies or refresh: self.assets.dependencies = self.assets.get_package_assets() self.display_dependencies_box() def show_used(self, asset_filter=None): self.show_assets(self.assets.used, asset_filter) self.last_show_command = self.show_used def show_unused(self, asset_filter=None): self.show_assets(self.assets.unused, asset_filter) self.last_show_command = self.show_unused def show_all(self, asset_filter=None): self.show_assets(self.assets.used.union(self.assets.unused), asset_filter) self.last_show_command = self.show_all def show_assets(self, asset_types, asset_filter=None): self.asset_list.delete(0, END) if asset_filter: asset_filter = asset_filter.get() for asset in asset_types: if asset_filter: if asset_filter in asset: self.asset_list.insert(END, asset) else: self.asset_list.insert(END, asset) def setup_filter(self): self.filter_text = StringVar() self.filter_text.trace("w", lambda name, index, mode, sv=self.filter_text: self.on_filter_text_changed(sv)) self.filter = Entry(self.root, textvariable=self.filter_text, exportselection=0) self.filter.pack(expand=False, fill="x") def setup_menu(self): menubar = Menu(self.root) actions = Menu(menubar, tearoff=1) actions.add_command(label="Show All", command=self.show_all) actions.add_command(label="Show Only Used", command=self.show_used) actions.add_command(label="Show Only Unused", command=self.show_unused) actions.add_command(label="Show Dependencies", command=self.show_dependencies) actions.add_command(label="Remove Selected", command=self.remove_selected) actions.add_command(label="Remove All Listed", command=self.remove_listed) actions.add_separator() actions.add_command(label="Exit", command=self.root.quit) menubar.add_cascade(label="Actions", menu=actions) edit_menu = Menu(menubar, tearoff=0) edit_menu.add_command(label="Undo", accelerator="Ctrl+Z") edit_menu.add_separator() edit_menu.add_command(label="Cut", command=lambda: self.asset_list.event_generate("<<Cut>>"), accelerator="Ctrl+X") edit_menu.add_command(label="Copy", command=lambda: self.asset_list.event_generate("<<Copy>>"), accelerator="Ctrl+C") edit_menu.add_command(label="Paste", command=lambda: self.asset_list.event_generate("<<Paste>>"), accelerator="Ctrl+V") edit_menu.add_separator() edit_menu.add_command(label="Select All", command=lambda: self.asset_list.event_generate("<Control-a>"), accelerator="Ctrl+A") edit_menu.add_command(label="Select None", command=lambda: self.asset_list.event_generate("<Control-d>"), accelerator="Ctrl+D") menubar.add_cascade(label="Edit", menu=edit_menu) help = Menu(menubar, tearoff=0) def show_about_box(): messagebox.showinfo(self.title, "Some message here ...") help.add_command(label="About", command=show_about_box) menubar.add_cascade(label="Help", menu=help) # Display of menu bar in the app self.menubar = menubar self.root.config(menu=menubar) def setup_asset_list(self): self.scrollbar = Scrollbar(self.root) self.scrollbar.pack(side=RIGHT, fill=Y) # Add text area """ self.text = Text(self.root, height=8) self.text.config(font=self.main_font) self.text.pack(expand=True, fill="both") """ def on_right_click(event): self.asset_list.selection_clear(0, END) #self.asset_list.selection_set(self.asset_list.nearest(event.y)) #self.asset_list.activate(self.asset_list.nearest(event.y)) def on_copy(event): self.root.clipboard_clear() for index in self.asset_list.curselection(): self.root.clipboard_append(self.asset_list.get(index) + "\n") def on_cut(event): on_copy(event) for index in self.asset_list.curselection()[::-1]: self.asset_list.delete(index) def on_select_all(event): # Select start to end self.asset_list.select_set(0, END) def on_select_none(event): self.asset_list.selection_clear(0, END) self.asset_list = Listbox(self.root, yscrollcommand=self.scrollbar.set, selectmode="extended") self.asset_list.config(font=self.main_font) self.asset_list.bind("<Button-3><ButtonRelease-3>", on_right_click) # self.asset_list.bind("<<ListboxSelect>>", ) self.asset_list.bind("<<Copy>>", on_copy) self.asset_list.bind("<<Cut>>", on_cut) self.asset_list.bind("<Control-a>", on_select_all) self.asset_list.bind("<Control-d>", on_select_none) self.asset_list.pack(expand=True, fill="both") self.scrollbar.config(command=self.asset_list.yview) def find_assets(self, asset_filter=None): self.asset_list.delete(0, END) _, unused_assets = self.assets.find_assets() for asset in unused_assets: if asset_filter: if asset_filter in asset: self.asset_list.insert(END, asset) else: self.asset_list.insert(END, asset) # self.text.insert("1.0", "\n".join(list(unused_assets))) # self.text["state"] = "disabled" # dirr = fd.askdirectory(initialdir=downloads_dir) def remove_listed(self): # Get all assets listed in the asset_list listed_assets = set() for index in range(0, self.asset_list.size()): listed_assets.add(self.asset_list.get(index)) print(listed_assets) self.assets.remove(listed_assets) exit(0) def remove_selected(self): # Get assets selected in the asset_list selected_assets = set() for index in self.asset_list.curselection(): selected_assets.add(self.asset_list.get(index)) print(selected_assets) self.assets.remove(selected_assets) exit(0) def display_data_grid(self, data, title="Data", geometry="750x250"): popup_window = CustomToplevel(self.root, self.root) popup_window.geometry(geometry) popup_window.title(title) # Ensure data is a list (should be a list of dicts) if not isinstance(data, list): if not isinstance(data, dict): data = {"NoHeader": data} data = [data] # Get IDs for all columns in dict columns = data[0].keys() rows = len(data) # Display all col/rows for r in range(rows): for c in range(len(columns)): if r == 0: Entry(popup_window, text=columns[c], borderwidth=1).grid(row=r, column=c) else: Entry(popup_window, text=data[r][columns[c]], borderwidth=1).grid(row=r, column=c) # Grab focus self.root.focus_set() popup_window.focus_set() def display_text_box(self, data, title="Text", geometry="640x420"): popup_window = CustomToplevel(self.root, self.root) popup_window.geometry(geometry) popup_window.title(title) scrollbar = Scrollbar(popup_window) scrollbar.pack(side=RIGHT, fill=Y) textbox = FancyTextbox(popup_window, self.root) textbox.config(font=self.main_font) textbox.pack(expand=True, fill="both") scrollbar.config(command=textbox.yview) # Ensure data is a list (should be a list of dicts) if isinstance(data, (list, dict, set)): if isinstance(data, set): data = list(data) textbox.insert(END, json.dumps(data, indent=2)) else: textbox.insert(END, data) # Grab focus self.root.focus_set() textbox.focus_set() #Define a function to open the Popup Dialogue def display_dependencies_box(self): dependency_lists = list() dependency_selection_window = CustomToplevel(self.root, self.root) dependency_selection_window.geometry("420x640") dependency_selection_window.resizable(height=True, width=None) def on_select_all(event): # Select start to end for dl in dependency_lists: dl.listbox.select_set(0, END) def on_select_none(event): for dl in dependency_lists: dl.listbox.selection_clear(0, END) dependency_selection_window.bind("<Control-a>", on_select_all) dependency_selection_window.bind("<Control-d>", on_select_none) frame = Frame(dependency_selection_window) canvas = Canvas(frame) scrollbar = Scrollbar(frame, orient="vertical", command=canvas.yview) frame.scrollable_frame = Frame(canvas) frame.scrollable_frame.bind( "<Configure>", lambda e: canvas.configure( scrollregion=canvas.bbox("all") ) ) def on_open_selected_assets(): selected_assets = [a for dl in dependency_lists for a in dl.get_selected()] if len(selected_assets) > 0: assets = list() for selected_asset in selected_assets: assets.append(unreal.load_asset(selected_asset)) editor_subsystem.open_editor_for_assets(assets) self.dependency_selection_window.destroy() self.dependency_selection_window.update() else: messagebox.showinfo("ERROR", "Please select a mod path to continue ...") # Add mod paths to selection window for dependency, referencers in self.assets.dependencies.items(): d = DependencyList( frame.scrollable_frame, self, referencers, text=dependency, wraplength=132, justify="left" ) dependency_lists.append(d) d.pack(expand=False, side="left", fill="x") d.listbox.pack(expand=True, fill="x") #frame.scrollable_frame.pack(expand=False, fill="x") #frame.pack(expand=True, fill="both") Label(frame.scrollable_frame, text=" "*132).pack(expand=True, fill="x") frame.scrollable_frame.pack(expand=True, fill="both") frame.pack(expand=True, fill="both") canvas.create_window((0, 0), window=frame.scrollable_frame, anchor="nw") canvas.configure(yscrollcommand=scrollbar.set) canvas.pack(side=LEFT, fill="both", expand=True) scrollbar.pack(side=RIGHT, fill="y") # Add selection button btn = Button(dependency_selection_window, text="Open Selected", command=on_open_selected_assets) btn.config(font=self.main_font) btn.pack(expand=False, fill="x") #Create a Button Widget in the Toplevel Window #button= Button(top, text="Ok", command=lambda:close_win(top)) #button.pack(pady=5, side= TOP) def old_di(self): dependency_selection_window = CustomToplevel(self.root, self.root) dependency_selection_window.geometry("420x420") frame = ScrollableFrame(dependency_selection_window) """ for i in range(50): l = Label(frame.scrollable_frame, text="Sample scrolling label") l.pack(expand=True, fill="x") """ # Pack the scrollable frame dependency_lists = list() def on_open_selected_assets(): selected_assets = [a for dl in dependency_lists for a in dl.get_selected()] if len(selected_assets) > 0: assets = list() for selected_asset in selected_assets: assets.append(unreal.load_asset(selected_asset)) asset_tools.open_editor_for_assets(assets) self.dependency_selection_window.destroy() self.dependency_selection_window.update() else: messagebox.showinfo("ERROR", "Please select a mod path to continue ...") # Add mod paths to selection window for dependency, referencers in self.assets.dependencies.items(): dependency_lists.append( DependencyList( frame.scrollable_frame, self, referencers, text=dependency, wraplength=132, justify="left" )) #frame.scrollable_frame.pack(expand=False, fill="x") #frame.pack(expand=True, fill="both") # Add selection button btn = Button(dependency_selection_window, text="Open Selected", command=on_open_selected_assets) btn.config(font=self.main_font) btn.pack(expand=False, fill="x") #Create a Button Widget in the Toplevel Window #button= Button(top, text="Ok", command=lambda:close_win(top)) #button.pack(pady=5, side= TOP) #Define a function to open the Popup Dialogue def display_mod_path_selection(self): #Create a Toplevel window self.mod_path_selection_window = CustomToplevel(self.root, self.root) self.mod_path_selection_window.geometry("420x420") def on_use_selected_mod_path(event=None): if len(mod_path_list.curselection()) > 0: selected_mod_path = mod_path_list.get(mod_path_list.curselection()[0]) self.assets.set_mod_path(selected_mod_path) self.mod_path_selection_window.destroy() self.mod_path_selection_window.update() # self.show_dependencies() else: messagebox.showinfo("ERROR", "Please select a mod path to continue ...") scrollbar = Scrollbar(self.mod_path_selection_window) scrollbar.pack(side=RIGHT, fill=Y) mod_path_list = Listbox(self.mod_path_selection_window, yscrollcommand=scrollbar.set, selectmode="single") mod_path_list.config(font=self.main_font) mod_path_list.bind("<Double-Button-1>", on_use_selected_mod_path) mod_path_list.pack(expand=True, fill="both") scrollbar.config(command=mod_path_list.yview) # Add mod paths to selection window for mod_path in self.assets.get_mod_paths(): mod_path_list.insert(END, mod_path) # Add selection button btn = Button(self.mod_path_selection_window, text="Use Selected Mod Path", command=on_use_selected_mod_path) btn.config(font=self.main_font) btn.pack(expand=False, fill="x") # Get focus self.mod_path_selection_window.focus_set() def main(): app = App() try: app.run() except Exception: app.running = False print(traceback.format_exc()) if __name__ == "__main__": main()
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)
from array import array from pickle import FALSE import unreal import json import sys inputFile = sys.argv[1] print("input argument: " + inputFile) fObj = open(inputFile) jsonData = json.load(fObj)[0] fObj.close() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() spritefactory = unreal.PaperSpriteFactory() flipbookFactory = unreal.PaperFlipbookFactory() blueprintFactory = unreal.BlueprintFactory() blueprintFactory.set_editor_property("ParentClass", unreal.Actor) projectName = jsonData["name"].replace(" ", "") def setupTextureSettings(): for asset in jsonData["assets"]: texture = unreal.Texture2D.cast(unreal.EditorAssetLibrary.load_asset("/project/"+projectName+"/"+asset["id"].replace(" ", ""))) #unreal.TextureRenderTargetFormat.RTF_RGBA8_SRGB texture.set_editor_property("lod_group", unreal.TextureGroup.TEXTUREGROUP_PIXELS2D) texture.set_editor_property("compression_settings", unreal.TextureCompressionSettings.TC_EDITOR_ICON) unreal.EditorAssetLibrary.save_loaded_asset(texture, False) def createBackground(): texture = unreal.Texture2D.cast(unreal.EditorAssetLibrary.load_asset("/project/"+projectName+"/background")) projectSize = unreal.Vector2D( jsonData["width"], jsonData["height"]) newSprite = unreal.PaperSprite.cast(asset_tools.create_asset("background", "/project/"+projectName+"/assets/", None, spritefactory) ) newSprite.set_editor_property("source_texture", texture) newSprite.set_editor_property("source_dimension", projectSize) newSprite.set_editor_property("source_texture_dimension", projectSize) newSprite.set_editor_property("pivot_mode", unreal.SpritePivotMode.CENTER_CENTER) newSprite.set_editor_property("source_uv", unreal.Vector2D( 0, 0, )) newSprite.set_editor_property("trimmed_in_source_image", True) newSprite.set_editor_property("trimmed_in_source_image", False) unreal.EditorAssetLibrary.save_loaded_asset(newSprite, False) newSprite.set_editor_property("source_uv", unreal.Vector2D( 0, 0, )) def createAssets(): with unreal.ScopedSlowTask(len(jsonData["assets"]), "Creating Assets") as slow_task: slow_task.make_dialog(True) currentAssetCount = 0 for asset in jsonData["assets"]: print("Setup asset for "+asset['id']) currentAssetCount += 1 slow_task.enter_progress_frame(currentAssetCount) id = asset['id'] tileSize = unreal.Vector2D(asset["tileSize"]["x"], asset["tileSize"]["y"]) spriteSize = unreal.Vector2D(asset["spriteSize"]["x"], asset["spriteSize"]["y"]) texture = unreal.Texture2D.cast(unreal.EditorAssetLibrary.load_asset("/project/"+projectName+"/"+asset["id"].replace(" ", ""))) xTiles = int(spriteSize.x / tileSize.x) yTiles = int(spriteSize.y / tileSize.y) currentTile = 1 for ytile in list(range(1,yTiles+1)): for xtile in list(range(1,xTiles+1)): newSprite = unreal.PaperSprite.cast(asset_tools.create_asset(str(currentTile), "/project/"+projectName+"/assets/"+id+"/sprites".replace(" ", ""), None, spritefactory) ) newSprite.set_editor_property("source_texture", texture) newSprite.set_editor_property("source_dimension", tileSize) newSprite.set_editor_property("source_texture_dimension", spriteSize) newSprite.set_editor_property("pivot_mode", unreal.SpritePivotMode.CENTER_CENTER) newSprite.set_editor_property("source_uv", unreal.Vector2D( (xtile-1) * tileSize.x, (ytile-1) * tileSize.y, )) newSprite.set_editor_property("trimmed_in_source_image", True) newSprite.set_editor_property("trimmed_in_source_image", False) unreal.EditorAssetLibrary.save_loaded_asset(newSprite, False) newSprite.set_editor_property("source_uv", unreal.Vector2D( (xtile-1) * tileSize.x, (ytile-1) * tileSize.y, )) currentTile += 1 print(id) defaultFlipbook = unreal.PaperFlipbook.cast(asset_tools.create_asset("default", "/project/"+projectName+"/assets/"+id+"/animations".replace(" ", ""), None, flipbookFactory) ) defaultFlipbook.set_editor_property("frames_per_second", 0.0) defaultFrame = unreal.PaperFlipbookKeyFrame() defaultFrame.set_editor_property("sprite",unreal.PaperSprite.cast(unreal.EditorAssetLibrary.load_asset( "/project/"+projectName+"/assets/"+id+"/project/".replace(" ", "")) )) defaultFrame.set_editor_property("frame_run",1) defaultFlipbook.set_editor_property("key_frames", [defaultFrame]) unreal.EditorAssetLibrary.save_loaded_asset(defaultFlipbook, False) animations = asset["animations"] currentAnimation = 0 for animation in animations: print(animation["name"]) newFlipbook = unreal.PaperFlipbook.cast(asset_tools.create_asset(str(animation["name"].replace(" ", "")), "/project/"+projectName+"/assets/"+id+"/animations".replace(" ", ""), None, flipbookFactory) ) newFlipbook.set_editor_property("frames_per_second", 45-float(animation["frameskip"]*10)) ##frame1.set_editor_property("sprite") animationFrames = [] for tile in animation["tiles"]: frame = unreal.PaperFlipbookKeyFrame() spritePath = "/project/"+projectName+"/assets/"+id+"/sprites/" + str(tile+1).replace(" ", "") frameSprite = unreal.PaperSprite.cast(unreal.EditorAssetLibrary.load_asset( spritePath ) ) frame.set_editor_property("sprite",frameSprite) frame.set_editor_property("frame_run",1) animationFrames.append(frame) newFlipbook.set_editor_property("key_frames", animationFrames) unreal.EditorAssetLibrary.save_loaded_asset(newFlipbook, False) currentAnimation+=1 slow_task.make_dialog(False) try: backgroundAsset = unreal.PaperSprite.cast(unreal.EditorAssetLibrary.load_asset("/project/"+projectName+"/project/")) print("skipping asset pipeline, already generated. To regenerate remote project /assets/ folder") except: setupTextureSettings() createAssets() createBackground()
# 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 all of its outputs. """ _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_instantiation(in_wrapper): print('on_post_instantiation') # in_wrapper.on_post_instantiation_state_exited_delegate_delegate.remove_callable(on_post_instantiation) # Set parameter values for the next cook # in_wrapper.set_bool_parameter_value('add_instances', True) # in_wrapper.set_int_parameter_value('num_instances', 8) in_wrapper.set_parameter_tuples({ 'add_instances': unreal.HoudiniParameterTuple(bool_values=(True, )), 'num_instances': unreal.HoudiniParameterTuple(int32_values=(8, )), }) # 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)) # Force a cook/recook in_wrapper.recook() def on_post_bake(in_wrapper, success): in_wrapper.on_post_bake_delegate.remove_callable(on_post_bake) print('bake complete ... {}'.format('success' if success else 'failed')) # Delete the hda after the bake in_wrapper.delete_instantiated_asset() global _g_wrapper _g_wrapper = None def on_post_process(in_wrapper): print('on_post_process') # in_wrapper.on_post_processing_delegate.remove_callable(on_post_process) # Print out all outputs generated by the HDA 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('') # bind to the post bake delegate in_wrapper.on_post_bake_delegate.add_callable(on_post_bake) # Bake all outputs to actors print('baking all outputs to actors') in_wrapper.bake_all_outputs_with_settings( unreal.HoudiniEngineBakeOption.TO_ACTOR, replace_previous_bake=False, remove_temp_outputs_on_success=False) def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset, disabling auto-cook of the asset (so we have to # call wrapper.reCook() to cook it) _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform(), enable_auto_cook=False) # Bind to the on post instantiation delegate (before the first cook) _g_wrapper.on_post_instantiation_delegate.add_callable(on_post_instantiation) # 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()
import unreal #from typing import List world_setting :object = unreal.EditorLevelLibrary.get_editor_world().get_world_settings() is_HLOD_enabled :bool = world_setting.get_editor_property('enable_hierarchical_lod_system') need_to_print :str = 'HLOD enabled = ' + str(is_HLOD_enabled) unreal.log_warning(need_to_print)
# -*- coding: utf-8 -*- import unreal def do_some_things(*args, **kwargs): unreal.log("do_some_things start:") for arg in args: unreal.log(arg) unreal.log("do_some_things end.")
import unreal from pamux_unreal_tools.utils.types import * from pamux_unreal_tools.utils.interface_types import * @material_function_interface("{asset_path_root}/project/{layer_name}") @parameter_name_prefix("{layer_name}") def ILayerX( 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 selected_assets = unreal.EditorUtilityLibrary.get_selected_assets() # 확인하고자 하는 파라미터 이름 parameter_name = "EnableUDW" # get boolean parameter for asset in selected_assets: if isinstance(asset, unreal.MaterialInstance): # 파라미터 이름과 값을 가져오기 found = unreal.MaterialEditingLibrary.get_material_instance_static_switch_parameter_value(asset, parameter_name) if found: print(f"Asset: {asset.get_name()}", parameter_name, ">>>", found ) else: pass else: pass # # get scalar parameter # for asset in selected_assets: # if isinstance(asset, unreal.MaterialInstance): # found = unreal.MaterialEditingLibrary.get_material_instance_scalar_parameter_value(asset,parameter_name) # if found: # print(f"Asset: {asset.get_name()}", parameter_name, ">>>", found ) # else: # pass # else: # pass
import unreal cube_target = unreal.EditorAssetLibrary.load_asset('/project/.NewTextureRenderTargetCube') cube_texture = unreal.RedArtToolkitBPLibrary.render_target_cube_create_static_texture_cube(cube_target,'/project/') print(cube_texture) # print(dir(cube_target))
# 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()
# coding: utf-8 import unreal import argparse print("VRM4U python begin") print (__file__) parser = argparse.ArgumentParser() parser.add_argument("-rigSrc") parser.add_argument("-rigDst") args = parser.parse_args() #print(args.vrm) ###### ## rig 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); a = reg.get_all_assets(); for aa in a: if (aa.get_editor_property("object_path") == args.rigSrc): rigSrc = aa.get_asset() if (aa.get_editor_property("object_path") == args.rigDst): rigDst = aa.get_asset() print(rigSrc) print(rigDst) modSrc = rigSrc.get_hierarchy_modifier() modDst = rigDst.get_hierarchy_modifier() conSrc = rigSrc.controller conDst = rigDst.controller graSrc = conSrc.get_graph() graDst = conDst.get_graph() modDst.initialize() print(rig[3]) meta = vv rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] h_mod = rig.get_hierarchy_modifier() elements = h_mod.get_selection() c = rig.controller g = c.get_graph() n = g.get_nodes() print(n) #c.add_branch_node() #c.add_array_pin() a:unreal.RigUnit_CollectionItems = unreal.RigUnit_CollectionItems() print(a) # 配列ノード追加 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=Bone' in pin.get_default_value(): collectionItem_forBone= node if 'Type=Control' in pin.get_default_value(): collectionItem_forControl = 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()) # bone array if (collectionItem_forBone == None): collectionItem_forBone = c.add_struct_node(unreal.RigUnit_CollectionItems.static_struct(), method_name='Execute') items_forBone = collectionItem_forBone.find_pin('Items') c.clear_array_pin(items_forBone.get_pin_path()) ## h_mod rigs = unreal.ControlRigBlueprint.get_currently_open_rig_blueprints() rig = rigs[0] h_mod = rig.get_hierarchy_modifier() ## meta 取得 reg = unreal.AssetRegistryHelpers.get_asset_registry(); 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 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) #print(bone_m) tmp = '(Type=Control,Name=' tmp += "{}".format(bone_h).lower() + '_c' tmp += ')' c.add_array_pin(items_forControl.get_pin_path(), default_value=tmp) #print(bone_h) #for e in h_mod.get_elements(): # 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) # print(e.name) # if (e.type == unreal.RigElementType.BONE): # tmp = '(Type=Bone,Name=' # tmp += "{}".format(e.name) # tmp += ')' # c.add_array_pin(items_forBone.get_pin_path(), default_value=tmp) # print(e.name) #print(i.get_all_pins_recursively()) #ii:unreal.RigUnit_CollectionItems = n[1] #pp = ii.get_editor_property('Items') #print(pp) #print(collectionItem.get_all_pins_recursively()[0]) #i.get_editor_property("Items") #c.add_array_pin("Execute") # arrayを伸ばす #i.get_all_pins_recursively()[0].get_pin_path() #c.add_array_pin(i.get_all_pins_recursively()[0].get_pin_path(), default_value='(Type=Bone,Name=Global)') #rig = rigs[10]
import unreal from Utilities.Utils import Singleton import math try: import numpy as np b_use_numpy = True except: b_use_numpy = False class ImageCompare(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.left_texture_size = (128, 128) self.right_texture_size = (128, 128) self.dpi_scale = 1 self.ui_img_left = "ImageLeft" self.ui_img_right = "ImageRight" self.ui_img_right_bg = "ImageRightBG" self.ui_comparison_widget = "ComparisonWidget" self.ui_dpi_scaler = "Scaler" self.ui_status_bar = "StatusBar" self.ui_ignore_alpha = "AlphaCheckBox" self.ui_scaler_combobox = "ScaleComboBox" self.combobox_items = self.data.get_combo_box_items(self.ui_scaler_combobox) self.update_status_bar() def set_image_from_viewport(self, bLeft): data, width_height = unreal.PythonBPLib.get_viewport_pixels_as_data() w, h = width_height.x, width_height.y channel_num = int(len(data) / w / h) if b_use_numpy: im = np.fromiter(data, dtype=np.uint8).reshape(w, h, channel_num) self.data.set_image_data_from_memory(self.ui_img_left if bLeft else self.ui_img_right, im.ctypes.data, len(data) , w, h, channel_num=channel_num, bgr=False , tiling=unreal.SlateBrushTileType.HORIZONTAL if bLeft else unreal.SlateBrushTileType.NO_TILE) else: texture = unreal.PythonBPLib.get_viewport_pixels_as_texture() self.data.set_image_data_from_texture2d(self.ui_img_left if bLeft else self.ui_img_right, texture , tiling=unreal.SlateBrushTileType.HORIZONTAL if bLeft else unreal.SlateBrushTileType.NO_TILE) if bLeft: self.left_texture_size = (w, h) else: self.right_texture_size = (w, h) self.update_dpi_by_texture_size() self.fit_window_size() def fit_window_size1(self): size = unreal.ChameleonData.get_chameleon_desired_size(self.json_path) def set_images_from_viewport(self): unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_LIT) self.set_image_from_viewport(bLeft=True) unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_WIREFRAME) self.set_image_from_viewport(bLeft=False) unreal.AutomationLibrary.set_editor_viewport_view_mode(unreal.ViewModeIndex.VMI_LIT) self.fit_window_size() self.update_status_bar() def update_dpi_by_texture_size(self): max_size = max(self.left_texture_size[1], self.right_texture_size[1]) if max_size >= 64: self.dpi_scale = 1 / math.ceil(max_size / 512) else: self.dpi_scale = 4 if max_size <= 16 else 2 print(f"Set dpi -> {self.dpi_scale }") self.data.set_dpi_scale(self.ui_dpi_scaler, self.dpi_scale) for index, value_str in enumerate(self.combobox_items): if float(value_str) == self.dpi_scale: self.data.set_combo_box_selected_item(self.ui_scaler_combobox, index) break def on_ui_change_scale(self, value_str): self.dpi_scale = float(value_str) self.data.set_dpi_scale(self.ui_dpi_scaler, self.dpi_scale) self.fit_window_size() def update_status_bar(self): self.data.set_text(self.ui_status_bar, f"Left: {self.left_texture_size}, Right: {self.right_texture_size} ") if self.left_texture_size != self.right_texture_size: self.data.set_color_and_opacity(self.ui_status_bar, unreal.LinearColor(2, 0, 0, 1)) else: self.data.set_color_and_opacity(self.ui_status_bar, unreal.LinearColor.WHITE) def fit_window_size(self): max_x = max(self.left_texture_size[0], self.right_texture_size[0]) max_y = max(self.left_texture_size[1], self.right_texture_size[1]) MIN_WIDTH = 400 MAX_HEIGHT = 900 self.data.set_chameleon_window_size(self.json_path , unreal.Vector2D(max(MIN_WIDTH, max_x * self.dpi_scale + 18) , min(MAX_HEIGHT, max_y * self.dpi_scale + 125)) ) def on_drop(self, bLeft, **kwargs): for asset_path in kwargs["assets"]: asset = unreal.load_asset(asset_path) if isinstance(asset, unreal.Texture2D): width = asset.blueprint_get_size_x() height = asset.blueprint_get_size_y() ignore_alpha = self.data.get_is_checked(self.ui_ignore_alpha) if self.data.set_image_data_from_texture2d(self.ui_img_left if bLeft else self.ui_img_right, asset, ignore_alpha=ignore_alpha): if bLeft: self.left_texture_size = (width, height) else: self.right_texture_size = (width, height) self.update_dpi_by_texture_size() self.fit_window_size() self.update_status_bar() break
#!/project/ python3 """ String Handling Test for MCP Server This script tests string handling in the MCP Server. It connects to the server, sends Python code with various string formats, and verifies they are handled correctly. """ import socket import json import sys def main(): """Connect to the MCP Server and test string handling.""" try: # Create socket print("Connecting to MCP Server on localhost:13377...") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(10) # 10 second timeout # Connect to server s.connect(("localhost", 13377)) print("✓ Connected successfully") # Python code with various string formats code = """ import unreal import json # Test 1: Basic string types test_string1 = "This is a simple string with double quotes" test_string2 = 'This is a simple string with single quotes' test_string3 = \"\"\"This is a multiline string\"\"\" test_string4 = f"This is an f-string with {'interpolation'}" test_string5 = "This string has escape sequences: \\n \\t \\\\ \\' \\"" test_string6 = r"This is a raw string with no escape processing: \n \t \\" # Test 2: Print statements print("Print statement 1: Simple string") print(f"Print statement 2: F-string with {test_string2}") print("Print statement 3: Multiple", "arguments", 123, test_string3) print("Print statement 4: With escape sequences: \\n \\t") # Test 3: Potentially problematic strings test_string7 = "String with quotes: 'single' and \\"double\\"" test_string8 = 'String with quotes: "double" and \\'single\\'' test_string9 = "String with backslashes: \\ \\\\ \\n" test_string10 = "String with special characters: 🐍 😊 🚀" # Test 4: Unterminated strings (these are properly terminated but might be misinterpreted) test_string11 = "String with a quote at the end: '" test_string12 = 'String with a quote at the end: "' test_string13 = "String with a backslash at the end: \\" test_string14 = "String with multiple backslashes at the end: \\\\" # Test 5: String concatenation test_string15 = "Part 1 " + "Part 2" test_string16 = "Multiple " + "parts " + "concatenated" test_string17 = "Mixed " + 'quote' + " types" # Collect results in a dictionary results = { "test1": test_string1, "test2": test_string2, "test3": test_string3, "test4": test_string4, "test5": test_string5, "test6": test_string6, "test7": test_string7, "test8": test_string8, "test9": test_string9, "test10": test_string10, "test11": test_string11, "test12": test_string12, "test13": test_string13, "test14": test_string14, "test15": test_string15, "test16": test_string16, "test17": test_string17 } # Log the results unreal.log("===== STRING TEST RESULTS =====") for key, value in results.items(): unreal.log(f"{key}: {value}") # Return the results as JSON return json.dumps(results, indent=2) """ # Create command with multiple formats to try to make it work command = { "command": "execute_python", "type": "execute_python", "code": code, "data": { "code": code } } # Send command print("Sending execute_python command...") command_str = json.dumps(command) + "\n" # Add newline s.sendall(command_str.encode('utf-8')) # Receive response print("Waiting for response...") response = b"" while True: data = s.recv(4096) if not data: break response += data if b"\n" in data: # Check for newline which indicates end of response break # Close connection s.close() print("✓ Connection closed properly") # Process response if response: response_str = response.decode('utf-8').strip() try: response_json = json.loads(response_str) print("\n=== RESPONSE ===") print(f"Status: {response_json.get('status', 'unknown')}") if response_json.get('status') == 'success': print("✓ String test successful") result = response_json.get('result', {}) if isinstance(result, dict) and 'output' in result: output = result['output'] print(f"Output length: {len(output)} characters") print("First 200 characters of output:") print(output[:200] + "..." if len(output) > 200 else output) return True else: print("✗ String test failed") print(f"Error: {response_json.get('message', 'Unknown error')}") return False except json.JSONDecodeError as e: print(f"✗ Error parsing JSON response: {e}") print(f"Raw response: {response_str}") return False else: print("✗ No response received from server") return False except ConnectionRefusedError: print("✗ Connection refused. Is the MCP Server running?") return False except socket.timeout: print("✗ Connection timed out. Is the MCP Server running?") return False except Exception as e: print(f"✗ Error: {e}") return False if __name__ == "__main__": print("=== MCP Server String Handling Test ===") success = main() print("\n=== TEST RESULT ===") if success: print("✓ String handling test PASSED") sys.exit(0) else: print("✗ String handling test FAILED") sys.exit(1)
import gc import unreal import sys __lo_d_level :str _num_lod : int = int(__lo_d_level) # Binded value from Widget UI selected : list = unreal.EditorUtilityLibrary.get_selected_assets() #get selected assets using editorUtilityLib def skeletal_mesh_lod_builder ( __num_lod : int, __asssets : list ) -> bool : for each in __asssets : each.regenerate_lod(__num_lod, True) return True #return TRUE if this has been run successfully def static_mesh_lod_builder ( __num_lod : int, __asssets : list ) -> bool : for each in __asssets : #unreal.EditorStaticMeshLibrary(each, ) pass skeletal_mesh_lod_builder( _num_lod, selected ) #Memory Free here del selected del _num_lod
import unreal import argparse import json def get_scriptstruct_by_node_name(node_name): control_rig_blueprint = unreal.load_object(None, '/project/') rig_vm_graph = control_rig_blueprint.get_model() nodes = rig_vm_graph.get_nodes() for node in nodes: if node.get_node_path() == node_name: return node.get_script_struct() last_construction_link = 'PrepareForExecution' def create_construction(bone_name): global last_construction_link control_name = bone_name + '_ctrl' get_bone_transform_node_name = "RigUnit_Construction_GetTransform_" + bone_name set_control_transform_node_name = "RigtUnit_Construction_SetTransform_" + control_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(137.732236, -595.972187), get_bone_transform_node_name) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_bone_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.bInitial', 'True') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Type', 'Bone', True) rig_controller.set_node_selection([get_bone_transform_node_name]) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(526.732236, -608.972187), set_control_transform_node_name) except Exception as e: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(526.732236, -608.972187), set_control_transform_node_name) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_control_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bInitial', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Type', 'Control', True) try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Value') except: try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py, line 45: rig_controller.add_link(): " + str(e)) rig_controller.set_node_position_by_name(set_control_transform_node_name, unreal.Vector2D(512.000000, -656.000000)) rig_controller.add_link(last_construction_link + '.ExecuteContext', set_control_transform_node_name + '.ExecuteContext') last_construction_link = set_control_transform_node_name last_backward_solver_link = 'InverseExecution.ExecuteContext' def create_backward_solver(bone_name): global last_backward_solver_link control_name = bone_name + '_ctrl' get_bone_transform_node_name = "RigUnit_BackwardSolver_GetTransform_" + bone_name set_control_transform_node_name = "RigtUnit_BackwardSolver_SetTransform_" + control_name #rig_controller.add_link('InverseExecution.ExecuteContext', 'RigUnit_SetTransform_3.ExecuteContext') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-636.574629, -1370.167943), get_bone_transform_node_name) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_bone_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(get_bone_transform_node_name + '.Item.Type', 'Bone', True) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(-190.574629, -1378.167943), set_control_transform_node_name) except: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(-190.574629, -1378.167943), set_control_transform_node_name) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_control_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bInitial', 'False') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_control_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(set_control_transform_node_name + '.Item.Type', 'Control', True) #rig_controller.set_pin_default_value(set_control_transform_node_name + '.Transform', '(Rotation=(X=0.000000,Y=0.000000,Z=0.000000,W=-1.000000),Translation=(X=0.551784,Y=-0.000000,Z=72.358307),Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))', True) try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Value') except: try: rig_controller.add_link(get_bone_transform_node_name + '.Transform', set_control_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py, line 84: rig_controller.add_link(): " + str(e)) rig_controller.add_link(last_backward_solver_link, set_control_transform_node_name + '.ExecuteContext') last_backward_solver_link = set_control_transform_node_name + '.ExecuteContext' def create_control(bone_name): control_name = bone_name + '_ctrl' default_setting = unreal.RigControlSettings() default_setting.shape_name = 'Box_Thin' default_setting.control_type = unreal.RigControlType.EULER_TRANSFORM default_value = hierarchy.make_control_value_from_euler_transform( unreal.EulerTransform(scale=[1, 1, 1])) key = unreal.RigElementKey(type=unreal.RigElementType.BONE, name=bone_name) rig_control_element = hierarchy.find_control(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name)) control_key = rig_control_element.get_editor_property('key') print(rig_control_element) if control_key.get_editor_property('name') != "": control_key = rig_control_element.get_editor_property('key') else: try: control_key = hierarchy_controller.add_control(control_name, unreal.RigElementKey(), default_setting, default_value, True, True) except: control_key = hierarchy_controller.add_control(control_name, unreal.RigElementKey(), default_setting, default_value, True) transform = hierarchy.get_global_transform(key, True) hierarchy.set_control_offset_transform(control_key, transform, True) if bone_name in control_list: create_direct_control(bone_name) elif bone_name in effector_list: create_effector(bone_name) create_construction(bone_name) create_backward_solver(bone_name) effector_get_transform_widget_height = 0 def create_direct_control(bone_name): global next_forward_execute global effector_get_transform_widget_height #effector_get_transform_widget_height += 250 control_name = bone_name + '_ctrl' get_control_transform_node_name = "RigUnit_DirectControl_GetTransform_" + bone_name set_bone_transform_node_name = "RigtUnit_DirectControl_SetTransform_" + control_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(101.499447, -244.500249), get_control_transform_node_name) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_control_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Type', 'Control', True) try: rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) except: set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item', '(Type=Bone,Name="None")') rig_controller.set_pin_expansion(set_bone_transform_node_name + '.Item', False) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bInitial', 'False') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Weight', '1.000000') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bPropagateToChildren', 'True') rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Name', bone_name, True) rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Type', 'Bone', True) try: rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Value') except: try: rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Transform') except Exception as e: print("ERROR: CreateControlRig.py: rig_controller.add_Link(): " + str(e)) rig_controller.add_link(next_forward_execute, set_bone_transform_node_name + '.ExecuteContext') next_forward_execute = set_bone_transform_node_name + '.ExecuteContext' # def create_preferred_angle_control(bone_name): # global next_forward_execute # global effector_get_transform_widget_height # #effector_get_transform_widget_height += 250 # control_name = bone_name + '_ctrl' # get_control_transform_node_name = "RigUnit_PreferredAngle_GetTransform_" + bone_name # set_bone_transform_node_name = "RigtUnit_PreferredAngle_SetTransform_" + control_name # rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(101.499447, -244.500249), get_control_transform_node_name) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item', '(Type=Bone)') # rig_controller.set_pin_expansion(get_control_transform_node_name + '.Item', True) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Space', 'GlobalSpace') # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Name', control_name, True) # rig_controller.set_pin_default_value(get_control_transform_node_name + '.Item.Type', 'Control', True) # try: # rig_controller.add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren,io ExecuteContext)', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) # except: # set_transform_scriptstruct = get_scriptstruct_by_node_name("SetTransform") # rig_controller.add_unit_node(set_transform_scriptstruct, 'Execute', unreal.Vector2D(542.832780, -257.833582), set_bone_transform_node_name) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item', '(Type=Bone,Name="None")') # rig_controller.set_pin_expansion(set_bone_transform_node_name + '.Item', False) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Space', 'GlobalSpace') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bInitial', 'False') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Weight', '1.000000') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.bPropagateToChildren', 'True') # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Name', bone_name, True) # rig_controller.set_pin_default_value(set_bone_transform_node_name + '.Item.Type', 'Bone', True) # try: # rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Value') # except: # try: # rig_controller.add_link(get_control_transform_node_name + '.Transform', set_bone_transform_node_name + '.Transform') # except Exception as e: # print("ERROR: CreateControlRig.py: rig_controller.add_Link(): " + str(e)) # rig_controller.add_link(next_forward_execute, set_bone_transform_node_name + '.ExecuteContext') # next_forward_execute = set_bone_transform_node_name + '.ExecuteContext' def create_effector(bone_name): global effector_get_transform_widget_height effector_get_transform_widget_height += 250 control_name = bone_name + '_ctrl' get_transform_name = control_name + '_RigUnit_GetTransform' pin_name = rig_controller.insert_array_pin('PBIK.Effectors', -1, '') print(pin_name) rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-122.733358, effector_get_transform_widget_height), get_transform_name) rig_controller.set_pin_default_value(get_transform_name + '.Item', '(Type=Bone)') rig_controller.set_pin_expansion(get_transform_name + '.Item', True) rig_controller.set_pin_default_value(get_transform_name + '.Space', 'GlobalSpace') rig_controller.set_pin_default_value(get_transform_name + '.Item.Name', control_name, True) rig_controller.set_pin_default_value(get_transform_name + '.Item.Type', 'Control', True) rig_controller.set_node_selection([get_transform_name]) rig_controller.add_link(get_transform_name + '.Transform', pin_name + '.Transform') rig_controller.set_pin_default_value(pin_name + '.Bone', bone_name, False) if(bone_name in guide_list): rig_controller.set_pin_default_value(pin_name + '.StrengthAlpha', '0.200000', False) parser = argparse.ArgumentParser(description = 'Creates a Control Rig given a SkeletalMesh') parser.add_argument('--skeletalMesh', help='Skeletal Mesh to Use') parser.add_argument('--dtuFile', help='DTU File to use') args = parser.parse_args() asset_name = args.skeletalMesh.split('.')[1] + '_CR' package_path = args.skeletalMesh.rsplit('/', 1)[0] blueprint = unreal.load_object(name = package_path + '/' + asset_name , outer = None) if not blueprint: blueprint = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=asset_name, package_path=package_path, asset_class=unreal.ControlRigBlueprint, factory=unreal.ControlRigBlueprintFactory()) #blueprint = unreal.load_object(name = '/project/.NewControlRigBlueprint', outer = None) if blueprint: # Turn off notifications or each change will compile the RigVM blueprint.suspend_notifications(True) library = blueprint.get_local_function_library() library_controller = blueprint.get_controller(library) hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() rig_controller = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() #rig_controller.set_node_selection(['RigUnit_BeginExecution']) hierarchy_controller.import_bones_from_asset(args.skeletalMesh, 'None', True, False, True) # Remove Existing Nodes graph = rig_controller.get_graph() node_count = len(graph.get_nodes()) while node_count > 0: rig_controller.remove_node(graph.get_nodes()[-1]) node_count = node_count - 1 # Create Full Body IK Node rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_BeginExecution', 'Execute', unreal.Vector2D(22.229613, 60.424645), 'BeginExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PrepareForExecution', 'Execute', unreal.Vector2D(-216.659278, -515.130927), 'PrepareForExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_InverseExecution', 'Execute', unreal.Vector2D(-307.389434, -270.395477), 'InverseExecution') rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PBIK', 'Execute', unreal.Vector2D(370.599976, 42.845032), 'PBIK') rig_controller.set_pin_default_value('PBIK.Settings', '(Iterations=20,MassMultiplier=1.000000,MinMassMultiplier=0.200000,bStartSolveFromInputPose=True)') rig_controller.set_pin_expansion('PBIK.Settings', False) rig_controller.set_pin_default_value('PBIK.Debug', '(DrawScale=1.000000)') rig_controller.set_pin_expansion('PBIK.Debug', False) rig_controller.set_node_selection(['PBIK']) rig_controller.set_pin_default_value('PBIK.Root', 'hip', False) rig_controller.insert_array_pin('PBIK.BoneSettings', -1, '') rig_controller.set_pin_default_value('PBIK.BoneSettings.0.Bone', 'pelvis', False) rig_controller.set_pin_default_value('PBIK.BoneSettings.0.RotationStiffness', '0.900000', False) rig_controller.set_pin_default_value('PBIK.BoneSettings.0.PositionStiffness', '0.900000', False) next_forward_execute = 'BeginExecution.ExecuteContext' #rig_controller.add_link('BeginExecution.ExecuteContext', 'PBIK.ExecuteContext') # Get Bone list for character dtu_data = json.load(open(args.dtuFile.replace('\"', ''))) limits = dtu_data['LimitData'] bones_in_dtu = ['root'] for bone_limits in limits.values(): bone_limit_name = bone_limits[0] #print(bone_limit_name) bones_in_dtu.append(bone_limit_name) # Create Effectors, order matters. Child controls should be after Parent Control effector_list = ['pelvis', 'l_foot', 'r_foot', 'spine4', 'l_hand', 'r_hand'] # G9 effector_list+= ['chestUpper', 'head', 'lFoot', 'rFoot', 'lHand', 'rHand'] #G8 effector_list = [bone for bone in effector_list if bone in bones_in_dtu] #print(effector_list) # These controls are mid chain and don't have full weight guide_list = ['l_shin', 'r_shin', 'l_forearm', 'r_forearm'] # G9 guide_list+= ['lShin', 'rShin', 'lForearmBend', 'rForearmBend'] # G8 guide_list = [bone for bone in guide_list if bone in bones_in_dtu] # These controls are for bones that shouldn't move much on their own, but user can rotate them suggested_rotation_list = ['l_shoulder', 'r_shoulder'] # G9 suggested_rotation_list+= ['lCollar', 'rCollar'] # G8 suggested_rotation_list = [bone for bone in suggested_rotation_list if bone in bones_in_dtu] # This is for controls outside of Full Body IK control_list = ['root', 'hip'] control_list = [bone for bone in control_list if bone in bones_in_dtu] for effector_name in control_list + effector_list + guide_list: create_control(effector_name) parent_list = { 'root':['hip', 'l_foot', 'r_foot', 'l_shin', 'r_shin', 'lFoot', 'rFoot', 'lShin', 'rShin'], 'hip':['pelvis'], 'pelvis':['spine4', 'chestUpper'], 'spine4':['head', 'l_hand', 'r_hand', 'l_forearm', 'r_forearm'], 'chestUpper':['head', 'lHand', 'rHand', 'lForearmBend', 'rForearmBend'] } for parent_bone, child_bone_list in parent_list.items(): if not parent_bone in bones_in_dtu: continue filtered_child_bone_list = [bone for bone in child_bone_list if bone in bones_in_dtu] for child_bone in child_bone_list: hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name= child_bone + '_ctrl'), unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name= parent_bone + '_ctrl'), True) hierarchy.set_local_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=child_bone + '_ctrl'), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,-0.000000],scale=[1.000000,1.000000,1.000000]), True, True) skeletal_mesh = unreal.load_object(name = args.skeletalMesh, outer = None) skeletal_mesh_import_data = skeletal_mesh.get_editor_property('asset_import_data') skeletal_mesh_force_front_x = skeletal_mesh_import_data.get_editor_property('force_front_x_axis') stiff_limits = ['l_shoulder', 'r_shoulder'] stiff_limits+= ['lCollar', 'rCollar'] exclude_limits = ['root', 'hip', 'pelvis'] for bone_limits in limits.values(): # Get the name of the bone bone_limit_name = bone_limits[0] # Add twist bones to the exlude list if 'twist' in bone_limit_name.lower(): exluded_bone_settings = rig_controller.insert_array_pin('PBIK.ExcludedBones', -1, '') rig_controller.set_pin_default_value(exluded_bone_settings, bone_limit_name, False) # Get the bone limits bone_limit_x_min = bone_limits[2] bone_limit_x_max = bone_limits[3] bone_limit_y_min = bone_limits[4] * -1.0 bone_limit_y_max = bone_limits[5] * -1.0 bone_limit_z_min = bone_limits[6] * -1.0 bone_limit_z_max = bone_limits[7] * -1.0 # update the axis if force front was used (facing right) if skeletal_mesh_force_front_x: bone_limit_y_min = bone_limits[2] * -1.0 bone_limit_y_max = bone_limits[3] * -1.0 bone_limit_z_min = bone_limits[4] * -1.0 bone_limit_z_max = bone_limits[5] * -1.0 bone_limit_x_min = bone_limits[6] bone_limit_x_max = bone_limits[7] if not bone_limit_name in exclude_limits: #if not bone_limit_name == "l_shin": continue limit_bone_settings = rig_controller.insert_array_pin('PBIK.BoneSettings', -1, '') rig_controller.set_pin_default_value(limit_bone_settings + '.Bone', bone_limit_name, False) x_delta = abs(bone_limit_x_max - bone_limit_x_min) y_delta = abs(bone_limit_y_max - bone_limit_y_min) z_delta = abs(bone_limit_z_max - bone_limit_z_min) if(x_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Locked', False) elif (x_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Free', False) if(y_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Locked', False) elif (y_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Free', False) if(z_delta < 15.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Locked', False) elif (z_delta > 90.0): rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Free', False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Free', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.X', 'Limited', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.Y', 'Limited', False) # rig_controller.set_pin_default_value(limit_bone_settings + '.Z', 'Limited', False) # It feels like Min\Max angel aren't the actual extents, but the amount of rotation allowed. So they shoudl be 0 to abs(min, max) # I think there's a bug if a min rotation is more negative than max is positive, the negative gets clamped to the relative positive. rig_controller.set_pin_default_value(limit_bone_settings + '.MinX', str(min(bone_limit_x_max, bone_limit_x_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxX', str(max(bone_limit_x_max, abs(bone_limit_x_min))), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MinY', str(min(bone_limit_y_max, bone_limit_y_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxY', str(max(bone_limit_y_max, abs(bone_limit_y_min))), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MinZ', str(min(bone_limit_z_max, bone_limit_z_min)), False) rig_controller.set_pin_default_value(limit_bone_settings + '.MaxZ', str(max(bone_limit_z_max, abs(bone_limit_z_min))), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinX', str(min(bone_limit_z_max, bone_limit_z_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxX', str(max(bone_limit_z_max, bone_limit_z_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinY', str(min(bone_limit_x_max, bone_limit_x_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxY', str(max(bone_limit_x_max, bone_limit_x_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MinZ', str(min(bone_limit_y_max, bone_limit_y_min)), False) # rig_controller.set_pin_default_value(limit_bone_settings + '.MaxZ', str(max(bone_limit_y_max, bone_limit_y_min)), False) if bone_limit_name in stiff_limits: rig_controller.set_pin_default_value(limit_bone_settings + '.PositionStiffness', '0.800000', False) rig_controller.set_pin_default_value(limit_bone_settings + '.RotationStiffness', '0.800000', False) # Figure out preferred angles, the primary angle is the one that turns the furthest from base pose rig_controller.set_pin_default_value(limit_bone_settings + '.bUsePreferredAngles', 'true', False) x_max_rotate = max(abs(bone_limit_x_min), abs(bone_limit_x_max)) y_max_rotate = max(abs(bone_limit_y_min), abs(bone_limit_y_max)) z_max_rotate = max(abs(bone_limit_z_min), abs(bone_limit_z_max)) #print(bone_limit_name, x_max_rotate, y_max_rotate, z_max_rotate) if bone_limit_name in suggested_rotation_list: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', "0.0", False) rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', "0.0", False) rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', "0.0", False) create_control(bone_limit_name) to_euler_name = "Preferred_Angles_To_Euler_" + bone_limit_name get_transform_name = "Preferred_Angles_GetRotator_" + bone_limit_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetControlRotator', 'Execute', unreal.Vector2D(-344.784477, 4040.400172), get_transform_name) rig_controller.set_pin_default_value(get_transform_name + '.Space', 'GlobalSpace') #rig_controller.set_pin_default_value(get_transform_name + '.bInitial', 'False') rig_controller.set_pin_default_value(get_transform_name + '.Control', bone_limit_name + '_ctrl', True) #rig_controller.set_pin_default_value(get_transform_name + '.Item.Type', 'Control', True) #rig_controller.add_unit_node_from_struct_path('/project/.RigVMFunction_MathQuaternionToEuler', 'Execute', unreal.Vector2D(9.501237, 4176.400172), to_euler_name) #rig_controller.add_link(get_transform_name + '.Transform.Rotation', to_euler_name + '.Value') rig_controller.add_link(get_transform_name + '.Rotator.Roll', limit_bone_settings + '.PreferredAngles.X') rig_controller.add_link(get_transform_name + '.Rotator.Pitch', limit_bone_settings + '.PreferredAngles.Y') rig_controller.add_link(get_transform_name + '.Rotator.Yaw', limit_bone_settings + '.PreferredAngles.Z') else: limit_divider = 1.0 if x_max_rotate > y_max_rotate and x_max_rotate > z_max_rotate: if abs(bone_limit_x_min) > abs(bone_limit_x_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', str(bone_limit_x_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.X', str(bone_limit_x_max / limit_divider), False) if y_max_rotate > x_max_rotate and y_max_rotate > z_max_rotate: if abs(bone_limit_y_min) > abs(bone_limit_y_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', str(bone_limit_y_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Y', str(bone_limit_y_max / limit_divider), False) if z_max_rotate > x_max_rotate and z_max_rotate > y_max_rotate: if abs(bone_limit_z_min) > abs(bone_limit_z_max): rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', str(bone_limit_z_min / limit_divider), False) else: rig_controller.set_pin_default_value(limit_bone_settings + '.PreferredAngles.Z', str(bone_limit_z_max / limit_divider), False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.Bone', 'pelvis', False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.RotationStiffness', '0.900000', False) # rig_controller.set_pin_default_value('PBIK.BoneSettings.0.PositionStiffness', '0.900000', False) # Attach the node to execute rig_controller.add_link(next_forward_execute, 'PBIK.ExecuteContext') unreal.ControlRigBlueprintLibrary.set_preview_mesh(blueprint, skeletal_mesh) # Turn on notifications and force a recompile blueprint.suspend_notifications(False) unreal.ControlRigBlueprintLibrary.recompile_vm(blueprint) #rig_controller.add_link('RigUnit_BeginExecution.ExecuteContext', 'PBIK.ExecuteContext')
# 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 src_num :str #Binded value from Widget UI dst_num :str # Binded value from Widget UI ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets() if len(ar_asset_lists) > 0 : for each in ar_asset_lists : src_asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(each) dst_asset_path = src_asset_path.replace(src_num, dst_num) rename = unreal.EditorAssetLibrary.rename_asset(src_asset_path, dst_asset_path) #Memory Free here del ar_asset_lists del src_num del dst_num
import unreal import argparse import DTUControlRigHelpers import importlib importlib.reload(DTUControlRigHelpers) # Info about Python with IKRigs here: # https://docs.unrealengine.com/5.2/en-US/using-python-to-create-and-edit-ik-rigs-in-unreal-engine/ # https://docs.unrealengine.com/5.2/en-US/using-python-to-create-and-edit-ik-retargeter-assets-in-unreal-engine/ # Figure out the forward axis for a child bone def get_bone_forward_axis(child_bone_relative_pos): forward = "X+" if abs(child_bone_relative_pos.x) > max(abs(child_bone_relative_pos.y), abs(child_bone_relative_pos.z)): forward = 'X' + forward[1] if abs(child_bone_relative_pos.y) > max(abs(child_bone_relative_pos.x), abs(child_bone_relative_pos.z)): forward = 'Y' + forward[1] if abs(child_bone_relative_pos.z) > max(abs(child_bone_relative_pos.x), abs(child_bone_relative_pos.y)): forward = 'Z' + forward[1] if forward[0] == 'X' and child_bone_relative_pos.x > 0: forward = forward[0] + '+' if forward[0] == 'X' and child_bone_relative_pos.x < 0: forward = forward[0] + '-' if forward[0] == 'Y' and child_bone_relative_pos.y > 0: forward = forward[0] + '+' if forward[0] == 'Y' and child_bone_relative_pos.y < 0: forward = forward[0] + '-' if forward[0] == 'Z' and child_bone_relative_pos.z > 0: forward = forward[0] + '+' if forward[0] == 'Z' and child_bone_relative_pos.z < 0: forward = forward[0] + '-' return forward parser = argparse.ArgumentParser(description = 'Creates an IKRetargetter between two control rigs') parser.add_argument('--sourceIKRig', help='Source IKRig to Use') parser.add_argument('--targetIKRig', help='Target IKRig to Use') args = parser.parse_args() # Retageter name is Source_to_Target asset_tools = unreal.AssetToolsHelpers.get_asset_tools() source_rig_name = args.sourceIKRig.split('.')[-1] target_rig_name = args.targetIKRig.split('.')[-1] # Check if it exists package_path = args.targetIKRig.rsplit('/', 1)[0] + '/' asset_name = source_rig_name.replace('_IKRig', '') + '_to_' + target_rig_name.replace('_IKRig', '') + '_IKRetargeter' rtg = skel_mesh = unreal.load_asset(name = package_path + asset_name ) # If not, create a new one if not rtg: rtg = asset_tools.create_asset( asset_name=asset_name, package_path=package_path, asset_class=unreal.IKRetargeter, factory=unreal.IKRetargetFactory()) # Get the IK Retargeter controller rtg_controller = unreal.IKRetargeterController.get_controller(rtg) # Load the Source and Target IK Rigs source_ik_rig = unreal.load_asset(name = args.sourceIKRig) target_ik_rig = unreal.load_asset(name = args.targetIKRig) source_ikr_controller = unreal.IKRigController.get_controller(source_ik_rig) target_ikr_controller = unreal.IKRigController.get_controller(target_ik_rig) # Load the Source and Target Skeletal Meshes source_ik_mesh = unreal.IKRigController.get_controller(source_ik_rig).get_skeletal_mesh() target_ik_mesh = unreal.IKRigController.get_controller(target_ik_rig).get_skeletal_mesh() # Assign the Source and Target IK Rigs rtg_controller.set_ik_rig(unreal.RetargetSourceOrTarget.SOURCE, source_ik_rig) rtg_controller.set_ik_rig(unreal.RetargetSourceOrTarget.TARGET, target_ik_rig) rtg_controller.auto_map_chains(unreal.AutoMapChainType.EXACT, True) # Get the root rotation source_asset_import_data = source_ik_mesh.get_editor_property('asset_import_data') target_asset_import_data = target_ik_mesh.get_editor_property('asset_import_data') source_force_front_x = source_asset_import_data.get_editor_property('force_front_x_axis') target_force_front_x = target_asset_import_data.get_editor_property('force_front_x_axis') # Rotate the root if needed so the character faces forward if source_force_front_x == False and target_force_front_x == True: rotation_offset = unreal.Rotator() rotation_offset.yaw = 90 rtg_controller.set_rotation_offset_for_retarget_pose_bone("root", rotation_offset.quaternion(), unreal.RetargetSourceOrTarget.TARGET) # Setup the root translation root_chain_settings = rtg_controller.get_retarget_chain_settings('Root') root_chain_fk_settings = root_chain_settings.get_editor_property('fk') root_chain_fk_settings.set_editor_property('translation_mode', unreal.RetargetTranslationMode.ABSOLUTE) rtg_controller.set_retarget_chain_settings('Root', root_chain_settings) # Set the root Settings (not the root chain settings) root_settings = rtg_controller.get_root_settings() root_settings.blend_to_source = 1.0 # Fixes a hitch in the MM_Run_Fwd conversion rtg_controller.set_root_settings(root_settings) # Get the bone limit data bone_limits = DTUControlRigHelpers.get_bone_limits_from_skeletalmesh(target_ik_mesh) # Align chains source_skeleton = source_ik_mesh.get_editor_property('skeleton') target_skeleton = target_ik_mesh.get_editor_property('skeleton') source_reference_pose = source_skeleton.get_reference_pose() target_reference_pose = target_skeleton.get_reference_pose() def single_axis_bend(target_bone, source_bone): axis_x, axis_y, axis_z = bone_limits[str(target_bone)].get_preferred_angle() source_bone_transform = source_reference_pose.get_ref_bone_pose(source_bone, space=unreal.AnimPoseSpaces.LOCAL) source_bone_rotation = source_bone_transform.get_editor_property('rotation').rotator() source_angle = abs(max(source_bone_rotation.get_editor_property("pitch"), source_bone_rotation.get_editor_property("yaw"), source_bone_rotation.get_editor_property("roll"), key=lambda x: abs(x))) new_rot = unreal.Rotator() if axis_x > 0.01: new_rot.set_editor_property('roll', source_angle) #X if axis_x < -0.01: new_rot.set_editor_property('roll', source_angle * -1.0) #X if axis_y > 0.01: new_rot.set_editor_property('pitch', source_angle) #Y if axis_y < -0.01: new_rot.set_editor_property('pitch', source_angle * -1.0) #Y if axis_z > 0.01: new_rot.set_editor_property('yaw', source_angle) #Z if axis_z < -0.01: new_rot.set_editor_property('yaw', source_angle * -1.0) #Z rtg_controller.set_rotation_offset_for_retarget_pose_bone(target_bone, new_rot.quaternion(), unreal.RetargetSourceOrTarget.TARGET) def dual_axis_target_bend(target_bone, source_bone, target_end_bone, source_end_bone): source_bone_transform = source_reference_pose.get_ref_bone_pose(source_bone, space=unreal.AnimPoseSpaces.WORLD) source_end_bone_transform = source_reference_pose.get_ref_bone_pose(source_end_bone, space=unreal.AnimPoseSpaces.WORLD) source_relative_position = source_end_bone_transform.get_editor_property('translation') - source_bone_transform.get_editor_property('translation') # Fix the axis if the target character is facing right if source_force_front_x == False and target_force_front_x == True: new_relative_position = unreal.Vector() new_relative_position.x = source_relative_position.y * -1.0 new_relative_position.y = source_relative_position.x * -1.0 new_relative_position.z = source_relative_position.z source_relative_position = new_relative_position target_bone_transform_world = target_reference_pose.get_ref_bone_pose(target_bone, space=unreal.AnimPoseSpaces.WORLD) target_end_bone_transform_world = target_reference_pose.get_ref_bone_pose(target_end_bone, space=unreal.AnimPoseSpaces.WORLD) target_relative_position = target_end_bone_transform_world.get_editor_property('translation') - target_bone_transform_world.get_editor_property('translation') target_position = target_bone_transform_world.get_editor_property('translation') + source_relative_position #- (target_relative_position - source_relative_position) new_pos = target_bone_transform_world.inverse_transform_location(target_position) target_child_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_bone, target_end_bone) target_child_bone_transform_local = target_reference_pose.get_ref_bone_pose(target_child_bone, space=unreal.AnimPoseSpaces.LOCAL) forward_direction = get_bone_forward_axis(target_child_bone_transform_local.get_editor_property('translation')) # Make a rotator to point the joints at the new new_rot = unreal.Rotator() if forward_direction[0] == 'X': y_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.x) * -1.0 z_rot = unreal.MathLibrary.deg_atan(new_pos.y / new_pos.x) new_rot.set_editor_property('pitch', y_rot) #Y new_rot.set_editor_property('yaw', z_rot) #Z if forward_direction == 'Y+': x_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.y) #* -1.0 z_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.y) * -1.0 new_rot.set_editor_property('yaw', z_rot) #Z new_rot.set_editor_property('roll', x_rot) #X if forward_direction == 'Y-': x_rot = unreal.MathLibrary.deg_atan(new_pos.z / new_pos.y) * -1.0 z_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.y) * -1.0 new_rot.set_editor_property('yaw', z_rot) #Z new_rot.set_editor_property('roll', x_rot) #X if forward_direction[0] == 'Z': x_rot = unreal.MathLibrary.deg_atan(new_pos.y / new_pos.z) y_rot = unreal.MathLibrary.deg_atan(new_pos.x / new_pos.z) * -1.0 new_rot.set_editor_property('roll', x_rot) #X new_rot.set_editor_property('pitch', y_rot) #Y # Set the new rotation on the joint rtg_controller.set_rotation_offset_for_retarget_pose_bone(target_bone, new_rot.quaternion(), unreal.RetargetSourceOrTarget.TARGET) # Single Axis Bends (Elbow, Knee, etc) for chain in ['LeftArm', 'RightArm', 'LeftLeg', 'RightLeg']: source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain) source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain) target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain) target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain) target_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone) source_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone) single_axis_bend(target_bone, source_bone) # Dual Axis Bends (Elbow, Knee, etc) for chain in ['LeftArm', 'RightArm', 'LeftLeg', 'RightLeg']: source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain) source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain) target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain) target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain) # Get the joint (elbow, knee) target_joint_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone) source_joint_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone) # Got one deeper (hand, foot) target_end_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_joint_bone, target_end_bone) source_end_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_joint_bone, source_end_bone) dual_axis_target_bend(target_start_bone, source_start_bone, target_end_bone, source_end_bone) # Single Axis Chains (fingers) for chain in ['RightThumb', 'RightIndex', 'RightMiddle', 'RightRing', 'RightPinky', 'LeftThumb', 'LeftIndex', 'LeftMiddle', 'LeftRing', 'LeftPinky']: source_start_bone = source_ikr_controller.get_retarget_chain_start_bone(chain) source_end_bone = source_ikr_controller.get_retarget_chain_end_bone(chain) target_start_bone = target_ikr_controller.get_retarget_chain_start_bone(chain) target_end_bone = target_ikr_controller.get_retarget_chain_end_bone(chain) while target_start_bone and source_start_bone and target_start_bone != target_end_bone and source_start_bone != source_end_bone: target_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(target_skeleton, target_start_bone, target_end_bone) source_bone = unreal.DazToUnrealBlueprintUtils.get_next_bone(source_skeleton, source_start_bone, source_end_bone) single_axis_bend(target_bone, source_bone) target_start_bone = target_bone source_start_bone = source_bone
import unreal import re import os from collections import deque # ----------------------------------------------------------------------------- # 스크립트 설정 및 전역 변수 # ----------------------------------------------------------------------------- # 파일 유형 약어 매핑: 필요에 따라 이 사전을 수정하거나 확장하세요. ASSET_TYPE_MAPPING = { "Texture2D": "T", "TextureCube": "TC", "TextureRenderTarget2D": "TRT", "Material": "M", "MaterialInstanceConstant": "MI", "MaterialFunction": "MF", "MaterialParameterCollection": "MPC", "StaticMesh": "SM", "SkeletalMesh": "SK", "AnimSequence": "AS", "AnimMontage": "AM", "BlendSpace": "BS", "AnimBlueprint": "ABP", "Skeleton": "SKEL", "Blueprint": "BP", "DataTable": "DT", "UserDefinedEnum": "ENUM", "UserDefinedStruct": "STRUCT", "LevelSequence": "SEQ", "NiagaraSystem": "NS", "NiagaraEmitter": "NE", "StaticMeshActor": "SMA", "SkeletalMeshActor": "SKA", "Level": "MAP", "World": "MAP" } # 작업 경로의 고유 식별자 (이 경로가 포함된 에셋을 이동시킴) WORKSPACE_IDENTIFIER = "/A_Cinematic_Workspace/" # 빌드 포함 경로의 기본 경로 COOK_PATH_BASE = "/project/" class CinematicAssetSanitizer: """ 시네마틱 에셋 참조 및 네이밍 규칙을 자동으로 수정하는 메인 클래스 """ def __init__(self, error_handling_policy): self.logs = [] self.stop_on_error = (error_handling_policy == "Stop on first error") self.asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() # EditorAssetLibrary 대신 EditorAssetSubsystem을 사용합니다. # 서브시스템은 상태를 가지므로 복잡한 에셋 작업에 더 안정적입니다. self.editor_asset_subsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) def log(self, message, level="info"): """로그를 기록하고 언리얼 로그에 출력하는 함수""" # 언리얼 로그에 먼저 출력 (레벨에 따라 다른 함수 사용) if level == "warning": unreal.log_warning(message) elif level == "error": unreal.log_error(message) else: # info, success 등 unreal.log(message) # UI 리포트용 로그 저장 (접두사 포함) prefix_map = {"info": "[INFO]", "warning": "[WARNING]", "error": "[ERROR]", "success": "[SUCCESS]"} prefix = prefix_map.get(level.lower(), "[INFO]") log_message = f"{prefix} {message}" self.logs.append(log_message) def svn_checkout_files(self, asset_paths): """ 지정된 에셋 경로에 해당하는 파일들을 SVN에서 체크아웃(Lock)하는 함수. EditorAssetSubsystem.checkout_asset API를 사용합니다. """ self.log(f"SVN Checking out {len(asset_paths)} asset(s) using EditorAssetSubsystem...") all_succeeded = True for asset_path in asset_paths: # checkout_asset은 에셋이 존재하지 않거나 다른 이유로 실패하면 False를 반환합니다. if not self.editor_asset_subsystem.does_asset_exist(asset_path): self.log(f"Asset to checkout does not exist, skipping: {asset_path}", "warning") continue # 존재하지 않는 에셋은 체크아웃을 시도하지 않음 # EditorAssetSubsystem.checkout_asset를 직접 호출하여 체크아웃을 시도합니다. success = self.editor_asset_subsystem.checkout_asset(asset_path) if success: self.log(f" - Checkout successful for: {asset_path}", "success") else: self.log(f" - Checkout FAILED for: {asset_path}", "error") all_succeeded = False return all_succeeded def _get_all_workspace_dependencies(self, initial_asset_paths): """ 초기 에셋 목록에서 시작하여 작업 공간 내의 모든 재귀적 의존성을 찾습니다. """ self.log(f"Finding all dependencies for {len(initial_asset_paths)} initial asset(s)...") # 의존성 검색을 위한 옵션. 패키지 의존성만 검색합니다. # 'include_manage_references'는 이전 버전의 API와 호환되지 않을 수 있으므로 제거합니다. dependency_options = unreal.AssetRegistryDependencyOptions( include_soft_package_references=True, include_hard_package_references=True, include_searchable_names=False ) assets_to_scan = deque(initial_asset_paths) all_dependencies = set(initial_asset_paths) scanned_assets = set() # 이미 스캔한 에셋을 추적하여 중복 작업을 피함 self.log(f"Starting dependency scan loop. Initial queue size: {len(assets_to_scan)}") loop_iteration = 0 while assets_to_scan: loop_iteration += 1 if loop_iteration > 5000: # 매우 많은 수의 에셋을 대비해 안전장치 강화 self.log(f"Dependency scan loop exceeded 5000 iterations. Aborting. This might indicate a circular dependency or an extremely large number of assets. Total assets found so far: {len(all_dependencies)}", "error") break asset_path = assets_to_scan.popleft() if asset_path in scanned_assets: continue self.log(f"[DepScan {loop_iteration}] Scanning: {os.path.basename(asset_path)} (Queue size: {len(assets_to_scan)})") scanned_assets.add(asset_path) try: # get_dependencies는 FName 배열을 반환하므로 문자열로 변환해야 합니다. self.log(f" -> Querying dependencies for {os.path.basename(asset_path)}...") dependencies = self.asset_registry.get_dependencies(asset_path, dependency_options) self.log(f" -> Query finished. Found {len(dependencies) if dependencies else 0} dependencies.") if not dependencies: continue for dep_path_name in dependencies: dep_path = str(dep_path_name) # 작업 공간 내에 있고 아직 목록에 없는 에셋만 추가합니다. if WORKSPACE_IDENTIFIER in dep_path and dep_path not in all_dependencies: all_dependencies.add(dep_path) assets_to_scan.append(dep_path) self.log(f" - Added to queue: {os.path.basename(dep_path)}", "info") except Exception as e: self.log(f"Could not get dependencies for {asset_path}: {e}", "warning") self.log(f"Dependency scan finished. Found a total of {len(all_dependencies)} assets to process (including dependencies).", "success") return all_dependencies def parse_cook_log(self, cook_log_text): """Cook 로그 텍스트를 파싱하여 (소스, 타겟) 쌍의 리스트를 반환""" self.log("Parsing cook log...") pattern = re.compile( r"Source package: (.*?)\s*\n\s*Target package: (.*?)\s*\n", re.MULTILINE ) matches = pattern.findall(cook_log_text) if not matches: self.log("No valid 'Source package' -> 'Target package' references found in the log.", "warning") return [] self.log(f"Found {len(matches)} problematic references.", "success") return list(set(matches)) # 중복 제거 def _process_single_asset(self, asset_path_to_process, all_paths_in_workspace): """ 한 개의 에셋에 대해 이동 및 이름 변경 작업을 수행합니다. 성공 시 (생성된 리디렉터 경로 set, None)을 반환합니다. 참조 문제로 실패 시 (None, 블로킹 에셋 경로)를 반환합니다. """ new_redirectors = set() self.log(f"--------------------------------------------------") self.log(f"Processing asset: {os.path.basename(asset_path_to_process)}") # 0. 수정 전, AssetData에서 미리 클래스 정보를 가져옵니다. # rename 후 불안정한 상태에서 load_asset을 호출하는 것을 피하기 위함입니다. asset_data = self.editor_asset_subsystem.find_asset_data(asset_path_to_process) if not asset_data.is_valid(): self.log(f"Could not find valid asset data for {asset_path_to_process}. Skipping this asset.", "warning") return None, None # 치명적이지 않은 오류로 간주하고 건너뜁니다. # asset_class_path.get_asset_name() 대신 더 안정적인 asset_class 속성을 직접 사용합니다. asset_class = str(asset_data.asset_class) try: # 원자적 연산을 위해 전체 프로세스를 하나의 트랜잭션으로 묶습니다. # 이렇게 하면 rename 도중 다른 시스템이 반응하여 발생하는 크래시를 방지할 수 있습니다. with unreal.ScopedEditorTransaction(f"Sanitize Asset: {os.path.basename(asset_path_to_process)}") as trans: # 1. 에셋 이동 new_path_after_move = asset_path_to_process.replace(WORKSPACE_IDENTIFIER, "/Cinematic/") # 경로에 'BackUp' 폴더가 포함되어 있으면 제거합니다. if "/BackUp/" in new_path_after_move: self.log(f"Path contains 'BackUp' folder. Adjusting destination path...") path_parts = new_path_after_move.split('/') filtered_parts = [part for part in path_parts if part != "BackUp"] new_path_after_move = "/".join(filtered_parts) self.log(f" -> New adjusted path: {new_path_after_move}") # 목적지에 에셋이 이미 있다면 백업합니다. if self.editor_asset_subsystem.does_asset_exist(new_path_after_move): self.log(f"Asset already exists at destination: {new_path_after_move}", "warning") backup_dir = os.path.dirname(new_path_after_move) + "/_Backup" backup_path = os.path.join(backup_dir, os.path.basename(new_path_after_move)) self.log(f"Attempting to back up existing asset to: {backup_path}") if not self.svn_checkout_files([new_path_after_move]): raise Exception(f"Failed to SVN checkout existing asset for backup: {new_path_after_move}") self.editor_asset_subsystem.rename_asset(new_path_after_move, backup_path) self.log(f"Backup successful.", "success") self.log(f"Moving asset: {asset_path_to_process} -> {new_path_after_move}") if not self.svn_checkout_files([asset_path_to_process]): raise Exception(f"Failed to SVN checkout target asset for move: {asset_path_to_process}") rename_success = self.editor_asset_subsystem.rename_asset(asset_path_to_process, new_path_after_move) if not rename_success: # 이동 실패 시, 참조하고 있는 에셋을 찾아 반환합니다. referencers = self.editor_asset_subsystem.find_package_referencers_for_asset(asset_path_to_process) for ref_name in referencers: ref = str(ref_name) # 작업 공간 내의 에셋이면서, 아직 처리 목록에 없는 경우 if WORKSPACE_IDENTIFIER in ref and ref in all_paths_in_workspace: self.log(f"Asset move failed. Found blocking reference: {os.path.basename(ref)}", "warning") # 트랜잭션이 진행 중이므로 예외를 발생시켜 롤백되도록 유도하고, 블로커를 반환합니다. # 하지만 여기서는 블로커를 직접 반환하여 상위 루프에서 처리하도록 합니다. return None, ref # 블로커 반환 raise Exception("Asset move failed for an unknown reason (no workspace referencers found).") self.log(f"Move successful.", "success") new_redirectors.add(asset_path_to_process) # 2. 에셋 이름 변경 (이동된 새 경로 기준) type_abbr = ASSET_TYPE_MAPPING.get(asset_class, None) asset_name = os.path.basename(new_path_after_move) if type_abbr and not asset_name.startswith(f"CN_{type_abbr}_"): new_name_base = f"CN_{type_abbr}_{asset_name}" if asset_name.startswith("CN_"): new_name_base = f"CN_{type_abbr}_{asset_name[3:]}" final_name_path = os.path.join(os.path.dirname(new_path_after_move), new_name_base) self.log(f"Applying naming convention: {asset_name} -> {new_name_base}") self.editor_asset_subsystem.rename_asset(new_path_after_move, final_name_path) self.log(f"Rename successful.", "success") new_redirectors.add(new_path_after_move) except Exception as e: # 트랜잭션은 예외 발생 시 자동으로 롤백됩니다. self.log(f"An error occurred during asset processing '{os.path.basename(asset_path_to_process)}': {e}", "error") if self.stop_on_error: raise return None, None # 치명적이지 않은 오류는 건너뜁니다. return new_redirectors, None def run(self, cook_log): """메인 실행 함수""" # 1. 쿡 로그에서 초기 작업 대상 에셋을 수집합니다. self.log("Parsing cook log to find initial assets...") initial_assets = set() fix_list = self.parse_cook_log(cook_log) if not fix_list: return self.logs for _, target_path in fix_list: if WORKSPACE_IDENTIFIER in target_path and self.editor_asset_subsystem.does_asset_exist(target_path): initial_assets.add(target_path) if not initial_assets: self.log("No existing assets from the cook log are located in the workspace.", "info") return self.logs # 2. 초기 에셋의 모든 작업 공간 내 의존성을 재귀적으로 찾습니다. all_assets_in_scope = self._get_all_workspace_dependencies(initial_assets) if not all_assets_in_scope: self.log("Could not identify any assets to process.", "warning") return self.logs # 3. 재귀적 의존성 해결 및 에셋 처리 루프 assets_to_process = list(all_assets_in_scope) processed_assets = set() redirectors_to_fix = set() # 최대 재시도 횟수를 전체 에셋 수에 비례하여 설정 max_retries = len(assets_to_process) * len(assets_to_process) + 20 with unreal.ScopedSlowTask(len(assets_to_process), "Processing Cinematic Assets...") as slow_task: slow_task.make_dialog(True) while assets_to_process and max_retries > 0: max_retries -= 1 asset_path = assets_to_process.pop(0) # 큐의 맨 앞에서 하나를 꺼냅니다. if asset_path in processed_assets: continue # 이미 성공적으로 처리된 에셋은 건너뜁니다. # slow_task의 전체 단계 수를 동적으로 업데이트하는 로직을 제거하고, 메시지만 업데이트합니다. slow_task.enter_progress_frame(1, f"Processing [{len(processed_assets) + 1}/{len(all_assets_in_scope)}]: {os.path.basename(asset_path)}") try: # 전체 에셋 목록을 `_process_single_asset`에 전달합니다. new_redirectors, blocker = self._process_single_asset(asset_path, all_assets_in_scope) if blocker: # 처리 실패, 블로커를 맨 앞에 두고 현재 에셋을 맨 뒤에 다시 추가 self.log(f"Re-queuing {os.path.basename(blocker)} to be processed first.", "info") assets_to_process.insert(0, blocker) assets_to_process.append(asset_path) # 현재 실패한 에셋은 나중에 다시 시도 # all_assets_in_scope는 이미 모든 의존성을 포함하므로 업데이트할 필요가 없습니다. elif new_redirectors is not None: # 처리 성공 processed_assets.add(asset_path) redirectors_to_fix.update(new_redirectors) # new_redirectors가 None이면 치명적이지 않은 오류로 간주하고 그냥 넘어감 (건너뜀) except Exception: # _process_single_asset에서 예외가 발생하면 루프를 중단합니다. import traceback self.log(f"A critical error occurred while processing '{os.path.basename(asset_path)}'. See traceback below.", "error") self.log(traceback.format_exc(), "error") self.log("Stopping all processing.", "error") break if max_retries <= 0: self.log("Max retries exceeded. There might be a circular dependency or unresolvable issue.", "error") self.log(f"Unprocessed assets: {[os.path.basename(p) for p in assets_to_process]}", "error") # 4. 모든 작업 완료 후, 수동 리디렉터 정리 안내 if redirectors_to_fix: self.log("======== MANUAL ACTION REQUIRED ========", "warning") folder_paths = set(os.path.dirname(path) for path in redirectors_to_fix) self.log("Redirector fix-up could not be performed automatically.", "warning") self.log("Please fix them manually by right-clicking the following folder(s) in the Content Browser and choosing 'Fix Up Redirectors in Folder':", "warning") for folder in sorted(list(folder_paths)): self.log(f" -> {folder}", "warning") self.log("======== PROCESSING COMPLETE ========", "info") return self.logs # ============================================================================= # 이 아래 함수를 에디터 유틸리티 위젯의 버튼 OnClicked 이벤트에 연결합니다. # ============================================================================= # 블루프린트와 연동하기 위한 전역 변수. # 이 스크립트가 실행된 후, 블루프린트의 'Execute Python Script' 노드는 # 'report'라는 이름의 출력 핀에서 이 변수의 값을 읽을 수 있습니다. report = "" def run_sanitizer_from_ui(cook_log_text, error_policy): """ UI로부터 호출될 엔트리 포인트 함수. 처리 결과는 전역 변수 'report'에 저장되며, 값으로도 반환됩니다. :param cook_log_text: UI의 텍스트 박스에 있는 쿡 로그 :param error_policy: "Stop on first error" 또는 "Skip errors and continue" :return: 처리 결과 로그 문자열 """ global report sanitizer = CinematicAssetSanitizer(error_policy) # TypeError 수정을 위해 UI에서 받은 Text 객체를 string으로 변환합니다. logs = sanitizer.run(str(cook_log_text)) report = "\n".join(logs) return report # 블루프린트의 'Execute Python Script' 노드는 이 스크립트 파일을 실행합니다. # 노드의 입력 핀 'cook_log_text'와 'error_policy'는 이 스크립트의 전역 변수가 됩니다. # run_sanitizer_from_ui 함수를 호출하여 로깅 작업을 수행한 후, # 그 결과를 'report' 전역 변수에 저장합니다. # 노드는 실행 후 이 'report' 변수의 값을 읽어 'report' 출력 핀으로 전달합니다. report = run_sanitizer_from_ui(cook_log_text, error_policy)
import unreal import os GITIGNORE_PATH = unreal.Paths.project_dir() + "/.gitignore" def add_to_gitignore(file_name): if not os.path.exists(GITIGNORE_PATH): with open(GITIGNORE_PATH, "w") as gitignore: gitignore.write(file_name + "\n") else: with open(GITIGNORE_PATH, "r+") as gitignore: lines = gitignore.readlines() if file_name not in [line.strip() for line in lines]: gitignore.write("\n" + file_name + "\n") # Example usage if __name__ == "__main__": add_to_gitignore("test.json")
# Copyright (c) 2023 Max Planck Society # License: https://bedlam.is.tuebingen.mpg.de/license.html # # Import HDR images into Unreal Engine # import fnmatch import os import time import unreal data_root = r"/project/" data_root_unreal = "/project/" def import_textures(data_root, data_root_unreal): unreal.log('Importing data: ' + data_root) import_texture_paths = [] for root, dirnames, filenames in os.walk(data_root): for filename in fnmatch.filter(filenames, '*.hdr'): import_texture_paths.append((root, filename)) import_tasks = [] for import_texture_dir, import_texture_name in import_texture_paths: import_texture_path = os.path.join(import_texture_dir, import_texture_name) # Check if texture is already imported texture_name = import_texture_name.replace(".hdr", "") texture_dir = import_texture_dir.replace(data_root, "").replace("\\", "/").lstrip("/") texture_dir = "%s/%s" % (data_root_unreal, texture_dir) texture_path = "%s/%s" % (texture_dir, texture_name) if unreal.EditorAssetLibrary.does_asset_exist(texture_path): unreal.log(" Already imported: " + texture_path) else: unreal.log(" Importing: " + texture_path) task = unreal.AssetImportTask() task.set_editor_property("filename", import_texture_path) task.set_editor_property("destination_path", texture_dir) task.set_editor_property('save', True) # Import one HDR at a time and save all imported assets immediately to avoid data loss on Unreal Editor crash import_tasks = [task] unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(import_tasks) unreal.EditorAssetLibrary.save_directory(data_root_unreal) # save imported data return ###################################################################### # Main ###################################################################### if __name__ == '__main__': unreal.log("============================================================") unreal.log("Running: %s" % __file__) # Import HDR as texture cube into Unreal start_time = time.perf_counter() import_textures(data_root, data_root_unreal) print(f"HDR batch import finished. Total import time: {(time.perf_counter() - start_time):.1f}s")
# -*- coding: utf-8 -*- import unreal from ayon_core.pipeline import CreatorError from ayon_core.hosts.unreal.api.pipeline import ( create_folder ) from ayon_core.hosts.unreal.api.plugin import ( UnrealAssetCreator ) from ayon_core.lib import UILabelDef class CreateLook(UnrealAssetCreator): """Shader connections defining shape look.""" identifier = "io.ayon.creators.unreal.look" label = "Look" product_type = "look" icon = "paint-brush" def create(self, product_name, instance_data, pre_create_data): # We need to set this to True for the parent class to work pre_create_data["use_selection"] = True sel_objects = unreal.EditorUtilityLibrary.get_selected_assets() selection = [a.get_path_name() for a in sel_objects] if len(selection) != 1: raise CreatorError("Please select only one asset.") selected_asset = selection[0] look_directory = "/project/" # Create the folder folder_name = create_folder(look_directory, product_name) path = f"{look_directory}/{folder_name}" instance_data["look"] = path # Create a new cube static mesh ar = unreal.AssetRegistryHelpers.get_asset_registry() cube = ar.get_asset_by_object_path("/project/.Cube") # Get the mesh of the selected object original_mesh = ar.get_asset_by_object_path(selected_asset).get_asset() materials = original_mesh.get_editor_property('static_materials') pre_create_data["members"] = [] # Add the materials to the cube for material in materials: mat_name = material.get_editor_property('material_slot_name') object_path = f"{path}/{mat_name}.{mat_name}" unreal_object = unreal.EditorAssetLibrary.duplicate_loaded_asset( cube.get_asset(), object_path ) # Remove the default material of the cube object unreal_object.get_editor_property('static_materials').pop() unreal_object.add_material( material.get_editor_property('material_interface')) pre_create_data["members"].append(object_path) unreal.EditorAssetLibrary.save_asset(object_path) super(CreateLook, self).create( product_name, instance_data, pre_create_data) def get_pre_create_attr_defs(self): return [ UILabelDef("Select the asset from which to create the look.") ]
# 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
""" Global thread tracker for UEMCP This module persists across reloads to track all server threads """ # import threading import unreal # Global storage that persists across module reloads _all_server_threads = [] _all_httpd_servers = [] def add_server_thread(thread): """Add a server thread to track""" _all_server_threads.append(thread) # Clean up dead threads _all_server_threads[:] = [t for t in _all_server_threads if t.is_alive()] def add_httpd_server(httpd): """Add an httpd server to track""" _all_httpd_servers.append(httpd) def cleanup_all(): """Clean up all tracked threads and servers""" global _all_server_threads unreal.log(f"UEMCP: Cleaning up {len(_all_server_threads)} threads and {len(_all_httpd_servers)} servers") # Force close all server sockets for httpd in _all_httpd_servers: try: # Close the socket immediately if hasattr(httpd, "socket"): httpd.socket.close() httpd.server_close() except Exception: pass # Clear the list _all_httpd_servers.clear() # Don't wait for threads - they'll die when sockets close dead_threads = [] for thread in _all_server_threads: if not thread.is_alive(): dead_threads.append(thread) # Only keep alive threads (should be none after socket close) _all_server_threads = [t for t in _all_server_threads if t.is_alive()] if _all_server_threads: unreal.log_warning(f"UEMCP: {len(_all_server_threads)} threads still alive after cleanup") unreal.log("UEMCP: Cleanup complete") def track_thread(thread): """Track a thread (alias for add_server_thread)""" add_server_thread(thread) def get_tracked_threads(): """Get all tracked threads""" # Clean up dead threads first _all_server_threads[:] = [t for t in _all_server_threads if t.is_alive()] return _all_server_threads.copy() def clear_threads(): """Clear all tracked threads (alias for cleanup_all)""" cleanup_all()
import unreal # target_path = "/project/" # # target_path = "/project/" # """ # 获取指定路径下的所有 static mesh 资产 # """ # assets = unreal.EditorAssetLibrary.list_assets(target_path, recursive=True, include_folder=False) # static_mesh_assets = unreal.EditorFilterLibrary.by_class(assets, unreal.StaticMesh) # """ # 检查静态网格体的材质插槽,如果为空则新建一个材质插槽 # """ # for static_mesh in static_mesh_assets: # # 获取静态网格体的材质插槽数量 # static_materials = static_mesh.static_materials # if not len(static_materials): # # 创建新的材质插槽并设置材质 # new_material_slot_name = "NewMaterialSlot" # new_material = unreal.EditorAssetLibrary.load_asset(material_path) # static_mesh_editor_subsystem = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) # static_mesh_editor_subsystem.add_material(static_mesh, new_material) # unreal.EditorAssetLibrary.save_asset(static_mesh.get_path_name()) # print(f"成功创建新的材质插槽并设置材质为: /project/") # else: # print(f"静态网格体: {static_mesh.get_name()} 已存在材质插槽,无需创建") # 一键修改当前资产材质 material_path = r'/project/' red_material = unreal.EditorAssetLibrary.load_asset(material_path) selected_assets = unreal.EditorUtilityLibrary.get_selected_assets() static_mesh_assets = unreal.EditorFilterLibrary.by_class(selected_assets, unreal.StaticMesh.static_class()) if static_mesh_assets: for static_mesh_asset in static_mesh_assets: static_materials = static_mesh_asset.static_materials if len(static_materials) == 0: # 新建材质插槽 new_material_slot_name = "NewMaterialSlot" new_material_slot = unreal.StaticMaterial() new_material_slot.material_slot_name = new_material_slot_name # 将新的材质插槽添加到静态网格体中 static_materials.append(new_material_slot) static_mesh_asset.static_materials = static_materials # 保存静态网格体 unreal.EditorAssetLibrary.save_asset(static_mesh_asset.get_path_name()) print(f"成功创建新的材质插槽: {new_material_slot_name}") else: print(f"静态网格体已经存在材质插槽: {static_mesh_asset.get_name()} \t {len(static_materials)}个") for i in range(len(static_materials)): static_mesh_asset.set_material(i, red_material)
# -*- coding: utf-8 -*- import unreal import Utilities.Utils def print_refs(packagePath): print("-" * 70) results, parentsIndex = unreal.PythonBPLib.get_all_refs(packagePath, True) print ("resultsCount: {}".format(len(results))) assert len(results) == len(parentsIndex), "results count not equal parentIndex count" print("{} Referencers Count: {}".format(packagePath, len(results))) def _print_self_and_children(results, parentsIndex, index, gen): if parentsIndex[index] < -1: return print ("{}{}".format("\t" * (gen +1), results[index])) parentsIndex[index] = -2 for j in range(index + 1, len(parentsIndex), 1): if parentsIndex[j] == index: _print_self_and_children(results, parentsIndex, j, gen + 1) for i in range(len(results)): if parentsIndex[i] >= -1: _print_self_and_children(results, parentsIndex, i, 0) def print_deps(packagePath): print("-" * 70) results, parentsIndex = unreal.PythonBPLib.get_all_deps(packagePath, True) print ("resultsCount: {}".format(len(results))) assert len(results) == len(parentsIndex), "results count not equal parentIndex count" print("{} Dependencies Count: {}".format(packagePath, len(results))) def _print_self_and_children(results, parentsIndex, index, gen): if parentsIndex[index] < -1: return print ("{}{}".format("\t" * (gen +1), results[index])) parentsIndex[index] = -2 for j in range(index + 1, len(parentsIndex), 1): if parentsIndex[j] == index: _print_self_and_children(results, parentsIndex, j, gen + 1) for i in range(len(results)): if parentsIndex[i] >= -1: _print_self_and_children(results, parentsIndex, i, 0) def print_related(packagePath): print_deps(packagePath) print_refs(packagePath) def print_selected_assets_refs(): assets = Utilities.Utils.get_selected_assets() for asset in assets: print_refs(asset.get_outermost().get_path_name()) def print_selected_assets_deps(): assets = Utilities.Utils.get_selected_assets() for asset in assets: print_deps(asset.get_outermost().get_path_name()) def print_selected_assets_related(): assets = Utilities.Utils.get_selected_assets() for asset in assets: print_related(asset.get_outermost().get_path_name()) def print_who_used_custom_depth(): world = unreal.EditorLevelLibrary.get_editor_world() allActors = unreal.GameplayStatics.get_all_actors_of_class(world, unreal.Actor) print(len(allActors)) errorCount = 0 for actor in allActors: comps = actor.get_components_by_class(unreal.PrimitiveComponent) for comp in comps: if comp.render_custom_depth: errorCount += 1 # v = comp.get_editor_property("custom_depth_stencil_value") # m = comp.get_editor_property("custom_depth_stencil_write_mask") print("actor: {} comp: {} enabled Custom depth ".format(actor.get_name(), comp.get_name())) # errorCount += 1 print("Custom Depth comps: {}".format(errorCount))
import unreal def tryCast(): if unreal.Texture2D.cast(unreal.load_asset('/project/')): print('Texture2D Cast Succeeded') else: print('Texture2D Cast Failed') if unreal.Actor.cast(unreal.load_asset('/project/')): print('Actor Cast Succeeded') else: print('Actor Cast Failed') def cast(obj, cls): try: return cls.cast(obj) except Exception as ex: print(ex.message)
# -*- 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())
import unreal test_dir = '/project/' assetSubsystem = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) # Create a test directory in Game if assetSubsystem.does_directory_exist(test_dir): assetSubsystem.delete_directory(test_dir) assetSubsystem.make_directory(test_dir) def basic_material(name='test_mat', path='/Game', color = {'r': 1.000000,'g': 1.000000,'b': 1.000000,'a': 0} ): ''' Create a material with a Constant 3 Vector to the base color input arg: name = str, material name path = str, asset library path where the material will be located color = dict, color vector ''' assetTools = unreal.AssetToolsHelpers.get_asset_tools() material = assetTools.create_asset(asset_name=name, package_path=path, asset_class=unreal.Material, factory=unreal.MaterialFactoryNew()) loaded_yellow = assetSubsystem.load_asset('{}/{}'.format(path, name)) constant_3vector = unreal.MaterialEditingLibrary.create_material_expression(material, unreal.MaterialExpressionConstant3Vector) constant_3vector.set_editor_property('constant', color) unreal.MaterialEditingLibrary.connect_material_property(constant_3vector, "", unreal.MaterialProperty.MP_BASE_COLOR) unreal.MaterialEditingLibrary.layout_material_expressions(material) unreal.MaterialEditingLibrary.recompile_material(material) basic_material ( name = 'yellow', path = test_dir, color = {'r': 1.000000,'g': 1.000000,'b': 0.000000,'a': 0} )
import json import unreal from .component import mgComponent from .rig import mgRig from .colour import MAYA_LOOKUP """ This container handles all the mGear component data that will be used to deserialise the `*.scd` file. """ def load_json_file(file_path: str): """ Load a JSON file using the json module. """ with open(file_path, 'r') as file: data = json.load(file) return data def convert_json_to_mg_rig(build_json_path: str) -> mgRig: """ Converts the mGear build json file into a mgRig object. This process filters out all none required data. """ data = load_json_file(build_json_path) rig = mgRig() # Dumps the entire MainSettings dictionary into the rig.settings rig.settings = data["MainSettings"] for data_component in data["Components"]: component_type = data_component["Type"] component_side = data_component["Side"] component_name = data_component["Name"] component_fullname = data_component["FullName"] data_contrat = data_component["DataContracts"] joints = data_component["Joints"] controls = data_component["Controls"] guide_transforms = data_component.get("guideTransforms", None) mgear_component = mgComponent() mgear_component.name = component_name mgear_component.side = component_side mgear_component.comp_type = component_type mgear_component.fullname = component_fullname mgear_component.parent_fullname = data_component['parent_fullName'] mgear_component.parent_localname = data_component['parent_localName'] mgear_component.data_contracts = {} mgear_component.joint_relatives = data_component['jointRelatives'] mgear_component.control_relatives = data_component['controlRelatives'] mgear_component.alias_relatives = data_component['aliasRelatives'] mgear_component.settings = data_component['Settings'] # checks if guide transforms exists, as not all components have this attribute. if guide_transforms: # Converts the numeric list matrix into an Unreal Matrix for key, val in guide_transforms.items(): mtx = unreal.Matrix() mtx.x_plane = unreal.Plane(val[0][0], val[0][1], val[0][2], val[0][3]) mtx.y_plane = unreal.Plane(val[1][0], val[1][1], val[1][2], val[1][3]) mtx.z_plane = unreal.Plane(val[2][0], val[2][1], val[2][2], val[2][3]) mtx.w_plane = unreal.Plane(val[3][0], val[3][1], val[3][2], val[3][3]) guide_transforms[key] = mtx mgear_component.guide_transforms = guide_transforms # Stores all the controls associated with this component for ctrl in controls: if mgear_component.controls is None: mgear_component.controls = [] mgear_component.controls_role = {} mgear_component.controls_aabb = {} mgear_component.controls_colour = {} mgear_component.controls.append(ctrl["Name"]) mgear_component.controls_role[ctrl["Name"]] = ctrl["Role"] # Store the RGB Color # ::ASSUMPTION:: A control will all have the same colour shape_category = ctrl["Shape"] for crv_name in shape_category["curves_names"]: crv_color = shape_category[crv_name]["crv_color"] if crv_color is None or crv_color == "null": # There is an edge case where the colour is null mgear_component.controls_colour[ctrl["Name"]] = None elif type(crv_color) == type([]): # There is an edge case where the colour is stored as an RGB value mgear_component.controls_colour[ctrl["Name"]] = crv_color else: mgear_component.controls_colour[ctrl["Name"]] = MAYA_LOOKUP[crv_color] # Calculate control size bounding_box_data = _calculate_bounding_box(ctrl) mgear_component.controls_aabb[ctrl["Name"]] = bounding_box_data # Checks the controls transform data and records it as a Unreal.Transform world_pos = ctrl["WorldPosition"] world_rot = ctrl["QuaternionWorldRotation"] world_pos = [world_pos['x'], world_pos['y'], world_pos['z']] ue_quaternion = unreal.Quat(world_rot[0], world_rot[1], world_rot[2], world_rot[3]) # Setting the transform with a euler instead of quaternion, due to slight difference in how # unreal handles them world_euler = ctrl["WorldRotation"] euler = unreal.Vector(x=world_euler['x'], y=world_euler['y'], z=world_euler['z']) # ue_quaternion.set_from_euler(euler) ue_trans = unreal.Transform() ue_trans.set_editor_property("translation", world_pos) ue_trans.set_editor_property("rotation", ue_quaternion) # Converts from Maya space into Unreal Space ue_trans = _convert_maya_matrix(ue_trans.to_matrix()) if mgear_component.control_transforms is None: mgear_component.control_transforms = {} mgear_component.control_transforms[ctrl["Name"]] = ue_trans # Stores all the joints associated with this component for jnt in joints: if mgear_component.joints is None: mgear_component.joints = [] mgear_component.joints.append(jnt["Name"]) # Stores all the contracts and their related joints for contract_name in data_contrat: related_joints = data_component[contract_name] mgear_component.data_contracts[contract_name] = related_joints rig.add_component(new_component=mgear_component) return rig def _calculate_bounding_box(control_data: dict) -> tuple[list, list]: """ Calculates a bounding box around the control, by evaluating the control points. This bounding box is used to help scale the control rig's control shape. - Shape points are in local space The bounding box will be a centered bounding box, storing the offset position from the center to the corners. This is an Axis Aligned Bounding Box (AABB) :todo: bounding box center needs to be calculated in Maya space, else multiplying it back in unreal causes an issue due to orientation """ min_point, max_point = _calculate_min_max_points(control_data) bb_center, bb_offset = _calculate_bb(min_point, max_point) bb_center = _calculate_maya_bb_center(control_data) return bb_center, bb_offset def _calculate_maya_bb_center(control_data: dict) -> list: """ The center of the bounding box is required to be in Maya space to make multiplying and conversion easier in the control rig build node. """ bb_min = [float('inf')] * 3 bb_max = [float('-inf')] * 3 shape_category = control_data["Shape"] for crv_name in shape_category["curves_names"]: shape_meta_data = shape_category[crv_name]["shapes"] shape_data_list = shape_meta_data.values() for shape_data in shape_data_list: shape_points = shape_data["points"] # Loop over all the points and record the largest and smallest positions for point in shape_points: pos = [round(point[0], 4), round(point[1], 4), round(point[2], 4)] # Finds the largest and smallest value, by comparison for index in range(len(pos)): bb_min[index] = min(bb_min[index], pos[index]) bb_max[index] = max(bb_max[index], pos[index]) # Calculate the center of the bb in Maya coordinates bb_center = [] for i, ii in zip(bb_min, bb_max): center = round((i + ii) / 2, 4) bb_center.append(center) return bb_center def _calculate_min_max_points(control_data: dict): """ Finds the minimum and the maximum points for all the points that exist in the controls dictionary. """ # Initialise the min and max points to be infinity bb_min = [float('inf')] * 3 bb_max = [float('-inf')] * 3 shape_category = control_data["Shape"] for crv_name in shape_category["curves_names"]: shape_meta_data = shape_category[crv_name]["shapes"] shape_data_list = shape_meta_data.values() for shape_data in shape_data_list: shape_points = shape_data["points"] # Loop over all the points and record the largest and smallest positions for point in shape_points: # Converts the Point from maya space into Unreal space, else the bounding box will not align # correctly to the object in Unreal point_mtx = unreal.Matrix.IDENTITY point_mtx.w_plane = point + [1.0] # ue_space_trans = _convert_maya_matrix(point_mtx) ue_space_trans = _convert_maya_shape_matrix(point_mtx) trans = ue_space_trans.translation pos = [round(trans.x, 4), round(trans.y, 4), round(trans.z, 4)] # Finds the largest and smallest value, by comparison for index in range(len(pos)): bb_min[index] = min(bb_min[index], pos[index]) bb_max[index] = max(bb_max[index], pos[index]) return bb_min, bb_max def _calculate_bb(min, max): """ Calculates the center point of the bounding box, and the distance to the corners :param min: smallest value for each axis that exists in the bounding box :param max: largest value for each axis that exists in the bounding box :return: The center of the bounding box, the length to the corner """ bb_offset = [] bb_center = [] for i, ii in zip(min, max): center = round((i + ii) / 2, 4) offset = ii - center bb_offset.append(offset) bb_center.append(center) # Checks no axis is 0 as unreal 5.3 has an issue that is a shape # has an axis of 0 then shape updating does not work. for idx, value in enumerate(bb_offset): if value < 0.001: bb_offset[idx] = 0.01 return bb_center, bb_offset def _convert_maya_matrix(maya_mtx: unreal.Matrix) -> unreal.Transform: # Reorient Matrix # This matrix is used to turn left hand rule into right hand rule plane_x = unreal.Plane(x=1, y=0, z=0, w=0) plane_y = unreal.Plane(x=0, y=0, z=-1, w=0) plane_z = unreal.Plane(x=0, y=1, z=0, w=0) plane_w = unreal.Plane(x=0, y=0, z=0, w=1) reordered_mtx = unreal.Matrix(plane_x, plane_y, plane_z, plane_w) t = unreal.Transform() t_qaut = unreal.Quat() t_qaut.set_from_euler(unreal.Vector(0, 0, 0)) t.rotation = t_qaut rot_mtx = t.to_matrix() plane_x2 = unreal.Plane(x=1, y=0, z=0, w=0) plane_y2 = unreal.Plane(x=0, y=1, z=0, w=0) plane_z2 = unreal.Plane(x=0, y=0, z=-1, w=0) plane_w2 = unreal.Plane(x=0, y=0, z=0, w=1) scale_mtx = unreal.Matrix(plane_x2, plane_y2, plane_z2, plane_w2) # Calculates the new space by multiplying the reorder matrix and # Rotating the new Y rotation by 180 corrected_space_mtx = maya_mtx * reordered_mtx * rot_mtx * scale_mtx corrected_space_trans = corrected_space_mtx.transform() # quat_rotation = corrected_space_mtx.to_quat() # euler_rotation = quat_rotation.euler() # euler_rotation.y = euler_rotation.z + 180 # quat_rotation.set_from_euler(euler_rotation) # corrected_space_trans.rotation = quat_rotation return corrected_space_trans def _convert_maya_shape_matrix(maya_mtx: unreal.Matrix) -> unreal.Transform: # Reorient Matrix # This matrix is used to turn left hand rule into right hand rule plane_x = unreal.Plane(x=1, y=0, z=0, w=0) plane_y = unreal.Plane(x=0, y=0, z=1, w=0) plane_z = unreal.Plane(x=0, y=1, z=0, w=0) plane_w = unreal.Plane(x=0, y=0, z=0, w=1) reordered_mtx = unreal.Matrix(plane_x, plane_y, plane_z, plane_w) # Calculates the new space by multiplying the reorder matrix and # Rotating the new Y rotation by 180 corrected_space_mtx = maya_mtx * reordered_mtx corrected_space_trans = corrected_space_mtx.transform() quat_rotation = corrected_space_mtx.to_quat() euler_rotation = quat_rotation.euler() euler_rotation.y = euler_rotation.y + 180 quat_rotation.set_from_euler(euler_rotation) corrected_space_trans.rotation = quat_rotation return corrected_space_trans
import unreal from Lib import __lib_topaz__ as topaz import importlib importlib.reload(topaz) def set_light_env_tag(selected_actors : list[unreal.Actor] ) -> None: for each in selected_actors: print(each.__class__) if each.__class__ == unreal.Actor: # in case of blueprintActor if ( each.get_class().get_name() == 'Ultra_Dynamic_Sky' or each.get_class().get_name() == 'Ultra_Dynamic_Weather' ): print('Ultra_Dynamic_Weather / Sky') else : has_light : list = topaz.get_component_by_class(each. unreal.RectLight) if has_light.__len__() > 0 : topaz.set_actor_tag_by_class(each, unreal.RectLight, 'Env_Light') print('Blueprint') elif ( each.__class__ == unreal.PointLight or # in case of light each.__class__ == unreal.SpotLight or each.__class__ == unreal.RectLight ): print('Light') elif each.__class__ == unreal.CameraActor : # in case of camera print('Camera') else : print('None') actors = topaz.get_selected_level_actors() set_light_env_tag(actors)
# Copyright (c) 2023 Max Planck Society # License: https://bedlam.is.tuebingen.mpg.de/license.html # # Batch import Alembic .abc files into Unreal Engine # import math import os from pathlib import Path import sys import time import unreal data_root = r"/project/" #whitelist_subjects_path = r"/project/.txt" whitelist_subjects_path = None #whitelist_animations_path = r"/project/.txt" whitelist_animations_path = None data_root_unreal = "/project/" def import_abc(data_root, data_root_unreal, current_batch, num_batches, whitelist_subjects=None, whitelist_animations=None): # Build import list import_abc_paths = sorted(Path(data_root).rglob("*.abc")) if current_batch is not None: section_length = math.ceil(len(import_abc_paths)/num_batches) start_index = current_batch * section_length end_index = start_index + section_length if end_index > len(import_abc_paths): end_index = len(import_abc_paths) print(f"Processing section: {current_batch}, total sections: {num_batches}, range: [{start_index}:{end_index}]") import_abc_paths = import_abc_paths[start_index : end_index] import_tasks = [] for import_abc_path in import_abc_paths: if whitelist_subjects is not None: current_subject_name = import_abc_path.parent.name if current_subject_name not in whitelist_subjects: unreal.log(f"Skipping Alembic. Subject not whitelisted: {import_abc_path}") continue if whitelist_animations is not None: current_animation_name = import_abc_path.stem.split("_")[-1] if current_animation_name not in whitelist_animations: unreal.log(f"Skipping Alembic. Animation not whitelisted: {import_abc_path}") continue unreal.log(f"Processing Alembic: {import_abc_path}") # unreal.log_flush() # Note: does not update editor console log # Check if file is already imported uasset_folder_name = import_abc_path.parent.name uasset_folder = f"{data_root_unreal}/{uasset_folder_name}" uasset_name = import_abc_path.stem uasset_path = f"{uasset_folder}/{uasset_name}" if unreal.EditorAssetLibrary.does_asset_exist(uasset_path): unreal.log(" Skipping import. Already imported: " + uasset_path) else: unreal.log(" Importing: " + uasset_path) options = unreal.AbcImportSettings() options.import_type = unreal.AlembicImportType.GEOMETRY_CACHE # Blender SMPL-X animations are in range [1-n], not [0-n]. Set frame start to 1 to properly import Blender SMPL-X Alembic exports. # # BUG (Unreal 4.27.2): # We have to use default frame_end=0 value since we don't know the exact number of frames for each file when using Python API. # This leads to extra unwanted duplicated end frame in imported sequence. options.sampling_settings = unreal.AbcSamplingSettings(sampling_type=unreal.AlembicSamplingType.PER_FRAME, frame_steps=1, time_steps=0.0, frame_start=1, frame_end=0, skip_empty=False) # Maximum UI quality setting for position precision and texture coordinates, do not calculate motion vectors on import # Note: Strong face ghosting when Alembic was imported with unreal.AbcGeometryCacheMotionVectorsImport.CALCULATE_MOTION_VECTORS_DURING_IMPORT options.geometry_cache_settings = unreal.AbcGeometryCacheSettings(flatten_tracks=True, apply_constant_topology_optimizations=False, motion_vectors=unreal.AbcGeometryCacheMotionVectorsImport.NO_MOTION_VECTORS, optimize_index_buffers=False, compressed_position_precision=0.01, compressed_texture_coordinates_number_of_bits=16) # default: 10 # Source Alembic data exported from Blender [m], apply conversion settings to convert to Unreal [cm] options.conversion_settings = unreal.AbcConversionSettings(preset=unreal.AbcConversionPreset.CUSTOM, flip_u=False, flip_v=True, scale=[100.0, - 100.0, 100.0], rotation=[90.0, 0.0, 0.0]) task = unreal.AssetImportTask() task.set_editor_property("automated", True) task.set_editor_property("filename", str(import_abc_path)) task.set_editor_property("destination_path", uasset_folder) task.set_editor_property("destination_name", "") task.set_editor_property("replace_existing", True) task.set_editor_property("save", True) task.set_editor_property("options", options) # Import one FBX at a time and save all imported assets immediately to avoid data loss on Unreal Editor crash import_tasks = [task] unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(import_tasks) unreal.EditorAssetLibrary.save_directory(data_root_unreal) # save imported materials and textures ###################################################################### # Main ###################################################################### if __name__ == "__main__": unreal.log("============================================================") unreal.log("Running: %s" % __file__) current_batch = None num_batches = None if len(sys.argv) == 3: current_batch = int(sys.argv[1]) num_batches = int(sys.argv[2]) whitelist_subjects = None if whitelist_subjects_path is not None: with open(whitelist_subjects_path) as f: whitelist_subjects = f.read().splitlines() whitelist_animations = None if whitelist_animations_path is not None: with open(whitelist_animations_path) as f: whitelist_animations = f.read().splitlines() # Import all Alembic files start_time = time.perf_counter() import_abc(data_root, data_root_unreal, current_batch, num_batches, whitelist_subjects, whitelist_animations) print(f"Alembic batch import finished. Total import time: {(time.perf_counter() - start_time):.1f}s")
import os import xml.etree.ElementTree as ET from collections import defaultdict import ce_path_utils from typing import List class Texture: def __init__(self): self.Filter = None self.IsTileU = None self.Map = None self.IsTileV = None self.File = None self.TileU = 1.0 self.TileV = 1.0 def __repr__(self): return f"Texture(Map={self.Map}, File={self.File})" class Material: def __init__(self, name) -> None: self.name = name # Material attributes self.Emittance = None self.VoxelCoverage = None self.FurAmount = None self.Emissive = None self.CloakAmount = None self.Opacity = None self.StringGenMask = None self.GlowAmount = None self.vertModifType = None self.MtlFlags = None self.Shininess = None self.Diffuse = None self.HeatAmountScaled = None self.Shader = None self.CustomSortPriority = None self.MatTemplate = None self.SurfaceType = None self.Specular = None self.AlphaTest = None self.GenMask = None self.LayerAct = None # PublicParams attributes self.WeaponBloodColor = None self.WeaponQualityZone2 = None self.MaskSaturation3 = None self.FresnelPower = None self.FresnelScale = None self.DirOverlayX = None self.DecalFalloff = None self.DetailDiffuseScale = None self.RandomValueOffset = None self.BlendLayer2Specular = None self.ColorizingHue = None self.SelfShadowStrength = None self.WeaponBloodSpecular = None self.ObmDisplacement = None self.AmbientMultiplier = None self.MaskBrightness2 = None self.RandomValueScale = None self.WeaponQualityZone0 = None self.TessellationFactorMin = None self.WeaponQualityZone5 = None self.FresnelBias = None self.BlendMaskTiling = None self.WeaponBloodBlendFactor = None self.ColorizingSaturation = None self.WeaponBloodBlendFalloff = None self.OverlayDetailR = None self.OverlayDetailG = None self.BackFaceBrightnessMult = None self.HeightBias = None self.DirOverlayThresholdMin = None self.WeaponBloodGloss = None self.BlendFactor = None self.MaskBrightness3 = None self.DecalAlphaMult = None self.OverlayTiling = None self.GlossFromDiffuseOffset = None self.DirOverlayTilingU = None self.SubsurfaceScatteringAmount = None self.EmittanceMapGamma = None self.SndUVsTileV = None self.IndirectColor = None self.SSSIndex = None self.WeaponQualityZone6 = None self.WeaponBloodTexScale = None self.WeaponQualityZone4 = None self.MaskSaturation1 = None self.GlossFromDiffuseContrast = None self.MaskHue2 = None self.DirOverlayThresholdMax = None self.ColorizingBrightness = None self.GlossFromDiffuseBrightness = None self.MaskBrightness1 = None self.MaskHue1 = None self.GlossFromDiffuseAmount = None self.BlendLayer2Tiling = None self.DirOverlayTilingV = None self.WeaponQualityZone7 = None self.SndUVsTileU = None self.WeaponRustBlendFalloff = None self.TessellationFaceCull = None self.BlendFalloff = None self.DirOverlayZ = None self.MaskSaturation2 = None self.WeaponQualityZone1 = None self.NumTexParts = None self.WeaponRustTexScale = None self.DetailGlossScale = None self.DirOverlayBumpScale = None self.TessellationFactor = None self.DecalDiffuseOpacity = None self.DebugUVScale = None self.PomDisplacement = None self.TessellationFactorMax = None self.WeaponQualityZone3 = None self.WeaponRustBlendFactor = None self.WeaponRustBlend = None self.MaskHue3 = None self.OverlayDetailB = None self.DirOverlayY = None self.DetailBumpScale = None # Textures self.textures = [] def get_enabled_switches(self): enabled_switches = self.StringGenMask.split('%') if self.StringGenMask else [] if len(enabled_switches) > 1: enabled_switches.remove('') # Remove empty strings return enabled_switches def __repr__(self): return f"Material(name={self.name}, textures={self.textures})" def parse_mtl_file(file_path) -> List[Material]: import xml.etree.ElementTree as ET materials = [] try: tree = ET.parse(file_path) root = tree.getroot() sub_node = root.find(".//SubMaterials") # If <SubMaterials> not found, check if root is <Material> if sub_node is None: if root.tag == "Material": material_elems = [root] else: print(f"SubMaterials not found and root is not Material in {file_path}") return materials else: material_elems = sub_node.findall("Material") for material_elem in material_elems: mat_name = material_elem.attrib.get("Name", "") if not mat_name: mat_name = os.path.splitext(os.path.basename(file_path))[0] mat = Material(mat_name.replace(".", "_")) # Set Material attributes for k, v in material_elem.attrib.items(): if hasattr(mat, k): setattr(mat, k, v) # Parse <Textures> textures_elem = material_elem.find("Textures") if textures_elem is not None: for tex_elem in textures_elem.findall("Texture"): tex = Texture() for k, v in tex_elem.attrib.items(): if hasattr(tex, k): setattr(tex, k, v) texmod_elem = tex_elem.find("TexMod") if texmod_elem is not None: tex.TileU = float(texmod_elem.attrib.get("TileU", 1.0)) tex.TileV = float(texmod_elem.attrib.get("TileV", 1.0)) mat.textures.append(tex) # Parse <PublicParams> public_params_elem = material_elem.find("PublicParams") if public_params_elem is not None: for k, v in public_params_elem.attrib.items(): if hasattr(mat, k): setattr(mat, k, v) materials.append(mat) except ET.ParseError as e: print(f"Error parsing {file_path}: {e}") return materials def collect_unique_attributes(directory): # Dictionary to store unique attributes for each element type unique_attributes = defaultdict(set) # Recursively iterate through all files in the directory and subdirectories for root_dir, _, files in os.walk(directory): for filename in files: if filename.endswith(".mtl"): file_path = os.path.join(root_dir, filename) print(file_path) try: # Parse the XML file tree = ET.parse(file_path) root = tree.getroot() # Collect attributes for each element type sub_node = root.find(".//SubMaterials") if sub_node is None: print(f"SubMaterials not found in {file_path}") continue for material in sub_node.findall("Material"): shader_type = material.attrib.get("Shader") if shader_type != "Illum": print(f"ShaderType{shader_type} is not Illum in {file_path}") continue unique_attributes["Material"].update(material.attrib.keys()) for child in material: unique_attributes[child.tag].update(child.attrib.keys()) for subchild in child: unique_attributes[subchild.tag].update(subchild.attrib.keys()) except ET.ParseError as e: print(f"Error parsing {file_path}: {e}") return unique_attributes # # Get the results and print them # unique_attributes = collect_unique_attributes(ce_path_utils.CRY_ENGINE_OUTPUT_FOLDER_ROOT) # print(unique_attributes) # for element_type, attributes in unique_attributes.items(): # print(f"{element_type}: {', '.join(attributes)}") def find_material_by_name(materials, name): # First try exact match for mat in materials: if mat.name == name: return mat # If no exact match, try to find by decrementing trailing numbers import re # Pattern to match trailing numbers (e.g., "_03", "_02_decals1") pattern = r'(.+?)(\d+)(_.*)?$' match = re.match(pattern, name) if match: base_name = match.group(1) # Everything before the number number = int(match.group(2)) # The number suffix = match.group(3) or "" # Everything after the number (if any) # Try decrementing the number until we find a match or reach 0 for i in range(number - 1, 0, -1): # For cases like "stone_wall_03" -> "stone_wall_02" candidate_name = f"{base_name}{i:02d}{suffix}" for mat in materials: if mat.name == candidate_name: return mat # Also try without zero-padding for single digits if i < 10: candidate_name = f"{base_name}{i}{suffix}" for mat in materials: if mat.name == candidate_name: return mat # Special case for suffix numbers like "_decals1" -> "_decals" if suffix and re.match(r'_.*\d+$', suffix): # Remove trailing digit from suffix suffix_no_digit = re.sub(r'\d+$', '', suffix) candidate_name = f"{base_name}{number:02d}{suffix_no_digit}" for mat in materials: if mat.name == candidate_name: return mat # Also try with original number decremented for i in range(number - 1, 0, -1): candidate_name = f"{base_name}{i:02d}{suffix_no_digit}" for mat in materials: if mat.name == candidate_name: return mat return None def find_texture_by_path(mat_data, texture_name, is_gloss=False): texture_path = None for tex in mat_data.textures: if tex.Map == texture_name: texture_path = tex.File break if not texture_path: print(f"Texture {texture_name} not found in material {mat_data.name}") return None texture_path = texture_path.replace('.tif', '') texture_path = texture_path.replace('.dds', '') texture_path = f"/project/{texture_path}" if is_gloss: texture_path += "_glossmap" import unreal if unreal.EditorAssetLibrary.does_asset_exist(texture_path): return unreal.EditorAssetLibrary.load_asset(texture_path) else: unreal.log_warning(f"Texture asset not found: {texture_path}") return None def get_texture_tiling(mat_data, texture_name): for tex in mat_data.textures: if tex.Map == texture_name: return (tex.TileU, tex.TileV) return (1.0, 1.0) # Default tiling if not found def str_to_vec3(s): parts = s.split(',') if len(parts) == 3: return [float(part.strip()) for part in parts] return [0.0, 0.0, 0.0] # Default if parsing fails def create_material_instance(material_data: Material, target_path, mesh_name, parent_material_path, cached_instance): import unreal parent_material = unreal.EditorAssetLibrary.load_asset(parent_material_path) target_package_name = f"{target_path}/mtl_{mesh_name}_{material_data.name}" material_instance = None if unreal.EditorAssetLibrary.does_asset_exist(target_package_name): material_instance = unreal.EditorAssetLibrary.load_asset(target_package_name) if material_instance in cached_instance: print(f"Material instance {target_package_name} already exists in cache, skipping creation.") return material_instance unreal.EditorAssetLibrary.delete_asset(target_package_name) # material_instance = unreal.EditorAssetLibrary.load_asset(target_package_name) # Create the material instance asset_tools = unreal.AssetToolsHelpers.get_asset_tools() factory = unreal.MaterialInstanceConstantFactoryNew() material_instance = asset_tools.create_asset( asset_name=f"mtl_{mesh_name}_{material_data.name}", package_path=target_path, asset_class=unreal.MaterialInstanceConstant, factory=factory ) if material_instance: material_instance.set_editor_property("parent", parent_material) return material_instance def create_material_instance_illum(material_data: Material, target_path, mesh_name, cached_instance): import unreal material_instance = create_material_instance( material_data, target_path, mesh_name, "/project/", cached_instance) if material_instance: # set material properties mat_edit_lib = unreal.MaterialEditingLibrary diffuse_tex = find_texture_by_path(material_data, "Diffuse") if diffuse_tex: if material_data.AlphaTest and float(material_data.AlphaTest) > 0.0: diffuse_tex_data = unreal.EditorAssetLibrary.find_asset_data(diffuse_tex.get_path_name()) has_alpha = diffuse_tex_data.get_tag_value("HasAlphaChannel") if has_alpha == "True": print(f"Material {material_data.name} has alpha channel in Diffuse texture, setting blend mode to Masked.") overide_prop = material_instance.get_editor_property("base_property_overrides") overide_prop.set_editor_property("override_blend_mode", True) overide_prop.set_editor_property("blend_mode", unreal.BlendMode.BLEND_MASKED) overide_prop.set_editor_property("override_opacity_mask_clip_value", True) overide_prop.set_editor_property("opacity_mask_clip_value", float(material_data.AlphaTest)) material_instance.set_editor_property("base_property_overrides", overide_prop) mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Diffuse", diffuse_tex) bump_tex = find_texture_by_path(material_data, "Bumpmap") if bump_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Bumpmap", bump_tex) gloss_tex = find_texture_by_path(material_data, "Bumpmap", is_gloss=True) if gloss_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Bumpmap Gloss", gloss_tex) specular_tex = find_texture_by_path(material_data, "Specular") if specular_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Specular", specular_tex) if material_data.Diffuse: mat_edit_lib.set_material_instance_vector_parameter_value( material_instance, "MatDiffuse", str_to_vec3(material_data.Diffuse)) if material_data.Specular: mat_edit_lib.set_material_instance_vector_parameter_value( material_instance, "MatSpecular", str_to_vec3(material_data.Specular)) enabled_switches = material_data.get_enabled_switches() if "BLENDLAYER" in enabled_switches: mat_edit_lib.set_material_instance_static_switch_parameter_value( material_instance, "BLENDLAYER", True) if material_data.BlendFactor: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "BlendFactor", float(material_data.BlendFactor)) if material_data.BlendMaskTiling: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "BlendMaskTiling", float(material_data.BlendMaskTiling)) if material_data.BlendFalloff: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "BlendFalloff", float(material_data.BlendFalloff)) if material_data.BlendLayer2Tiling: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "BlendLayer2Tiling", float(material_data.BlendLayer2Tiling)) if material_data.BlendLayer2Specular: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "BlendLayer2Specular", float(material_data.BlendLayer2Specular)) custom_tex = find_texture_by_path(material_data, "Custom") if custom_tex: mat_edit_lib.set_material_instance_texture_parameter_value( material_instance, "Custom", custom_tex) custom_1_tex = find_texture_by_path(material_data, "[1] Custom") if custom_1_tex: mat_edit_lib.set_material_instance_texture_parameter_value( material_instance, "[1] Custom", custom_1_tex) custom_1_gloss_tex = find_texture_by_path(material_data, "[1] Custom", is_gloss=True) if custom_1_gloss_tex: mat_edit_lib.set_material_instance_texture_parameter_value( material_instance, "[1] Custom Gloss", custom_1_gloss_tex) opacity_tex = find_texture_by_path(material_data, "Opacity") if opacity_tex: mat_edit_lib.set_material_instance_texture_parameter_value( material_instance, "Opacity", opacity_tex) if "DETAIL_MAPPING" in enabled_switches: mat_edit_lib.set_material_instance_static_switch_parameter_value( material_instance, "DETAIL_MAPPING", True) detail_tex = find_texture_by_path(material_data, "Detail") if detail_tex: mat_edit_lib.set_material_instance_texture_parameter_value( material_instance, "Detail", detail_tex) if "DETAIL_ATLAS" in enabled_switches: mat_edit_lib.set_material_instance_static_switch_parameter_value( material_instance, "DETAIL_ATLAS", True) mat_edit_lib.set_material_instance_static_switch_parameter_value( material_instance, "DETAIL_MAPPING", True) detail_atlas_tex = find_texture_by_path(material_data, "Detail") mat_edit_lib.set_material_instance_texture_parameter_value( material_instance, "DetailMask", detail_atlas_tex) if "DETAIL_ATLAS" in enabled_switches or "DETAIL_MAPPING" in enabled_switches: if material_data.DetailDiffuseScale: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "DetailDiffuseScale", float(material_data.DetailDiffuseScale)) if material_data.DetailGlossScale: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "DetailGlossScale", float(material_data.DetailGlossScale)) if material_data.DetailBumpScale: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "DetailBumpScale", float(material_data.DetailBumpScale)) tile_u, tile_v = get_texture_tiling(material_data, "Detail") mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "Detail Tile U", float(tile_u)) mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "Detail Tile V", float(tile_v)) if "USE_FIRST_UV_DETMAP" in enabled_switches: mat_edit_lib.set_material_instance_static_switch_parameter_value( material_instance, "USE_FIRST_UV_DETMAP", True) if "SNDUVS" in enabled_switches: mat_edit_lib.set_material_instance_static_switch_parameter_value( material_instance, "SNDUVS", True) snd_uvs_tex = find_texture_by_path(material_data, "[1] Diffuse") if snd_uvs_tex: mat_edit_lib.set_material_instance_texture_parameter_value( material_instance, "[1] Diffuse", snd_uvs_tex) if material_data.SndUVsTileU: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "SndUVsTileU", float(material_data.SndUVsTileU)) if material_data.SndUVsTileV: mat_edit_lib.set_material_instance_scalar_parameter_value( material_instance, "SndUVsTileV", float(material_data.SndUVsTileV)) unreal.EditorAssetLibrary.save_loaded_asset(material_instance) return material_instance return None def create_material_instance_vegetation(material_data: Material, target_path, mesh_name, cached_instance): import unreal PARENT_MATERIAL_PATH = "/project/" material_instance = create_material_instance( material_data, target_path, mesh_name, PARENT_MATERIAL_PATH, cached_instance) if material_instance: # set material properties mat_edit_lib = unreal.MaterialEditingLibrary diffuse_tex = find_texture_by_path(material_data, "Diffuse") if diffuse_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Diffuse", diffuse_tex) bump_tex = find_texture_by_path(material_data, "Bumpmap") if bump_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Bumpmap", bump_tex) gloss_tex = find_texture_by_path(material_data, "Bumpmap", is_gloss=True) if gloss_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Bumpmap Gloss", gloss_tex) if material_data.Diffuse: mat_edit_lib.set_material_instance_vector_parameter_value( material_instance, "MatDiffuse", str_to_vec3(material_data.Diffuse)) opacity_tex = find_texture_by_path(material_data, "Opacity") if opacity_tex: mat_edit_lib.set_material_instance_texture_parameter_value( material_instance, "Opacity", opacity_tex) unreal.EditorAssetLibrary.save_loaded_asset(material_instance) return material_instance return None def create_material_instance_glass(material_data: Material, target_path, mesh_name, cached_instance): import unreal PARENT_MATERIAL_PATH = "/project/" material_instance = create_material_instance( material_data, target_path, mesh_name, PARENT_MATERIAL_PATH, cached_instance) if material_instance: # set material properties mat_edit_lib = unreal.MaterialEditingLibrary diffuse_tex = find_texture_by_path(material_data, "Diffuse") if diffuse_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Diffuse", diffuse_tex) bump_tex = find_texture_by_path(material_data, "Bumpmap") if bump_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Bumpmap", bump_tex) gloss_tex = find_texture_by_path(material_data, "Bumpmap", is_gloss=True) if gloss_tex: mat_edit_lib.set_material_instance_texture_parameter_value(material_instance, "Bumpmap Gloss", gloss_tex) if material_data.Diffuse: mat_edit_lib.set_material_instance_vector_parameter_value( material_instance, "MatDiffuse", str_to_vec3(material_data.Diffuse)) if material_data.Specular: mat_edit_lib.set_material_instance_vector_parameter_value( material_instance, "MatSpecular", str_to_vec3(material_data.Specular)) unreal.EditorAssetLibrary.save_loaded_asset(material_instance) return material_instance return None def create_and_assign_mat_to_mesh(mesh_data): import unreal static_mesh = unreal.EditorAssetLibrary.load_asset(mesh_data.package_name) mesh_path = str(mesh_data.package_path) name = str(mesh_data.asset_name) source_folder = os.path.join(ce_path_utils.CRY_ENGINE_OUTPUT_FOLDER_ROOT, mesh_path.replace('/project/', '')) if os.path.exists(source_folder): has_transparency = False cached_instance = [] for mat_slot in static_mesh.static_materials: mat_slot_name = str(mat_slot.material_slot_name) parts = [] if '_mtl__' in mat_slot_name: parts = mat_slot_name.split('_mtl__') elif '_mtl_' in mat_slot_name: parts = mat_slot_name.split('_mtl_') if len(parts) != 2: unreal.log_warning(f"Material slot name {mat_slot_name} does not match expected format, skipping.") continue mtl_file_name = parts[0] mat_name = parts[1] target_mat = os.path.join(source_folder, mtl_file_name + ".mtl") materials = None if os.path.exists(target_mat): materials = parse_mtl_file(target_mat) else: root_folder = ce_path_utils.CRY_ENGINE_OUTPUT_FOLDER_ROOT found_mtl_files = [] for dirpath, dirnames, filenames in os.walk(root_folder): for f in filenames: if f.endswith('.mtl'): found_mtl_files.append(os.path.join(dirpath, f)) for mtl_file in found_mtl_files: # get file name without extension mtl_name = os.path.splitext(os.path.basename(mtl_file))[0] if mtl_name == mtl_file_name: target_mat = mtl_file materials = parse_mtl_file(target_mat) break if materials: mat_data = find_material_by_name(materials, mat_name) if mat_data: material_instance = None if mat_data.Shader == "Illum": material_instance = create_material_instance_illum(mat_data, mesh_path, mesh_data.asset_name, cached_instance) elif mat_data.Shader == "Vegetation": material_instance = create_material_instance_vegetation(mat_data, mesh_path, mesh_data.asset_name, cached_instance) elif mat_data.Shader == "Glass": material_instance = create_material_instance_glass(mat_data, mesh_path, mesh_data.asset_name, cached_instance) has_transparency = True else: unreal.log_warning(f"Material {mat_data.name} is not Illum/Vege, skipping.") continue if material_instance: mat_slot.material_interface = material_instance static_mesh.set_material(static_mesh.get_material_index(mat_slot.material_slot_name), material_instance) cached_instance.append(material_instance) else: unreal.log_warning(f"Material file not found: {target_mat}") if has_transparency: sm_edit_sub = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) nanite_setting = sm_edit_sub.get_nanite_settings(static_mesh) nanite_setting.set_editor_property('enabled', False) sm_edit_sub.set_nanite_settings(static_mesh, nanite_setting, True) unreal.EditorAssetLibrary.save_loaded_asset(static_mesh) def create_and_assign_mat_to_selected_meshes(): import unreal editor_util_lib = unreal.EditorUtilityLibrary selected_assets = editor_util_lib.get_selected_asset_data() with unreal.ScopedSlowTask(len(selected_assets), "Importing Materials..") as slow_task: # display the dialog slow_task.make_dialog(True) for selected_asset in selected_assets: if slow_task.should_cancel(): break slow_task.enter_progress_frame(1, "Importing Materials For {}".format(selected_asset.asset_name)) create_and_assign_mat_to_mesh(selected_asset) if __name__ == "__main__": create_and_assign_mat_to_selected_meshes()
import unreal import argparse import json def get_scriptstruct_by_node_name(node_name): control_rig_blueprint = unreal.load_object(None, '/project/') rig_vm_graph = control_rig_blueprint.get_model() nodes = rig_vm_graph.get_nodes() for node in nodes: if node.get_node_path() == node_name: return node.get_script_struct() parser = argparse.ArgumentParser(description = 'Creates a Control Rig given a SkeletalMesh') parser.add_argument('--skeletalMesh', help='Skeletal Mesh to Use') parser.add_argument('--animBlueprint', help='Anim Blueprint that contains the Control Rig Node') parser.add_argument('--dtuFile', help='DTU File to use') args = parser.parse_args() # Create the Control Rig asset_name = args.skeletalMesh.split('.')[1] + '_JCM_CR' package_path = args.skeletalMesh.rsplit('/', 1)[0] blueprint = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=asset_name, package_path=package_path, asset_class=unreal.ControlRigBlueprint, factory=unreal.ControlRigBlueprintFactory()) skeletal_mesh = unreal.load_object(name = args.skeletalMesh, outer = None) unreal.ControlRigBlueprintLibrary.set_preview_mesh(blueprint, skeletal_mesh) # Check if this is a forward or right facing model skeletal_mesh_import_data = skeletal_mesh.get_editor_property('asset_import_data') skeletal_mesh_force_front_x = skeletal_mesh_import_data.get_editor_property('force_front_x_axis') # Turn off notifications or each change will compile the RigVM blueprint.suspend_notifications(True) rig_controller = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() morph_target_names = skeletal_mesh.get_all_morph_target_names() progress = unreal.ScopedSlowTask(len(morph_target_names), "Adding Morphs to JCM Control Rig") progress.make_dialog() anim_blueprint = unreal.load_object(name = args.animBlueprint, outer = None) for graph in anim_blueprint.get_animation_graphs(): if graph.get_fname() == 'AnimGraph': for graph_node in graph.get_graph_nodes_of_class(unreal.AnimGraphNode_ControlRig, True): anim_node = graph_node.get_editor_property('node') anim_node.set_editor_property('control_rig_class', blueprint.generated_class()) unreal.BlueprintEditorLibrary.compile_blueprint(anim_blueprint) # Setup the JCM Control Rig hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() hierarchy_controller.import_bones_from_asset(args.skeletalMesh, 'None', False, False, True) hierarchy_controller.import_curves_from_asset(args.skeletalMesh, 'None', False) rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_BeginExecution', 'Execute', unreal.Vector2D(-97.954082, -704.318460), 'BeginExecution') # Get Bone list for character dtu_data = json.load(open(args.dtuFile.replace('\"', ''))) joint_links = dtu_data['JointLinks'] joint_axis_list = {} for joint_link in joint_links: joint_link_bone_name = joint_link['Bone'] daz_axis = joint_link['Axis'] joint_link_axis = daz_axis if not joint_link_axis in ['XRotate', 'YRotate', 'ZRotate']: continue # Adjust the axis if right facing (front X) if skeletal_mesh_force_front_x: if daz_axis == 'XRotate': joint_link_axis = 'YRotate' if daz_axis == 'YRotate': joint_link_axis = 'ZRotate' if daz_axis == 'ZRotate': joint_link_axis = 'XRotate' if not joint_link_bone_name in joint_axis_list.keys(): joint_axis_list[joint_link_bone_name] = [] joint_axis_list[joint_link_bone_name].append(joint_link_axis) # Go through once to get all axis for secondary axis purposes node_height = 0 node_spacing = 250 execute_from = 'BeginExecution.ExecuteContext' for joint_link in joint_links: joint_link_bone_name = joint_link['Bone'] #if not 'forearm' in joint_link_bone_name: continue #if not ('Thigh' in joint_link_bone_name or 'Shin' in joint_link_bone_name): continue joint_link_morph = joint_link['Morph'] joint_link_scalar = joint_link['Scalar'] joint_link_alpha = joint_link['Alpha'] link_name = joint_link_bone_name + '_' + joint_link_morph # Match Axis for Unreal daz_axis = joint_link['Axis'] joint_link_primary_axis = daz_axis if not joint_link_primary_axis in ['XRotate', 'YRotate', 'ZRotate']: continue # Adjust the axis if right facing (front X) if skeletal_mesh_force_front_x: if daz_axis == 'XRotate': joint_link_primary_axis = 'YRotate' if daz_axis == 'YRotate': joint_link_primary_axis = 'ZRotate' if daz_axis == 'ZRotate': joint_link_primary_axis = 'XRotate' if joint_link_primary_axis in ['XRotate', 'ZRotate']: joint_link_scalar = joint_link_scalar * -1.0 joint_min = 0.0 if joint_link_scalar != 0.0: joint_max = 1.0 / joint_link_scalar else: joint_max = 90.0 # Choose secondary axis joint_link_secondary_axis = None for axis in joint_axis_list[joint_link_bone_name]: if axis != joint_link_primary_axis: joint_link_secondary_axis = axis break joint_link_keys = [] rotation_direction = 0 if 'Keys' in joint_link.keys(): for joint_link_key in joint_link['Keys']: key_data = {} key_data["Angle"] = joint_link_key['Angle'] key_data["Value"] = joint_link_key['Value'] joint_link_keys.append(key_data) if len(joint_link_keys) == 0 and joint_link_scalar > 0.0: rotation_direction = 1.0 if len(joint_link_keys) == 0 and joint_link_scalar < 0.0: rotation_direction = -1.0 for key_data in joint_link_keys: if key_data['Angle'] > 0.0: rotation_direction = 1.0 if key_data['Angle'] < 0.0: rotation_direction = -1.0 if joint_link_primary_axis in ['XRotate', 'ZRotate']: rotation_direction = rotation_direction * -1.0 angles = [ abs(item['Angle']) for item in joint_link_keys ] angles.sort() joint_max = angles[-1] * rotation_direction joint_min = angles[-2] * rotation_direction rotation_order = 'ZYX' if joint_link_primary_axis == 'YRotate': rotation_order = 'ZXY' if joint_link_secondary_axis: if joint_link_primary_axis == 'XRotate' and joint_link_secondary_axis == 'YRotate': rotation_order = 'YZX' if joint_link_primary_axis == 'XRotate' and joint_link_secondary_axis == 'ZRotate': rotation_order = 'ZYX' if joint_link_primary_axis == 'YRotate' and joint_link_secondary_axis == 'XRotate': rotation_order = 'XZY' if joint_link_primary_axis == 'YRotate' and joint_link_secondary_axis == 'ZRotate': rotation_order = 'ZXY' if joint_link_primary_axis == 'ZRotate' and joint_link_secondary_axis == 'XRotate': rotation_order = 'XYZ' if joint_link_primary_axis == 'ZRotate' and joint_link_secondary_axis == 'YRotate': rotation_order = 'YXZ' joint_max = joint_max * float(joint_link_alpha) joint_min = joint_min * float(joint_link_alpha) joint_link_morphs_to_process = [joint_link_morph] if joint_link_morph + '_dq2lb' in morph_target_names: joint_link_morphs_to_process.append(joint_link_morph + '_dq2lb') for morph_to_process in joint_link_morphs_to_process: progress.enter_progress_frame() link_name = joint_link_bone_name + '_' + morph_to_process # Set Curve Value node_name = 'Set_' + link_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_SetCurveValue', 'Execute', unreal.Vector2D(1130.0, node_height), node_name) rig_controller.set_pin_default_value(node_name + '.Curve', morph_to_process, False) # Get Transform get_initial_transform_node_name = 'GetInitialTransform_' + link_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-250.0, node_height), get_initial_transform_node_name) rig_controller.set_pin_default_value(get_initial_transform_node_name + '.Item', '(Type=Bone)', False, False) rig_controller.set_pin_expansion(get_initial_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_initial_transform_node_name + '.Space', 'LocalSpace', False, False) rig_controller.set_pin_default_value(get_initial_transform_node_name + '.Item.Name', joint_link_bone_name, False, False) rig_controller.set_pin_default_value(get_initial_transform_node_name + '.Item.Type', 'Bone', False, False) rig_controller.set_pin_default_value(get_initial_transform_node_name + '.bInitial', 'true', False, False) get_transform_node_name = 'GetTransform_' + link_name rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(-500.0, node_height), get_transform_node_name) rig_controller.set_pin_default_value(get_transform_node_name + '.Item', '(Type=Bone)', False, False) rig_controller.set_pin_expansion(get_transform_node_name + '.Item', True) rig_controller.set_pin_default_value(get_transform_node_name + '.Space', 'LocalSpace', False, False) rig_controller.set_pin_default_value(get_transform_node_name + '.Item.Name', joint_link_bone_name, False, False) rig_controller.set_pin_default_value(get_transform_node_name + '.Item.Type', 'Bone', False, False) make_relative_node_name = 'MakeRelative_' + link_name try: rig_controller.add_template_node('Make Relative::Execute(in Global,in Parent,out Local)', unreal.Vector2D(-50.0, node_height), make_relative_node_name) except: make_relative_scriptstruct = get_scriptstruct_by_node_name("MathTransformMakeRelative") rig_controller.add_unit_node(make_relative_scriptstruct, 'Execute', unreal.Vector2D(-50.0, node_height), make_relative_node_name) rig_controller.add_link(get_initial_transform_node_name + '.Transform', make_relative_node_name + '.Parent') rig_controller.add_link(get_transform_node_name + '.Transform', make_relative_node_name + '.Global') # To Euler to_euler_node_name = 'To_Euler_' + link_name #rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_MathQuaternionToEuler', 'Execute', unreal.Vector2D(276.703686, node_height), to_euler_node_name) rig_controller.add_unit_node_from_struct_path('/project/.RigVMFunction_MathQuaternionToEuler', 'Execute', unreal.Vector2D(276.0, node_height), to_euler_node_name) rig_controller.set_pin_default_value(to_euler_node_name + '.Value', '(X=0.000000,Y=0.000000,Z=0.000000,W=1.000000)', False, False) rig_controller.set_pin_expansion(to_euler_node_name + '.Value', False, False) rig_controller.set_pin_default_value(to_euler_node_name + '.RotationOrder', rotation_order, False, False) rig_controller.set_pin_expansion(to_euler_node_name + '.Result', False, False) rig_controller.add_link(make_relative_node_name +'.Local.Rotation', to_euler_node_name + '.Value') #rig_controller.add_link(get_transform_node_name + '.Transform.Rotation', to_euler_node_name + '.Value') # Remap remap_node_name = 'Remap_' + link_name try: rig_controller.add_template_node('Remap::Execute(in Value,in SourceMinimum,in SourceMaximum,in TargetMinimum,in TargetMaximum,in bClamp,out Result)', unreal.Vector2D(759.666641, node_height), remap_node_name) #rig_controller.add_template_node('Remap::Execute(in Value,in SourceMinimum,in SourceMaximum,in TargetMinimum,in TargetMaximum,in bClamp,out Result)', unreal.Vector2D(473.000031, 415.845032), 'Remap') except: remap_script_struct = get_scriptstruct_by_node_name("MathFloatRemap") rig_controller.add_unit_node(remap_script_struct, 'Execute', unreal.Vector2D(759.666641, node_height), remap_node_name) #print(to_euler_node_name + '.Result.' + joint_link_primary_axis[0], remap_node_name +'.Value') rig_controller.add_link(to_euler_node_name + '.Result.' + joint_link_primary_axis[0], remap_node_name +'.Value') rig_controller.set_pin_default_value(remap_node_name +'.SourceMinimum', str(joint_min), False, False) rig_controller.set_pin_default_value(remap_node_name +'.SourceMaximum', str(joint_max), False, False) rig_controller.set_pin_default_value(remap_node_name +'.bClamp', 'true', False, False) #rig_controller.set_pin_default_value(remap_node_name +'.bClamp', 'true', False) rig_controller.add_link(remap_node_name +'.Result', node_name + '.Value') # Link to Previous rig_controller.add_link(execute_from, node_name + '.ExecuteContext') execute_from = node_name + '.ExecuteContext' node_height += node_spacing blueprint.suspend_notifications(False) unreal.ControlRigBlueprintLibrary.recompile_vm(blueprint)