UE Editor API 整理
过一下 https://github.com/20tab/UnrealEnginePython/blob/master/docs/,熟悉一下编辑器 API,方便后续编辑器脚本开发
后续的目标是所有编辑器操作应该都可以脚本化(自动化),这样把 GPT 接进 UE 里就可以 Chat UE 操作了
- SM_ = static mesh, HISM = …
- http 略
- runtime 开发就用到的略
ICollectionManager
集合 是一种将资产集整理成组的方式。与文件夹不同,集合不包含资产本身,而仅包含对这些资产的引用。实际上,这意味着一个资产可以属于多个集合。
#include “Developer/CollectionManager/Public/ICollectionManager.h”
DataTable
#include “Runtime/Engine/Classes/Engine/DataTable.h”
#include “Editor/UnrealEd/Public/DataTableEditorUtils.h”
DT 内部是 FName => UScriptStruct 的映射
TMap<FName, uint8*> RowMap;
DT 转 json string
FString GetTableAsJSON(const EDataTableExportFlags InDTExportFlags = EDataTableExportFlags::None) const;
创建新 DT
dt_factory = DataTableFactory()
dt_factory.Struct = Transformdt = dt_factory.factory_create_new('/Game/TransformDataTable')
工厂模式,每个资源类型都有一个
检查下路径有没有冲突
class UDataTableFactory : public UFactory
{UPROPERTY(BlueprintReadWrite, Category = "Data Table Factory")TObjectPtr<const class UScriptStruct> Struct;
...void ue_factory_create_new(UFactory* factory, const FString& name)
{FString PackageName = UPackageTools::SanitizePackageName(name);UPackage* outer = CreatePackage(*PackageName);if (!outer){// Handle error: unable to create packagereturn;}TArray<UPackage*> TopLevelPackages;TopLevelPackages.Add(outer);if (!UPackageTools::HandleFullyLoadingPackages(TopLevelPackages, FText::FromString("Create a new object"))){// Handle error: unable to fully load packagereturn;}UClass* u_class = factory->GetSupportedClass();if (u_class->IsChildOf<UBlueprint>() && FindObject<UBlueprint>(outer, *name)){// Handle error: a blueprint with this name already exists in the packagereturn;}if (u_class->IsChildOf<UUserDefinedStruct>() && FindObject<UUserDefinedStruct>(outer, *name)){// Handle error: a structure with this name already exists in the packagereturn;}UObject* u_object =nullptr;u_object = factory->FactoryCreateNew(u_class, outer, FName(*name), RF_Public | RF_Standalone, nullptr, GWarn);if (u_object){FAssetRegistryModule::AssetCreated(u_object);outer->MarkPackageDirty();}else{// Handle error: unable to create new object from factoryreturn;}
}
Foliage
UE 自带的植被系统,专门有个刷植被的编辑模式,刷的结果存在 UWorld 的 AInstancedFoliageActor 里(单例,自动创建)
存储用了一个 Map,每一项是一个 SM_,渲染用 HISM
TMap<TObjectPtr<UFoliageType>, TUniqueObj<FFoliageInfo>> FoliageInfos;
? 某种资源 todo
factory = FoliageTypeFactory()
foliage_type = factory.factory_create_new('/Game/Foliage/FirstFoliageType')
foliage_type.Mesh = ue.load_object(StaticMesh, '/Game/Mesh/StaticMesh001')
foliage_type.save_package()
这个 Map 存 UWorld.AInstancedFoliageActor 里,即每个 .umap 都单独有一套植被表
foliage_actor = world.get_instanced_foliage_actor_for_current_level()
world.add_foliage_asset(foliage_type)
world.add_foliage_asset(ue.load_object(StaticMesh, '/Game/Mesh/StaticMesh001'))
void ue_add_foliage_asset(UObject* self, UObject* u_object)
{UWorld* world = ue_get_uworld(self);if (!world){// Handle error: unable to retrieve UWorld from uobjectreturn;}UFoliageType* foliage_type = nullptr;AInstancedFoliageActor* ifa = AInstancedFoliageActor::GetInstancedFoliageActorForCurrentLevel(world, true);if (u_object->IsA<UStaticMesh>()){foliage_type = ifa->GetLocalFoliageTypeForSource(u_object);if (!foliage_type){ifa->AddMesh(static_cast<UStaticMesh*>(u_object), &foliage_type);}}else if (u_object->IsA<UFoliageType>()){foliage_type = static_cast<UFoliageType*>(u_object);ifa->AddFoliageType(foliage_type);}if (!foliage_type){// Handle error: unable to add foliage assetreturn;}// Return foliage_type if needed
}
遍历植被表
import unreal_engine as uefoliage_actor = ue.get_editor_world().get_instanced_foliage_actor_for_current_level()for foliage_type in foliage_actor.get_foliage_types():print('Foliage Type: {0}'.format(foliage_type.get_name()))for foliage_instance in foliage_actor.get_foliage_instances(foliage_type):print(foliage_instance.location)print(foliage_instance.draw_scale3d)print(foliage_instance.pre_align_rotation)print(foliage_instance.rotation)print(foliage_instance.flags)print(foliage_instance.zoffset)print('*' * 20)
Add a ForEachLoop Macro node
蓝图编辑器的 API,非常恶心,添加节点,添加 pin 脚连线,保存
# for_each_loop = ue.load_object(EdGraph, '/Engine/EditorBlueprintResources/StandardMacros.StandardMacros:ForEachLoop')
for_each_loop = ue.find_object('ForEachLoop')# get a reference to your blueprint
blueprint = ...# add the node
node = blueprint.UberGraphPages[0].graph_add_node(K2Node_MacroInstance)
# assign the macro graph to the node
node.MacroGraphReference = GraphReference(MacroGraph=for_each_loop)
# allocate pins
node.node_allocate_default_pins()# update the blueprint
ue.blueprint_mark_as_structurally_modified(bp)
Landscape/Terrain
Landscape 也是特殊单例对象(和植被一样),用 heightmap 渲染
地形支持分块,实际以 ULandscapeComponent 为单位渲染,每个 ULandscapeComponent 存一小块 heightmap texture 引用
python 里 heightmap 对应到 bytearray 来操作
创建 heightmap,创建 landscape 并指定 heightmap,设置地形大小,分块粒度(存在 ULandscapeInfo)
其他导出 SM_ 等略
width = 1024
height = 1024
heightmap = []for y in range(0, height):for x in range(0, width):heightmap.append(random.randint(0, 65535))data = struct.pack('{0}H'.format(width * height), *heightmap)quads_per_section = 63
number_of_sections = 1
components_x = 8
components_y = 8fixed_data = ue.heightmap_expand(data, width, height, quads_per_section * number_of_sections * components_x + 1, quads_per_section * number_of_sections * components_y + 1)landscape = ue.get_editor_world().actor_spawn(Landscape)
landscape.landscape_import(quads_per_section, number_of_sections, components_x, components_y, fixed_data)
landscape.set_actor_scale(1,1,1)
Level & World
编辑器下理解 level 很重要
- level 和 world 的区别,level 是静态容器,world 是动态容器,两个都是存 actor 列表
创建 .umap
factory = WorldFactory()
new_world = factory.factory_create_new('/Game/Maps/FooLevel')
spawn 一些 actor 到 world 里
# create a world (it will be the main one, the one you load into the editor by double clicking it)
main_world = factory.factory_create_new('/Game/MapsTest/MainWorld001')
# spawn actors in the world
actor0 = main_world.actor_spawn(PlayerStart)# create another world
child_world1 = factory.factory_create_new('/Game/MapsTest/ChildWorld001')
# spawn actors in the world
actor1 = child_world1.actor_spawn(Actor)
actor2 = child_world1.actor_spawn(Actor)
actor3 = child_world1.actor_spawn(Actor)# create another world
child_world2 = factory.factory_create_new('/Game/MapsTest/ChildWorld002')
# spawn actors in the world
actor4 = child_world2.actor_spawn(Actor)# now the important part, each UWorld, has a ULevel mapped to it (the PersistentLevel):
main_level = main_world.PersistentLevel
child_level1 = child_world1.PersistentLevel
child_level2 = child_world2.PersistentLevel# open main world in the editor
ue.open_editor_for_asset(main_world)
level 面板里,sub-level 和 level-streaming 的概念
added_streaming_level = ue.add_level_to_world(main_world, child_world1.get_path_name()[, always_loaded])
添加一个 sub-level(用 path),指定 ULevelStreaming StreamingMode
这个存在 main-level 的 TArray<TObjectPtr<ULevelStreaming>> StreamingLevels
// todo double check
ULevelStreaming* ue_add_level_to_world(UWorld* u_world, const FString& name, bool isAlwaysLoaded)
{if (!u_world){// Handle error: argument is not a UWorldreturn nullptr;}if (!FPackageName::DoesPackageExist(*name, nullptr)){// Handle error: package does not existreturn nullptr;}UClass* streaming_mode_class = ULevelStreamingDynamic::StaticClass();if (isAlwaysLoaded){streaming_mode_class = ULevelStreamingAlwaysLoaded::StaticClass();}ULevelStreaming* level_streaming = nullptr;
#if ENGINE_MAJOR_VERSION == 5 || (ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 17)level_streaming = EditorLevelUtils::AddLevelToWorld(u_world, *name, streaming_mode_class);
#elselevel_streaming = EditorLevelUtils::AddLevelToWorld(u_world, *name, streaming_mode_class);
#endifif (!level_streaming){// Handle error: unable to add level to the worldreturn nullptr;}#if ENGINE_MAJOR_VERSION == 5 || (ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 16)FEditorDelegates::RefreshLevelBrowser.Broadcast();
#endifreturn level_streaming;
}
CurrentLevel
是编辑器下当前正在编辑的 level(focus),可以切 level,编辑器所有 actor 操作都是在这个 level 进行
# get a reference to the current level
current_level = ue.get_editor_world().get_current_level()# change the current level
ue.get_editor_world().set_current_level(child_level1)# spawn an actor in editor world, but effectively it will be spawned
# in a child level
actor001 = ue.get_editor_world().actor_spawn(actor001)# back to the original level
ue.get_editor_world().set_current_level(current_level)