def _compare_value(val, other, inverse=False): if inverse: if val == other: unreal.log_error("Value was '{0}' but it wasn't supposed to be!".format(other)) else: if val != other: unreal.log_error("Value was '{0}' but '{1}' was expected!".format(val, other))
def set_selected_assets_property(property_name, property_value): # EditorUtilityLibraryのインスタンスを生成 editor_utility_instance = EUL() # 現在コンテンツブラウザで選択しているアセットを取得 selected_assets = EUL.get_selected_assets() # 選択しているアセットをFor分で回す for asset in selected_assets: # Blueprintクラスかをチェック try: unreal.Blueprint.cast(asset) print(asset.get_name()) except: # BPクラスじゃないなら次へ error_log = str(asset.get_name()) + "は、BlueprintClassではありません。" unreal.log_error(error_log) continue try: # 指定した変数のデフォルトの値をセットする set_default_property(asset.get_path_name(), property_name, property_value) except: # セットできなくても次へ error_log = str(asset.get_name() ) + "は、Property「" + property_name + "」を持っていません。" unreal.log_error(error_log) continue
def error(message): """ Prints a error message :param message: str :return: """ unreal.log_error(message)
def _compare_property_value(obj, other, prop_name, inverse=False): obj_value = getattr(obj, prop_name) other_value = getattr(other, prop_name) if inverse: if obj_value == other_value: unreal.log_error("Property '{0}' has the value '{1}' but it wasn't supposed to!".format(prop_name, other_value)) else: if obj_value != other_value: unreal.log_error("Property '{0}' has the value '{1}' but '{2}' was expected!".format(prop_name, other_value, obj_value))
def unregister_callback(cls, func, *args, **kws): try: del cls._callbacks[hashlib.md5(str((func, args, kws)).encode()).hexdigest()] except KeyError: unreal.log_error( "No callback name {} with arguments: {} and keywords {} to unregister".format( func.__name__, args, kws ) )
def run_callbacks(cls): for func_name, func_param in cls._callbacks.items(): func, args, kws = func_param unreal.log_warning( "execute {} with param {} keywords: {}".format(func.__name__, args, kws) ) try: func(*args, **kws) except Exception as why: unreal.log_error("failed to run with error:\n{}".format(why))
def exchangeEnvironment(index): global all_actors global texture_cube_assets if not len(texture_cube_assets) > 0: unreal.log_error("No cubemap textures found!") else: for actor in all_actors: if not actor.get_name().find("light_HDRIBackdrop") == -1: # get HDRIBackdrop actor in scene actor.set_editor_property("Cubemap", texture_cube_assets[index]) unreal.log_warning("New cubemap: {}".format(actor.get_editor_property("Cubemap")))
def _generate_fbx_export_task(destination_path, asset_path, asset_name): """ Create and configure an Unreal AssetExportTask :param destination_path: The path where the exported FBX will be placed :param asset_path: The Unreal asset to export to FBX :param asset_name: The FBX filename to export to :return the configured AssetExportTask """ loaded_asset = unreal.EditorAssetLibrary.load_asset(asset_path) if not loaded_asset: unreal.log_error( "Failed to create FBX export task for {}: Could not load asset {}". format(asset_name, asset_path)) return None filename = os.path.join(destination_path, asset_name + ".fbx") # Setup AssetExportTask for non-interactive mode task = unreal.AssetExportTask() task.object = loaded_asset # the asset to export task.filename = filename # the filename to export as task.automated = True # don't display the export options dialog task.replace_identical = True # always overwrite the output # Setup export options for the export task task.options = unreal.FbxExportOption() # These are the default options for the FBX export # task.options.fbx_export_compatibility = fbx_2013 # task.options.ascii = False # task.options.force_front_x_axis = False # task.options.vertex_color = True # task.options.level_of_detail = True # task.options.collision = True # task.options.welded_vertices = True # task.options.map_skeletal_motion_to_root = False return task
def _unreal_export_asset_to_fbx(destination_path, asset_path, asset_name): """ Export an asset to FBX from Unreal :param destination_path: The path where the exported FBX will be placed :param asset_path: The Unreal asset to export to FBX :param asset_name: The asset name to use for the FBX filename """ # Get an export task task = _generate_fbx_export_task(destination_path, asset_path, asset_name) if not task: return False, None # Do the FBX export result = unreal.Exporter.run_asset_export_task(task) if not result: unreal.log_error("Failed to export {}".format(task.filename)) for error_msg in task.errors: unreal.log_error("{}".format(error_msg)) return result, None return result, task.filename
#################### Load UI Library #################### """) for m in __all__: # __import__(m, locals(), globals()) try: mod = importlib.import_module("{}.{}".format(dir_basename, m)) if m in globals(): unreal.log("""@ #################### ReLoad UI Library #################### """) try: reload(mod) except: importlib.reload(mod) unreal.log("Successfully import {}".format(m)) except Exception as why: unreal.log_error("Fail to import {}.\n {}".format(m, why)) traceback.print_exc(file=sys.stdout) unreal.log("""@ #################### """)
help(unreal.SourceControl) unreal.log("\nDisplaying source control file state members") help(unreal.SourceControlState) #--------------------------------------- # Source control tests _sc_test_file_strings() # Outside of source controlled directories unreal.log( "\nTesting state of file not in source control: \NoSuchFile.txt") state = _sc_test_state(r"\NoSuchFile.txt") if state.is_source_controlled: unreal.log_error( "Expected '\NoSuchFile.txt' to not be source controlled.") # Test checking out, deleting, adding and reverting if len(file_in_sc): #--------------------------------------- unreal.log( "\nTesting state of file during check out and revert: {0}".format( file_in_sc)) # Test pre check out state = _sc_test_state(file_in_sc) if not state.can_check_out: unreal.log_error( "Expected '{0}' to be able checked out.".format(file_in_sc)) # Test check out
import unreal gl_level_actors = unreal.EditorLevelLibrary.get_all_level_actors() def getActor(actorName): filtered_list = unreal.EditorFilterLibrary.by_actor_label( gl_level_actors, actorName, unreal.EditorScriptingStringMatchType.EXACT_MATCH) if len(filtered_list) == 0: unreal.log_warning( 'Did not find any actor with label: "{}"'.format(actorName)) if len(filtered_list) > 1: unreal.log_warning( 'More then one actor with label: "{}"'.format(actorName)) return filtered_list myActor = getActor('TPhotometricLight_UniforDiffuse')[0] my_light_component = myActor.light_component # Usual Python assert assert my_light_component.intensity_units.name == 'LUMENS', 'Wrong light intensity units' # or use unreal log error msgs if not my_light_component.intensity_units.name == 'LUMENS': unreal.log_error('Wrong light intensity units')
def _test_object_properties(obj): _test_common_properties(obj) _test_common_properties(obj.struct) _test_common_properties(obj.child_struct) if obj.delegate: unreal.log_error("Property 'delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) obj.delegate.bind_function(obj, "delegate_property_callback") if not obj.delegate: unreal.log_error("Property 'delegate' on '{0}' is unbound when it should be bound!".format(type(obj).__name__)) if obj.delegate: _compare_value(obj.delegate(obj.int), 10) obj.delegate.unbind() if obj.delegate: unreal.log_error("Property 'delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) if obj.delegate: unreal.log_error("Property 'delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) obj.delegate.bind_callable(lambda value : value * 2) if not obj.delegate: unreal.log_error("Property 'delegate' on '{0}' is unbound when it should be bound!".format(type(obj).__name__)) if obj.delegate: _compare_value(obj.delegate(obj.int), 20) obj.delegate.unbind() if obj.delegate: unreal.log_error("Property 'delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) if obj.multicast_delegate: unreal.log_error("Property 'multicast_delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) obj.multicast_delegate.add_function(obj, "multicast_delegate_property_callback") if not obj.multicast_delegate: unreal.log_error("Property 'multicast_delegate' on '{0}' is unbound when it should be bound!".format(type(obj).__name__)) if obj.multicast_delegate: obj.multicast_delegate(obj.string) obj.multicast_delegate.clear() if obj.multicast_delegate: unreal.log_error("Property 'multicast_delegate' on '{0}' is bound when it should be unbound!".format(type(obj).__name__)) for s in obj.struct_array: _test_common_properties(s) _compare_common_properties(obj, obj.struct) for s in obj.struct_array: _compare_common_properties(obj, s, True)
def _test_set_value(obj, prop_name, value): setattr(obj, prop_name, value) cur_value = getattr(obj, prop_name) if cur_value != value: unreal.log_error("Property '{0}' on '{1}' has the value '{2}' but '{3}' was expected!".format(prop_name, type(obj).__name__, cur_value, value))
import unreal avalon_detected = True try: from avalon import api from avalon import unreal as avalon_unreal except ImportError as exc: avalon_detected = False unreal.log_error("Avalon: cannot load avalon [ {} ]".format(exc)) if avalon_detected: api.install(avalon_unreal) @unreal.uclass() class AvalonIntegration(unreal.AvalonPythonBridge): @unreal.ufunction(override=True) def RunInPython_Create(self): unreal.log_warning("Avalon: showing creator window") if avalon_detected: avalon_unreal.show_creator() @unreal.ufunction(override=True) def RunInPython_Load(self): unreal.log_warning("Avalon: showing loader window") if avalon_detected: avalon_unreal.show_loader() @unreal.ufunction(override=True) def RunInPython_Publish(self):
def importfbxstack(self): #FBX scene ''' data = unreal.AutomatedAssetImportData() data.set_editor_property('destination_path', self.UEMeshDirectory) data.set_editor_property('filenames', [self.fbxPath]) #data.set_editor_property('level_to_load', '/Game/MyNewLevel') data.set_editor_property('replace_existing', True) factory = unreal.FbxSceneImportFactory() data.set_editor_property('factory', factory) unreal.AssetToolsHelpers.get_asset_tools().import_assets_automated(data) ''' ###delete all static meshes in directory unreal.EditorAssetLibrary.save_directory(self.UEMeshDirectory) #save directory we imported into unreal.EditorAssetLibrary.does_directory_have_assets(self.UEMeshDirectory, recursive=True) registry = unreal.AssetRegistryHelpers.get_asset_registry() assetsinfolder = registry.get_assets_by_path(self.UEMeshDirectory,False,False) #assetsinfolder = unreal.EditorAssetLibrary.list_assets(self.UEMeshDirectory, recursive=False, include_folder=False) #staticMeshes = unreal.EditorFilterLibrary.by_class( assetsinfolder , unreal.StaticMeshActor) for deletedmesh in assetsinfolder: #unreal.log_warning(deletedmesh.asset_class) if str(deletedmesh.asset_class) == 'StaticMesh' or str(deletedmesh.asset_class) == 'DataTable': #unreal.log_warning("delete") unreal.EditorAssetLibrary.delete_asset(deletedmesh.package_name) #FBX normal #set up the import import_tasks = [] #factory = unreal.FbxSceneImportFactory() factory = unreal.FbxFactory() fbxPath = self.rootImportFolder + self.fbxName factory.script_factory_can_import(fbxPath) ##########use this to test if the file is an FBX AssetImportTask = unreal.AssetImportTask() AssetImportTask.set_editor_property('filename', fbxPath) AssetImportTask.set_editor_property('factory', factory) AssetImportTask.set_editor_property('destination_path', self.UEMeshDirectory) AssetImportTask.set_editor_property('automated', True)#self.automateImports) AssetImportTask.set_editor_property('options', self.buildFbxImportOptions()) AssetImportTask.set_editor_property('save', False) import_tasks.append(AssetImportTask) #do the import self.AssetTools.import_asset_tasks(import_tasks) unreal.log_warning("starting Rename") #rename the fbxs to the correct format #unreal.EditorAssetLibrary.does_directory_have_assets("/Game/", recursive=True) meshesInFolder = unreal.AssetRegistryHelpers.get_asset_registry().get_assets_by_path(self.UEMeshDirectory, recursive=True, include_only_on_disk_assets=False) #static_mesh_objects = [data.get_asset() for data in static_mesh_data] #unreal.log_warning(len(meshesInFolder)) for renamedmesh in meshesInFolder: #unreal.log_warning("testingasset") #unreal.log_warning(str(renamedmesh.asset_name)) if str(renamedmesh.asset_class) == 'StaticMesh': unreal.log_warning(renamedmesh) oldMeshName = renamedmesh.object_path #.package_name unreal.log_warning(oldMeshName) newMeshName = str(renamedmesh.object_path).rpartition(".")[2] if newMeshName == self.fbxName[0:-3]: True else: unreal.log_warning(newMeshName) newMeshName = newMeshName[len(self.fbxName)-3:] unreal.log_warning(newMeshName) if newMeshName[0:4] == "prep": #remove prep from the start of the name if it exists newMeshName = newMeshName[4:] newMeshName = str(renamedmesh.package_path) + "/" + newMeshName unreal.log_warning("4:"+newMeshName) #newMeshName = self.UEMeshDirectory + str(oldMeshName).rpartition("/") if True: #start of code to reassign static mesh materials per object in content browser assetObject = renamedmesh.get_asset() unreal.log_warning(assetObject) mesh = unreal.StaticMesh.cast(assetObject) for material_index in range(0,mesh.get_num_sections(0)): material_name = mesh.get_material(material_index).get_name() unreal.log_error(material_name) #mesh.set_material(material_index, new_material) #unreal.log_warning("rename: "+ str(renamedmesh.object_path) + " to " + str(renamedmesh.package_name) + " to " + str(renamedmesh.package_path))#+ str(newMeshName)) #TODO unreal.log_warning("rename: "+ str(oldMeshName) + " to " + newMeshName) unreal.EditorAssetLibrary.rename_asset(oldMeshName , newMeshName) #unreal.EditorAssetLibrary.save_directory(self.UEMeshDirectory) #save directory we imported into #does_directory_have_assets(directory_path, recursive=True) TODO does the tool delete any copies of the meshes already out in the world? ''' actors = unreal.EditorLevelLibrary.get_all_level_actors() for actor in actors: #delete the imported actor if actor.get_actor_location() == unreal.Vector(x=0.0, y=0.0, z=0.0) and self.fbxName[0:-4] in actor.get_actor_label(): if actor.get_component_by_class(unreal.StaticMeshComponent) != None: mesh = actor.get_component_by_class(unreal.StaticMeshComponent).static_mesh path = self.UEMeshDirectory in unreal.EditorAssetLibrary.get_path_name_for_loaded_asset(mesh) if path: unreal.EditorLevelLibrary.destroy_actor(actor) ''' #Fbx automated sample code ''' #Fbx automated task factory = unreal.FbxFactory() factory.set_editor_property('options',self.buildFbxImportOptions()) assetImportData = unreal.AutomatedAssetImportData() #factory.script_factory_can_import(filename) ##########use this to test if the file is an FBX assetImportData.set_editor_property('filenames', [self.fbxPath]) assetImportData.set_editor_property('destination_path', self.UEMeshDirectory) assetImportData.set_editor_property('factory',factory ) #Pointer to the factory currently being used #assetImportData.set_editor_property('factory_name', ) #Name of the factory to use when importing these assets. If not specified the factory type will be auto detected assetImportData.set_editor_property('group_name',"BlenderFiles") #Display name of the group. This is for logging purposes only. assetImportData.set_editor_property('replace_existing',True) assetImportData.set_editor_property('skip_read_only',False) #Whether or not to skip importing over read only assets that could not be checked out importedFiles = self.AssetTools.import_assets_automated(assetImportData) ''' unreal.EditorAssetLibrary.save_directory(self.UEMeshDirectory) #save directories we imported into
def createMaterialInstance(self , NewMatName = "MI_test",parameterNames = [], parameters = []): EditorLibrary=self.EditorLibrary if parameters[3] == "y" or parameters[3] == "True" or parameters[3] == "yes": writeParameters = True else: writeParameters = False if unreal.EditorAssetLibrary.does_asset_exist(self.UEMaterialDirectory + '/' + self.legalizeName(NewMatName)): #unreal.log_warning("material already exists, skipping") #TODO if the overwrite command is set, set parameters for that material anyway. NewMaterial = unreal.EditorAssetLibrary.load_asset(self.UEMaterialDirectory + '/' + self.legalizeName(NewMatName)) else: writeParameters = True NewMaterial = self.AssetTools.create_asset(asset_name=self.legalizeName(NewMatName),package_path=self.UEMaterialDirectory,asset_class = unreal.MaterialInstanceConstant, factory=unreal.MaterialInstanceConstantFactoryNew()) #EditorLibrary.save_asset(NewMaterial.get_path_name(),True) #TODO Fix error? if writeParameters ==True: index = 0 for parameterName in parameterNames: try: if index == 2: unreal.log("foundParent") parentPath = parameters[index] if not parentPath.startswith("/"): parentPath = "/"+parentPath if EditorLibrary.does_asset_exist(parentPath): unreal.log("parent confirmed") parentMaterial = EditorLibrary.load_asset(parentPath) unreal.MaterialEditingLibrary.set_material_instance_parent(NewMaterial,parentMaterial) else: unreal.log_error("No parent material found for:" + NewMaterial.get_path_name()) break elif parameterName.startswith('T_') and parameters[index]: if parameters[index].startswith('/Game/'): texPath = parameters[index] else: texPath = UEImporter.UEMaterialDirectory + "/"+parameters[index] if EditorLibrary.does_asset_exist(texPath): unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(NewMaterial,parameterName[2:],EditorLibrary.load_asset(texPath)) else: unreal.log_warning("Texture not found for ")# + NewMaterial.get_path_name() + ": " + parameters[index]) #TODO FIX ERROR ? elif parameterName.startswith('S_') and parameters[index]: #unreal.log("foundScalar") unreal.MaterialEditingLibrary.set_material_instance_scalar_parameter_value(NewMaterial,parameterName[2:],float(parameters[index])) elif parameterName.startswith('V_') and parameters[index]: unreal.log("foundVector3") colorfour = parameters[index] if colorfour.startswith("["): colorfour = colorfour [1:-1] colorfour = colorfour.split(",") color = unreal.LinearColor(r=float(colorfour[0]), g=float(colorfour[1]), b=float(colorfour[2]), a=1) unreal.MaterialEditingLibrary.set_material_instance_vector_parameter_value(NewMaterial,parameterName[2:],color) ''' doesn't work elif parameterName.startswith('B_') and parameters[index]: unreal.log("foundBool") unreal.MaterialEditingLibrary.set_material_instance_boolean_parameter_value(NewMaterial,parameterName[2:],False) #if parameters[index] == "True" or parameters[index] == "TRUE" or parameters[index] == "yes" or parameters[index] == "yes" or parameters[index] == "true" or parameters[index] == "y": # unreal.MaterialEditingLibrary.set_material_instance_boolean_parameter_value(NewMaterial,parameterName[2:],True) #elif parameters[index] == "False" or parameters[index] == "FALSE" or parameters[index] == "false" or parameters[index] == "FALSE" or parameters[index] == "no" or parameters[index] == "n": # unreal.MaterialEditingLibrary.set_material_instance_boolean_parameter_value(NewMaterial,parameterName[2:],False) ''' except Exception: unreal.log("no index") unreal.log_warning(index) index += 1 return