Skip to content

Python Examples ​

For full control of the Simplygon workflow you can export a set of meshes (actors, components and static meshes) directly from Unreal Engine into a Simplygon scene, and then have access to the full suite of tools in Simplygon for processing. The processed Simplygon scene can be imported into Unreal (as actors or static meshes), that can be used either as a replacement of the original, a combined static mesh which can be hooked up as a stand in runtime replacement, or as hierarchical LOD replacement. In this section, we present a few short examples of how to export a scene from Unreal to Simplygon, or import a scene into Unreal from Simplygon.

The examples are located in:

  • Content → Python → simplygon_export_import_examples.py
  • Content → Python → simplygon_merge_actors_example.py

The managed-scene examples in simplygon_export_import_examples.py export geometry, capture material channels or append landscape clipping geometry, and save one scene. See Managed Scene Export and Capture for the settings and data conventions used by these workflows.

Note

The Simplygon Subsystem is an Editor Subsystem. This means it is only available for Editor Utility Blueprints or Editor Utility Widgets.

Export Examples ​

Export example for exporting selected Actors into a Simplygon .sgscene file using a callback to report when the export process has finished.

Actors ​

py
# Export example for exporting selected Actors using a callback.
def export_actors_example():
    """Example for exporting actors from a level and get the result via a callback."""
    simplygon_subsystem = unreal.get_editor_subsystem(unreal.SimplygonSubsystem)
    simplygon_subsystem.on_export_scene_completed.add_callable(on_export_completed)

    # Get actors to export.
    EAS = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
    selected_actors = EAS.get_selected_level_actors()

    # The target file path of where the exported Simplygon scene will be saved.
    export_file_path = (
        unreal.Paths.project_intermediate_dir()
        + "/Simplygon/"
        + "PythonExportActorsExampleCallback.sgscene"
    )

    # Call export function which will call the callback once it's finished.
    simplygon_subsystem.export_actors_to_scene(
        export_file_path, selected_actors, get_default_scene_export_settings(True)
    )

Static Mesh Components ​

py
# Export example for exporting Static Mesh Components using a callback.
def export_components_example(add_components):
    """Example for exporting static mesh components and get the result via a callback."""
    simplygon_subsystem = unreal.get_editor_subsystem(unreal.SimplygonSubsystem)
    simplygon_subsystem.on_export_scene_completed.add_callable(on_export_completed)

    static_mesh_components = []
    if add_components:
        static_mesh_components = setup_components()

    # The target file path of where the exported Simplygon scene will be saved.
    export_file_path = (
        unreal.Paths.project_intermediate_dir()
        + "/Simplygon/"
        + "PythonExportComponentsExampleCallback.sgscene"
    )

    simplygon_subsystem.export_static_mesh_components_to_scene(
        export_file_path,
        static_mesh_components,
        get_default_scene_export_settings(True),
    )

Static Mesh ​

py
# Export example for exporting Static Mesh using a callback.
def export_mesh_example(setup_mesh, mesh_path):
    """Example for exporting a mesh and get the result via a callback."""
    simplygon_subsystem = unreal.get_editor_subsystem(unreal.SimplygonSubsystem)
    simplygon_subsystem.on_export_scene_completed.add_callable(on_export_completed)

    mesh_to_export = None
    if setup_mesh:
        mesh_to_export = get_static_mesh_from_path(mesh_path)

    # The target file path of where the exported Simplygon scene will be saved.
    export_file_path = (
        unreal.Paths.project_intermediate_dir()
        + "/Simplygon/"
        + "PythonExportMeshExampleCallback.sgscene"
    )

    simplygon_subsystem.export_static_mesh_to_scene(
        export_file_path, mesh_to_export, get_default_mesh_export_settings(True)
    )

Managed Scene Capture ​

Select one or more actors with static mesh components, then call managed_scene_capture_selected_components_example(). Pass include_landscape_clipping=True to also extract intersecting landscape geometry and append it to ClippingGeometrySet before camera generation and capture. Only landscape proxies with Use Landscape for Culling Invisible HLOD Vertices (bUseLandscapeForCullingInvisibleHLODVertices) enabled contribute geometry.

python
# Export and capture the selected components.
managed_scene_capture_selected_components_example()

# Also append intersecting landscape clipping geometry before capture.
managed_scene_capture_selected_components_example(include_landscape_clipping=True)

The workflow retains its context and components, filters shared completion delegates by job ID, and writes the resulting scene to the project's Intermediate/Simplygon directory. When processing a scene containing the optional landscape geometry, enable clipping geometry and use ClippingGeometrySet as the clipping geometry selection-set name. The example uses preview-world capture. For source-world capture and its lighting/LOD rules, see Choose a capture world.

Scene Export Manifest ​

The scene export manifest examples are located in Content → Python → scene_export_manifest_examples.py. They build manifests that the scene export commandlet later uses to export Simplygon scenes in a separate process.

Selected actors and a static mesh ​

Select one or more saved actors with static mesh components, then call scene_export_manifest_example(mesh_path, manifest_file_path). The example adds a scene of the selected actors with baked materials and landscape clipping geometry, and a scene of a static mesh.

py
# Example for building a scene export manifest that a scene export commandlet can process later.
def scene_export_manifest_example(mesh_path, manifest_file_path):
    """Example for describing selected actors and a static mesh as scenes in a scene export manifest."""
    # Actors must be saved in a saved map, since the manifest references them by actor GUID and level package.
    EAS = unreal.get_editor_subsystem(unreal.EditorActorSubsystem)
    selected_actors = EAS.get_selected_level_actors()

    manifest = unreal.SimplygonSceneExportManifestBuilder.create()
    output_directory = unreal.Paths.project_saved_dir() + "Simplygon/ManifestExample/"

    # Paths are stored as absolute paths. Relative paths follow the Unreal convention, like the ones from unreal.Paths.
    # Failures raise a RuntimeError with the reason.
    manifest.add_actor_scene(
        "SelectedActors",
        output_directory + "SelectedActors.sgscene",
        selected_actors,
        get_default_scene_export_settings(True),
    )

    # Adds landscape geometry inside the bounds of the selected actors as clipping geometry.
    # allow_empty lets the export succeed when no landscape intersects the actors.
    manifest.add_landscape_clipping(
        "SelectedActors", unreal.LandscapeCullingPrecision.MEDIUM, allow_empty=True
    )

    manifest.add_static_mesh_scene(
        "Mesh",
        output_directory + "Mesh.sgscene",
        get_static_mesh_from_path(mesh_path),
        get_default_mesh_export_settings(True),
    )

    manifest.save_to_file(manifest_file_path)
    unreal.log(
        f"Scene export manifest with scenes {list(manifest.get_scene_names())} saved to {manifest_file_path}"
    )

World Partition grid cells with splatter casters ​

Open a saved World Partition world, then call scene_export_manifest_world_partition_example(manifest_file_path). The example lists the world's actors without loading them and adds one scene per grid cell. Each scene exports geometry only, with landscape clipping geometry and a splatter caster capture, set up for remeshing with a splatter caster. This is useful for generating proxies of large areas, for example HLODs.

py
# Example for building a scene export manifest for a whole World Partition world without loading its actors.
def scene_export_manifest_world_partition_example(manifest_file_path, cell_size=25600.0, view_distance=100.0):
    """Example for splitting the actors of the open World Partition world into one scene per grid cell, set up for
    remeshing with splatter casters like the Remeshing HLOD builder."""
    # The actors are read from World Partition's saved actor descriptors, so unloaded actors are included and no actors
    # are loaded. Unsaved changes are not captured, so save the world first.
    world = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem).get_editor_world()

    # The default filter skips actors that can not be exported, such as HLOD actors, landscapes, and Level Instance
    # actors. The actors inside Level Instances are listed instead.
    # Failures raise a RuntimeError with the reason.
    actor_filter = unreal.SgSceneExportManifestWorldPartitionActorFilter()
    manifest_world_partition_actors = (
        unreal.SimplygonSceneExportManifestBuilder.get_manifest_world_partition_actors(world, actor_filter)
    )

    # Groups the actors in grid cells by the center of their saved bounds.
    cells = {}
    for manifest_world_partition_actor in manifest_world_partition_actors:
        bounds = manifest_world_partition_actor.editor_bounds
        cell_x = math.floor((bounds.min.x + bounds.max.x) * 0.5 / cell_size)
        cell_y = math.floor((bounds.min.y + bounds.max.y) * 0.5 / cell_size)
        cells.setdefault(f"Cell_X{cell_x}_Y{cell_y}", []).append(manifest_world_partition_actor)

    # Splatter casters bake materials from the captured images, so only the geometry is exported.
    export_settings = unreal.SgSceneExportSettings()
    export_settings.general_export_settings.overwrite_existing_file = True
    export_settings.component_export_settings.apply_vertex_colors_from_component = False
    mesh_export_settings = export_settings.mesh_export_settings
    mesh_export_settings.material_export_mode = unreal.SgMaterialExportMode.NONE
    mesh_export_settings.geometry_export_settings.export_tex_coords = False
    mesh_export_settings.geometry_export_settings.export_normals = False
    mesh_export_settings.geometry_export_settings.export_tangents = False
    mesh_export_settings.geometry_export_settings.export_vertex_colors = False

    manifest = unreal.SimplygonSceneExportManifestBuilder.create()
    output_directory = unreal.Paths.project_saved_dir() + "Simplygon/ManifestWorldPartitionExample/"
    for scene_name, cell_actors in sorted(cells.items()):
        manifest.add_actor_scene_from_world_partition_actors(
            scene_name,
            output_directory + scene_name + ".sgscene",
            world,
            cell_actors,
            export_settings,
        )

        # The clipping bounds are computed from the saved bounds of the cell's actors.
        manifest.add_landscape_clipping(
            scene_name, unreal.LandscapeCullingPrecision.MEDIUM, allow_empty=True
        )

        # Renders the cell's components from cameras around them when the scene is exported. view_distance is the
        # expected viewing distance in world units (centimeters).
        manifest.add_splatter_caster_capture(scene_name, view_distance)

    manifest.save_to_file(manifest_file_path)
    unreal.log(
        f"Scene export manifest with {len(cells)} scenes from {len(manifest_world_partition_actors)} actors saved to "
        f"{manifest_file_path}"
    )

Import Examples ​

Import example which imports a Simplygon .sgscene file into Unreal, and uses a callback to report when the import process has finished.

Actors ​

py
# Import example spawning imported actors into the current editor world using a callback.
def import_actors_example(import_scene_path, tex_coord_name):
    """Import example spawning imported actors into the current editor world using a callback."""
    simplygon_subsystem = unreal.get_editor_subsystem(unreal.SimplygonSubsystem)
    simplygon_subsystem.on_import_scene_completed.add_callable(on_import_completed)

    # Get world to spawn imported actors into.
    editor_subsystem = unreal.get_editor_subsystem(unreal.UnrealEditorSubsystem)
    world = editor_subsystem.get_editor_world()

    # Set import settings to use.
    import_settings = unreal.SgSceneImportSettings()
    import_settings.geometry_settings.tex_coord_names = [tex_coord_name]

    # Call import function which will call the callback once it's finished.
    simplygon_subsystem.import_scene_as_actors(
        import_scene_path, world, import_settings
    )

Static Meshes ​

py
# Import example for importing a scene as static meshes using a callback.
def import_meshes_example(import_scene_path, tex_coord_name):
    """Import example that imports meshes as static meshes."""
    simplygon_subsystem = unreal.get_editor_subsystem(unreal.SimplygonSubsystem)
    simplygon_subsystem.on_import_scene_completed.add_callable(on_import_completed)

    # Set import settings to use.
    import_settings = unreal.SgSceneImportSettings()
    import_settings.geometry_settings.tex_coord_names = [tex_coord_name]

    # Call import function which will call the callback once it's finished.
    simplygon_subsystem.import_scene_as_static_meshes(
        import_scene_path, import_settings
    )

Merge Actor Examples ​

An example workflow for scripting a merging tool can be found in the simplygon_merge_actors_example.py. It runs the full workflow, starting at exporting the selected actors, then running a Simplygon pipeline and finally importing the processed result. The example is quite extensive and it is therefore only the starting points that are added as examples below.

Merging using aggregation ​

py
def merge_selected_actors(bakeMaterials: bool = False):
    merge_tool = SgMergeActorsTool()
    merge_tool.merge_selected_actors(EMergeType.AGGREGATION, bakeMaterials)

Merging using remeshing for proxies in the distance ​

py
def create_proxy_actor_from_selected_actors():
    merge_tool = SgMergeActorsTool()
    merge_tool.merge_selected_actors(EMergeType.REMESHING, True)