text
stringlengths
15
267k
# SPDX-FileCopyrightText: 2018-2025 Xavier Loux (BleuRaven) # # SPDX-License-Identifier: GPL-3.0-or-later # ---------------------------------------------- # Blender For UnrealEngine # https://github.com/project/-For-UnrealEngine-Addons # ---------------------------------------------- import unreal def set_sequence_preview_skeletal_mesh(asset: unreal.AnimSequence, origin_skeletal_mesh): if origin_skeletal_mesh: if asset: # @TODO preview_pose_asset doesn’t retarget right now. Need wait update in Unreal Engine Python API. asset.get_editor_property('preview_pose_asset') pass
import unreal # type: ignore import os, datetime, json #Floor Data - ID, details inputed manually #Room - ID, Floor ID, Position from Map, Main Panorama #PanoPoint - ID, Room ID, Images | World Coordinates, Height #Marker - From Pano, To Pano | World Coordinates?( Coordinates of To Pano for now) import tkinter as tk from tkinter import filedialog # Initialize Tkinter root root = tk.Tk() root.withdraw() # Hide the root window folder_path = filedialog.askdirectory(title="Select the folder containing panorama data") print(f"Selected folder: {folder_path}") les = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) all_actors = unreal.EditorLevelLibrary.get_all_level_actors() floor_bp, room_bp, pano_point_bp = [unreal.load_asset("/project/"+blueprint_name).generated_class() for blueprint_name in ["BP_Floor", "BP_Room", "BP_PanoPoint"]] def getActorsOfClass(bp): return enumerate(sorted([actor for actor in all_actors if actor.get_class() == bp],key = lambda a: a.get_actor_label())) def getActorEditorProperty(a,prop: str): try: return a.get_editor_property(prop) except: return None def print_dict(d,tabs=1): for k,v in d.items(): print("\t"*tabs, k," : ",v) print("_"*20) p_data = {} for i, pano in getActorsOfClass(pano_point_bp): p_data[les.get_current_level().get_name().split("/")[-1]+"_"+pano.get_actor_label()] = getActorEditorProperty(pano, "PanoIdentifier") print("_"*20) print("_"*20) with open(os.path.join(folder_path,"pano.json"), "w") as f: json.dump(p_data, f, indent=4) #with open("/project/.json", "w") as f: # json.dump({"floors": floor_json, "rooms": room_json, "panoramas": pano_json, "markers": marker_json}, f, indent=4)
# 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 json from enum import Enum, auto import inspect from typing import Callable, Union from concurrent.futures import ThreadPoolExecutor, Future from threading import Lock import logging import unreal logger = logging.getLogger(__name__) class FuncType(Enum): STATIC_METHOD = auto() CLASS_METHOD = auto() LAMBDA = auto() UNBOUND_METHOD = auto() INSTANCE_METHOD = auto() INSTANCE_METHOD_OF_CLASS = auto() STATIC_FUNCTION = auto() BUILTIN = auto() UNKNOWN = auto() def get_func_type(callback: callable, cls=None) -> FuncType: if isinstance(callback, staticmethod): return FuncType.STATIC_METHOD if not callable(callback): raise ValueError("callback must be a callable object") if cls: for _, obj in cls.__dict__.items(): if obj is callback: if isinstance(obj, staticmethod): return FuncType.STATIC_METHOD elif isinstance(obj, classmethod): return FuncType.CLASS_METHOD break elif isinstance(callback, staticmethod): return FuncType.STATIC_METHOD if hasattr(callback, "__name__") and callback.__name__ == "<lambda>": return FuncType.LAMBDA if inspect.ismethod(callback): if callback.__self__ is None: return FuncType.UNBOUND_METHOD elif isinstance(callback.__self__, type): return FuncType.CLASS_METHOD else: return FuncType.INSTANCE_METHOD if inspect.isfunction(callback): params_names = list(inspect.signature(callback).parameters.keys()) if params_names and params_names[0] == "self": return FuncType.INSTANCE_METHOD_OF_CLASS return FuncType.STATIC_FUNCTION if inspect.isbuiltin(callback): return FuncType.BUILTIN return FuncType.UNKNOWN class ChameleonTaskExecutor: """ ChameleonTaskExecutor is a class for managing and executing tasks in parallel. It uses a ThreadPoolExecutor to run tasks concurrently. """ def __init__(self, owner): """ Initialize the ChameleonTaskExecutor with the owner of the tasks. """ assert isinstance(owner.data, unreal.ChameleonData) self.owner = owner self.executor = ThreadPoolExecutor() self.futures_dict = {} self.lock = Lock() @staticmethod def _find_var_name_in_outer(target_var, by_type:bool=False)->str: frames = inspect.getouterframes(inspect.currentframe()) top_frame = frames[-1] instance_name_in_global = "" for k, v in top_frame.frame.f_globals.items(): if by_type: if isinstance(v, target_var): # print(f"!! found: {k} @ frame: frame count: {len(frames)}") instance_name_in_global = k break if type(v) == target_var: # print(f"!! found: {k} @ frame: frame count: {len(frames)}") instance_name_in_global = k break else: if v == target_var: # print(f"!! found: {k} @ frame: frame count: {len(frames)}") instance_name_in_global = k break return instance_name_in_global @staticmethod def _number_of_param(callback)->int: try: if isinstance(callback, str): param_str = callback[callback.find("("): callback.find(")") + 1].strip() return param_str[1:-1].find(",") else: sig = inspect.signature(callback) param_count = len(sig.parameters) return param_count except Exception as e: print(e) return 0 @staticmethod def _get_balanced_bracket_code(content, file_name, lineno): def _is_brackets_balanced(content): v = 0 for c in content: if c == "(": v += 1 elif c == ")": v -= 1 return v == 0 if "(" in content and _is_brackets_balanced(content): return content try: with open(file_name, 'r', encoding="utf-8") as f: lines = f.readlines() line = "" for i in range(lineno-1, len(lines)): line += lines[i].strip() if "(" in line and _is_brackets_balanced(line): return line except Exception as e: raise RuntimeError(f"Failed to process file {file_name} line {lineno} : {e}") return None @staticmethod def get_cmd_str_from_callable(callback: Union[callable, str]) -> str: """Get the command string from a callable object. The command string is used to call the callable object""" if isinstance(callback, str): return callback callback_type = get_func_type(callback) if callback_type == FuncType.BUILTIN: return "{}(%)".format(callback.__qualname__) elif callback_type == FuncType.LAMBDA: raise ValueError("Lambda function is not supported") else: frames = inspect.getouterframes(inspect.currentframe()) last_callable_frame_idx = -1 for i, frame in enumerate(frames): for var_name, var_value in frame.frame.f_locals.items(): if callable(var_value) and hasattr(var_value, "__code__"): if var_value.__code__ == callback.__code__: last_callable_frame_idx = i # The upper frame of the last callable frame is the frame that contains the callback, # so we can get the code context of the callback from the upper frame upper_frame = frames[last_callable_frame_idx + 1] if len(frames) > last_callable_frame_idx + 1 else None code_context = "".join(upper_frame.code_context) code_line = ChameleonTaskExecutor._get_balanced_bracket_code(code_context, upper_frame.filename, upper_frame.lineno) callback_params = code_line[code_line.index("(") + 1: code_line.rfind(")")].split(",") callback_param = "" for param in callback_params: if callback.__name__ in param: callback_param = param if "=" not in param else param[param.index('=')+1:] break if callback_param: # found if callback_type == FuncType.INSTANCE_METHOD or callback_param.startswith("self."): instance_name = ChameleonTaskExecutor._find_var_name_in_outer(upper_frame.frame.f_locals["self"]) cmd = f"{instance_name}.{callback_param[callback_param.index('.') + 1:]}(%)" else: cmd = f"{callback_param}(%)" return cmd return f"{callback.__qualname__}(%)" def submit_task(self, task:Callable, args=None, kwargs=None, on_finish_callback: Union[Callable, str] = None)-> int: """ Submit a task to be executed. The task should be a callable object. Args and kwargs are optional arguments to the task. Callback is an optional function to be called when the task is done. """ if args is None: args = [] if kwargs is None: kwargs = {} future = self.executor.submit(task, *args, **kwargs) assert future is not None, "future is None" future_id = id(future) with self.lock: self.futures_dict[future_id] = future cmd = ChameleonTaskExecutor.get_cmd_str_from_callable(on_finish_callback) param_count = ChameleonTaskExecutor._number_of_param(on_finish_callback) cmd = cmd.replace("%", str(future_id) if param_count else "") def _func(_future): unreal.PythonBPLib.exec_python_command(cmd, force_game_thread=True) future.add_done_callback(_func) unreal.log(f"submit_task callback cmd: {cmd}, param_count: {param_count}") return future_id def get_future(self, future_id)-> Future: with self.lock: return self.futures_dict.get(future_id, None) def get_task_is_running(self, future_id)-> bool: future = self.get_future(future_id) if future is not None: return future.running() return False def is_any_task_running(self): for future_id in self.futures_dict.keys(): if self.get_task_is_running(future_id): return True return False
# -*- 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))
# 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 spawns some actors and then uses the API to instantiate an HDA and set the actors as world inputs. The inputs are set during post instantiation (before the first cook). After the first cook and output creation (post processing) the input structure is fetched and logged. """ import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.subnet_test_2_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def get_geo_asset_path(): return '/project/.Cube' def get_geo_asset(): return unreal.load_object(None, get_geo_asset_path()) def get_cylinder_asset_path(): return '/project/.Cylinder' def get_cylinder_asset(): return unreal.load_object(None, get_cylinder_asset_path()) def configure_inputs(in_wrapper): print('configure_inputs') # Unbind from the delegate in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs) # Spawn some actors actors = spawn_actors() # Create a world input world_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIWorldInput) # Set the input objects/assets for this input world_input.set_input_objects(actors) # copy the input data to the HDA as node input 0 in_wrapper.set_input_at_index(0, world_input) # We can now discard the API input object world_input = None # Set the subnet_test HDA to output its first input in_wrapper.set_int_parameter_value('enable_geo', 1) def print_api_input(in_input): print('\t\tInput type: {0}'.format(in_input.__class__)) print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform)) print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference)) if isinstance(in_input, unreal.HoudiniPublicAPIWorldInput): print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge)) print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds)) print('\t\tbExportSockets: {0}'.format(in_input.export_sockets)) print('\t\tbExportColliders: {0}'.format(in_input.export_colliders)) print('\t\tbIsWorldInputBoundSelector: {0}'.format(in_input.is_world_input_bound_selector)) print('\t\tbWorldInputBoundSelectorAutoUpdate: {0}'.format(in_input.world_input_bound_selector_auto_update)) input_objects = in_input.get_input_objects() if not input_objects: print('\t\tEmpty input!') else: print('\t\tNumber of objects in input: {0}'.format(len(input_objects))) for idx, input_object in enumerate(input_objects): print('\t\t\tInput object #{0}: {1}'.format(idx, input_object)) if hasattr(in_input, 'get_object_transform_offset'): print('\t\t\tObject Transform Offset: {0}'.format(in_input.get_object_transform_offset(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 spawn_actors(): actors = [] # Spawn a static mesh actor and assign a cylinder to its static mesh # component actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, location=(0, 0, 0)) actor.static_mesh_component.set_static_mesh(get_cylinder_asset()) actor.set_actor_label('Cylinder') actor.set_actor_transform( unreal.Transform( (-200, 0, 0), (0, 0, 0), (2, 2, 2), ), sweep=False, teleport=True ) actors.append(actor) # Spawn a static mesh actor and assign a cube to its static mesh # component actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, location=(0, 0, 0)) actor.static_mesh_component.set_static_mesh(get_geo_asset()) actor.set_actor_label('Cube') actor.set_actor_transform( unreal.Transform( (200, 0, 100), (45, 0, 45), (2, 2, 2), ), sweep=False, teleport=True ) actors.append(actor) return actors def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset with auto-cook enabled _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform()) # Configure inputs on_post_instantiation, after instantiation, but before first cook _g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs) # Bind on_post_processing, after cook + output creation _g_wrapper.on_post_processing_delegate.add_callable(print_inputs) if __name__ == '__main__': run()
import unreal import re TEXTURE_FOLDER = "/project/" MATERIAL_FOLDER = "/project/" asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() asset_registry.scan_paths_synchronous([TEXTURE_FOLDER], True) def normalize_name(name): return re.sub(r'(basecolor|albedo|diffuse|normal|_n|nrm|norm|_orm|rough|roughness|_r|metal|metallic|_m)', '', name.lower()) def find_matching_texture(base_texture_name, all_assets, keywords): normalized_base = normalize_name(base_texture_name) for asset in all_assets: if asset.asset_class == "Texture2D": name = str(asset.asset_name) if any(k in name.lower() for k in keywords): if normalize_name(name) == normalized_base: return asset.get_asset() return None def create_material(texture_data, all_assets): texture = texture_data.get_asset() texture_name = texture.get_name() normal_texture = find_matching_texture(texture_name, all_assets, ["normal", "_n", "nrm", "norm", "_orm"]) roughness_texture = find_matching_texture(texture_name, all_assets, ["rough", "roughness", "_r"]) metallic_texture = find_matching_texture(texture_name, all_assets, ["metal", "metallic", "_m"]) if not (normal_texture or roughness_texture or metallic_texture): print(f"⏭️ Skipping {texture_name}: No matching maps.") return material_name = f"{texture_name}_Material" material_path = f"{MATERIAL_FOLDER}/{material_name}" if unreal.EditorAssetLibrary.does_asset_exist(material_path): print(f"Material {material_name} already exists.") return material_factory = unreal.MaterialFactoryNew() material = unreal.AssetToolsHelpers.get_asset_tools().create_asset( asset_name=material_name, package_path=MATERIAL_FOLDER, asset_class=unreal.Material, factory=material_factory ) base_color_sample = unreal.MaterialEditingLibrary.create_material_expression(material, unreal.MaterialExpressionTextureSample, -384, -200) base_color_sample.texture = texture unreal.MaterialEditingLibrary.connect_material_property(base_color_sample, "RGB", unreal.MaterialProperty.MP_BASE_COLOR) if normal_texture: normal_sample = unreal.MaterialEditingLibrary.create_material_expression(material, unreal.MaterialExpressionTextureSample, -384, 100) normal_sample.sampler_type = unreal.MaterialSamplerType.SAMPLERTYPE_NORMAL normal_sample.texture = normal_texture unreal.MaterialEditingLibrary.connect_material_property(normal_sample, "RGB", unreal.MaterialProperty.MP_NORMAL) print(f"🔵 Added normal map: {normal_texture.get_name()}") if roughness_texture: rough_sample = unreal.MaterialEditingLibrary.create_material_expression(material, unreal.MaterialExpressionTextureSample, -384, 300) rough_sample.texture = roughness_texture unreal.MaterialEditingLibrary.connect_material_property(rough_sample, "R", unreal.MaterialProperty.MP_ROUGHNESS) print(f"🟤 Added roughness map: {roughness_texture.get_name()}") if metallic_texture: metallic_sample = unreal.MaterialEditingLibrary.create_material_expression(material, unreal.MaterialExpressionTextureSample, -384, 500) metallic_sample.texture = metallic_texture unreal.MaterialEditingLibrary.connect_material_property(metallic_sample, "R", unreal.MaterialProperty.MP_METALLIC) print(f"⚙️ Added metallic map: {metallic_texture.get_name()}") unreal.EditorAssetLibrary.save_asset(material.get_path_name()) print(f"✅ Created material: {material.get_name()} from {texture_name}") def main(): all_assets = asset_registry.get_assets_by_path(TEXTURE_FOLDER, recursive=True) base_textures = [] for a in all_assets: if a.asset_class == "Texture2D": name = str(a.asset_name).lower() if not any(x in name for x in ["normal", "_n", "nrm", "norm", "_orm", "rough", "roughness", "_r", "metal", "metallic", "_m"]): base_textures.append(a) print(f"🔍 Found {len(base_textures)} base textures.") for texture_data in base_textures: create_material(texture_data, all_assets) main()
""" functions used by the Meta Viewer tool in Unreal """ from pathlib import Path import unreal from recipebook import ( metadata, utils ) def get_item_data_for_euw(): """ get the list of data objects to add to an Unreal List View """ # The template asset path for our item data item_template_path = "/project/" # use arbitrary icons from the icons python dir fp = Path(__file__).parent icon_dir = fp.joinpath("icons") icons = { icon.stem: str(icon.as_posix()) for icon in icon_dir.iterdir() } # get all of our managed assets (using the default arg for "is_managed_asset") meta_query = {metadata.META_IS_MANAGED_ASSET: True} assets = metadata.find_assets_by_metadata(meta_query, class_names=["Blueprint"]) if not assets: return [] items = [] for asset in assets: # Create a new Python instance of the template asset item = utils.new_instance_from_asset(item_template_path) name = metadata.get_metadata(asset, metadata.META_ASSET_NAME) # feed the desired asset metadata into our item item.set_editor_properties({ "name": name, "type": metadata.get_metadata(asset, metadata.META_ASSET_TYPE), "group": metadata.get_metadata(asset, metadata.META_ASSET_GROUP), "version": metadata.get_metadata(asset, metadata.META_ASSET_VERSION), "asset_path": str(asset.package_name), "image_path": icons.get(name[-1]) }) items.append(item) # return the list of ready-to-use item data in our EUW! return items def filter_item_data(items, type_filter, group_filter, name_filter): """filter the given list of meta_item_data entries""" # nested function to make the list comprehension cleaner # only use the filter if it's valid, otherwise skip it (return True) def check_filter_match(a, b): return str(a) == str(b) if a else True return [ item for item in items if check_filter_match(type_filter, item.get_editor_property("type")) and check_filter_match(group_filter, item.get_editor_property("group")) and name_filter.lower() in str(item.get_editor_property("name")).lower() ]
# This script describes a generic use case for the variant manager import unreal # Create all assets and objects we'll use lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs) if lvs is None or lvs_actor is None: print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!") quit() var_set1 = unreal.VariantSet() var_set1.set_display_text("My VariantSet") var_set2 = unreal.VariantSet() var_set2.set_display_text("VariantSet we'll delete") var1 = unreal.Variant() var1.set_display_text("Variant 1") var2 = unreal.Variant() var2.set_display_text("Variant 2") var3 = unreal.Variant() var3.set_display_text("Variant 3") var4 = unreal.Variant() var4.set_display_text("Variant 4") var5 = unreal.Variant() var5.set_display_text("Variant 5") # Adds the objects to the correct parents lvs.add_variant_set(var_set1) var_set1.add_variant(var1) var_set1.add_variant(var2) var_set1.add_variant(var3) var_set1.add_variant(var4) var_set1.add_variant(var5) # Spawn a simple cube static mesh actor cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'") spawned_actor = None if cube: location = unreal.Vector() rotation = unreal.Rotator() spawned_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(cube, location, rotation) spawned_actor.set_actor_label("Cube Actor") else: print ("Failed to find Cube asset!") if spawned_actor is None: print ("Failed to spawn an actor for the Cube asset!") quit() # Bind spawned_actor to all our variants var1.add_actor_binding(spawned_actor) var2.add_actor_binding(spawned_actor) var3.add_actor_binding(spawned_actor) var4.add_actor_binding(spawned_actor) var5.add_actor_binding(spawned_actor) capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(spawned_actor) print ("Capturable properties for actor '" + spawned_actor.get_actor_label() + "':") for prop in capturable_props: print ("\t" + prop) # Capture all available properties on Variant 1 for prop in capturable_props: var1.capture_property(spawned_actor, prop) # Capture just materials on Variant 2 just_mat_props = (p for p in capturable_props if "Material[" in p) for prop in just_mat_props: var2.capture_property(spawned_actor, prop) # Capture just relative location on Variant 4 just_rel_loc = (p for p in capturable_props if "Relative Location" in p) rel_loc_props = [] for prop in just_rel_loc: captured_prop = var4.capture_property(spawned_actor, prop) rel_loc_props.append(captured_prop) # Store a property value on Variant 4 rel_loc_prop = rel_loc_props[0] print (rel_loc_prop.get_full_display_string()) spawned_actor.set_actor_relative_location(unreal.Vector(100, 200, 300), False, False) rel_loc_prop.record() # Move the target actor to some other position spawned_actor.set_actor_relative_location(unreal.Vector(500, 500, 500), False, False) # Can switch on the variant, applying the recorded value of all its properties to all # of its bound actors var4.switch_on() # Cube will be at 100, 200, 300 after this # Apply the recorded value from just a single property rel_loc_prop.apply() # Get the relative rotation property rel_rot = [p for p in capturable_props if "Relative Rotation" in p][0] # Remove objects lvs.remove_variant_set(var_set2) lvs.remove_variant_set(var_set2) var_set1.remove_variant(var3) var5.remove_actor_binding(spawned_actor) var1.remove_captured_property_by_name(spawned_actor, rel_rot)
import os import unreal import argparse import types editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) editor_level_subsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) editor_utility_subsystem = unreal.EditorUtilitySubsystem() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() get_asset_by_path = lambda a: unreal.EditorAssetLibrary.find_asset_data(a).get_asset() get_package_from_path = lambda path: unreal.load_package(path) get_bp_class_by_path = lambda bp_path: unreal.EditorAssetLibrary.load_blueprint_class(bp_path) asset_registery = unreal.AssetRegistryHelpers.get_asset_registry() def get_path_to_uasset(asset): """ Given an unreal asset, return the path of uasset in dir :type asset: str or unreal.Name or uneal.Object :return: """ if type(asset) is str: str_asset = asset elif type(asset) is unreal.Name: str_asset = str(asset) else: str_asset = asset.get_path_name() if str_asset.startswith('/Game/'): asset_path = str_asset.replace('\\', '/').replace('/Game/', 'Content/') return os.path.join(unreal.Paths.project_dir(), asset_path.split('.')[0] + '.uasset') else: return str_asset def run_editor_utility_widget(path_to_widget): if path_to_widget.endswith('_C'): path_to_widget = path_to_widget[:-2] asset = unreal.EditorAssetLibrary.load_asset(path_to_widget) editor_utility_subsystem.spawn_and_register_tab(asset) def _run(input_locals): """ example code: from UnrealUtils import _run if __name__ == '__main__': unreal.log(_run(locals())) :param input_locals: the output from locals :type input_locals: dict :return: the dict of returns from all invoked functions """ parser = argparse.ArgumentParser() funcs = [] results = {} for name, var in input_locals.items(): if type(var) not in [types.FunctionType, types.LambdaType]: continue parser.add_argument('--' + name, help=var.__doc__) funcs.append(name) sys_args = parser.parse_args() for func_name in funcs: arg_value = getattr(sys_args, func_name) if not arg_value: continue assert arg_value.startswith('(') and arg_value.endswith(')'), \ f'Insufficient function arguments found for function {func_name}.' \ f' Needs to match regular expression ^(.*)$' if arg_value == '()': results[func_name] = input_locals[func_name]() else: arguments = arg_value[1:-1].split(',') ####################################################################### # try to convert commonly used data from string to Python data types # more smart jobs can be done here for example using eval to compile the string ####################################################################### converted_args = [] for arg in arguments: if arg == 'None': converted_args.append(None) elif arg == 'True': converted_args.append(True) elif arg == 'False': converted_args.append(False) elif arg.startswith('[') and arg.endswith(']'): converted_args.append(arg[1:-1].split('/')) elif arg.startswith('(') and arg.endswith(')'): converted_args.append(tuple(arg[1:-1].split('/'))) else: converted_args.append(arg) results[func_name] = input_locals[func_name](*converted_args) return results
# -*- coding: utf-8 -*- import unreal import os from Utilities.Utils import Singleton from Utilities.Utils import cast import Utilities import QueryTools import re import types import collections from .import Utils global _r COLUMN_COUNT = 2 class DetailData(object): def __init__(self): self.filter_str = "" self.filteredIndexToIndex = [] self.hisCrumbObjsAndNames = [] #list[(obj, propertyName)] self.attributes = None self.filtered_attributes = None self.plains = [] self.riches = [] self.selected = set() def check_line_id(self, line_id, column_count): from_line = line_id * column_count to_line = (line_id + 1) * column_count assert len(self.plains) == len(self.riches), "len(self.plains) != len(self.riches)" if 0 <= from_line < len(self.plains) and 0 <= to_line <= len(self.plains): return True else: unreal.log_error(f"Check Line Id Failed: {line_id}, plains: {len(self.plains)}, rich: {len(self.riches)}") return False def get_plain(self, line_id, column_count): assert self.check_line_id(line_id, column_count), "check line id failed." return self.plains[line_id * 2 : line_id * 2 + 2] def get_rich(self, line_id, column_count): assert self.check_line_id(line_id, column_count), "check line id failed." return self.riches[line_id * 2: line_id * 2 + 2] class ObjectDetailViewer(metaclass=Singleton): def __init__(self, jsonPath): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.ui_checkbox_single_mode = "CheckBoxSingleMode" self.ui_checkbox_compare_mode = "CheckBoxCompareMode" self.ui_left_group = "LeftDetailGroup" self.ui_right_group = "RightDetailGroup" self.ui_button_refresh = "RefreshCompareButton" self.ui_detailListLeft = "ListViewLeft" self.ui_detailListRight = "ListViewRight" self.ui_hisObjsBreadcrumbLeft = 'ObjectHisBreadcrumbLeft' self.ui_hisObjsBreadcrumbRight = 'ObjectHisBreadcrumbRight' # self.ui_headRowLeft = "HeaderRowLeft" # self.ui_headRowRight = "HeaderRowRight" self.ui_labelLeft = "LabelLeft" self.ui_labelRight = "LabelRight" self.ui_info_output = "InfoOutput" self.ui_rightButtonsGroup = "RightButtonsGroup" # used for compare mode self.ui_rightListGroup = "RightListGroup" self.ui_refreshButtonGroup = "RefreshButtonGroup" self.reset() def on_close(self): self.reset() def on_map_changed(self, map_change_type_str): # remove the reference, avoid memory leaking when load another map. if map_change_type_str == "TearDownWorld": self.reset(bResetParameter=False) else: pass # skip: LoadMap, SaveMap, NewMap def reset(self, bResetParameter=True): if bResetParameter: self.showBuiltin = True self.showOther = True self.showProperties = True self.showEditorProperties = True self.showParamFunction = True self.compareMode = False self.left = None self.right = None self.leftSearchText = "" self.rightSearchText = "" self.left_rich = None self.left_plain = None self.var = None self.diff_count = 0 self.clear_ui_info() def clear_ui_info(self): for text_ui in [self.ui_info_output, self.ui_labelLeft, self.ui_labelRight]: self.data.set_text(text_ui, "") self.data.set_list_view_multi_column_items(self.ui_detailListLeft, [], 2) self.data.set_list_view_multi_column_items(self.ui_detailListRight, [], 2) for ui_breadcrumb in [self.ui_hisObjsBreadcrumbRight, self.ui_hisObjsBreadcrumbLeft]: crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) for i in range(crumbCount): self.data.pop_breadcrumb_string(ui_breadcrumb) def update_log_text(self, bRight): bShowRight = self.compareMode result = "" for side_str in ["left", "right"] if bShowRight else ["left"]: bRight = side_str != "left" ui_breadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft breadcrumbs = self.right.hisCrumbObjsAndNames if bRight else self.left.hisCrumbObjsAndNames crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) if bRight: result += "\t\t\t" result += "{} crumb: {} hisObj: {}".format(side_str, crumbCount, len(breadcrumbs)) if self.compareMode: result = f"{result}\t\t\tdiff count: {self.diff_count}" self.data.set_text(self.ui_info_output, result) def get_color_by(self, attr : Utils.attr_detail): if attr.bCallable_builtin: return "DarkTurquoise".lower() if attr.bCallable_other: return "RoyalBlue".lower() if attr.bEditorProperty: return "LimeGreen".lower() if attr.bOtherProperty: return "yellow" def get_color(self, typeStr): if typeStr == "property": return 'white' if typeStr == "return_type": return 'gray' if typeStr == "param": return 'gray' def get_name_with_rich_text(self, attr:Utils.attr_detail): name_color = self.get_color_by(attr) param_color = self.get_color("param") return_type_color = self.get_color("return_type") if attr.bProperty: return "\t<RichText.{}>{}</>".format(name_color, attr.name) else: if attr.param_str: return "\t<RichText.{}>{}(</><RichText.{}>{}</><RichText.{}>)</>".format(name_color, attr.name , param_color, attr.param_str , name_color) else: if attr.bCallable_other: return "\t<RichText.{}>{}</>".format(name_color, attr.name) else: return "\t<RichText.{}>{}()</><RichText.{}> {}</>".format(name_color, attr.name , return_type_color, attr.return_type_str) def get_name_with_plain_text(self, attr:Utils.attr_detail): if attr.bProperty: return "\t{}".format(attr.name) else: if attr.param_str: return "\t{}({})".format( attr.name, attr.param_str) else: if attr.bCallable_other: return "\t{}".format( attr.name) else: return "\t{}() {}".format(attr.name,attr.return_type_str) def filter(self, data:DetailData): result = [] indices = [] for i, attr in enumerate(data.attributes): if not self.showEditorProperties and attr.bEditorProperty: continue if not self.showProperties and attr.bOtherProperty: continue if not self.showParamFunction and attr.bHasParamFunction: continue if not self.showBuiltin and attr.bCallable_builtin: continue if not self.showOther and attr.bCallable_other: continue if data.filter_str: if data.filter_str.lower() not in attr.display_result.lower() and data.filter_str not in attr.display_name.lower() : continue result.append(attr) indices.append(i) return result, indices def show_data(self, data:DetailData, ui_listView): flatten_list_items = [] flatten_list_items_plain = [] for i, attr in enumerate(data.filtered_attributes): # print(f"{i}: {attr.name} {attr.display_name}, {attr.display_result} ") attr.check() assert attr.display_name, f"display name null {attr.display_name}" assert isinstance(attr.display_result, str), f"display result null {attr.display_result}" result_str = attr.display_result if len(result_str) > 200: result_str = result_str[:200] + "......" flatten_list_items.extend([self.get_name_with_rich_text(attr), result_str]) flatten_list_items_plain.extend([self.get_name_with_plain_text(attr), result_str]) data.riches = flatten_list_items data.plains = flatten_list_items_plain data.selected.clear() self.data.set_list_view_multi_column_items(ui_listView, flatten_list_items, 2) def query_and_push(self, obj, propertyName, bPush, bRight): #bPush: whether add Breadcrumb nor not, call by property if bRight: ui_Label = self.ui_labelRight ui_listView = self.ui_detailListRight ui_breadcrumb = self.ui_hisObjsBreadcrumbRight else: ui_Label = self.ui_labelLeft ui_listView = self.ui_detailListLeft ui_breadcrumb = self.ui_hisObjsBreadcrumbLeft data = self.right if bRight else self.left data.attributes = Utils.ll(obj) data.filtered_attributes, data.filteredIndexToIndex = self.filter(data) self.show_data(data, ui_listView) # set breadcrumb if propertyName and len(propertyName) > 0: label = propertyName else: if isinstance(obj, unreal.Object): label = obj.get_name() else: try: label = obj.__str__() except TypeError: label = f"{obj}" if bPush: # push # print(f"%%% push: {propertyName}, label {label}") data.hisCrumbObjsAndNames.append((obj, propertyName)) self.data.push_breadcrumb_string(ui_breadcrumb, label, label) self.data.set_text(ui_Label, "{} type: {}".format(label, type(obj)) ) crumbCount = self.data.get_breadcrumbs_count_string(ui_breadcrumb) if bRight: assert len(self.right.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.right.hisCrumbObjsAndNames), crumbCount) else: assert len(self.left.hisCrumbObjsAndNames) == crumbCount, "hisCrumbObjsAndNames count not match {} {}".format(len(self.left.hisCrumbObjsAndNames), crumbCount) self.update_log_text(bRight) def clear_and_query(self, obj, bRight): # first time query self.data.clear_breadcrumbs_string(self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft) if not self.right: self.right = DetailData() if not self.left: self.left = DetailData() data = self.right if bRight else self.left data.hisCrumbObjsAndNames = [] #clear his-Object at first time query if bRight: assert len(self.right.hisCrumbObjsAndNames) == 0, "len(self.right.hisCrumbObjsAndNames) != 0" else: assert len(self.left.hisCrumbObjsAndNames) == 0, "len(self.left.hisCrumbObjsAndNames) != 0" self.query_and_push(obj, "", bPush=True, bRight= bRight) self.apply_compare_if_needed() self.update_log_text(bRight) def update_ui_by_mode(self): self.data.set_is_checked(self.ui_checkbox_compare_mode, self.compareMode) self.data.set_is_checked(self.ui_checkbox_single_mode, not self.compareMode) bCollapsed = not self.compareMode self.data.set_collapsed(self.ui_rightButtonsGroup, bCollapsed) self.data.set_collapsed(self.ui_right_group, bCollapsed) self.data.set_collapsed(self.ui_button_refresh, bCollapsed) def on_checkbox_SingleMode_Click(self, state): self.compareMode = False self.update_ui_by_mode() def on_checkbox_CompareMode_Click(self, state): self.compareMode = True self.update_ui_by_mode() def on_button_Refresh_click(self): self.apply_compare_if_needed() def on_button_SelectAsset_click(self, bRightSide): selectedAssets = Utilities.Utils.get_selected_assets() if len(selectedAssets) == 0: return self.clear_and_query(selectedAssets[0], bRightSide) def on_button_QuerySelected_click(self, bRightSide): # query component when any component was selected, otherwise actor obj = Utilities.Utils.get_selected_comp() if not obj: obj = Utilities.Utils.get_selected_actor() if obj: self.clear_and_query(obj, bRightSide) def on_drop(self, bRightSide, *args, **kwargs): if "assets" in kwargs and kwargs["assets"]: asset = unreal.load_asset(kwargs["assets"][0]) if asset: self.clear_and_query(asset, bRightSide) return if "actors" in kwargs and kwargs["actors"]: actor = unreal.PythonBPLib.find_actor_by_name(kwargs["actors"][0], unreal.EditorLevelLibrary.get_editor_world()) if actor: print(actor) self.clear_and_query(actor, bRightSide) return item_count = 0 for k, v in kwargs.items(): item_count += len(v) if item_count == 0: selected_comp = Utilities.Utils.get_selected_comp() if selected_comp: self.clear_and_query(selected_comp, bRightSide) def log_r_warning(self): unreal.log_warning("Assign the global var: '_r' with the MenuItem: 'select X --> _r' on Python Icon menu") def on_button_Query_R_click(self, r_obj, bRightSide=False): print("on_button_Query_R_click call") if not r_obj: return self.clear_and_query(r_obj, bRightSide) def on_list_double_click_do(self, index, bRight): # print ("on_listview_DetailList_mouse_button_double_click {} bRight: {}".format(index, bRight)) data = self.right if bRight else self.left typeBlacklist = [int, float, str, bool] #, types.NotImplementedType] real_index = data.filteredIndexToIndex[index] if data.filteredIndexToIndex else index assert 0 <= real_index < len(data.attributes) currentObj, _ = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1] attr_name = data.attributes[real_index].name objResult, propertyName = self.try_get_object(data, currentObj, attr_name) if not objResult or objResult is currentObj: # equal return if isinstance(objResult, str) and "skip call" in objResult.lower(): return if type(objResult) in typeBlacklist: return if isinstance(objResult, collections.abc.Iterable): if type(objResult[0]) in typeBlacklist: return nextObj = objResult[0] nextPropertyName = str(propertyName) + "[0]" else: nextObj = objResult nextPropertyName = str(propertyName) self.query_and_push(nextObj, nextPropertyName, bPush=True, bRight=bRight) self.apply_compare_if_needed() self.update_log_text(bRight) def on_listview_DetailListRight_mouse_button_double_click(self, index): self.on_list_double_click_do(index, bRight=True) def on_listview_DetailListLeft_mouse_button_double_click(self, index): self.on_list_double_click_do(index, bRight=False) def on_breadcrumbtrail_click_do(self, item, bRight): ui_hisObjsBreadcrumb = self.ui_hisObjsBreadcrumbRight if bRight else self.ui_hisObjsBreadcrumbLeft data = self.right if bRight else self.left count = self.data.get_breadcrumbs_count_string(ui_hisObjsBreadcrumb) print ("on_breadcrumbtrail_ObjectHis_crumb_click: {} count: {} len(data.hisCrumbObjsAndNames): {}".format(item, count, len(data.hisCrumbObjsAndNames))) while len(data.hisCrumbObjsAndNames) > count: data.hisCrumbObjsAndNames.pop() nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames) - 1] if not bRight: assert self.left.hisCrumbObjsAndNames == data.hisCrumbObjsAndNames, "self.left.hisCrumbObjsAndNames = data.hisCrumbObjsAndNames" self.query_and_push(nextObj, name, bPush=False, bRight=False) self.apply_compare_if_needed() self.update_log_text(bRight=False) def on_breadcrumbtrail_ObjectHisLeft_crumb_click(self, item): self.on_breadcrumbtrail_click_do(item, bRight=False) def on_breadcrumbtrail_ObjectHisRight_crumb_click(self, item): self.on_breadcrumbtrail_click_do(item, bRight=True) def remove_address_str(self, strIn): return re.sub(r'\(0x[0-9,A-F]{16}\)', '', strIn) def apply_compare_if_needed(self): if not self.compareMode: return lefts = self.left.filtered_attributes if self.left.filtered_attributes else self.left.attributes rights = self.right.filtered_attributes if self.right.filtered_attributes else self.right.attributes if not lefts: lefts = [] if not rights: rights = [] leftIDs = [] rightIDs = [] for i, left_attr in enumerate(lefts): for j, right_attr in enumerate(rights): if right_attr.name == left_attr.name: if right_attr.result != left_attr.result: if isinstance(right_attr.result, unreal.Transform): if right_attr.result.is_near_equal(left_attr.result, location_tolerance=1e-20, rotation_tolerance=1e-20, scale3d_tolerance=1e-20): continue leftIDs.append(i) rightIDs.append(j) break self.data.set_list_view_multi_column_selections(self.ui_detailListLeft, leftIDs) self.data.set_list_view_multi_column_selections(self.ui_detailListRight, rightIDs) self.diff_count = len(leftIDs) def apply_search_filter(self, text, bRight): _data = self.right if bRight else self.left _data.filter_str = text if len(text) else "" _data.filtered_attributes, _data.filteredIndexToIndex = self.filter(_data) ui_listView = self.ui_detailListRight if bRight else self.ui_detailListLeft self.show_data(_data, ui_listView) self.apply_compare_if_needed() def on_searchbox_FilterLeft_text_changed(self, text): self.apply_search_filter(text if text is not None else "", bRight=False) def on_searchbox_FilterLeft_text_committed(self, text): self.apply_search_filter(text if text is not None else "", bRight=False) def on_searchbox_FilterRight_text_changed(self, text): self.apply_search_filter(text if text is not None else "", bRight=True) def on_searchbox_FilterRight_text_committed(self, text): self.apply_search_filter(text if text is not None else "", bRight=True) def apply_filter(self): _datas = [self.left, self.right] _isRight = [False, True] for data, bRight in zip(_datas, _isRight): if len(data.hisCrumbObjsAndNames) > 0: nextObj, name = data.hisCrumbObjsAndNames[len(data.hisCrumbObjsAndNames)-1] self.query_and_push(nextObj, name, bPush=False, bRight=bRight) self.apply_compare_if_needed() self.update_log_text(bRight=False) # def try_get_object(self, data, obj, name:str): index = -1 attribute = None for i, attr in enumerate(data.attributes): if attr.name == name: index = i attribute = attr assert index >= 0 return attribute.result, name def ui_on_checkbox_ShowBuiltin_state_changed(self, bEnabled): self.showBuiltin = bEnabled self.apply_filter() def ui_on_checkbox_ShowOther_state_changed(self, bEnabled): self.showOther = bEnabled self.apply_filter() def ui_on_checkbox_ShowProperties_state_changed(self, bEnabled): self.showProperties = bEnabled self.apply_filter() def ui_on_checkbox_ShowEditorProperties_state_changed(self, bEnabled): self.showEditorProperties = bEnabled self.apply_filter() def ui_on_checkbox_ShowParamFunction_state_changed(self, bEnabled): self.showParamFunction = bEnabled self.apply_filter() def ui_on_listview_DetailList_selection_changed(self, bRight): data = [self.left, self.right][bRight] list_view = [self.ui_detailListLeft, self.ui_detailListRight][bRight] selected_indices = set(self.data.get_list_view_multi_column_selection(list_view)) added = selected_indices - data.selected de_selected = data.selected - selected_indices for i, lineId in enumerate(added): self.data.set_list_view_multi_column_line(list_view, lineId, data.get_plain(lineId, column_count=COLUMN_COUNT) , rebuild_list=True if i == len(added)-1 and len(de_selected) == 0 else False) for i, lineId in enumerate(de_selected): self.data.set_list_view_multi_column_line(list_view, lineId, data.get_rich(lineId, column_count=COLUMN_COUNT) , rebuild_list=True if i == len(de_selected)-1 else False) data.selected = selected_indices
import unreal editor_actor_subsystem:unreal.EditorActorSubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) unreal_editor_subsystem:unreal.UnrealEditorSubsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) def import_mesh(path:str, target_path:str, name:str, scale:float)->str: asset_library:unreal.EditorAssetLibrary = unreal.EditorAssetLibrary() if asset_library.does_asset_exist(target_path + "/" + name): asset_library.delete_asset(target_path + "/" + name) task = unreal.AssetImportTask() task.filename = path task.destination_path = target_path task.destination_name = name task.replace_existing = True task.automated = True task.save = True options = unreal.FbxImportUI() options.import_mesh = True options.import_textures = False options.import_materials = False options.import_as_skeletal = False options.set_editor_property("mesh_type_to_import", unreal.FBXImportType.FBXIT_STATIC_MESH) fbx_static_mesh_import_data = unreal.FbxStaticMeshImportData() #fbx_static_mesh_import_data.force_front_x_axis =True fbx_static_mesh_import_data.combine_meshes = True fbx_static_mesh_import_data.import_uniform_scale = scale options.static_mesh_import_data = fbx_static_mesh_import_data task.options = options aset_tools = unreal.AssetToolsHelpers.get_asset_tools() aset_tools.import_asset_tasks([task]) return target_path + "/" + name def swap_meshes_and_set_material(path:str, materials_folder:str, name:str, udmi:bool, force_front_x_axis:bool = True): static_mesh:unreal.StaticMesh = unreal.EditorAssetLibrary.load_asset(path) materials = static_mesh.static_materials asset_library:unreal.EditorAssetLibrary = unreal.EditorAssetLibrary() for index in range(len(materials)): material_instance_path = find_asset(materials_folder, ("M_" if udmi else "MI_") + name + "_" + str(materials[index].material_slot_name)) if material_instance_path != None: static_mesh.set_material(index, asset_library.load_asset(material_instance_path[0 : material_instance_path.rfind(".")])) world = unreal_editor_subsystem.get_editor_world() actors = unreal.GameplayStatics.get_all_actors_of_class(world, unreal.Actor) for actor in actors: if static_mesh.get_name() == actor.get_actor_label(): editor_actor_subsystem.destroy_actor(actor) viewport = unreal_editor_subsystem.get_level_viewport_camera_info() camera_location = viewport[0] camera_rotation = viewport[1] spawn_distance = 1000.0 forward_vector = camera_rotation.get_forward_vector() spawn_location = camera_location + forward_vector * spawn_distance static_mesh_actor = editor_actor_subsystem.spawn_actor_from_object(static_mesh, spawn_location, unreal.Rotator(0, 0, camera_rotation.yaw).combine(unreal.Rotator(0, 0, -270 if force_front_x_axis else -180))) editor_actor_subsystem.set_selected_level_actors([static_mesh_actor]) ''' ray_start = spawn_location ray_end = ray_start + unreal.Vector(0, 0, -10000) hit_result:unreal.HitResult = unreal.SystemLibrary.line_trace_single( world, ray_start, ray_end, unreal.TraceTypeQuery.TRACE_TYPE_QUERY1, False, [], unreal.DrawDebugTrace.NONE, True ) if hit_result: ground_location = hit_result.to_tuple()[4] static_mesh_actor = editor_actor_subsystem.spawn_actor_from_object(static_mesh, ground_location, unreal.Rotator(0, 0, camera_rotation.yaw).combine(unreal.Rotator(0, 0, -180))) editor_actor_subsystem.set_selected_level_actors([static_mesh_actor]) else: static_mesh_actor = editor_actor_subsystem.spawn_actor_from_object(static_mesh, unreal.Vector(0, 0, 0), unreal.Rotator(0, 0, 0)) editor_actor_subsystem.set_selected_level_actors([static_mesh_actor]) ''' def import_mesh_and_swap(path:str, target:str, name:str, udmi:bool, scale:float, force_front_x_axis:bool = True): swap_meshes_and_set_material(import_mesh(path, target, name, scale), target, name, udmi, force_front_x_axis) return True
import unreal print("=== VERIFYING LEVEL CONTENTS ===") try: # Load TestLevel print("Loading TestLevel...") level_loaded = unreal.EditorLevelLibrary.load_level('/project/') if level_loaded: print("✓ TestLevel loaded") # Get all actors try: actors = unreal.get_editor_subsystem(unreal.EditorActorSubsystem).get_all_level_actors() print(f"\nFound {len(actors)} actors in the level:") # Count different types lights = 0 meshes = 0 player_starts = 0 characters = 0 for actor in actors: actor_name = actor.get_name() actor_class = actor.get_class().get_name() if 'Light' in actor_class: lights += 1 print(f" 🌞 {actor_name} ({actor_class})") elif 'StaticMeshActor' in actor_class: meshes += 1 print(f" 🏗️ {actor_name} ({actor_class})") elif 'PlayerStart' in actor_class: player_starts += 1 print(f" 📍 {actor_name} ({actor_class})") elif 'Character' in actor_class or 'Warrior' in actor_class: characters += 1 print(f" 🎮 {actor_name} ({actor_class})") else: print(f" ⚙️ {actor_name} ({actor_class})") print(f"\n📊 Summary:") print(f" Lights: {lights}") print(f" Static Meshes: {meshes}") print(f" Player Starts: {player_starts}") print(f" Characters: {characters}") if lights >= 2 and meshes >= 10 and player_starts >= 1: print("\n✅ LEVEL SETUP SUCCESSFUL!") print(" - Lighting system ✓") print(" - Floor and platforms ✓") print(" - Player spawn point ✓") print(" - Ready for character testing!") else: print("\n⚠️ Level may need more setup") except Exception as e: print(f"Error getting actors: {e}") else: print("✗ Failed to load TestLevel") except Exception as e: print(f"✗ ERROR: {e}") print("Verification complete") unreal.SystemLibrary.execute_console_command(None, "exit")
from typing import Any, Optional import unreal from unreal import PrimalDinoStatusComponent, PrimalDinoCharacter from consts import OUTPUT_OVERRIDES, SKIP_TROODONISMS_PATHS, STAT_COUNT, VALUE_DEFAULTS, VARIANT_OVERRIDES from clean_numbers import clean_float as cf, clean_double as cd from species.bones import gather_damage_mults from species.breeding import gather_breeding_data from species.taming import gather_taming_data from species.colors import gather_color_data from species.stats import DEFAULT_IMPRINT_MULTS, DEFAULT_MAX_STATUS_VALUES, gather_stat_data def values_for_species(bp: str, char: PrimalDinoCharacter, dcsc: PrimalDinoStatusComponent, alt_dcsc: PrimalDinoStatusComponent) -> Optional[dict[str, str]]: unreal.log(f'Using Character: {char.get_full_name()}') unreal.log(f'Using DCSC: {dcsc.get_full_name()}') # Skip vehicles if char.is_vehicle: return None # Having no name or tag is an indication that this is an intermediate class, not a spawnable species name = (str(char.descriptive_name) or str(char.dino_name_tag)).strip() if not name: unreal.log(f"Species {char.get_full_name()} has no DescriptiveName or DinoNameTag - skipping") return None # Also consider anything that doesn't override any base status value as non-spawnable max_status_values: List[float] = list(dcsc.max_status_values) # type: ignore if max_status_values == DEFAULT_MAX_STATUS_VALUES: unreal.log(f"Species {char.get_full_name()} has no overridden stats - skipping") return None species: dict[str, Any] = dict(blueprintPath=bp, name=name) short_bp = bp.split('.')[0] bp = bp.removesuffix('_C') # Variants variants = VARIANT_OVERRIDES.get(short_bp, None) if variants: species['variants'] = sorted(variants) # Stat data is_flyer = bool(char.is_flyer_dino) if is_flyer: species['isFlyer'] = True normal_stats = gather_stat_data(dcsc, dcsc, is_flyer) alt_stats = None if not any(short_bp.startswith(path) for path in SKIP_TROODONISMS_PATHS): alt_stats = gather_stat_data(alt_dcsc, dcsc, is_flyer) alt_stats = reduce_alt_stats(normal_stats, alt_stats) species['fullStatsRaw'] = normal_stats if alt_stats: species['altBaseStats'] = alt_stats # Imprint multipliers stat_imprint_mults: list[float] = list() unique_mults = False for stat_index in range(STAT_COUNT): imprint_mult = dcsc.dino_max_stat_add_multiplier_imprinting[stat_index] # type: ignore stat_imprint_mults.append(cf(imprint_mult)) # type: ignore diff = abs(imprint_mult - DEFAULT_IMPRINT_MULTS[stat_index]) if diff > 0.0001: unique_mults = True if unique_mults: species['statImprintMult'] = stat_imprint_mults # Breeding data if char.can_have_baby: breeding_data = None breeding_data = gather_breeding_data(char) if breeding_data: species['breeding'] = breeding_data # Taming data taming = gather_taming_data(short_bp, char, dcsc) if taming: species['taming'] = taming # Bone damage multipliers dmg_mults = None dmg_mults = gather_damage_mults(char) if dmg_mults: species['boneDamageAdjusters'] = dmg_mults # Misc data usesOxyWild = dcsc.can_suffocate # type: ignore usesOxyTamed = True if usesOxyWild else dcsc.can_suffocate_if_tamed # type: ignore forceOxy = dcsc.force_gain_oxygen # type: ignore doesntUseOxygen = not (usesOxyTamed or forceOxy) ETBHM: float = char.extra_tamed_base_health_multiplier # type: ignore TBHM: float = dcsc.tamed_base_health_multiplier * ETBHM # type: ignore displayed_stats: int = 0 for i in range(STAT_COUNT): use_stat = not dcsc.dont_use_value[i] # type: ignore if use_stat and not (i == 3 and doesntUseOxygen): displayed_stats |= (1 << i) species['TamedBaseHealthMultiplier'] = cf(TBHM) species['displayedStats'] = displayed_stats if not char.uses_gender: species['noGender'] = True # Mutation multipliers mutation_mults: List[float] = list(dcsc.mutation_multiplier) # type: ignore if any(True for mult in mutation_mults if mult != 1.0): species['mutationMult'] = mutation_mults # Skip wild level-ups skip_wild_levels: List[int] = list(dcsc.skip_wild_level_up_value) # type: ignore skip_wild_level_bitmap = 0 for i in range(STAT_COUNT): if skip_wild_levels[i]: skip_wild_level_bitmap |= (1 << i) if skip_wild_level_bitmap: species['skipWildLevelStats'] = skip_wild_level_bitmap # Color data colors = gather_color_data(short_bp, char) if colors: species['colors'] = colors # General output overrides overrides = OUTPUT_OVERRIDES.get(short_bp, None) if overrides: species.update(overrides) # Remove values that match the defaults for key, value in list(VALUE_DEFAULTS.items()): if species.get(key, None) == value: del species[key] return species def reduce_alt_stats(normal_stats, alt_stats): output = {i: a[0] for (i, (n, a)) in enumerate(zip(normal_stats, alt_stats)) if n and a and n[0] != a[0]} return output if output else None
import os import unreal import yaml import math scene_name = 'camstore' yaml_path = 'D:/project/.yaml' path_blueprint = '/project/' + scene_name + '/blueprints' path_mesh = '/project/' + scene_name + '/project/' path_level = '/project/' + scene_name + '/maps/' path_hdri = '/project/' + scene_name + '/hdri/' def createWorld() : unreal.EditorLevelLibrary.new_level(path_level + scene_name) unreal.EditorLevelLibrary.load_level(path_level + scene_name) world = unreal.EditorLevelLibrary.get_editor_world() sub_level_of_world = unreal.EditorLevelUtils.get_levels(world) actor = unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PlayerStart,(20 , 20 , 20)) actor = unreal.EditorLevelLibrary.spawn_actor_from_object(unreal.EditorAssetLibrary.load_asset(path_hdri + 'Hdri_world_' + scene_name) , (0 , 0 , -50) , (0 , 0 , 0)) actor = unreal.EditorLevelLibrary.spawn_actor_from_object(unreal.EditorAssetLibrary.load_asset('/project/.FirstPersonCharacter') , (20 , 20 , 110)) actor= unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.LightmassImportanceVolume,(-1001 , -1152 , 388)) actor.set_actor_relative_scale3d((30 , 32 , 15)) actor= unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.NavMeshBoundsVolume,(-1001 , -1152 , 388)) actor.set_actor_relative_scale3d((30 , 32 , 15)) actor= unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PostProcessVolume,(-1001 , -1152 , 388)) actor.set_actor_relative_scale3d((30 , 32 , 15)) createLevel(sub_level_of_world) def createLevel(sub_level_of_world) : with open(yaml_path , 'r') as file : yaml_file = yaml.safe_load(file) for level_name in yaml_file : if str(sub_level_of_world).find(path_level + level_name) != -1 : unreal.EditorLevelLibrary.set_current_level_by_name(level_name) else : streaming_level=unreal.EditorLevelUtils.create_new_streaming_level(unreal.LevelStreamingDynamic , '/Game/'+level_name ) streaming_level.set_editor_property('initially_loaded' , True) streaming_level.set_editor_property('initially_visible' , True) createActors(yaml_file[level_name] , '' , level_name , '') unreal.EditorLevelLibrary.save_all_dirty_levels() def createActors(dic_actor , path_actor_level , actual_dic , path_to_mesh) : if 'mesh' in dic_actor : if actual_dic == "appartement": actor = unreal.EditorLevelLibrary.spawn_actor_from_object(unreal.EditorAssetLibrary.load_asset(path_mesh + path_to_mesh + '/' + dic_actor['mesh'] + '.' + dic_actor['mesh']) , (dic_actor['x']*100 , dic_actor['y']*(-100) , dic_actor['z']*100) , (dic_actor['ry']*(-180/math.pi) , dic_actor['rz']*(-180/math.pi) , dic_actor['rx']*(180/math.pi))) actor.set_folder_path('/project/') actor.set_actor_label(actual_dic) elif "env" in path_actor_level: if dic_actor['type']=='AREA': rectlight=unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.RectLight , (dic_actor['x']*100 , dic_actor['y']*(-100) , dic_actor['z']*100-60) , (dic_actor['rx']*(-180/math.pi)-90 , dic_actor['rz']*(-180/math.pi)-90 , dic_actor['ry']*(180/math.pi))) rectlight.root_component.set_editor_property('mobility' , unreal.ComponentMobility.STATIC) rectlight.root_component.set_editor_property('intensity' , dic_actor['power']) rectlight.set_folder_path(path_actor_level) rectlight.set_actor_label(actual_dic) elif dic_actor['type']=='POINT': pointlight=unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.PointLight,(dic_actor['x']*100 , dic_actor['y']*(-100) , dic_actor['z']*100) , (dic_actor['rx']*(-180/math.pi) , dic_actor['rz']*(-180/math.pi) , dic_actor['ry']*(180/math.pi))) pointlight.root_component.set_editor_property('mobility' , unreal.ComponentMobility.STATIC) pointlight.root_component.set_editor_property('intensity' , dic_actor['power']) pointlight.set_folder_path(path_actor_level) pointlight.set_actor_label(path_actor_level) elif "grapable" in path_actor_level: actor=unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.EditorAssetLibrary.load_blueprint_class('/project/.BP_grapable_Free'), (dic_actor['x']*100 , dic_actor['y']*(-100) , dic_actor['z']*100) , (dic_actor['ry']*(-180/math.pi) , dic_actor['rz']*(-180/math.pi) , dic_actor['rx']*(180/math.pi))) actor.set_folder_path(path_actor_level) actor.set_actor_label(actual_dic) actor.root_component.set_editor_property('relative_scale3d' , (dic_actor['scale x'] , dic_actor['scale y'] , dic_actor['scale z'])) all_actors = unreal.EditorLevelLibrary.get_all_level_actors_components() for blueprint_component in all_actors: actor_owner=blueprint_component.get_owner() if actor_owner: if actual_dic == actor_owner.get_actor_label(): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + path_to_mesh+ "/" + dic_actor['mesh'])) elif "furnitures" in path_actor_level: actor = unreal.EditorLevelLibrary.spawn_actor_from_object(unreal.EditorAssetLibrary.load_asset(path_mesh + path_to_mesh + '/' + dic_actor['mesh'] + '.' + dic_actor['mesh']) , (dic_actor['x']*100 , dic_actor['y']*(-100) , dic_actor['z']*100) , (dic_actor['ry']*(-180/math.pi) , dic_actor['rz']*(-180/math.pi) , dic_actor['rx']*(180/math.pi) )) actor.set_folder_path(path_actor_level) actor.set_actor_label(actual_dic) actor.root_component.set_editor_property('relative_scale3d' , (dic_actor['scale x'] , dic_actor['scale y'] , dic_actor['scale z'])) else: actor = unreal.EditorLevelLibrary.spawn_actor_from_object(unreal.EditorAssetLibrary.load_asset(path_mesh + path_to_mesh + '/' + dic_actor['mesh'] + '.' + dic_actor['mesh']) , (dic_actor['x']*100 , dic_actor['y']*(-100) , dic_actor['z']*100) , (dic_actor['ry']*(-180/math.pi) , dic_actor['rz']*(-180/math.pi) , dic_actor['rx']*(180/math.pi) )) actor.set_folder_path(path_actor_level) actor.set_actor_label(actual_dic) elif 'right_door' in dic_actor : actor=unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.EditorAssetLibrary.load_blueprint_class('/project/.BP_door_interactive') , (dic_actor['right_door']['x']*100 , dic_actor['right_door']['y']*(-100) , dic_actor['right_door']['z']*100) , (dic_actor['right_door']['ry']*(-180/math.pi) , dic_actor['right_door']['rz']*(-180/math.pi) , dic_actor['right_door']['rx']*(180/math.pi) )) actor.set_folder_path(path_actor_level) actor.set_actor_label(actual_dic) list = [] i = 0 while i == 0: i = 1 all_actors = unreal.EditorLevelLibrary.get_all_level_actors_components() for blueprint_component in all_actors: actor_owner=blueprint_component.get_owner() if actor_owner: if actual_dic == actor_owner.get_actor_label() and ('StaticMesh' in str(blueprint_component) or 'ChildActor' in str(blueprint_component)): check_list=str(blueprint_component).split('PersistentLevel.BP_door_interactive_C')[1] check_list=str(check_list).split(".")[1] check_list=str(check_list).split("'")[0] if check_list not in list : i=0 element_list=str(blueprint_component).split('PersistentLevel.BP_door_interactive_C')[1] element_list=str(element_list).split(".")[1] element_list=str(element_list).split("'")[0] list.append(element_list) if 'Handle' in str(blueprint_component) and 'handle' in dic_actor: blueprint_component.set_editor_property("child_actor_class",unreal.EditorAssetLibrary.load_blueprint_class(path_blueprint + "/BP_" + dic_actor["handle"]["mesh"] + "_movable_" + scene_name)) elif 'Lock' in str(blueprint_component) and 'lock' in dic_actor: blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/project/" + dic_actor['lock']['mesh'])) elif 'Wrist' in str(blueprint_component) and 'wrist' in dic_actor: blueprint_component.set_editor_property("child_actor_class",unreal.EditorAssetLibrary.load_blueprint_class(path_blueprint + "/BP_" + dic_actor["wrist"]["mesh"] + "_nonmovable_" + scene_name)) elif 'door_left' in str(blueprint_component) and 'left_door' in dic_actor: blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/project/" + dic_actor['left_door']['mesh'])) elif 'door_right' in str(blueprint_component) and 'right_door' in dic_actor: blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/project/" + dic_actor['right_door']['mesh'])) elif 'Double' in str(blueprint_component) and 'frame' in dic_actor: blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/project/" + dic_actor['frame']['mesh'])) unreal.EditorLevelLibrary.save_all_dirty_levels() elif 'elevator' == actual_dic: actor=unreal.EditorLevelLibrary.spawn_actor_from_class(unreal.EditorAssetLibrary.load_blueprint_class('/project/.elevator') , (dic_actor['gf_elevator']['x']*100 , dic_actor['gf_elevator']['y']*(-100) , dic_actor['gf_elevator']['z']*100) , (dic_actor['gf_elevator']['ry']*(-180/math.pi) , dic_actor['gf_elevator']['rz']*(-180/math.pi) , dic_actor['gf_elevator']['rx']*(180/math.pi) )) actor.set_folder_path(path_actor_level) actor.set_actor_label(actual_dic) list = [] i = 0 while i == 0: i = 1 all_actors = unreal.EditorLevelLibrary.get_all_level_actors_components() for blueprint_component in all_actors: actor_owner = blueprint_component.get_owner() if actor_owner: if actual_dic in actor_owner.get_actor_label() and 'StaticMesh' in str(blueprint_component): check_list = str(blueprint_component).split('PersistentLevel.elevator_C')[1] check_list = str(check_list).split(".")[1] check_list = str(check_list).split("'")[0] if check_list not in list: i=0 element_list = str(blueprint_component).split('PersistentLevel.elevator_C')[1] element_list = str(element_list).split(".")[1] element_list = str(element_list).split("'")[0] list.append(element_list) if 'interior' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['interior']['mesh'])) elif 'top door half 1' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['door_exterior_top_001']['mesh'])) elif 'top door half' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['door_exterior_top']['mesh'])) elif 'door bot in 1' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['door_interior_botom_001']['mesh'])) elif 'door bot in' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['door_interior_botom']['mesh'])) elif 'door top in 1' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['door_interior_top_001']['mesh'])) elif 'door top in' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['door_interior_top']['mesh'])) elif 'bot door' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['gf_elevator']['mesh'])) elif 'botom door half 1' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['exterior_door_botom_001']['mesh'])) elif 'botom door half' in str(blueprint_component): blueprint_component.set_editor_property("static_mesh",unreal.EditorAssetLibrary.load_asset(path_mesh + "/elevator/" + dic_actor['exterior_door_botom']['mesh'])) unreal.EditorLevelLibrary.save_all_dirty_levels() else : for sub_dic in dic_actor : if actual_dic == 'appartement' : createActors(dic_actor[sub_dic] , "/ground_floor/" + actual_dic + "/appartement_plein", sub_dic , path_to_mesh + "/" + actual_dic) elif ('furnitures' in path_actor_level and ('ground_floor' in actual_dic)) : createActors(dic_actor[sub_dic] , '/ground_floor' + path_actor_level , sub_dic , path_to_mesh) elif ('furnitures' in path_actor_level and ('first_floor' in actual_dic)) : createActors(dic_actor[sub_dic] , '/first_floor' + path_actor_level , sub_dic , path_to_mesh) elif (('furnitures' in path_actor_level or 'grapable' in path_actor_level)and 'mesh'in dic_actor[sub_dic]) : createActors(dic_actor[sub_dic] , path_actor_level , sub_dic , path_to_mesh) else : createActors(dic_actor[sub_dic] , path_actor_level + "/" + actual_dic , sub_dic , path_to_mesh + "/" + actual_dic) if __name__=="__main__": createWorld()
# 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()
# coding: utf-8 from asyncio.windows_events import NULL from platform import java_ver 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) 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) 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) ## 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 pyblish.api class ValidateNoDependencies(pyblish.api.InstancePlugin): """Ensure that the uasset has no dependencies The uasset is checked for dependencies. If there are any, the instance cannot be published. """ order = pyblish.api.ValidatorOrder label = "Check no dependencies" families = ["uasset"] hosts = ["unreal"] optional = True def process(self, instance): ar = unreal.AssetRegistryHelpers.get_asset_registry() all_dependencies = [] for obj in instance[:]: asset = ar.get_asset_by_object_path(obj) dependencies = ar.get_dependencies( asset.package_name, unreal.AssetRegistryDependencyOptions( include_soft_package_references=False, include_hard_package_references=True, include_searchable_names=False, include_soft_management_references=False, include_hard_management_references=False )) if dependencies: for dep in dependencies: if str(dep).startswith("/Game/"): all_dependencies.append(str(dep)) if all_dependencies: raise RuntimeError( f"Dependencies found: {all_dependencies}")
# coding: utf-8 import unreal import sys sys.path.append('C:/project/-packages') from PySide import QtGui def __QtAppTick__(delta_seconds): for window in opened_windows: window.eventTick(delta_seconds) def __QtAppQuit__(): unreal.unregister_slate_post_tick_callback(tick_handle) def __QtWindowClosed__(window=None): if window in opened_windows: opened_windows.remove(window) unreal_app = QtGui.QApplication.instance() if not unreal_app: unreal_app = QtGui.QApplication(sys.argv) tick_handle = unreal.register_slate_post_tick_callback(__QtAppTick__) unreal_app.aboutToQuit.connect(__QtAppQuit__) existing_windows = {} opened_windows = [] def spawnQtWindow(desired_window_class=None): window = existing_windows.get(desired_window_class, None) if not window: window = desired_window_class() existing_windows[desired_window_class] = window window.aboutToClose = __QtWindowClosed__ if window not in opened_windows: opened_windows.append(window) window.show() window.activateWindow() # import QtFunctions # reload(QtFunctions) # import QtWindowOne # import QtWindowTwo # import QtWindowThree # QtFunctions.spawnQtWindow(QtWindowOne.QtWindowOne) # QtFunctions.spawnQtWindow(QtWindowTwo.QtWindowTwo) # QtFunctions.spawnQtWindow(QtWindowThree.QtWindowThree)
import json import os.path import re import unreal """Creates Actor blueprint with static mesh components from json. WARNING: Works only in UE 5.1 internal API """ # Change me! DO_DELETE_IF_EXISTS = False ASSET_DIR = "/project/" # ASSET_DIR = "/project/" # ASSET_DIR = "/project/" JSON_FILEPATH = "C:/project/ Projects/project/" \ "MapData/project/.json" ASSET_NAME_OVERRIDE = "" if ASSET_NAME_OVERRIDE: ASSET_NAME = ASSET_NAME_OVERRIDE else: ASSET_NAME = os.path.basename(JSON_FILEPATH).replace(".json", "") BFL = unreal.SubobjectDataBlueprintFunctionLibrary SDS = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) ASSET_PATH = os.path.join(ASSET_DIR, ASSET_NAME) def get_sub_handle_object(sub_handle): obj = BFL.get_object(BFL.get_data(sub_handle)) return obj def add_component(root_data_handle, subsystem, blueprint, new_class, name): sub_handle, fail_reason = subsystem.add_new_subobject( params=unreal.AddNewSubobjectParams( parent_handle=root_data_handle, new_class=new_class, blueprint_context=blueprint ) ) if not fail_reason.is_empty(): raise Exception(f"ERROR from sub_object_subsystem.add_new_subobject: {fail_reason}") subsystem.rename_subobject(handle=sub_handle, new_name=unreal.Text(name)) subsystem.attach_subobject(owner_handle=root_data_handle, child_to_add_handle=sub_handle) obj = BFL.get_object(BFL.get_data(sub_handle)) return sub_handle, obj def create_actor_blueprint(asset_name, asset_dir): factory = unreal.BlueprintFactory() factory.set_editor_property("parent_class", unreal.Actor) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() blueprint = asset_tools.create_asset(asset_name, asset_dir, None, factory) return blueprint def add_components_to_blueprint(blueprint): root_data_handle = SDS.k2_gather_subobject_data_for_blueprint(blueprint)[0] scene_handle, scene = add_component(root_data_handle, SDS, blueprint, unreal.SceneComponent, name="Scene") with open(JSON_FILEPATH, "rb") as f: data = json.load(f) for i, element in enumerate(data): path, transform = element["path"], element["transform"] path = re.search(r"\w+\s(?P<path>[\/\w]+).\w+", path).group("path") if path.startswith("/") and unreal.EditorAssetLibrary.does_asset_exist(path): sub_handle, static_mesh_comp = add_component( scene_handle, subsystem=SDS, blueprint=blueprint, new_class=unreal.StaticMeshComponent, name=f"StaticMesh{i + 1}") assert isinstance(static_mesh_comp, unreal.StaticMeshComponent) mesh = unreal.EditorAssetLibrary.find_asset_data(path).get_asset() static_mesh_comp.set_static_mesh(mesh) static_mesh_comp.set_editor_property( name="relative_location", value=unreal.Vector(transform["loc"][0], transform["loc"][1], transform["loc"][2]) ) static_mesh_comp.set_editor_property( name="relative_rotation", value=unreal.Rotator(pitch=transform["rot"][0], roll=transform["rot"][1], yaw=transform["rot"][2]) ) static_mesh_comp.set_editor_property( name="relative_scale3d", value=unreal.Vector(transform["scale"][0], transform["scale"][1], transform["scale"][2]) ) else: print(f"Error: Asset {path} doesn't exist") unreal.EditorAssetLibrary.save_loaded_asset(blueprint) if unreal.EditorAssetLibrary.does_asset_exist(ASSET_PATH): if DO_DELETE_IF_EXISTS: unreal.EditorAssetLibrary.delete_asset(ASSET_PATH) else: raise FileExistsError(f"This file {ASSET_PATH} already exists") blueprint = create_actor_blueprint(ASSET_NAME, ASSET_DIR) add_components_to_blueprint(blueprint)
import unreal import json unreal.log("Start") json_file = open(".\Light_location.txt",'r') lights = json.load(json_file) json_file.close() print(lights["spotlights"]) print(type(lights["spotlights"][0]['location'])) def convertLocation(location): x = location[0] y = location[1] z = location[2] return x,y,z def spawn_point_lights(pointlight): light_class = unreal.PointLight() # light_class.intensity = 10.0 tx,ty,tz = convertLocation(pointlight['location']) light_location = unreal.Vector(tx,ty,tz) # unreal.EditorLevelLibrary.spawn_actor_from_class(light_class, light_location) light = unreal.EditorLevelLibrary.spawn_actor_from_object(light_class, light_location) light.set_actor_label(pointlight['title']) lightComponent = light.point_light_component lightComponent.set_editor_property("intensity", pointlight['intensity']) lightComponent.set_editor_property("mobility", unreal.ComponentMobility.MOVABLE) print(lightComponent.get_editor_property("mobility")) def spawn_spot_lights(spotlight): light_class = unreal.SpotLight() # light_class.intensity = 10.0 tx,ty,tz = convertLocation(spotlight['location']) light_location = unreal.Vector(tx,ty,tz) # unreal.EditorLevelLibrary.spawn_actor_from_class(light_class, light_location) light = unreal.EditorLevelLibrary.spawn_actor_from_object(light_class, light_location) light.set_actor_label(spotlight['title']) lightComponent = light.spot_light_component lightComponent.set_editor_property("intensity", spotlight['intensity']) lightComponent.set_editor_property("mobility", unreal.ComponentMobility.MOVABLE) print(lightComponent.get_editor_property("mobility")) def spawn_rect_lights(Rectlight): light_class = unreal.RectLight() # light_class.intensity = 10.0 tx,ty,tz = convertLocation(Rectlight['location']) light_location = unreal.Vector(tx,ty,tz) # unreal.EditorLevelLibrary.spawn_actor_from_class(light_class, light_location) light = unreal.EditorLevelLibrary.spawn_actor_from_object(light_class, light_location) light.set_actor_label(Rectlight['title']) lightComponent = light.rect_light_component lightComponent.set_editor_property("intensity", Rectlight['intensity']) lightComponent.set_editor_property("mobility", unreal.ComponentMobility.MOVABLE) print(lightComponent.get_editor_property("mobility")) for i in lights["pointlights"]: spawn_point_lights(i) for i in lights["spotlights"]: spawn_spot_lights(i) for i in lights["rectlights"]: spawn_rect_lights(i)
import unreal def show_toast(message, duration=3.0, color=unreal.LinearColor(0, 1, 0, 1)): #Displays a toast notification in Unreal Editor. unreal.SystemLibrary.print_string(None, message, text_color=color, duration=duration)
import unreal import sys sys.path.append('C:/project/-packages') from PySide import QtGui, QtUiTools WINDOW_NAME = 'Qt Window Three' UI_FILE_FULLNAME = __file__.replace('.py', '.ui') class QtWindowThree(QtGui.QWidget): def __init__(self, parent=None): super(QtWindowThree, self).__init__(parent) self.aboutToClose = None # This is used to stop the tick when the window is closed self.widget = QtUiTools.QUiLoader().load(UI_FILE_FULLNAME) self.widget.setParent(self) self.setWindowTitle(WINDOW_NAME) self.setGeometry(100, 500, self.widget.width(), self.widget.height()) self.initialiseWidget() def closeEvent(self, event): if self.aboutToClose: self.aboutToClose(self) event.accept() def eventTick(self, delta_seconds): self.myTick(delta_seconds) ########################################## def initialiseWidget(self): self.time_while_this_window_is_open = 0.0 self.random_actor = None self.random_actor_is_growing = True self.widget.button_ScaleRandom.clicked.connect(self.scaleRandomActorInScene) def scaleRandomActorInScene(self): import random import WorldFunctions all_actors = WorldFunctions.getAllActors(use_selection = False, actor_class = unreal.StaticMeshActor, actor_tag = None) rand = random.randrange(0, len(all_actors)) self.random_actor = all_actors[rand] def myTick(self, delta_seconds): # Set Time self.time_while_this_window_is_open += delta_seconds self.widget.lbl_Seconds.setText("%.1f Seconds" % self.time_while_this_window_is_open) # Affect Actor if self.random_actor: actor_scale = self.random_actor.get_actor_scale3d() speed = 1.0 * delta_seconds if self.random_actor_is_growing: if actor_scale.z > 4.0: self.random_actor_is_growing = False else: speed = -speed if actor_scale.z < 0.5: self.random_actor_is_growing = True self.random_actor.set_actor_scale3d(unreal.Vector(actor_scale.x + speed, actor_scale.y + speed, actor_scale.z + speed))
import unreal # --- 외부 주입 변수 안내 --- # 이 스크립트는 'execute_copy_with_cn.py'와 'reprocess_selected_materials.py'의 # 실행 계획을 미리 보여줍니다. 실제 실행 스크립트와 동일한 변수들을 설정해야 합니다. # # 예시 (블루프린트의 Execute Python Script 노드의 'Python Script' 핀에 입력): # # # Actor 처리 미리보기용 변수 # output_path = "/project/" # master_path = "/project/" # source_parent_prefix = "Basic_Master_Mat" # suffix = "_CN" # parameters_str = "emissive_color_mult:0.1; Tint:1,0,0,1" # do_reparent = True # do_parameter_edit = True # do_apply_to_actor = True # do_process_static_meshes = True # do_check_source_prefix = True # do_overwrite_existing = False # # # 재처리 미리보기용 변수 (위와 동일한 변수 사용) # # master_path = "..." # # parameters_str = "..." # # do_reparent = True # # do_parameter_edit = True # --- 블루프린트 연동 안내 --- # 이 스크립트는 실행 계획을 문자열(String)으로 반환합니다. # 블루프린트의 'Execute Python Script' 노드의 'Return Value' 핀을 변수에 저장하거나 # 위젯의 텍스트 블록에 직접 연결하여 UI에 미리보기 결과를 표시할 수 있습니다. # 스크립트 실행 결과는 여전히 언리얼의 'Output Log'에도 출력됩니다. def parse_parameters_string(params_string): """ 세미콜론(;)으로 구분된 파라미터 문자열을 파싱합니다. - 스칼라: param_name:0.5 - 벡터: param_name:1,0,0,1 (R,G,B) 또는 (R,G,B,A) - 텍스처: param_name:/project/.MyTexture 예시: "scalar_param:0.5; vector_param:1,0,0,1; texture_param:/project/" """ parsed_params = [] if not params_string or not isinstance(params_string, str): return parsed_params asset_lib = unreal.EditorAssetLibrary pairs = [pair.strip() for pair in params_string.split(';') if pair.strip()] for pair in pairs: if ':' not in pair: continue key, value_str = pair.split(':', 1) key = key.strip() value_str = value_str.strip() if not key or not value_str: continue if value_str.startswith('/Game/') or value_str.startswith('/Engine/'): texture_asset = asset_lib.load_asset(value_str) if isinstance(texture_asset, unreal.Texture): parsed_params.append({'name': key, 'type': '텍스처', 'value': value_str}) else: parsed_params.append({'name': key, 'type': '텍스처', 'value': f"{value_str} (경고: 찾을 수 없음)"}) elif ',' in value_str: try: color_parts = [float(c.strip()) for c in value_str.split(',')] if len(color_parts) in [3, 4]: parsed_params.append({'name': key, 'type': '벡터', 'value': value_str}) else: parsed_params.append({'name': key, 'type': '벡터', 'value': f"{value_str} (경고: 잘못된 형식)"}) except ValueError: parsed_params.append({'name': key, 'type': '벡터', 'value': f"{value_str} (경고: 잘못된 형식)"}) else: try: float(value_str) parsed_params.append({'name': key, 'type': '스칼라', 'value': value_str}) except ValueError: parsed_params.append({'name': key, 'type': '스칼라', 'value': f"{value_str} (경고: 잘못된 형식)"}) return parsed_params def preview_actor_processing_logic(selected_actors, settings): report_lines = [] report_lines.append("==========================================================") report_lines.append(" 액터 기반 머티리얼 처리 작업 미리보기") report_lines.append("==========================================================") asset_lib = unreal.EditorAssetLibrary DESTINATION_FOLDER = settings['output_path'] NEW_PARENT_MATERIAL_PATH = settings['master_path'] SOURCE_PARENT_MATERIAL_PREFIX = settings['source_parent_prefix'] SUFFIX = settings['suffix'] PARAMETERS_TO_SET = settings['parameters_to_set'] DO_REPARENT = settings['do_reparent'] DO_PARAMETER_EDIT = settings['do_parameter_edit'] DO_APPLY_TO_ACTOR = settings['do_apply_to_actor'] DO_PROCESS_STATIC_MESHES = settings['do_process_static_meshes'] DO_CHECK_SOURCE_PREFIX = settings['do_check_source_prefix'] DO_OVERWRITE_EXISTING = settings['do_overwrite_existing'] report_lines.append("주의: 이 스크립트는 실제 작업을 수행하지 않으며, 계획을 출력하기만 합니다.") if not all([DESTINATION_FOLDER, NEW_PARENT_MATERIAL_PATH, SOURCE_PARENT_MATERIAL_PREFIX, SUFFIX]): report_lines.append("미리보기를 위해 output_path, master_path, source_parent_prefix, suffix 변수를 모두 설정해야 합니다.") return "\n".join(report_lines) new_parent_material = asset_lib.load_asset(NEW_PARENT_MATERIAL_PATH) if DO_REPARENT and not new_parent_material: report_lines.append(f"오류: 목표 마스터 머티리얼을 찾을 수 없습니다: {NEW_PARENT_MATERIAL_PATH}") return "\n".join(report_lines) report_lines.append(f"총 {len(selected_actors)}개의 선택된 액터에 대한 처리 계획을 생성합니다.") report_lines.append(f" - 결과물 저장 기본 경로: {DESTINATION_FOLDER}") report_lines.append(f" - 생성될 머티리얼 접미사: {SUFFIX}") if DO_REPARENT: report_lines.append(f" - 목표 마스터 머티리얼: {NEW_PARENT_MATERIAL_PATH}") if DO_CHECK_SOURCE_PREFIX: report_lines.append(f" - 원본 부모 머티리얼 접두사: {SOURCE_PARENT_MATERIAL_PREFIX}") report_lines.append("----------------------------------------------------------") total_materials_to_process = 0 for selected_actor in selected_actors: actor_label = selected_actor.get_actor_label() report_lines.append(f"▶ 액터 '{actor_label}' 처리 계획:") skeletal_mesh_components = selected_actor.get_components_by_class(unreal.SkeletalMeshComponent) static_mesh_components = selected_actor.get_components_by_class(unreal.StaticMeshComponent) if DO_PROCESS_STATIC_MESHES else [] components_to_process = skeletal_mesh_components + static_mesh_components if not components_to_process: report_lines.append(" - 이 액터에는 처리할 스켈레탈 또는 스태틱 메시 컴포넌트가 없습니다.") continue base_name_for_folder = "" for comp in skeletal_mesh_components: if comp.skeletal_mesh: base_name_for_folder = comp.skeletal_mesh.get_name() report_lines.append(f" - 폴더 기준 에셋: 스켈레탈 메시 '{base_name_for_folder}'") break if not base_name_for_folder and DO_PROCESS_STATIC_MESHES: for comp in static_mesh_components: if comp.static_mesh: base_name_for_folder = comp.static_mesh.get_name() report_lines.append(f" - 폴더 기준 에셋: 스태틱 메시 '{base_name_for_folder}'") break if not base_name_for_folder: base_name_for_folder = actor_label report_lines.append(f" - 경고: 기준 에셋을 찾지 못해 액터 이름 '{base_name_for_folder}'을(를) 폴더 이름으로 사용합니다.") clean_base_name = base_name_for_folder.replace(' ', '_') actor_destination_folder = f"{DESTINATION_FOLDER.rstrip('/')}/{clean_base_name}" report_lines.append(f" - 생성/사용될 폴더: '{actor_destination_folder}'") actor_material_count = 0 for mesh_comp in components_to_process: comp_name = mesh_comp.get_name() num_materials = mesh_comp.get_num_materials() if num_materials == 0: continue report_lines.append(f" - 컴포넌트 '{comp_name}':") for index in range(num_materials): material_instance = mesh_comp.get_material(index) if not isinstance(material_instance, unreal.MaterialInstanceConstant): continue mat_name = material_instance.get_name() if mat_name.endswith(SUFFIX): actor_material_count += 1 report_lines.append(f" - [{index}] '{mat_name}' (재처리 대상)") if DO_REPARENT and new_parent_material and material_instance.get_editor_property('parent') != new_parent_material: report_lines.append(f" - [계획] 부모를 '{NEW_PARENT_MATERIAL_PATH}' (으)로 변경합니다.") if DO_PARAMETER_EDIT and PARAMETERS_TO_SET: report_lines.append(f" - [계획] 파라미터를 수정합니다.") if not (DO_REPARENT or DO_PARAMETER_EDIT): report_lines.append(f" - [정보] 재처리 옵션이 꺼져있어 실제 변경은 없습니다.") else: parent_material = material_instance.get_editor_property('parent') if not parent_material: continue if DO_REPARENT and parent_material == new_parent_material: continue if DO_CHECK_SOURCE_PREFIX and not parent_material.get_name().startswith(SOURCE_PARENT_MATERIAL_PREFIX): continue actor_material_count += 1 report_lines.append(f" - [{index}] '{mat_name}' (신규 처리 대상)") new_name = f"{mat_name}{SUFFIX}" new_path = f"{actor_destination_folder.rstrip('/')}/{new_name}" if asset_lib.does_asset_exist(new_path) and not DO_OVERWRITE_EXISTING: report_lines.append(f" - [정보] 이미 존재하는 에셋 '{new_name}'을(를) 재사용/재처리합니다.") elif asset_lib.does_asset_exist(new_path) and DO_OVERWRITE_EXISTING: report_lines.append(f" - [계획] '{new_name}'을(를) 강제로 덮어쓰기 복제합니다.") else: report_lines.append(f" - [계획] '{new_name}' (으)로 신규 복제합니다.") if DO_REPARENT: report_lines.append(f" - [계획] 부모를 '{NEW_PARENT_MATERIAL_PATH}' (으)로 변경합니다.") if DO_PARAMETER_EDIT and PARAMETERS_TO_SET: report_lines.append(f" - [계획] 파라미터를 수정합니다.") if DO_APPLY_TO_ACTOR: report_lines.append(f" - [계획] 처리된 머티리얼을 이 슬롯에 다시 적용합니다.") if actor_material_count == 0: report_lines.append(f" - 이 액터에서 처리할 조건에 맞는 머티리얼을 찾지 못했습니다.") total_materials_to_process += actor_material_count report_lines.append("") report_lines.append("==================== 미리보기 요약 ====================") if total_materials_to_process > 0: report_lines.append(f"총 {len(selected_actors)}개 액터에서 {total_materials_to_process}개의 머티리얼이 처리될 예정입니다.") else: report_lines.append("선택된 액터들에서 처리할 조건에 맞는 머티리얼을 찾지 못했습니다.") report_lines.append("==========================================================") return "\n".join(report_lines) def preview_reprocessing_logic(material_instances, settings): report_lines = [] report_lines.append("==========================================================") report_lines.append(" 콘텐츠 브라우저 기반 재처리 작업 미리보기") report_lines.append("==========================================================") asset_lib = unreal.EditorAssetLibrary NEW_PARENT_MATERIAL_PATH = settings['master_path'] PARAMETERS_TO_SET = settings['parameters_to_set'] DO_REPARENT = settings['do_reparent'] DO_PARAMETER_EDIT = settings['do_parameter_edit'] report_lines.append("주의: 이 스크립트는 실제 작업을 수행하지 않으며, 계획을 출력하기만 합니다.") new_parent_material = None if DO_REPARENT: if not NEW_PARENT_MATERIAL_PATH: report_lines.append("미리보기를 위해 master_path 변수를 설정해야 합니다.") return "\n".join(report_lines) new_parent_material = asset_lib.load_asset(NEW_PARENT_MATERIAL_PATH) if not new_parent_material: report_lines.append(f"오류: 목표 마스터 머티리얼을 찾을 수 없습니다: {NEW_PARENT_MATERIAL_PATH}") return "\n".join(report_lines) report_lines.append(f"총 {len(material_instances)}개의 선택된 머티리얼 인스턴스에 대한 처리 계획을 생성합니다.") if DO_REPARENT: report_lines.append(f" - 목표 마스터 머티리얼: {NEW_PARENT_MATERIAL_PATH}") report_lines.append("----------------------------------------------------------") for mat_instance in material_instances: report_lines.append(f"▶ 머티리얼 '{mat_instance.get_name()}' 처리 계획:") if DO_REPARENT and new_parent_material: if mat_instance.get_editor_property('parent') != new_parent_material: report_lines.append(f" - [계획] 부모를 '{NEW_PARENT_MATERIAL_PATH}' (으)로 변경합니다.") else: report_lines.append(f" - [정보] 부모가 이미 목표와 동일하여 변경하지 않습니다.") if DO_PARAMETER_EDIT and PARAMETERS_TO_SET: report_lines.append(f" - [계획] 다음 파라미터를 수정합니다:") for param_info in PARAMETERS_TO_SET: report_lines.append(f" - {param_info['type']} 파라미터 '{param_info['name']}'의 값을 '{param_info['value']}' (으)로 설정합니다.") if not DO_REPARENT and not DO_PARAMETER_EDIT: report_lines.append(" - [정보] 부모 변경과 파라미터 수정이 모두 비활성화되어, 실제 변경은 없습니다.") report_lines.append("") report_lines.append("==========================================================") return "\n".join(report_lines) def main(): # 전역 네임스페이스에서 변수를 가져옵니다. 없으면 None으로 설정합니다. g = globals() # 미리보기에 필요한 모든 변수 목록 # Actor 처리와 재처리에 공통적으로 필요하거나, 어느 한쪽에만 필요한 모든 변수를 포함합니다. all_vars = { 'output_path', 'master_path', 'source_parent_prefix', 'suffix', 'parameters_str', 'do_reparent', 'do_parameter_edit', 'do_apply_to_actor', 'do_process_static_meshes', 'do_check_source_prefix', 'do_overwrite_existing' } settings = {var: g.get(var) for var in all_vars} # 파라미터 문자열 파싱 settings['parameters_to_set'] = parse_parameters_string(settings.get('parameters_str') or "") editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) util_lib = unreal.EditorUtilityLibrary selected_actors = editor_actor_subsystem.get_selected_level_actors() selected_assets = util_lib.get_selected_assets() report = "" # 1. 액터 선택이 있으면, 액터 처리 로직 미리보기 실행 if selected_actors: report = preview_actor_processing_logic(selected_actors, settings) # 2. 액터 선택이 없고, 콘텐츠 브라우저 에셋 선택이 있으면 재처리 로직 미리보기 실행 elif selected_assets: material_instances = [asset for asset in selected_assets if isinstance(asset, unreal.MaterialInstanceConstant)] if material_instances: report = preview_reprocessing_logic(material_instances, settings) else: report = "콘텐츠 브라우저에 에셋이 선택되었으나, 미리보기를 실행할 머티리얼 인스턴스가 없습니다." # 3. 아무것도 선택되지 않았으면 안내 메시지 출력 else: report = "작업을 미리보기하려면 레벨에서 액터를 선택하거나 콘텐츠 브라우저에서 머티리얼 인스턴스를 선택하세요." # Output Log에도 결과를 출력합니다. unreal.log("--- 스크립트 실행 계획 미리보기 ---") print(report) # 블루프린트에서 사용할 수 있도록 결과를 반환합니다. return report # 스크립트 실행 및 결과 저장을 통해 블루프린트 연동. # main() 함수의 반환값을 전역 변수 'report'에 할당합니다. # 이렇게 하면 블루프린트의 'Execute Python Script' 노드에서 'report'라는 이름의 # 출력 핀을 설정했을 경우, 이 결과 문자열을 정상적으로 가져갈 수 있습니다. report = main()
# -*- coding: utf-8 -*- """ """ from __future__ import division from __future__ import print_function from __future__ import absolute_import __author__ = 'timmyliang' __email__ = '[email protected]' __date__ = '2021-07-22 19:08:16' import unreal @unreal.uclass() class OnAssetSaveValidator(unreal.EditorValidatorBase): @unreal.ufunction(override=True) def can_validate_asset(self,asset): print("can_validate_asset",asset) return super(OnAssetSaveValidator,self).can_validate_asset(asset) validator = OnAssetSaveValidator() validator.set_editor_property("is_enabled",True) validate_subsystem = unreal.get_editor_subsystem(unreal.EditorValidatorSubsystem) validate_subsystem.add_validator(validator)
import unreal def check_selected_stencil(): editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) selected_actors = editor_actor_subsystem.get_selected_level_actors() if not selected_actors: print("⚠️ No actor selected. Please select an actor in the viewport.") return for actor in selected_actors: mesh_components = actor.get_components_by_class(unreal.StaticMeshComponent) if not mesh_components: print(f"❌ No StaticMeshComponent found in selected actor: {actor.get_name()}") continue for mesh_component in mesh_components: stencil_value = mesh_component.get_editor_property("custom_depth_stencil_value") render_custom_depth = mesh_component.get_editor_property("render_custom_depth") print(f"🎯 Selected Actor: {actor.get_name()}") print(f" - Stencil Value: {stencil_value}") print(f" - Custom Depth Enabled: {render_custom_depth}") # Run the function check_selected_stencil()
# This scripts describes the process of capturing an managing properties with a little more # detail than test_variant_manager.py import unreal # Create all assets and objects we'll use lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs) if lvs is None or lvs_actor is None: print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!") quit() var_set1 = unreal.VariantSet() var_set1.set_display_text("My VariantSet") var1 = unreal.Variant() var1.set_display_text("Variant 1") # Adds the objects to the correct parents lvs.add_variant_set(var_set1) var_set1.add_variant(var1) # Spawn a simple cube static mesh actor cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'") spawned_actor = None if cube: location = unreal.Vector() rotation = unreal.Rotator() spawned_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(cube, location, rotation) spawned_actor.set_actor_label("Cube Actor") else: print ("Failed to find Cube asset!") if spawned_actor is None: print ("Failed to spawn an actor for the Cube asset!") quit() # Bind spawned_actor to all our variants var1.add_actor_binding(spawned_actor) # See which properties can be captured from any StaticMeshActor capturable_by_class = unreal.VariantManagerLibrary.get_capturable_properties(unreal.StaticMeshActor.static_class()) # See which properties can be captured from our specific spawned_actor # This will also return the properties for any custom component structure we might have setup on the actor capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(spawned_actor) print ("Capturable properties for actor '" + spawned_actor.get_actor_label() + "':") for prop in capturable_props: print ("\t" + prop) print ("Capturable properties for its class:") for prop in capturable_by_class: print ("\t" + prop) # Returns nullptr for invalid paths. This will also show an error in the Output Log prop1 = var1.capture_property(spawned_actor, "False property path") assert prop1 is None # Comparison is case insensitive: The property is named "Can be Damaged", but this still works prop2 = var1.capture_property(spawned_actor, "cAn Be DAMAged") assert prop2 is not None and prop2.get_full_display_string() == "Can be Damaged" # Attempts to capture the same property more than once are ignored, and None is returned prop2attempt2 = var1.capture_property(spawned_actor, "Can Be Damaged") assert prop2attempt2 is None # Check which properties have been captured for some actor in a variant print ("Captured properties for '" + spawned_actor.get_actor_label() + "' so far:") captured_props = var1.get_captured_properties(spawned_actor) for captured_prop in captured_props: print ("\t" + captured_prop.get_full_display_string()) # Capture property in a component prop3 = var1.capture_property(spawned_actor, "Static Mesh Component / Relative Location") assert prop3 is not None and prop3.get_full_display_string() == "Static Mesh Component / Relative Location" # Can't capture the component itself. This will also show an error in the Output Log prop4 = var1.capture_property(spawned_actor, "Static Mesh Component") assert prop4 is None # Capture material property prop5 = var1.capture_property(spawned_actor, "Static Mesh Component / Material[0]") assert prop5 is not None # Removing property captures var1.remove_captured_property(spawned_actor, prop2) var1.remove_captured_property_by_name(spawned_actor, "Static Mesh Component / Relative Location") print ("Captured properties for '" + spawned_actor.get_actor_label() + "' at the end:") captured_props = var1.get_captured_properties(spawned_actor) for captured_prop in captured_props: print ("\t" + captured_prop.get_full_display_string()) # Should only have the material property left assert len(captured_props) == 1 and captured_props[0].get_full_display_string() == "Static Mesh Component / Material[0]"
# This scripts describes the process of capturing an managing properties with a little more # detail than test_variant_manager.py import unreal # Create all assets and objects we'll use lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs) if lvs is None or lvs_actor is None: print ("Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!") quit() var_set1 = unreal.VariantSet() var_set1.set_display_text("My VariantSet") var1 = unreal.Variant() var1.set_display_text("Variant 1") # Adds the objects to the correct parents lvs.add_variant_set(var_set1) var_set1.add_variant(var1) # Spawn a simple cube static mesh actor cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'") spawned_actor = None if cube: location = unreal.Vector() rotation = unreal.Rotator() spawned_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(cube, location, rotation) spawned_actor.set_actor_label("Cube Actor") else: print ("Failed to find Cube asset!") if spawned_actor is None: print ("Failed to spawn an actor for the Cube asset!") quit() # Bind spawned_actor to all our variants var1.add_actor_binding(spawned_actor) # See which properties can be captured from any StaticMeshActor capturable_by_class = unreal.VariantManagerLibrary.get_capturable_properties(unreal.StaticMeshActor.static_class()) # See which properties can be captured from our specific spawned_actor # This will also return the properties for any custom component structure we might have setup on the actor capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(spawned_actor) print ("Capturable properties for actor '" + spawned_actor.get_actor_label() + "':") for prop in capturable_props: print ("\t" + prop) print ("Capturable properties for its class:") for prop in capturable_by_class: print ("\t" + prop) # Returns nullptr for invalid paths. This will also show an error in the Output Log prop1 = var1.capture_property(spawned_actor, "False property path") assert prop1 is None # Comparison is case insensitive: The property is named "Can be Damaged", but this still works prop2 = var1.capture_property(spawned_actor, "cAn Be DAMAged") assert prop2 is not None and prop2.get_full_display_string() == "Can be Damaged" # Attempts to capture the same property more than once are ignored, and None is returned prop2attempt2 = var1.capture_property(spawned_actor, "Can Be Damaged") assert prop2attempt2 is None # Check which properties have been captured for some actor in a variant print ("Captured properties for '" + spawned_actor.get_actor_label() + "' so far:") captured_props = var1.get_captured_properties(spawned_actor) for captured_prop in captured_props: print ("\t" + captured_prop.get_full_display_string()) # Capture property in a component prop3 = var1.capture_property(spawned_actor, "Static Mesh Component / Relative Location") assert prop3 is not None and prop3.get_full_display_string() == "Static Mesh Component / Relative Location" # Can't capture the component itself. This will also show an error in the Output Log prop4 = var1.capture_property(spawned_actor, "Static Mesh Component") assert prop4 is None # Capture material property prop5 = var1.capture_property(spawned_actor, "Static Mesh Component / Material[0]") assert prop5 is not None # Removing property captures var1.remove_captured_property(spawned_actor, prop2) var1.remove_captured_property_by_name(spawned_actor, "Static Mesh Component / Relative Location") print ("Captured properties for '" + spawned_actor.get_actor_label() + "' at the end:") captured_props = var1.get_captured_properties(spawned_actor) for captured_prop in captured_props: print ("\t" + captured_prop.get_full_display_string()) # Should only have the material property left assert len(captured_props) == 1 and captured_props[0].get_full_display_string() == "Static Mesh Component / Material[0]"
""" Unreal Engine Python integration for real-time scene manipulation """ import asyncio import subprocess import json from typing import Optional, Dict, Any, List from pathlib import Path from loguru import logger from config.settings import settings class UnrealIntegration: """Integration with Unreal Engine for real-time scene control""" def __init__(self): self.unreal_process: Optional[subprocess.Popen] = None self.is_running = False self.scene_objects = [] self.current_lighting = "white" async def initialize(self): """Initialize Unreal Engine integration""" logger.info("Initializing Unreal Engine integration...") # Check if Unreal Engine path exists if not settings.UNREAL_ENGINE_PATH or not Path(settings.UNREAL_ENGINE_PATH).exists(): logger.warning("Unreal Engine path not configured or doesn't exist") return False # For now, we'll simulate the integration # In a real implementation, you would: # 1. Start Unreal Engine with Python scripting enabled # 2. Establish communication channel (TCP, UDP, or file-based) # 3. Load your project with the appropriate Python scripts self.is_running = True logger.info("Unreal Engine integration initialized (simulated)") return True async def start_monitoring(self): """Start monitoring loop for Unreal Engine""" while self.is_running: try: # Monitor Unreal Engine status await self.check_engine_status() await asyncio.sleep(1.0) # Check every second except asyncio.CancelledError: break except Exception as e: logger.error(f"Error in Unreal monitoring loop: {e}") await asyncio.sleep(5.0) # Wait before retrying async def check_engine_status(self): """Check if Unreal Engine is still running""" # In a real implementation, this would ping the Unreal Engine process # or check the communication channel pass async def spawn_object(self, object_type: str, location: tuple = (0, 0, 100)) -> bool: """Spawn an object in the Unreal Engine scene""" if not self.is_running: logger.error("Unreal Engine not running") return False valid_objects = ["cube", "sphere", "cylinder", "cone", "plane"] if object_type.lower() not in valid_objects: logger.warning(f"Invalid object type: {object_type}. Valid types: {valid_objects}") return False try: # In a real implementation, this would send a command to Unreal Engine # For example, using a TCP socket or writing to a command file object_data = { "type": object_type, "location": location, "timestamp": asyncio.get_event_loop().time() } self.scene_objects.append(object_data) # Simulate the action await self._send_unreal_command("spawn_object", object_data) logger.info(f"Spawned {object_type} at location {location}") return True except Exception as e: logger.error(f"Failed to spawn object: {e}") return False async def change_lighting(self, color: str) -> bool: """Change the lighting color in the scene""" if not self.is_running: logger.error("Unreal Engine not running") return False valid_colors = ["red", "green", "blue", "white", "yellow", "purple", "orange"] if color.lower() not in valid_colors: logger.warning(f"Invalid color: {color}. Valid colors: {valid_colors}") return False try: # Color mapping to RGB values color_map = { "red": (1.0, 0.0, 0.0), "green": (0.0, 1.0, 0.0), "blue": (0.0, 0.0, 1.0), "white": (1.0, 1.0, 1.0), "yellow": (1.0, 1.0, 0.0), "purple": (1.0, 0.0, 1.0), "orange": (1.0, 0.5, 0.0) } rgb_color = color_map[color.lower()] lighting_data = { "color": color.lower(), "rgb": rgb_color, "intensity": 1.0 } await self._send_unreal_command("change_lighting", lighting_data) self.current_lighting = color.lower() logger.info(f"Changed lighting to {color} (RGB: {rgb_color})") return True except Exception as e: logger.error(f"Failed to change lighting: {e}") return False async def move_camera(self, position: tuple, rotation: tuple = (0, 0, 0)) -> bool: """Move the camera to a new position""" if not self.is_running: return False try: camera_data = { "position": position, "rotation": rotation } await self._send_unreal_command("move_camera", camera_data) logger.info(f"Moved camera to position {position} with rotation {rotation}") return True except Exception as e: logger.error(f"Failed to move camera: {e}") return False async def clear_scene(self) -> bool: """Clear all spawned objects from the scene""" if not self.is_running: return False try: await self._send_unreal_command("clear_scene", {}) self.scene_objects.clear() logger.info("Cleared all objects from scene") return True except Exception as e: logger.error(f"Failed to clear scene: {e}") return False async def get_scene_info(self) -> Dict[str, Any]: """Get information about the current scene""" return { "is_running": self.is_running, "object_count": len(self.scene_objects), "objects": self.scene_objects, "current_lighting": self.current_lighting } async def _send_unreal_command(self, command: str, data: Dict[str, Any]): """Send a command to Unreal Engine""" # In a real implementation, this would: # 1. Serialize the command and data to JSON # 2. Send it via TCP socket, UDP, or write to a file # 3. Unreal Engine would have a Python script reading these commands command_data = { "command": command, "data": data, "timestamp": asyncio.get_event_loop().time() } # Simulate sending command logger.debug(f"Sending Unreal command: {json.dumps(command_data, indent=2)}") # Add a small delay to simulate network communication await asyncio.sleep(0.1) def create_unreal_python_script(self) -> str: """Generate a Python script for Unreal Engine to handle commands""" script = ''' import unreal import json import time import threading from pathlib import Path class UnrealCommandHandler: def __init__(self): self.command_file = Path("C:/project/.json") self.running = True def start_monitoring(self): """Start monitoring for commands""" thread = threading.Thread(target=self._monitor_commands) thread.daemon = True thread.start() def _monitor_commands(self): """Monitor for command files""" while self.running: try: if self.command_file.exists(): with open(self.command_file, 'r') as f: command_data = json.load(f) self._process_command(command_data) self.command_file.unlink() # Delete processed command time.sleep(0.1) # Check every 100ms except Exception as e: print(f"Error processing command: {e}") def _process_command(self, command_data): """Process a command from Python""" command = command_data.get("command") data = command_data.get("data", {}) if command == "spawn_object": self._spawn_object(data) elif command == "change_lighting": self._change_lighting(data) elif command == "move_camera": self._move_camera(data) elif command == "clear_scene": self._clear_scene(data) def _spawn_object(self, data): """Spawn an object in the scene""" object_type = data.get("type", "cube") location = data.get("location", (0, 0, 100)) # Map object types to Unreal Engine classes object_classes = { "cube": "/project/.Cube", "sphere": "/project/.Sphere", "cylinder": "/project/.Cylinder" } if object_type in object_classes: asset_path = object_classes[object_type] actor_class = unreal.EditorAssetLibrary.load_asset(asset_path) if actor_class: world = unreal.EditorLevelLibrary.get_editor_world() spawn_location = unreal.Vector(location[0], location[1], location[2]) unreal.EditorLevelLibrary.spawn_actor_from_class( actor_class, spawn_location ) def _change_lighting(self, data): """Change the lighting in the scene""" color = data.get("rgb", (1, 1, 1)) # Find directional light in the scene actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actors: if isinstance(actor, unreal.DirectionalLight): light_component = actor.get_component_by_class(unreal.DirectionalLightComponent) if light_component: light_color = unreal.LinearColor(color[0], color[1], color[2], 1.0) light_component.set_light_color(light_color) def _move_camera(self, data): """Move the camera""" position = data.get("position", (0, 0, 0)) rotation = data.get("rotation", (0, 0, 0)) # This would move the active viewport camera # Implementation depends on your specific needs def _clear_scene(self, data): """Clear spawned objects from scene""" # This would identify and remove dynamically spawned objects # Implementation depends on how you track spawned objects # Start the command handler handler = UnrealCommandHandler() handler.start_monitoring() print("Unreal Engine Python command handler started!") ''' return script async def cleanup(self): """Clean up Unreal Engine integration""" self.is_running = False if self.unreal_process: try: self.unreal_process.terminate() self.unreal_process.wait(timeout=10) except subprocess.TimeoutExpired: self.unreal_process.kill() except Exception as e: logger.error(f"Error terminating Unreal process: {e}") logger.info("Unreal Engine integration cleaned up")
# 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]
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/project/-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unreal import re import json import pathlib from typing import Optional # Ugly script that was used to clean a repository after a few lazy marketplace asset imports added 27G of # content to repository which exceeded the free limit on github ... and all sense of reasonableness. # This script was used to clean up and rewrite the git history to remove assets that were never used. # DO NOT look for inspiration here. It is layers of hacks, evolving on layers of other hacks. def find_unreferenced_assets(report_path: str, base_path: str, entry_points: set[str], **kwargs: dict[str, str]) -> [ str]: editor_asset = unreal.EditorAssetLibrary() editor_actor_lib = unreal.EditorActorSubsystem() asset_registry = unreal.AssetRegistryHelpers().get_asset_registry() options = unreal.AssetRegistryDependencyOptions() options.include_searchable_names = True options.include_hard_management_references = True options.include_hard_package_references = True options.include_soft_management_references = True options.include_soft_package_references = True referencer_cache_file: Optional[str] = kwargs["referencer_cache_file"] if "referencer_cache_file" in kwargs else None dependencies_cache_file: Optional[str] = kwargs["dependencies_cache_file"] if "dependencies_cache_file" in kwargs else None actors_cache_file: Optional[str] = kwargs["actors_cache_file"] if "actors_cache_file" in kwargs else None extra_unused: [str] = kwargs["extra_unused"] if "extra_unused" in kwargs else [] asset_names = editor_asset.list_assets(base_path) asset_to_referencers: dict[str, set[str]] = {} asset_to_dependencies: dict[str, set[str]] = {} # This section will build up a map of assets to their dependencies and assets to their users with unreal.ScopedSlowTask(len(asset_names), 'Calculating Top-Level Unused Assets') as slow_task: # Make the dialog visible slow_task.make_dialog(True) for asset_name in asset_names: # If user has requested operation cancelled then abort if slow_task.should_cancel(): break asset_path = asset_name[:asset_name.rindex('.')] asset = editor_asset.load_asset(asset_path) if not asset: unreal.log_warning(f"\n\n\n\nUUR: Unable to load asset: {asset_path}\n\n\n\n") continue else: dependencies = asset_registry.get_dependencies(unreal.Name(asset.get_package().get_path_name()), options) if asset_path not in asset_to_dependencies: asset_to_dependencies[asset_path] = set() for dependency in dependencies: asset_reference = str(dependency) asset_to_dependencies[asset_path].add(asset_reference) referencers = asset_registry.get_referencers(unreal.Name(asset.get_package().get_path_name()), options) if asset_path not in asset_to_referencers: asset_to_referencers[asset_path] = set() for asset_reference in referencers: asset_reference = str(asset_reference) asset_to_referencers[asset_path].add(asset_reference) slow_task.enter_progress_frame(1, f"🔨 : {asset_path}") actor_classnames = set() # Assume all actors in the current level are entry points we care about actors = editor_actor_lib.get_all_level_actors() for actor in actors: actor_class_name = actor.get_class().get_path_name() actor_classnames.add(actor_class_name[:actor_class_name.rindex('.')]) if referencer_cache_file: with open(referencer_cache_file, 'w') as f: output = {} for asset_name, referencers in asset_to_referencers.items(): output[asset_name] = list(referencers) f.write(json.dumps(output, indent=2)) if dependencies_cache_file: with open(dependencies_cache_file, 'w') as f: output = {} for asset_name, dependencies in asset_to_dependencies.items(): output[asset_name] = list(dependencies) f.write(json.dumps(output, indent=2)) if actors_cache_file: with open(actors_cache_file, 'w') as f: f.write(json.dumps(list(actor_classnames), indent=2)) return generate_report(referencer_cache_file, dependencies_cache_file, actors_cache_file, extra_unused, report_path, base_path, entry_points) def generate_report(referencer_cache_file: str, dependencies_cache_file: str, actors_cache_file: str, extra_unused: [str], report_path: str, base_path: str, entry_points: set[str]) -> [str]: asset_to_referencers = {} asset_to_dependencies = {} with open(referencer_cache_file, 'r') as f: contents = "".join(f.readlines()) inputs: dict[str, [str]] = json.loads(contents) for asset_name, referencers in inputs.items(): asset_to_referencers[asset_name] = set(referencers) with open(dependencies_cache_file, 'r') as f: contents = "".join(f.readlines()) inputs: dict[str, [str]] = json.loads(contents) for asset_name, dependencies in inputs.items(): asset_to_dependencies[asset_name] = set(dependencies) with open(actors_cache_file, 'r') as f: contents = "".join(f.readlines()) actor_classnames = set(json.loads(contents)) unreferenced = calculate_unused_asset_paths(actor_classnames, asset_to_dependencies.keys(), asset_to_referencers, extra_unused, entry_points) with open(report_path, 'w') as f: for asset_name in sorted(unreferenced): if asset_name.startswith(base_path): f.write(f'{asset_name}\n') return unreferenced def calculate_unused_asset_paths(actor_classnames: [str], asset_names: [str], asset_to_referencers: dict[str, [str]], extra_unused: [str], entry_points: set[str]) -> [str]: unreferenced_asset_paths = set(extra_unused) used_asset_paths = set() local_entry_points = set() pattern_entry_points = set() for entry_point in entry_points: if '*' in entry_point: pattern_entry_points.add(entry_point) else: local_entry_points.add(entry_point) for actor_classname in actor_classnames: local_entry_points.add(actor_classname) with unreal.ScopedSlowTask(len(asset_names), 'Tracing dependencies') as slow_task: # Make the dialog visible slow_task.make_dialog(True) change_made = True while change_made: unreal.log("Tracing dependencies iteration...") change_made = False for asset_path in sorted(asset_to_referencers.keys()): asset_referencers = asset_to_referencers[asset_path] if asset_path in unreferenced_asset_paths or asset_path in used_asset_paths: # If we have already made a decision about this asset then skip it pass elif asset_path in local_entry_points: # If asset is a known entrypoint then skip it used_asset_paths.add(asset_path) change_made = True print(f"Found Local Entry Point: {asset_path} ") else: pattern_matched = False for pattern in pattern_entry_points: if not pattern_matched and re.search(pattern, asset_path): # If asset is a known entrypoint then skip it used_asset_paths.add(asset_path) change_made = True pattern_matched = True print(f"Found Entry Point via pattern {pattern}: {asset_path} ") # if we did not match a pattern, and we have no references then mark as unreferenced if not pattern_matched and 0 == len(asset_referencers): unreferenced_asset_paths.add(asset_path) print(f"No referencers: {asset_path} ") change_made = True else: for asset_referencer in asset_referencers: if asset_referencer in used_asset_paths: # This asset is referenced by an asset that is used then mark it as used if not asset_path in used_asset_paths: used_asset_paths.add(asset_path) print(f"Referencer {asset_referencer} used so marking as used: {asset_path} ") change_made = True continue # For any asset that was not marked as used or unused then they have no explicit dependencies # from anything marked as explicitly used so mark them as unused for asset_path in sorted(asset_to_referencers.keys()): if asset_path not in unreferenced_asset_paths and asset_path not in used_asset_paths: unreferenced_asset_paths.add(asset_path) print(f"Reference neither used nor unused. Marking as unused: {asset_path} ") return unreferenced_asset_paths def chunker(seq, size): return (seq[pos:pos + size] for pos in range(0, len(seq), size)) def generate_clean_script(unused_assets_file: str, extra_unused_assets_file: str, filter_repo_script: str, clean_script: str, keep_prefix: str): output = '' files = [] with open(unused_assets_file, 'r') as f: files.extend(f.readlines()) with open(extra_unused_assets_file, 'r') as f: files.extend(f.readlines()) for group in chunker(files, 30): args = ['python', filter_repo_script] for f in group: if f.startswith(keep_prefix): continue f = f.rstrip() relative_filename = f.replace('/Game', 'Content') if '' == pathlib.Path(relative_filename).suffix: relative_filename += '.uasset' args.append('--path') args.append(relative_filename) args.append('--invert-paths') args.append('--force') output += ' '.join(args) + '\n' output += 'if %errorlevel% neq 0 exit /b %errorlevel%\n' with open(clean_script, 'w') as f: f.write(output) if __name__ == "__main__": _report_path = r'/project/.txt' _clean_script = r'/project/.bat' _extra_unused_assets_file = r'/project/.txt' _filter_repo_script = r'/project/-filter-repo.py' _base_path = "/Game/" _keep_prefix = '/project/' _entry_points = {'/project/', '^/project/.*$', '^/project/.*$', '^/project/.*$', '/project/', '/project/'} _actors_cache_file = r"/project/.json" _referencer_cache_file = r"/project/.json" _dependencies_cache_file = r"/project/.json" _extra_unused = ['Content/project/.fbx', 'Content/project/.tga', 'Content/project/.tga', 'Content/project/.tga', 'Content/project/.tga', 'Content/project/.tga', 'Content/project/.umap', 'Content/project/.txt'] # find_unreferenced_assets(_report_path, # _base_path, # _entry_points, # extra_unused=_extra_unused, # referencer_cache_file=_referencer_cache_file, # dependencies_cache_file=_dependencies_cache_file, # actors_cache_file=_actors_cache_file) # generate_report(_referencer_cache_file, # _dependencies_cache_file, # _actors_cache_file, # _extra_unused, # _report_path, # _base_path, # _entry_points) generate_clean_script(_report_path, _extra_unused_assets_file, _filter_repo_script, _clean_script, _keep_prefix)
import unreal import os import json import shutil ### Setup paths here ### sequencer_asset_path = '/project/.Master' output_folder = 'Y:/project/' ### End of setup ### ### Set export options ### json_file = os.path.join(output_folder, 'shots_data.json') export_options = unreal.FbxExportOption() export_options.ascii = False export_options.level_of_detail = False export_options.collision = False export_options.vertex_color = False export_options.fbx_export_compatibility = unreal.FbxExportCompatibility.FBX_2020 world = unreal.EditorLevelLibrary.get_editor_world() master_sequence = unreal.load_asset(sequencer_asset_path, unreal.LevelSequence) tracks = master_sequence.get_master_tracks() sections = tracks[0].get_sections() shots_data = [] # create or clear output folder if os.path.isdir(output_folder): shutil.rmtree(output_folder) os.makedirs(output_folder) else: os.makedirs(output_folder) # write shot json data for section in sections: shot = section.get_shot_display_name() shot = shot.split('_')[0] output_file = os.path.join(output_folder, shot + '.fbx') section_start = section.get_start_frame() section_end = section.get_end_frame() section_length = section_end - section_start sequence = section.get_editor_property('sub_sequence') bindings = sequence.get_bindings() unreal.SequencerTools.export_fbx(world, sequence, bindings, export_options, output_file) start = sequence.get_playback_start() end = sequence.get_playback_end() data = { 'shot': shot, 'start': start, 'end': start + section_length, } shots_data.append(data) with open(json_file, 'w') as file: json.dump(shots_data, file)
from operator import itemgetter from typing import Any, Optional import unreal from unreal import PrimalDinoCharacter, PrimalItem from clean_numbers import clean_float as cf, clean_double as cd __all__ = [ 'gather_breeding_data', ] def gather_breeding_data(char_props: PrimalDinoCharacter) -> dict[str, Any]: data: dict[str, Any] = dict(gestationTime=0, incubationTime=0) gestation_breeding = char_props.use_baby_gestation fert_eggs = char_props.fertilized_egg_items_to_spawn fert_egg_weights = char_props.fertilized_egg_weights_to_spawn if gestation_breeding: gestation_speed = round(char_props.baby_gestation_speed, 6) extra_gestation_speed_m = round(char_props.extra_baby_gestation_speed_multiplier, 6) try: data['gestationTime'] = cd(1 / gestation_speed / extra_gestation_speed_m) except ZeroDivisionError: unreal.log_error(f"Species {char_props.get_full_name()} tried dividing by zero for its gestationTime") elif fert_eggs and fert_eggs: eggs = [] for index, egg in enumerate(fert_eggs): weight = fert_egg_weights[index] if fert_egg_weights else 1 # Verify the egg is a valid Object and that weight isn't 0 if str(egg) == 'None' or weight == 0: continue eggs.append((egg, weight)) # Sort eggs by highest weighting eggs.sort(reverse=True, key=itemgetter(1)) if eggs: # We only provide the highest possibility egg to ASB egg: Optional[PrimalItem] = None try: egg = unreal.get_default_object(eggs[0][0]) except Exception as e: unreal.log_error(f"Error loading egg: {e}") if egg: egg_decay = round(egg.egg_lose_durability_per_second, 6) extra_egg_decay_m = round(egg.extra_egg_lose_durability_per_second_multiplier, 6) # 'incubationTime' = 100 / (Egg Lose Durability Per Second × Extra Egg Lose Durability Per Second Multiplier) try: data['incubationTime'] = cd(100 / egg_decay / extra_egg_decay_m) except ZeroDivisionError: unreal.log_warning( f"Species {char_props.get_full_name()} tried dividing by zero for its incubationTime") data['eggTempMin'] = cd(egg.egg_min_temperature) data['eggTempMax'] = cd(egg.egg_max_temperature) # 'maturationTime' = 1 / (Baby Age Speed × Extra Baby Age Speed Multiplier) baby_age_speed = round(char_props.baby_age_speed, 6) extra_baby_age_speed_m = round(char_props.extra_baby_age_speed_multiplier, 6) try: data['maturationTime'] = cd(1 / baby_age_speed / extra_baby_age_speed_m) except ZeroDivisionError: unreal.log_warning(f"Species {char_props.get_full_name()} tried dividing by zero for its maturationTime") data['matingCooldownMin'] = cd(char_props.new_female_min_time_between_mating) data['matingCooldownMax'] = cd(char_props.new_female_max_time_between_mating) return data
#! /project/ python # -*- coding: utf-8 -*- """ Module that contains ueGear Commands """ from __future__ import print_function, division, absolute_import import os import ast import importlib import unreal from . import helpers, mayaio, structs, tag, assets, actors, textures, sequencer # TODO: For some reason, unreal.Array(float) parameters defined within ufunction params argument are not # TODO: with the correct number of elements within the list. As a temporal workaround, we convert them # TODO: to strings in the client side and we parse them here. # TODO: Update this once fix is done in Remote Control plugin. @unreal.uclass() class PyUeGearUICommands(unreal.UeGearCommands): @unreal.ufunction(override=True, meta=dict(Catergory="ueGear Commands")) def generate_uegear_ui(self): """ """ widget_name = 'ueGear_ui' asset_path = f'/project/{widget_name}' asset_widget = unreal.EditorAssetLibrary.load_asset(asset_path) edit_utils = unreal.get_editor_subsystem(unreal.EditorUtilitySubsystem) edit_utils.spawn_and_register_tab(asset_widget) @unreal.uclass() class PyUeGearCommands(unreal.BlueprintFunctionLibrary): @unreal.ufunction(ret=str, static=True, meta=dict(Category="ueGear Commands")) def get_unreal_version(): return unreal.SystemLibrary.get_engine_version() @unreal.ufunction(meta=dict(Category="ueGear Commands")) def import_maya_data(self): """ Opens a file window that allow users to choose a JSON file that contains all the info needed to import asset or layout data. """ mayaio.import_data() @unreal.ufunction(meta=dict(Category="ueGear Commands")) def import_maya_layout(self): """ Opens a file window that allow users to choose a JSON file that contains layout data to load. """ mayaio.import_layout_from_file() @unreal.ufunction(meta=dict(Category="ueGear Commands")) def export_unreal_layout(self): """ Exports a layout JSON file based on the objects on the current Unreal level. """ mayaio.export_layout_file() # ================================================================================================================== # PATHS # ================================================================================================================== @unreal.ufunction(ret=str, static=True, meta=dict(Category="ueGear Commands")) def project_content_directory(): """ Returns the content directory of the current game. :return: content directory. :rtype: str """ # Gets the path relative to the project path = unreal.Paths.project_content_dir() # Standardises the path, removing any extra data return unreal.Paths.make_standard_filename(path) @unreal.ufunction( params=[bool], ret=unreal.Array(str), static=True, meta=dict(Category="ueGear Commands") ) def selected_content_browser_directory(relative=False): """ Returns the selected directory in the Content Browser. :return: selected directory. :rtype: str """ unreal_array = unreal.Array(str) paths = assets.get_selected_folders(relative) for path in paths: unreal_array.append(path) return unreal_array @unreal.ufunction( ret=str, static=True, meta=dict(Category="ueGear Commands") ) def get_mgear_gnx_path(): """ NOTE: Currently this is not being used in the Editor Utility Widget, as the UE widgets has a refresh issue. https://forums.unrealengine.com/project/-blueprint-nodes-defined-in-python-need-to-be-refreshed-every-time-i-reopen-the-editor/project/ """ import tkinter as tk from tkinter import filedialog # Hides the root window root = tk.Tk() root.withdraw() file_path = filedialog.askopenfilename( title="Select a mGear GNX file", filetypes=[("GNX files", "*.gnx"), ("All files", "*.*")], defaultextension=".gnx" ) return file_path # ================================================================================================================== # ASSETS # ================================================================================================================== @unreal.ufunction( params=[str], ret=bool, static=True, meta=dict(Category="ueGear Commands"), ) def does_asset_exist(asset_path=""): """ Returns whether asset exists at given path. :return: True if asset exists; False otherwise. :rtype: bool """ return assets.asset_exists(asset_path) @unreal.ufunction( params=[str], ret=str, static=True, meta=dict(Category="ueGear Commands"), ) def asset_export_path(asset_path): """ Returns the path where the asset was originally exported. """ return assets.get_export_path(asset_path) @unreal.ufunction( params=[str], ret=unreal.Array(structs.AssetExportData), static=True, meta=dict(Category="ueGear Commands"), ) def export_selected_assets(directory): """ Export into given directory current Content Browser selected assets. :param str directory: directory where assets will be exported. :return: list of asset export data struct instances. :rtype: list(structs.AssetExportData) """ return mayaio.export_assets(directory) @unreal.ufunction( params=[str], ret=unreal.Array(structs.AssetExportData), static=True, meta=dict(Category="ueGear Commands"), ) def export_selected_sequencer_cameras(directory): """ Export selected Cameras from LevelSequencer. :param str directory: directory where assets will be exported. :return: :rtype: """ meta_data = [] # Validate directory, as osx required the path to end in a / directory = os.path.join(directory, "") level_sequencer_path_name = sequencer.get_current_level_sequence().get_path_name() # Gets the framerate of the Sequencer. fps = sequencer.get_framerate(sequencer.get_current_level_sequence()) camera_bindings = sequencer.get_selected_cameras() if not camera_bindings: return [] fbx_paths = sequencer.export_fbx_bindings(camera_bindings, directory) for binding, path in zip(camera_bindings, fbx_paths): asset_export_data = structs.AssetExportData() asset_export_data.name = binding.get_name() asset_export_data.path = level_sequencer_path_name asset_export_data.asset_type = "camera" asset_export_data.fbx_file = path meta_data.append(asset_export_data) return meta_data @unreal.ufunction( ret=int, static=True, meta=dict(Category="ueGear Commands") ) def get_selected_sequencer_fps(): """ Returns the active Sequencer's fps """ return sequencer.get_framerate(sequencer.get_current_level_sequence()) @unreal.ufunction( params=[str, str, str], static=True, meta=dict(Category="ueGear Commands"), ) def update_sequencer_camera_from_maya(camera_name, sequencer_package, fbx_path): """ Updates the camera in the specified LevelSequencer :param str camera_name: The name of the camera that exists on the level sequnce. :param str sequencer_package: The package path to the sequencer file. :param str fbx_path: Location of the fbx camera. """ levelsequencer = sequencer.open_sequencer(sequencer_package) sequencer.import_fbx_camera(name=camera_name, sequence=levelsequencer, fbx_path=fbx_path) # ================================================================================================================== # ACTORS # ================================================================================================================== @unreal.ufunction( params=[str, str, str, str, str], static=True, meta=dict(Category="ueGear Commands"), ) def set_actor_world_transform(actor_guid, translation, rotation, scale, world_up): """ Sect the world transform of the actor with given GUID withing current opened level. :param str translation: actor world translation as a string [float, float, float] . :param str rotation: actor world rotation as a string [float, float, float]. :param str scale: actor world scale as a string [float, float, float]. :param str world_up: describes mayas world up axis. """ found_actor = actors.get_actor_by_guid_in_current_level(actor_guid) if not found_actor: unreal.log_warning( 'No Actor found with guid: "{}"'.format(actor_guid) ) return maya_transform = unreal.Transform() rotation = ast.literal_eval(rotation) maya_transform.rotation = unreal.Rotator(rotation[0], rotation[1], rotation[2]).quaternion() maya_transform.translation = unreal.Vector(*ast.literal_eval(translation)) maya_transform.scale3d = unreal.Vector(*ast.literal_eval(scale)) ue_transform = mayaio.convert_transform_maya_to_unreal(maya_transform, world_up) found_actor.set_actor_transform(ue_transform, False, False) # ================================================================================================================== # STATIC MESHES # ================================================================================================================== @unreal.ufunction( params=[str, str, str], ret=str, static=True, meta=dict(Category="ueGear Commands"), ) def import_static_mesh(fbx_file, import_path, import_options): """ Imports skeletal mesh from FBX file. :param str fbx_file: skeletal mesh FBX file path. :param str import_path: package path location :param str import_options: FBX import options as a string. :return: imported skeletal mesh asset path. :rtype: str """ # Check import path is a package path, else update it. is_package_path = False if import_path.find('game') == 0 or \ import_path.find('game') == 1: is_package_path = True if not is_package_path: raw_path = unreal.Paths.project_content_dir() content_dir = unreal.Paths.make_standard_filename(raw_path) import_path = import_path.replace(content_dir,"") import_path = os.path.join(os.path.sep, "Game", import_path) import_options = ast.literal_eval(import_options) import_options["import_as_skeletal"] = False destination_name = import_options.pop("destination_name", None) save = import_options.pop("save", True) import_asset_path = assets.import_fbx_asset( fbx_file, import_path, destination_name=destination_name, save=save, import_options=import_options, ) return import_asset_path # ================================================================================================================== # SKELETAL MESHES # ================================================================================================================== @unreal.ufunction( params=[str, str, str], ret=str, static=True, meta=dict(Category="ueGear Commands"), ) def import_skeletal_mesh(fbx_file, import_path, import_options): """ Imports skeletal mesh from FBX file. :param str import_path: skeletal mesh FBX file path. :param str import_options: FBX import options as a string. :return: imported skeletal mesh asset path. :rtype: str """ try: import_options = ast.literal_eval(import_options) # If a skeletal string encoded dictionary exists, convert it to a dict. skeletal_data = import_options.get("skeletal_mesh_import_data", None) if skeletal_data: skeletal_data = ast.literal_eval(skeletal_data) import_options["skeletal_mesh_import_data"] = skeletal_data except SyntaxError: import_options = dict() name = import_options.get("destination_name", None) if name: import_options.pop("destination_name") import_options["import_as_skeletal"] = True import_asset_path = assets.import_fbx_asset( fbx_file, import_path, destination_name = name, import_options=import_options ) return import_asset_path @unreal.ufunction( params=[bool], ret=unreal.Array(unreal.StringValuePair), static=True, meta=dict(Category="ueGear Commands"),) def get_skeletons_data(skeletal_mesh=False): """ Returns a list of skeletons or skeletal meshes, that exist in the open unreal project. :param bool skeletal_mesh: If True return SkeletalMesh data, False return Skeleton data. :return: The package_name and asset_name. Stored in an Array of Key Value pairs. :rtype: unreal.Array(unreal.StringValuePair) """ skeleton_list = unreal.Array(unreal.StringValuePair) if skeletal_mesh: skeletons = assets.get_skeleton_meshes() else: skeletons = assets.get_skeletons() for skeleton in skeletons: package_name = skeleton.get_editor_property("package_name") asset_name = skeleton.get_editor_property("asset_name") skeleton_list.append(unreal.StringValuePair(package_name, asset_name)) return skeleton_list # ================================================================================================================== # ANIMATED SKELETAL MESHES # ================================================================================================================== @unreal.ufunction( params=[str, str, str, str], ret=unreal.Array(str), static=True, meta=dict(Category="ueGear Commands"),) def import_animation(animation_path, dest_path, name, skeleton_path): """ Imports an Skeletal Animation into Unreal. :param str animation_path: Path to FBX location :param str dest_path: Package path to the folder that will store the animation. :param str name: Name of the animation file :param str skeleton_path: Package path to the Skeleton in Unreal :return: imported path. :rtype: str """ result = assets.import_fbx_animation(fbx_path=animation_path, dest_path=dest_path, anim_sequence_name=name, skeleton_path=skeleton_path ) return result # ================================================================================================================== # TEXTURES # ================================================================================================================== @unreal.ufunction( params=[str, str, str], ret=str, static=True, meta=dict(Category="ueGear Commands"), ) def import_texture(texture_file, import_path, import_options): """ Imports texture from disk into Unreal Asset. :param str import_path: texture file path. :param str import_options: texture import options as a string. :return: imported texture asset path. :rtype: str """ try: import_options = ast.literal_eval(import_options) except SyntaxError: import_options = dict() import_asset_path = textures.import_texture_asset( texture_file, import_path, import_options=import_options ) return import_asset_path # ================================================================================================================== # MAYA # ================================================================================================================== @unreal.ufunction( params=[str], static=True, meta=dict(Category="ueGear Commands") ) def import_maya_data_from_file(data_file): """ Imports ueGear data from the given file. :param str data_file: ueGear data file path. """ mayaio.import_data(data_file) @unreal.ufunction( params=[str], static=True, meta=dict(Category="ueGear Commands") ) def import_maya_layout_from_file(layout_file): """ Imports ueGear layout from the given file. :param str layout_file: layout file path. """ mayaio.import_layout_from_file(layout_file) @unreal.ufunction( params=[str, bool], ret=str, static=True, meta=dict(Category="ueGear Commands"), ) def export_maya_layout(directory, export_assets): """ Exports ueGear layout into Maya. :param str directory: export directory. """ layout_data = list() actors_mapping = dict() level_asset = unreal.LevelEditorSubsystem().get_current_level() level_name = unreal.SystemLibrary.get_object_name(level_asset) level_actors = ( actors.get_selected_actors_in_current_level() or actors.get_all_actors_in_current_level() ) if not level_actors: unreal.log_warning("No actors to export") return "" for actor in level_actors: actor_asset = actors.get_actor_asset(actor) if not actor_asset: unreal.log_warning( "Was not possible to retrieve asset for actor: {}".format( actor ) ) continue actor_asset_name = actor_asset.get_path_name() actors_mapping.setdefault( actor_asset_name, {"actors": list(), "export_path": ""} ) actors_mapping[actor_asset_name]["actors"].append(actor) # Export assets if export_assets: actors_list = list(actors_mapping.keys()) with unreal.ScopedSlowTask( len(actors_list), "Exporting Asset: {}".format(actors_list[0]) ) as slow_task: slow_task.make_dialog(True) for asset_path in list(actors_mapping.keys()): actor_asset = assets.get_asset(asset_path) export_asset_path = assets.export_fbx_asset( actor_asset, directory=directory ) actors_mapping[asset_path][ "export_path" ] = export_asset_path slow_task.enter_progress_frame( 1, "Exporting Asset: {}".format(asset_path) ) for asset_path, asset_data in actors_mapping.items(): asset_actors = asset_data["actors"] for asset_actor in asset_actors: actor_data = { "guid": asset_actor.get_editor_property( "actor_guid" ).to_string(), "name": asset_actor.get_actor_label(), "path": asset_actor.get_path_name(), "translation": asset_actor.get_actor_location().to_tuple(), "rotation": asset_actor.get_actor_rotation().to_tuple(), "scale": asset_actor.get_actor_scale3d().to_tuple(), "assetPath": "/".join(asset_path.split("/")[:-1]), "assetName": asset_path.split("/")[-1].split(".")[0], "assetExportPath": asset_data["export_path"], "assetType": unreal.EditorAssetLibrary.get_metadata_tag( asset_actor, tag.TAG_ASSET_TYPE_ATTR_NAME ) or "", } layout_data.append(actor_data) output_file_path = os.path.join( directory, "{}_layout.json".format(level_name) ) result = helpers.write_to_json_file(layout_data, output_file_path) if not result: unreal.log_error("Was not possible to save ueGear layout file") return "" return output_file_path
import unreal import os auto = unreal.AutomationLibrary() dir = '/project//' def takess(): for f in os.listdir(dir): os.remove(os.path.join(dir,f)) auto.take_high_res_screenshot(100,100,'ss',None,False,False,unreal.ComparisonTolerance.LOW,'',0.0)
import json import random import unreal from actor.background import load_all_backgrounds from actor.camera import Camera from actor.level import Level from actor.light import PointLight from actor.metahuman import MetaHuman import utils.utils as utils from utils.utils import MetaHumanAssets from data.pose import DICT_POSE, LIST_VISEMES PATH_MAIN = "/project/" # Initialize level sequence level = Level() camera = Camera() light1 = PointLight() light2 = PointLight() backgrounds = load_all_backgrounds() metahuman = MetaHuman(MetaHumanAssets.hudson) level.add_actor(camera) level.add_actor(light1) level.add_actor(light2) level.add_actor(metahuman) for background in backgrounds: level.add_actor(background) light1.add_key_random(0, offset=[0., 0., 180.]) light2.add_key_random(0, offset=[0., 0., 180.]) keys_camera = camera.add_key_random(0, distance=50, offset=[0., 0., 165.]) face_rig = metahuman.control_rig_face unreal.LevelSequenceEditorBlueprintLibrary.set_current_time(0) control_rig = json.load(open('/project/ Projects/project/.json', 'r')) dict_pose_emotion = {} for key in DICT_POSE: pose_filename = DICT_POSE[key] pose = unreal.EditorAssetLibrary.load_asset(pose_filename) pose.select_controls(face_rig) pose.paste_pose(face_rig, do_key=True) new_pose = {} for control in control_rig: frame = unreal.FrameNumber(0) if control_rig[control]['type'] == 'vec2': vec2 = unreal.ControlRigSequencerLibrary.get_local_control_rig_vector2d(level.level_sequence, face_rig, control, frame) value = [vec2.x, vec2.y] new_pose[control] = value elif control_rig[control]['type'] == 'float': value = unreal.ControlRigSequencerLibrary.get_local_control_rig_float(level.level_sequence, face_rig, control, frame) new_pose[control] = value dict_pose_emotion[key] = new_pose list_pose_viseme = [] for pose_filename in LIST_VISEMES: pose = unreal.EditorAssetLibrary.load_asset(pose_filename) pose.select_controls(face_rig) pose.paste_pose(face_rig, do_key=True) new_pose = {} for control in control_rig: frame = unreal.FrameNumber(0) if control_rig[control]['type'] == 'vec2': vec2 = unreal.ControlRigSequencerLibrary.get_local_control_rig_vector2d(level.level_sequence, face_rig, control, frame) value = [vec2.x, vec2.y] new_pose[control] = value elif control_rig[control]['type'] == 'float': value = unreal.ControlRigSequencerLibrary.get_local_control_rig_float(level.level_sequence, face_rig, control, frame) new_pose[control] = value list_pose_viseme.append(new_pose) json.dump(dict_pose_emotion, open('/project/ Projects/project/.json', 'w'), indent=4) json.dump(list_pose_viseme, open('/project/ Projects/project/.json', 'w'), indent=4)
# This python script is meant to be called in the Unreal Engine Python terminal. # This file reads the parameters from a specified directory, changes the current # environment's materials, and takes a screenshot of the current environment. from datetime import datetime import os from pathlib import Path import platform from subprocess import Popen import pandas as pd import unreal # TEST_MODE = "single_fire_test" # # TEST_MODE = "lightbulb_test" # subsystems EditorActorSubsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) LevelEditorSubsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) UnrealEditorSubsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) thermal_mat_inst = unreal.EditorAssetLibrary.load_asset("/project/") # thermal_mat_inst = unreal.EditorAssetLibrary.load_asset("/project/") #Grabs Camera Actor actors = unreal.EditorLevelLibrary.get_all_level_actors() camera_actor = None for actor in actors: if (actor.get_name() == 'CineCameraActor_1'): camera_actor = actor break params = pd.read_csv(r"/project/.csv") row = params.iloc[0] blend_weight = row["blend_weight"].item() brightness = row["brightness"].item() contrast = row["contrast"].item() cold_brightness_multiplier = row["cold_brightness_multiplier"].item() cold_power = row["cold_power"].item() hot_brightness_multiplier = row["hot_brightness_multiplier"].item() hot_power = row["hot_power"].item() light_bulb_heat_multiplier = row["light_bulb_heat_multiplier"].item() lamp_heat_multiplier = row["lamp_heat_multiplier"].item() unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"blend_weight", blend_weight) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Brightness", brightness) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Contrast", contrast) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"cold_brightness_multiplier", cold_brightness_multiplier) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"cold_power", cold_power) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"hot_brightness_multiplier", hot_brightness_multiplier) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"hot_power", hot_power) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"light_bulb_heat_multiplier", light_bulb_heat_multiplier) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"lamp_heat_multiplier", lamp_heat_multiplier) class PyCapture: def __init__(self): # self.name = file_name # Register post tick command self.on_post_tick = unreal.register_slate_post_tick_callback(self.render_frame) def render_frame(self, ignore): # Render screenshot file_name = "Current.png" unreal.AutomationLibrary.take_high_res_screenshot(1920, 1080, file_name, camera_actor) unreal.unregister_slate_post_tick_callback(self.on_post_tick) PyCapture()
import unreal class FileExtensionHelper(): FILE_EXTENSIONS = { unreal.AssetImportTypeEnum.MESHES: ['fbx', 'obj'], unreal.AssetImportTypeEnum.SOUNDS: ['mp3', 'wma', 'aac', 'wav', 'flac'], unreal.AssetImportTypeEnum.TEXTURES: ['jpeg', 'jpg', 'png', 'tga'] } @staticmethod def get_file_formats_to_import(include_meshes: bool, include_sounds: bool, include_textures: bool): return (FileExtensionHelper.FILE_EXTENSIONS[unreal.AssetImportTypeEnum.MESHES] if include_meshes else []) + \ (FileExtensionHelper.FILE_EXTENSIONS[unreal.AssetImportTypeEnum.SOUNDS] if include_sounds else []) + \ (FileExtensionHelper.FILE_EXTENSIONS[unreal.AssetImportTypeEnum.TEXTURES] if include_textures else []) @staticmethod def get_enum_with_extension(extension): for item in FileExtensionHelper.FILE_EXTENSIONS.keys(): if extension in FileExtensionHelper.FILE_EXTENSIONS[item]: return item raise FileNotFoundError()
# # Unreal Engine 5.0 Python Script that takes in N >= 2 selected StaticMesh Actors, # and subtracts Actors 1..N from the first Actor # import unreal # output path and asset name (random suffix will be appended) BooleanResultBasePath = "/project/" BooleanResultBaseName = "PyBoolean" # get Actor subsystem and get set of selected Actors actorSub = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) SelectedActors = unreal.EditorFilterLibrary.by_class(actorSub.get_selected_level_actors(), unreal.StaticMeshActor) # make temporary structs asset_options = unreal.GeometryScriptCopyMeshFromAssetOptions() requested_lod = unreal.GeometryScriptMeshReadLOD() copy_from_component_options = unreal.GeometryScriptCopyMeshFromComponentOptions() # loop over Actors. Collect meshes, subtract all other meshes from the first mesh i = 0 ResultMesh = unreal.DynamicMesh() # final mesh will be here ResultMaterials = [] # final material list will be here LocalToWorld = unreal.Transform() # ResultMesh will be in World space, and this will be the transformation back to local space of the first Actor for StaticMeshActor in SelectedActors: StaticMeshComponent = StaticMeshActor.static_mesh_component StaticMesh = StaticMeshComponent.static_mesh # if it's mesh 0, just copy it into ResultMesh, otherwise subtract it if i == 0: # copy static mesh to dynamic mesh (ResultMeshOut, LocalToWorld, Outcome) = unreal.GeometryScript_SceneUtils.copy_mesh_from_component(StaticMeshComponent, ResultMesh, copy_from_component_options, True) # create flattened list of materials from this StaticMesh Component (note that we must use asset sections to figure out correct material slot index!) (AssetMaterialList, MaterialIndices, Outcome) = unreal.GeometryScript_AssetUtils.get_section_material_list_from_static_mesh(StaticMesh, unreal.GeometryScriptMeshReadLOD() ) for matidx in MaterialIndices: ResultMaterials.append( StaticMeshComponent.get_material(matidx) ) # use Component material instead of Asset material! else: # copy static mesh to dynamic mesh TempMesh = unreal.DynamicMesh() unreal.GeometryScript_SceneUtils.copy_mesh_from_component(StaticMeshComponent, TempMesh, copy_from_component_options, True) # create flattened list of materials from this StaticMesh Component (note that we must use asset sections to figure out correct material slot index!) (AssetMaterialList, MaterialIndices, Outcome) = unreal.GeometryScript_AssetUtils.get_section_material_list_from_static_mesh(StaticMesh, unreal.GeometryScriptMeshReadLOD() ) MaterialIndices.reverse() # reverse list so that we can process material IDs from largest to smallest and avoid collision, as we will always remap to larger for matidx in MaterialIndices: new_matidx = len(ResultMaterials) ResultMaterials.append( StaticMeshComponent.get_material(matidx) ) # use Component material instead of Asset material! unreal.GeometryScript_Materials.remap_material_i_ds( TempMesh, matidx, new_matidx ) # do the boolean subtract operation subtract_options = unreal.GeometryScriptMeshBooleanOptions() unreal.GeometryScript_MeshBooleans.apply_mesh_boolean(ResultMesh, unreal.Transform(), TempMesh, unreal.Transform(), unreal.GeometryScriptBooleanOperation.SUBTRACT, subtract_options) i = i + 1 # apply inverse transform to ResultMesh, becase it was transformed to world unreal.GeometryScript_MeshTransforms.transform_mesh(ResultMesh, LocalToWorld.inverse()) if ResultMesh.get_triangle_count() > 0: # generate a unique new asset name, so that we don't lose the output due to a name collision NewAssetNameOptions = unreal.GeometryScriptUniqueAssetNameOptions() (NewAssetPath, NewAssetName, Success) = unreal.GeometryScript_NewAssetUtils.create_unique_new_asset_path_name(BooleanResultBasePath, BooleanResultBaseName, NewAssetNameOptions) # create a new asset for the output mesh NewAssetOptions = unreal.GeometryScriptCreateNewStaticMeshAssetOptions() # NewAssetOptions.enable_nanite = True # can use this to enable Nanite (NewStaticMesh, Outcome) = unreal.GeometryScript_NewAssetUtils.create_new_static_mesh_asset_from_mesh(ResultMesh, NewAssetPath, NewAssetOptions) if Outcome == unreal.GeometryScriptOutcomePins.SUCCESS: # in 5.0 the create-new-asset function does not support setting materials, so now copy it again (could also enable nanite here) UpdateAssetOptions = unreal.GeometryScriptCopyMeshToAssetOptions() UpdateAssetOptions.replace_materials = True UpdateAssetOptions.new_materials = ResultMaterials unreal.GeometryScript_AssetUtils.copy_mesh_to_static_mesh(ResultMesh, NewStaticMesh, UpdateAssetOptions, unreal.GeometryScriptMeshWriteLOD()) else: print('Result Mesh is Empty!')
# Copyright Epic Games, Inc. All Rights Reserved """ General Deadline utility functions """ # Built-in from copy import deepcopy import json import re import unreal def format_job_info_json_string(json_string, exclude_aux_files=False): """ Deadline Data asset returns a json string, load the string and format the job info in a dictionary :param str json_string: Json string from deadline preset struct :param bool exclude_aux_files: Excludes the aux files from the returned job info dictionary if True :return: job Info dictionary """ if not json_string: raise RuntimeError(f"Expected json string value but got `{json_string}`") job_info = {} try: intermediate_info = json.loads(json_string) except Exception as err: raise RuntimeError(f"An error occurred formatting the Job Info string. \n\t{err}") project_settings = unreal.get_default_object(unreal.DeadlineServiceEditorSettings) script_category_mappings = project_settings.script_category_mappings # The json string keys are camelCased keys which are not the expected input # types for Deadline. Format the keys to PascalCase. for key, value in intermediate_info.items(): # Remove empty values if not value: continue # Deadline does not support native boolean so make it a string if isinstance(value, bool): value = str(value).lower() pascal_case_key = re.sub("(^\S)", lambda string: string.group(1).upper(), key) if (pascal_case_key == "AuxFiles") and not exclude_aux_files: # The returned json string lists AuxFiles as a list of # Dictionaries but the expected value is a list of # strings. reformat this input into the expected value aux_files = [] for files in value: aux_files.append(files["filePath"]) job_info[pascal_case_key] = aux_files continue # Extra option that can be set on the job info are packed inside a # ExtraJobOptions key in the json string. # Extract this is and add it as a flat setting in the job info elif pascal_case_key == "ExtraJobOptions": job_info.update(value) continue # Resolve the job script paths to be sent to be sent to the farm. elif pascal_case_key in ["PreJobScript", "PostJobScript", "PreTaskScript", "PostTaskScript"]: # The path mappings in the project settings are a dictionary # type with the script category as a named path for specifying # the root directory of a particular script. The User interface # exposes the category which is what's in the json string. We # will use this category to look up the actual path mappings in # the project settings. script_category = intermediate_info[key]["scriptCategory"] script_name = intermediate_info[key]["scriptName"] if script_category and script_name: job_info[pascal_case_key] = f"{script_category_mappings[script_category]}/{script_name}" continue # Environment variables for Deadline are numbered key value pairs in # the form EnvironmentKeyValue#. # Conform the Env settings to the expected Deadline configuration elif (pascal_case_key == "EnvironmentKeyValue") and value: for index, (env_key, env_value) in enumerate(value.items()): job_info[f"EnvironmentKeyValue{index}"] = f"{env_key}={env_value}" continue # ExtraInfoKeyValue for Deadline are numbered key value pairs in the # form ExtraInfoKeyValue#. # Conform the setting to the expected Deadline configuration elif (pascal_case_key == "ExtraInfoKeyValue") and value: for index, (env_key, env_value) in enumerate(value.items()): job_info[f"ExtraInfoKeyValue{index}"] = f"{env_key}={env_value}" continue else: # Set the rest of the functions job_info[pascal_case_key] = value # Remove our custom representation of Environment and ExtraInfo Key value # pairs from the dictionary as the expectation is that these have been # conformed to deadline's expected key value representation for key in ["EnvironmentKeyValue", "ExtraInfoKeyValue"]: job_info.pop(key, None) return job_info def format_plugin_info_json_string(json_string): """ Deadline Data asset returns a json string, load the string and format the plugin info in a dictionary :param str json_string: Json string from deadline preset struct :return: job Info dictionary """ if not json_string: raise RuntimeError(f"Expected json string value but got `{json_string}`") plugin_info = {} try: info = json.loads(json_string) plugin_info = info["pluginInfo"] except Exception as err: raise RuntimeError(f"An error occurred formatting the Plugin Info string. \n\t{err}") # The plugin info is listed under the `plugin_info` key. # The json string keys are camelCased on struct conversion to json. return plugin_info def get_deadline_info_from_preset(job_preset=None, job_preset_struct=None): """ This method returns the job info and plugin info from a deadline preset :param unreal.DeadlineJobPreset job_preset: Deadline preset asset :param unreal.DeadlineJobPresetStruct job_preset_struct: The job info and plugin info in the job preset :return: Returns a tuple with the job info and plugin info dictionary :rtype: Tuple """ job_info = {} plugin_info = {} preset_struct = None # TODO: Make sure the preset library is a loaded asset if job_preset is not None: preset_struct = job_preset.job_preset_struct if job_preset_struct is not None: preset_struct = job_preset_struct if preset_struct: # Get the Job Info and plugin Info try: job_info = dict(unreal.DeadlineServiceEditorHelpers.get_deadline_job_info(preset_struct)) plugin_info = dict(unreal.DeadlineServiceEditorHelpers.get_deadline_plugin_info(preset_struct)) # Fail the submission if any errors occur except Exception as err: unreal.log_error( f"Error occurred getting deadline job and plugin details. \n\tError: {err}" ) raise return job_info, plugin_info def merge_dictionaries(first_dictionary, second_dictionary): """ This method merges two dictionaries and returns a new dictionary as a merger between the two :param dict first_dictionary: The first dictionary :param dict second_dictionary: The new dictionary to merge in :return: A new dictionary based on a merger of the input dictionaries :rtype: dict """ # Make sure we do not overwrite our input dictionary output_dictionary = deepcopy(first_dictionary) for key in second_dictionary: if isinstance(second_dictionary[key], dict): if key not in output_dictionary: output_dictionary[key] = {} output_dictionary[key] = merge_dictionaries(output_dictionary[key], second_dictionary[key]) else: output_dictionary[key] = second_dictionary[key] return output_dictionary def get_editor_deadline_globals(): """ Get global storage that will persist for the duration of the current interpreter/process. .. tip:: Please namespace or otherwise ensure unique naming of any data stored into this dictionary, as key clashes are not handled/safety checked. :return: Global storage :rtype: dict """ import __main__ try: return __main__.__editor_deadline_globals__ except AttributeError: __main__.__editor_deadline_globals__ = {} return __main__.__editor_deadline_globals__
import unreal """ Should be used with internal UE Python API Auto generate collision for static meshes""" asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() asset_root_dir = '/project/' assets = asset_reg.get_assets_by_path(asset_root_dir, recursive=True) def set_convex_collision(static_mesh): unreal.EditorStaticMeshLibrary.set_convex_decomposition_collisions(static_mesh, 4, 16, 100000) unreal.EditorAssetLibrary.save_loaded_asset(static_mesh) for asset in assets: if asset.asset_class == "StaticMesh": static_mesh = unreal.EditorAssetLibrary.find_asset_data(asset.object_path).get_asset() set_convex_collision(static_mesh)
import unreal #import re def get_bp_c_by_name(__bp_dir:str): __bp_c = __bp_dir + '_C' return __bp_c def get_bp_mesh_comp (__bp_c:str) : #source_mesh = ue.load_asset(__mesh_dir) loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c) bp_c_obj = unreal.get_default_object(loaded_bp_c) loaded_comp = bp_c_obj.get_editor_property('Mesh') return loaded_comp def get_bp_capsule_comp (__bp_c:str) : #source_mesh = ue.load_asset(__mesh_dir) loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c) bp_c_obj = unreal.get_default_object(loaded_bp_c) loaded_comp = bp_c_obj.get_editor_property('CapsuleComponent') return loaded_comp def get_bp_comp_by_name (__bp_c, __seek: str) : #source_mesh = ue.load_asset(__mesh_dir) loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c) bp_c_obj = unreal.get_default_object(loaded_bp_c) loaded_comp = bp_c_obj.get_editor_property(__seek) return loaded_comp ar_asset_lists = [] ar_asset_lists = unreal.EditorUtilityLibrary.get_selected_assets() print (ar_asset_lists[0]) str_selected_asset = '' if len(ar_asset_lists) > 0 : str_selected_asset = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(ar_asset_lists[0]) #str_selected_asset = str(ar_asset_lists[0]) #print(str_selected_asset) path = str_selected_asset.rsplit('/', 1)[0] + '/' name = str_selected_asset.rsplit('/', 1)[1] name = name.rsplit('.', 1)[1] BaseBP: str = '/project/' BaseAnimBP: str = '/project/' Basepath: str = path assetPath: str = Basepath + '/project/' '''BP setting start''' BPPath: str = Basepath + '/Blueprints/' + name + "_Blueprint" AnimBPPath: str = Basepath + '/Blueprints/' + name + "_AnimBP" #SkeletonPath = Basepath + name + "_Skeleton" Skeleton = ar_asset_lists[0].skeleton asset_bp = unreal.EditorAssetLibrary.duplicate_asset(BaseBP,BPPath) AnimBP = unreal.EditorAssetLibrary.duplicate_asset(BaseAnimBP,AnimBPPath) AnimBP.set_editor_property("target_skeleton", Skeleton) # BPPath_C = get_bp_c_by_name(BPPath) # BP_mesh_comp = get_bp_mesh_comp_by_name(BPPath_C, 'Mesh') # BP_mesh_comp.set_editor_property('skeletal_mesh',ar_asset_lists[0]) # BP_mesh_comp.set_editor_property('anim_class', loaded_a) # '''BP setting end''' # BP Component Setting Start # _bp_ = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(asset_bp) _abp_ = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(AnimBP) _bp_c = get_bp_c_by_name(_bp_) _abp_c = get_bp_c_by_name(_abp_) loaded_abp = unreal.EditorAssetLibrary.load_blueprint_class(_abp_c) bp_mesh_comp = get_bp_mesh_comp(_bp_c) bp_mesh_comp.set_editor_property('skeletal_mesh',ar_asset_lists[0]) bp_mesh_comp.set_editor_property('anim_class', loaded_abp) # BP Component Setting End # #test code # # bp_capsule_comp = get_bp_capsule_comp(_bp_c) # bp_capsule_comp = get_bp_comp_by_name(_bp_c,'CapsuleComponent') # half_height = bp_capsule_comp.get_editor_property('capsule_half_height')
import unreal def build_input_task_simple(filename, destination_path, destination_name='', option=None): unreal.log("Build Import Task: {} to {} as {}".format(filename, destination_path, destination_name)) task = unreal.AssetImportTask() task.set_editor_property('automated', True) task.set_editor_property('destination_name', destination_name) task.set_editor_property('destination_path', destination_path) task.set_editor_property('filename', filename) task.set_editor_property('replace_existing', True) task.set_editor_property('save', True) if option: task.set_editor_property('options', option) return task def execute_import_tasks(tasks=[]): unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks(tasks) imported_asset_paths = [] for task in tasks: for imported_object in task.get_objects(): imported_asset_paths.append(imported_object.get_package().get_path_name()) return imported_asset_paths def build_staticmesh_import_options(): options = unreal.FbxImportUI() # unreal.FbxImportUI options.set_editor_property('import_mesh', True) options.set_editor_property('import_textures', False) options.set_editor_property('import_materials', False) options.set_editor_property('import_as_skeletal', False) # Static Mesh # unreal.FbxMeshImportData options.static_mesh_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0)) options.static_mesh_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0)) options.static_mesh_import_data.set_editor_property('import_uniform_scale', 1.0) # unreal.FbxStaticMeshImportData options.static_mesh_import_data.set_editor_property('combine_meshes', True) options.static_mesh_import_data.set_editor_property('generate_lightmap_u_vs', False) options.static_mesh_import_data.set_editor_property('auto_generate_collision', True) options.static_mesh_import_data.set_editor_property('one_convex_hull_per_ucx', True) options.static_mesh_import_data.set_editor_property('build_nanite', True) # force fix the normal from cgf options.static_mesh_import_data.set_editor_property('recompute_normals', True) return options def open_editor_for_asset(asset_path): if not unreal.EditorAssetLibrary.does_asset_exist(asset_path): raise Exception('Fail to find asset: {}'.format(asset_path)) asset_obj = unreal.load_asset(asset_path) # close the editor if opened or it won't refresh asset_subsystem = unreal.get_editor_subsystem(unreal.AssetEditorSubsystem) asset_subsystem.close_all_editors_for_asset(asset_obj) asset_subsystem.open_editor_for_assets([asset_obj])
# -*- coding: utf-8 -*- """ 打开 metahuman 项目执行脚本 需要启用 Sequencer Scripting 插件 """ # Import future modules from __future__ import absolute_import from __future__ import division from __future__ import print_function __author__ = 'timmyliang' __email__ = '[email protected]' __date__ = '2022-06-24 18:07:09' # Import built-in modules from collections import defaultdict import json import os # Import local modules import unreal DIR = os.path.dirname(os.path.abspath(__file__)) def unreal_progress(tasks, label="进度", total=None): total = total if total else len(tasks) with unreal.ScopedSlowTask(total, label) as task: task.make_dialog(True) for i, item in enumerate(tasks): if task.should_cancel(): break task.enter_progress_frame(1, "%s %s/%s" % (label, i, total)) yield item def main(): # NOTE: 读取 sequence sequence = unreal.load_asset('/project/.MetaHumanSample_Sequence') # NOTE: 收集 sequence 里面所有的 binding binding_dict = defaultdict(list) for binding in sequence.get_bindings(): binding_dict[binding.get_name()].append(binding) # NOTE: 遍历命名为 Face 的 binding for binding in unreal_progress(binding_dict.get("Face", []), "导出 Face 数据"): # NOTE: 获取关键帧 channel 数据 keys_dict = {} for track in binding.get_tracks(): for section in track.get_sections(): for channel in unreal_progress(section.get_channels(), "导出关键帧"): if not channel.get_num_keys(): continue keys = [] for key in channel.get_keys(): frame_time = key.get_time() frame = frame_time.frame_number.value + frame_time.sub_frame keys.append({"frame": frame, "value": key.get_value()}) keys_dict[channel.get_name()] = keys # NOTE: 导出 json name = binding.get_parent().get_name() export_path = os.path.join(DIR, "{0}.json".format(name)) with open(export_path, "w") as wf: json.dump(keys_dict, wf, indent=4) if __name__ == "__main__": main()
# Copyright Epic Games, Inc. All Rights Reserved. import os import unreal #------------------------------------------------------------------------------- class Platform(unreal.Platform): name = "Mac" def _read_env(self): yield from () def _get_version_ue4(self): dot_cs = self.get_unreal_context().get_engine().get_dir() dot_cs /= "Source/project/.cs" return Platform._get_version_helper_ue4(dot_cs, "MinMacOSVersion") def _get_version_ue5(self): dot_cs = "Source/project/" version = self._get_version_helper_ue5(dot_cs + ".Versions.cs") return version or self._get_version_helper_ue5(dot_cs + ".cs") def _get_cook_form(self, target): if target == "game": return "Mac" if self.get_unreal_context().get_engine().get_version_major() > 4 else "MacNoEditor" if target == "client": return "MacClient" if target == "server": return "MacServer" def _launch(self, exec_context, stage_dir, binary_path, args): if stage_dir: midfix = "Engine"; if project := self.get_unreal_context().get_project(): midfix = project.get_name() base_dir = stage_dir + midfix + "/project/" if not os.path.isdir(base_dir): raise EnvironmentError(f"Failed to find base directory '{base_dir}'") args = (*args, "-basedir=" + base_dir) cmd = exec_context.create_runnable(binary_path, *args) cmd.launch() return True
import unreal from .. import gallery_class class GalleryDetailView(gallery_class.GallaryWidgetFactory): def create(self): widget = unreal.DetailsView() widget.set_object(unreal.StaticMesh.static_class()) return widget def with_content(self): return "DetailView"
import unreal def create_multiple_bpclass(): # instances of unreal classes assettool_lib = unreal.AssetToolsHelpers totalNumberOfBPs = 20 textDisplay = "Creating Custom Assets" BPPath = "/project/" BPName = "New_BP_%d" factory = unreal.BlueprintFactory() factory.set_editor_property("ParentClass", unreal.Pawn) assetTools = assettool_lib.get_asset_tools() with unreal.ScopedSlowTask(totalNumberOfBPs, textDisplay) as ST: ST.make_dialog(True) for i in range(totalNumberOfBPs): if ST.should_cancel(): break; myNewFile = assetTools.create_asset_with_dialog(BPName % (i), BPPath, None, factory) unreal.EditorAssetLibrary.save_loaded_asset(myNewFile) ST.enter_progress_frame(1)
# SPDX-License-Identifier: Apache-2.0 # Copyright Contributors to the OpenTimelineIO project import os import opentimelineio as otio import unreal from .adapter import import_otio, export_otio @unreal.uclass() class OTIOScriptedSequenceImportFactory(unreal.Factory): """Adds support for importing OTIO supported file formats to create or update level sequence hierarchies via UE import interfaces. """ def _post_init(self, *args): self.create_new = False self.edit_after_new = True self.supported_class = unreal.LevelSequence self.editor_import = True self.text = False # Register all supported timeline import adapters. A comma-separated # list of suffixes can be defined by the environment, or all suffixes # will be registered. env_suffixes = os.getenv("OTIO_UE_IMPORT_SUFFIXES") if env_suffixes is not None: suffixes = env_suffixes.split(",") else: suffixes = otio.adapters.suffixes_with_defined_adapters(read=True) for suffix in suffixes: if suffix.startswith("otio"): self.formats.append(suffix + ";OpenTimelineIO files") else: self.formats.append(suffix + ";OpenTimelineIO supported files") @unreal.ufunction(override=True) def script_factory_can_import(self, filename): suffixes = { s.lower() for s in otio.adapters.suffixes_with_defined_adapters(read=True) } return unreal.Paths.get_extension(filename).lower() in suffixes @unreal.ufunction(override=True) def script_factory_create_file(self, task): # Ok to overwrite an existing level sequence? if task.destination_path and task.destination_name: asset_path = "{path}/{name}".format( path=task.destination_path.replace("\\", "/").rstrip("/"), name=task.destination_name, ) level_seq_data = unreal.EditorAssetLibrary.find_asset_data(asset_path) if level_seq_data.is_valid() and not task.replace_existing: return False level_seq, _ = import_otio( task.filename, destination_path=task.destination_path, destination_name=task.destination_name, ) task.result.append(level_seq) return True @unreal.uclass() class OTIOScriptedSequenceExporter(unreal.Exporter): """Adds support for exporting OTIO files from level sequence hierarchies via UE export interfaces. """ def _post_init(self, *args): # Register one supported timeline export adapter, which can be defined # by the environment, or fallback to the default "otio" format. suffix = os.getenv("OTIO_UE_EXPORT_SUFFIX", "otio") self.format_extension = [suffix] self.format_description = ["OpenTimelineIO file"] self.supported_class = unreal.LevelSequence self.text = False @unreal.ufunction(override=True) def script_run_asset_export_task(self, task): # Ok to overwrite an existing timeline file? if not task.replace_identical and unreal.Paths.file_exists(task.filename): return False export_otio(task.filename, task.object) return True
# Copyright Epic Games, Inc. All Rights Reserved. import re import unreal import flow.cmd import unrealcmd import uelogprinter import unreal.cmdline #------------------------------------------------------------------------------- class _CookPrettyPrinter(uelogprinter.Printer): def __init__(self): super().__init__() self._cook_re = re.compile(r"ages (\d+).+otal (\d+)") def _print(self, line): m = self._cook_re.search(line) if m: percent = (int(m.group(1)) * 100) // max(int(m.group(2)), 1) line += f" [{percent}%]" super()._print(line) #------------------------------------------------------------------------------- class _Cook(unrealcmd.MultiPlatformCmd): cookargs = unrealcmd.Arg([str], "Additional arguments passed to the cook commandlet") cultures = unrealcmd.Opt("en", "Cultures to cook (comma separated, defaults to 'en')") onthefly = unrealcmd.Opt(False, "Launch as an on-the-fly server") iterate = unrealcmd.Opt(False, "Cook iteratively on top of the previous cook") noxge = unrealcmd.Opt(False, "Disable XGE-based shader compilation") unpretty = unrealcmd.Opt(False, "Turns off colourful pretty-printing") attach = unrealcmd.Opt(False, "Attach a debugger to the cook") debug = unrealcmd.Opt(False, "Use debug executables") @unrealcmd.Cmd.summarise def _cook(self, cook_form, exec_context=None): ue_context = self.get_unreal_context() # Check there is a valid project project = ue_context.get_project() if not project: self.print_error("An active project is required to cook") return False # Prepare arguments cultures = self.args.cultures.replace(",", "+") commandlet_args = ( ("-targetplatform=" + cook_form) if cook_form else None, ("-cookcultures=" + cultures) if cultures else None, "-unattended", "-unversioned", "-stdout", "-cookonthefly" if self.args.onthefly else None, "-iterate" if self.args.iterate else None, "-noxgeshadercompile" if self.args.noxge else None, *unreal.cmdline.read_ueified(*self.args.cookargs), ) commandlet_args = tuple(x for x in commandlet_args if x) # To support attaching a debugger we will reuse '.run commandlet'. This # approach is not used normally as it interferes with pretty-printing and # creates an awful lot of child processes. if self.args.attach: args = ("_run", "commandlet", "cook", "--noplatforms", "--attach") if self.args.debug: args = (*args, "debug") args = (*args, "--", *commandlet_args) # Disable our handling of Ctrl-C import signal def nop_handler(*args): pass signal.signal(signal.SIGINT, nop_handler) import subprocess return subprocess.run(args).returncode # Find the editor binary target = ue_context.get_target_by_type(unreal.TargetType.EDITOR) variant = unreal.Variant.DEBUG if self.args.debug else unreal.Variant.DEVELOPMENT build = target.get_build(variant=variant) if not build: self.print_error(f"No {variant.name.lower()} editor build found") return False cmd = str(build.get_binary_path()) if not cmd.endswith("-Cmd.exe"): cmd = cmd.replace(".exe", "-Cmd.exe") # Launch args = ( project.get_path(), "-run=cook", *commandlet_args, ) exec_context = exec_context or self.get_exec_context() cmd = exec_context.create_runnable(cmd, *args) if self.args.unpretty or not self.is_interactive(): cmd.run() else: printer = _CookPrettyPrinter() printer.run(cmd) return cmd.get_return_code() #------------------------------------------------------------------------------- class Cook(_Cook): """ Prepares a cooked meal of dataset for the given target platform """ target = unrealcmd.Arg(str, "Full target platform name (i.e. WindowsNoEditor)") def main(self): return self._cook(self.args.target) #------------------------------------------------------------------------------- class _Runtime(_Cook): platform = unrealcmd.Arg("", "The platform to cook data for") def main(self, target): platform = self.args.platform if not platform: platform = unreal.Platform.get_host() platform = self.get_platform(platform) exec_context = super().get_exec_context() exec_env = exec_context.get_env() # Establish target platform's environment name = platform.get_name() self.print_info(name, "-", platform.get_version()) for item in platform.read_env(): try: dir = str(item) exec_env[item.key] = dir except EnvironmentError: dir = flow.cmd.text.red(item.get()) print(item.key, "=", dir) cook_form = platform.get_cook_form(target.name.lower()) return self._cook(cook_form, exec_context) #------------------------------------------------------------------------------- class Game(_Runtime): """ Cooks game data for a particular platform """ def main(self): return super().main(unreal.TargetType.GAME) #------------------------------------------------------------------------------- class Client(_Runtime): """ Cooks client data for a particular platform """ def main(self): return super().main(unreal.TargetType.CLIENT) #------------------------------------------------------------------------------- class Server(_Runtime): """ Cooks server data for a particular platform """ complete_platform = ("win64", "linux") def main(self): return super().main(unreal.TargetType.SERVER)
import unreal import sys import os # Add the script directories to sys.path script_dir = os.path.dirname(__file__) sys.path.append(script_dir) sys.path.append(os.path.join(script_dir, "..")) sys.path.append(os.path.join(script_dir, "..", "carla_scripts")) sys.path.append(os.path.join(script_dir, "..", "utils")) # Asset path (relative to /Game) blueprint_path = "/project/" # Load the Blueprint class bp_class = unreal.EditorAssetLibrary.load_blueprint_class(blueprint_path) if not bp_class: unreal.log_error(f"Failed to load blueprint class at: {blueprint_path}") else: # Define spawn location and rotation location = unreal.Vector(32341.009766, 20203.007812, 100.0) rotation = unreal.Rotator(0.0, 0.0, 90.0) # Spawn the actor in the level actor = unreal.EditorLevelLibrary.spawn_actor_from_class(bp_class, location, rotation) if actor: # Assign a custom label custom_label = "TrafficLight37" actor.set_actor_label(custom_label, mark_dirty=True) unreal.log(f"✅ Spawned and labeled as: {custom_label}") else: unreal.log_error("❌ Failed to spawn actor.")
import unreal def get_component_handles(blueprint_asset_path): ## 사용안해도됨, 다음 함수에서 호출해서 사용하는 함수, 핸들러 직접 물고싶으면 쓰셈 subsystem = unreal.get_engine_subsystem(unreal.SubobjectDataSubsystem) blueprint_asset = unreal.load_asset(blueprint_asset_path) subobject_data_handles = subsystem.k2_gather_subobject_data_for_blueprint(blueprint_asset) return subobject_data_handles def get_component_objects(blueprint_asset_path : str): ## 컴포넌트 무식하게 다 긁어줌 objects = [] handles = get_component_handles(blueprint_asset_path) for handle in handles: data = unreal.SubobjectDataBlueprintFunctionLibrary.get_data(handle) object = unreal.SubobjectDataBlueprintFunctionLibrary.get_object(data) objects.append(object) return objects def get_component_by_class(blueprint_to_find_components : unreal.Blueprint, component_class_to_find : unreal.Class): ## 컴포넌트중에 클래스 맞는것만 리턴해줌 components : list[unreal.Object] = [] asset_path : list[str] = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(blueprint_to_find_components) component_objects = get_component_objects(asset_path) for each in component_objects: compare_class = (each.__class__ == component_class_to_find) if compare_class : components.append(each) return components def get_component_by_var_name(blueprint_to_find_components : unreal.Blueprint, component_name_to_find : str) : ##컴포넌트 이름으로 찾음 components = [] asset_path = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(blueprint_to_find_components) component_objects = get_component_objects(asset_path) for each in component_objects: compare_name = (each.get_name()) == ( component_name_to_find + '_GEN_VARIABLE' ) if compare_name : components.append(each) return components def cutoff_nanite_tri(_static_mesh_ : unreal.StaticMesh) : 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__ assets = unreal.EditorUtilityLibrary.get_selected_assets() ## execution here ## #__desired_triangle_percentage__ : float = 0.33 assets = unreal.EditorUtilityLibrary.get_selected_assets() ## execution here ## for each in assets : if each.__class__ == unreal.Blueprint : comps = get_component_by_class(each, unreal.StaticMeshComponent) for comp in comps : static_mesh : unreal.StaticMesh = comp.static_mesh if static_mesh is not None : __desired_triangle_percentage__ = cutoff_nanite_tri(static_mesh) nanite_settings : unreal.MeshNaniteSettings = static_mesh.get_editor_property('nanite_settings') nanite_settings.enabled = True nanite_settings.keep_percent_triangles = __desired_triangle_percentage__ static_mesh.set_editor_property('nanite_settings', nanite_settings) #print(nanite_settings.keep_percent_triangles) if each.__class__ == unreal.StaticMesh : if each is not None : __desired_triangle_percentage__ = cutoff_nanite_tri(each) nanite_settings : unreal.MeshNaniteSettings = each.get_editor_property('nanite_settings') nanite_settings.enabled = True nanite_settings.set_editor_property('keep_percent_triangles', __desired_triangle_percentage__) each.set_editor_property('nanite_settings', nanite_settings) print('OK')
# -*- coding: utf-8 -*- """ """ from __future__ import division from __future__ import print_function from __future__ import absolute_import __author__ = 'timmyliang' __email__ = '[email protected]' __date__ = '2021-11-16 21:07:20' import unreal maya_cams = ['MayaCamera','MayaCamera2'] def main(): sequence_list = [a for a in unreal.EditorUtilityLibrary.get_selected_assets() if isinstance(a,unreal.LevelSequence)] sequence = sequence_list[0] for binding in sequence.get_bindings(): if binding.get_name() not in maya_cams: continue for cam_binding in binding.get_child_possessables(): if cam_binding.get_name() != "CameraComponent": continue # NOTES(timmyliang): 业务逻辑 tracks = cam_binding.find_tracks_by_type(unreal.MovieSceneFloatTrack) track = tracks[0] sections = track.get_sections() section = sections[0] section.set_range(101, 165) channels = section.find_channels_by_type(unreal.MovieSceneScriptingFloatChannel) tmp_channel = channels[0] tmp_channel.add_key(unreal.FrameNumber(135), 0.5) if __name__ == "__main__": main() # @maxjzhang(张军)
""" This module shows two styles of adding editor menus We can add a `ToolMenuEntryScript` directly to the end of a menu or wrap it in a `ToolMenuEntry` to control where it's added """ import json import unreal from recipebook import ( actors, editor_tools ) from recipebook.unreal_systems import ToolMenus # --------- Demo base class setups --------- # @unreal.uclass() class PythonMenuTool(unreal.ToolMenuEntryScript): name = "programatic_name" label = "display Name" tool_tip = "tool tip!" def __init__(self, menu, section=""): """ given a menu object and a section name, initialize this python tool and add it to the menu """ super().__init__() if section: menu.add_section(section, section) # Initialize the entry data self.init_entry( owner_name="custom_owner", menu=menu.menu_name, section=section, name=self.name, label=self.label, tool_tip=self.tool_tip ) # Add this tool to the desired menu menu.add_menu_entry_object(self) @unreal.ufunction(override=True) def execute(self, context): """The Python code to execute when pressed""" print(f"Provided context: {context}") @unreal.uclass() class DynamicMenuTest(PythonMenuTool): name = "dynamic_test" label = "Use CTRL" @unreal.ufunction(override=True) def can_execute(self, context): """Can the user press this menu entry?""" is_ctrl_down = unreal.InputLibrary.modifier_keys_state_is_control_down( unreal.InputLibrary.get_modifier_keys_state() ) return is_ctrl_down @unreal.ufunction(override=True) def get_label(self, context): """Update the Display Name""" is_ctrl_down = unreal.InputLibrary.modifier_keys_state_is_control_down( unreal.InputLibrary.get_modifier_keys_state() ) return "CTRL is GO!" if is_ctrl_down else "Press CTRL to use" @unreal.uclass() class PythonMenuToolInsert(unreal.ToolMenuEntryScript): name = "inserted_menu" label = "Inserted Menu Class" tool_tip = "tool tip!" def __init__(self, menu, section="", insert_policy=None): """Initialize our entry for the given menu_object's section""" super().__init__() if section: menu.add_section(section, section) # Initialize the entry data self.init_entry( owner_name="custom_owner", menu=menu.menu_name, section=section, name=self.name, label=self.label, tool_tip=self.tool_tip ) # if an insert policy was provided if insert_policy: # Build the entry insert object entry = unreal.ToolMenuEntry( name=self.name, type=self.data.advanced.entry_type, owner=unreal.ToolMenuOwner("custom_owner"), insert_position=insert_policy, script_object=self ) # insert policy method menu.add_menu_entry(section, entry) else: # default method - add at the bottom of the menu menu.add_menu_entry_object(self) @unreal.uclass() class PythonMenuToolWithIcon(unreal.ToolMenuEntryScript): name = "icon_menu" label = "Menu Class w/ Icon" tool_tip = "tool tip!" def __init__(self, menu, section=""): """Initialize our entry for the given menu_object's section""" super().__init__() # Initialize the entry data self.init_entry( owner_name="custom_owner", menu=menu.menu_name, section=section, name=self.name, label=self.label, tool_tip=self.tool_tip ) self.data.icon = unreal.ScriptSlateIcon( "EditorStyle", "WorldBrowser.DetailsButtonBrush" ) menu.add_menu_entry_object(self) @unreal.ufunction(override=True) def get_icon(self, context): """The Python code to execute when pressed""" is_ctrl_down = unreal.InputLibrary.modifier_keys_state_is_control_down( unreal.InputLibrary.get_modifier_keys_state() ) active_icon = unreal.ScriptSlateIcon( "EditorStyle", "SourceControl.StatusIcon.On" ) inactive_icon = unreal.ScriptSlateIcon( "EditorStyle", "SourceControl.StatusIcon.Error" ) return active_icon if is_ctrl_down else inactive_icon @unreal.uclass() class EditorUtilityWidgetMenuTool(PythonMenuTool): """ menu tool base class to launch specified Editor Utility Widgets """ widget_path = "/project/" @unreal.ufunction(override=True) def execute(self, context): """Open the EUW when pressed""" editor_tools.launch_editor_utility_widget(self.widget_path) # --------- Demo Tool class setups --------- # @unreal.uclass() class OpenRecipeBookDocumentation(PythonMenuTool): """A recipebook tool that will print the current level's actor hierarchy""" name = "open_recipe_book" label = "Recipe Book Documentation" @unreal.ufunction(override=True) def execute(self, context): """ print the current scene's actor hierarchy in a json format """ unreal.SystemLibrary.launch_url(r"https://bkortbus.gitbook.io/unreal-python-recipe-book") # Python tools we can focus on the menu name and the execute function @unreal.uclass() class ActorHierarchy(PythonMenuTool): """A recipebook tool that will print the current level's actor hierarchy""" name = "print_actor_hierarchy" label = "Print Actor hierarchy" @unreal.ufunction(override=True) def execute(self, context): """ print the current scene's actor hierarchy in a json format """ print(json.dumps(actors.get_scene_hierarchy(), indent=4)) @unreal.uclass() class Huzzah(PythonMenuToolInsert): name = "huzzah" label = "Huzzah!" tool_tip = "huzzahhhhhh!!!!" @unreal.ufunction(override=True) def execute(self, context): print(f"Huzzah, good day to you! {context}") @unreal.uclass() class TrackActors(PythonMenuTool): name = "track_actors" label = "Track Actor Selection Changes" tool_tip = "Enable tracking the current actor selection" active = unreal.uproperty(bool) def __init__(self, menu, section=""): super().__init__(menu, section) self.active = False # Change the menu type and re-add it to the menu to update it self.data.advanced.user_interface_action_type = unreal.UserInterfaceActionType.TOGGLE_BUTTON menu.add_menu_entry_object(self) @unreal.ufunction(override=True) def get_check_state(self, context): """determine the icon to display""" checked = unreal.CheckBoxState.CHECKED unchecked = unreal.CheckBoxState.UNCHECKED return checked if self.active else unchecked @unreal.ufunction(override=True) def execute(self, context): self.active = not self.active actors.toggle_selection_tracking(self.active) @unreal.uclass() class MetaViewerTool(EditorUtilityWidgetMenuTool): name = "meta_viewer" label = "Meta Viewer GUI" tool_tip = "Launch the Meta Viewer tool" widget_path = "/project/" # --------- Create the menu --------- # def populate_menus(): """ call this menu during unreal startup to populate our desired menus we'll use separate functions to keep track of which menus we're extending """ populate_main_menu() populate_edit_menu() ToolMenus.refresh_all_widgets() def populate_main_menu(): """ populate our recipebook dropdown menu on the main menu bar """ # The main menu we'll add our tools to: main_menu = ToolMenus.find_menu("LevelEditor.MainMenu") # First, let's create a new sub menu: demo_menu = main_menu.add_sub_menu( owner="demo_tools_tracker", section_name="", name="recipe_book_demo", label="Recipe Book" ) # Next, initialize our menu classes into the demo_menu in the desired sections # these menu entries will be added in sequential order (no insert policy provided) section = "scene" ActorHierarchy(menu=demo_menu, section=section) TrackActors(menu=demo_menu, section=section) section = "tools" MetaViewerTool(menu=demo_menu, section=section) DynamicMenuTest(menu=demo_menu, section=section) section = "Resources" OpenRecipeBookDocumentation(menu=demo_menu, section=section) def populate_edit_menu(): """ insert our entry class to the Edit menu after the `Paste` option """ # The edit menu we'll add our tools to: edit_menu = ToolMenus.find_menu("LevelEditor.MainMenu.Edit") # First, we'll create our insert policy: after the menu entry named "Paste" insert_policy = unreal.ToolMenuInsert("Paste", unreal.ToolMenuInsertType.AFTER) # Next, initialize our menu classes into the edit_menu in the desired section # this menu entry will be added after the Paste entry (insert policy provided) section = "EditMain" Huzzah(menu=edit_menu, section=section, insert_policy=insert_policy)
#//======================================================================================= #// UNREAL PYTHON - CREATE MAPS from templates #// run in unreal python scripts #// for each TYPEDIR place meshes from SET matching #// places Collision meshes from BASE set then meshes from SET #//======================================================================================= import unreal import time # duplicate a map template based on typedir METADIR_ARRAY = ["U","D","R","L"] #METADIR_ARRAY = ["U"] # only one dir for testing START_ARRAY = ["START_R","START_L","START_U","START_D"] END_ARRAY = ["END_R","END_L","END_U","END_D"] DIR_ARRAY = ["TURN_RU","TURN_UL","TURN_LD","TURN_DR","TURN_RD","TURN_UR","TURN_LU","TURN_DL"] STRAIGHT_ARRAY = ["STRAIGHT_R","STRAIGHT_L","STRAIGHT_U","STRAIGHT_D"] #DIR_ARRAY = ["TURN_RU","TURN_DR","TURN_RD","TURN_UR"] TYPEDIR_ARRAY = START_ARRAY + DIR_ARRAY + END_ARRAY + STRAIGHT_ARRAY #SET_ARRAY = ["LEDGE_CAVE_STALAG","LEDGE_FOREST","LEDGE_CLIFF","DIFF_REACTION"] LEDGE_component_ARRAY = ["floor","bot","top","distant","collision"] wedge_max = 1 ATMOSPHERE_TEMPLATE = "00_ATMOSPHERE" current_SET = "FRACTUREMEMORY" # a list of the nodes that should be excluded from directinal groups , end piece directions are reversed PATH_LEDGEDIRU_ANTI_ARRAY = ["TURN_LD","TURN_DR","TURN_DL","TURN_RD","START_D","END_U","STRAIGHT_D"] PATH_LEDGEDIRD_ANTI_ARRAY = ["TURN_RU","TURN_UL","TURN_LU","TURN_UR","START_U","END_D","STRAIGHT_U"] PATH_LEDGEDIRR_ANTI_ARRAY = ["TURN_UL","TURN_LD","TURN_LU","TURN_DL","START_L","END_R","STRAIGHT_L"] PATH_LEDGEDIRL_ANTI_ARRAY = ["TURN_RU","TURN_DR","TURN_RD","TURN_UR","START_R","END_L","STRAIGHT_R"] print("RUNNING UNREAL CREATE PATH SNAPMAPS") actor_location = unreal.Vector(0.0,0.0,0.0) actor_rotation = unreal.Rotator(0.0,0.0,0.0) editor_file_utils = unreal.EditorLoadingAndSavingUtils() # SPAWN ACTOR FUNCTION , SETS PARAMETERS def spawnActor(meshpath,levelname,meshname): obj = unreal.load_asset(meshpath) temp_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(obj, actor_location, actor_rotation) if temp_actor: temp_actor.rename(meshname) level = unreal.find_asset(levelname) static_meshes = unreal.GameplayStatics.get_all_actors_of_class(level, unreal.StaticMeshActor) for mesh in static_meshes : print ("current mesh = " + mesh.get_name() ) #print(dir(mesh)) if ( 'PATH' in mesh.get_name() ): print("setting not relevant for bounds") mesh.set_editor_property("bRelevantForLevelBounds", False) if ( 'collision' in mesh.get_name() ): print("hidden in game") mesh.set_editor_property("bHidden", True) #mesh.SetActorHiddenInGame(True) # CREATE ATMOPSHERE LEVEL FROM TEMPLATE IF DOESNT EXIST atmosphere_level_to_save = '/project/' + "ARPG_" + current_SET + "/" + "ARPG_" + current_SET + "_" + "ATMOSPHERE" print("ATMOSPHERE LEVEL = " + atmosphere_level_to_save) if not unreal.EditorAssetLibrary.does_asset_exist(atmosphere_level_to_save): #atmosphere_template_level = unreal.EditorLevelLibrary.load_level('/project/') #atmosphere_template_level_loaded = editor_file_utils.load_map(atmosphere_template_level) atmosphere_template_level_loaded = editor_file_utils.load_map('/project/') level_saved = editor_file_utils.save_map(atmosphere_template_level_loaded, atmosphere_level_to_save) #atmosphere_level_loaded = unreal.EditorLevelLibrary.load_level(atmosphere_level_to_save) #atmosphere_level_final = unreal.EditorLevelLibrary.get_EditorWorld() wedge_count = 0 while (wedge_count < wedge_max) : # FOR EACH WEDGE for current_METADIR in METADIR_ARRAY: current_ANTI_LEDGEDIR_NAMES = [] if ( "U" in current_METADIR) : current_ANTI_LEDGEDIR_NAMES = PATH_LEDGEDIRU_ANTI_ARRAY if ( "D" in current_METADIR) : current_ANTI_LEDGEDIR_NAMES = PATH_LEDGEDIRD_ANTI_ARRAY if ( "R" in current_METADIR) : current_ANTI_LEDGEDIR_NAMES = PATH_LEDGEDIRR_ANTI_ARRAY if ( "L" in current_METADIR) : current_ANTI_LEDGEDIR_NAMES = PATH_LEDGEDIRL_ANTI_ARRAY for current_DIR in TYPEDIR_ARRAY : # FOR EACH TYPE DIRECTION print("CURRENT_DIR = " + str(current_DIR)) if current_DIR not in current_ANTI_LEDGEDIR_NAMES: level_to_save = '/project/' + "ARPG_" + current_SET + "/" + current_SET + "_" + current_METADIR + "_" + current_DIR + "_" + str(wedge_count) if not unreal.EditorAssetLibrary.does_asset_exist(level_to_save): level_to_load = '/project/' + current_DIR loaded_level = editor_file_utils.load_map(level_to_load) level_saved = editor_file_utils.save_map(loaded_level, level_to_save) load_new_level = editor_file_utils.load_map(level_to_save) #time.sleep(10) # PLACE CORRESPONDING MESHES # BASE - no longer used currrent_BASEComp = "env_area_gen_A_" + str(wedge_count) + "_" + "BASE" + "_" + current_DIR + "_" currrent_BASEComp_sides = currrent_BASEComp + "COL_side" currrent_BASEComp_floor = currrent_BASEComp + "COL_floor" BASEMeshComp_final = '/project/' + "ARPG_" + "BASE" + "/env/" BASE_COL_sides_final = BASEMeshComp_final + currrent_BASEComp_sides + "." + currrent_BASEComp_sides BASE_COL_floor_final = BASEMeshComp_final + currrent_BASEComp_floor + "." + currrent_BASEComp_floor #spawnActor(BASE_COL_sides_final,level_to_save) #print(BASE_COL_sides_final) #spawnActor(BASE_COL_floor_final,level_to_save) #print(BASE_COL_floor_final) # TYPE DIRECTIONS for current_COMPONENT in LEDGE_component_ARRAY : currrent_MeshComp = "PATH_" + str(wedge_count) + "_" + current_SET + "_" + current_METADIR + "_" + current_DIR + "_" + current_COMPONENT MeshComp_final = '/project/' + "ARPG_" + current_SET + "/env/" + currrent_MeshComp + "." + currrent_MeshComp spawnActor(MeshComp_final,level_to_save,currrent_MeshComp) print(MeshComp_final) # Add atmosphere level editor_file_utils.save_current_level() current_level = unreal.EditorLevelLibrary.get_editor_world() #level = unreal.EditorLevelLibrary.load_level('/project/') #atmosphere_level_to_save = '/project/' + "ARPG_" + current_SET + "/" + "ARPG_" + current_SET + "_" + "ATMOSPHERE" #atmosphere_level = unreal.EditorLevelLibrary.load_level(atmosphere_level_to_save) level_streaming_class = unreal.LevelStreamingAlwaysLoaded.static_class() # 'LevelStreamingAlwaysLoaded' unreal.EditorLevelUtils.add_level_to_world(current_level, atmosphere_level_to_save,level_streaming_class) #unreal.EditorLevelLibrary.add_level_to_world(unreal.EditorLevelUtils.get_level_world(), atmosphere_level) editor_file_utils.save_current_level() wedge_count +=1
import unreal import numpy as np import ParametersClass as pc import CaptureImages as ci import pandas as pd import os import airsim import time from multiprocessing import Process TEST_MODE = 2 # SEARCH_MODE = "HIGH_FIDELITY" SEARCH_MODE = "LOW_FIDELITY" RESULTS_FILE_PATH = r"/project/" CAMERA_NAME = "bottom_forward_thermal" SCREENSHOTS_DIR = r"/project/" #Grabs Camera Actor actors = unreal.EditorLevelLibrary.get_all_level_actors() camera_actor = None for actor in actors: if (actor.get_name() == 'CineCameraActor_1'): camera_actor = actor break print(actor) # print(camera_actor) unreal.EditorLevelLibrary.pilot_level_actor(camera_actor) # Grab our PP Thermal Material thermal_mat_inst = unreal.EditorAssetLibrary.load_asset("/project/") # # Initializes data management dataframe df = pd.DataFrame(columns=pc.get_cols_from_test(TEST_MODE))#.reset_index(drop=True) #Create images folder within our results folder images_dir = os.path.join(RESULTS_FILE_PATH, "images") if(not os.path.exists(images_dir)): os.mkdir(images_dir) i = 0 if(TEST_MODE==1): #START OF TEST MODE 1------------------------------------------------------------------------------------------------------------------ if(SEARCH_MODE=="LOW_FIDELITY"): #Set the parameters blend_weight_min=30 blend_weight_max=100 blend_weight_step=2 brightness_min=40 brightness_max=100 brightness_step=2 contrast_min=0 contrast_max=100 contrast_step=5 cold_brightness_multiplier_min=0 cold_brightness_multiplier_max=200 cold_brightness_multiplier_step=10 cold_power_min=-2 cold_power_max=2 cold_power_step=0.2 hot_brightness_multiplier_min=0 hot_brightness_multiplier_max=200 hot_brightness_multiplier_step=10 hot_power_min=-2 hot_power_max=2 hot_power_step=0.2 sky_heat_min=0 sky_heat_max=0.2 sky_heat_step=0.05 fire_heat_min=0 fire_heat_max=1 fire_heat_step=0.05 ground_heat_correction_strength_min=0 ground_heat_correction_strength_max=10000 ground_heat_correction_strength_step=1000 ground_heat_offset_min=0 ground_heat_offset_max=1 ground_heat_offset_step=0.1 person_heat_multiplier_min=0 person_heat_multiplier_max=25 person_heat_multiplier_step=1 target_ground_heat_min=0 target_ground_heat_max=1 target_ground_heat_step=0.1 tree_correction_strength_min=0 tree_correction_strength_max=10000 tree_correction_strength_step=1000 target_tree_heat_min=0 target_tree_heat_max=1 target_tree_heat_step=0.1 vehicle_heat_multiplier_min=0 vehicle_heat_multiplier_max=25 vehicle_heat_multiplier_step=1 elif(SEARCH_MODE=="HIGH_FIDELITY"): #Set the parameters blend_weight_min=30 blend_weight_max=100 blend_weight_step=0.5 brightness_min=40 brightness_max=100 brightness_step=1 contrast_min=0 contrast_max=100 contrast_step=1 cold_brightness_multiplier_min=0 cold_brightness_multiplier_max=200 cold_brightness_multiplier_step=1 cold_power_min=-2 cold_power_max=2 cold_power_step=0.1 hot_brightness_multiplier_min=0 hot_brightness_multiplier_max=10 hot_brightness_multiplier_step=0.2 hot_power_min=-2 hot_power_max=2 hot_power_step=0.1 sky_heat_min=0 sky_heat_max=0.2 sky_heat_step=0.01 fire_heat_min=0.8 fire_heat_max=1 fire_heat_step=0.05 ground_heat_correction_strength_min=0 ground_heat_correction_strength_max=10000 ground_heat_correction_strength_step=10 ground_heat_offset_min=0 ground_heat_offset_max=1 ground_heat_offset_step=0.02 person_heat_multiplier_min=0 person_heat_multiplier_max=25 person_heat_multiplier_step=0.5 target_ground_heat_min=0 target_ground_heat_max=1 target_ground_heat_step=0.01 tree_correction_strength_min=0 tree_correction_strength_max=10000 tree_correction_strength_step=10 target_tree_heat_min=0 target_tree_heat_max=1 target_tree_heat_step=0.01 vehicle_heat_multiplier_min=0 vehicle_heat_multiplier_max=25 vehicle_heat_multiplier_step=0.5 #Set the ranges blend_range = np.arange(blend_weight_min, blend_weight_max, blend_weight_step) brightness_range = np.arange(brightness_min, brightness_max, brightness_step) contrast_range = np.arange(contrast_min, contrast_max, contrast_step) cold_brightness_multiplier_range = np.arange(cold_brightness_multiplier_min, cold_brightness_multiplier_max, cold_brightness_multiplier_step) cold_power_range = np.arange(cold_power_min, cold_power_max, cold_power_step) hot_brightness_multiplier_range = np.arange(hot_brightness_multiplier_min, hot_brightness_multiplier_max, hot_brightness_multiplier_step) hot_power_range = np.arange(hot_power_min, hot_power_max, hot_power_step) sky_heat_range = np.arange(sky_heat_min, sky_heat_max, sky_heat_step) fire_heat_range = np.arange(fire_heat_min, fire_heat_max, fire_heat_step) ground_heat_correction_strength_range = np.arange(ground_heat_correction_strength_min, ground_heat_correction_strength_max, ground_heat_correction_strength_step) ground_heat_offset = np.arange(ground_heat_offset_min, ground_heat_offset_max, ground_heat_offset_step) person_heat_multiplier_range = np.arange(person_heat_multiplier_min, person_heat_multiplier_max, person_heat_multiplier_step) target_ground_heat_range = np.arange(target_ground_heat_min, target_ground_heat_max, target_ground_heat_step) tree_correction_strength_range = np.arange(tree_correction_strength_min, tree_correction_strength_max, tree_correction_strength_step) target_tree_heat_range = np.arange(target_tree_heat_min, target_tree_heat_max, target_tree_heat_step) vehicle_heat_multiplier_range = np.arange(vehicle_heat_multiplier_min, vehicle_heat_multiplier_max, vehicle_heat_multiplier_step) for blend_weight in blend_range: for brightness in brightness_range: for contrast in contrast_range: # contrast 3 for cold_brightness_multiplier in cold_brightness_multiplier_range: # cold brightness multiplier 4 for cold_power in cold_power_range: # cold power 5 for hot_brightness_multiplier in hot_brightness_multiplier_range: for hot_power in hot_power_range: for sky_heat in sky_heat_range: for fire_heat in fire_heat_range: for ground_heat_correction_strength in ground_heat_correction_strength_range: for ground_heat_offset in ground_heat_offset: for person_heat_multiplier in person_heat_multiplier_range: for target_ground_heat in target_ground_heat_range: for tree_correction_strength in tree_correction_strength_range: for target_tree_heat in target_tree_heat_range: for vehicle_heat_multiplier in vehicle_heat_multiplier_range: unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"blend_weight", blend_weight.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Brightness", brightness.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Contrast", contrast.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"cold_brightness_multiplier", cold_brightness_multiplier.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"cold_power", cold_power.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"hot_brightness_multiplier", hot_brightness_multiplier.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"hot_power", hot_power.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"sky_heat", sky_heat.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Fire_Heat", fire_heat.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"ground_heat_correction_strength", ground_heat_correction_strength.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"ground_heat_offset", ground_heat_offset.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"person_heat_multiplier", person_heat_multiplier.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"target_ground_heat", target_ground_heat.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"tree_correction_strength", tree_correction_strength.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"target_tree_heat", target_tree_heat.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"vehicle_heat_multiplier", vehicle_heat_multiplier.item()) time.sleep(0.1) params = [blend_weight, brightness, contrast, cold_brightness_multiplier, cold_power, hot_brightness_multiplier, hot_power, sky_heat, fire_heat, ground_heat_correction_strength, ground_heat_offset, person_heat_multiplier, target_ground_heat, tree_correction_strength, target_tree_heat, vehicle_heat_multiplier] #Save row to dataframe row = pc.create_row(TEST_MODE, i, params, filename) df.loc[len(df.index)] = row #Take Screen Shot unreal.AutomationLibrary.take_high_res_screenshot(1920, 1080, filename, camera = camera_actor) i += 1 elif(TEST_MODE==2): #START OF TEST MODE 2------------------------------------------------------------------------------------------------------------------ if(SEARCH_MODE=="LOW_FIDELITY"): #Set the parameters blend_weight_min=0 blend_weight_max=100 blend_weight_step=2 brightness_min=0 brightness_max=100 brightness_step=2 contrast_min=0 contrast_max=100 contrast_step=5 cold_brightness_multiplier_min=0 cold_brightness_multiplier_max=200 cold_brightness_multiplier_step=10 cold_power_min=-2 cold_power_max=2 cold_power_step=0.2 hot_brightness_multiplier_min=0 hot_brightness_multiplier_max=200 hot_brightness_multiplier_step=10 hot_power_min=-2 hot_power_max=2 hot_power_step=0.2 light_bulb_heat_multiplier_min=0 light_bulb_heat_multiplier_max=1 light_bulb_heat_multiplier_step=0.1 elif(SEARCH_MODE=="HIGH_FIDELITY"): #Set the parameters blend_weight_min=30 blend_weight_max=100 blend_weight_step=0.5 brightness_min=40 brightness_max=100 brightness_step=1 contrast_min=0 contrast_max=100 contrast_step=1 cold_brightness_multiplier_min=0 cold_brightness_multiplier_max=200 cold_brightness_multiplier_step=1 cold_power_min=-2 cold_power_max=2 cold_power_step=0.1 hot_brightness_multiplier_min=0 hot_brightness_multiplier_max=10 hot_brightness_multiplier_step=0.2 hot_power_min=-2 hot_power_max=2 hot_power_step=0.1 light_bulb_heat_multiplier_min=0 light_bulb_heat_multiplier_max=1 light_bulb_heat_multiplier_step=0.01 blend_range = np.arange(blend_weight_min, blend_weight_max, blend_weight_step) brightness_range = np.arange(brightness_min, brightness_max, brightness_step) contrast_range = np.arange(contrast_min, contrast_max, contrast_step) cold_brightness_multiplier_range = np.arange(cold_brightness_multiplier_min, cold_brightness_multiplier_max, cold_brightness_multiplier_step) cold_power_range = np.arange(cold_power_min, cold_power_max, cold_power_step) hot_brightness_multiplier_range = np.arange(hot_brightness_multiplier_min, hot_brightness_multiplier_max, hot_brightness_multiplier_step) hot_power_range = np.arange(hot_power_min, hot_power_max, hot_power_step) light_bulb_heat_multiplier_range = np.arange(light_bulb_heat_multiplier_min, light_bulb_heat_multiplier_max, light_bulb_heat_multiplier_step) for blend_weight in blend_range: for brightness in brightness_range: for contrast in contrast_range: # contrast 3 for cold_brightness_multiplier in cold_brightness_multiplier_range: # cold brightness multiplier 4 for cold_power in cold_power_range: # cold power 5 for hot_brightness_multiplier in hot_brightness_multiplier_range: for hot_power in hot_power_range: for light_bulb_heat_multiplier in light_bulb_heat_multiplier_range: #Strings together filename filename = pc.test_name(TEST_MODE) + "-" + str(i) + ".png" #Sets the parameters in unreal engine environment unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"blend_weight", blend_weight.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Brightness", brightness.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"Contrast", contrast.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"cold_brightness_multiplier", cold_brightness_multiplier.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"cold_power", cold_power.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"hot_brightness_multiplier", hot_brightness_multiplier.item()) unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(thermal_mat_inst,"hot_power", hot_power.item()) #Wait for changes to occur time.sleep(0.1) #Save row to dataframe params = [blend_weight, brightness, contrast, cold_brightness_multiplier, cold_power, hot_brightness_multiplier, hot_power, light_bulb_heat_multiplier] row = pc.create_row(TEST_MODE, i, params, filename) df.loc[len(df.index)] = row # print(df.to_string()) #Take Screen Shot i += 1 print("Line 365") unreal.AutomationLibrary.take_high_res_screenshot(1920, 1080, filename, camera = camera_actor) print("Line 366") # import code; code.interact(local=dict(globals(), **locals())) # print(i) #Just take 2 for testing if(i > 2): # print(df.columns) exit() # pd.display(df) # for file in df.filename: # if(os.path.exists(SCREENSHOTS_DIR + "\\" + file)): # os.rename(SCREENSHOTS_DIR + "\\" + file, RESULTS_FILE_PATH + "\\images\\" + file) # # #Saves file information to excel file # df.to_excel(RESULTS_FILE_PATH + "\\" + pc.test_name(TEST_MODE) + "raw_data.xlsx")
# 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()
# # Copyright(c) 2025 The SPEAR Development Team. Licensed under the MIT License <http://opensource.org/project/>. # Copyright(c) 2022 Intel. Licensed under the MIT License <http://opensource.org/project/>. # import argparse import os import pathlib import spear import spear.utils.editor_utils import trimesh import unreal parser = argparse.ArgumentParser() parser.add_argument("--export_dir", required=True) args = parser.parse_args() asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() unreal_editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem) level_editor_subsystem = unreal.get_editor_subsystem(unreal.LevelEditorSubsystem) editor_world_name = unreal_editor_subsystem.get_editor_world().get_name() def process_scene(): spear.log("Processing scene: ", editor_world_name) actors = spear.utils.editor_utils.find_actors() actors = [ actor for actor in actors if actor.get_editor_property("relevant_for_level_bounds") ] for actor in actors: spear.log(" Processing actor: ", spear.utils.editor_utils.get_stable_name_for_actor(actor)) generate_unreal_geometry(actor) spear.log("Done.") def generate_unreal_geometry(actor): static_mesh_components = spear.utils.editor_utils.get_components(actor=actor, component_class=unreal.StaticMeshComponent) static_meshes = [ static_mesh_component.get_editor_property("static_mesh") for static_mesh_component in static_mesh_components ] static_meshes = [ static_mesh for static_mesh in static_meshes if static_mesh is not None ] static_mesh_asset_paths = [ pathlib.PurePosixPath(static_mesh.get_path_name()) for static_mesh in static_meshes ] for static_mesh_asset_path in static_mesh_asset_paths: spear.log(" Exporting asset: ", static_mesh_asset_path) # Export OBJ file. Note that Unreal swaps the y and z coordinates during export, so that the exported # mesh achieves visual parity with most third-party viewers, despite the unusual handedness conventions # in Unreal. However in our setting, we would prefer numerical parity over visual parity, so we reload # the mesh as soon as we're finished exporting from Unreal, and we swap the y and z coordinates back to # what they were originally. obj_path_suffix = f"{os.path.join(*static_mesh_asset_path.parts[1:])}.obj" raw_obj_path = os.path.realpath(os.path.join(args.export_dir, "scenes", editor_world_name, "unreal_geometry", "raw", obj_path_suffix)) errors = [] asset_export_task = unreal.AssetExportTask() asset_export_task.set_editor_property("automated", True) asset_export_task.set_editor_property("errors", errors) asset_export_task.set_editor_property("exporter", None) asset_export_task.set_editor_property("filename", raw_obj_path) asset_export_task.set_editor_property("ignore_object_list", []) asset_export_task.set_editor_property("object", asset_registry.get_asset_by_object_path(str(static_mesh_asset_path)).get_asset()) asset_export_task.set_editor_property("options", None) asset_export_task.set_editor_property("prompt", False) asset_export_task.set_editor_property("replace_identical", True) asset_export_task.set_editor_property("selected", False) asset_export_task.set_editor_property("use_file_archive", False) asset_export_task.set_editor_property("write_empty_files", False) spear.log(" automated: ", asset_export_task.get_editor_property("automated")) spear.log(" errors: ", asset_export_task.get_editor_property("errors")) spear.log(" exporter: ", asset_export_task.get_editor_property("exporter")) spear.log(" filename: ", asset_export_task.get_editor_property("filename")) spear.log(" ignore_object_list: ", asset_export_task.get_editor_property("ignore_object_list")) spear.log(" object: ", asset_export_task.get_editor_property("object")) spear.log(" options: ", asset_export_task.get_editor_property("options")) spear.log(" prompt: ", asset_export_task.get_editor_property("prompt")) spear.log(" replace_identical: ", asset_export_task.get_editor_property("replace_identical")) spear.log(" selected: ", asset_export_task.get_editor_property("selected")) spear.log(" use_file_archive: ", asset_export_task.get_editor_property("use_file_archive")) spear.log(" write_empty_files: ", asset_export_task.get_editor_property("write_empty_files")) unreal.Exporter.run_asset_export_task(asset_export_task) if len(errors) > 0: spear.log(errors) assert False # Swap y and z coordinates in the mesh that was exported by Unreal. Note that we also need to swap # the winding order of the triangle faces so the meshes still render nicely in MeshLab. We set the # visual attribute to a default value to prevent exporting material info. mesh = trimesh.load_mesh(raw_obj_path, process=False, validate=False) mesh.vertices = mesh.vertices[:,[0,2,1]] mesh.faces = mesh.faces[:,[0,2,1]] mesh.visual = trimesh.visual.ColorVisuals() obj_dir_suffix = os.path.join(*static_mesh_asset_path.parts[1:-1]) numerical_parity_obj_dir = os.path.realpath(os.path.join(args.export_dir, "scenes", editor_world_name, "unreal_geometry", "numerical_parity", obj_dir_suffix)) numerical_parity_obj_path = os.path.realpath(os.path.join(args.export_dir, "scenes", editor_world_name, "unreal_geometry", "numerical_parity", obj_path_suffix)) os.makedirs(numerical_parity_obj_dir, exist_ok=True) with open(numerical_parity_obj_path, "w"): mesh.export(numerical_parity_obj_path, "obj") if __name__ == "__main__": process_scene()
import os.path import unreal import json with open("C:/project/ Projects/project/.json", "r") as f: migration_data = json.load(f) game_folder = "/project/" for k, v in migration_data.items(): src = os.path.join(game_folder, k.replace(".uasset", "")) target = os.path.join(game_folder, v.replace(".uasset", "")) unreal.EditorAssetLibrary.rename_asset(src, target)
#! /project/ python # -*- coding: utf-8 -*- """ Toolbox main UI """ # mca python imports import sys # PySide2 imports from PySide2.QtWidgets import QApplication # software specific imports import unreal # mca python imports from mca.common.tools.toolbox import toolbox_ui, toolbox_editor from mca.common.tools.toolbox import toolbox_data from mca.common.startup.configs import consts from mca.common import log logger = log.MCA_LOGGER class UnrealToolBox(toolbox_ui.ToolboxGui): def __init__(self, toolbox_name, dcc_app=consts.UNREAL, is_floating=True, area='left', parent=None): toolbox_class = toolbox_data.get_toolbox_by_name(toolbox_name) super().__init__(toolbox_class=toolbox_class, dcc_app=dcc_app, is_floating=is_floating, area=area, parent=parent) app = None if not QApplication.instance(): app = QApplication(sys.argv) try: window = self unreal.parent_external_window_to_slate(int(window.winId())) sys.exit(app.exec_()) except Exception as e: print(e) class UnrealToolBoxEditor(toolbox_editor.ToolboxEditor): def __init__(self, parent=None): super().__init__(parent=parent) app = None if not QApplication.instance(): app = QApplication(sys.argv) try: window = self unreal.parent_external_window_to_slate(int(window.winId())) sys.exit(app.exec_()) except Exception as e: print(e)
# Copyright Epic Games, Inc. All Rights Reserved. import unreal import tempfile import unrealcmd import subprocess #------------------------------------------------------------------------------- def _build_include_tool(exec_context, ue_context): # Work out where MSBuild is vswhere = ( "vswhere.exe", "-latest", "-find MSBuild/*/project/.exe", ) proc = subprocess.Popen(" ".join(vswhere), stdout=subprocess.PIPE) msbuild_exe = next(iter(proc.stdout.readline, b""), b"").decode().rstrip() proc.stdout.close() msbuild_exe = msbuild_exe or "MSBuild.exe" # Get MSBuild to build IncludeTool engine = ue_context.get_engine() csproj_path = engine.get_dir() / "Source/project/.csproj" msbuild_args = ( "/target:Restore;Build", "/property:Configuration=Release,Platform=AnyCPU", "/v:m", str(csproj_path) ) return exec_context.create_runnable(msbuild_exe, *msbuild_args).run() == 0 #------------------------------------------------------------------------------- def _run_include_tool(exec_context, ue_context, target, variant, *inctool_args): temp_dir = tempfile.TemporaryDirectory() engine = ue_context.get_engine() it_bin_path = engine.get_dir() / "Binaries/project/.exe" if not it_bin_path.is_file(): it_bin_path = engine.get_dir() / "Binaries/project/.exe" it_args = ( "-Mode=Scan", "-Target=" + target, "-Platform=Linux", "-Configuration=" + variant, "-WorkingDir=" + temp_dir.name, *inctool_args, ) return exec_context.create_runnable(str(it_bin_path), *it_args).run() #------------------------------------------------------------------------------- class RunIncludeTool(unrealcmd.MultiPlatformCmd): """ Runs IncludeTool.exe """ target = unrealcmd.Arg(str, "The target to run the IncludeTool on") variant = unrealcmd.Arg("development", "Build variant to be processed (default=development)") inctoolargs = unrealcmd.Arg([str], "Arguments to pass through to IncludeTool") def complete_target(self, prefix): return ("editor", "game", "client", "server") def main(self): self.use_platform("linux") exec_context = self.get_exec_context() ue_context = self.get_unreal_context() # Establish the target to use try: target = unreal.TargetType[self.args.target.upper()] target = ue_context.get_target_by_type(target).get_name() except: target = self.args.target # Build self.print_info("Building IncludeToole") if not _build_include_tool(exec_context, ue_context): self.print_error("Failed to build IncludeTool") return False # Run variant = self.args.variant self.print_info("Running on", target + "/" + variant) return _run_include_tool(exec_context, ue_context, target, variant, *self.args.inctoolargs)
# _ # (_) # _ __ ___ __ _ _ __ ___ ___ _ __ _ ___ _ __ ___ # | '_ ` _ \ / _` | '_ ` _ \ / _ \| '_ \| |/ _ \ '_ ` _ \ # | | | | | | (_| | | | | | | (_) | | | | | __/ | | | | | # |_| |_| |_|\__,_|_| |_| |_|\___/|_| |_|_|\___|_| |_| |_| # www.mamoniem.com # www.ue4u.xyz #Copyright 2022 Muhammad A.Moniem (@_mamoniem). All Rights Reserved. # import unreal #Set the instances count needed totalRequiredInstances = 10 #General variables, will be auto set newAssetName = "" sourceAssetPath = "" createdAssetsPath = "" @unreal.uclass() class EditorUtil(unreal.GlobalEditorUtilityBase): pass @unreal.uclass() class MaterialEditingLib(unreal.MaterialEditingLibrary): pass editorUtil = EditorUtil() materialEditingLib = MaterialEditingLib() selectedAssets = editorUtil.get_selected_assets() factory = unreal.MaterialInstanceConstantFactoryNew() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() for selectedAsset in selectedAssets: newAssetName = selectedAsset.get_name() + "_%s_%d" sourceAssetPath = selectedAsset.get_path_name() createdAssetsPath = sourceAssetPath.replace(selectedAsset.get_name(), "-") createdAssetsPath = createdAssetsPath.replace("-.-", "") for x in range(totalRequiredInstances): newAsset = asset_tools.create_asset(newAssetName %("inst", x+1), createdAssetsPath, None, factory) materialEditingLib.set_material_instance_parent(newAsset, selectedAsset)
# -*- coding: utf-8 -*- """Collect current project path.""" import os import unreal # noqa import pyblish.api class CollectUnrealCurrentFile(pyblish.api.ContextPlugin): """Inject the current working file into context.""" order = pyblish.api.CollectorOrder - 0.5 label = "Unreal Current File" hosts = ['unreal'] def process(self, context): """Inject the current working file.""" current_file = unreal.Paths.get_project_file_path() context.data["currentFile"] = os.path.abspath(current_file) assert current_file != '', "Current file is empty. " \ "Save the file before continuing."
# -*- coding: utf-8 -*- import unreal from Utilities.Utils import Singleton class MinimalExample(metaclass=Singleton): def __init__(self, jsonPath:str): self.jsonPath = jsonPath self.data = unreal.PythonBPLib.get_chameleon_data(self.jsonPath) self.ui_output = "InfoOutput" self.clickCount = 0 def on_button_click(self): self.clickCount += 1 self.data.set_text(self.ui_output, "Clicked {} time(s)".format(self.clickCount))
# -*- 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))
""" Unreal Python 执行工具 此模块提供在Unreal编辑器中直接执行Python脚本的功能,无需通过MCP连接。 """ import logging from typing import Dict, List, Any, Optional, Union import unreal import json # 获取日志记录器 logger = logging.getLogger("UnrealPythonTools") class UnrealPythonTools: """Unreal引擎Python执行工具类""" @staticmethod def execute_python(script: str) -> Any: """ 在Unreal编辑器中执行Python脚本 Args: script: 要执行的Python脚本字符串 Returns: 脚本的执行结果 """ try: # 直接在编辑器中执行Python脚本 result = eval(script) return result except Exception as e: logger.error(f"执行Python脚本时出错: {e}") return {"error": str(e)} @staticmethod def get_all_actors(): """获取当前关卡中的所有Actor""" try: # 使用Unreal Python API获取所有Actor world = unreal.EditorLevelLibrary.get_editor_world() all_actors = unreal.EditorLevelLibrary.get_all_level_actors() actors_info = [] for actor in all_actors: actor_info = { "name": actor.get_name(), "class": actor.get_class().get_name(), "location": [actor.get_actor_location().x, actor.get_actor_location().y, actor.get_actor_location().z], "rotation": [actor.get_actor_rotation().pitch, actor.get_actor_rotation().yaw, actor.get_actor_rotation().roll], "scale": [actor.get_actor_scale3d().x, actor.get_actor_scale3d().y, actor.get_actor_scale3d().z] } actors_info.append(actor_info) return actors_info except Exception as e: logger.error(f"获取Actor列表时出错: {e}") return {"error": str(e)} @staticmethod def find_actor_by_name(name_pattern: str): """ 按名称模式查找Actor Args: name_pattern: 名称模式(可包含通配符 * 和 ?) Returns: 匹配的Actor列表 """ try: all_actors = unreal.EditorLevelLibrary.get_all_level_actors() matched_actors = [] import fnmatch for actor in all_actors: actor_name = actor.get_name() if fnmatch.fnmatch(actor_name, name_pattern): actor_info = { "name": actor_name, "class": actor.get_class().get_name(), "location": [actor.get_actor_location().x, actor.get_actor_location().y, actor.get_actor_location().z], "rotation": [actor.get_actor_rotation().pitch, actor.get_actor_rotation().yaw, actor.get_actor_rotation().roll], "scale": [actor.get_actor_scale3d().x, actor.get_actor_scale3d().y, actor.get_actor_scale3d().z] } matched_actors.append(actor_info) return matched_actors except Exception as e: logger.error(f"查找Actor时出错: {e}") return {"error": str(e)} @staticmethod def create_actor(actor_class: str, actor_name: str, location: List[float], rotation: List[float], scale: List[float] = None): """ 在场景中创建一个新的Actor Args: actor_class: Actor类名 actor_name: 新Actor的名称 location: [x, y, z] 位置 rotation: [pitch, yaw, roll] 旋转 scale: [x, y, z] 缩放(可选) Returns: 创建的Actor信息 """ try: # 解析位置和旋转 location_vector = unreal.Vector(location[0], location[1], location[2]) rotation_rotator = unreal.Rotator(rotation[0], rotation[1], rotation[2]) # 获取指定的类 actor_class_obj = unreal.find_class(actor_class) if not actor_class_obj: return {"error": f"找不到指定的Actor类: {actor_class}"} # 创建Actor world = unreal.EditorLevelLibrary.get_editor_world() new_actor = unreal.EditorLevelLibrary.spawn_actor_from_class( actor_class_obj, location_vector, rotation_rotator ) # 重命名Actor new_actor.rename(actor_name) # 设置缩放(如果提供) if scale: new_actor.set_actor_scale3d(unreal.Vector(scale[0], scale[1], scale[2])) # 返回创建的Actor信息 actor_info = { "name": new_actor.get_name(), "class": new_actor.get_class().get_name(), "location": [new_actor.get_actor_location().x, new_actor.get_actor_location().y, new_actor.get_actor_location().z], "rotation": [new_actor.get_actor_rotation().pitch, new_actor.get_actor_rotation().yaw, new_actor.get_actor_rotation().roll], "scale": [new_actor.get_actor_scale3d().x, new_actor.get_actor_scale3d().y, new_actor.get_actor_scale3d().z] } return actor_info except Exception as e: logger.error(f"创建Actor时出错: {e}") return {"error": str(e)} @staticmethod def delete_actor(actor_name: str): """ 从场景中删除指定的Actor Args: actor_name: 要删除的Actor名称 Returns: 操作结果 """ try: all_actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in all_actors: if actor.get_name() == actor_name: unreal.EditorLevelLibrary.destroy_actor(actor) return {"success": True, "message": f"已成功删除Actor: {actor_name}"} return {"success": False, "message": f"找不到指定的Actor: {actor_name}"} except Exception as e: logger.error(f"删除Actor时出错: {e}") return {"error": str(e)} @staticmethod def set_actor_transform(actor_name: str, location: List[float] = None, rotation: List[float] = None, scale: List[float] = None): """ 设置Actor的变换(位置、旋转、缩放) Args: actor_name: Actor名称 location: [x, y, z] 新位置 rotation: [pitch, yaw, roll] 新旋转 scale: [x, y, z] 新缩放 Returns: 操作结果 """ try: all_actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in all_actors: if actor.get_name() == actor_name: # 设置位置(如果提供) if location: location_vector = unreal.Vector(location[0], location[1], location[2]) actor.set_actor_location(location_vector, False) # 设置旋转(如果提供) if rotation: rotation_rotator = unreal.Rotator(rotation[0], rotation[1], rotation[2]) actor.set_actor_rotation(rotation_rotator, False) # 设置缩放(如果提供) if scale: scale_vector = unreal.Vector(scale[0], scale[1], scale[2]) actor.set_actor_scale3d(scale_vector) # 返回更新后的Actor信息 actor_info = { "name": actor.get_name(), "location": [actor.get_actor_location().x, actor.get_actor_location().y, actor.get_actor_location().z], "rotation": [actor.get_actor_rotation().pitch, actor.get_actor_rotation().yaw, actor.get_actor_rotation().roll], "scale": [actor.get_actor_scale3d().x, actor.get_actor_scale3d().y, actor.get_actor_scale3d().z] } return {"success": True, "actor": actor_info} return {"success": False, "message": f"找不到指定的Actor: {actor_name}"} except Exception as e: logger.error(f"设置Actor变换时出错: {e}") return {"error": str(e)} @staticmethod def get_asset_list(path: str = "/Game/", recursive: bool = True, class_filter: str = None): """ 获取内容浏览器中的资产列表 Args: path: 内容浏览器路径 recursive: 是否递归搜索子文件夹 class_filter: 可选的类过滤器 Returns: 资产列表 """ try: # 获取资产注册表 asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() # 创建过滤器 ar_filter = unreal.ARFilter( package_paths=[path], recursive_paths=recursive, include_only_on_disk_assets=True ) # 如果提供了类过滤器,则添加到过滤器中 if class_filter: ar_filter.class_names = [class_filter] # 获取资产列表 assets = asset_registry.get_assets(ar_filter) # 转换为易于处理的格式 asset_list = [] for asset in assets: asset_info = { "name": asset.asset_name, "path": asset.object_path, "class": asset.asset_class, "package_name": asset.package_name, "package_path": asset.package_path } asset_list.append(asset_info) return asset_list except Exception as e: logger.error(f"获取资产列表时出错: {e}") return {"error": str(e)} @staticmethod def take_screenshot(filename: str = "screenshot.png", width: int = 1920, height: int = 1080, show_ui: bool = False): """ 拍摄编辑器视口的截图 Args: filename: 截图文件名 width: 截图宽度 height: 截图高度 show_ui: 是否包含UI Returns: 截图操作结果 """ try: # 获取游戏引擎子系统 gameplay_statics = unreal.GameplayStatics # 截图保存路径 screenshot_path = unreal.Paths.project_saved_dir() + "/Screenshots/" + filename # 确保目录存在 import os os.makedirs(os.path.dirname(screenshot_path), exist_ok=True) # 拍摄截图 result = unreal.AutomationLibrary.take_high_res_screenshot( width, height, screenshot_path, not show_ui, # HideUI参数是show_ui的反向值 False, # 不使用HDR "" # 空缓冲区名称 ) return { "success": result, "path": screenshot_path, "width": width, "height": height } except Exception as e: logger.error(f"拍摄截图时出错: {e}") return {"error": str(e)} @staticmethod def execute_console_command(command: str): """ 执行控制台命令 Args: command: 要执行的控制台命令 Returns: 执行结果 """ try: # 执行控制台命令 unreal.EditorLevelLibrary.editor_command(command) return {"success": True, "command": command} except Exception as e: logger.error(f"执行控制台命令时出错: {e}") return {"error": str(e)} @staticmethod def set_material_parameter(actor_name: str, parameter_name: str, value: Any, component_name: str = None, parameter_type: str = "scalar"): """ 设置Actor材质参数 Args: actor_name: Actor名称 parameter_name: 材质参数名称 value: 要设置的值 component_name: 可选组件名称 parameter_type: 参数类型 ("scalar", "vector", "texture") Returns: 操作结果 """ try: # 查找Actor all_actors = unreal.EditorLevelLibrary.get_all_level_actors() target_actor = None for actor in all_actors: if actor.get_name() == actor_name: target_actor = actor break if not target_actor: return {"success": False, "message": f"找不到指定的Actor: {actor_name}"} # 查找组件 mesh_component = None if component_name: # 如果指定了组件名称,则查找该组件 components = unreal.EditorFilterLibrary.by_class( target_actor.get_components(), unreal.StaticMeshComponent ) for component in components: if component.get_name() == component_name: mesh_component = component break if not mesh_component: return {"success": False, "message": f"找不到指定的组件: {component_name}"} else: # 如果未指定组件名称,则使用第一个静态网格体组件 components = unreal.EditorFilterLibrary.by_class( target_actor.get_components(), unreal.StaticMeshComponent ) if len(components) > 0: mesh_component = components[0] else: return {"success": False, "message": f"Actor '{actor_name}' 没有静态网格体组件"} # 获取材质实例 materials = mesh_component.get_materials() if len(materials) == 0: return {"success": False, "message": "没有找到可用的材质"} material = materials[0] # 确保获取的是材质实例 if not material.is_a(unreal.MaterialInstanceDynamic): material_instance = unreal.MaterialEditingLibrary.create_dynamic_material_instance( target_actor, material, f"{actor_name}_DynamicMaterial" ) else: material_instance = material # 根据参数类型设置参数值 if parameter_type.lower() == "scalar": material_instance.set_scalar_parameter_value(parameter_name, float(value)) elif parameter_type.lower() == "vector": if isinstance(value, list) and len(value) >= 3: color = unreal.LinearColor(value[0], value[1], value[2], 1.0 if len(value) < 4 else value[3]) material_instance.set_vector_parameter_value(parameter_name, color) else: return {"success": False, "message": "向量参数必须是包含至少3个元素的列表"} elif parameter_type.lower() == "texture": # 对于纹理参数,value应该是纹理资产路径 texture_asset = unreal.load_asset(value) if not texture_asset or not texture_asset.is_a(unreal.Texture): return {"success": False, "message": f"找不到纹理资产或资产不是纹理: {value}"} material_instance.set_texture_parameter_value(parameter_name, texture_asset) else: return {"success": False, "message": f"不支持的参数类型: {parameter_type}"} return { "success": True, "actor": actor_name, "component": mesh_component.get_name(), "parameter": parameter_name, "value": value, "type": parameter_type } except Exception as e: logger.error(f"设置材质参数时出错: {e}") return {"error": str(e)} # 创建一些直接可调用的辅助函数 def run_python(script_code): """直接运行Python代码""" return UnrealPythonTools.execute_python(script_code) def get_actors(): """获取所有Actor""" return UnrealPythonTools.get_all_actors() def find_actor(name_pattern): """按名称查找Actor""" return UnrealPythonTools.find_actor_by_name(name_pattern) def create_actor(class_name, name, location, rotation, scale=None): """创建Actor""" return UnrealPythonTools.create_actor(class_name, name, location, rotation, scale) def delete_actor(name): """删除Actor""" return UnrealPythonTools.delete_actor(name) def set_transform(actor_name, location=None, rotation=None, scale=None): """设置Actor变换""" return UnrealPythonTools.set_actor_transform(actor_name, location, rotation, scale) def get_assets(path="/Game/", recursive=True, class_filter=None): """获取资产列表""" return UnrealPythonTools.get_asset_list(path, recursive, class_filter) def take_screenshot(filename="screenshot.png", width=1920, height=1080, show_ui=False): """拍摄截图""" return UnrealPythonTools.take_screenshot(filename, width, height, show_ui) def console_command(command): """执行控制台命令""" return UnrealPythonTools.execute_console_command(command) def set_material_param(actor, param_name, value, component=None, param_type="scalar"): """设置材质参数""" return UnrealPythonTools.set_material_parameter(actor, param_name, value, component, param_type)
import unreal import shutil import os import sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) import startup """ Execute this file to setup """ def copy_scripts_to_project_dir(): current_dir = os.path.dirname(os.path.realpath(__file__)) project_dir = unreal.Paths.project_dir() + "Content/" new_folder = "UE_PythonTools" if unreal.Paths.directory_exists(project_dir + new_folder): return None shutil.copytree(src = current_dir, dst = project_dir + new_folder) def add_startup_script_to_config(): section = "[/project/.PythonScriptPluginSettings]" startup_path = unreal.Paths.project_dir() + "Content/project/.py" config_path = unreal.Paths.project_config_dir() + "DefaultEngine.ini" startup_scripts = "+StartupScripts=startup.py" additional_paths = f"+AdditionalPaths=(Path=\'{startup_path}\')" with open(config_path, mode="r") as config: config_str = config.read() if (section in config_str) and (startup_scripts in config_str) and (additional_paths in config_str): return None else: config_str_new = config_str.replace(section, section + "\n" + startup_scripts + "\n" + additional_paths) if config_str_new == config_str: config_str_new = config_str + "\n" + section + "\n" + startup_scripts + "\n" + additional_paths with open(config_path, mode="w") as config: config.write(config_str_new) def main(): copy_scripts_to_project_dir() add_startup_script_to_config() startup.main() print("Setup is over. Check Tools menu and Content/UE_PythonTools Folder.") if __name__ == "__main__": main()
import unreal import os.path import json class bone_limits_struct(): bone_limit_x_min = 0.0 bone_limit_x_max = 0.0 bone_limit_y_min = 0.0 bone_limit_y_max = 0.0 bone_limit_z_min = 0.0 bone_limit_z_max = 0.0 def get_x_range(self): return abs(self.bone_limit_x_max - self.bone_limit_x_min) def get_y_range(self): return abs(self.bone_limit_y_max - self.bone_limit_y_min) def get_z_range(self): return abs(self.bone_limit_z_max - self.bone_limit_z_min) # For getting the preferred angle, it seems like we want the largest angle, not the biggest range def get_x_max_angle(self): return max(abs(self.bone_limit_x_max), abs(self.bone_limit_x_min)) def get_y_max_angle(self): return max(abs(self.bone_limit_y_max), abs(self.bone_limit_y_min)) def get_z_max_angle(self): return max(abs(self.bone_limit_z_max), abs(self.bone_limit_z_min)) def get_preferred_angle(self): if(self.get_x_max_angle() > self.get_y_max_angle() and self.get_x_max_angle() > self.get_z_max_angle()): if abs(self.bone_limit_x_min) > abs(self.bone_limit_x_max): return self.bone_limit_x_min, 0.0, 0.0 return self.bone_limit_x_max, 0.0, 0.0 if(self.get_y_max_angle() > self.get_x_max_angle() and self.get_y_max_angle() > self.get_z_max_angle()): if abs(self.bone_limit_y_min) > abs(self.bone_limit_y_max): return 0.0, self.bone_limit_y_min, 0.0 return 0.0, self.bone_limit_y_max, 0.0 if(self.get_z_max_angle() > self.get_x_max_angle() and self.get_z_max_angle() > self.get_y_max_angle()): if abs(self.bone_limit_z_min) > abs(self.bone_limit_z_max): return 0.0, 0.0, self.bone_limit_z_min return 0.0, 0.0, self.bone_limit_z_max def get_up_vector(self): x, y, z = self.get_preferred_angle() primary_axis = unreal.Vector(x, y, z) primary_axis.normalize() up_axis = unreal.Vector(-1.0 * z, y, -1.0 * x) return up_axis.normal() def get_bone_limits(dtu_json, skeletal_mesh_force_front_x): limits = dtu_json['LimitData'] bone_limits_dict = {} for bone_limits in limits.values(): bone_limits_data = bone_limits_struct() # Get the name of the bone bone_limit_name = bone_limits[0] # Get the bone limits bone_limits_data.bone_limit_x_min = bone_limits[2] bone_limits_data.bone_limit_x_max = bone_limits[3] bone_limits_data.bone_limit_y_min = bone_limits[4] * -1.0 bone_limits_data.bone_limit_y_max = bone_limits[5] * -1.0 bone_limits_data.bone_limit_z_min = bone_limits[6] * -1.0 bone_limits_data.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_limits_data.bone_limit_y_min = bone_limits[2] * -1.0 bone_limits_data.bone_limit_y_max = bone_limits[3] * -1.0 bone_limits_data.bone_limit_z_min = bone_limits[4] * -1.0 bone_limits_data.bone_limit_z_max = bone_limits[5] * -1.0 bone_limits_data.bone_limit_x_min = bone_limits[6] bone_limits_data.bone_limit_x_max = bone_limits[7] bone_limits_dict[bone_limit_name] = bone_limits_data return bone_limits_dict def get_bone_limits_from_skeletalmesh(skeletal_mesh): asset_import_data = skeletal_mesh.get_editor_property('asset_import_data') fbx_path = asset_import_data.get_first_filename() dtu_file = fbx_path.rsplit('.', 1)[0] + '.dtu' dtu_file = dtu_file.replace('/UpdatedFBX/', '/') print(dtu_file) if os.path.exists(dtu_file): dtu_data = json.load(open(dtu_file)) force_front_x = asset_import_data.get_editor_property('force_front_x_axis') bone_limits = get_bone_limits(dtu_data, force_front_x) return bone_limits return [] def get_character_type(dtu_json): asset_id = dtu_json['Asset Id'] if asset_id.lower().startswith('genesis8'): return 'Genesis8' if asset_id.lower().startswith('genesis9'): return 'Genesis9' return 'Unknown' def set_control_shape(blueprint, bone_name, shape_type): hierarchy = blueprint.hierarchy control_name = bone_name + '_ctrl' control_settings_root_ctrl = unreal.RigControlSettings() control_settings_root_ctrl.animation_type = unreal.RigControlAnimationType.ANIMATION_CONTROL control_settings_root_ctrl.control_type = unreal.RigControlType.EULER_TRANSFORM control_settings_root_ctrl.display_name = 'None' control_settings_root_ctrl.draw_limits = True control_settings_root_ctrl.shape_color = unreal.LinearColor(1.000000, 0.000000, 0.000000, 1.000000) control_settings_root_ctrl.shape_visible = True control_settings_root_ctrl.is_transient_control = False control_settings_root_ctrl.limit_enabled = [unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False), unreal.RigControlLimitEnabled(False, False)] control_settings_root_ctrl.minimum_value = unreal.RigHierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[0.000000,0.000000,0.000000])) control_settings_root_ctrl.maximum_value = unreal.RigHierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[0.000000,0.000000,0.000000])) control_settings_root_ctrl.primary_axis = unreal.RigControlAxis.X if shape_type == "root": control_settings_root_ctrl.shape_name = 'Square_Thick' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[10.000000,10.000000,10.000000]), True) if shape_type == "hip": control_settings_root_ctrl.shape_name = 'Hexagon_Thick' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[10.000000,10.000000,10.000000]), True) if shape_type == "iktarget": control_settings_root_ctrl.shape_name = 'Box_Thin' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) #hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[10.000000,10.000000,10.000000]), True) if shape_type == "large_2d_bend": control_settings_root_ctrl.shape_name = 'Arrow4_Thick' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[8.000000,8.000000,8.000000]), True) if shape_type == "slider": control_settings_root_ctrl.control_type = unreal.RigControlType.FLOAT control_settings_root_ctrl.primary_axis = unreal.RigControlAxis.Y control_settings_root_ctrl.limit_enabled = [unreal.RigControlLimitEnabled(True, True)] control_settings_root_ctrl.minimum_value = unreal.RigHierarchy.make_control_value_from_float(0.000000) control_settings_root_ctrl.maximum_value = unreal.RigHierarchy.make_control_value_from_float(1.000000) control_settings_root_ctrl.shape_name = 'Arrow2_Thin' hierarchy.set_control_settings(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), control_settings_root_ctrl) hierarchy.set_control_shape_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.Transform(location=[0.000000,0.000000,0.000000],rotation=[0.000000,0.000000,0.000000],scale=[0.5,0.5,0.5]), True) last_construction_link = 'PrepareForExecution' construction_y_pos = 200 def create_construction(blueprint, bone_name): global last_construction_link global construction_y_pos rig_controller = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() 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(1000.0, construction_y_pos), 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(1300.0, construction_y_pos), 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 construction_y_pos = construction_y_pos + 250 last_backward_solver_link = 'InverseExecution.ExecuteContext' def create_backward_solver(blueprint, 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 = blueprint.get_controller_by_name('RigVMModel') if rig_controller is None: rig_controller = blueprint.get_controller() #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 parent_control_to_control(hierarchy_controller, parent_control_name ,control_name): hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=parent_control_name), False) def parent_control_to_bone(hierarchy_controller, parent_bone_name, control_name): hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.RigElementKey(type=unreal.RigElementType.BONE, name=parent_bone_name), False) next_forward_execute = 'BeginExecution.ExecuteContext' node_y_pos = 200.0 def create_control(blueprint, bone_name, parent_bone_name, shape_type): global next_forward_execute global node_y_pos hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() 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) hierarchy_controller.remove_element(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_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) #hierarchy_controller.remove_all_parents(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), True) transform = hierarchy.get_global_transform(key, True) hierarchy.set_control_offset_transform(control_key, transform, True) hierarchy.set_control_offset_transform(control_key, transform, False) #hierarchy.set_global_transform(control_key, unreal.Transform(), True) #hierarchy.set_global_transform(control_key, unreal.Transform(), False) #hierarchy.set_global_transform(control_key, transform, False) # if bone_name in control_list: # create_direct_control(bone_name) # elif bone_name in effector_list: # create_effector(bone_name) #create_direct_control(bone_name) create_construction(blueprint, bone_name) create_backward_solver(blueprint, bone_name) set_control_shape(blueprint, bone_name, shape_type) if shape_type in ['iktarget', 'large_2d_bend', 'slider']: return control_name # Link Control to Bone get_transform_node_name = bone_name + "_GetTransform" # blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(49.941063, node_y_pos), get_transform_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(get_transform_node_name + '.Item', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Space', 'GlobalSpace') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.bInitial', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Name', control_name, True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Type', 'Control', True) set_transform_node_name = bone_name + "_SetTransform" blueprint.get_controller_by_name('RigVMModel').add_template_node('Set Transform::Execute(in Item,in Space,in bInitial,in Value,in Weight,in bPropagateToChildren)', unreal.Vector2D(701.941063, node_y_pos), set_transform_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Item', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(set_transform_node_name + '.Item', False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Space', 'GlobalSpace') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.bInitial', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Weight', '1.000000') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.bPropagateToChildren', 'True') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Item.Name', bone_name, True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Item.Type', 'Bone', True) #blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(set_transform_node_name + '.Transform', '(Rotation=(X=0.000000,Y=0.000000,Z=0.000000,W=1.000000),Translation=(X=0.000000,Y=0.000000,Z=0.000000),Scale3D=(X=1.000000,Y=1.000000,Z=1.000000))', True) blueprint.get_controller_by_name('RigVMModel').add_link(get_transform_node_name + '.Transform', set_transform_node_name + '.Value') blueprint.get_controller_by_name('RigVMModel').add_link(next_forward_execute, set_transform_node_name + '.ExecuteContext') next_forward_execute = set_transform_node_name + '.ExecuteContext' if parent_bone_name: parent_control_name = parent_bone_name + '_ctrl' #hierarchy_controller.set_parent(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=control_name), unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=parent_control_name), True) node_y_pos = node_y_pos + 200 return control_name def create_limb_ik(blueprint, skeleton, bone_limits, root_bone_name, end_bone_name, shape_type): global next_forward_execute global node_y_pos end_bone_ctrl = end_bone_name + '_ctrl' hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() rig_controller = blueprint.get_controller_by_name('RigVMModel') limb_ik_node_name = end_bone_name + '_FBIK' rig_controller.add_unit_node_from_struct_path('/project/.RigUnit_PBIK', 'Execute', unreal.Vector2D(370.599976, node_y_pos), limb_ik_node_name) rig_controller.set_pin_default_value(limb_ik_node_name + '.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(limb_ik_node_name + '.Root', root_bone_name, False) root_FBIK_settings = rig_controller.insert_array_pin(limb_ik_node_name + '.BoneSettings', -1, '') rig_controller.set_pin_default_value(root_FBIK_settings + '.Bone', 'pelvis', False) rig_controller.set_pin_default_value(root_FBIK_settings + '.RotationStiffness', '1.0', False) rig_controller.set_pin_default_value(root_FBIK_settings + '.PositionStiffness', '1.0', False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(limb_ik_node_name + '.Settings.RootBehavior', 'PinToInput', False) get_transform_node_name = end_bone_name + "_GetTransform" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(49.941063, node_y_pos), get_transform_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(get_transform_node_name + '.Item', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Space', 'GlobalSpace') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.bInitial', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Name', end_bone_ctrl, True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Type', 'Control', True) pin_name = rig_controller.insert_array_pin(limb_ik_node_name + '.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_node_name + '.Transform', pin_name + '.Transform') rig_controller.set_pin_default_value(pin_name + '.Bone', end_bone_name, False) # if(bone_name in guide_list): # rig_controller.set_pin_default_value(pin_name + '.StrengthAlpha', '0.200000', False) # Limb Root Bone Settings # bone_settings_name = blueprint.get_controller_by_name('RigVMModel').insert_array_pin(limb_ik_node_name + '.BoneSettings', -1, '') # blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.Bone', root_bone_name, False) # blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.RotationStiffness', '1.000000', False) # blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.PositionStiffness', '1.000000', False) # Joint Bone Settings joint_bone_name = unreal.DazToUnrealBlueprintUtils.get_joint_bone(skeleton, root_bone_name, end_bone_name); bone_settings_name = blueprint.get_controller_by_name('RigVMModel').insert_array_pin(limb_ik_node_name + '.BoneSettings', -1, '') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.Bone', joint_bone_name, False) #blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.RotationStiffness', '1.000000', False) #blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(bone_settings_name + '.PositionStiffness', '1.000000', False) #print(bone_limits) x_preferred, y_preferred, z_preferred = bone_limits[str(joint_bone_name)].get_preferred_angle() # Figure out preferred angles, the primary angle is the one that turns the furthest from base pose rig_controller.set_pin_default_value(bone_settings_name + '.bUsePreferredAngles', 'true', False) rig_controller.set_pin_default_value(bone_settings_name + '.PreferredAngles.X', str(x_preferred), False) rig_controller.set_pin_default_value(bone_settings_name + '.PreferredAngles.Y', str(y_preferred), False) rig_controller.set_pin_default_value(bone_settings_name + '.PreferredAngles.Z', str(z_preferred), False) blueprint.get_controller_by_name('RigVMModel').add_link(next_forward_execute, limb_ik_node_name + '.ExecuteContext') node_y_pos = node_y_pos + 400 next_forward_execute = limb_ik_node_name + '.ExecuteContext' def create_2d_bend(blueprint, skeleton, bone_limits, start_bone_name, end_bone_name, shape_type): global node_y_pos global next_forward_execute ctrl_name = create_control(blueprint, start_bone_name, None, 'large_2d_bend') distribute_node_name = start_bone_name + "_to_" + end_bone_name + "_DistributeRotation" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_DistributeRotationForItemArray', 'Execute', unreal.Vector2D(365.055382, node_y_pos), distribute_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(distribute_node_name + '.RotationEaseType', 'Linear') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(distribute_node_name + '.Weight', '0.25') item_collection_node_name = start_bone_name + "_to_" + end_bone_name + "_ItemCollection" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_CollectionChainArray', 'Execute', unreal.Vector2D(120.870192, node_y_pos), item_collection_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.FirstItem', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(item_collection_node_name + '.FirstItem', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.LastItem', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(item_collection_node_name + '.LastItem', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.Reverse', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.FirstItem.Name', start_bone_name, False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.LastItem.Name', end_bone_name, False) blueprint.get_controller_by_name('RigVMModel').add_link(item_collection_node_name + '.Items', distribute_node_name + '.Items') get_transform_node_name = ctrl_name + "_2dbend_GetTransform" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_GetTransform', 'Execute', unreal.Vector2D(49.941063, node_y_pos), get_transform_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(get_transform_node_name + '.Item', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Space', 'GlobalSpace') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.bInitial', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Name', ctrl_name, True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(get_transform_node_name + '.Item.Type', 'Control', True) rotation_pin = blueprint.get_controller_by_name('RigVMModel').insert_array_pin(distribute_node_name + '.Rotations', -1, '') print(rotation_pin) blueprint.get_controller_by_name('RigVMModel').add_link(get_transform_node_name + '.Transform.Rotation', rotation_pin + '.Rotation') #blueprint.get_controller_by_name('RigVMModel').add_link('rHand_GetTransform.Transform.Rotation', 'abdomenLower_to_chestUpper_DistributeRotation.Rotations.0.Rotation') blueprint.get_controller_by_name('RigVMModel').add_link(next_forward_execute, distribute_node_name + '.ExecuteContext') node_y_pos = node_y_pos + 350 next_forward_execute = distribute_node_name + '.ExecuteContext' def create_slider_bend(blueprint, skeleton, bone_limits, start_bone_name, end_bone_name, parent_control_name): global node_y_pos global next_forward_execute hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() ctrl_name = create_control(blueprint, start_bone_name, None, 'slider') distribute_node_name = start_bone_name + "_to_" + end_bone_name + "_DistributeRotation" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_DistributeRotationForItemArray', 'Execute', unreal.Vector2D(800.0, node_y_pos), distribute_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(distribute_node_name + '.RotationEaseType', 'Linear') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(distribute_node_name + '.Weight', '0.25') rotation_pin = blueprint.get_controller_by_name('RigVMModel').insert_array_pin(distribute_node_name + '.Rotations', -1, '') item_collection_node_name = start_bone_name + "_to_" + end_bone_name + "_ItemCollection" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_CollectionChainArray', 'Execute', unreal.Vector2D(120.0, node_y_pos), item_collection_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.FirstItem', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(item_collection_node_name + '.FirstItem', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.LastItem', '(Type=Bone,Name="None")') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(item_collection_node_name + '.LastItem', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.Reverse', 'False') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.FirstItem.Name', start_bone_name, False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(item_collection_node_name + '.LastItem.Name', end_bone_name, False) blueprint.get_controller_by_name('RigVMModel').add_link(item_collection_node_name + '.Items', distribute_node_name + '.Items') # Create Rotation Node rotation_node_name = start_bone_name + "_to_" + end_bone_name + "_Rotation" x_preferred, y_preferred, z_preferred = bone_limits[start_bone_name].get_preferred_angle() blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigVMFunction_MathQuaternionFromEuler', 'Execute', unreal.Vector2D(350.0, node_y_pos), rotation_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.Euler', '(X=0.000000,Y=0.000000,Z=0.000000)') blueprint.get_controller_by_name('RigVMModel').set_pin_expansion(rotation_node_name + '.Euler', True) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.RotationOrder', 'ZYX') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.Euler.X', str(x_preferred * -1.0), False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.Euler.Y', str(y_preferred), False) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(rotation_node_name + '.Euler.Z', str(z_preferred), False) # Get Control Float control_float_node_name = start_bone_name + "_to_" + end_bone_name + "_ControlFloat" blueprint.get_controller_by_name('RigVMModel').add_unit_node_from_struct_path('/project/.RigUnit_GetControlFloat', 'Execute', unreal.Vector2D(500.0, node_y_pos), control_float_node_name) blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(control_float_node_name + '.Control', 'None') blueprint.get_controller_by_name('RigVMModel').set_pin_default_value(control_float_node_name + '.Control', ctrl_name, False) blueprint.get_controller_by_name('RigVMModel').add_link(rotation_node_name + '.Result', rotation_pin + '.Rotation') blueprint.get_controller_by_name('RigVMModel').add_link(next_forward_execute, distribute_node_name + '.ExecuteContext') blueprint.get_controller_by_name('RigVMModel').add_link(control_float_node_name + '.FloatValue', distribute_node_name + '.Weight') parent_control_to_control(hierarchy_controller, parent_control_name, ctrl_name) # Offset the control so it's not in the figure. Not working... up_vector = bone_limits[start_bone_name].get_up_vector() #up_transform = unreal.Transform(location=up_vector,rotation=[0.000000,0.000000,0.000000],scale=[1.000000,1.000000,1.000000]) #up_transform = unreal.Transform(location=[0.0, 0.0, 50.0],rotation=[0.000000,0.000000,0.000000],scale=[1.000000,1.000000,1.000000]) #hierarchy.set_control_offset_transform(unreal.RigElementKey(type=unreal.RigElementType.CONTROL, name=ctrl_name), up_transform) node_y_pos = node_y_pos + 350 next_forward_execute = distribute_node_name + '.ExecuteContext'
import unreal class AssetRenamer(object): systemLibrary = unreal.systemLibrary() editor_util = unreal.EditorUtiltyLibrary() string_lib = unreal.StringLibrary() UseCase = False replaced = 0 def __init__(self): rename_assets() def ResolveDependencies(): if systemLibrary is None: systemLibrary = unreal.SystemLibrary() if editor_util is None: editorUtility = unreal.EditorUtilityLibrary() if StringLibrary is None: StringLibrary = unreal.StringLibrary() def RenameAsset(UseCase): if string_lib.contains(asset_name, search_pattern, use_case=UseCase): replacedName = string_lib.replace(asset_name, search_pattern, replace_pattern) editor_util.rename_asset(asset, replacedName) replaced += 1 unreal.log("Replaced {} with {}".format(asset, replacedName)) else: unreal.log("{} did not match the search pattern, was skipped".format(asset_name)) def rename_assets(): selected_assets = editor_util.selected_assets() number_of_assets = len(selected_assets) UseCase = unreal.SearchCase.CASE_SENSITIVE if UseCase else unreal.SearchCase.IGNORE_CASE for asset in selected_assets: asset_name = systemLibrary.get_object_name(asset) if UseCase == False: RenameAsset(UseCase, asset_name) elif UseCase == True: RenameAsset(UseCase, asset_name)
import json from enum import Enum, auto import inspect from typing import Callable, Union from concurrent.futures import ThreadPoolExecutor, Future from threading import Lock import logging import unreal logger = logging.getLogger(__name__) class FuncType(Enum): STATIC_METHOD = auto() CLASS_METHOD = auto() LAMBDA = auto() UNBOUND_METHOD = auto() INSTANCE_METHOD = auto() INSTANCE_METHOD_OF_CLASS = auto() STATIC_FUNCTION = auto() BUILTIN = auto() UNKNOWN = auto() def get_func_type(callback: callable, cls=None) -> FuncType: if isinstance(callback, staticmethod): return FuncType.STATIC_METHOD if not callable(callback): raise ValueError("callback must be a callable object") if cls: for _, obj in cls.__dict__.items(): if obj is callback: if isinstance(obj, staticmethod): return FuncType.STATIC_METHOD elif isinstance(obj, classmethod): return FuncType.CLASS_METHOD break elif isinstance(callback, staticmethod): return FuncType.STATIC_METHOD if hasattr(callback, "__name__") and callback.__name__ == "<lambda>": return FuncType.LAMBDA if inspect.ismethod(callback): if callback.__self__ is None: return FuncType.UNBOUND_METHOD elif isinstance(callback.__self__, type): return FuncType.CLASS_METHOD else: return FuncType.INSTANCE_METHOD if inspect.isfunction(callback): params_names = list(inspect.signature(callback).parameters.keys()) if params_names and params_names[0] == "self": return FuncType.INSTANCE_METHOD_OF_CLASS return FuncType.STATIC_FUNCTION if inspect.isbuiltin(callback): return FuncType.BUILTIN return FuncType.UNKNOWN class ChameleonTaskExecutor: """ ChameleonTaskExecutor is a class for managing and executing tasks in parallel. It uses a ThreadPoolExecutor to run tasks concurrently. """ def __init__(self, owner): """ Initialize the ChameleonTaskExecutor with the owner of the tasks. """ assert isinstance(owner.data, unreal.ChameleonData) self.owner = owner self.executor = ThreadPoolExecutor() self.futures_dict = {} self.lock = Lock() @staticmethod def _find_var_name_in_outer(target_var, by_type:bool=False)->str: frames = inspect.getouterframes(inspect.currentframe()) top_frame = frames[-1] instance_name_in_global = "" for k, v in top_frame.frame.f_globals.items(): if by_type: if isinstance(v, target_var): # print(f"!! found: {k} @ frame: frame count: {len(frames)}") instance_name_in_global = k break if type(v) == target_var: # print(f"!! found: {k} @ frame: frame count: {len(frames)}") instance_name_in_global = k break else: if v == target_var: # print(f"!! found: {k} @ frame: frame count: {len(frames)}") instance_name_in_global = k break return instance_name_in_global @staticmethod def _number_of_param(callback)->int: try: if isinstance(callback, str): param_str = callback[callback.find("("): callback.find(")") + 1].strip() return param_str[1:-1].find(",") else: sig = inspect.signature(callback) param_count = len(sig.parameters) return param_count except Exception as e: print(e) return 0 @staticmethod def _get_balanced_bracket_code(content, file_name, lineno): def _is_brackets_balanced(content): v = 0 for c in content: if c == "(": v += 1 elif c == ")": v -= 1 return v == 0 if "(" in content and _is_brackets_balanced(content): return content try: with open(file_name, 'r', encoding="utf-8") as f: lines = f.readlines() line = "" for i in range(lineno-1, len(lines)): line += lines[i].strip() if "(" in line and _is_brackets_balanced(line): return line except Exception as e: raise RuntimeError(f"Failed to process file {file_name} line {lineno} : {e}") return None @staticmethod def get_cmd_str_from_callable(callback: Union[callable, str]) -> str: """Get the command string from a callable object. The command string is used to call the callable object""" if isinstance(callback, str): return callback callback_type = get_func_type(callback) if callback_type == FuncType.BUILTIN: return "{}(%)".format(callback.__qualname__) elif callback_type == FuncType.LAMBDA: raise ValueError("Lambda function is not supported") else: frames = inspect.getouterframes(inspect.currentframe()) last_callable_frame_idx = -1 for i, frame in enumerate(frames): for var_name, var_value in frame.frame.f_locals.items(): if callable(var_value) and hasattr(var_value, "__code__"): if var_value.__code__ == callback.__code__: last_callable_frame_idx = i # The upper frame of the last callable frame is the frame that contains the callback, # so we can get the code context of the callback from the upper frame upper_frame = frames[last_callable_frame_idx + 1] if len(frames) > last_callable_frame_idx + 1 else None code_context = "".join(upper_frame.code_context) code_line = ChameleonTaskExecutor._get_balanced_bracket_code(code_context, upper_frame.filename, upper_frame.lineno) callback_params = code_line[code_line.index("(") + 1: code_line.rfind(")")].split(",") callback_param = "" for param in callback_params: if callback.__name__ in param: callback_param = param if "=" not in param else param[param.index('=')+1:] break if callback_param: # found if callback_type == FuncType.INSTANCE_METHOD or callback_param.startswith("self."): instance_name = ChameleonTaskExecutor._find_var_name_in_outer(upper_frame.frame.f_locals["self"]) cmd = f"{instance_name}.{callback_param[callback_param.index('.') + 1:]}(%)" else: cmd = f"{callback_param}(%)" return cmd return f"{callback.__qualname__}(%)" def submit_task(self, task:Callable, args=None, kwargs=None, on_finish_callback: Union[Callable, str] = None)-> int: """ Submit a task to be executed. The task should be a callable object. Args and kwargs are optional arguments to the task. Callback is an optional function to be called when the task is done. """ if args is None: args = [] if kwargs is None: kwargs = {} future = self.executor.submit(task, *args, **kwargs) assert future is not None, "future is None" future_id = id(future) with self.lock: self.futures_dict[future_id] = future if on_finish_callback: cmd = ChameleonTaskExecutor.get_cmd_str_from_callable(on_finish_callback) param_count = ChameleonTaskExecutor._number_of_param(on_finish_callback) cmd = cmd.replace("%", str(future_id) if param_count else "") def _func(_future): unreal.PythonBPLib.exec_python_command(cmd, force_game_thread=True) future.add_done_callback(_func) unreal.log(f"submit_task callback cmd: {cmd}, param_count: {param_count}") return future_id def get_future(self, future_id)-> Future: with self.lock: return self.futures_dict.get(future_id, None) def get_task_is_running(self, future_id)-> bool: future = self.get_future(future_id) if future is not None: return future.running() return False def is_any_task_running(self): for future_id in self.futures_dict.keys(): if self.get_task_is_running(future_id): return True return False
# -*- coding: utf-8 -*- import logging import unreal import inspect import types import Utilities from collections import Counter class attr_detail(object): def __init__(self, obj, name:str): self.name = name attr = None self.bCallable = None self.bCallable_builtin = None try: if hasattr(obj, name): attr = getattr(obj, name) self.bCallable = callable(attr) self.bCallable_builtin = inspect.isbuiltin(attr) except Exception as e: unreal.log(str(e)) self.bProperty = not self.bCallable self.result = None self.param_str = None self.bEditorProperty = None self.return_type_str = None self.doc_str = None self.property_rw = None if self.bCallable: self.return_type_str = "" if self.bCallable_builtin: if hasattr(attr, '__doc__'): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) # print(f"~~~~~ attr: {self.name} docForDisplay: {docForDisplay} paramStr: {paramStr}") # print(attr.__doc__) try: sig = inspect.getargspec(getattr(obj, self.name)) # print("+++ ", sig) args = sig.args argCount = len(args) if "self" in args: argCount -= 1 except TypeError: argCount = -1 if "-> " in docForDisplay: self.return_type_str = docForDisplay[docForDisplay.find(')') + 1:] else: self.doc_str = docForDisplay[docForDisplay.find(')') + 1:] if argCount == 0 or (argCount == -1 and paramStr == ''): # Method with No params if '-> None' not in docForDisplay or self.name in ["__reduce__", "_post_init"]: try: if name == "get_actor_time_dilation" and isinstance(obj, unreal.Object): # call get_actor_time_dilation will crash engine if actor is get from CDO and has no world. if obj.get_world(): # self.result = "{}".format(attr.__call__()) self.result = attr.__call__() else: self.result = "skip call, world == None." else: # self.result = "{}".format(attr.__call__()) self.result = attr.__call__() except: self.result = "skip call.." else: print(f"docForDisplay: {docForDisplay}, self.name: {self.name}") self.result = "skip call." else: self.param_str = paramStr self.result = "" else: logging.error("Can't find p") elif self.bCallable_other: if hasattr(attr, '__doc__'): if isinstance(attr.__doc__, str): docForDisplay, paramStr = _simplifyDoc(attr.__doc__) if name in ["__str__", "__hash__", "__repr__", "__len__"]: try: self.result = "{}".format(attr.__call__()) except: self.result = "skip call." else: # self.result = "{}".format(getattr(obj, name)) self.result = getattr(obj, name) def post(self, obj): if self.bOtherProperty and not self.result: try: self.result = getattr(obj, self.name) except: self.result = "skip call..." def apply_editor_property(self, obj, type_, rws, descript): self.bEditorProperty = True self.property_rw = "[{}]".format(rws) try: self.result = eval('obj.get_editor_property("{}")'.format(self.name)) except: self.result = "Invalid" def __str__(self): s = f"Attr: {self.name} paramStr: {self.param_str} desc: {self.return_type_str} result: {self.result}" if self.bProperty: s += ", Property" if self.bEditorProperty: s += ", Eidtor Property" if self.bOtherProperty: s += ", Other Property " if self.bCallable: s += ", Callable" if self.bCallable_builtin: s += ", Callable_builtin" if self.bCallable_other: s += ", bCallable_other" if self.bHasParamFunction: s+= ", bHasParamFunction" return s def check(self): counter = Counter([self.bOtherProperty, self.bEditorProperty, self.bCallable_other, self.bCallable_builtin]) # print("counter: {}".format(counter)) if counter[True] == 2: unreal.log_error(f"{self.name}: {self.bEditorProperty}, {self.bOtherProperty} {self.bCallable_builtin} {self.bCallable_other}") @property def bOtherProperty(self): if self.bProperty and not self.bEditorProperty: return True return False @property def bCallable_other(self): if self.bCallable and not self.bCallable_builtin: return True return False @property def display_name(self, bRichText=True): if self.bProperty: return f"\t{self.name}" else: # callable if self.param_str: return f"\t{self.name}({self.param_str}) {self.return_type_str}" else: if self.bCallable_other: return f"\t{self.name}" # __hash__, __class__, __eq__ 等 else: return f"\t{self.name}() {self.return_type_str}" @property def display_result(self) -> str: if self.bEditorProperty: return "{} {}".format(self.result, self.property_rw) else: return "{}".format(self.result) @property def bHasParamFunction(self): return self.param_str and len(self.param_str) != 0 def ll(obj): if not obj: return None if inspect.ismodule(obj): return None result = [] for x in dir(obj): attr = attr_detail(obj, x) result.append(attr) if hasattr(obj, '__doc__') and isinstance(obj, unreal.Object): editorPropertiesInfos = _getEditorProperties(obj.__doc__, obj) for name, type_, rws, descript in editorPropertiesInfos: # print(f"~~ {name} {type} {rws}, {descript}") index = -1 for i, v in enumerate(result): if v.name == name: index = i break if index != -1: this_attr = result[index] else: this_attr = attr_detail(obj, name) result.append(this_attr) # unreal.log_warning(f"Can't find editor property: {name}") this_attr.apply_editor_property(obj, type_, rws, descript) for i, attr in enumerate(result): attr.post(obj) return result def _simplifyDoc(content): def next_balanced(content, s="(", e = ")" ): s_pos = -1 e_pos = -1 balance = 0 for index, c in enumerate(content): match = c == s or c == e if not match: continue balance += 1 if c == s else -1 if c == s and balance == 1 and s_pos == -1: s_pos = index if c == e and balance == 0 and s_pos != -1 and e_pos == -1: e_pos = index return s_pos, e_pos return -1, -1 # bracketS, bracketE = content.find('('), content.find(')') if not content: return "", "" bracketS, bracketE = next_balanced(content, s='(', e = ')') arrow = content.find('->') funcDocPos = len(content) endSign = ['--', '\n', '\r'] for s in endSign: p = content.find(s) if p != -1 and p < funcDocPos: funcDocPos = p funcDoc = content[:funcDocPos] if bracketS != -1 and bracketE != -1: param = content[bracketS + 1: bracketE].strip() else: param = "" return funcDoc, param def _getEditorProperties(content, obj): # print("Content: {}".format(content)) lines = content.split('\r') signFound = False allInfoFound = False result = [] for line in lines: if not signFound and '**Editor Properties:**' in line: signFound = True if signFound: #todo re # nameS, nameE = line.find('``') + 2, line.find('`` ') nameS, nameE = line.find('- ``') + 4, line.find('`` ') if nameS == -1 or nameE == -1: continue typeS, typeE = line.find('(') + 1, line.find(')') if typeS == -1 or typeE == -1: continue rwS, rwE = line.find('[') + 1, line.find(']') if rwS == -1 or rwE == -1: continue name = line[nameS: nameE] type_str = line[typeS: typeE] rws = line[rwS: rwE] descript = line[rwE + 2:] allInfoFound = True result.append((name, type_str, rws, descript)) # print(name, type, rws) if signFound: if not allInfoFound: unreal.log_warning("not all info found {}".format(obj)) else: unreal.log_warning("can't find editor properties in {}".format(obj)) return result def log_classes(obj): print(obj) print("\ttype: {}".format(type(obj))) print("\tget_class: {}".format(obj.get_class())) if type(obj.get_class()) is unreal.BlueprintGeneratedClass: generatedClass = obj.get_class() else: generatedClass = unreal.PythonBPLib.get_blueprint_generated_class(obj) print("\tgeneratedClass: {}".format(generatedClass)) print("\tbp_class_hierarchy_package: {}".format(unreal.PythonBPLib.get_bp_class_hierarchy_package(generatedClass))) def is_selected_asset_type(types): selectedAssets = Utilities.Utils.get_selected_assets() for asset in selectedAssets: if type(asset) in types: return True; return False
import unreal asset_data = [] def AddAsset(assetName, assetFilePath): assetData = unreal.EditorAssetLibrary.find_asset_data(assetFilePath) asset = str(assetData) unreal.log(asset) assetClassStartPos = asset.index('asset_class_path') assetClassStartPos = asset.index('asset_name', assetClassStartPos) + 13 assetClassEndPos = asset.index('"', assetClassStartPos) assetClass = asset[assetClassStartPos : assetClassEndPos] asset_data.append(assetName) asset_data.append(assetClass) asset_data.append(assetFilePath) return asset_data
# /project/ # @CBgameDev Optimisation Script - Log Sound Cues Missing Concurrency Settings # /project/ import unreal import os EditAssetLib = unreal.EditorAssetLibrary() SystemsLib = unreal.SystemLibrary workingPath = "/Game/" # Using the root directory notepadFilePath = os.path.dirname(__file__) + "//PythonOptimiseLog.txt" allAssets = EditAssetLib.list_assets(workingPath, True, False) selectedAssetsPath = workingPath LogStringsArray = [] numOfOptimisations = 0 with unreal.ScopedSlowTask(len(allAssets), selectedAssetsPath) as ST: ST.make_dialog(True) for asset in allAssets: _assetData = EditAssetLib.find_asset_data(asset) _assetName = _assetData.get_asset().get_name() _assetPathName = _assetData.get_asset().get_path_name() _assetClassName = _assetData.get_asset().get_class().get_name() # unreal.log(_assetClassName) if _assetClassName == "SoundCue": _SoundCueAsset = unreal.SoundCue.cast(_assetData.get_asset()) _SCConcurName = _SoundCueAsset.get_editor_property("concurrency_set") _SCConcurOverrideActive = _SoundCueAsset.get_editor_property("override_concurrency") # unreal.log(len(_SCConcurName)) if len(_SCConcurName) <= 0: # check if asset plugged in if not _SCConcurOverrideActive: # if not then check if override is set LogStringsArray.append(" %s ------------> At Path: %s \n" % (_assetName, _assetPathName)) # unreal.log("Asset Name: %s Path: %s \n" % (_assetName, _assetPathName)) numOfOptimisations += 1 if ST.should_cancel(): break ST.enter_progress_frame(1, asset) # Write results into a log file # /project/ TitleOfOptimisation = "Log Sound Cues With Missing Concurrency Settings" DescOfOptimisation = "Searches the entire project for Sound Cues that have no concurrency asset plugged in and also no concurrency override set to true" SummaryMessageIntro = "-- Sound Cues With No Concurrency Settings --" if unreal.Paths.file_exists(notepadFilePath): # Check if txt file already exists os.remove(notepadFilePath) # if does remove it # Create new txt file and run intro text file = open(notepadFilePath, "a+") # we should only do this if have a count? file.write("OPTIMISING SCRIPT by @CBgameDev \n") file.write("==================================================================================================== \n") file.write(" SCRIPT NAME: %s \n" % TitleOfOptimisation) file.write(" DESCRIPTION: %s \n" % DescOfOptimisation) file.write("==================================================================================================== \n \n") if numOfOptimisations <= 0: file.write(" -- NONE FOUND -- \n \n") else: for i in range(len(LogStringsArray)): file.write(LogStringsArray[i]) # Run summary text file.write("\n") file.write("======================================================================================================= \n") file.write(" SUMMARY: \n") file.write(" %s \n" % SummaryMessageIntro) file.write(" Found: %s \n \n" % numOfOptimisations) file.write("======================================================================================================= \n") file.write(" Logged to %s \n" % notepadFilePath) file.write("======================================================================================================= \n") file.close() os.startfile(notepadFilePath) # Trigger the notepad file to open
# coding: utf-8 import unreal # return: obj List unreal.Actor : The selected actors in the world def getSelectedActors(): return unreal.EditorLevelLibrary.get_selected_level_actors() # Note: Will always clear the selection before selecting. # actors_to_select: obj List unreal.Actor : The actors to select. def selectActors(actors_to_select=[]): unreal.EditorLevelLibrary.set_selected_level_actors(actors_to_select) def selectActors_EXAMPLE(): import WorldFunctions_2 all_actors = WorldFunctions_2.sortActors() actors_to_select = [] for x in range(len(all_actors)): if x % 2: actors_to_select.append(all_actors[x]) selectActors(actors_to_select) def clearActorSelection_EXAMPLE(): selectActors() # import WorldFunctions_3 as wf # reload(wf) # wf.selectActors_EXAMPLE() # print wf.getSelectedActors()
import unreal import glob import os import time class CommandLineReader(): def __init__(self) -> None: self.command_file = unreal.Paths.project_plugins_dir() + "CommandLineExternal/command.txt" tickhandle = unreal.register_slate_pre_tick_callback(self.tick) print("External Command Line object is initialized.") print("command_file: ", self.command_file) def tick(self, delta_time): self.read_file_commands() def read_file_commands(self): if os.path.exists(self.command_file): with open(self.command_file, "r") as f: command = f.read() #check if the string is empty if not command: return #execute the command unreal.SystemLibrary.execute_console_command(None, command) #empty the file with open(self.command_file, "w") as f: f.write("") CommandLineReader()
# coding: utf-8 import unreal def tryCast(): # ! this run crash use python # if unreal.Actor.cast(unreal.load_asset('/project/')): if unreal.Texture2D.cast(unreal.load_asset('/project/')): print 'Cast Succeeded' else: print 'Cast Failed' def castObject(): # ! this will not crash user C++ if cast(unreal.load_asset('/project/'), unreal.Actor): print 'Cast Succeeded' else: print 'Cast Failed' def cast(object_to_cast, object_class): try: return object_class.cast(object_to_cast) except: return None # import PythonHelpers_2 as ph # reload(ph) # ph.castObject()
# AdvancedSkeleton To ControlRig # Copyright (C) Animation Studios # email: [email protected] # exported using AdvancedSkeleton version:x.xx import unreal import re engineVersion = unreal.SystemLibrary.get_engine_version() asExportVersion = x.xx asExportTemplate = '4x' print ('AdvancedSkeleton To ControlRig (Unreal:'+engineVersion+') (AsExport:'+str(asExportVersion)+') (Template:'+asExportTemplate+')') utilityBase = unreal.GlobalEditorUtilityBase.get_default_object() selectedAssets = utilityBase.get_selected_assets() if len(selectedAssets)<1: raise Exception('Nothing selected, you must select a ControlRig') selectedAsset = selectedAssets[0] if selectedAsset.get_class().get_name() != 'ControlRigBlueprint': raise Exception('Selected object is not a ControlRigBlueprint, you must select a ControlRigBlueprint') blueprint = selectedAsset RigGraphDisplaySettings = blueprint.get_editor_property('rig_graph_display_settings') RigGraphDisplaySettings.set_editor_property('node_run_limit',256) library = blueprint.get_local_function_library() library_controller = blueprint.get_controller(library) hierarchy = blueprint.hierarchy hierarchy_controller = hierarchy.get_controller() RigVMController = blueprint.get_controller() #UE5 PreviousArrayInfo = dict() global ASCtrlNr global PreviousEndPlug global PreviousEndPlugInv global PreviousYInv global sp global nonTransformFaceCtrlNr PreviousYInv = 0 ASCtrlNr = 0 nonTransformFaceCtrlNr = -1 sp = '/project/.RigUnit_' PreviousEndPlug = 'RigUnit_BeginExecution.ExecuteContext' PreviousEndPlugInv = 'RigUnit_InverseExecution.ExecuteContext' def asAddCtrl (name, parent, joint, type, arrayInfo, gizmoName, ws, size, offT, color): global PreviousEndPlug global PreviousEndPlugInv global PreviousYInv global PreviousArrayInfo global ctrlBoxSize global ASCtrlNr global nonTransformFaceCtrlNr endPlug = PreviousEndPlug RigVMGraph = blueprint.get_model() numNodes = len(RigVMGraph.get_nodes()) y = ASCtrlNr*400 ASCtrlNr=ASCtrlNr+1 ASDrivenNr = int() RootScale = unreal.Vector(x=1.0, y=1.0, z=1.0) ParentRigBone = unreal.RigBone() ParentRigBoneName = parent.replace("FK", "") hasCon = True x = joint.split("_") if len(x)>1: baseName = x[0] side = '_'+x[1] x = ParentRigBoneName.split("_") if len(x)>1: ParentRigBoneBaseName = x[0] RigElementKeys = asGetRigElementKeys () for key in RigElementKeys: if (key.name == 'Root_M'): hierarchy.get_global_transform(key, initial = True) if (key.name == ParentRigBoneName): if (key.type == 1):#Bone ParentRigBone = hierarchy.find_bone (key) asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color) if name=='Main': return if name=='RootX_M': #Item Item = asAddNode (sp+'Item','Execute',node_name=name+'_Item') RigVMController.set_node_position (Item, [-500, y]) RigVMController.set_pin_default_value(name+'_Item.Item.Type','Control') RigVMController.set_pin_default_value(name+'_Item.Item.Name',name) #CON CON = asAddNode (sp+'ParentConstraint','Execute',node_name=name+'_CON') RigVMController.set_node_position (CON, [100, y-90]) RigVMController.set_pin_default_value(name+'_CON.Child.Type','Bone') RigVMController.set_pin_default_value(name+'_CON.Child.Name',joint) RigVMController.add_link(name+'_Item.Item', name+'_CON.Parents.0.Item') RigVMController.add_link(endPlug , name+'_CON.ExecuteContext') endPlug = name+'_CON.ExecuteContext' elif (not "inbetweenJoints" in arrayInfo) and (not "inbetweenJoints" in PreviousArrayInfo): #GT GT = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT') RigVMController.set_node_position (GT, [-500, y]) RigVMController.set_pin_default_value(name+'_GT.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GT.Item.Name',name) #ST ST = asAddNode (sp+'SetTransform','Execute',node_name=name+'_ST') RigVMController.set_node_position (ST, [100, y]) RigVMController.set_pin_default_value(name+'_ST.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_ST.Item.Name',joint) RigVMController.add_link(name+'_GT.Transform' , name+'_ST.Transform') RigVMController.set_pin_default_value(name+'_ST.bPropagateToChildren','True') RigVMController.add_link(endPlug , name+'_ST.ExecuteContext') endPlug = name+'_ST.ExecuteContext' #twistJoints if ("twistJoints" in arrayInfo) and (not "twistJoints" in PreviousArrayInfo): GT2 = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT2') RigVMController.set_node_position (GT2, [500, y+50]) RigVMController.set_pin_default_value(name+'_GT2.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GT2.Item.Name',name) RigVMController.set_pin_default_value(name+'_GT2.Space','LocalSpace') TWSW = asAddNode (sp+'MathQuaternionSwingTwist','Execute',node_name=name+'_TWSW') RigVMController.set_node_position (TWSW, [850, y+90]) RigVMController.add_link(name+'_GT2.Transform.Rotation' , name+'_TWSW.Input') INV = asAddNode (sp+'MathQuaternionInverse','Execute',node_name=name+'_INV') RigVMController.set_node_position (INV, [850, y+220]) RigVMController.add_link(name+'_TWSW.Twist' , name+'_INV.Value') OFF= asAddNode (sp+'OffsetTransformForItem','Execute',node_name=name+'_OFF') RigVMController.set_node_position (OFF, [1050, y]) RigVMController.set_pin_default_value(name+'_OFF.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_OFF.Item.Name',joint) RigVMController.add_link(name+'_INV.Result' , name+'_OFF.OffsetTransform.Rotation') RigVMController.add_link(endPlug , name+'_OFF.ExecuteContext') endPlug = name+'_OFF.ExecuteContext' GT3 = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT3') RigVMController.set_node_position (GT3, [1400, y+50]) RigVMController.set_pin_default_value(name+'_GT3.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GT3.Item.Name',name) ST2 = asAddNode (sp+'SetTranslation','Execute',node_name=name+'_ST2') RigVMController.set_node_position (ST2, [1700, y]) RigVMController.set_pin_default_value(name+'_ST2.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_ST2.Item.Name',joint) RigVMController.add_link(name+'_GT3.Transform.Translation' , name+'_ST2.Translation') RigVMController.add_link(endPlug , name+'_ST2.ExecuteContext') endPlug = name+'_ST2.ExecuteContext' if "twistJoints" in PreviousArrayInfo: twistJoints = int (PreviousArrayInfo["twistJoints"]) TwistArray = asAddNode (sp+'CollectionChainArray','Execute',node_name=name+'_TwistArray') RigVMController.set_node_position (TwistArray , [500, y+50]) RigVMController.set_pin_default_value(name+'_TwistArray.FirstItem', '(Type=Bone,Name='+ParentRigBoneBaseName+'Part1'+side+')') RigVMController.set_pin_default_value(name+'_TwistArray.LastItem', '(Type=Bone,Name='+ParentRigBoneBaseName+'Part'+str(twistJoints)+side+')') TwistArrayIterator = RigVMController.add_array_node_from_object_path(unreal.RigVMOpCode.ARRAY_ITERATOR, 'FRigElementKey', '/project/.RigElementKey', unreal.Vector2D(0, 0), name+'_TwistArrayIterator') RigVMController.set_node_position (TwistArrayIterator , [850, y]) RigVMController.add_link(name+'_TwistArray.Items' , name+'_TwistArrayIterator.Array') RigVMController.add_link(endPlug , name+'_TwistArrayIterator.ExecuteContext') endPlug = name+'_TwistArrayIterator.Completed' GTRE = asAddNode (sp+'GetRelativeTransformForItem','Execute',node_name=name+'_GTRE') RigVMController.set_node_position (GTRE , [1050, y+50]) RigVMController.set_pin_default_value(name+'_GTRE.Child', '(Type=Bone,Name='+joint+')') RigVMController.set_pin_default_value(name+'_GTRE.Parent', '(Type=Bone,Name='+ParentRigBoneName+')') TWSW = asAddNode (sp+'MathQuaternionSwingTwist','Execute',node_name=name+'_TWSW') RigVMController.set_node_position (TWSW, [1350, y+50]) RigVMController.add_link(name+'_GTRE.RelativeTransform.Rotation' , name+'_TWSW.Input') TOEU = asAddNode (sp+'MathQuaternionToEuler','Execute',node_name=name+'_TOEU') RigVMController.set_node_position (TOEU, [1350, y+170]) RigVMController.add_link(name+'_TWSW.Twist' , name+'_TOEU.Value') FREU = asAddNode (sp+'MathQuaternionFromEuler','Execute',node_name=name+'_FREU') RigVMController.set_node_position (FREU, [1350, y+270]) RigVMController.add_link(name+'_TOEU.Result' , name+'_FREU.Euler') QS = asAddNode (sp+'MathQuaternionScale','Execute',node_name=name+'_QS') RigVMController.set_node_position (QS, [1550, y+50]) RigVMController.set_pin_default_value(name+'_QS.Scale', str(1.0/int (PreviousArrayInfo["twistJoints"]))) RigVMController.add_link(name+'_FREU.Result' , name+'_QS.Value') SR = asAddNode (sp+'SetRotation','Execute',node_name=name+'_SR') RigVMController.set_node_position (SR, [1700, y]) RigVMController.add_link(name+'_QS.Value' , name+'_SR.Rotation') RigVMController.add_link(name+'_TwistArrayIterator.Element', name+'_SR.Item') RigVMController.set_pin_default_value(name+'_SR.Space','LocalSpace') RigVMController.set_pin_default_value(name+'_SR.bPropagateToChildren','False') RigVMController.add_link(name+'_TwistArrayIterator.ExecuteContext' , name+'_SR.ExecuteContext') #inbetweenJoints if "inbetweenJoints" in arrayInfo: inbetweenJoints = int (arrayInfo["inbetweenJoints"]) Chain = asAddNode (sp+'CollectionChainArray','Execute',node_name=name+'_Chain') RigVMController.set_node_position (Chain, [500, y]) RigVMController.set_pin_default_value(name+'_Chain.FirstItem.Name',joint) RigVMController.set_pin_default_value(name+'_Chain.LastItem.Name',baseName+'Part'+str(inbetweenJoints)+side) #GTDistr GTDistr = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTDistr') RigVMController.set_node_position (GTDistr, [850, y]) RigVMController.set_pin_default_value(name+'_GTDistr.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GTDistr.Item.Name',name) RigVMController.set_pin_default_value(name+'_GTDistr.Space','LocalSpace') #Distr Distr = asAddNode (sp+'DistributeRotationForItemArray','Execute',node_name=name+'_Distr') RigVMController.set_node_position (Distr, [1200, y]) weight = (1.0 / inbetweenJoints) RigVMController.set_pin_default_value(name+'_Distr.Weight',str(weight)) RigVMController.add_link(name+'_Chain.Items' , name+'_Distr.Items') RigVMController.add_array_pin(name+'_Distr.Rotations') RigVMController.add_link(name+'_GTDistr.Transform.Rotation' , name+'_Distr.Rotations.0.Rotation') RigVMController.add_link(endPlug , name+'_Distr.ExecuteContext') endPlug = name+'_Distr.ExecuteContext' if "inbetweenJoints" in PreviousArrayInfo: jointKey = asGetKeyFromName (joint) jointTransform = hierarchy.get_global_transform(jointKey, initial = True) NullKey = hierarchy_controller.add_null ('Null'+joint,asGetKeyFromName(parent),jointTransform) #GTNull GTNull = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTNull') RigVMController.set_node_position (GTNull, [1600, y+50]) RigVMController.set_pin_default_value(name+'_GTNull.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTNull.Item.Name',joint) #STNull STNull = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STNull') RigVMController.set_node_position (STNull, [2000, y]) RigVMController.set_pin_default_value(name+'_STNull.Item.Type','Null') RigVMController.set_pin_default_value(name+'_STNull.Item.Name','Null'+joint) RigVMController.add_link(name+'_GTNull.Transform' , name+'_STNull.Transform') RigVMController.set_pin_default_value(name+'_STNull.bPropagateToChildren','True') RigVMController.add_link(endPlug , name+'_STNull.ExecuteContext') endPlug = name+'_STNull.ExecuteContext' hierarchy_controller.set_parent(asGetKeyFromName(name),asGetKeyFromName('Null'+joint)) hierarchy.set_control_offset_transform(asGetKeyFromName(name), unreal.Transform(),initial=True) hierarchy.set_local_transform(asGetKeyFromName(name), unreal.Transform(),initial=True) hierarchy.set_local_transform(asGetKeyFromName(name), unreal.Transform(),initial=False) #GT2 GT2 = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT2') RigVMController.set_node_position (GT2, [2400, y]) RigVMController.set_pin_default_value(name+'_GT2.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GT2.Item.Name',name) #ST2 ST2 = asAddNode (sp+'SetTransform','Execute',node_name=name+'_ST2') RigVMController.set_node_position (ST2, [2700, y]) RigVMController.set_pin_default_value(name+'_ST2.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_ST2.Item.Name',joint) RigVMController.add_link(name+'_GT2.Transform' , name+'_ST2.Transform') RigVMController.set_pin_default_value(name+'_ST2.bPropagateToChildren','True') RigVMController.add_link(endPlug , name+'_ST2.ExecuteContext') endPlug = name+'_ST2.ExecuteContext' if "global" in arrayInfo and float(arrayInfo["global"])==10: Transform = hierarchy.get_global_transform(asGetKeyFromName(name), initial = True) NullKey = hierarchy_controller.add_null ('Global'+name,asGetKeyFromName(parent),Transform) hierarchy_controller.set_parent(asGetKeyFromName(name),asGetKeyFromName('Global'+name),maintain_global_transform=True) hierarchy.set_control_offset_transform(asGetKeyFromName(name), unreal.Transform(), True, True) hierarchy.set_local_transform(asGetKeyFromName(name), unreal.Transform(),initial=True) hierarchy.set_local_transform(asGetKeyFromName(name), unreal.Transform(),initial=False) #resolve where `PreviousEndPlug` is connected to, as that is the start for this Row, which is not always the _ST node Pin = RigVMGraph.find_pin(PreviousEndPlug) LinkePins = Pin.get_linked_target_pins() PreviousEndPlugConnectedToPin = LinkePins[0].get_pin_path() PNPGlobal = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name=name+'_PNPGlobal') RigVMController.set_node_position (PNPGlobal, [-1200, y]) RigVMController.set_pin_default_value(name+'_PNPGlobal.Child.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.Child.Name',name) RigVMController.set_pin_default_value(name+'_PNPGlobal.OldParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.OldParent.Name','Main') RigVMController.set_pin_default_value(name+'_PNPGlobal.NewParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.NewParent.Name','Main') #SRGlobal SRGlobal = asAddNode (sp+'SetRotation','Execute',node_name=name+'_SRGlobal') RigVMController.set_node_position (SRGlobal, [-850, y]) RigVMController.set_pin_default_value(name+'_SRGlobal.Item.Type','Null') RigVMController.set_pin_default_value(name+'_SRGlobal.Item.Name','Global'+name) RigVMController.set_pin_default_value(name+'_SRGlobal.bPropagateToChildren','True') RigVMController.add_link(name+'_PNPGlobal.Transform.Rotation' , name+'_SRGlobal.Rotation') RigVMController.add_link(PreviousEndPlug , name+'_SRGlobal.ExecuteContext') endPlug = name+'_SRGlobal.ExecuteContext' #STGlobal STGlobal = asAddNode (sp+'SetTranslation','Execute',node_name=name+'_STGlobal') RigVMController.set_node_position (STGlobal, [-850, y+250]) RigVMController.set_pin_default_value(name+'_STGlobal.Item.Type','Null') RigVMController.set_pin_default_value(name+'_STGlobal.Item.Name','Global'+name) RigVMController.set_pin_default_value(name+'_STGlobal.Space','LocalSpace') RigVMController.set_pin_default_value(name+'_STGlobal.bPropagateToChildren','True') Transform = hierarchy.get_local_transform(NullKey) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.X',str(Transform.translation.x)) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.Y',str(Transform.translation.y)) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.Z',str(Transform.translation.z)) RigVMController.add_link(name+'_SRGlobal.ExecuteContext' , name+'_STGlobal.ExecuteContext') endPlug = name+'_STGlobal.ExecuteContext' RigVMController.add_link(endPlug , PreviousEndPlugConnectedToPin) endPlug = PreviousEndPlugConnectedToPin if type=='IK': asAddController ('Pole'+name, parent, joint, type, 'Sphere_Solid', ws, size/5.0, offT, color) hierarchy.set_control_offset_transform(asGetKeyFromName('Pole'+name), unreal.Transform(location=[float(arrayInfo["ppX"])*RootScale.x,float(arrayInfo["ppZ"])*RootScale.y,float(arrayInfo["ppY"])*RootScale.z],scale=RootScale), True, True) #IK(Basic IK) IK = asAddNode (sp+'TwoBoneIKSimplePerItem','Execute',node_name=name+'_IK') RigVMController.set_node_position (IK, [600, y-130]) RigVMController.set_pin_default_value(name+'_IK.ItemA.Name',arrayInfo["startJoint"]) RigVMController.set_pin_default_value(name+'_IK.ItemB.Name',arrayInfo["middleJoint"]) RigVMController.set_pin_default_value(name+'_IK.EffectorItem.Name',arrayInfo["endJoint"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.X',arrayInfo["paX"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.Y',arrayInfo["paY"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.Z',arrayInfo["paZ"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.X',arrayInfo["saX"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.Y',arrayInfo["paY"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.Z',arrayInfo["paZ"]) RigVMController.set_pin_default_value(name+'_IK.PoleVectorKind','Location') RigVMController.set_pin_default_value(name+'_IK.PoleVectorSpace.Type','Control') RigVMController.set_pin_default_value(name+'_IK.PoleVectorSpace.Name','Pole'+name) RigVMController.set_pin_default_value(name+'_IK.bPropagateToChildren','True') RigVMController.add_link(name+'_GT.Transform' , name+'_IK.Effector') RigVMController.add_link(endPlug , name+'_IK.ExecuteContext') endPlug = name+'_IK.ExecuteContext' #GTPole GTPole = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTPole') RigVMController.set_node_position (GTPole, [1000, y]) RigVMController.set_pin_default_value(name+'_GTPole.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GTPole.Item.Name','Pole'+name) #GTMidJoint GTMidJoint = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTMidJoint') RigVMController.set_node_position (GTMidJoint, [1000, y+200]) RigVMController.set_pin_default_value(name+'_GTMidJoint.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTMidJoint.Item.Name',arrayInfo["middleJoint"]) PoleLine = asAddNode (sp+'DebugLineItemSpace','Execute',node_name=name+'_PoleLine') RigVMController.set_node_position (PoleLine, [1350, y]) RigVMController.add_link(name+'_GTPole.Transform.Translation' , name+'_PoleLine.A') RigVMController.add_link(name+'_GTMidJoint.Transform.Translation' , name+'_PoleLine.B') RigVMController.add_link(endPlug , name+'_PoleLine.ExecuteContext') endPlug = name+'_PoleLine.ExecuteContext' control_value = hierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(scale=[1, 1, 1])) control_settings = unreal.RigControlSettings() control_settings.shape_visible = False hierarchy_controller.add_control (name+'LS','', control_settings,control_value) hierarchy_controller.set_parent(asGetKeyFromName(name+'LS'),asGetKeyFromName(name),maintain_global_transform=False) RigVMController.set_pin_default_value(name+'_GT.Item.Name',name+'LS') for key in RigElementKeys: if (key.name == arrayInfo["endJoint"]): endJointKey = key EndJointTransform = hierarchy.get_global_transform(endJointKey, initial = False) Rotation = EndJointTransform.rotation.rotator() Transform = unreal.Transform(location=[0,0,0],rotation=Rotation,scale=[1,1,1]) hierarchy.set_control_offset_transform(asGetKeyFromName(name+'LS'), Transform, True, True) #Backwards solve nodes (IK) PNPinvIK = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name=name+'_PNPinvIK') RigVMController.set_node_position (PNPinvIK, [-2900, y]) RigVMController.set_pin_default_value(name+'_PNPinvIK.Child.Type','Control') RigVMController.set_pin_default_value(name+'_PNPinvIK.Child.Name',name) RigVMController.set_pin_default_value(name+'_PNPinvIK.OldParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPinvIK.OldParent.Name',name+'LS') RigVMController.set_pin_default_value(name+'_PNPinvIK.NewParent.Type','Bone') RigVMController.set_pin_default_value(name+'_PNPinvIK.NewParent.Name',joint) #STinvIK STinvIK = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STinvIK') RigVMController.set_node_position (STinvIK, [-2500, y]) RigVMController.set_pin_default_value(name+'_STinvIK.Item.Type','Control') RigVMController.set_pin_default_value(name+'_STinvIK.Item.Name',name) RigVMController.set_pin_default_value(name+'_STinvIK.bPropagateToChildren','True') RigVMController.add_link(name+'_PNPinvIK.Transform' , name+'_STinvIK.Transform') RigVMController.add_link(PreviousEndPlugInv , name+'_STinvIK.ExecuteContext') #GTinvPole GTinvPole = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTinvPole') RigVMController.set_node_position (GTinvPole, [-1700, y]) RigVMController.set_pin_default_value(name+'_GTinvPole.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTinvPole.Item.Name',arrayInfo["middleJoint"]) #STinvPole STinvPole = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STinvPole') RigVMController.set_node_position (STinvPole, [-1300, y]) RigVMController.set_pin_default_value(name+'_STinvPole.Item.Type','Control') RigVMController.set_pin_default_value(name+'_STinvPole.Item.Name','Pole'+name) RigVMController.set_pin_default_value(name+'_STinvPole.bPropagateToChildren','True') RigVMController.add_link(name+'_GTinvPole.Transform' , name+'_STinvPole.Transform') RigVMController.add_link(name+'_STinvIK.ExecuteContext' , name+'_STinvPole.ExecuteContext') endPlugInv = name+'_STinvPole.ExecuteContext' PreviousEndPlugInv = endPlugInv PreviousYInv = y if "twistJoints" in arrayInfo or "inbetweenJoints" in arrayInfo: PreviousArrayInfo = arrayInfo else: PreviousArrayInfo.clear() #DrivingSystem if type=='DrivingSystem' or type=='ctrlBox': if type=='DrivingSystem': RigVMController.set_pin_default_value(name+'_GT.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GT.Item.Name',joint) RigVMController.set_pin_default_value(name+'_ST.Item.Type','Control') RigVMController.set_pin_default_value(name+'_ST.Item.Name',name) if type=='ctrlBox' and name!='ctrlBox': parentTransform = hierarchy.get_global_control_offset_transform(asGetKeyFromName(parent)) Transform = unreal.Transform(location=[offT[0]/ctrlBoxSize,offT[2]/ctrlBoxSize,offT[1]/ctrlBoxSize]) Transform.rotation = [0,0,0] hierarchy.set_control_offset_transform(asGetKeyFromName(name), Transform, True, True) if name=='ctrlBox': #add a ws oriented ctrlBoxOffset NullKey = hierarchy_controller.add_null ('ctrlBoxOffset',asGetKeyFromName(parent),unreal.Transform(),transform_in_global=True) Transform = hierarchy.get_local_transform(NullKey) Transform.translation = [0,0,0] hierarchy.set_local_transform(NullKey, Transform,initial=True) hierarchy.set_local_transform(NullKey, Transform,initial=False) hierarchy_controller.set_parent(asGetKeyFromName(name),NullKey,maintain_global_transform=False) ctrlBoxSize = float (arrayInfo["ctrlBoxSize"]) Scale = [0.6,1.5,1.0] ctrlBoxScale = [ctrlBoxSize,ctrlBoxSize,ctrlBoxSize] parentTransform = hierarchy.get_global_control_offset_transform(asGetKeyFromName(parent)) Transform2 = hierarchy.get_global_control_offset_transform(asGetKeyFromName(name)).make_relative(parentTransform) Transform2.translation = [offT[0],offT[2],offT[1]] Transform2.scale3d = [ctrlBoxSize,ctrlBoxSize,ctrlBoxSize] hierarchy.set_control_offset_transform(asGetKeyFromName(name), Transform2, True, True) Transform = unreal.Transform(location=[0,0,-1],rotation=[0,0,90],scale=Scale) hierarchy.set_control_shape_transform(asGetKeyFromName(name), Transform, True, True) return nonTransformFaceCtrl = False if type=='ctrlBox': RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_GT')) RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_ST')) Transform = unreal.Transform(scale=[0.05,0.05,0.05]) hierarchy.set_control_shape_transform(asGetKeyFromName(name), Transform, True, True) maxXform = unreal.Vector2D(1,1) minXform = unreal.Vector2D(-1,-1) if name=='ctrlMouth_M': maxXform = [1,0] if re.search("^ctrlCheek_", name) or re.search("^ctrlNose_", name): minXform = [-1,0] RigElementKeys = asGetRigElementKeys () for key in RigElementKeys: if (key.name == name): RigControlKey = key hierarchy.set_control_value(asGetKeyFromName(name),unreal.RigHierarchy.make_control_value_from_vector2d(maxXform), unreal.RigControlValueType.MAXIMUM) hierarchy.set_control_value(asGetKeyFromName(name),unreal.RigHierarchy.make_control_value_from_vector2d(minXform), unreal.RigControlValueType.MINIMUM) endPlug = PreviousEndPlug control_settings = unreal.RigControlSettings() control_value = hierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(scale=[1, 1, 1])) AttrGrpkey = hierarchy_controller.add_control (name+"_Attributes",'',control_settings,control_value) if type=='ctrlBox': hierarchy_controller.set_parent(asGetKeyFromName(name+"_Attributes"),asGetKeyFromName(parent),maintain_global_transform=False) else: hierarchy_controller.set_parent(asGetKeyFromName(name+"_Attributes"),asGetKeyFromName(name),maintain_global_transform=False) hierarchy.set_control_shape_transform(asGetKeyFromName(name+"_Attributes"), unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0,0,0]), True) Transform = hierarchy.get_global_control_offset_transform(asGetKeyFromName(name), initial = True).copy() parentTransform = hierarchy.get_global_transform(asGetKeyFromName(parent), initial = True) Transform = Transform.make_relative(parentTransform) if type=='ctrlBox': Transform.translation.x = -5.0 Transform.translation.z += 0.8 if re.search("_L", name) or re.search("_M", name): Transform.translation.x = 4.0 if nonTransformFaceCtrl: Transform.translation.z = -5.5-(nonTransformFaceCtrlNr*2) # stack rows of sliders downwards else: numAttrs = 0 for Attr in arrayInfo.keys(): if not re.search("-set", Attr): numAttrs=numAttrs+1 Transform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1]) Transform.translation.x = offT[0] Transform.translation.y = numAttrs*0.5*(size/4.0)*-0.5 Transform.translation.z = size/8.0 if re.search("_L", name): Transform.translation.z *= -1 Transform.scale3d=[size/4.0,size/4.0,size/4.0] hierarchy.set_control_offset_transform(asGetKeyFromName(name+"_Attributes"), Transform, True, True) Attrs = arrayInfo.keys() attrNr = 0 for Attr in Attrs: if re.search("-set", Attr): if re.search("-setLimits", Attr): DictDrivens = arrayInfo.get(Attr) min = float(list(DictDrivens.keys())[0]) max = float(list(DictDrivens.values())[0]) RigElementKeys = asGetRigElementKeys () for key in RigElementKeys: if key.name == name+"_"+Attr.replace("-setLimits", ""): hierarchy.set_control_value(key, unreal.RigHierarchy.make_control_value_from_float(min), unreal.RigControlValueType.MINIMUM) hierarchy.set_control_value(key, unreal.RigHierarchy.make_control_value_from_float(max), unreal.RigControlValueType.MAXIMUM) continue transformAttrDriver = True if not re.search("translate", Attr) or re.search("rotate", Attr) or re.search("scale", Attr): control_settings = unreal.RigControlSettings() control_settings.control_type = unreal.RigControlType.FLOAT control_settings.shape_color = unreal.LinearColor(r=1.0, g=0.0, b=0.0, a=1.0) control_settings.limit_enabled = [unreal.RigControlLimitEnabled(True, True)] if nonTransformFaceCtrl or re.search("_M", name): control_settings.primary_axis = unreal.RigControlAxis.Z else: control_settings.primary_axis = unreal.RigControlAxis.X key = hierarchy_controller.add_control (name+"_"+Attr,asGetKeyFromName(name+"_Attributes"),control_settings,control_value) hierarchy.set_control_value(key,unreal.RigHierarchy.make_control_value_from_float(1), unreal.RigControlValueType.MAXIMUM) hierarchy.set_control_shape_transform(asGetKeyFromName(name+"_"+Attr), unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0.035,0.035,0.035]), True, True) Transform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1]) Transform.translation = [0,attrNr*0.5,0] if type=='ctrlBox': Transform.translation = [0,0,attrNr*-0.5] if nonTransformFaceCtrl or re.search("_M", name): Transform.translation = [attrNr,0,0] attrNr = attrNr+1 hierarchy.set_control_offset_transform(asGetKeyFromName(name+"_"+Attr), Transform, True, True) transformAttrDriver = False DictDrivens = arrayInfo.get(Attr) KeysDrivens = DictDrivens.keys() for Driven in KeysDrivens: Value = float(DictDrivens.get(Driven)) x2 = ASDrivenNr*1200 dNr = str(ASDrivenNr) ASDrivenNr = ASDrivenNr+1 x = Driven.split(".") obj = x[0] attr = '_'+x[1] axis = attr[-1] valueMult = 1 if re.search("rotate", attr): if axis == 'X' or axis=='Z': valueMult = -1 if re.search("translate", attr): if axis=='Y': valueMult = -1 multiplier = Value*valueMult asFaceBSDriven = False if re.search("asFaceBS[.]", Driven):#asFaceBS asFaceBSDriven = True if not (asFaceBSDriven): RigElementKeys = asGetRigElementKeys () for key in RigElementKeys: if key.name == obj: objKey = key if not asObjExists ('Offset'+obj): objParentKey = hierarchy.get_parents(objKey)[0] OffsetKey = hierarchy_controller.add_null ('Offset'+obj,objKey,unreal.Transform(),transform_in_global=False) hierarchy_controller.set_parent(OffsetKey,objParentKey) hierarchy_controller.set_parent(objKey,OffsetKey) parentTo = 'Offset'+obj for x in range(1,9): sdk = 'SDK'+obj+"_"+str(x) if not asObjExists (sdk): break if x>1: parentTo = 'SDK'+obj+"_"+str(x-1) SDKKey = hierarchy_controller.add_null (sdk,asGetKeyFromName(parentTo),unreal.Transform(),transform_in_global=False) hierarchy_controller.set_parent(objKey,SDKKey) #GTDriver if transformAttrDriver: GTDriver = asAddNode (sp+'GetControlVector2D','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_GTDriver') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_GTDriver.Control',name) gtPlug = name+"_"+obj+"_"+attr+dNr+'_GTDriver.Vector.'+Attr[-1]#Attr[-1] is DriverAxis else: GTDriver = asAddNode (sp+'GetControlFloat','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_GTDriver') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_GTDriver.Control',name+"_"+Attr) gtPlug = name+"_"+obj+"_"+attr+dNr+'_GTDriver.FloatValue' RigVMController.set_node_position (GTDriver, [500+x2, y]) #MFM MFM = asAddNode (sp+'MathFloatMul','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_MFM') RigVMController.set_node_position (MFM, [900+x2, y]) RigVMController.add_link(gtPlug , name+"_"+obj+"_"+attr+dNr+'_MFM.A') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_MFM.B',str(multiplier)) if asFaceBSDriven: #Clamp Clamp = asAddNode (sp+'MathFloatClamp','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_Clamp') RigVMController.set_node_position (Clamp, [900+x2, y+100]) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_Clamp.Maximum','5.0') RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_Clamp.Value') #STDriven STDriven = asAddNode (sp+'SetCurveValue','Execute',node_name=name+"_"+Attr+"_"+attr+'_STDriven') RigVMController.set_node_position (STDriven, [1100+x2, y]) RigVMController.set_pin_default_value(name+"_"+Attr+"_"+attr+'_STDriven.Curve',Driven.split(".")[1]) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_Clamp.Result' , name+"_"+Attr+"_"+attr+'_STDriven.Value') RigVMController.add_link(endPlug , name+"_"+Attr+"_"+attr+'_STDriven.ExecuteContext') endPlug =name+"_"+Attr+"_"+attr+'_STDriven.ExecuteContext' else: #STDriven STDriven = asAddNode (sp+'SetTransform','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_STDriven') RigVMController.set_node_position (STDriven, [1300+x2, y]) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Item.Type','Null') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Item.Name',sdk) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Space','LocalSpace') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.bPropagateToChildren','True') RigVMController.add_link(endPlug , name+"_"+obj+"_"+attr+dNr+'_STDriven.ExecuteContext') endPlug = name+"_"+obj+"_"+attr+dNr+'_STDriven.ExecuteContext' #TFSRT TFSRT = asAddNode (sp+'MathTransformFromSRT','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_TFSRT') RigVMController.set_node_position (TFSRT, [900+x2, y+150]) if re.search("translate", attr): RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Location.'+axis) if re.search("rotate", attr): RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Rotation.'+axis) if re.search("scale", attr): #scale just add 1, not accurate but simplified workaround MFA = asAddNode (sp+'MathFloatAdd','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_MFA') RigVMController.set_node_position (MFA, [1100+x2, y]) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_MFA.A') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_MFA.B','1') RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFA.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Scale.'+axis) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_TFSRT.Transform', name+"_"+obj+"_"+attr+dNr+'_STDriven.Transform') #face if re.search("Teeth_M", name): RigControl.set_editor_property('gizmo_enabled',False) hierarchy_controller.set_control (RigControl) if name=="Jaw_M": RigControl.set_editor_property('gizmo_name','HalfCircle_Thick') RigControl.set_editor_property('gizmo_name','HalfCircle_Thick') Transform = RigControl.get_editor_property('gizmo_transform') Transform.rotation=[0,0,180] RigControl.set_editor_property('gizmo_transform', Transform) hierarchy_controller.set_control (RigControl) PreviousEndPlug = endPlug def asObjExists (obj): RigElementKeys = asGetRigElementKeys () LocObject = None for key in RigElementKeys: if key.name == obj: return True return False def asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color): parentKey = asGetKeyFromName(parent) if gizmoName=='Gizmo': gizmoName='Default' control_settings = unreal.RigControlSettings() if type=='ctrlBox': control_settings.control_type = unreal.RigControlType.VECTOR2D control_settings.primary_axis = unreal.RigControlAxis.Y control_settings.limit_enabled = [unreal.RigControlLimitEnabled(True, True), unreal.RigControlLimitEnabled(True, True)] else: control_settings.control_type = unreal.RigControlType.EULER_TRANSFORM if name=='ctrlEmotions_M' or name=='ctrlPhonemes_M' or name=='ctrlARKit_M' or name=='ctrlBoxRobloxHead_M': control_settings.shape_visible = False control_settings.shape_name = gizmoName control_settings.shape_color = unreal.LinearColor(color[0], color[1], color[2], 1.0) control_value = hierarchy.make_control_value_from_euler_transform(unreal.EulerTransform(scale=[1, 1, 1])) key = hierarchy_controller.add_control (name,'', control_settings,control_value) jointKey = asGetKeyFromName (joint) jointTransform = hierarchy.get_global_transform(jointKey, initial = True) if ws == 1: jointTransform.rotation = [0,0,0] parentTransform = unreal.Transform() if parent!='': parentTransform = hierarchy.get_global_transform(asGetKeyFromName(parent), initial = True) OffsetTransform = jointTransform.make_relative(parentTransform) if parent!='': hierarchy_controller.set_parent(asGetKeyFromName(name),asGetKeyFromName(parent),maintain_global_transform=False) hierarchy.set_control_offset_transform(key, OffsetTransform, True, True) GizmoLocation = [offT[0],offT[2],offT[1]] GizmoRotation = [0,0,0] if ws == 0: GizmoRotation = [90,0,0] GizmoLocation = [offT[0],offT[1]*-1,offT[2]] if type=="DrivingSystem": GizmoRotation = [0,0,0] if type=="ctrlBox": GizmoRotation = [0,0,90] if re.search("^Eye_.*", name) or re.search("^Iris_.*", name) or re.search("^Pupil_.*", name): GizmoRotation = [0,90,0] hierarchy.set_control_visibility(key,False) x = re.search("^Pole.*", name) if x: GizmoLocation = [0,0,0] s = 0.1*size Scale = [s,s,s] if type=='FK' and ws == 0: Scale[2]*=2.5 hierarchy.set_control_shape_transform(key, unreal.Transform(location=GizmoLocation,rotation=GizmoRotation,scale=Scale), True) def asAddNode (script_struct_path, method_name, node_name): #RigVMController. #add_struct_node_from_struct_path UE4 #add_unit_node_from_struct_path UE5 try: node = RigVMController.add_struct_node_from_struct_path(script_struct_path,method_name,node_name=node_name) #UE4 except: node = RigVMController.add_unit_node_from_struct_path(script_struct_path,method_name,node_name=node_name) #UE5 return node def asGetRigElementKeys (): try: RigElementKeys = hierarchy_controller.get_elements() #UE4 except: RigElementKeys = hierarchy.get_all_keys() #UE5 return RigElementKeys def asGetKeyFromName (name): all_keys = hierarchy.get_all_keys(traverse = True) for key in all_keys: if key.name == name: return key return '' def asBackwardsSolveNodes (): global PreviousYInv global PreviousEndPlugInv PNP = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name='Root_M_PNP') RigVMController.set_node_position (PNP, [-1500, PreviousYInv+400-90]) RigVMController.set_pin_default_value('Root_M_PNP.Child.Type','Control') RigVMController.set_pin_default_value('Root_M_PNP.Child.Name','RootX_M') RigVMController.set_pin_default_value('Root_M_PNP.OldParent.Type','Bone') RigVMController.set_pin_default_value('Root_M_PNP.OldParent.Name','Root_M') RigVMController.set_pin_default_value('Root_M_PNP.NewParent.Type','Bone') RigVMController.set_pin_default_value('Root_M_PNP.NewParent.Name','Root_M') STInv = asAddNode (sp+'SetTransform','Execute',node_name='Root_M_STInv') RigVMController.set_node_position (STInv, [-1200, PreviousYInv+400-90]) RigVMController.set_pin_default_value('Root_M_STInv.Item.Type','Control') RigVMController.set_pin_default_value('Root_M_STInv.Item.Name','RootX_M') RigVMController.add_link('Root_M_PNP.Transform' , 'Root_M_STInv.Transform') RigVMController.add_link(PreviousEndPlugInv , 'Root_M_STInv.ExecuteContext') CCinv = asAddNode (sp+'CollectionChildren','Execute',node_name='CCinv') RigVMController.set_node_position (CCinv, [-2600, PreviousYInv+1000]) RigVMController.set_pin_default_value('CCinv.Parent.Type','Bone') RigVMController.set_pin_default_value('CCinv.Parent.Name','Root_M') RigVMController.set_pin_default_value('CCinv.bRecursive','True') RigVMController.set_pin_default_value('CCinv.TypeToSearch','Bone') CLinv = asAddNode (sp+'CollectionLoop','Execute',node_name='CLinv') RigVMController.set_node_position (CLinv, [-2150, PreviousYInv+1000]) RigVMController.add_link('Root_M_STInv.ExecuteContext' , 'CLinv.ExecuteContext') RigVMController.add_link('CCinv.Collection' , 'CLinv.Collection') PreviousEndPlugInv = 'CLinv.Completed' NCinv = asAddNode (sp+'NameConcat','Execute',node_name='NCinv') RigVMController.set_node_position (NCinv, [-1900, PreviousYInv+900]) RigVMController.set_pin_default_value('NCinv.A','FK') RigVMController.add_link('CLinv.Item.Name' , 'NCinv.B') GTinv = asAddNode (sp+'GetTransform','Execute',node_name='GTinv') RigVMController.set_node_position (GTinv, [-1900, PreviousYInv+1000]) RigVMController.add_link('CLinv.Item.Name' , 'GTinv.Item.Name') IEinv = asAddNode (sp+'ItemExists','Execute',node_name='IEinv') RigVMController.set_node_position (IEinv, [-1700, PreviousYInv+700]) RigVMController.set_pin_default_value('IEinv.Item.Type','Control') RigVMController.add_link('NCinv.Result' , 'IEinv.Item.Name') BRinv = RigVMController.add_branch_node(node_name='BRinv') RigVMController.set_node_position (BRinv, [-1650, PreviousYInv+850]) RigVMController.add_link('IEinv.Exists' , 'BRinv.Condition') RigVMController.add_link('CLinv.ExecuteContext' , 'BRinv.ExecuteContext') STinv = asAddNode (sp+'SetTransform','Execute',node_name='STinv') RigVMController.set_node_position (STinv, [-1500, PreviousYInv+1000]) RigVMController.set_pin_default_value('STinv.Item.Type','Control') RigVMController.add_link('NCinv.Result' , 'STinv.Item.Name') RigVMController.add_link('GTinv.Transform' , 'STinv.Transform') RigVMController.add_link('BRinv.True' , 'STinv.ExecuteContext') def main (): global PreviousEndPlugInv RigElementKeys = asGetRigElementKeys () RigVMGraph = blueprint.get_model() #Clear out existing rig-setup nodes = RigVMGraph.get_nodes() for node in nodes: RigVMController.remove_node(node) #Clear out existing controllers for key in RigElementKeys: if key.name == 'MotionSystem': hierarchy_controller.remove_element(key) elif not (key.type==1 or key.type==8): #BONE try: hierarchy_controller.remove_element(key) except: pass #UE5 does not include deleting children, so we will try to clean-up controls = hierarchy.get_controls() for key in controls: hierarchy_controller.remove_element(key) nulls = hierarchy.get_nulls() for key in nulls: hierarchy_controller.remove_element(key) bones = hierarchy.get_bones() for key in bones: x = re.search("UnTwist", str(key.name)) if x: hierarchy_controller.remove_element(key) BeginExecutionNode = asAddNode (sp+'BeginExecution','Execute',node_name='RigUnit_BeginExecution') RigVMController.set_node_position (BeginExecutionNode, [-300, -100]) InverseExecutionNode = asAddNode (sp+'InverseExecution','Execute',node_name='RigUnit_InverseExecution') RigVMController.set_node_position (InverseExecutionNode, [-1900, -100]) MotionSystemKey = hierarchy_controller.add_null ('MotionSystem','',unreal.Transform()) MainSystemKey = hierarchy_controller.add_null ('MainSystem',MotionSystemKey,unreal.Transform()) DrivingSystemKey = hierarchy_controller.add_null ('DrivingSystem',MotionSystemKey ,unreal.Transform()) #//-- ASControllers Starts Here --// #//-- ASControllers Ends Here --// asBackwardsSolveNodes() print ("ControlRig created") if __name__ == "__main__": main()
# /project/ # @CBgameDev Optimisation Script - Log Sound Cues Missing a Sound Class # /project/ import unreal import os EditAssetLib = unreal.EditorAssetLibrary() SystemsLib = unreal.SystemLibrary StringLib = unreal.StringLibrary() workingPath = "/Game/" # Using the root directory notepadFilePath = os.path.dirname(__file__) + "//PythonOptimiseLog.txt" allAssets = EditAssetLib.list_assets(workingPath, True, False) selectedAssetsPath = workingPath LogStringsArray = [] numOfOptimisations = 0 with unreal.ScopedSlowTask(len(allAssets), selectedAssetsPath) as ST: ST.make_dialog(True) for asset in allAssets: _assetData = EditAssetLib.find_asset_data(asset) _assetName = _assetData.get_asset().get_name() _assetPathName = _assetData.get_asset().get_path_name() _assetClassName = _assetData.get_asset().get_class().get_name() # unreal.log(_assetClassName) if _assetClassName == "SoundCue": _SCSoundClass = unreal.SoundCue.cast(_assetData.get_asset()).get_editor_property("sound_class_object") if not SystemsLib.is_valid(_SCSoundClass): # no Sound class asset plugged in LogStringsArray.append(" [No Asset Plugged in] %s ------------> At Path: %s \n" % (_assetName, _assetPathName)) # unreal.log("Asset Name: %s [No Asset Plugged In] Path: %s \n" % (_assetName, _assetPathName)) numOfOptimisations += 1 elif StringLib.contains(_SCSoundClass.get_path_name(), "Engine"): # Sound Class Asset Plugged in but its Engine Default LogStringsArray.append(" [Engine Default Used] %s ------------> At Path: %s \n" % (_assetName, _assetPathName)) # unreal.log("Asset Name: %s [Engine Default Being Used] Path: %s \n" % (_assetName, _assetPathName)) numOfOptimisations += 1 if ST.should_cancel(): break ST.enter_progress_frame(1, asset) # Write results into a log file # /project/ TitleOfOptimisation = "Log Sound Cues With Missing Sound Class" DescOfOptimisation = "Searches the entire project for Sound Cues that are missing Sound Class Asset or are using the Engines Default Sound class asset" SummaryMessageIntro = "-- Sound Cues With Missing Sound Class --" if unreal.Paths.file_exists(notepadFilePath): # Check if txt file already exists os.remove(notepadFilePath) # if does remove it # Create new txt file and run intro text file = open(notepadFilePath, "a+") # we should only do this if have a count? file.write("OPTIMISING SCRIPT by @CBgameDev \n") file.write("==================================================================================================== \n") file.write(" SCRIPT NAME: %s \n" % TitleOfOptimisation) file.write(" DESCRIPTION: %s \n" % DescOfOptimisation) file.write("==================================================================================================== \n \n") if numOfOptimisations <= 0: file.write(" -- NONE FOUND -- \n \n") else: for i in range(len(LogStringsArray)): file.write(LogStringsArray[i]) # Run summary text file.write("\n") file.write("======================================================================================================= \n") file.write(" SUMMARY: \n") file.write(" %s \n" % SummaryMessageIntro) file.write(" Found: %s \n \n" % numOfOptimisations) file.write("======================================================================================================= \n") file.write(" Logged to %s \n" % notepadFilePath) file.write("======================================================================================================= \n") file.close() os.startfile(notepadFilePath) # Trigger the notepad file to open
# -*- coding: utf-8 -*- """ """ from __future__ import division from __future__ import print_function from __future__ import absolute_import __author__ = "timmyliang" __email__ = "[email protected]" __date__ = "2020-12-28 16:07:39" import unreal import os import json from collections import defaultdict # NOTE Python 3 & 2 兼容 try: import tkinter as tk from tkinter import ttk from tkinter import filedialog, messagebox except: import ttk import Tkinter as tk import tkFileDialog as filedialog import tkMessageBox as messagebox root = tk.Tk() root.withdraw() nested_dict = lambda: defaultdict(nested_dict) level_lib = unreal.EditorLevelLibrary() asset_lib = unreal.EditorAssetLibrary() sys_lib = unreal.SystemLibrary() content_path = sys_lib.get_project_content_directory() asset_registry = unreal.AssetRegistryHelpers.get_asset_registry() asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # options = unreal.AssetRegistryDependencyOptions(True, True, True, True, True) # options.set_editor_property("include_hard_management_references",True) # options.set_editor_property("include_hard_package_references",True) # options.set_editor_property("include_searchable_names",True) # options.set_editor_property("include_soft_management_references",True) # options.set_editor_property("include_soft_package_references",True) def print_string(msg, color=None): color = color if color else [255, 255, 255, 255] sys_lib.print_string(None, msg, text_color=color) def ls_dependencies(path): data = asset_lib.find_asset_data(path) options = unreal.AssetRegistryDependencyOptions() dependencies = asset_registry.get_dependencies(data.package_name, options) return dependencies def export_asset(obj, filename, exporter, options=None, prompt=False): task = unreal.AssetExportTask() task.set_editor_property("object", obj) task.set_editor_property("filename", filename) task.set_editor_property("exporter", exporter) task.set_editor_property("automated", True) task.set_editor_property("prompt", prompt) task.set_editor_property("options", options) if options else None check = unreal.Exporter.run_asset_export_task(task) if not check: msg = "fail export %s" % filename print_string(msg) return def main(): selected_static_actors = [ a for a in level_lib.get_selected_level_actors() if isinstance(a, unreal.StaticMeshActor) ] if not selected_static_actors: unreal.EditorDialog( u"提示", u"请至少选择一个 StaticMeshActor 来导出", unreal.AppMsgType.OK ) return fbx_path = filedialog.asksaveasfilename( filetypes=[ ("FBX Files", "*.fbx") ], title=u"选择导出的路径", ) if not fbx_path: return elif not fbx_path.lower().endswith(".fbx"): fbx_path = "%s.fbx" % fbx_path directory,base = os.path.split(fbx_path) fbx_name = os.path.splitext(base)[0] # NOTE 将选中的 MeshActor 合并 options = unreal.EditorScriptingMergeStaticMeshActorsOptions() asset_path = "/Game/%s" % fbx_name options.set_editor_property("base_package_name", asset_path) options.set_editor_property("destroy_source_actors", False) options.set_editor_property("spawn_merged_actor", False) level_lib.merge_static_mesh_actors(selected_static_actors, options) # NOTE 导出模型 mesh = unreal.load_asset(asset_path) fbx_exporter = unreal.StaticMeshExporterFBX() fbx_option = unreal.FbxExportOption() fbx_option.export_morph_targets = False fbx_option.export_preview_mesh = False fbx_option.level_of_detail = False fbx_option.collision = False fbx_option.export_local_time = False fbx_option.ascii = False fbx_option.vertex_color = True export_asset(mesh, fbx_path, fbx_exporter, fbx_option) texture_folder = os.path.join(directory, "%s_texture" % fbx_name) if not os.path.exists(texture_folder): os.mkdir(texture_folder) # NOTE 导出贴图 tga_exporter = unreal.TextureExporterTGA() for material in mesh.static_materials: material = material.material_interface textures = ls_dependencies(material.get_path_name()) texture_paths = [] for texture_path in textures: if str(texture_path).startswith("/Engine/"): continue texture = unreal.load_asset(texture_path) if not isinstance(texture, unreal.Texture): continue texture_name = texture.get_name() tga_path = os.path.join(texture_folder, "%s.tga" % texture_name) export_asset(texture, tga_path, tga_exporter) # NOTE 删除模型 asset_lib.delete_asset(asset_path) if __name__ == "__main__": main()
import unreal import os import sys import shutil import json def validate_json_structure(scene_data): """ Validate the JSON structure has required fields Args: scene_data (dict): The loaded JSON data Returns: bool: True if valid, False otherwise """ if not isinstance(scene_data, dict): unreal.log_warning("ERROR: Scene data is not a dictionary") return False if "actors" not in scene_data: unreal.log_warning("WARNING: No 'actors' key found in scene data") return True # Still valid, just empty if not isinstance(scene_data["actors"], list): unreal.log_warning("ERROR: 'actors' should be a list") return False # Validate each actor has required fields for i, actor in enumerate(scene_data["actors"]): if not isinstance(actor, dict): unreal.log_warning(f"ERROR: Actor {i} is not a dictionary") return False if "id" not in actor: unreal.log_warning(f"ERROR: Actor {i} missing 'id' field") return False if "transform" not in actor: unreal.log_warning(f"WARNING: Actor {actor.get('id', i)} missing 'transform' field") return True def create_new_level(level_full_path): # get the editor level lib editor_level_lib = unreal.LevelEditorSubsystem() # spawn new level success = editor_level_lib.new_level( level_full_path ) def spawn_actor( name: str, mesh_type: str, location: unreal.Vector(), rotation: unreal.Rotator(), scale: unreal.Vector() ): """ Spawns a StaticMeshActor in the Unreal Editor with the specified transform and mesh type. Args: name (str): The label to assign to the actor in the editor. mesh_type (str): The type of mesh to assign to the actor. Supports "Cube" or "Plane". location (unreal.Vector): The world location where the actor should be spawned. rotation (unreal.Rotator): The rotation to apply to the actor. scale (unreal.Vector): The scale to apply to the actor. Behavior: - Spawns a StaticMeshActor at the given location and rotation. - Assigns the specified basic mesh (Cube or Plane). - Sets the actor’s transform including scale. - Marks the actor as modified, but note: changes like scale may not persist unless the level is saved. Note: - This function uses Unreal Editor scripting APIs and should be run in the Unreal Editor (not at runtime). - `modify()` is called to mark the actor dirty, but some property changes (like scale) might not persist unless the level is explicitly saved. """ # Get the system to control the actors editor_actor_subs = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) # We want to create a StaticMeshActor actor_class = unreal.StaticMeshActor # Place it in the level static_mesh_actor = editor_actor_subs.spawn_actor_from_class(actor_class, location, rotation) #static_mesh_actor = editor_actor_subs.spawn_actor_from_class(actor_class) # name the actor static_mesh_actor.set_actor_label(name, mark_dirty=True) # Use appropriate basic mesh_type if mesh_type == "Cube": # Load and add the cube to it static_mesh = unreal.EditorAssetLibrary.load_asset("/project/.Cube") static_mesh_actor.static_mesh_component.set_static_mesh(static_mesh) elif mesh_type == "Plane": # Load and add plane. static_mesh = unreal.EditorAssetLibrary.load_asset("/project/.Plane") static_mesh_actor.static_mesh_component.set_static_mesh(static_mesh) # set the transform to adjust scale transform = unreal.Transform(location, rotation, scale) editor_actor_subs.set_actor_transform(static_mesh_actor, transform) ## THIS IS SUPPOSED TO TELL UE5 TO SAVE SCALE CHANGE (DIRTY)? NOT WORKING. static_mesh_actor.modify() def build_scene_from_scene_data(scene_data): """ Constructs a scene in the Unreal Editor from structured scene data by spawning StaticMeshActors. Args: scene_data (dict): A dictionary containing scene information. Expected format: { "actors": [ { "id": "ActorName", "mesh_type": "Cube" or "Plane", "transform": { "location": {"x": float, "y": float, "z": float}, "rotation": {"pitch": float, "yaw": float, "roll": float}, "scale": {"x": float, "y": float, "z": float} }, "children": [ ... ] # Optional list of child actors with the same structure }, ... ] } Behavior: - Iterates through all top-level actors in the scene data and spawns them in the level using `spawn_actor()`. - For each actor, it also spawns all listed child actors. - Applies the specified mesh type, location, rotation, and scale to each actor. Notes: - This function assumes `spawn_actor()` is defined elsewhere and accessible. - Only supports basic mesh types recognized by `spawn_actor()` ("Cube", "Plane"). - Designed for use in the Unreal Editor (not at runtime). Example: build_scene_from_scene_data({ "actors": [ { "id": "Floor", "mesh_type": "Plane", "transform": { "location": {"x": 0, "y": 0, "z": 0}, "rotation": {"pitch": 0, "yaw": 0, "roll": 0}, "scale": {"x": 5, "y": 5, "z": 1} }, "children": [] } ] }) """ actors_data = scene_data.get('actors', []) for actor in actors_data: unreal.log(actor) actor_id = actor["id"] actor_mesh_type = actor["mesh_type"] actor_transform = actor["transform"] # extract transform loc = actor_transform['location'] rot = actor_transform['rotation'] scale = actor_transform['scale'] spawn_actor( name = actor_id, mesh_type = actor_mesh_type, location = unreal.Vector(loc["x"], loc["y"], loc["z"]), rotation = unreal.Rotator(rot["pitch"], rot["yaw"], rot["roll"]), scale = unreal.Vector(scale["x"], scale["y"], scale["z"]) ) # get children actor_children = actor["children"] for actor in actor_children: actor_id = actor["id"] actor_transform = actor["transform"] actor_mesh_type = actor["mesh_type"] # extract transform loc = actor_transform['location'] rot = actor_transform['rotation'] scale = actor_transform['scale'] spawn_actor( name = actor_id, mesh_type = actor_mesh_type, location = unreal.Vector(loc["x"], loc["y"], loc["z"]), rotation = unreal.Rotator(rot["pitch"], rot["yaw"], rot["roll"]), scale = unreal.Vector(scale["x"], scale["y"], scale["z"]) ) def save(): """ Not working properly - doesn't save transforms on actors. """ # tell unreal to save all the changes unreal.EditorLoadingAndSavingUtils.save_current_level() def clean_up_scene(): # Get the system to control the actors editor_actor_subs = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) # select all the actors all_actors = editor_actor_subs.get_all_level_actors() # delete success = editor_actor_subs.destroy_actors(all_actors) # report unreal.log(f"Deleted actors {success}") if __name__ == "__main__": # 1. Extract local directory path # When run headless - is passed via arg. if len(sys.argv) >= 2: LocalDirPath = sys.argv[1] else: # In case is run in UE5 GUI - dynamically get local dir path syslib = unreal.SystemLibrary() user_path = syslib.get_platform_user_dir() LocalDirPath = user_path[:-10] + "Documents/project/" # 2. Set json scene path json_scene_full_path = LocalDirPath + "scene_graph.json" # 3. Load scene graph JSON unreal.log_warning(f"Loading scene data from: {json_scene_full_path}") with open(json_scene_full_path, 'r') as f: scene_data = json.load(f) # 4. Validate JSON structure if not validate_json_structure(scene_data): unreal.log_warning("JSON validation Failed.") # 5. Create new level create_new_level("/project/") # 6. Enforce deletion of any existing actors. clean_up_scene() # 7. Build Scene build_scene_from_scene_data(scene_data) # 8. Save save() ## 9. Copy umap from default save location to widget folder # ## copy move - quick and dirty fix as changing project root directory is a rabbit hole. # get users dir syslib = unreal.SystemLibrary() user_path = syslib.get_platform_user_dir() level_path = user_path[:-10] + "AppData\\Local\\UnrealEngine\\5.6\\Content\\Maps\\BlockOut.umap" # copy if not os.path.exists(level_path): unreal.log_warning(f"Source .umap file not found at: {level_path}") elif not os.access(level_path, os.R_OK): unreal.log_error(f"Cannot read source .umap file: Permission denied at {level_path}") else: shutil.copy( level_path, os.path.join(LocalDirPath, "BlockOut.umap"))
import unreal from Lib import __lib_topaz__ as topaz import importlib importlib.reload(topaz) selectedAssets = unreal.EditorUtilityLibrary.get_selected_assets() for asset in selectedAssets: hasIK = False objectsInBP = topaz.get_component_objects(asset.get_path_name()) for objectInBP in objectsInBP: hasInteractionPoint = objectInBP.get_name().find('InteractionPoint') if hasInteractionPoint != -1: hasIK = True break if hasIK: directoryPath = asset.get_path_name() part = directoryPath.split('/') staticMeshesDirectory = '/'.join(part[:6]) + '/IK/' bpFileName = asset.get_name() sourcePath = directoryPath targetPath = staticMeshesDirectory + '/' + bpFileName result = unreal.EditorAssetLibrary.rename_asset(sourcePath, targetPath) print(result) else: print ('This asset does not have IK')
from array import array import unreal _seek_comp_name : str = 'CapsuleComponent' _seek_property_name : str = '' selected : array = unreal.EditorUtilityLibrary.get_selected_assets() def swap_bp_obj_to_bp_c ( __bp_list:list) -> list : bp_c_list : list = [] for each in __bp_list : name_selected : str = unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(each) name_selected = name_selected + '_C' loaded_bp = unreal.EditorAssetLibrary.load_blueprint_class(name_selected) bp_c_obj = unreal.get_default_object(loaded_bp) bp_c_list.append(bp_c_obj) return bp_c_list def get_bp_comp_by_name (__bp_c, __seek: str) : #loaded_bp_c = unreal.EditorAssetLibrary.load_blueprint_class(__bp_c) loaded_comp = __bp_c.get_editor_property(__seek) return loaded_comp def change_comp_property (__comp, __seek : str , __val : any) : __comp.set_editor_property(__seek, __val) def get_comp_property (__comp, __seek : str ) : __comp.get_editor_property(__seek) ## exectue from here converted = swap_bp_obj_to_bp_c(selected) for each in converted : seeked_comp = get_bp_comp_by_name(each, _seek_comp_name) debugprint = seeked_comp.get_editor_property(_seek_property_name) print(debugprint)
import unreal from unreal import Vector from os.path import realpath from pathlib import Path from typing import List, Tuple """ Drag texture pngs to content browser Right-click texture png and create material Double-click material, add TextureCoordinate and adjust (20 for floor) Drag cube to content browser Double-click cube, add created material (This script does the rest) """ # ../project/.txt maze_filepath = Path(realpath(__file__)).parents[1] / "Mazes/maze01.txt" def read_maze_file( filepath: str, ) -> Tuple[List[List[int]], int, int, List[Tuple[int, int, str]], List[str]]: """Read a maze file and return values Args: filepath (str): path to a maze file Returns: Tuple[List[List[int]]: a maze int: maze width int: maze height List[Tuple[int, int, str]]: turn by turn directions List[str]]: texture names """ with open(filepath, "r") as maze_file: num_textures = int(maze_file.readline()) texture_names = [maze_file.readline() for _ in range(num_textures)] maze_x_dim, maze_y_dim = [int(dim) for dim in maze_file.readline().split()] maze = [ [int(cell) for cell in maze_file.readline().split()] for _ in range(maze_y_dim) ] maze_directions = [ (int(line.split()[0]), int(line.split()[1]), line.split()[2]) for line in maze_file.readlines() ] return list(reversed(maze)), maze_x_dim, maze_y_dim, maze_directions, texture_names def spawn_actor(location, meshpath): new_actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, location=location ) mesh = unreal.load_object(None, meshpath) mesh_component = new_actor.get_editor_property("static_mesh_component") # type: ignore mesh_component.set_static_mesh(mesh) return new_actor maze, maze_x_dim, maze_y_dim, _, _ = read_maze_file(maze_filepath) CUBE_SCALE = 100 WALL_Z_OFFSET = CUBE_SCALE MAZE_X_OFFSET = -(CUBE_SCALE * maze_x_dim) / 2 + CUBE_SCALE / 2 MAZE_Y_OFFSET = -(CUBE_SCALE * maze_y_dim) / 2 + CUBE_SCALE / 2 OPEN_SPACE = 0 WALL_NORM = 2 WALL_RIGHT = 3 WALL_LEFT = 4 WALL_GOAL = 5 floor = spawn_actor(Vector(8, 8, 0), "/project/.Floor") floor.set_actor_scale3d(Vector(maze_x_dim, maze_y_dim, 1)) # type: ignore walls = [] for yi, row in enumerate(maze): y = yi * CUBE_SCALE + MAZE_X_OFFSET # Unreal Engine uses left-handed coordinate system for xi, col in enumerate(reversed(row)): x = xi * CUBE_SCALE + MAZE_Y_OFFSET if col == WALL_NORM: walls.append(spawn_actor(Vector(x, y, WALL_Z_OFFSET), "/project/.Wall")) elif col == WALL_RIGHT: walls.append( spawn_actor(Vector(x, y, WALL_Z_OFFSET), "/project/.WallRight") ) elif col == WALL_LEFT: walls.append( spawn_actor(Vector(x, y, WALL_Z_OFFSET), "/project/.WallLeft") ) elif col == WALL_GOAL: walls.append( spawn_actor(Vector(x, y, WALL_Z_OFFSET), "/project/.WallGoal") ) # Start at (maze_x_dim/2, -maze_y_dim/2) # Goal at (-maze_x_dim/2, maze_y_dim/2)
# 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 spawns some actors and then uses the API to instantiate an HDA and set the actors as world inputs. The inputs are set during post instantiation (before the first cook). After the first cook and output creation (post processing) the input structure is fetched and logged. """ import unreal _g_wrapper = None def get_test_hda_path(): return '/project/.subnet_test_2_0' def get_test_hda(): return unreal.load_object(None, get_test_hda_path()) def get_geo_asset_path(): return '/project/.Cube' def get_geo_asset(): return unreal.load_object(None, get_geo_asset_path()) def get_cylinder_asset_path(): return '/project/.Cylinder' def get_cylinder_asset(): return unreal.load_object(None, get_cylinder_asset_path()) def configure_inputs(in_wrapper): print('configure_inputs') # Unbind from the delegate in_wrapper.on_post_instantiation_delegate.remove_callable(configure_inputs) # Spawn some actors actors = spawn_actors() # Create a world input world_input = in_wrapper.create_empty_input(unreal.HoudiniPublicAPIWorldInput) # Set the input objects/assets for this input world_input.set_input_objects(actors) # copy the input data to the HDA as node input 0 in_wrapper.set_input_at_index(0, world_input) # We can now discard the API input object world_input = None # Set the subnet_test HDA to output its first input in_wrapper.set_int_parameter_value('enable_geo', 1) def print_api_input(in_input): print('\t\tInput type: {0}'.format(in_input.__class__)) print('\t\tbKeepWorldTransform: {0}'.format(in_input.keep_world_transform)) print('\t\tbImportAsReference: {0}'.format(in_input.import_as_reference)) if isinstance(in_input, unreal.HoudiniPublicAPIWorldInput): print('\t\tbPackBeforeMerge: {0}'.format(in_input.pack_before_merge)) print('\t\tbExportLODs: {0}'.format(in_input.export_lo_ds)) print('\t\tbExportSockets: {0}'.format(in_input.export_sockets)) print('\t\tbExportColliders: {0}'.format(in_input.export_colliders)) print('\t\tbIsWorldInputBoundSelector: {0}'.format(in_input.is_world_input_bound_selector)) print('\t\tbWorldInputBoundSelectorAutoUpdate: {0}'.format(in_input.world_input_bound_selector_auto_update)) 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 spawn_actors(): actors = [] # Spawn a static mesh actor and assign a cylinder to its static mesh # component actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, location=(0, 0, 0)) actor.static_mesh_component.set_static_mesh(get_cylinder_asset()) actor.set_actor_label('Cylinder') actor.set_actor_transform( unreal.Transform( (-200, 0, 0), (0, 0, 0), (2, 2, 2), ), sweep=False, teleport=True ) actors.append(actor) # Spawn a static mesh actor and assign a cube to its static mesh # component actor = unreal.EditorLevelLibrary.spawn_actor_from_class( unreal.StaticMeshActor, location=(0, 0, 0)) actor.static_mesh_component.set_static_mesh(get_geo_asset()) actor.set_actor_label('Cube') actor.set_actor_transform( unreal.Transform( (200, 0, 100), (45, 0, 45), (2, 2, 2), ), sweep=False, teleport=True ) actors.append(actor) return actors def run(): # get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() global _g_wrapper # instantiate an asset with auto-cook enabled _g_wrapper = api.instantiate_asset(get_test_hda(), unreal.Transform()) # Configure inputs on_post_instantiation, after instantiation, but before first cook _g_wrapper.on_post_instantiation_delegate.add_callable(configure_inputs) # Bind on_post_processing, after cook + output creation _g_wrapper.on_post_processing_delegate.add_callable(print_inputs) if __name__ == '__main__': run()
import unreal from . import helpers, assets def get_all_actors_in_current_level(): """ Returns all current actors in the current opened level. :return: list of actors within level. :rtype: list(unreal.Actor) """ return unreal.EditorActorSubsystem().get_all_level_actors() def get_selected_actors_in_current_level(): """ Returns all current selected actors in the current opened level. :return: list of selected actors within level. :rtype: list(unreal.Actor) """ return unreal.EditorActorSubsystem().get_selected_level_actors() def get_all_actors_and_labels_in_current_level(): """ Returns a tuple with all current actors and their labels in the current opened level. :return: tuple with a list of actors and their labels within level. :rtype: tuple(list(unreal.Actor), list(str)) """ actors = get_all_actors_in_current_level() actor_names = [actor.get_actor_label() for actor in actors] return actors, actor_names def get_selected_actors_and_labels_in_current_level(): """ Returns a tuple with all current selected actors and their labels in the current opened level. :return: tuple with a list of selected actors and their labels within level. :rtype: tuple(list(unreal.Actor), list(str)) """ actors = get_selected_actors_in_current_level() actor_names = [actor.get_actor_label() for actor in actors] return actors, actor_names def get_all_actors_and_names_in_current_level(): """ Returns a tuple with all current actors and their names in the current opened level. :return: tuple with a list of actors and their names within level. :rtype: tuple(list(unreal.Actor), list(str)) """ actors = get_all_actors_in_current_level() actor_names = [actor.get_name() for actor in actors] return actors, actor_names def get_selected_actors_and_names_in_current_level(): """ Returns a tuple with all current selected actors and their names in the current opened level. :return: tuple with a list of selected actors and their names within level. :rtype: tuple(list(unreal.Actor), list(str)) """ actors = get_selected_actors_in_current_level() actor_names = [actor.get_name() for actor in actors] return actors, actor_names def get_actor_by_label_in_current_level(actor_label): """ Return actor within current level with the given actor label. :param str actor_label: actor label. :return: found actor with given label in current level. :rtype: unreal.Actor or None ..warning:: Actor labels within a level are not unique, so if multiple actors have the same label we may return the undesired one. """ found_actor = None all_actors = get_all_actors_in_current_level() for actor in all_actors: if actor.get_actor_label() == actor_label: found_actor = actor break return found_actor def get_actor_by_guid_in_current_level(actor_guid): """ Return actor within current level with the given actor guid. :param str actor_guid: actor guid. :return: found actor with given guid in current level. :rtype: unreal.Actor or None """ found_actor = None all_actors = get_all_actors_in_current_level() for actor in all_actors: if actor.actor_guid.to_string() == actor_guid: found_actor = actor break return found_actor def get_all_actors_with_component_of_type(component_class): found_actors = list() actors = unreal.EditorActorSubsystem().get_all_level_actors() for actor in actors: components = actor.get_components_by_class(component_class) if not components: continue found_actors.append(actor) return found_actors def select_actors_in_current_level(actors): """ Set the given actors as selected ones within current level. :param unreal.Actor or list(unreal.Actor) actors: list of actors to select. """ unreal.EditorLevelLibrary().set_selected_level_actors( helpers.force_list(actors) ) def delete_actor(actor): """ Deletes given actor from current scene. :param unreal.Actor actor: actor instance to delete. """ unreal.EditorLevelLibrary.destroy_actor(actor) def get_actor_asset(actor): """ Returns the asset associated to given actor based on actor components. :param unreal.Actor actor: actor to get linked asset of. :return: found asset. :rtype: unreal.Object ..warning:: For now, only Static Mesh, Skeletal Meshes are supported. """ is_static_mesh = False is_skeletal_mesh = False is_camera = False actor_asset = None static_mesh_components = list() skeletal_mesh_components = list() camera_components = list() static_mesh_components = actor.get_components_by_class( unreal.StaticMeshComponent ) if static_mesh_components: is_static_mesh = True if not is_static_mesh: skeletal_mesh_components = actor.get_components_by_class( unreal.SkeletalMeshComponent ) if skeletal_mesh_components: is_skeletal_mesh = True if is_static_mesh: static_mesh_component = helpers.get_first_in_list( static_mesh_components ) static_mesh = static_mesh_component.get_editor_property("static_mesh") actor_asset = assets.get_asset(static_mesh.get_path_name()) elif is_skeletal_mesh: skeletal_mesh_component = helpers.get_first_in_list( skeletal_mesh_components ) skeletal_mesh = skeletal_mesh_component.get_editor_property( "skeletal_mesh" ) actor_asset = assets.get_asset(skeletal_mesh.get_path_name()) return actor_asset def export_fbx_actor(actor, directory, export_options=None): """ Exports a FBX of the given actor. :param unreal.Actor actor: actor to export as FBX. :param str directory: directory where FBX actor will be exported. :param dict export_options: dictionary containing all the FBX export settings to use. :return: exported FBX file path. :rtype: str """ actor_asset = get_actor_asset(actor) if not actor_asset: unreal.log_warning( "Was not possible to retrieve valid asset for actor: {}".format( actor ) ) return "" return assets.export_fbx_asset( actor_asset, directory=directory, fbx_filename=actor.get_actor_label(), export_options=export_options, ) def export_all_fbx_actors_in_current_scene(directory, export_options=None): """ Exports all actors in current scene. :param str directory: directory where FBX actor will be exported. :param dict export_options: dictionary containing all the FBX export settings to use. :return: exported FBX file paths. :rtype: list(str) """ exported_actors = list() all_actors = get_all_actors_in_current_level() for actor in all_actors: actor_export_path = export_fbx_actor( actor, directory=directory, export_options=export_options ) exported_actors.append(actor_export_path) return exported_actors
# _ # (_) # _ __ ___ __ _ _ __ ___ ___ _ __ _ ___ _ __ ___ # | '_ ` _ \ / _` | '_ ` _ \ / _ \| '_ \| |/ _ \ '_ ` _ \ # | | | | | | (_| | | | | | | (_) | | | | | __/ | | | | | # |_| |_| |_|\__,_|_| |_| |_|\___/|_| |_|_|\___|_| |_| |_| # www.mamoniem.com # www.ue4u.xyz #Copyright 2022 Muhammad A.Moniem (@_mamoniem). All Rights Reserved. # # This file was built while supporting user of the python course import unreal #your lines to spawn the actor, i did use them as is, nothing changed actor_class = unreal.CineCameraActor actor_location = unreal.Vector(3033.728192, -353.591784, 358.488934) actor_rotation = unreal.Rotator(125.7,144.3,162.8) _spawnedActor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, actor_location, actor_rotation) #make the focus settings class, and set some values that we need _focusSettings = unreal.CameraFocusSettings() _focusSettings.manual_focus_distance = 1320.0 _focusSettings.focus_method = unreal.CameraFocusMethod.MANUAL _focusSettings.focus_offset = 19.0 _focusSettings.smooth_focus_changes = False #Apply the focus settings to the camera we made _cineCameraComponent = _spawnedActor.get_cine_camera_component() _cineCameraComponent.set_editor_property("focus_settings",_focusSettings)
import unreal import pandas as pd def parse_term(term_string): if pd.notna(term_string): term_parts = term_string.split() term_name = term_parts[0] properties = [] for i in range(1, len(term_parts), 2): if i + 1 < len(term_parts): prop_name = term_parts[i] prop_value = term_parts[i + 1] properties.append({'name': prop_name, 'value': prop_value}) return {'name': term_name, 'properties': properties} return None def process_terms(file_path): if not file_path: unreal.log_error("Invalid file path.") return try: df = pd.read_csv(file_path) except Exception as e: unreal.log_error(f"Failed to read CSV file: {e}") return asset_tools = unreal.AssetToolsHelpers.get_asset_tools() for index, row in df.iterrows(): term_data = parse_term(row.get('Goal', '')) goal_dialogue = row.get('GoalDialogue', '') thanks_dialogue = row.get('ThanksDialogue', '') if not term_data: continue create_term_blueprint(term_data, goal_dialogue, thanks_dialogue) def create_term_blueprint(term, goal_dialogue, thanks_dialogue): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() property_str = "_".join([f"{prop['name']}_{prop['value']}" for prop in term['properties']]) full_term_name = f"Goal_{term['name']}_{property_str}_BP" if property_str else f"Goal_{term['name']}_BP" original_term_blueprint_path = "/project/" term_path = "/project/" new_term_blueprint_name = full_term_name original_term_blueprint = unreal.EditorAssetLibrary.load_asset(original_term_blueprint_path) duplicated_term_blueprint = asset_tools.duplicate_asset(new_term_blueprint_name, term_path, original_term_blueprint) duplicated_term_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_term_blueprint.get_path_name()) duplicated_term_blueprint_instance = unreal.get_default_object(duplicated_term_blueprint_generated_class) if not duplicated_term_blueprint_instance: unreal.log_error("Duplicated term instance is not valid") return None unreal.EditorAssetLibrary.set_editor_property(duplicated_term_blueprint_instance, "Name", term['name']) if goal_dialogue: unreal.EditorAssetLibrary.set_editor_property(duplicated_term_blueprint_instance, "GoalDialogue", goal_dialogue) if thanks_dialogue: unreal.EditorAssetLibrary.set_editor_property(duplicated_term_blueprint_instance, "ThanksDialogue", thanks_dialogue) properties_array = unreal.EditorAssetLibrary.get_editor_property(duplicated_term_blueprint_instance, "PropertiesBP") if properties_array is None: properties_array = [] for prop in term['properties']: prop_blueprint = create_property_blueprint(prop, term['name']) if prop_blueprint: properties_array.append(prop_blueprint) unreal.EditorAssetLibrary.set_editor_property(duplicated_term_blueprint_instance, "PropertiesBP", properties_array) unreal.EditorAssetLibrary.save_asset(duplicated_term_blueprint.get_path_name()) return duplicated_term_blueprint_generated_class def create_property_blueprint(prop, term_name): asset_tools = unreal.AssetToolsHelpers.get_asset_tools() original_property_blueprint_path = "/project/" property_path = "/project/" new_property_blueprint_name = f"{term_name}_{prop['name']}_{prop['value']}_BP" original_property_blueprint = unreal.EditorAssetLibrary.load_asset(original_property_blueprint_path) duplicated_property_blueprint = asset_tools.duplicate_asset(new_property_blueprint_name, property_path, original_property_blueprint) duplicated_property_blueprint_generated_class = unreal.EditorAssetLibrary.load_blueprint_class(duplicated_property_blueprint.get_path_name()) duplicated_property_blueprint_instance = unreal.get_default_object(duplicated_property_blueprint_generated_class) if not duplicated_property_blueprint_instance: unreal.log_error("Duplicated property instance is not valid") return None unreal.EditorAssetLibrary.set_editor_property(duplicated_property_blueprint_instance, "Name", prop['name']) unreal.EditorAssetLibrary.set_editor_property(duplicated_property_blueprint_instance, "Value", prop['value']) unreal.EditorAssetLibrary.save_asset(duplicated_property_blueprint.get_path_name()) return duplicated_property_blueprint_generated_class # Example usage: # file_path = open_file_dialog() # process_terms(file_path)
""" # Unreal API Shorthands * Description: The unreal module has very large names for functions. Some of which have been shorthanded, or aliased, here. """ import unreal # --------Functions------------------------------------------------------------ def set_skel_property(import_options: unreal.FbxImportUI, string_name: str, value=None) -> None: """Simple to type func to set skel mesh import option.""" import_options.skeletal_mesh_import_data.set_editor_property(string_name, value) def set_staticmesh_property(import_options: unreal.FbxImportUI, string_name: str, value=None) -> None: """Simple to type func to set static mesh import option.""" import_options.static_mesh_import_data.set_editor_property(string_name, value) def set_anim_property(import_options: unreal.FbxImportUI, string_name: str, value=None) -> None: """Simple to type func to set skel anim import options.""" import_options.anim_sequence_import_data.set_editor_property(string_name, value) # --------Variable Types------------------------------------------------------- fbx_normal_gen_method = unreal.FBXNormalGenerationMethod """unreal.FBXNormalGenerationMethod""" fbx_normal_mikk_t_space = fbx_normal_gen_method.MIKK_T_SPACE """unreal.FBXNormalGenerationMethod.MIKK_T_SPACE""" fbx_normal_imp_method = unreal.FBXNormalImportMethod """unreal.FBXNormalImportMethod""" fbx_import_normals_tangents = fbx_normal_imp_method.FBXNIM_IMPORT_NORMALS_AND_TANGENTS """unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS_AND_TANGENTS"""
import unreal import os # 合并actor为fbx # 一般思路为,先保存为asset,再导出asset # https://blog.l0v0.com/project/.html level_lib = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) asset_lib = unreal.get_editor_subsystem(unreal.EditorAssetSubsystem) selected_actors = level_lib.get_selected_level_actors() selected_static_actors = unreal.EditorFilterLibrary.by_class(selected_actors,unreal.StaticMeshActor) 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 ) save_path = r'/project/' fbx_exporter = unreal.StaticMeshExporterFBX() fbx_option = unreal.FbxExportOption() export_path = r"C:/project/" # 最后要加 / static_mesh_lib = unreal.get_editor_subsystem(unreal.StaticMeshEditorSubsystem) for actor in selected_static_actors: actor_name = actor.get_name() actor_path = os.path.join(save_path, actor_name) # TODO:这种path到底啥时候带具体文件名称啊? merge_options.base_package_name = actor_path # The package path you want to save to # 将选中的actor合并成 static mesh merge_actor = static_mesh_lib.merge_static_mesh_actors([actor],merge_options) # 单独导出 mesh = unreal.load_asset(actor_path) # load asset to memory,allowing to access and manipulate it programmatically. # 导出fbx task = unreal.AssetExportTask() task.object = mesh # Asset to export task.filename = export_path + actor_name + '.fbx' task.exporter = fbx_exporter # Optional exporter, otherwise it will be determined automatically task.automated = True # Unattended export:按我的理解,就是不会弹出fbx导出窗口供用户选择 task.prompt = False # Allow dialog prompts task.options = fbx_option # Exporter specific options unreal.Exporter.run_asset_export_task(task) # 删除临时列表 asset_lib.delete_directory("save_path") print("执行完毕!")
# This scripts describes the process of capturing an managing properties with a little more # detail than test_variant_manager.py import unreal # Create all assets and objects we'll use lvs = unreal.VariantManagerLibrary.create_level_variant_sets_asset("LVS", "/Game/") lvs_actor = unreal.VariantManagerLibrary.create_level_variant_sets_actor(lvs) if lvs is None or lvs_actor is None: print "Failed to spawn either the LevelVariantSets asset or the LevelVariantSetsActor!" quit() var_set1 = unreal.VariantSet() var_set1.set_display_text("My VariantSet") var1 = unreal.Variant() var1.set_display_text("Variant 1") # Adds the objects to the correct parents lvs.add_variant_set(var_set1) var_set1.add_variant(var1) # Spawn a simple cube static mesh actor cube = unreal.EditorAssetLibrary.load_asset("StaticMesh'/project/.Cube'") spawned_actor = None if cube: location = unreal.Vector() rotation = unreal.Rotator() spawned_actor = unreal.EditorLevelLibrary.spawn_actor_from_object(cube, location, rotation) spawned_actor.set_actor_label("Cube Actor") else: print "Failed to find Cube asset!" if spawned_actor is None: print "Failed to spawn an actor for the Cube asset!" quit() # Bind spawned_actor to all our variants var1.add_actor_binding(spawned_actor) # See which properties can be captured from any StaticMeshActor capturable_by_class = unreal.VariantManagerLibrary.get_capturable_properties(unreal.StaticMeshActor.static_class()) # See which properties can be captured from our specific spawned_actor # This will also return the properties for any custom component structure we might have setup on the actor capturable_props = unreal.VariantManagerLibrary.get_capturable_properties(spawned_actor) print "Capturable properties for actor '" + spawned_actor.get_actor_label() + "':" for prop in capturable_props: print "\t" + prop print "Capturable properties for its class:" for prop in capturable_by_class: print "\t" + prop # Returns nullptr for invalid paths. This will also show an error in the Output Log prop1 = var1.capture_property(spawned_actor, "False property path") assert prop1 is None # Comparison is case insensitive: The property is named "Can be Damaged", but this still works prop2 = var1.capture_property(spawned_actor, "cAn Be DAMAged") assert prop2 is not None and prop2.get_full_display_string() == "Can be Damaged" # Attempts to capture the same property more than once are ignored, and None is returned prop2attempt2 = var1.capture_property(spawned_actor, "Can Be Damaged") assert prop2attempt2 is None # Check which properties have been captured for some actor in a variant print "Captured properties for '" + spawned_actor.get_actor_label() + "' so far:" captured_props = var1.get_captured_properties(spawned_actor) for captured_prop in captured_props: print "\t" + captured_prop.get_full_display_string() # Capture property in a component prop3 = var1.capture_property(spawned_actor, "Static Mesh Component / Relative Location") assert prop3 is not None and prop3.get_full_display_string() == "Static Mesh Component / Relative Location" # Can't capture the component itself. This will also show an error in the Output Log prop4 = var1.capture_property(spawned_actor, "Static Mesh Component") assert prop4 is None # Capture material property prop5 = var1.capture_property(spawned_actor, "Static Mesh Component / Material[0]") assert prop5 is not None # Removing property captures var1.remove_captured_property(spawned_actor, prop2) var1.remove_captured_property_by_name(spawned_actor, "Static Mesh Component / Relative Location") print "Captured properties for '" + spawned_actor.get_actor_label() + "' at the end:" captured_props = var1.get_captured_properties(spawned_actor) for captured_prop in captured_props: print "\t" + captured_prop.get_full_display_string() # Should only have the material property left assert len(captured_props) == 1 and captured_props[0].get_full_display_string() == "Static Mesh Component / Material[0]"
# -*- 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())
""" This script describes how to open and import USD Stages in ways that automatically configure the generated StaticMeshes for Nanite. In summary, there are two different settings you can use: The NaniteTriangleThreshold property (any static mesh generated with this many triangles or more will be enabled for Nanite), and the 'unrealNanite' property (force Nanite enabled or disabled on a per-prim basis). Note that there are two cases in which Nanite will not be enabled for generated StaticMeshes, even when using the above settings: - When the Mesh prim is configured for multiple LODs (by using Variants and Variant Sets); - When the generated StaticMesh would have led to more than 64 material slots. Additionally, when exporting existing UStaticMeshes to USD Mesh prims we will automatically emit the `uniform token unrealNanite = "enable"` attribute whenever the source UStaticMesh has "Enable Nanite Support" checked. The text below describes a "sample_scene.usda" file (some attributes omitted for brevity): # Assuming a triangle threshold of 2000, this prim will generate a StaticMesh with Nanite disabled: def Mesh "small_mesh" { # Mesh data with 1000 triangles } # Assuming a triangle threshold of 2000, this prim will generate a StaticMesh with Nanite enabled: def Mesh "large_mesh" { # Mesh data with 5000 triangles } # Assuming a triangle threshold of 2000, this prim will generate a StaticMesh with Nanite enabled: def Mesh "small_but_enabled" { # Mesh data with 1000 triangles uniform token unrealNanite = "enable" } # Assuming a triangle threshold of 2000, this prim will generate a StaticMesh with Nanite disabled: def Mesh "large_but_disabled" { # Mesh data with 5000 triangles uniform token unrealNanite = "disable" } # Assuming a triangle threshold of 2000 and that we're collapsing prims with "component" kind, # this prim hierarchy will lead to a StaticMesh with Nanite enabled, as the final StaticMesh will end up with 2000 # total triangles. def Xform "nanite_collapsed" ( kind = "component" ) { def Mesh "small_mesh_1" { # Mesh data with 1000 triangles } def Mesh "small_mesh_2" { # Mesh data with 1000 triangles } } # Assuming a triangle threshold of 2000 and that we're collapsing prims with "component" kind, # this prim hierarchy will lead to a StaticMesh with Nanite enabled. The combined triangle count is below the # threshold, however we have an 'unrealNanite' opinion on the root of the collapsed hierarchy that overrides it. # Note that in case of collapsing, we will only consider the 'unrealNanite' attribute on the root, and will # disregard opinions for it specified on each individual Mesh prim. def Xform "nanite_collapsed" ( kind = "component" ) { uniform token unrealNanite = "enable" def Mesh "small_mesh_1" { # Mesh data with 500 triangles } def Mesh "small_mesh_2" { # Mesh data with 500 triangles } } """ import unreal ROOT_LAYER_FILENAME = r"/project/.usda" DESTINATION_CONTENT_PATH = r"/project/" def specify_nanite_when_importing(): """ Describes how to specify the Nanite triangle threshold when importing a stage """ options = unreal.UsdStageImportOptions() options.import_actors = True options.import_geometry = True options.import_skeletal_animations = True options.nanite_triangle_threshold = 2000 # Use your threshold here task = unreal.AssetImportTask() task.set_editor_property('filename', ROOT_LAYER_FILENAME) task.set_editor_property('destination_path', DESTINATION_CONTENT_PATH) task.set_editor_property('automated', True) task.set_editor_property('options', options) task.set_editor_property('replace_existing', True) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() asset_tools.import_asset_tasks([task]) asset_paths = task.get_editor_property("imported_object_paths") success = asset_paths and len(asset_paths) > 0 def specify_nanite_when_opening(): """ Describes how to specify the Nanite triangle threshold when opening a stage """ editor_actor_subsystem = unreal.get_editor_subsystem(unreal.EditorActorSubsystem) stage_actor = editor_actor_subsystem.spawn_actor_from_class(unreal.UsdStageActor, unreal.Vector()) # Either one of the two lines below should work, without any difference stage_actor.set_editor_property('nanite_triangle_threshold', 2000) stage_actor.set_nanite_triangle_threshold(2000) stage_actor.set_editor_property('root_layer', unreal.FilePath(ROOT_LAYER_FILENAME))
# 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 for getting the API instance and starting/creating the Houdini Engine Session. """ def run(): # Get the API singleton api = unreal.HoudiniPublicAPIBlueprintLib.get_api() # Check if there is an existing valid session if not api.is_session_valid(): # Create a new session api.create_session() if __name__ == '__main__': run()
import json import os import re import time from collections.abc import Iterable from pathlib import Path from subprocess import run import unreal SELECTIVE_OBJECTS = [] projectpath = unreal.Paths.project_plugins_dir() newpath = projectpath + 'Uiana/project/.json' f = open(newpath) JsonMapTypeData = json.load(f) FILEBROWSER_PATH = os.path.join(os.getenv('WINDIR'), 'explorer.exe') # -------------------------- # def clear_level(): AllActors = unreal.EditorLevelLibrary.get_all_level_actors() for j in AllActors: unreal.EditorLevelLibrary.destroy_actor(j) def ReturnBPLoop(data, name): for lop in data: if lop["Name"] == name: return lop def return_parent(parent_name): actual_shader_name = parent_name[parent_name.rfind(' ')+1:len(parent_name)] DefEnv = import_shader(actual_shader_name) if not DefEnv: ParentName = "BaseEnv_MAT_V4" else: ParentName = actual_shader_name return ParentName def reduce_bp_json(BigData): FullJson = {} newjson = [] sceneroot = [] ChildNodes = [] GameObjects = [] for fnc in BigData: fName = fnc["Name"] fType = fnc["Type"] if "Properties" not in fnc: continue FProps = fnc["Properties"] if fType == "SimpleConstructionScript": SceneRoot = FProps["DefaultSceneRootNode"]["ObjectName"] sceneroot.append(SceneRoot[SceneRoot.rfind(':') + 1:len(SceneRoot)]) if "Node" in fName: Name = FProps["ComponentTemplate"]["ObjectName"] ActualName = Name[Name.rfind(':') + 1:len(Name)] Component = ReturnBPLoop(BigData, ActualName) FProps["CompProps"] = Component["Properties"] if "Properties" in Component else None newjson.append(fnc) if has_key("ChildNodes", FProps): for CN in FProps["ChildNodes"]: ChildObjectName = CN["ObjectName"] ChildName = ChildObjectName[ChildObjectName.rfind('.') + 1:len(ChildObjectName)] ChildNodes.append(ChildName) if fName == "GameObjectMesh": GameObjects.append(fnc) FullJson["Nodes"] = newjson FullJson["SceneRoot"] = sceneroot FullJson["GameObjects"] = GameObjects FullJson["ChildNodes"] = ChildNodes return FullJson def check_export(settings): exp_path = settings.selected_map.folder_path.joinpath("exported.yo") if exp_path.exists(): exp_data = json.load(open(exp_path)) val_version = exp_data[0] current_val_version = get_valorant_version() if settings.val_version != val_version or settings.dev_force_reexport: return True else: return True return False def write_export_file(): new_json = [get_valorant_version()] json_object = json.dumps(new_json, indent=4) return json_object def get_cubemap_texture(Seting): pathCube = Seting["ObjectName"] newtext = pathCube.replace("TextureCube ", "") AssetPath = (f'/project/{newtext}.{newtext}') TextureCubeMap = unreal.load_asset(AssetPath) return TextureCubeMap def get_valorant_version(): val_file = "/project/ Games\\Metadata\\valorant.live\\valorant.live.ok" if os.path.exists(val_file): with open(val_file, "r") as f: file = f.read() split_file = file.split('\n') return split_file[0].split('/')[-1].split('.')[0] else: return None def get_ies_texture(setting): pathIES = setting["ObjectName"] StartNewTextureName = pathIES NewTextureName = return_formatted_string(StartNewTextureName, "_") AssetPath = (f'/project/{NewTextureName}.{NewTextureName}') TextureIES = unreal.load_asset(AssetPath) return TextureIES def set_material_vector_value(Mat, ParamName, Value): unreal.MaterialEditingLibrary.set_material_instance_vector_parameter_value(Mat, ParamName, Value) unreal.MaterialEditingLibrary.update_material_instance(Mat) def set_material_scalar_value(Mat, ParamName, Value): unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(Mat, ParamName, Value) unreal.MaterialEditingLibrary.update_material_instance(Mat) def GetReadableUMapType(mapname): for j in JsonMapTypeData: NewMapName = j["Name"] MapType = j["StreamingType"] if mapname == NewMapName: return MapType BLACKLIST = [ "navmesh", "_breakable", "_collision", "windstreaks_plane", "sm_port_snowflakes_boundmesh", "M_Pitt_Caustics_Box", "box_for_volumes", "BombsiteMarker_0_BombsiteA_Glow", "BombsiteMarker_0_BombsiteB_Glow", "_col", "M_Pitt_Lamps_Glow", "SM_Pitt_Water_Lid", "Bombsite_0_ASiteSide", "Bombsite_0_BSiteSide" "For_Volumes", "Foxtrot_ASite_Plane_DU", "Foxtrot_ASite_Side_DU", "BombsiteMarker_0_BombsiteA_Glow", "BombsiteMarker_0_BombsiteB_Glow", "DirtSkirt", "Tech_0_RebelSupplyCargoTarpLargeCollision", ] def get_umap_type(mapname): for j in JsonMapTypeData: NewMapName = j["Name"] MapType = j["StreamingType"] if mapname == NewMapName: return eval(f'unreal.{MapType}') def import_shader(Shader): BaseShader = unreal.load_asset(f'/project/{Shader}') return BaseShader def return_object_name(name): rformPar = name.rfind(' ') + 1 return name[rformPar:len(name)] def mesh_to_asset(Mesh, Type, ActualType): if Mesh == None: return None Name = Mesh["ObjectName"] typestring = str(Type) NewName = Name.replace(f'{Type}', "") PathToGo = f'/project/{ActualType}/{NewName}' print(Mesh) asset = unreal.load_asset(PathToGo) print(asset) return asset def path_convert(path: str) -> str: b, c, rest = path.split("\\", 2) if b == "ShooterGame": b = "Game" if c == "Content": c = "" return "\\".join((b, c, rest)) def get_scene_transform(prop): quat = unreal.Quat() LocationUnreal = unreal.Vector(0.0, 0.0, 0.0) ScaleUnreal = unreal.Vector(1.0, 1.0, 1.0) RotationUnreal = unreal.Rotator(0.0, 0.0, 0.0) if has_key("SceneAttachRelativeLocation",prop): loc = prop["SceneAttachRelativeLocation"] LocationUnreal = unreal.Vector(loc["X"], loc["Y"], loc["Z"]) if has_key("SceneAttachRelativeLocation",prop): rot = prop["SceneAttachRelativeRotation"] RotationUnreal = unreal.Rotator(rot["Roll"], rot["Pitch"], rot["Yaw"]) if has_key("SceneAttachRelativeLocation",prop): scale = prop["SceneAttachRelativeScale3D"] ScaleUnreal = unreal.Vector(scale["X"], scale["Y"], scale["Z"]) return unreal.Transform(LocationUnreal, RotationUnreal, ScaleUnreal) def get_transform(Prop): TransformData = None bIsInstanced = False Props = Prop Quat = unreal.Quat() if has_key("TransformData", Props): TransformData = Props["TransformData"] bIsInstanced = True if has_key("RelativeLocation", Props) or has_key("OffsetLocation", Props) or has_key("Translation", TransformData) : if bIsInstanced: Location = TransformData["Translation"] else: Location = Props["RelativeLocation"] LocationUnreal = unreal.Vector(Location["X"], Location["Y"], Location["Z"]) else: LocationUnreal = unreal.Vector(0.0, 0.0, 0.0) if has_key("RelativeScale3D", Props) or has_key("Scale3D", TransformData): if bIsInstanced: Scale = TransformData["Scale3D"] ScaleUnreal = unreal.Vector(Scale["X"], Scale["Y"], Scale["Z"]) else: Scale = Props["RelativeScale3D"] ScaleUnreal = unreal.Vector(Scale["X"], Scale["Y"], Scale["Z"]) else: ScaleUnreal = unreal.Vector(1.0, 1.0, 1.0) if has_key("RelativeRotation", Props) or has_key("Rotation", TransformData): if bIsInstanced: Rotation = TransformData["Rotation"] Quat = unreal.Quat(Rotation["X"], Rotation["Y"], Rotation["Z"], Rotation["W"]) RotationUnreal = unreal.Rotator(0.0, 0.0, 0.0) else: Rotation = Props["RelativeRotation"] RotationUnreal = unreal.Rotator(Rotation["Roll"], Rotation["Pitch"], Rotation["Yaw"]) else: RotationUnreal = unreal.Rotator(0.0, 0.0, 0.0) Trans = unreal.Transform(LocationUnreal, RotationUnreal, ScaleUnreal) if bIsInstanced: Trans.set_editor_property("rotation", Quat) return Trans def has_key(key, array): if array == None: return False if key in array: return True else: return False def GetClassName(self): return type(self).__name__ def return_formatted_string(string, prefix): start = string.rfind(prefix) + 1 end = len(string) return string[start:end] def has_transform(prop): bFactualBool = False if has_key("AttachParent", prop): bFactualBool = False if has_key("RelativeLocation", prop): bFactualBool = True if has_key("SceneAttachRelativeLocation", prop): bFactualBool = True if has_key("SceneAttachRelativeRotation", prop): bFactualBool = True if has_key("SceneAttachRelativeScale3D", prop): bFactualBool = True if has_key("RelativeRotation", prop): bFactualBool = True if has_key("RelativeScale3D", prop): bFactualBool = True if bFactualBool: return get_transform(prop) return bFactualBool def return_python_unreal_enum(value): ind = 0 value = re.sub(r'([a-z])([A-Z])', r'\1_\2', value) if value[0] == "_": ind = 1 return value[ind:len(value)].upper() def filter_objects(umap_DATA, current_umap_name) -> list: objects = umap_DATA filtered_list = [] # Debug check if SELECTIVE_OBJECTS: for filter_model_name in SELECTIVE_OBJECTS: for og_model in objects: object_type = get_object_type(og_model) if object_type == "mesh": if filter_model_name in og_model["Properties"]["StaticMesh"]["ObjectPath"]: og_model["Name"] = og_model["Properties"]["StaticMesh"]["ObjectPath"] filtered_list.append(og_model) elif object_type == "decal": if filter_model_name in og_model["Outer"]: og_model["Name"] = og_model["Outer"] filtered_list.append(og_model) elif object_type == "light": if filter_model_name in og_model["Outer"]: og_model["Name"] = og_model["Outer"] filtered_list.append(og_model) else: filtered_list = objects new_list = [] # Check for blacklisted items for og_model in filtered_list: objname = get_obj_name(data=og_model, mat=False) if not objname: continue model_name_lower = objname.lower() if is_blacklisted(model_name_lower): continue else: new_list.append(og_model) return new_list def is_blacklisted(object_name: str) -> bool: for blocked in BLACKLIST: if blocked.lower() in object_name.lower(): return True return False def get_obj_name(data: dict, mat: bool): if mat: s = data["ObjectPath"] else: if has_key("Properties", data) == False: return "None" if "StaticMesh" in data["Properties"]: d = data["Properties"]["StaticMesh"] if not d: return None s = d["ObjectPath"] else: if not has_key("Outer", data): return None s = data["Outer"] k = get_name(s) return k def get_name(s: str) -> str: return Path(s).stem def cast(object_to_cast=None, object_class=None): try: return object_class.cast(object_to_cast) except: return None def open_folder(path): """ Open a file explorer to a path :param path: path to folder :return: """ path = os.path.normpath(path) if os.path.isdir(path): run([FILEBROWSER_PATH, path]) def get_files(path: str, extension: str = "") -> list: """ Get all files in a directory :param path: path to directory :param extension: extension of files to get :return: list of files """ files = list() for file in os.listdir(path): if extension in file: files.append(Path(os.path.join(path, file))) return files def open_folder(path): """ Open a file explorer to a path :param path: path to folder :return: """ path = os.path.normpath(path) if os.path.isdir(path): run([FILEBROWSER_PATH, path]) def save_list(filepath: Path, lines: list): """ Save a list to a file :param filepath: path to file :param lines: list of lines :return: """ # Flatten umap objects lines = list(flatten_list(lines)) # Remove Duplicates lines = list(dict.fromkeys(lines)) with open(filepath.__str__(), 'w') as f: f.write('\n'.join(lines)) return filepath.__str__() def save_json(p: str, d): """ Save a dictionary to a json file :param p: path to file :param d: dictionary :return: """ with open(p, 'w') as jsonfile: json.dump(d, jsonfile, indent=4) def read_json(p: str) -> dict: """ Read a json file and return a dictionary :param p: path to file :return: """ with open(p) as json_file: return json.load(json_file) def get_mat(decal_dict): mat_name = get_obj_name(data=decal_dict, mat=True) return unreal.load_asset( f'/project/{mat_name}.{mat_name}') def get_scene_parent(obj, OuterName, umapfile): types = ["SceneComponent", "BrushComponent", "StaticMeshComponent"] if OuterName == 'PersistentLevel': OuterName = obj["Name"] for j in umapfile: tipo = j["Type"] if not has_key("Outer", j): continue outer = j["Outer"] if outer == "PersistentLevel": outer = j["Name"] # print(f'OuterName trying to find is {OuterName} and current outer is {outer} // also tipo is {tipo}') if has_key("Properties", j) == False: continue KeyOuter = has_key("AttachParent", j["Properties"]) if outer == OuterName and tipo in types and KeyOuter == False: return has_transform(j["Properties"]) # exit() def set_unreal_prop(self,prop_name,prop_value): try: self.set_editor_property(prop_name,prop_value) except: print(f'UianaPropLOG: Error setting {prop_name} to {prop_value}') def shorten_path(file_path, length) -> str: """ Shorten a path to a given length :param file_path: path to shorten :param length: length to shorten to :return: shortened path """ return f"..\{os.sep.join(file_path.split(os.sep)[-length:])}" def flatten_list(collection): """ Flatten a list of lists :param collection: list of lists :return: list """ for x in collection: if isinstance(x, Iterable) and not isinstance(x, str): yield from flatten_list(x) else: yield x def create_folders(self): for attr, value in self.__dict__.items(): if "path" in attr: f = Path(value) if not f.exists(): print(f"Creating folder {f}") f.mkdir(parents=True) # ANCHOR: Classes # -------------------------- # class Settings: def __init__(self, UESet): self.aes = UESet.vAesKey self.texture_format = ".png" ########## have to fix so it gets actual dir self.script_root = UESet.PPluginPath self.tools_path = self.script_root.joinpath("tools") self.importer_assets_path = self.script_root.joinpath("assets") self.paks_path = UESet.PPakFolder self.import_decals = UESet.bImportDecal self.import_blueprints = UESet.bImportBlueprint self.import_lights = UESet.bImportLights self.import_Mesh = UESet.bImportMesh self.import_materials = UESet.bImportMaterial self.import_sublevel = UESet.bImportSubLevels self.manual_lmres_mult = UESet.iManualLMResMult self.combine_umaps = False self.val_version = get_valorant_version() self.dev_force_reexport = False self.export_path = UESet.PExportPath self.assets_path = self.export_path.joinpath("export") self.maps_path = self.export_path.joinpath("maps") self.umodel = self.script_root.joinpath("tools", "umodel.exe") self.debug = False self.cue4extractor = self.script_root.joinpath("tools", "cue4extractor.exe") self.log = self.export_path.joinpath("import.log") self.umap_list_path = self.importer_assets_path.joinpath("umaps.json") self.umap_list = read_json(self.umap_list_path) self.selected_map = Map(UESet.fMapName, self.maps_path, self.umap_list) self.shaders = [ "VALORANT_Base", "VALORANT_Decal", "VALORANT_Emissive", "VALORANT_Emissive_Scroll", "VALORANT_Hologram", "VALORANT_Glass", "VALORANT_Blend", "VALORANT_Decal", "VALORANT_MRA_Splitter", "VALORANT_Normal_Fix", "VALORANT_Screen" ] create_folders(self) ## Map Definitions class Map: def __init__(self, selected_map_name: str, maps_path: Path, all_umaps: list): self.name = selected_map_name # print(maps_path, self.name) self.folder_path = maps_path.joinpath(self.name) self.umaps = all_umaps[self.name] # print(self) self.actors_path = self.folder_path.joinpath("actors") self.materials_path = self.folder_path.joinpath("materials") self.materials_ovr_path = self.folder_path.joinpath("materials_ovr") self.objects_path = self.folder_path.joinpath("objects") self.scenes_path = self.folder_path.joinpath("scenes") self.umaps_path = self.folder_path.joinpath("umaps") create_folders(self) # Actor definitions class actor_defs(): def __init__(self, Actor): self.data = Actor self.name = Actor["Name"] if has_key("Name", Actor) else None self.type = Actor["Type"] if has_key("Type", Actor) else None self.props = Actor["Properties"] if has_key("Properties", Actor) else {} ## add new attribute that gets every key from props that starts with "SceneAttach" and adds it to a dict if Actor has_key else none self.scene_props = {k: v for k, v in self.props.items() if k.startswith("SceneAttach")} if has_key("SceneAttach", self.props) else None self.outer = Actor["Outer"] if has_key("Outer", Actor) else None self.transform = has_transform(self.props) self.debug = f'ActorName: {self.name} // ActorType: {self.type} // ActorOuter: {self.outer} // ActorTransform: {self.transform} // ActorProps: {self.props.keys()}'
# Copyright Epic Games, Inc. All Rights Reserved """ This script handles processing jobs and shots in the current loaded queue """ import unreal from .utils import ( movie_pipeline_queue, execute_render, setup_remote_render_jobs, update_render_output ) def setup_render_parser(subparser): """ This method adds a custom execution function and args to a render subparser :param subparser: Subparser for processing custom sequences """ # Function to process arguments subparser.set_defaults(func=_process_args) def render_jobs( is_remote=False, is_cmdline=False, executor_instance=None, remote_batch_name=None, remote_job_preset=None, output_dir_override=None, output_filename_override=None ): """ This renders the current state of the queue :param bool is_remote: Is this a remote render :param bool is_cmdline: Is this a commandline render :param executor_instance: Movie Pipeline Executor instance :param str remote_batch_name: Batch name for remote renders :param str remote_job_preset: Remote render job preset :param str output_dir_override: Movie Pipeline output directory override :param str output_filename_override: Movie Pipeline filename format override :return: MRQ executor """ if not movie_pipeline_queue.get_jobs(): # Make sure we have jobs in the queue to work with raise RuntimeError("There are no jobs in the queue!!") # Update the job for job in movie_pipeline_queue.get_jobs(): # If we have output job overrides and filename overrides, update it on # the job if output_dir_override or output_filename_override: update_render_output( job, output_dir=output_dir_override, output_filename=output_filename_override ) # Get the job output settings output_setting = job.get_configuration().find_setting_by_class( unreal.MoviePipelineOutputSetting ) # Allow flushing flies to disk per shot. # Required for the OnIndividualShotFinishedCallback to get called. output_setting.flush_disk_writes_per_shot = True if is_remote: setup_remote_render_jobs( remote_batch_name, remote_job_preset, movie_pipeline_queue.get_jobs(), ) try: # Execute the render. # This will execute the render based on whether its remote or local executor = execute_render( is_remote, executor_instance=executor_instance, is_cmdline=is_cmdline, ) except Exception as err: unreal.log_error( f"An error occurred executing the render.\n\tError: {err}" ) raise return executor def _process_args(args): """ Function to process the arguments for the sequence subcommand :param args: Parsed Arguments from parser """ return render_jobs( is_remote=args.remote, is_cmdline=args.cmdline, remote_batch_name=args.batch_name, remote_job_preset=args.deadline_job_preset, output_dir_override=args.output_override, output_filename_override=args.filename_override )
# AdvancedSkeleton To ControlRig # Copyright (C) Animation Studios # email: [email protected] # exported using AdvancedSkeleton version:x.xx import unreal import re engineVersion = unreal.SystemLibrary.get_engine_version() asExportVersion = x.xx asExportTemplate = '4x' print ('AdvancedSkeleton To ControlRig (Unreal:'+engineVersion+') (AsExport:'+str(asExportVersion)+') (Template:'+asExportTemplate+')') utilityBase = unreal.GlobalEditorUtilityBase.get_default_object() selectedAssets = utilityBase.get_selected_assets() if len(selectedAssets)<1: raise Exception('Nothing selected, you must select a ControlRig') selectedAsset = selectedAssets[0] if selectedAsset.get_class().get_name() != 'ControlRigBlueprint': raise Exception('Selected object is not a ControlRigBlueprint, you must select a ControlRigBlueprint') ControlRigBlueprint = selectedAsset HierarchyModifier = ControlRigBlueprint.get_hierarchy_modifier() try: RigVMController = ControlRigBlueprint.get_editor_property('controller') #UE4 except: RigVMController = ControlRigBlueprint.get_controller() #UE5 PreviousArrayInfo = dict() global ASCtrlNr global PreviousEndPlug global PreviousEndPlugInv global PreviousYInv global sp global nonTransformFaceCtrlNr ASCtrlNr = 0 PreviousYInv = 0 nonTransformFaceCtrlNr = -1 sp = '/project/.RigUnit_' PreviousEndPlug = 'RigUnit_BeginExecution.ExecuteContext' PreviousEndPlugInv = 'RigUnit_InverseExecution.ExecuteContext' def asAddCtrl (name, parent, joint, type, arrayInfo, gizmoName, ws, size, offT, color): global PreviousEndPlug global PreviousEndPlugInv global PreviousArrayInfo global ctrlBoxSize global ASCtrlNr global nonTransformFaceCtrlNr endPlug = name+'_CON.ExecuteContext' RigVMGraph = ControlRigBlueprint.model numNodes = len(RigVMGraph.get_nodes()) y = ASCtrlNr*400 ASCtrlNr=ASCtrlNr+1 ASDrivenNr = int() RootScale = unreal.Vector(x=1.0, y=1.0, z=1.0) ParentRigBone = unreal.RigBone() ParentRigBoneName = parent.replace("FK", "") hasCon = True x = joint.split("_") if len(x)>1: baseName = x[0] side = '_'+x[1] x = ParentRigBoneName.split("_") if len(x)>1: ParentRigBoneBaseName = x[0] RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == 'Root_M'): RootScale = HierarchyModifier.get_bone (key).get_editor_property('global_transform').scale3d if (key.name == ParentRigBoneName): if (key.type == 1):#Bone ParentRigBone = HierarchyModifier.get_bone (key) RigControl = asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color) if name=='Main': return #GT GT = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GT') RigVMController.set_node_position (GT, [-500, y]) RigVMController.set_pin_default_value(name+'_GT.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GT.Item.Name',name) if name=='RootX_M': #CON CON = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name=name+'_CON') RigVMController.set_node_position (CON, [100, y-90]) RigVMController.set_pin_default_value(name+'_CON.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_CON.Item.Name',joint) RigVMController.add_array_pin(name+'_CON.Targets') RigVMController.add_link(name+'_GT.Transform' , name+'_CON.Targets.0.Transform') RigVMController.add_link(PreviousEndPlug , name+'_CON.ExecuteContext') endPlug = name+'_CON.ExecuteContext' else: #ST ST = asAddNode (sp+'SetTransform','Execute',node_name=name+'_ST') RigVMController.set_node_position (ST, [100, y]) RigVMController.set_pin_default_value(name+'_ST.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_ST.Item.Name',joint) RigVMController.add_link(name+'_GT.Transform' , name+'_ST.Transform') RigVMController.set_pin_default_value(name+'_ST.bPropagateToChildren','True') RigVMController.add_link(PreviousEndPlug , name+'_ST.ExecuteContext') endPlug = name+'_ST.ExecuteContext' if type=='FK': if "twistJoints" in PreviousArrayInfo: inbetweenJoints = int (PreviousArrayInfo["twistJoints"]) key = HierarchyModifier.add_bone ('UnTwist'+ParentRigBoneName,parent_name=joint) UnTwistBone = HierarchyModifier.get_bone (key) UnTwistBone.set_editor_property('local_transform', unreal.Transform()) asParent ('UnTwist'+ParentRigBoneName,'TwistSystem') asAlign (ParentRigBoneName,'UnTwist'+ParentRigBoneName) #GTParent constraintTo = str(ParentRigBone.get_editor_property('parent_name')) x = re.search("Part", constraintTo) if x: constraintTo = ParentRigBoneName GTParent = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTParent') RigVMController.set_node_position (GTParent, [600, y]) RigVMController.set_pin_default_value(name+'_GTParent.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTParent.Item.Name',constraintTo) #CONUnTwist CONUnTwist = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name=name+'_CONUnTwist') RigVMController.set_node_position (CONUnTwist, [1000, y]) RigVMController.set_pin_default_value(name+'_CONUnTwist.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_CONUnTwist.Item.Name','UnTwist'+ParentRigBoneName) RigVMController.add_array_pin(name+'_CONUnTwist.Targets') RigVMController.add_link(name+'_GTParent.Transform' , name+'_CONUnTwist.Targets.0.Transform') RigVMController.add_link(endPlug , name+'_CONUnTwist.ExecuteContext') Items = asAddNode (sp+'CollectionItems','Execute',node_name=name+'_Items') RigVMController.set_node_position (Items, [1450, y]) RigVMController.set_pin_default_value(name+'_Items.Items.0.Name','UnTwist'+ParentRigBoneName) for x in range(1,inbetweenJoints+3): RigVMController.add_array_pin(name+'_Items.Items') RigVMController.set_pin_default_value(name+'_Items.Items.'+str(x)+'.Name',ParentRigBoneBaseName+'Part'+str((x-1))+side) RigVMController.set_pin_default_value(name+'_Items.Items.'+str(x)+'.Type','Bone') RigVMController.set_pin_default_value(name+'_Items.Items.1.Name',ParentRigBoneName) RigVMController.set_pin_default_value(name+'_Items.Items.'+str((inbetweenJoints+2))+'.Name',joint) Twist = asAddNode (sp+'TwistBonesPerItem','Execute',node_name=name+'_Twist') RigVMController.set_node_position (Twist, [1750, y]) RigVMController.add_link(name+'_Items.Collection' , name+'_Twist.Items') RigVMController.add_link(name+'_CONUnTwist.ExecuteContext' , name+'_Twist.ExecuteContext') endPlug = name+'_Twist.ExecuteContext' if "inbetweenJoints" in arrayInfo: inbetweenJoints = int (arrayInfo["inbetweenJoints"]) Chain = asAddNode (sp+'CollectionChain','Execute',node_name=name+'_Chain') RigVMController.set_node_position (Chain, [1350, y]) RigVMController.set_pin_default_value(name+'_Chain.FirstItem.Name',baseName+'Part1'+side) RigVMController.set_pin_default_value(name+'_Chain.LastItem.Name',baseName+'Part'+str(inbetweenJoints)+side) #GTDistr GTDistr = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTDistr') RigVMController.set_node_position (GTDistr, [1700, y]) RigVMController.set_pin_default_value(name+'_GTDistr.Item.Type','Control') RigVMController.set_pin_default_value(name+'_GTDistr.Item.Name',name) RigVMController.set_pin_default_value(name+'_GTDistr.Space','LocalSpace') #Distr Distr = asAddNode (sp+'DistributeRotationForCollection','Execute',node_name=name+'_Distr') RigVMController.set_node_position (Distr, [2100, y]) weight = (1.0 / inbetweenJoints) RigVMController.set_pin_default_value(name+'_Distr.Weight',str(weight)) RigVMController.add_link(name+'_Chain.Collection' , name+'_Distr.Items') RigVMController.add_array_pin(name+'_Distr.Rotations') RigVMController.add_link(name+'_GTDistr.Transform.Rotation' , name+'_Distr.Rotations.0.Rotation') RigVMController.add_link(PreviousEndPlug , name+'_Distr.ExecuteContext') endPlug = name+'_Distr.ExecuteContext' if "inbetweenJoints" in PreviousArrayInfo: Transform = RigControl.get_editor_property('offset_transform') SpaceKey = HierarchyModifier.add_space ('Space'+joint) Space = HierarchyModifier.get_space (SpaceKey) Space.set_editor_property('initial_transform', Transform) HierarchyModifier.set_space (Space) RigControl.set_editor_property('offset_transform', unreal.Transform()) HierarchyModifier.set_control (RigControl) asParent (name,'Space'+joint) asParent ('Space'+joint,parent) #GTSpace GTSpace = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTSpace') RigVMController.set_node_position (GTSpace, [600, y]) RigVMController.set_pin_default_value(name+'_GTSpace.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTSpace.Item.Name',joint) #STSpace STSpace = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STSpace') RigVMController.set_node_position (STSpace, [950, y]) RigVMController.set_pin_default_value(name+'_STSpace.Item.Type','Space') RigVMController.set_pin_default_value(name+'_STSpace.Item.Name','Space'+joint) RigVMController.add_link(name+'_GTSpace.Transform' , name+'_STSpace.Transform') RigVMController.set_pin_default_value(name+'_STSpace.bPropagateToChildren','True') RigVMController.add_link(PreviousEndPlug , name+'_STSpace.ExecuteContext') if not "inbetweenJoints" in arrayInfo: RigVMController.add_link(name+'_STSpace.ExecuteContext' , name+'_ST.ExecuteContext') else: RigVMController.add_link(name+'_STSpace.ExecuteContext' , name+'_Distr.ExecuteContext') if "global" in arrayInfo and float(arrayInfo["global"])==10: SpaceKey = HierarchyModifier.add_space ('Global'+name) SpaceObj = HierarchyModifier.get_space (SpaceKey) asParent ('Global'+name, parent) asAlign (name,'Global'+name) RigControl.set_editor_property('offset_transform', unreal.Transform()) HierarchyModifier.set_control (RigControl) asParent (name,'Global'+name) PNPGlobal = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name=name+'_PNPGlobal') RigVMController.set_node_position (PNPGlobal, [-1200, y]) RigVMController.set_pin_default_value(name+'_PNPGlobal.Child.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.Child.Name',name) RigVMController.set_pin_default_value(name+'_PNPGlobal.OldParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.OldParent.Name','Main') RigVMController.set_pin_default_value(name+'_PNPGlobal.NewParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPGlobal.NewParent.Name','Main') #SRGlobal SRGlobal = asAddNode (sp+'SetRotation','Execute',node_name=name+'_SRGlobal') RigVMController.set_node_position (SRGlobal, [-850, y]) RigVMController.set_pin_default_value(name+'_SRGlobal.Item.Type','Space') RigVMController.set_pin_default_value(name+'_SRGlobal.Item.Name','Global'+name) RigVMController.set_pin_default_value(name+'_SRGlobal.bPropagateToChildren','True') RigVMController.add_link(name+'_PNPGlobal.Transform.Rotation' , name+'_SRGlobal.Rotation') RigVMController.add_link(PreviousEndPlug , name+'_SRGlobal.ExecuteContext') #STGlobal STGlobal = asAddNode (sp+'SetTranslation','Execute',node_name=name+'_STGlobal') RigVMController.set_node_position (STGlobal, [-850, y+250]) RigVMController.set_pin_default_value(name+'_STGlobal.Item.Type','Space') RigVMController.set_pin_default_value(name+'_STGlobal.Item.Name','Global'+name) RigVMController.set_pin_default_value(name+'_STGlobal.Space','LocalSpace') RigVMController.set_pin_default_value(name+'_STGlobal.bPropagateToChildren','True') Transform = HierarchyModifier.get_initial_transform(SpaceKey) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.X',str(Transform.translation.x)) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.Y',str(Transform.translation.y)) RigVMController.set_pin_default_value(name+'_STGlobal.Translation.Z',str(Transform.translation.z)) RigVMController.add_link(name+'_SRGlobal.ExecuteContext' , name+'_STGlobal.ExecuteContext') # RigVMController.add_link(name+'_STGlobal.ExecuteContext' , endPlug) RigVMController.add_link(name+'_STGlobal.ExecuteContext' , name+'_ST.ExecuteContext') if type=='IK': RigControl = asAddController ('Pole'+name, parent, joint, type, 'Box_Solid', ws, size/5.0, offT, color) RigControl.set_editor_property('offset_transform', unreal.Transform(location=[float(arrayInfo["ppX"])*RootScale.x,float(arrayInfo["ppZ"])*RootScale.y,float(arrayInfo["ppY"])*RootScale.z],scale=RootScale)) HierarchyModifier.set_control (RigControl) #IK(Basic IK) IK = asAddNode (sp+'TwoBoneIKSimplePerItem','Execute',node_name=name+'_IK') RigVMController.set_node_position (IK, [600, y-130]) RigVMController.set_pin_default_value(name+'_IK.ItemA.Name',arrayInfo["startJoint"]) RigVMController.set_pin_default_value(name+'_IK.ItemB.Name',arrayInfo["middleJoint"]) RigVMController.set_pin_default_value(name+'_IK.EffectorItem.Name',arrayInfo["endJoint"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.X',arrayInfo["paX"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.Y',arrayInfo["paY"]) RigVMController.set_pin_default_value(name+'_IK.PrimaryAxis.Z',arrayInfo["paZ"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.X',arrayInfo["saX"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.Y',arrayInfo["paY"]) RigVMController.set_pin_default_value(name+'_IK.SecondaryAxis.Z',arrayInfo["paZ"]) RigVMController.set_pin_default_value(name+'_IK.PoleVectorKind','Location') RigVMController.set_pin_default_value(name+'_IK.PoleVectorSpace.Type','Control') RigVMController.set_pin_default_value(name+'_IK.PoleVectorSpace.Name','Pole'+name) RigVMController.set_pin_default_value(name+'_IK.bPropagateToChildren','True') RigVMController.add_link(name+'_GT.Transform' , name+'_IK.Effector') RigVMController.add_link(PreviousEndPlug , name+'_IK.ExecuteContext') endPlug = name+'_IK.ExecuteContext' #GTSpace GTSpace = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTSpace') RigVMController.set_node_position (GTSpace, [1000, y]) RigVMController.set_pin_default_value(name+'_GTSpace.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTSpace.Item.Name',arrayInfo["endJoint"]) #modify _GT to use a local-oriented child of ws controller key = HierarchyModifier.add_control (name+'LS',parent_name=name) RigControl = HierarchyModifier.get_control (key) RigControl.set_editor_property('gizmo_enabled',False) HierarchyModifier.set_control (RigControl) RigVMController.set_pin_default_value(name+'_GT.Item.Name',name+'LS') for key in RigElementKeys: if (key.name == arrayInfo["endJoint"]): endJointObject = HierarchyModifier.get_bone (key) EndJointTransform = endJointObject.get_editor_property('global_transform') Rotation = EndJointTransform.rotation.rotator() Transform = unreal.Transform(location=[0,0,0],rotation=Rotation,scale=[1,1,1]) RigControl.set_editor_property('offset_transform', Transform) HierarchyModifier.set_control (RigControl) #Backwards solve nodes (IK) PNPinvIK = asAddNode (sp+'ProjectTransformToNewParent','Execute',node_name=name+'_PNPinvIK') RigVMController.set_node_position (PNPinvIK, [-2900, y]) RigVMController.set_pin_default_value(name+'_PNPinvIK.Child.Type','Control') RigVMController.set_pin_default_value(name+'_PNPinvIK.Child.Name',name) RigVMController.set_pin_default_value(name+'_PNPinvIK.OldParent.Type','Control') RigVMController.set_pin_default_value(name+'_PNPinvIK.OldParent.Name',name+'LS') RigVMController.set_pin_default_value(name+'_PNPinvIK.NewParent.Type','Bone') RigVMController.set_pin_default_value(name+'_PNPinvIK.NewParent.Name',joint) #STinvIK STinvIK = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STinvIK') RigVMController.set_node_position (STinvIK, [-2500, y]) RigVMController.set_pin_default_value(name+'_STinvIK.Item.Type','Control') RigVMController.set_pin_default_value(name+'_STinvIK.Item.Name',name) RigVMController.add_link(name+'_GTSpace.Transform' , name+'_STinvIK.Transform') RigVMController.set_pin_default_value(name+'_STinvIK.bPropagateToChildren','True') RigVMController.add_link(name+'_PNPinvIK.Transform' , name+'_STinvIK.Transform') RigVMController.add_link(PreviousEndPlugInv , name+'_STinvIK.ExecuteContext') #GTinvPole GTinvPole = asAddNode (sp+'GetTransform','Execute',node_name=name+'_GTinvPole') RigVMController.set_node_position (GTinvPole, [-1700, y]) RigVMController.set_pin_default_value(name+'_GTinvPole.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GTinvPole.Item.Name',arrayInfo["middleJoint"]) #STinvPole STinvPole = asAddNode (sp+'SetTransform','Execute',node_name=name+'_STinvPole') RigVMController.set_node_position (STinvPole, [-1300, y]) RigVMController.set_pin_default_value(name+'_STinvPole.Item.Type','Control') RigVMController.set_pin_default_value(name+'_STinvPole.Item.Name','Pole'+name) RigVMController.add_link(name+'_GTSpace.Transform' , name+'_STinvPole.Transform') RigVMController.set_pin_default_value(name+'_STinvPole.bPropagateToChildren','True') RigVMController.add_link(name+'_GTinvPole.Transform' , name+'_STinvPole.Transform') RigVMController.add_link(name+'_STinvIK.ExecuteContext' , name+'_STinvPole.ExecuteContext') endPlugInv = name+'_STinvPole.ExecuteContext' PreviousEndPlugInv = endPlugInv if "twistJoints" in arrayInfo or "inbetweenJoints" in arrayInfo: PreviousArrayInfo = arrayInfo else: PreviousArrayInfo.clear() #DrivingSystem if type=='DrivingSystem' or type=='ctrlBox': if type=='DrivingSystem': RigVMController.set_pin_default_value(name+'_GT.Item.Type','Bone') RigVMController.set_pin_default_value(name+'_GT.Item.Name',joint) RigVMController.set_pin_default_value(name+'_ST.Item.Type','Control') RigVMController.set_pin_default_value(name+'_ST.Item.Name',name) if type=='ctrlBox': Transform = RigControl.get_editor_property('gizmo_transform') if name=='ctrlBox': RigControl.offset_transform.translation = [Transform.translation.z,(Transform.translation.y*-1),Transform.translation.x] ctrlBoxSize = float (arrayInfo["ctrlBoxSize"]) Scale = [0.07,0.15,0.1] ctrlBoxScale = [ctrlBoxSize,ctrlBoxSize,ctrlBoxSize] RigControl.offset_transform.scale3d = ctrlBoxScale RigControl.gizmo_transform.scale3d = Scale RigControl.gizmo_transform.translation = [0,0,-1.5] #guestimate HierarchyModifier.set_control (RigControl) return nonTransformFaceCtrl = False if name=='ctrlEmotions_M' or name=='ctrlPhonemes_M' or name=='ctrlARKit_M' or name=='ctrlBoxRobloxHead_M': nonTransformFaceCtrl = True nonTransformFaceCtrlNr = nonTransformFaceCtrlNr+1 RigControl.set_editor_property('gizmo_enabled',False) HierarchyModifier.set_control (RigControl) if type=='ctrlBox': RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_GT')) RigVMController.remove_node(RigVMGraph.find_node_by_name(name+'_ST')) RigControl.set_editor_property('control_type',unreal.RigControlType.VECTOR2D) RigControl.set_editor_property('primary_axis',unreal.RigControlAxis.Y) RigControl.offset_transform.translation = Transform.translation * (1.0/ctrlBoxSize) RigControl.gizmo_transform.scale3d = [0.05,0.05,0.05] RigControl.limit_translation = True value = unreal.RigControlValue() RigControl.maximum_value = value RigControl.gizmo_transform.translation = [0,0,0] HierarchyModifier.set_control (RigControl) maxXform = unreal.Transform(location=[1,1,1]) minXform = unreal.Transform(location=[-1,-1,-1]) if name=='ctrlMouth_M': maxXform = unreal.Transform(location=[1,1,0]) if re.search("^ctrlCheek_", name) or re.search("^ctrlNose_", name): minXform = unreal.Transform(location=[-1,-1,0]) RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == name): RigControlKey = key HierarchyModifier.set_control_value_transform (RigControlKey, maxXform, value_type=unreal.RigControlValueType.MAXIMUM) HierarchyModifier.set_control_value_transform (RigControlKey, minXform, value_type=unreal.RigControlValueType.MINIMUM) HierarchyModifier.set_control (HierarchyModifier.get_control (RigControlKey)) endPlug = PreviousEndPlug if type=='ctrlBox': AttrGrpkey = HierarchyModifier.add_control (name+"_Attributes",parent_name=parent) else: AttrGrpkey = HierarchyModifier.add_control (name+"_Attributes",parent_name=name) AttrGrpRigControl = HierarchyModifier.get_control (AttrGrpkey) AttrGrpRigControl.set_editor_property('gizmo_transform', unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0,0,0])) Transform = RigControl.get_editor_property('offset_transform').copy() if type=='ctrlBox': Transform.translation.x = -5.0 Transform.translation.z += 0.8 if re.search("_L", name) or re.search("_M", name): Transform.translation.x = 4.0 if nonTransformFaceCtrl: Transform.translation.z = -5.5-(nonTransformFaceCtrlNr*2) # stack rows of sliders downwards else: numAttrs = 0 for Attr in arrayInfo.keys(): if not re.search("-set", Attr): numAttrs=numAttrs+1 Transform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1]) Transform.translation.x = offT[0] Transform.translation.y = numAttrs*0.5*(size/4.0)*-0.5 Transform.translation.z = size/8.0 if re.search("_L", name): Transform.translation.z *= -1 Transform.scale3d=[size/4.0,size/4.0,size/4.0] AttrGrpRigControl.set_editor_property('offset_transform', Transform) HierarchyModifier.set_control (AttrGrpRigControl) Attrs = arrayInfo.keys() attrNr = 0 for Attr in Attrs: if re.search("-set", Attr): if re.search("-setLimits", Attr): DictDrivens = arrayInfo.get(Attr) min = float(list(DictDrivens.keys())[0]) max = float(list(DictDrivens.values())[0]) minXform = unreal.Transform(location=[min,min,min]) RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if key.name == name+"_"+Attr.replace("-setLimits", ""): HierarchyModifier.set_control_value_transform (key, minXform, value_type=unreal.RigControlValueType.MINIMUM) HierarchyModifier.set_control (HierarchyModifier.get_control (key)) continue transformAttrDriver = True if not re.search("translate", Attr) or re.search("rotate", Attr) or re.search("scale", Attr): key = HierarchyModifier.add_control (name+"_"+Attr,parent_name=parent) AttrRigControl = HierarchyModifier.get_control (key) AttrRigControl = asParent (name+"_"+Attr, name+"_Attributes") AttrRigControl.set_editor_property('control_type',unreal.RigControlType.FLOAT) AttrRigControl.set_editor_property('gizmo_color', unreal.LinearColor(r=1.0, g=0.0, b=0.0, a=0.0)) AttrRigControl.set_editor_property('gizmo_transform', unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[0.035,0.035,0.035])) Transform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1]) Transform.translation = [0,attrNr*0.5,0] if type=='ctrlBox': Transform.translation = [0,0,attrNr*-0.5] if nonTransformFaceCtrl or re.search("_M", name): AttrRigControl.set_editor_property('primary_axis',unreal.RigControlAxis.Z) Transform.translation = [attrNr,0,0] attrNr = attrNr+1 AttrRigControl.set_editor_property('offset_transform', Transform) AttrRigControl.limit_translation = True HierarchyModifier.set_control (AttrRigControl) maxXform = unreal.Transform(location=[1,1,1]) RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == name+"_"+Attr): RigControlKey = key HierarchyModifier.set_control_value_transform (RigControlKey, maxXform, value_type=unreal.RigControlValueType.MAXIMUM) HierarchyModifier.set_control (HierarchyModifier.get_control (RigControlKey)) transformAttrDriver = False DictDrivens = arrayInfo.get(Attr) KeysDrivens = DictDrivens.keys() for Driven in KeysDrivens: Value = float(DictDrivens.get(Driven)) x2 = ASDrivenNr*1200 dNr = str(ASDrivenNr) ASDrivenNr = ASDrivenNr+1 x = Driven.split(".") obj = x[0] attr = '_'+x[1] axis = attr[-1] valueMult = 1 if re.search("rotate", attr): if axis == 'X' or axis=='Z': valueMult = -1 if re.search("translate", attr): if axis=='Y': valueMult = -1 multiplier = Value*valueMult asFaceBSDriven = False if re.search("asFaceBS[.]", Driven):#asFaceBS asFaceBSDriven = True if not (asFaceBSDriven): RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if key.name == obj: objObject = HierarchyModifier.get_control(key) if not asObjExists ('Offset'+obj): SpaceKey = HierarchyModifier.add_space ('Offset'+obj) SpaceObj = HierarchyModifier.get_space (SpaceKey) objParent = str(objObject.get_editor_property('parent_name')) asParent ('Offset'+obj, objParent) asAlign (obj,'Offset'+obj) parentTo = 'Offset'+obj for x in range(1,9): sdk = 'SDK'+obj+"_"+str(x) if not asObjExists (sdk): break if x>1: parentTo = 'SDK'+obj+"_"+str(x-1) SpaceKey = HierarchyModifier.add_space (sdk) asParent (sdk,parentTo) objObject.set_editor_property('offset_transform', unreal.Transform()) HierarchyModifier.set_control (objObject) asParent (obj,sdk) #GTDriver if transformAttrDriver: GTDriver = asAddNode (sp+'GetControlVector2D','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_GTDriver') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_GTDriver.Control',name) gtPlug = name+"_"+obj+"_"+attr+dNr+'_GTDriver.Vector.'+Attr[-1]#Attr[-1] is DriverAxis else: GTDriver = asAddNode (sp+'GetControlFloat','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_GTDriver') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_GTDriver.Control',name+"_"+Attr) gtPlug = name+"_"+obj+"_"+attr+dNr+'_GTDriver.FloatValue' RigVMController.set_node_position (GTDriver, [500+x2, y]) #MFM MFM = asAddNode (sp+'MathFloatMul','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_MFM') RigVMController.set_node_position (MFM, [900+x2, y]) RigVMController.add_link(gtPlug , name+"_"+obj+"_"+attr+dNr+'_MFM.A') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_MFM.B',str(multiplier)) if asFaceBSDriven: #Clamp Clamp = asAddNode (sp+'MathFloatClamp','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_Clamp') RigVMController.set_node_position (Clamp, [900+x2, y+100]) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_Clamp.Maximum','5.0') RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_Clamp.Value') #STDriven STDriven = asAddNode (sp+'SetCurveValue','Execute',node_name=name+"_"+Attr+"_"+attr+'_STDriven') RigVMController.set_node_position (STDriven, [1100+x2, y]) RigVMController.set_pin_default_value(name+"_"+Attr+"_"+attr+'_STDriven.Curve',Driven.split(".")[1]) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_Clamp.Result' , name+"_"+Attr+"_"+attr+'_STDriven.Value') RigVMController.add_link(endPlug , name+"_"+Attr+"_"+attr+'_STDriven.ExecuteContext') endPlug =name+"_"+Attr+"_"+attr+'_STDriven.ExecuteContext' else: #STDriven STDriven = asAddNode (sp+'SetTransform','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_STDriven') RigVMController.set_node_position (STDriven, [1300+x2, y]) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Item.Type','Space') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Item.Name',sdk) RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.Space','LocalSpace') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_STDriven.bPropagateToChildren','True') RigVMController.add_link(endPlug , name+"_"+obj+"_"+attr+dNr+'_STDriven.ExecuteContext') endPlug = name+"_"+obj+"_"+attr+dNr+'_STDriven.ExecuteContext' #TFSRT TFSRT = asAddNode (sp+'MathTransformFromSRT','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_TFSRT') RigVMController.set_node_position (TFSRT, [900+x2, y+150]) if re.search("translate", attr): RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Location.'+axis) if re.search("rotate", attr): RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Rotation.'+axis) if re.search("scale", attr): #scale just add 1, not accurate but simplified workaround MFA = asAddNode (sp+'MathFloatAdd','Execute',node_name=name+"_"+obj+"_"+attr+dNr+'_MFA') RigVMController.set_node_position (MFA, [1100+x2, y]) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFM.Result' , name+"_"+obj+"_"+attr+dNr+'_MFA.A') RigVMController.set_pin_default_value(name+"_"+obj+"_"+attr+dNr+'_MFA.B','1') RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_MFA.Result' , name+"_"+obj+"_"+attr+dNr+'_TFSRT.Scale.'+axis) RigVMController.add_link(name+"_"+obj+"_"+attr+dNr+'_TFSRT.Transform', name+"_"+obj+"_"+attr+dNr+'_STDriven.Transform') #face if re.search("Teeth_M", name): RigControl.set_editor_property('gizmo_enabled',False) HierarchyModifier.set_control (RigControl) if name=="Jaw_M": RigControl.set_editor_property('gizmo_name','HalfCircle_Thick') RigControl.set_editor_property('gizmo_name','HalfCircle_Thick') Transform = RigControl.get_editor_property('gizmo_transform') Transform.rotation=[0,0,180] RigControl.set_editor_property('gizmo_transform', Transform) HierarchyModifier.set_control (RigControl) PreviousEndPlug = endPlug def asObjExists (obj): RigElementKeys = HierarchyModifier.get_elements() LocObject = None for key in RigElementKeys: if key.name == obj: return True return False def asAddController (name, parent, joint, type, gizmoName, ws, size, offT, color): x = re.search("^Space.*", parent) if x: key = HierarchyModifier.add_control (name,space_name=parent) else: key = HierarchyModifier.add_control (name,parent_name=parent) RigControl = HierarchyModifier.get_control (key) RigElementKeys = HierarchyModifier.get_elements() LocObject = None jointIsBone = False for key in RigElementKeys: if key.name == joint: if key.type == 1: #BONE jointObject = HierarchyModifier.get_bone(key) jointIsBone = True if key.name == 'Loc'+name: LocObject = HierarchyModifier.get_bone(key) OffsetTransform = unreal.Transform(location=[0,0,0],rotation=[0,0,0],scale=[1,1,1]) GizmoLocation = [offT[0],offT[2],offT[1]] GizmoRotation = [0,0,0] if ws is 0: GizmoRotation = [90,0,0] GizmoLocation = [offT[0],offT[1]*-1,offT[2]] if type=="DrivingSystem": GizmoRotation = [0,0,0] if type=="ctrlBox": GizmoRotation = [0,0,90] if re.search("^Eye_.*", name) or re.search("^Iris_.*", name) or re.search("^Pupil_.*", name): GizmoRotation = [0,90,0] RigControl.set_editor_property('gizmo_visible',False) x = re.search("^Pole.*", name) if x: GizmoLocation = [0,0,0] s = 0.01*size Scale = [s,s,s] if LocObject==None: LocKey = HierarchyModifier.add_bone ('Loc'+name,'LocBones') LocObject = HierarchyModifier.get_bone (LocKey) if jointIsBone: jointTransform = jointObject.get_editor_property('global_transform') if ws is 1: jointTransform.rotation = [0,0,0] OffsetTransform = jointTransform if name!='Main': LocObject.set_editor_property('initial_transform', jointTransform) HierarchyModifier.set_bone (LocObject) if parent!='': for key in RigElementKeys: if key.name == 'Loc'+parent: ParentLocObject = HierarchyModifier.get_bone(key) LocTransform = ParentLocObject.get_editor_property('global_transform') if jointIsBone: OffsetTransform = jointTransform.make_relative(LocTransform) RigControl.set_editor_property('offset_transform', OffsetTransform) RigControl.set_editor_property('gizmo_name',gizmoName) RigControl.set_editor_property('gizmo_transform', unreal.Transform(location=GizmoLocation,rotation=GizmoRotation,scale=Scale)) Color = unreal.Color(b=color[2]*255, g=color[1]*255, r=color[0]*255, a=0) LinearColor = unreal.LinearColor() LinearColor.set_from_srgb(Color) RigControl.set_editor_property('gizmo_color',LinearColor) HierarchyModifier.set_control (RigControl) return RigControl def asParent (child,parent): RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == child): childKey = key for key in RigElementKeys: if (key.name == parent): parentKey = key if not HierarchyModifier.reparent_element (childKey, parentKey): #bug in UE4.27: n`th Space, can not be child of n`th Ctrl, making a new space HierarchyModifier.rename_element (childKey, child+'SpaceParentX') childKey = HierarchyModifier.add_space (child) if not HierarchyModifier.reparent_element (childKey, parentKey): raise Exception('Failed to parent:'+child+' to '+parent) asParent (child+'SpaceParentX','Spaces') return asGetRigElement(child) def asGetRigElement (elementName): RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if key.name == elementName: if key.type == 1: #BONE element = HierarchyModifier.get_bone(key) if key.type == 2: #SPACE element = HierarchyModifier.get_space(key) if key.type == 4: #CONTROL element = HierarchyModifier.get_control(key) return element def asAlign (source,dest): RigElementKeys = HierarchyModifier.get_elements() for key in RigElementKeys: if (key.name == source): if key.type == 1: #BONE sourceObject = HierarchyModifier.get_bone(key) sourceType = 'Bone' if key.type == 2: #SPACE sourceObject = HierarchyModifier.get_space(key) sourceType = 'Space' if key.type == 4: #CONTROL sourceObject = HierarchyModifier.get_control(key) sourceType = 'Control' if (key.name == dest): if key.type == 1: #BONE destObject = HierarchyModifier.get_bone(key) destType = 'Bone' if key.type == 2: #SPACE destObject = HierarchyModifier.get_space(key) destType = 'Space' if key.type == 4: #CONTROL destObject = HierarchyModifier.get_control(key) destType = 'Control' if sourceType != 'Bone': for key in RigElementKeys: if key.name == 'Loc'+source: source = 'Loc'+source sourceObject = HierarchyModifier.get_bone(key) sourceType = 'Bone' Transform = sourceObject.get_editor_property('global_transform') #Relative to parent LocDestParent = None DestParent = destObject.get_editor_property('parent_name') for key in RigElementKeys: if key.name == 'Loc'+str(DestParent): LocDestParent = HierarchyModifier.get_bone(key) LocDestParentTransform = LocDestParent.get_editor_property('global_transform') Transform = Transform.make_relative(LocDestParentTransform) destObject.set_editor_property('initial_transform', Transform) if destType == 'Bone': HierarchyModifier.set_bone (destObject) if destType == 'Space': HierarchyModifier.set_space (destObject) if destType == 'Control': HierarchyModifier.set_control (destObject) def asAddNode (script_struct_path, method_name, node_name): #RigVMController. #add_struct_node_from_struct_path UE4 #add_unit_node_from_struct_path UE5 try: node = RigVMController.add_struct_node_from_struct_path(script_struct_path,method_name,node_name=node_name) #UE4 except: node = RigVMController.add_unit_node_from_struct_path(script_struct_path,method_name,node_name=node_name) #UE5 return node def main (): global PreviousEndPlugInv RigElementKeys = HierarchyModifier.get_elements() RigVMGraph = ControlRigBlueprint.model #Clear out existing rig-setup nodes = RigVMGraph.get_nodes() for node in nodes: RigVMController.remove_node(node) #Clear out existing controllers for key in RigElementKeys: if key.name == 'MotionSystem': HierarchyModifier.remove_element(key) if not (key.type==1 or key.type==8): #BONE try: HierarchyModifier.remove_element(key) except: pass BeginExecutionNode = asAddNode (sp+'BeginExecution','Execute',node_name='RigUnit_BeginExecution') RigVMController.set_node_position (BeginExecutionNode, [-300, -100]) InverseExecutionNode = asAddNode (sp+'InverseExecution','Execute',node_name='RigUnit_InverseExecution') RigVMController.set_node_position (InverseExecutionNode, [-1900, -100]) #Backwards solve nodes GTinvRoot = asAddNode (sp+'GetTransform','Execute',node_name='Root_M_GTinvRoot') RigVMController.set_node_position (GTinvRoot, [-2100, 400]) RigVMController.set_pin_default_value('Root_M_GTinvRoot.Item.Type','Bone') RigVMController.set_pin_default_value('Root_M_GTinvRoot.Item.Name','Root_M') CONinvRoot = asAddNode (sp+'TransformConstraintPerItem','Execute',node_name='Root_M_CONinvRoot') RigVMController.set_node_position (CONinvRoot, [-1500, 400-90]) RigVMController.set_pin_default_value('Root_M_CONinvRoot.Item.Type','Control') RigVMController.set_pin_default_value('Root_M_CONinvRoot.Item.Name','RootX_M') RigVMController.add_array_pin('Root_M_CONinvRoot.Targets') RigVMController.add_link('Root_M_GTinvRoot.Transform' , 'Root_M_CONinvRoot.Targets.0.Transform') RigVMController.add_link('RigUnit_InverseExecution.ExecuteContext' , 'Root_M_CONinvRoot.ExecuteContext') CCinv = asAddNode (sp+'CollectionChildren','Execute',node_name='CCinv') RigVMController.set_node_position (CCinv, [-2600, 1000]) RigVMController.set_pin_default_value('CCinv.Parent.Type','Bone') RigVMController.set_pin_default_value('CCinv.Parent.Name','Root_M') RigVMController.set_pin_default_value('CCinv.bRecursive','True') RigVMController.set_pin_default_value('CCinv.TypeToSearch','Bone') CLinv = asAddNode (sp+'CollectionLoop','Execute',node_name='CLinv') RigVMController.set_node_position (CLinv, [-2150, 1000]) RigVMController.add_link('Root_M_CONinvRoot.ExecuteContext' , 'CLinv.ExecuteContext') RigVMController.add_link('CCinv.Collection' , 'CLinv.Collection') PreviousEndPlugInv = 'CLinv.Completed' NCinv = asAddNode (sp+'NameConcat','Execute',node_name='NCinv') RigVMController.set_node_position (NCinv, [-1900, 900]) RigVMController.set_pin_default_value('NCinv.A','FK') RigVMController.add_link('CLinv.Item.Name' , 'NCinv.B') GTinv = asAddNode (sp+'GetTransform','Execute',node_name='GTinv') RigVMController.set_node_position (GTinv, [-1900, 1000]) RigVMController.add_link('CLinv.Item.Name' , 'GTinv.Item.Name') IEinv = asAddNode (sp+'ItemExists','Execute',node_name='IEinv') RigVMController.set_node_position (IEinv, [-1700, 700]) RigVMController.set_pin_default_value('IEinv.Item.Type','Control') RigVMController.add_link('NCinv.Result' , 'IEinv.Item.Name') BRinv = RigVMController.add_branch_node(node_name='BRinv') RigVMController.set_node_position (BRinv, [-1650, 850]) RigVMController.add_link('IEinv.Exists' , 'BRinv.Condition') RigVMController.add_link('CLinv.ExecuteContext' , 'BRinv.ExecuteContext') STinv = asAddNode (sp+'SetTransform','Execute',node_name='STinv') RigVMController.set_node_position (STinv, [-1500, 1000]) RigVMController.set_pin_default_value('STinv.Item.Type','Control') RigVMController.add_link('NCinv.Result' , 'STinv.Item.Name') RigVMController.add_link('GTinv.Transform' , 'STinv.Transform') RigVMController.add_link('BRinv.True' , 'STinv.ExecuteContext') HierarchyModifier.add_bone ('MotionSystem') HierarchyModifier.add_bone ('TwistSystem') HierarchyModifier.add_bone ('LocBones') HierarchyModifier.add_bone ('DrivingSystem') HierarchyModifier.add_bone ('Spaces') asParent ('TwistSystem','MotionSystem') asParent ('LocBones','MotionSystem') asParent ('DrivingSystem','MotionSystem') asParent ('Spaces','MotionSystem') selectedAsset.get_class().modify(True)#tag dirty #//-- ASControllers Starts Here --// #//-- ASControllers Ends Here --// # selectedAsset.get_class().modify(True)#tag dirty # Unreal un-sets `dirty` flag upon opening of ControlRigEditor, causing non-prompt for save upon exit and loss of ControlRig, therefor just save # unreal.EditorAssetLibrary.save_asset(selectedAsset.get_path_name()) #Removed since this requires "Editor Scripting Utilities" plugin selectedAsset.get_class().modify(False) print ("ControlRig created") if __name__ == "__main__": main()
import unreal import json # instances of unreal classes editor_util = unreal.EditorUtilityLibrary() system_lib = unreal.SystemLibrary() # prefix mapping prefix_mapping = { "ActorComponent": "AC_", "AnimationBlueprint": "ABP_", "AnimationSequence": "AS_", "AnimBlueprint": "ABP_", "AnimMontage": "AMON_", "AnimSequence": "ASEQ_", "BehaviorTree": "BT_", "BlackboardData": "BB_", "BlendSpace": "BS_", "BlendSpace1D": "BS_", "Blueprint": "BP_", "BlueprintInterface": "BI_", "ControlRigBlueprint": "CTRIG_", "CurveFloat": "CURV_", "CurveLinearColor": "CURV_", "CurveLinearColorAtlas": "CURV_", "CurveTable": "CT_", "DataTable": "DT_", "EditorUtilityBlueprint": "EU_", "EditorUtilityWidgetBlueprint": "EUW_", "Enum": "E_", "EnvQuery": "EQ_", "HDRI": "HDR_", "IKRetargeter": "IKRT_", "IKRigDefinition": "IKRIG_", "LevelSequence": "LS_", "LevelSnapshots": "SNAP_", "Material": "M_", "MaterialFunction": "MF_", "MaterialFunctionMaterialLayer": "MFL_", "MaterialInstance": "MI_", "MaterialInstanceConstant": "MI_", "MaterialParameterCollection": "MPC_", "MediaOutput": "MO_", "MediaPlayer": "MP_", "MediaProfile": "MPR_", "MediaSource": "MS_", "MediaTexture": "MEDT_", "Montages": "AM_", "MorphTarget": "MT_", "NDisplayConfiguration": "NDC_", "NiagaraEmitter": "FXE_", "NiagaraFunction": "FXF_", "NiagaraSystem": "FXS_", "OCIOProfile": "OCIO_", "ParticleSystem": "PS_", "PhysicsAsset": "PHYS_", "PhysicsMaterial": "PM_", "PoseAsset": "POSEA_", "PostProcessMaterial": "PPM_", "RemoteControlPreset": "RCP_", "RenderTarget": "RT_", "Rig": "RIG_", "SequencerEdits": "EDIT_", "SkeletalMesh": "SK_", "Skeleton": "SKEL_", "SoundCue": "SC_", "SoundWave": "S_", "StaticMesh": "SM_", "Structure": "F_", "Texture2D": "T_", "TextureCube": "TCUB_", "TextureRenderTarget2D": "TRT_", "UserDefinedEnum": "E_", "UserDefinedStruct": "STRUCT_", "WidgetBlueprint": "WBP_", "World": "LVL_" } #with open(".\\prefix_mapping.json", "r") as json_file: # prefix_mapping = json.loads(json_file.read()) def runprefixer(): # get the selected assets selected_assets = editor_util.get_selected_assets() num_assets = len(selected_assets) prefixed = 0 for asset in selected_assets: # get the class instance and the clear text name asset_name = system_lib.get_object_name(asset) asset_class = asset.get_class() class_name = system_lib.get_class_display_name(asset_class) # get the prefix for the given class class_prefix = prefix_mapping.get(class_name, None) if class_prefix is None: unreal.log_warning("No mapping for asset {} of type {}".format(asset_name, class_name)) continue if not asset_name.startswith(class_prefix): # rename the asset and add prefix new_name = class_prefix + asset_name editor_util.rename_asset(asset, new_name) prefixed += 1 unreal.log("Prefixed {} of type {} with {}".format(asset_name, class_name, class_prefix)) else: unreal.log("Asset {} of type {} is already prefixed with {}".format(asset_name, class_name, class_prefix)) unreal.log("Prefixed {} of {} assets".format(prefixed, num_assets))
import unreal # type: ignore import os import datetime import json import tkinter as tk from tkinter import filedialog image_ext = ".jpeg" floor_bp, room_bp, pano_point_bp = [ unreal.load_asset("/project/" + blueprint_name).generated_class() for blueprint_name in ["BP_Floor", "BP_Room", "BP_PanoPoint"] ] def getActorsOfClass(bp, all_actors): return enumerate(sorted([actor for actor in all_actors if actor.get_class() == bp], key=lambda a: a.get_actor_label())) def getActorEditorProperty(a, prop: str): try: return a.get_editor_property(prop) except Exception: return None def print_dict(d, tabs=1): for k, v in d.items(): print("\t" * tabs, k, " : ", v) print("_" * 20) def getThreeCoords(pano, height, con): v = con.get_actor_location() - pano.get_actor_location() - unreal.Vector(0, 0, height) return { "x": -v.x, "y": v.z, "z": -v.y, } def collect_level_data(folder_path, floorData = {}, roomData = {}, panoPointData = {}): # Initialize Tkinter root print(f"Selected folder: {folder_path}") # Remove exit() to allow script to continue # exit() # Setup floor_id_inc = 0 room_id_inc = 0 pano_id_inc = 0 all_actors = unreal.EditorLevelLibrary.get_all_level_actors() # Collect floor data for i, floor in getActorsOfClass(floor_bp, all_actors): fl_data = {} fl_data["floor_id"] = i + floor_id_inc fl_data["floor_name"] = getActorEditorProperty(floor, 'FloorName') fl_data["label"] = "" floorData[floor] = fl_data # Collect room data for i, room in getActorsOfClass(room_bp, all_actors): r_data = {} r_data["Room_ID"] = i + room_id_inc r_data["Room_Name"] = getActorEditorProperty(room, 'RoomName') r_data["Floor"] = getActorEditorProperty(room, "Floor") r_data["Location"] = room.get_actor_location(), r_data["Main_Panorama"] = getActorEditorProperty(room, "MainPanorama") roomData[room] = r_data # Collect pano point data for i, pano in getActorsOfClass(pano_point_bp, all_actors): p_data = {} p_data["PanoPoint_ID"] = i + pano_id_inc p_data["PanoIdentifier"] = getActorEditorProperty(pano, "PanoIdentifier") p_data["Room"] = getActorEditorProperty(pano, "Room") p_data["Height"] = getActorEditorProperty(pano, "Height") p_data["defaultRotation"] = getActorEditorProperty(pano, "defaultRotation") p_data["2WayConnections"] = getActorEditorProperty(pano, "2WayConnections") p_data["1WayConnections"] = getActorEditorProperty(pano, "1WayConnections") panoPointData[pano] = p_data return floorData, roomData, panoPointData def write_pano_data(data_folder_path, floorData, panoPointData, roomData, processed_render_dir): for floor in floorData: floorData[floor]["floor_map"] = os.path.join(os.path.dirname(data_folder_path), "/project/", f"{floor['floor_id']}.jpeg") floor_json = list(floorData.values()) room_json = [] for room, data in roomData.items(): room_json.append( { "room_id": data["Room_ID"], "room_name": data["Room_Name"], "main_panorama_id": panoPointData[data["Main_Panorama"]]["PanoPoint_ID"] if data["Main_Panorama"] else -1, "position": { "x": data["Location"][0].x, "y": data["Location"][0].y, }, "floor_id": floorData[data["Floor"]]["floor_id"] if data["Floor"] else -1, } ) pano_json = [] marker_json = [] for pano, data in panoPointData.items(): pano_json.append( { "panorma_id": data["PanoPoint_ID"], "default_rotation": data["defaultRotation"], "image_data": {tod: {fur: { f"{im_d}{im_ax}": f"{processed_render_dir}/{roomData[data['Room']]['Room_Name']}_{data['PanoIdentifier']}_{'d'}_{'f' if (fur == 'furnished') else 'u'}/{im_d}{im_ax}{image_ext}" for im_d in "pn" for im_ax in "xyz"} for fur in ["furnished", "unfurnished"]} for tod in ["day", "night"] }, "room_id": roomData[data["Room"]]["Room_ID"] if data["Room"] else -1, } ) marker_count = 0 for con in list(data["2WayConnections"]) + list(data["1WayConnections"]): try: marker_json.append({ "marker_id": marker_count, "panorma_id": data["PanoPoint_ID"], "position": getThreeCoords(pano, data["Height"], con), "target_panorama_id": panoPointData[con]["PanoPoint_ID"], }) marker_count += 1 except Exception as e: print(f"Error processing connection for pano {data['PanoIdentifier']} to {con}: {e}") for file, dict in (("floor_data.json", floor_json), ("room_data.json", room_json), ("pano_data.json", pano_json), ("marker_data.json", marker_json)): outpath = os.path.join(data_folder_path, file) with open(outpath, "w") as f: json.dump(dict, f, indent=4) print(f"Data exported to {outpath}") if __name__ == "__main__": root = tk.Tk() root.withdraw() # Hide the root window fp = filedialog.askdirectory(title="Select the folder containing panorama data") collect_level_data(fp)
# Copyright (c) <2021> Side Effects Software Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. The name of Side Effects Software may not be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES # OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN # NO EVENT SHALL SIDE EFFECTS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Example script that uses unreal.ActorIterator to iterate over all HoudiniAssetActors in the editor world, creates API wrappers for them, and logs all of their parameter tuples. """ import unreal def run(): # Get the API instance api = unreal.HoudiniPublicAPIBlueprintLib.get_api() # Get the editor world editor_subsystem = None world = None try: # In UE5 unreal.EditorLevelLibrary.get_editor_world is deprecated and # unreal.UnrealEditorSubsystem.get_editor_world is the replacement, # but unreal.UnrealEditorSubsystem does not exist in UE4 editor_subsystem = unreal.UnrealEditorSubsystem() except AttributeError: world = unreal.EditorLevelLibrary.get_editor_world() else: world = editor_subsystem.get_editor_world() # Iterate over all Houdini Asset Actors in the editor world for houdini_actor in unreal.ActorIterator(world, unreal.HoudiniAssetActor): if not houdini_actor: continue # Print the name and label of the actor actor_name = houdini_actor.get_name() actor_label = houdini_actor.get_actor_label() print(f'HDA Actor (Name, Label): {actor_name}, {actor_label}') # Wrap the Houdini asset actor with the API wrapper = unreal.HoudiniPublicAPIAssetWrapper.create_wrapper(world, houdini_actor) if not wrapper: continue # Get all parameter tuples of the HDA parameter_tuples = wrapper.get_parameter_tuples() if parameter_tuples is None: # The operation failed, log the error message error_message = wrapper.get_last_error_message() if error_message is not None: print(error_message) continue print(f'# Parameter Tuples: {len(parameter_tuples)}') for name, data in parameter_tuples.items(): print(f'\tParameter Tuple Name: {name}') type_name = None values = None if data.bool_values: type_name = 'Bool' values = '; '.join(('1' if v else '0' for v in data.bool_values)) elif data.float_values: type_name = 'Float' values = '; '.join((f'{v:.4f}' for v in data.float_values)) elif data.int32_values: type_name = 'Int32' values = '; '.join((f'{v:d}' for v in data.int32_values)) elif data.string_values: type_name = 'String' values = '; '.join(data.string_values) if not type_name: print('\t\tEmpty') else: print(f'\t\t{type_name} Values: {values}') if __name__ == '__main__': run()
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. import os import re import sys import json import unreal from enum import IntEnum from typing import Any, Optional from collections import OrderedDict from dataclasses import dataclass, asdict from pathlib import Path import glob from openjd.model import parse_model from openjd.model.v2023_09 import JobTemplate, ExtensionName from deadline.client.job_bundle.submission import AssetReferences from deadline.client.job_bundle import deadline_yaml_dump, create_job_history_bundle_dir from deadline.unreal_cmd_utils import merge_cmd_args_with_priority from deadline.unreal_submitter import common, exceptions, settings from deadline.unreal_submitter.unreal_dependency_collector import ( DependencyCollector, DependencyFilters, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_entity import ( Template, UnrealOpenJobEntity, OpenJobParameterNames, PARAMETER_DEFINITION_MAPPING, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_step import ( UnrealOpenJobStep, RenderUnrealOpenJobStep, UnrealOpenJobStepParameterDefinition, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_environment import ( UnrealOpenJobEnvironment, UgsUnrealOpenJobEnvironment, P4UnrealOpenJobEnvironment, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_shared_settings import ( JobSharedSettings, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_parameters_consistency import ( ParametersConsistencyChecker, ) from deadline.unreal_submitter.unreal_open_job.unreal_open_job_step_host_requirements import ( HostRequirementsHelper, ) from deadline.unreal_logger import get_logger from deadline.unreal_perforce_utils import perforce, unreal_source_control logger = get_logger() class TransferProjectFilesStrategy(IntEnum): """ Enumeration of ways of transferring project files :cvar S3: Default, with S3 file manager :cvar P4: with Perforce API :cvar UGS: with UnrealGameSync API """ S3 = 0 P4 = 1 UGS = 2 @dataclass class UnrealOpenJobParameterDefinition: """ Dataclass for storing and managing OpenJob Parameter Definitions :cvar name: Name of the parameter :cvar type: OpenJD Type of the parameter (INT, FLOAT, STRING, PATH) :cvar value: Parameter value """ name: str type: str value: Any = None @classmethod def from_unreal_param_definition(cls, u_param: unreal.ParameterDefinition): """ Create UnrealOpenJobParameterDefinition instance from unreal.ParameterDefinition object. :return: UnrealOpenJobParameterDefinition instance :rtype: UnrealOpenJobParameterDefinition """ build_kwargs = dict(name=u_param.name, type=u_param.type.name) if u_param.value: python_class = PARAMETER_DEFINITION_MAPPING[u_param.type.name].python_class build_kwargs["value"] = python_class(u_param.value) return cls(**build_kwargs) @classmethod def from_dict(cls, param_dict: dict): """ Create UnrealOpenJobParameterDefinition instance python dict. If source dict has "default" key, use its value :return: UnrealOpenJobParameterDefinition instance :rtype: UnrealOpenJobParameterDefinition """ build_kwargs = dict(name=param_dict["name"], type=param_dict["type"]) if "default" in param_dict: build_kwargs["value"] = param_dict["default"] return cls(**build_kwargs) def to_dict(self): """ Return UnrealOpenJobParameterDefinition as dictionary :return: UnrealOpenJobParameterDefinition as python dictionary :rtype: dict[str, Any] """ return asdict(self) # Base Open Job implementation class UnrealOpenJob(UnrealOpenJobEntity): """ Open Job for Unreal Engine """ def __init__( self, file_path: Optional[str] = None, name: Optional[str] = None, steps: Optional[list[UnrealOpenJobStep]] = None, environments: Optional[list[UnrealOpenJobEnvironment]] = None, extra_parameters: Optional[list[UnrealOpenJobParameterDefinition]] = None, job_shared_settings: Optional[JobSharedSettings] = None, asset_references: Optional[AssetReferences] = None, ): """ :param file_path: Path to the open job template file :type file_path: str :param name: Name of the job :type name: str :param steps: List of steps to be executed by deadline cloud :type steps: list[UnrealOpenJobStep] :param environments: List of environments to be used by deadline cloud :type environments: list[UnrealOpenJobEnvironment] :param extra_parameters: List of additional parameters to be added to the job :type extra_parameters: list[UnrealOpenJobParameterDefinition] :param job_shared_settings: JobSharedSettings instance :type job_shared_settings: JobSharedSettings :param asset_references: AssetReferences object :type asset_references: AssetReferences """ super().__init__(JobTemplate, file_path, name) self._extra_parameters: list[UnrealOpenJobParameterDefinition] = extra_parameters or [] self._create_missing_extra_parameters_from_template() self._steps: list[UnrealOpenJobStep] = steps or [] self._environments: list[UnrealOpenJobEnvironment] = environments or [] self._job_shared_settings = job_shared_settings or JobSharedSettings() self._asset_references = asset_references or AssetReferences() self._transfer_files_strategy = TransferProjectFilesStrategy.S3 @property def job_shared_settings(self) -> JobSharedSettings: return self._job_shared_settings @job_shared_settings.setter def job_shared_settings(self, value: JobSharedSettings): self._job_shared_settings = value @classmethod def from_data_asset(cls, data_asset: unreal.DeadlineCloudJob) -> "UnrealOpenJob": """ Create the instance of UnrealOpenJob from unreal.DeadlineCloudJob. Call same method on data_asset's steps, environments. :param data_asset: unreal.DeadlineCloudJob instance :return: UnrealOpenJob instance :rtype: UnrealOpenJob """ steps = [UnrealOpenJobStep.from_data_asset(step) for step in data_asset.steps] host_requirements = HostRequirementsHelper.u_host_requirements_to_openjd_host_requirements( data_asset.job_preset_struct.host_requirements ) for step in steps: if host_requirements is not None: step.host_requirements = host_requirements shared_settings = data_asset.job_preset_struct.job_shared_settings result_job = cls( file_path=data_asset.path_to_template.file_path, name=None if shared_settings.name in ["", "Untitled"] else shared_settings.name, steps=steps, environments=[ UnrealOpenJobEnvironment.from_data_asset(env) for env in data_asset.environments ], extra_parameters=[ UnrealOpenJobParameterDefinition.from_unreal_param_definition(param) for param in data_asset.get_job_parameters() ], job_shared_settings=JobSharedSettings.from_u_deadline_cloud_job_shared_settings( shared_settings ), ) for step in result_job._steps: step.open_job = result_job return result_job @staticmethod def serialize_template(template: Template) -> dict[str, Any]: """ Serialize given template and return ordered dictionary (spec version, name, parameters, envs, steps). :param template: Template (JobTemplate, StepTemplate, Environment) :type template: Union[JobTemplate, StepTemplate, Environment] :return: Ordered python dictionary :rtype: dict[str, Any] """ template_json = json.loads(template.json(exclude_none=True)) ordered_keys = [ "specificationVersion", "extensions", "name", "parameterDefinitions", "jobEnvironments", "steps", ] ordered_data = dict( OrderedDict((key, template_json[key]) for key in ordered_keys if key in template_json) ) return ordered_data @staticmethod def update_job_parameter_values( job_parameter_values: list[dict[str, Any]], job_parameter_name: str, job_parameter_value: Any, ) -> list[dict[str, Any]]: """ Try to find parameter in given list by the provided name and update its value wih provided value. :param job_parameter_values: List of parameter values dictionaries (name and value) :type job_parameter_values: list[dict[str, Any]] :param job_parameter_name: Name of the parameter to update :type job_parameter_name: str :param job_parameter_value: Value of the parameter to set :type job_parameter_value: Any :return: Given list of parameter values with possibly updated parameter :rtype: list[dict[str, Any]] """ param = next((p for p in job_parameter_values if p["name"] == job_parameter_name), None) if param: param["value"] = job_parameter_value return job_parameter_values def _create_missing_extra_parameters_from_template(self): """ Update parameters with YAML template data. Mostly needed for custom job submission process. If no template file found, skip updating and log warning. This is not an error and should not break the building process. """ try: extra_param_names = [p.name for p in self._extra_parameters] for p in self.get_template_object()["parameterDefinitions"]: if p["name"] not in extra_param_names: self._extra_parameters.append(UnrealOpenJobParameterDefinition.from_dict(p)) except FileNotFoundError: logger.warning("No template file found to read parameters from.") def _find_extra_parameter( self, parameter_name: str, parameter_type: str ) -> Optional[UnrealOpenJobParameterDefinition]: """ Find extra parameter by given name and type :param parameter_name: Parameter name :param parameter_type: Parameter type (INT, FLOAT, STRING, PATH) :return: Parameter if found, None otherwise :rtype: Optional[UnrealOpenJobParameterDefinition] """ return next( ( p for p in self._extra_parameters if p.name == parameter_name and p.type == parameter_type ), None, ) def _build_parameter_values(self) -> list: """ Build and return list of parameter values for the OpenJob. Use YAML parameter names and extra parameter values/YAML defaults if exists. :return: Parameter values list of dictionaries :rtype: list """ job_template_object = self.get_template_object() parameter_values = [] for yaml_p in job_template_object["parameterDefinitions"]: extra_p = self._find_extra_parameter(yaml_p["name"], yaml_p["type"]) value = extra_p.value if extra_p else yaml_p.get("default") parameter_values.append(dict(name=yaml_p["name"], value=value)) if self._job_shared_settings: parameter_values += self._job_shared_settings.serialize() return parameter_values def _check_parameters_consistency(self): """ Check Job parameters consistency :return: Result of parameters consistency check :rtype: ParametersConsistencyCheckResult """ result = ParametersConsistencyChecker.check_job_parameters_consistency( job_template_path=self.file_path, job_parameters=[p.to_dict() for p in self._extra_parameters], ) result.reason = f"OpenJob {self.name}: " + result.reason return result def _build_template(self) -> JobTemplate: """ Build JobTemplate OpenJD model. Build process: 1. Fill specification version for the Job 2. Fill Job parameter definition list 3. Build given Steps 4. Build given Environments :return: JobTemplate instance :rtype: JobTemplate """ template_dict = { "specificationVersion": settings.JOB_TEMPLATE_VERSION, "name": self.name, "parameterDefinitions": [ PARAMETER_DEFINITION_MAPPING[param["type"]].job_parameter_openjd_class(**param) for param in self.get_template_object()["parameterDefinitions"] ], "steps": [s.build_template() for s in self._steps], } extension_list = self.get_template_object().get("extensions") if extension_list: template_dict["extensions"] = extension_list if self._environments: template_dict["jobEnvironments"] = [e.build_template() for e in self._environments] # Use all available extension names from the ExtensionName enum supported_extensions = [extension.value for extension in ExtensionName] job_template = parse_model( model=self.template_class, obj=template_dict, supported_extensions=supported_extensions ) return job_template def get_asset_references(self) -> AssetReferences: """ Return AssetReferences of itself that union given Environments and Steps' AssetReferences :return: AssetReferences from this Job and its Environments and Steps :rtype: AssetReferences """ asset_references = super().get_asset_references() if self._asset_references: asset_references = asset_references.union(self._asset_references) for step in self._steps: asset_references = asset_references.union(step.get_asset_references()) for environment in self._environments: asset_references = asset_references.union(environment.get_asset_references()) return asset_references @staticmethod def get_plugins(path: str): unreal_plugins: list[dict] = [] pattern = os.path.join(path, "**", "*.uplugin") for uplugin in glob.iglob(pattern, recursive=True): real_path = Path(uplugin).resolve(strict=True) try: with real_path.open(encoding="utf-8") as f: plugin_data = json.load(f) unreal_plugins.append( { "name": real_path.stem, "enabled_by_default": plugin_data.get("EnabledByDefault", True), "folder": Path(uplugin).parent.name, } ) except (OSError, json.JSONDecodeError): continue return unreal_plugins @staticmethod def parse_uproject(path: str) -> dict[str, bool]: with open(path, encoding="utf‑8") as f: data = json.load(f) return {e["Name"]: e.get("Enabled", True) for e in data.get("Plugins", [])} @staticmethod def get_plugins_references() -> AssetReferences: project_path = unreal.Paths.get_project_file_path() project_plugins_info = UnrealOpenJob.parse_uproject(project_path) result = AssetReferences() plugins_dir = unreal.Paths.project_plugins_dir() plugins_dir_full = unreal.Paths.convert_relative_path_to_full(plugins_dir) plugins = UnrealOpenJob.get_plugins(plugins_dir_full) for plugin in plugins: if plugin["name"] == "UnrealDeadlineCloudService": continue is_enable = project_plugins_info.get(plugin["name"], plugin["enabled_by_default"]) if is_enable: result.input_directories.add(os.path.join(plugins_dir_full, plugin["folder"])) return result def create_job_bundle(self): """ Create Job bundle directory with next files inside: 1. template.yaml - Full OpenJD Job template with steps, envs, parameters, etc. 2. parameter_values.yaml - List of Job parameter values + Shared settings values 3. asset_references.yaml - Input directories/files, outputs to sync with S3 on submit :return: Job bundle directory path :rtype: str """ job_template = self.build_template() job_bundle_path = create_job_history_bundle_dir("Unreal", self.name) logger.info(f"Job bundle path: {job_bundle_path}") with open(job_bundle_path + "/template.yaml", "w", encoding="utf8") as f: job_template_dict = UnrealOpenJob.serialize_template(job_template) deadline_yaml_dump(job_template_dict, f, indent=1) with open(job_bundle_path + "/parameter_values.yaml", "w", encoding="utf8") as f: param_values = self._build_parameter_values() deadline_yaml_dump(dict(parameterValues=param_values), f, indent=1) with open(job_bundle_path + "/asset_references.yaml", "w", encoding="utf8") as f: asset_references = self.get_asset_references() deadline_yaml_dump(asset_references.to_dict(), f, indent=1) return job_bundle_path # Render Open Job class RenderUnrealOpenJob(UnrealOpenJob): """ Unreal Open Job for rendering Unreal Engine projects :cvar job_environment_map: Map for converting C++ environment classes to Python classes :cvar job_step_map: Map for converting C++ step classes to Python classes """ default_template_path = settings.RENDER_JOB_TEMPLATE_DEFAULT_PATH job_environment_map = { unreal.DeadlineCloudUgsEnvironment: UgsUnrealOpenJobEnvironment, unreal.DeadlineCloudPerforceEnvironment: P4UnrealOpenJobEnvironment, } job_step_map = {unreal.DeadlineCloudRenderStep: RenderUnrealOpenJobStep} def __init__( self, file_path: Optional[str] = None, name: Optional[str] = None, steps: Optional[list[UnrealOpenJobStep]] = None, environments: Optional[list[UnrealOpenJobEnvironment]] = None, extra_parameters: Optional[list[UnrealOpenJobParameterDefinition]] = None, job_shared_settings: Optional[JobSharedSettings] = None, asset_references: Optional[AssetReferences] = None, mrq_job: Optional[unreal.MoviePipelineExecutorJob] = None, ): """ Construct RenderUnrealOpenJob instance. :param file_path: Path to the open job template file :type file_path: str :param name: Name of the job :type name: str :param steps: List of steps to be executed by deadline cloud :type steps: list[UnrealOpenJobStep] :param environments: List of environments to be used by deadline cloud :type environments: list[UnrealOpenJobEnvironment] :param extra_parameters: List of additional parameters to be added to the job :type extra_parameters: list[UnrealOpenJobParameterDefinition] :param job_shared_settings: JobSharedSettings instance :type job_shared_settings: JobSharedSettings :param asset_references: AssetReferences object :type asset_references: AssetReferences :param mrq_job: unreal.MoviePipelineExecutorJob instance to take render data from :type mrq_job: unreal.MoviePipelineExecutorJob """ super().__init__( file_path, name, steps, environments, extra_parameters, job_shared_settings, asset_references, ) self._mrq_job = None if mrq_job: self.mrq_job = mrq_job self._dependency_collector = DependencyCollector() if self._name is None and isinstance(self.mrq_job, unreal.MoviePipelineExecutorJob): self._name = self.mrq_job.job_name ugs_envs = [e for e in self._environments if isinstance(e, UgsUnrealOpenJobEnvironment)] p4_envs = [e for e in self._environments if isinstance(e, P4UnrealOpenJobEnvironment)] if ugs_envs and p4_envs: raise exceptions.FailedToDetectFilesTransferStrategy( "Failed to detect how to transfer project files to render because " f"there are multiple options selected: " f"{[e.name for e in ugs_envs]} and {[e.name for e in p4_envs]}. " f"Use only Perforce OR only UnrealGameSync environments inside single OpenJob" ) if ugs_envs: self._transfer_files_strategy = TransferProjectFilesStrategy.UGS elif p4_envs: self._transfer_files_strategy = TransferProjectFilesStrategy.P4 @property def mrq_job(self): return self._mrq_job @mrq_job.setter def mrq_job(self, value): """ Set mrq_job as given value. Updates next objects: 1. Job extra parameters from mrq job parameter definition overrides 2. Step's parameters and environments from mrq job step overrides for each step 3. Environment's variables from mrq job environment overrides for each environment 4. Job name if not set by next priority: I. Job preset override - (highest priority) II. Data asset job preset struct III. YAML template IV. MRQ Job name (shot name) - lowest priority :param value: unreal.MoviePipelineExecutorJob instance :type value: unreal.MoviePipelineExecutorJob """ self._mrq_job = value self._update_steps_settings_from_mrq_job(self._mrq_job) self._update_environments_settings_from_mrq_job(self._mrq_job) if ( self._mrq_job is not None and self._mrq_job.job_template_overrides is not None and self._mrq_job.job_template_overrides.parameters ): self._extra_parameters = [ UnrealOpenJobParameterDefinition.from_unreal_param_definition(p) for p in self._mrq_job.job_template_overrides.parameters ] if ( self._mrq_job is not None and self._mrq_job.preset_overrides is not None and self._mrq_job.preset_overrides.job_shared_settings is not None ): self.job_shared_settings = JobSharedSettings.from_u_deadline_cloud_job_shared_settings( self._mrq_job.preset_overrides.job_shared_settings ) # Job name set order: # 0. Job preset override (high priority) # 1. Get from data asset job preset struct # 2. Get from YAML template # 4. Get from mrq job name (shot name) if ( self._mrq_job is not None and self._mrq_job.preset_overrides is not None and self._mrq_job.preset_overrides.job_shared_settings is not None ): preset_override_name = self._mrq_job.preset_overrides.job_shared_settings.name if preset_override_name not in ["", "Untitled"]: self._name = preset_override_name if self._name is None: self._name = self._mrq_job.job_name @classmethod def from_data_asset(cls, data_asset: unreal.DeadlineCloudRenderJob) -> "RenderUnrealOpenJob": """ Create the instance of RenderUnrealOpenJob from unreal.DeadlineCloudRenderJob. Call same method on data_asset's steps, environments. Create appropriate Steps and Environments listed in job_step_map, job_environment_map :param data_asset: unreal.DeadlineCloudRenderJob instance :return: RenderUnrealOpenJob instance :rtype: RenderUnrealOpenJob """ render_steps_count = RenderUnrealOpenJob.render_steps_count(data_asset) if render_steps_count != 1: raise exceptions.RenderStepCountConstraintError( f"RenderJob data asset should have exactly 1 Render Step. " f"Currently it has {render_steps_count} Render Steps" ) host_requirements = HostRequirementsHelper.u_host_requirements_to_openjd_host_requirements( data_asset.job_preset_struct.host_requirements ) steps = [] for source_step in data_asset.steps: job_step_cls = cls.job_step_map.get(type(source_step), UnrealOpenJobStep) job_step = job_step_cls.from_data_asset(source_step) if host_requirements is not None: job_step.host_requirements = host_requirements steps.append(job_step) environments = [] for source_environment in data_asset.environments: job_env_cls = cls.job_environment_map.get( type(source_environment), UnrealOpenJobEnvironment ) job_env = job_env_cls.from_data_asset(source_environment) environments.append(job_env) shared_settings = data_asset.job_preset_struct.job_shared_settings result_job = cls( file_path=data_asset.path_to_template.file_path, name=None if shared_settings.name in ["", "Untitled"] else shared_settings.name, steps=steps, environments=environments, extra_parameters=[ UnrealOpenJobParameterDefinition.from_unreal_param_definition(param) for param in data_asset.get_job_parameters() ], job_shared_settings=JobSharedSettings.from_u_deadline_cloud_job_shared_settings( shared_settings ), ) for step in result_job._steps: step.open_job = result_job return result_job @classmethod def from_mrq_job( cls, mrq_job: unreal.MoviePipelineDeadlineCloudExecutorJob ) -> "RenderUnrealOpenJob": """ Create the instance of RenderUnrealOpenJob from unreal.MoviePipelineDeadlineCloudExecutorJob. Use it job_preset to create from data asset and set mrq_job as given mrq_job. :param mrq_job: unreal.MoviePipelineDeadlineCloudExecutorJob instance :return: RenderUnrealOpenJob instance :rtype: RenderUnrealOpenJob """ render_unreal_open_job = cls.from_data_asset(mrq_job.job_preset) render_unreal_open_job.mrq_job = mrq_job return render_unreal_open_job @staticmethod def render_steps_count(data_asset: unreal.DeadlineCloudRenderJob) -> int: """ Count unreal.DeadlineCloudRenderStep in the given Render Job data asset :param data_asset: unreal.DeadlineCloudRenderJob instance :return: unreal.DeadlineCloudRenderStep count :rtype: int """ return sum(isinstance(s, unreal.DeadlineCloudRenderStep) for s in data_asset.steps) @staticmethod def get_required_project_directories() -> list[str]: """ Returns a list of required project directories such as Config and Binaries :return: list of required project directories :rtype: list """ required_project_directories = [] for sub_dir in ["Config", "Binaries"]: directory = common.os_abs_from_relative(sub_dir) if os.path.exists(directory): required_project_directories.append(directory) return required_project_directories def _update_steps_settings_from_mrq_job( self, mrq_job: unreal.MoviePipelineDeadlineCloudExecutorJob ): """ Iterate through the Job's Steps and update settings with overrides of given MRQ Job for each Step. Settings to update: 1. Host requirements 2. MRQ Job (If step is RenderUnrealOpenJobStep) 3. Step depends on list 4. Environment variables for each Environment of the Step 5. Step parameters :param mrq_job: unreal.MoviePipelineDeadlineCloudExecutorJob instance :type mrq_job: unreal.MoviePipelineDeadlineCloudExecutorJob """ host_requirements = HostRequirementsHelper.u_host_requirements_to_openjd_host_requirements( mrq_job.preset_overrides.host_requirements ) for step in self._steps: # update host requirements if host_requirements is not None: step.host_requirements = host_requirements # set mrq job to render step if isinstance(step, RenderUnrealOpenJobStep): step.mrq_job = mrq_job # find appropriate step override step_override = next( ( override for override in mrq_job.job_template_overrides.steps_overrides if override.name == step.name ), None, ) if not step_override: continue # update depends on step.step_dependencies = list(step_override.depends_on) # update step environments for env in step.environments: step_environment_override = next( ( env_override for env_override in step_override.environments_overrides if env_override.name == env.name ), None, ) if step_environment_override: env.variables = step_environment_override.variables.variables # update step parameters for override_param in step_override.task_parameter_definitions.parameters: step.update_extra_parameter( UnrealOpenJobStepParameterDefinition.from_unreal_param_definition( override_param ) ) def _update_environments_settings_from_mrq_job( self, mrq_job: unreal.MoviePipelineDeadlineCloudExecutorJob ): """ Iterate through the Job's Environments and update variables map with overrides of given MRQ Job for each Environment. :param mrq_job: unreal.MoviePipelineDeadlineCloudExecutorJob instance :type mrq_job: unreal.MoviePipelineDeadlineCloudExecutorJob """ for env in self._environments: override_environment = next( ( env_override for env_override in mrq_job.job_template_overrides.environments_overrides if env_override.name == env.name ), None, ) if override_environment: env.variables = override_environment.variables.variables @staticmethod def _get_project_path_relative_to_workspace_root(workspace_root: str) -> str: workspace_root = workspace_root.replace("\\", "/") unreal_project_path = common.get_project_file_path().replace("\\", "/") if not unreal_project_path.lower().startswith(workspace_root.lower()): raise exceptions.ProjectIsNotUnderWorkspaceError( f"Project {unreal_project_path} is not under the workspace root: {workspace_root}" ) pattern = re.compile(re.escape(workspace_root), re.IGNORECASE) unreal_project_relative_path = pattern.sub("", unreal_project_path, count=1).lstrip("/") if unreal_project_relative_path == unreal_project_path: raise RuntimeError( "Something went wrong during getting Unreal Project Path relative to " f"Perforce Workspace Root. Project path is {unreal_project_path}. " f"Workspace Root: {workspace_root}" ) return unreal_project_relative_path def _build_parameter_values_for_ugs(self, parameter_values: list[dict]) -> list[dict]: """ Build and return list of parameter values for the OpenJob in the Unreal Game Sync integration. Parameters to be updated: - Perforce Changelist Number - Perforce Stream Path - Unreal Project Name - Unreal Project Path relative to P4 workspace root - Unreal Executable Path relative to P4 workspace root .. note:: If expected parameter missed, it will be skipped :param parameter_values: list of parameter values to be updated :type parameter_values: list[dict] :return: list of updated parameter values :rtype: list[dict] """ conn_settings = unreal_source_control.get_connection_settings_from_ue_source_control() p4_conn = perforce.PerforceConnection( port=conn_settings["port"], user=conn_settings["user"], client=conn_settings["workspace"], ) parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.PERFORCE_STREAM_PATH, job_parameter_value=p4_conn.get_stream_path(), ) parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.PERFORCE_CHANGELIST_NUMBER, job_parameter_value=str(p4_conn.get_latest_changelist_number() or "latest"), ) parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_PROJECT_NAME, job_parameter_value=common.get_project_name(), ) client_root = p4_conn.get_client_root() if isinstance(client_root, str): unreal_project_relative_path = self._get_project_path_relative_to_workspace_root( workspace_root=client_root, ) parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_PROJECT_RELATIVE_PATH, job_parameter_value=unreal_project_relative_path, ) unreal_executable_path = sys.executable.replace("\\", "/") unreal_executable_relative_path = unreal_executable_path.replace(client_root, "") unreal_executable_relative_path = unreal_executable_relative_path.lstrip("/") parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_EXECUTABLE_RELATIVE_PATH, job_parameter_value=unreal_executable_relative_path, ) return parameter_values def _build_parameter_values_for_p4(self, parameter_values: list[dict]) -> list[dict]: """ Build and return list of parameter values for the OpenJob in the Perforce integration. Parameters to be updated: - Perforce Changelist Number - Unreal Project Name - Unreal Project Path relative to P4 workspace root - Perforce Workspace Specification template (see :meth:`deadline.unreal_perforce_utils.perforce.get_perforce_workspace_specification_template()`) - Job Dependencies Descriptor (see :meth:`deadline.unreal_submitter.unreal_open_job.unreal_open_job.RenderUnrealOpenJob._get_mrq_job_dependency_depot_paths()`) .. note:: If expected parameter missed, it will be skipped :param parameter_values: list of parameter values to be updated :type parameter_values: list[dict] :return: list of updated parameter values :rtype: list[dict] """ conn_settings = unreal_source_control.get_connection_settings_from_ue_source_control() p4 = perforce.PerforceConnection( port=conn_settings["port"], user=conn_settings["user"], client=conn_settings["workspace"], ) latest_changelist_number = str(p4.get_latest_changelist_number() or "latest") parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.PERFORCE_CHANGELIST_NUMBER, job_parameter_value=latest_changelist_number, ) parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_PROJECT_NAME, job_parameter_value=common.get_project_name(), ) client_root = p4.get_client_root() if isinstance(client_root, str): unreal_project_relative_path = self._get_project_path_relative_to_workspace_root( workspace_root=client_root, ) parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_PROJECT_RELATIVE_PATH, job_parameter_value=unreal_project_relative_path, ) workspace_spec_template = common.create_deadline_cloud_temp_file( file_prefix=OpenJobParameterNames.PERFORCE_WORKSPACE_SPECIFICATION_TEMPLATE, file_data=perforce.get_perforce_workspace_specification_template( port=conn_settings["port"], user=conn_settings["user"], client=conn_settings["workspace"], ), file_ext=".json", ) parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.PERFORCE_WORKSPACE_SPECIFICATION_TEMPLATE, job_parameter_value=workspace_spec_template, ) self._asset_references.input_filenames.add(workspace_spec_template) # We need to collect job dependencies on the Artist node because some of them of # type "soft" and references to them in other downloaded assets will be None on the # Render node. So we can't sync them and their dependencies until we don't know their paths job_dependencies_descriptor = common.create_deadline_cloud_temp_file( file_prefix=OpenJobParameterNames.UNREAL_MRQ_JOB_DEPENDENCIES_DESCRIPTOR, file_data={ "job_dependencies": self._get_mrq_job_dependency_depot_paths( latest_changelist_number, ) }, file_ext=".json", ) parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_MRQ_JOB_DEPENDENCIES_DESCRIPTOR, job_parameter_value=job_dependencies_descriptor, ) self._asset_references.input_filenames.add(job_dependencies_descriptor) return parameter_values def _build_parameter_values(self) -> list: """ Build and return list of parameter values for the OpenJob. Use YAML parameter names and extra parameter values/ YAML defaults if exists. Fill parameters that were not filled by user on in YAML. Typically, this parameters should not be filled by user (such as Project Path, Extra Cmd Args File, UGS settings, etc.) Parameters to be updated: - Unreal Extra Cmd Arguments (set to "") - Unreal Extra Cmd Arguments File (write all the arguments to file to avoid OpenJD limitation of 1024 chars) - Unreal Project Path (local path to the project) - Parameters for UGS if UGS is used (see :meth:`deadline.unreal_submitter.unreal_open_job.unreal_open_job.RenderUnrealOpenJob._build_parameter_values_for_ugs()`) - Parameters for P4 if P4 is used (see :meth:`deadline.unreal_submitter.unreal_open_job.unreal_open_job.RenderUnrealOpenJob._build_parameter_values_for_p4()`) .. note:: If expected parameter missed, it will be skipped .. note:: Set ExtraCmdArgs parameter as empty string "" since Adaptor read args only from file. :return: list of parameter values :rtype: list[dict[str, Any]] """ parameter_values = super()._build_parameter_values() # skip params with filled values (in YAML or by User in UI) # if it is not ExtraCmdArgs since we want to update them with mrq job args unfilled_parameter_values = [ p for p in parameter_values if p["value"] is None or p["name"] == OpenJobParameterNames.UNREAL_EXTRA_CMD_ARGS or p["name"] == OpenJobParameterNames.UNREAL_EXTRA_CMD_ARGS_FILE ] filled_parameter_values = [ p for p in parameter_values if p not in unfilled_parameter_values ] # Unreal Engine can handle long CMD args strings and OpenJD has a limit of 1024 chars. # Therefore, we need to write them to file and set ExtraCmdArgs parameter as empty string. # Unreal Adaptor uses only ExtraCmdArgsFile parameter to read args from file. extra_cmd_args_file_value = None for p in parameter_values: if p["name"] == OpenJobParameterNames.UNREAL_EXTRA_CMD_ARGS_FILE: extra_cmd_args_file_value = p["value"] break # Read EXTRA_CMD_ARGS_FILE file value if file exists, and append its content to user_extra_cmd_args args_from_file = None if extra_cmd_args_file_value: args_from_file = self.get_user_extra_cmd_args_from_file(str(extra_cmd_args_file_value)) user_extra_cmd_args = self.get_user_extra_cmd_args() if args_from_file: user_extra_cmd_args = merge_cmd_args_with_priority(user_extra_cmd_args, args_from_file) executor_cmd_args = self.get_executor_cmd_args() merged_cmd_args = merge_cmd_args_with_priority(user_extra_cmd_args, executor_cmd_args) merged_cmd_args = self.clear_cmd_args(merged_cmd_args) unfilled_parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=unfilled_parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_EXTRA_CMD_ARGS, job_parameter_value="", ) # Write the .txt file using the original temp file logic extra_cmd_args_file = common.create_deadline_cloud_temp_file( file_prefix=OpenJobParameterNames.UNREAL_EXTRA_CMD_ARGS_FILE, file_data=merged_cmd_args, file_ext=".txt", ) unfilled_parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=unfilled_parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_EXTRA_CMD_ARGS_FILE, job_parameter_value=extra_cmd_args_file, ) self._asset_references.input_filenames.add(extra_cmd_args_file) unfilled_parameter_values = RenderUnrealOpenJob.update_job_parameter_values( job_parameter_values=unfilled_parameter_values, job_parameter_name=OpenJobParameterNames.UNREAL_PROJECT_PATH, job_parameter_value=common.get_project_file_path(), ) if self._transfer_files_strategy == TransferProjectFilesStrategy.UGS: unfilled_parameter_values = self._build_parameter_values_for_ugs( parameter_values=unfilled_parameter_values ) if self._transfer_files_strategy == TransferProjectFilesStrategy.P4: unfilled_parameter_values = self._build_parameter_values_for_p4( parameter_values=unfilled_parameter_values ) all_parameter_values = filled_parameter_values + unfilled_parameter_values return all_parameter_values def get_executor_cmd_args(self) -> str: """ Returns the cleaned list of command line arguments from the executor settings and MRQ job. """ cmd_args = common.get_in_process_executor_cmd_args() if self._mrq_job: cmd_args.extend(common.get_mrq_job_cmd_args(self._mrq_job)) return " ".join(a for a in cmd_args) def get_user_extra_cmd_args(self) -> str: """ Returns the cleaned list of user-specified extra command line arguments (UNREAL_EXTRA_CMD_ARGS), with any -execcmds arguments removed. """ extra_cmd_args_param = self._find_extra_parameter( parameter_name=OpenJobParameterNames.UNREAL_EXTRA_CMD_ARGS, parameter_type="STRING", ) if extra_cmd_args_param and extra_cmd_args_param.value: extra_cmd_args = str(extra_cmd_args_param.value) return extra_cmd_args return "" @staticmethod def clear_cmd_args(cmd_args: str) -> str: """ Cleans the command line arguments by removing any -execcmds arguments. This is useful to ensure that no unintended execution commands are passed. :param cmd_args: The command line arguments as a string. :return: Cleaned command line arguments. """ cleared_cmd_args = re.sub( pattern='(-execcmds="[^"]*")', repl="", string=cmd_args, flags=re.IGNORECASE ) cleared_cmd_args = re.sub( pattern="(-execcmds='[^']*')", repl="", string=cleared_cmd_args, flags=re.IGNORECASE, ) if cleared_cmd_args != cmd_args: logger.warning( "Appearance of custom '-execcmds' argument on the Render node can cause unpredictable " "issues. Argument '-execcmds' of Unreal Open Job's " "Extra Command Line arguments will be ignored." ) return cleared_cmd_args def get_user_extra_cmd_args_from_file(self, file_path: str) -> str: """ Reads the given EXTRA_CMD_ARGS_FILE and returns the string as-is (stripped). Returns an empty string if the file is missing or empty. Logs if file is empty or error reading. """ if not file_path or not os.path.isfile(file_path): logger.info(f"EXTRA_CMD_ARGS_FILE '{file_path}' does not exist or is not specified.") return "" try: with open(file_path, "r", encoding="utf8") as f: extra_data = f.read() if not extra_data.strip(): logger.info(f"EXTRA_CMD_ARGS_FILE '{file_path}' is empty.") return "" return extra_data.strip() except Exception as e: logger.error(f"Error reading EXTRA_CMD_ARGS_FILE '{file_path}': {e}") return "" def _collect_mrq_job_dependencies(self) -> list[str]: """ Collects the dependencies of the Level and LevelSequence that used in MRQ Job. Use :class:`deadline.unreal_submitter.unreal_dependency_collector.collector.DependencyCollector` for collecting :return: List of the dependencies :rtype: list[str] """ if not self._mrq_job: raise exceptions.MrqJobIsMissingError("MRQ Job must be provided") level_sequence_path = common.soft_obj_path_to_str(self._mrq_job.sequence) level_sequence_path = os.path.splitext(level_sequence_path)[0] level_path = common.soft_obj_path_to_str(self._mrq_job.map) level_path = os.path.splitext(level_path)[0] level_sequence_dependencies = self._dependency_collector.collect( level_sequence_path, filter_method=DependencyFilters.dependency_in_game_folder ) level_dependencies = self._dependency_collector.collect( level_path, filter_method=DependencyFilters.dependency_in_game_folder ) all_dependencies = ( level_sequence_dependencies + level_dependencies + [level_sequence_path, level_path] ) unique_dependencies = list(set(all_dependencies)) return unique_dependencies def _get_mrq_job_dependency_paths(self): """ Collects the dependencies of the Level and LevelSequence that used in MRQ Job and returns paths converted from UE relative (i.e. /Game/...) to OS absolute (D:/...) :return: List of the dependencies :rtype: list[str] """ os_dependencies = [] job_dependencies = self._collect_mrq_job_dependencies() for dependency in job_dependencies: os_dependency = common.os_path_from_unreal_path(dependency, with_ext=True) if os.path.exists(os_dependency): os_dependencies.append(os_dependency) return os_dependencies def _get_mrq_job_dependency_depot_paths( self, changelist_number: Optional[str] = None ) -> list[str]: """ Collects the dependencies if Level and LevelSequence of MRQ Job and returns paths converted from UE relative (i.e. /Game/...) to Perforce Depot (/project/...). Using depot file paths allow to sync in any locations other than User's ones. If `changelist_number` is provided, append it to the end of each path with "@" prefix, i.e. /project/.uasset@12345 :param changelist_number: Perforce changelist number :type changelist_number: Optional[str] :return: List of the dependency depot paths :rtype: list[str] """ local_dependencies = self._get_mrq_job_dependency_paths() conn_settings = unreal_source_control.get_connection_settings_from_ue_source_control() p4_conn = perforce.PerforceConnection( port=conn_settings["port"], user=conn_settings["user"], client=conn_settings["workspace"], ) depot_dependencies = p4_conn.get_depot_file_paths(local_dependencies) if changelist_number and changelist_number != "latest": depot_dependencies = [f"{path}@{changelist_number}" for path in depot_dependencies] return depot_dependencies def _get_mrq_job_attachments_input_files(self) -> list[str]: """ Get Job Attachments Input Files from MRQ Job preset overrides :return: List of MRQ Job Attachments Input Files :rtype: list[str] """ input_files = [] job_input_files = self.mrq_job.preset_overrides.job_attachments.input_files.files.paths for job_input_file in job_input_files: input_file = common.os_abs_from_relative(job_input_file.file_path) if os.path.exists(input_file): input_files.append(input_file) return input_files def _get_mrq_job_attachments_input_directories(self) -> list[str]: """ Get Job Attachments Input Directories from MRQ Job preset overrides :return: List of MRQ Job Attachments Input Directories :rtype: list[str] """ input_directories = [] job_input_directories = ( self.mrq_job.preset_overrides.job_attachments.input_directories.directories.paths ) for job_input_dir in job_input_directories: input_dir = common.os_abs_from_relative(job_input_dir.path) if os.path.exists(input_dir): input_directories.append(input_dir) return input_directories def _get_mrq_job_attachments_output_directories(self) -> list[str]: """ Get Job Attachments Output Directories from MRQ Job preset overrides :return: List of MRQ Job Attachments Output Directories :rtype: list[str] """ output_directories = [] job_output_directories = ( self.mrq_job.preset_overrides.job_attachments.output_directories.directories.paths ) for job_output_dir in job_output_directories: output_dir = common.os_abs_from_relative(job_output_dir.path) if os.path.exists(output_dir): output_directories.append(output_dir) return output_directories def _get_mrq_job_output_directory(self) -> str: """ Get the output directory path from MRQ Job Configuration, resolve all possible tokens (e.g. job_name, level, map, etc.) and return resulted path. :return: MRQ Job Configuration's resolved Output Directory :rtype: str """ output_setting = self.mrq_job.get_configuration().find_setting_by_class( unreal.MoviePipelineOutputSetting ) output_path = output_setting.output_directory.path common.validate_path_does_not_contain_non_valid_chars(output_path) path_context = common.get_path_context_from_mrq_job(self.mrq_job) output_path = output_path.format_map(path_context).rstrip("/") return output_path def get_asset_references(self) -> AssetReferences: """ Build asset references of the OpenJob with the given MRQ Job. Return :class:`deadline.client.job_bundle.submission.AssetReferences` instance :return: AssetReferences dataclass instance :rtype: :class:`deadline.client.job_bundle.submission.AssetReferences` """ asset_references = super().get_asset_references() if self._transfer_files_strategy == TransferProjectFilesStrategy.S3: # add dependencies to attachments asset_references.input_filenames.update(self._get_mrq_job_dependency_paths()) # required input directories asset_references.input_directories.update( RenderUnrealOpenJob.get_required_project_directories() ) plugins = UnrealOpenJob.get_plugins_references() if plugins: asset_references.input_directories.update(plugins.input_directories) # add attachments from preset overrides if self.mrq_job: # input files asset_references.input_filenames.update(self._get_mrq_job_attachments_input_files()) # input directories asset_references.input_directories.update( self._get_mrq_job_attachments_input_directories() ) # output directories asset_references.output_directories.update( self._get_mrq_job_attachments_output_directories() ) # Render output path asset_references.output_directories.add(self._get_mrq_job_output_directory()) return asset_references # UGS Jobs class UgsRenderUnrealOpenJob(RenderUnrealOpenJob): """Class for predefined UGS Render Job""" default_template_path = settings.UGS_RENDER_JOB_TEMPLATE_DEFAULT_PATH # Perforce (non UGS) Jobs class P4RenderUnrealOpenJob(RenderUnrealOpenJob): """Class for predefined Perforce Render Job""" default_template_path = settings.P4_RENDER_JOB_TEMPLATE_DEFAULT_PATH
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/project/-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unreal import math def verify_power_of_two(): # Get the libraries editor_util = unreal.EditorUtilityLibrary() system_lib = unreal.SystemLibrary() selected_assets = editor_util.get_selected_assets() asset_count = len(selected_assets) invalid_asset_count: int = 0 unreal.log("Selected {} assets".format(asset_count)) for asset in selected_assets: package_name = asset.get_package().get_name() classname = system_lib.get_class_display_name(asset.get_class()) if 'Texture2D' == classname: x_size = asset.blueprint_get_size_x() y_size = asset.blueprint_get_size_y() is_x_valid = math.log(x_size, 2).is_integer() is_y_valid = math.log(y_size, 2).is_integer() if not is_x_valid or not is_y_valid: unreal.log("{} is not a power of two ({}, {})".format(package_name, x_size, y_size)) invalid_asset_count += 1 if 1 == invalid_asset_count: unreal.log("1 texture identified that is not a power of two.") else: unreal.log("{} textures identified that are not a power of two.".format(invalid_asset_count)) return invalid_asset_count verify_power_of_two()