def create_level_sequence_transform_track(asset_name, length_seconds=600, package_path='/Game/'): sequence = unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name, package_path, unreal.LevelSequence, unreal.LevelSequenceFactoryNew()) actor_class = unreal.EditorAssetLibrary.load_blueprint_class('/VideoCore/Blueprints/BP_RecordedPlaneBase') actor = unreal.EditorLevelLibrary.spawn_actor_from_class(actor_class, [-450.0, 1030.0, 230.0], [0, 0, 0]) binding = sequence.add_possessable(actor) transform_track = binding.add_track(unreal.MovieScene3DTransformTrack) transform_section = transform_track.add_section() transform_section.set_start_frame_seconds(0) transform_section.set_end_frame_seconds(length_seconds) ## now do media track media_track = sequence.add_master_track(unreal.MovieSceneMediaTrack) media_track.set_editor_property("display_name", "Media") media_section = media_track.add_section() img_source = unreal.AssetToolsHelpers.get_asset_tools().create_asset("MS_" + asset_name, '/Game', unreal.ImgMediaSource, None) image_path = unreal.SystemLibrary.get_project_content_directory() + "/Movies/NewImageSequence/1.png" img_source.set_sequence_path(image_path) media_section.media_source = img_source media_texture = unreal.AssetToolsHelpers.get_asset_tools().create_asset("MT_" + asset_name, '/Game/', unreal.MediaTexture, unreal.MediaTextureFactoryNew()) media_section.media_texture = media_texture media_section.set_range(0,30) # Now create a new material instance (from base chromakey bat) and apply to newly created actor material_instance = unreal.AssetToolsHelpers.get_asset_tools().create_asset("MI_" + asset_name, '/Game/', unreal.MaterialInstanceConstant, unreal.MaterialInstanceConstantFactoryNew()) base_material = unreal.load_asset('/VideoCore/Materials/M_CamChroma') material_instance.set_editor_property('parent', base_material) media_texture = unreal.load_asset('/Game/'+"MT_" + asset_name) unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(material_instance, 'Texture', media_texture) unreal.MaterialEditingLibrary.update_material_instance(material_instance) placeholder_mat = unreal.load_asset('/Engine/BasicShapes/BasicShapeMaterial') unreal.EditorLevelLibrary.replace_mesh_components_materials_on_actors([actor], placeholder_mat, material_instance) return sequence
def resetStaticMeshMaterial(self, package_path): # def __init__(self, package_names=[], package_paths=[], object_paths=[], class_names=[], recursive_classes_exclusion_set=[], recursive_paths=False, recursive_classes=False, include_only_on_disk_assets=False): filter_staticmesh = unreal.ARFilter( [], [package_path], [], [unreal.StaticMesh.static_class().get_name()], [], True) filter_materialIns = unreal.ARFilter( [], [package_path], [], [unreal.MaterialInstanceConstant.static_class().get_name()], [], True) AssetRegistry = unreal.AssetRegistryHelpers().get_asset_registry() MaterialInsDataArr = AssetRegistry.get_assets(filter_materialIns) StaticMeshAssetDataArr = AssetRegistry.get_assets(filter_staticmesh) print('MaterialInsDataArr len is {}, StaticMeshAssetDataArr is {}'. format(len(MaterialInsDataArr), len(StaticMeshAssetDataArr))) for StaticMeshAssetData in StaticMeshAssetDataArr: # print StaticMeshAssetData StaticMeshStr = str(StaticMeshAssetData.package_name) # print StaticMeshStr StaticMeshAsset = unreal.StaticMesh.cast( unreal.load_asset(StaticMeshStr)) if (StaticMeshAsset != None): for MaterialInsData in MaterialInsDataArr: # print MaterialInsData.asset_name materialIndex = StaticMeshAsset.get_material_index( MaterialInsData.asset_name) if (materialIndex != -1): MaterialInsStr = str(MaterialInsData.package_name) targetMaterial = unreal.MaterialInstance.cast( unreal.load_asset(MaterialInsStr)) StaticMeshAsset.set_material(materialIndex, targetMaterial) print MaterialInsStr
def openAssets(): assets = [ unreal.load_asset('/Game/MyAsset/Textures/dear'), unreal.load_asset('/Game/MyAsset/Sounds/easy'), unreal.load_asset('/Game/MyAsset/StaticMeshes/static_fbx') ] unreal.AssetToolsHelpers.get_asset_tools().open_editor_for_assets(assets)
def duplicateAssetDialog(show_dialog=True): if show_dialog: unreal.AssetToolsHelpers.get_asset_tools().duplicate_asset_with_dialog( 'dear_Duplicated', '/Game/MyAsset/Textures', unreal.load_asset('/Game/MyAsset/Textures/dear_Renamed')) else: unreal.AssetToolsHelpers.get_asset_tools().duplicate_asset( 'dear_Duplicated', '/Game/MyAsset/Textures', unreal.load_asset('/Game/MyAsset/Textures/dear_Renamed'))
def tryCast(): if unreal.Texture2D.cast(unreal.load_asset('/Game/Textures/T_Snow_N')): print('Texture2D Cast Succeeded') else: print('Texture2D Cast Failed') if unreal.Actor.cast(unreal.load_asset('/Game/Textures/T_Snow_N')): print('Actor Cast Succeeded') else: print('Actor Cast Failed')
def fbx_import_option(self): options = unreal.FbxImportUI() options.auto_compute_lod_distances = False options.lod_number = 0 options.import_as_skeletal = bool(self.asset_data.get("skeletal_mesh")) options.import_animations = bool(self.asset_data.get("animation")) options.import_materials = bool(self.asset_data.get("import_materials")) options.import_textures = bool(self.asset_data.get("import_textures")) options.import_mesh = bool(self.asset_data.get("import_mesh")) options.static_mesh_import_data.generate_lightmap_u_vs = False options.lod_distance0 = 1.0 # if this is a skeletal mesh import if bool(self.asset_data.get("skeletal_mesh")): options.skeletal_mesh_import_data.normal_import_method = unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS_AND_TANGENTS options.mesh_type_to_import = unreal.FBXImportType.FBXIT_SKELETAL_MESH options.skeletal_mesh_import_data.import_mesh_lo_ds = bool(self.asset_data.get("lods")) asset_name = self.asset_data.get("skeletal_mesh_game_path") if asset_name.find("/") != -1: unreal.log(unreal.EditorAssetLibrary.does_asset_exist(asset_name)) if unreal.EditorAssetLibrary.does_asset_exist(asset_name): asset = unreal.load_asset(asset_name) skeleton_asset_name = os.path.splitext(asset.get_editor_property("skeleton").get_path_name())[0] skeleton_asset = unreal.load_asset(skeleton_asset_name) unreal.log(skeleton_asset) if skeleton_asset: options.set_editor_property("skeleton", skeleton_asset) # if this is an static mesh import elif not bool(self.asset_data.get("skeletal_mesh")): options.static_mesh_import_data.normal_import_method = unreal.FBXNormalImportMethod.FBXNIM_IMPORT_NORMALS_AND_TANGENTS options.mesh_type_to_import = unreal.FBXImportType.FBXIT_STATIC_MESH options.static_mesh_import_data.import_mesh_lo_ds = bool(self.asset_data.get("lods")) # if this is an animation import if bool(self.asset_data.get("animation")): asset_name = self.asset_data.get("skeletal_mesh_game_path") if unreal.EditorAssetLibrary.does_asset_exist(asset_name): asset = unreal.load_asset(asset_name) skeleton_asset_name = os.path.splitext(asset.get_editor_property("skeleton").get_path_name())[0] skeleton_asset = unreal.load_asset(skeleton_asset_name) unreal.log(skeleton_asset) # if a skeleton can be loaded from the provided path if skeleton_asset: options.set_editor_property("skeleton", skeleton_asset) options.set_editor_property("original_import_type", unreal.FBXImportType.FBXIT_ANIMATION) options.set_editor_property("mesh_type_to_import", unreal.FBXImportType.FBXIT_ANIMATION) else: raise RuntimeError("Unreal could not find a skeleton here: {0}".format( self.asset_data.get("skeletal_mesh_game_path"))) return options
def CreateInstanceOfMaterial(self, materialFileName, newAssetName, destination_path, textureFileNameList, material_template): selectedAsset = unreal.load_asset(materialFileName) # newAssetName = "" # newAssetName = selectedAsset.get_name() + "_%s" # "_%s_%d" asset_import_task = unreal.AssetImportTask() asset_import_task.set_editor_property("save", True) asset_import_task.set_editor_property("automated", True) asset_import_task.set_editor_property("replace_existing", True) factory = unreal.MaterialInstanceConstantFactoryNew() factory.set_editor_property("asset_import_task", asset_import_task) factory.set_editor_property("create_new", True) asset_tools = unreal.AssetToolsHelpers.get_asset_tools() # createdAssetsPath = materialFileName.replace(selectedAsset.get_name(), "-") # createdAssetsPath = createdAssetsPath.replace("-.-", "")newAssetName %("inst") newAsset = asset_tools.create_asset(newAssetName, destination_path, None, factory) # add by chenganggui unreal.MaterialEditingLibrary.set_material_instance_parent( newAsset, selectedAsset) # add by chenganggui for textureFileName in textureFileNameList: for Minslot in material_template['Minslots']: if (textureFileName.find(Minslot) != -1) and newAssetName in textureFileName: print( 'textureFileName is {}, Minslot is {}, newAsset is {}'. format(textureFileName, Minslot, newAssetName)) texture_asset = unreal.Texture.cast( unreal.load_asset(textureFileName)) unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value( newAsset, Minslot, texture_asset) # for MaterialsTemplate in self.MaterialsTemplateArr: # if (newAssetName.find(MaterialsTemplate['mat_Inst'].split("_")[0]) != -1): # for textureFileName in textureFileNameList: # # print "newAssetName::"+newAssetName+" MaterialsTemplate.mat_Inst::"+MaterialsTemplate.mat_Inst+" textureFileName::"+textureFileName+" " # for Minslot in MaterialsTemplate['Minslots']: # # if (textureFileName.find(Minslot) != -1) and newAssetName[:-5] in textureFileName: # # print('textureFileName is {} minslot is {}, newAssetName is {}'.format( # # textureFileName, # # Minslot, # # newAssetName[:-5] # # )) # texture_asset = unreal.Texture.cast(unreal.load_asset(textureFileName)) # unreal.MaterialEditingLibrary.set_material_instance_texture_parameter_value(newAsset, # Minslot, # texture_asset) unreal.EditorLoadingAndSavingUtils.save_dirty_packages(True, True)
def renameAssetDialog(show_dialog=True): first_renmae_data = unreal.AssetRenameData( unreal.load_asset('/Game/MyAsset/Textures/dear_Renamed'), '/Game/MyAsset/Textures', 'dear_Renamed_2') second_rename_data = unreal.AssetRenameData( unreal.load_asset('/Game/MyAsset/Textures/dear_Duplicated'), '/Game/MyAsset/Textures', 'dear_Duplicated_Renamed') if show_dialog: unreal.AssetToolsHelpers.get_asset_tools().rename_assets_with_dialog( [first_renmae_data, second_rename_data]) else: unreal.AssetToolsHelpers.get_asset_tools().rename_assets( [first_renmae_data, second_rename_data])
def retrieve_sequence_edits(self): """ Build a dictionary for all Level Sequences where keys are Level Sequences and values the list of edits they are in. :returns: A dictionary of :class:`unreal.LevelSequence` where values are lists of :class:`SequenceEdit`. """ sequence_edits = defaultdict(list) asset_helper = unreal.AssetRegistryHelpers.get_asset_registry() # Retrieve all Level Sequence assets all_level_sequences = asset_helper.get_assets_by_class("LevelSequence") for lvseq_asset in all_level_sequences: lvseq = unreal.load_asset(lvseq_asset.object_path, unreal.LevelSequence) # Check shots for track in lvseq.find_master_tracks_by_type( unreal.MovieSceneCinematicShotTrack): for section in track.get_sections(): # Not sure if you can have anything else than a MovieSceneSubSection # in a MovieSceneCinematicShotTrack, but let's be cautious here. try: # Get the Sequence attached to the section and check if # it is the one we're looking for. section_seq = section.get_sequence() sequence_edits[section_seq].append( SequenceEdit(lvseq, track, section)) except AttributeError: pass return sequence_edits
def collect_level_sequence(self, parent_item, asset, sequence_edits): """ Collect the items for the given Level Sequence asset. Multiple items can be collected for a given Level Sequence if it appears in multiple edits. :param parent_item: Parent Item instance. :param asset: An Unreal LevelSequence asset. :param sequence_edits: A dictionary with :class:`unreal.LevelSequence as keys and lists of :class:`SequenceEdit` as values. """ level_sequence = unreal.load_asset(asset.object_path) for edits_path in self.get_all_paths_from_sequence( level_sequence, sequence_edits): # Reverse the path to have it from top master sequence to the shot. edits_path.reverse() self.logger.info("Collected %s" % [x.get_name() for x in edits_path]) if len(edits_path) > 1: display_name = "%s (%s)" % (edits_path[0].get_name(), edits_path[-1].get_name()) else: display_name = edits_path[0].get_name() item = self.create_asset_item( parent_item, edits_path[0].get_path_name(), "LevelSequence", edits_path[0].get_name(), display_name, ) # Store the edits on the item so we can leverage them later when # publishing. item.properties["edits_path"] = edits_path
def getSkeleton(self, assetname): if unreal.EditorAssetLibrary.does_asset_exist(assetname): asset = unreal.load_asset(assetname) skeleton = asset.get_editor_property("skeleton").get_path_name() else: skeleton = None return skeleton
def string_key_example(sequencer_asset_path): # Load the sequence asset sequence = unreal.load_asset("/Game/TestKeySequence", unreal.LevelSequence) # This example assumes you've created a Blueprint or C++ object with a String field that has # been marked for interpolation in Cinematics ("Expose to Cinematics" in BP, or UPROPERTY(Interp) in C++) to modify. print("Modifying the string value on all string keys in the sequence...") for track in all_tracks: # Tracks are composed of sections for section in track.get_sections(): # Sections are composed of channels which contain the actual data! for channel in section.find_channels_by_type( unreal.MovieSceneScriptingStringChannel): print("Found string channel in section " + section.get_name() + " for track " + track.get_name() + " modifying values...") # Channels are often composed of some (optional) default values and keys. for key in channel.get_keys(): key.set_value(key.get_value() + "_Modified!") num_bool_keys_modified = num_bool_keys_modified + 1 print( "Modified " + str(num_keys_modified) + " + keys! Please note that at this time you will need to modify the structure of the sequence (rearrange track) for the changes to show up in the UI if it is currently open." ) return
def tryCast(): # ! this run crash use python # if unreal.Actor.cast(unreal.load_asset('/Game/MyAsset/Textures/dear')): if unreal.Texture2D.cast(unreal.load_asset('/Game/MyAsset/Textures/dear')): print 'Cast Succeeded' else: print 'Cast Failed'
def generate_export_sequence(sequencer_path, usd_filename, called_from_ui=False): task = usd_unreal.capture_sequence.SequenceExporterUsdBake() task.usd_filename = usd_filename task.sequence = unreal.load_asset(sequencer_path) task.init_capture_settings(task.sequence.get_path_name()) # Ok to texture stream as not actually rendering final pixels task.capture_settings.settings.enable_texture_streaming = True # Match frame rate of sequence task.capture_settings.settings.frame_rate = task.sequence.get_display_rate( ) task.frame_rate = float( task.capture_settings.settings.frame_rate.numerator) / float( task.capture_settings.settings.frame_rate.denominator) # Create usd file on disk task.stage = Usd.Stage.CreateNew(task.usd_filename) # Note: Optionally assign function to task.on_task_finished # Note: Call task.start_capture_async() to begin the task return task
def int_byte_key_example(sequencer_asset_path, amount_to_add=5): # Load the sequence asset sequence = unreal.load_asset("/Game/TestKeySequence", unreal.LevelSequence) # This example assumes you've created a Blueprint or C++ object with Byte/uint8 or Integer/int32 fields that have # been marked for interpolation in Cinematics ("Expose to Cinematics" in BP, or UPROPERTY(Interp) in C++) to modify. print("Adding the value " + str(amount_to_add) + " to all integer and byte keys in the sequence...") num_keys_modified = 0 for object_binding in sequence.get_bindings(): for track in object_binding.get_tracks(): for section in track.get_sections(): int_channels = section.find_channels_by_type( unreal.MovieSceneScriptingIntegerChannel) byte_channels = section.find_channels_by_type( unreal.MovieSceneScriptingByteChannel) print("Found " + str(len(int_channels)) + " Integer tracks and " + str(len(byte_channels)) + " Byte channels for track " + track.get_name() + " raising values...") combined_channels = [] combined_channels.extend(int_channels) combined_channels.extend(byte_channels) for channel in combined_channels: for key in channel.get_keys(): key.set_value(key.get_value() + amount_to_add) num_keys_modified = num_keys_modified + 1 print( "Modified " + str(num_keys_modified) + " + keys! Please note that at this time you will need to modify the structure of the sequence (rearrange track) for the changes to show up in the UI if it is currently open." ) return
def import_skeletal_mesh(fbx_path, game_path, asset_name): """ Import a single skeletalMesh into the engine provided an FBX. :param str fbx_path: Path to fbx. :param str game_path: Game path asset location. :param str asset_name: Name of asset. :return: """ # Create an import task. import_task = unreal.AssetImportTask() # Set base properties on the import task. import_task.filename = fbx_path import_task.destination_path = game_path import_task.destination_name = asset_name import_task.automated = True # Suppress UI. # Set the skeletal mesh options on the import task. import_task.options = _get_skeletal_mesh_import_options() # Import the skeletalMesh. unreal.AssetToolsHelpers.get_asset_tools().import_asset_tasks( [import_task] # Expects a list for multiple import tasks. ) imported_assets = import_task.get_editor_property("imported_object_paths") if not imported_assets: unreal.log_warning("No assets were imported!") return # Return the instance of the imported SkeletalMesh return unreal.load_asset(imported_assets[0])
def bool_key_example(sequencer_asset_path): # Load the sequence asset sequence = unreal.load_asset("/Game/TestKeySequence", unreal.LevelSequence) # Iterate over object bindings and tracks/sections all_tracks = sequence.get_master_tracks() for object_binding in sequence.get_bindings(): all_tracks.extend(object_binding.get_tracks()) # Now we iterate through each section and look for Bool channels within each track. print("Found " + str(len(all_tracks)) + " tracks, searching for bool channels...") num_bool_keys_modified = 0 for track in all_tracks: # Tracks are composed of sections for section in track.get_sections(): # Sections are composed of channels which contain the actual data! for channel in section.find_channels_by_type( unreal.MovieSceneScriptingBoolChannel): print("Found bool channel in section " + section.get_name() + " for track " + track.get_name() + " flipping values...") # Channels are often composed of some (optional) default values and keys. for key in channel.get_keys(): key.set_value(not key.get_value()) num_bool_keys_modified = num_bool_keys_modified + 1 print("Modified " + str(num_bool_keys_modified) + " keys!") return
def create_asset(asset_path='', unique_name=True, asset_class=None, asset_factory=None, **kwargs): """ Creates a a new Unreal asset :param asset_path: str :param unique_name: str :param asset_class: cls :param asset_factory: cls :param kwargs: dict :return: """ if unique_name: asset_path, asset_name = get_unique_name(asset_path) if not asset_exists(asset_path): path = asset_path.rsplit('/', 1)[0] name = asset_path.rsplit('/', 1)[1] return unreal.AssetToolsHelpers.get_asset_tools().create_asset( asset_name=name, package_path=path, asset_class=asset_class, factory=asset_factory, **kwargs) return unreal.load_asset(asset_path)
def set_two_sided(): # UE里面暂时没有get_folder的选项,只能借助C++,但是对于编译版本的虚幻添加C++蓝图函数有问题 # 所以暂时只能用这种方式来处理双面材质 editorAssetLib = GetEditorAssetLibrary() editorUtil = GetEditorUtilityLibrary() editor_filter_lib = GetEditorFilterLibrary() workingPaths = os.path.dirname( editorUtil.get_selected_assets()[0].get_path_name()) + "/" if not workingPaths: return two_sided_count = 0 allAssets = editorAssetLib.list_assets(workingPaths, False) for asset in allAssets: loaded_asset = unreal.load_asset(asset) try: loaded_asset.get_editor_property("two_sided") except: continue loaded_asset.set_editor_property("two_sided", 1) editorAssetLib.save_asset(asset) two_sided_count += 1 print "materials two sided" print two_sided_count
def import_animation_fbx(animation_fbx_filename, skeleton): task = ue.AssetImportTask() task.filename = animation_fbx_filename task.options = ue.FbxImportUI() task.options.automated_import_should_detect_type = True task.options.mesh_type_to_import = ue.FBXImportType.FBXIT_SKELETAL_MESH # task.options.import_as_skeletal = False task.options.skeleton = ue.load_asset(skeleton) task.options.import_mesh = False task.options.import_animations = True task.options.create_physics_asset = False task.options.import_materials = False task.options.import_textures = False task.destination_path = get_content_from_working_path( os.path.dirname(animation_fbx_filename)) task.automated = True ue.AssetToolsHelpers.get_asset_tools().import_asset_tasks([task]) # remove not needed mesh asset and rename animation clip # THIS IS A TEMP FIX UNTIL import_meshes=False WON'T WORK base_name = os.path.basename(animation_fbx_filename).replace(".fbx", "") ue.EditorAssetLibrary.delete_asset(task.destination_path + "/" + base_name) ue.EditorAssetLibrary.rename_asset( task.destination_path + "/" + base_name + "_Anim", task.destination_path + "/" + base_name)
def resetSkeletonMeshMaterial(self, package_path): # def __init__(self, package_names=[], package_paths=[], object_paths=[], class_names=[], recursive_classes_exclusion_set=[], recursive_paths=False, recursive_classes=False, include_only_on_disk_assets=False): filter_skeletalMesh = unreal.ARFilter( [], [package_path], [], [unreal.SkeletalMesh.static_class().get_name()]) filter_materialIns = unreal.ARFilter( [], [package_path], [], [unreal.MaterialInstanceConstant.static_class().get_name()]) AssetRegistry = unreal.AssetRegistryHelpers().get_asset_registry() MaterialInsDataArr = AssetRegistry.get_assets(filter_materialIns) SkeletalMeshAssetDataArr = AssetRegistry.get_assets( filter_skeletalMesh) for SkeletalMeshAssetData in SkeletalMeshAssetDataArr: # print StaticMeshAssetData SkeletalMeshStr = str(SkeletalMeshAssetData.package_name) # print StaticMeshStr SkeletalMeshAsset = unreal.SkeletalMesh.cast( unreal.load_asset(SkeletalMeshStr)) materials = SkeletalMeshAsset.materials if (SkeletalMeshAsset != None): for MaterialInsData in MaterialInsDataArr: # print MaterialInsData.asset_name materialIndex = SkeletalMeshAsset.get_material_index( MaterialInsData.asset_name) if (materialIndex != -1): MaterialInsStr = str(MaterialInsData.package_name) targetMaterial = unreal.MaterialInstance.cast( unreal.load_asset(MaterialInsStr)) # SkeletalMeshAsset.set_material(materialIndex,targetMaterial) for SkeletalMeshMaterialIndex in range(materials): if (materials[SkeletalMeshMaterialIndex]. imported_material_slot_name == MaterialInsData.asset_name): targetSkeltalMaterial = unreal.SkeletalMaterial( targetMaterial, materials[SkeletalMeshMaterialIndex]. material_slot_name(), materials[SkeletalMeshMaterialIndex]. uv_channel_data()) materials[ SkeletalMeshMaterialIndex] = targetSkeltalMaterial print MaterialInsStr
def refreshIMGAsset(self, IMGFileName): # Get texture texture_asset = unreal.Texture.cast(unreal.load_asset(IMGFileName)) print('success refresh') texture_asset_str = texture_asset.get_name() if (texture_asset_str.find("BaseColor") != -1 or texture_asset_str.find("BentNormal") != -1): texture_asset.srgb = True else: texture_asset.srgb = False
def createGenericAsset(asset_path='', unique_name=True, asset_class=None, asset_factory=None): if unique_name: asset_path, asset_name = unreal.AssetToolsHelpers.get_asset_tools().create_unique_asset_name( base_package_name=asset_path, suffix='') if not unreal.EditorAssetLibrary.does_asset_exist(asset_path=asset_path): path = asset_path.rsplit('/', 1)[0] name = asset_path.rsplit('/', 1)[1] return unreal.AssetToolsHelpers.get_asset_tools().create_asset(asset_name=name, package_path=path, asset_class=asset_class, factory=asset_factory) return unreal.load_asset(asset_path)
def import_fbx_asset(fbx_files=[], dest_path="/Game/new_folder", import_type="static_mesh", assemble_scale_factor=1): # -------------------------------------------- # 判断类型,生成option # 尺寸缩放在这个时候(导入之前)进行 if import_type == "static_mesh": option = build_static_mesh_import_options(assemble_scale_factor) if import_type == "misc": option = None # -------------------------------------------- # 一个FBX对应一个task, 一个FBX可以包含若干个asset # 一个FBX对应一个actor,一个actor包含若干个asset # -------------------------------------------- # opertion start, with slow task !!! for idx, fbx in enumerate(fbx_files): # -------------------------------------------- # create folder # dest_path = dest_path + str("_%d" % (idx+1)) if not directory_exists(dest_path): create_directory(dest_path) # -------------------------------------------- # 对每个fbx新建一个task,导入到content browser fbx_task, spawn_actor_name = build_import_task(fbx, dest_path, option) execute_import_task(fbx_task) print("CB imported") editor_asset_lib = GetEditorAssetLibrary() editor_filter_lib = GetEditorFilterLibrary() asset_paths = editor_asset_lib.list_assets(dest_path) print(asset_paths) # -------------------------------------------- # 针对导入的fbx里每个单独的asset,spawn(导入的时候不要combine mesh!!!,build option里设置) # 做了一个过滤,只会spawn static mesh editor_level_lib = GetEditorLevelLibrary() actor_in_asset_list = [] for asset in asset_paths: loaded_asset = unreal.load_asset(asset) temp_list = [] temp_list.append(loaded_asset) temp_list = editor_filter_lib.by_class( temp_list, unreal.StaticMesh.static_class()) if not temp_list: continue actor = editor_level_lib.spawn_actor_from_object( loaded_asset, (0, 0, 0), (0, 0, 0)) actor_in_asset_list.append(actor) print("assets spawned") '''
def addSkeletalAnimationTrackOnPossessable(animation_path='', possessable=None): # Get Animation animation_asset = unreal.AnimSequence.cast(unreal.load_asset(animation_path)) params = unreal.MovieSceneSkeletalAnimationParams() params.set_editor_property('Animation', animation_asset) # Add track animation_track = possessable.add_track(track_type=unreal.MovieSceneSkeletalAnimationTrack) # Add section animation_section = animation_track.add_section() animation_section.set_editor_property('Params', params) animation_section.set_range(0, animation_asset.get_editor_property('sequence_length'))
def export_anim_sequence(map_asset_path, sequencer_asset_path, anim_sequence): # Load the map, get the world world = unreal.EditorLoadingAndSavingUtils.load_map(map_asset_path) # Load the sequence asset sequence = unreal.load_asset(sequencer_asset_path, unreal.LevelSequence) # Get Bindings, we are assuming the first binding has the skeletal mesh we want to export bindings = sequence.get_bindings() # Export unreal.SequencerTools.export_anim_sequence(world, sequence, anim_sequence, bindings[0]) return
def update(self, items): """ Perform replacements given a number of scene items passed from the app. The method relies on `tk-multi-loader2.unreal` `action_mappings` hook: the update is an import replacing the older version. This way, this `update` method can update all the types the loader can load, and will also apply the same metadata. Once a selection has been performed in the main UI and the user clicks the update button, this method is called. The items parameter is a list of dictionaries on the same form as was generated by the scan_scene hook above. The path key now holds the that each node should be updated *to* rather than the current path. """ imgspc_fw = self.load_framework("tk-framework-imgspc") imgspc_ue_imp = imgspc_fw.import_module("unreal.import_utils") for item in items: asset_to_update = unreal.load_asset(item["node"]) if not asset_to_update: self.logger.warning(f"Could not load asset {asset_to_update}.") continue asset_path = unreal.Paths.get_path(asset_to_update.get_path_name()) asset_name = asset_to_update.get_name() new_source_file_path = item["path"] publishes = sgtk.util.find_publish(self.sgtk, [new_source_file_path], fields=[ "name", "path", "task", "entity", "created_by", "version_number", "published_file_type", ]) if not publishes.get(new_source_file_path): self.logger.warning( f"No PublishedFile found in Shotgun for path `{new_source_file_path}`" ) continue sg_publish_data = publishes[new_source_file_path] imgspc_ue_imp.import_to_content_browser( new_source_file_path, sg_publish_data, )
def importHierarchyCSV(self): try: newname = self.fbxName.partition('.')[0] if newname[ 0: 3] == "SM_": #todo if there are any other prefixes in the future, test for them newname = "ASH_" + newname[3:] elif newname[ 0: 4] == "CAM_": #todo if there are any other prefixes in the future, test for them newname = "ASH_" + newname[4:] elif newname[ 0: 4] == "LGT_": #todo if there are any other prefixes in the future, test for them newname = "ASH_" + newname[4:] else: newname = "ASH_" + newname asset_name = newname import_tasks = [] factory = unreal.CSVImportFactory() csvPath = self.rootImportFolder + asset_name + '.csv' #todo at some point fix the hierarchy name so it is unique per import factory.script_factory_can_import(csvPath) # AssetImportTask = unreal.AssetImportTask() AssetImportTask.set_editor_property('filename', csvPath) AssetImportTask.set_editor_property('factory', factory) AssetImportTask.set_editor_property('destination_path', self.UEMeshDirectory) AssetImportTask.set_editor_property('automated', True) #self.automateImports) importSettings = unreal.CSVImportSettings() #importSettings.set_editor_property('import_row_struct',True) path_to_asset = '/OVFPPlugin/generalResources/blenderToUnrealAdgBridge/B2UADGBrige_MeshHierarcyCSV' #.B2UADGBrige_MeshHierarcyCSV' asset_reg = unreal.AssetRegistryHelpers.get_asset_registry() #CSVstruct = asset_reg.get_asset_by_object_path(path_to_asset) CSVstruct = unreal.load_asset(path_to_asset) #unreal.log_warning(str(CSVstruct)) factory.automated_import_settings.import_row_struct = CSVstruct #AssetImportTask.set_editor_property('save', False) import_tasks.append(AssetImportTask) #do the import self.AssetTools.import_asset_tasks(import_tasks) unreal.EditorAssetLibrary.save_directory( self.UEMeshDirectory) #save directory we imported into except Exception: unreal.log("Issue with hierarcy file")
def buildAnimationImportOptions(skeleton_path=''): options = unreal.FbxImportUI() # unreal.FbxImportUI options.set_editor_property('import_animations', True) options.skeleton = unreal.load_asset(skeleton_path) # unreal.FbxMeshImportData options.anim_sequence_import_data.set_editor_property('import_translation', unreal.Vector(0.0, 0.0, 0.0)) options.anim_sequence_import_data.set_editor_property('import_rotation', unreal.Rotator(0.0, 0.0, 0.0)) options.anim_sequence_import_data.set_editor_property('import_uniform_scale', 1.0) # unreal.FbxAnimSequenceImportData options.anim_sequence_import_data.set_editor_property('animation_length', unreal.FBXAnimationLengthImportType.FBXALIT_EXPORTED_TIME) options.anim_sequence_import_data.set_editor_property('remove_redundant_keys', False) return options
def get_bound_objects(map_asset_path, sequencer_asset_path): world = unreal.EditorLoadingAndSavingUtils.load_map(map_asset_path) sequence = unreal.load_asset(sequencer_asset_path, unreal.LevelSequence) range = sequence.get_playback_range() bound_objects = unreal.SequencerTools.get_bound_objects( world, sequence, sequence.get_bindings(), range) for bound_object in bound_objects: print 'Binding: %s' % bound_object.binding_proxy print 'Bound Objects: %s' % bound_object.bound_objects print '----\n'