Creating a soft-body simulation#

This tutorial shows how to create a soft-body simulation using SimulationManager. It covers the setup of the simulation context, adding a deformable mesh (soft object), and running the simulation loop.

The Code#

The tutorial corresponds to the create_softbody.py script in the scripts/tutorials/sim directory.

Code for create_softbody.py
  1# ----------------------------------------------------------------------------
  2# Copyright (c) 2021-2026 DexForce Technology Co., Ltd.
  3#
  4# Licensed under the Apache License, Version 2.0 (the "License");
  5# you may not use this file except in compliance with the License.
  6# You may obtain a copy of the License at
  7#
  8#     http://www.apache.org/licenses/LICENSE-2.0
  9#
 10# Unless required by applicable law or agreed to in writing, software
 11# distributed under the License is distributed on an "AS IS" BASIS,
 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13# See the License for the specific language governing permissions and
 14# limitations under the License.
 15# ----------------------------------------------------------------------------
 16
 17"""
 18This script demonstrates how to create a simulation scene using SimulationManager.
 19It shows the basic setup of simulation context, adding objects, lighting, and sensors.
 20"""
 21
 22import argparse
 23import time
 24from dexsim.utility.path import get_resources_data_path
 25from embodichain.lab.sim import SimulationManager, SimulationManagerCfg
 26from embodichain.lab.gym.utils.gym_utils import add_env_launcher_args_to_parser
 27from embodichain.lab.sim.cfg import (
 28    RenderCfg,
 29    SoftbodyVoxelAttributesCfg,
 30    SoftbodyPhysicalAttributesCfg,
 31)
 32from embodichain.lab.sim.shapes import MeshCfg
 33from embodichain.lab.sim.objects import (
 34    SoftObject,
 35    SoftObjectCfg,
 36)
 37
 38
 39def main():
 40    """Main function to create and run the simulation scene."""
 41
 42    # Parse command line arguments
 43    parser = argparse.ArgumentParser(
 44        description="Create a simulation scene with SimulationManager"
 45    )
 46    add_env_launcher_args_to_parser(parser)
 47    args = parser.parse_args()
 48
 49    # Configure the simulation
 50    sim_cfg = SimulationManagerCfg(
 51        width=1920,
 52        height=1080,
 53        headless=True,
 54        num_envs=args.num_envs,
 55        physics_dt=1.0 / 100.0,  # Physics timestep (100 Hz)
 56        sim_device="cuda",  # soft simulation only supports cuda device
 57        render_cfg=RenderCfg(
 58            renderer=args.renderer
 59        ),  # Enable ray tracing for better visuals
 60    )
 61
 62    # Create the simulation instance
 63    sim = SimulationManager(sim_cfg)
 64
 65    print("[INFO]: Scene setup complete!")
 66
 67    # add softbody to the scene
 68    cow: SoftObject = sim.add_soft_object(
 69        cfg=SoftObjectCfg(
 70            uid="cow",
 71            shape=MeshCfg(
 72                fpath=get_resources_data_path("Model", "cow", "cow.obj"),
 73            ),
 74            init_pos=[0.0, 0.0, 3.0],
 75            voxel_attr=SoftbodyVoxelAttributesCfg(
 76                simulation_mesh_resolution=8,
 77                maximal_edge_length=0.5,
 78            ),
 79            physical_attr=SoftbodyPhysicalAttributesCfg(
 80                youngs=1e6,
 81                poissons=0.45,
 82                density=100,
 83                dynamic_friction=0.1,
 84                min_position_iters=30,
 85            ),
 86        ),
 87    )
 88    print("[INFO]: Add soft object complete!")
 89
 90    # Open window when the scene has been set up
 91    if not args.headless:
 92        sim.open_window()
 93
 94    print(f"[INFO]: Running simulation with {args.num_envs} environment(s)")
 95    print("[INFO]: Press Ctrl+C to stop the simulation")
 96
 97    # Run the simulation
 98    run_simulation(sim, cow)
 99
100
101def run_simulation(sim: SimulationManager, soft_obj: SoftObject) -> None:
102    """Run the simulation loop.
103
104    Args:
105        sim: The SimulationManager instance to run
106        soft_obj: soft object
107    """
108
109    # Initialize GPU physics
110    sim.init_gpu_physics()
111
112    step_count = 0
113
114    try:
115        last_time = time.time()
116        last_step = 0
117        while True:
118            # Update physics simulation
119            sim.update(step=1)
120            step_count += 1
121
122            # Print FPS every second
123            if step_count % 100 == 0:
124                current_time = time.time()
125                elapsed = current_time - last_time
126                fps = (
127                    sim.num_envs * (step_count - last_step) / elapsed
128                    if elapsed > 0
129                    else 0
130                )
131                print(f"[INFO]: Simulation step: {step_count}, FPS: {fps:.2f}")
132                last_time = current_time
133                last_step = step_count
134                if step_count % 500 == 0:
135                    soft_obj.reset()
136
137    except KeyboardInterrupt:
138        print("\n[INFO]: Stopping simulation...")
139    finally:
140        # Clean up resources
141        sim.destroy()
142        print("[INFO]: Simulation terminated successfully")
143
144
145if __name__ == "__main__":
146    main()

The Code Explained#

Configuring the simulation#

The first step is to configure the simulation environment. This is done using the SimulationManagerCfg data class, which allows you to specify parameters like window dimensions, headless mode, physics timestep, simulation device (CPU/GPU), and rendering options like ray tracing. Reminded that soft body simulation can only run on cuda deive.

    # Configure the simulation
    sim_cfg = SimulationManagerCfg(
        width=1920,
        height=1080,
        headless=True,
        num_envs=args.num_envs,
        physics_dt=1.0 / 100.0,  # Physics timestep (100 Hz)
        sim_device="cuda",  # soft simulation only supports cuda device
        render_cfg=RenderCfg(
            renderer=args.renderer
        ),  # Enable ray tracing for better visuals
    )

    # Create the simulation instance
    sim = SimulationManager(sim_cfg)

    print("[INFO]: Scene setup complete!")

Adding a soft body to the scene#

With the simulation context created, we can add a soft (deformable) object. This tutorial demonstrates adding a soft-body cow mesh to the scene using the SimulationManager.add_soft_object() method. The object’s geometry and physical parameters are defined through configuration objects:

    # add softbody to the scene
    cow: SoftObject = sim.add_soft_object(
        cfg=SoftObjectCfg(
            uid="cow",
            shape=MeshCfg(
                fpath=get_resources_data_path("Model", "cow", "cow.obj"),
            ),
            init_pos=[0.0, 0.0, 3.0],
            voxel_attr=SoftbodyVoxelAttributesCfg(
                simulation_mesh_resolution=8,
                maximal_edge_length=0.5,
            ),
            physical_attr=SoftbodyPhysicalAttributesCfg(
                youngs=1e6,
                poissons=0.45,
                density=100,
                dynamic_friction=0.1,
                min_position_iters=30,
            ),
        ),
    )
    print("[INFO]: Add soft object complete!")

The Code Execution#

To run the script and see the result, execute the following command:

python scripts/tutorials/sim/create_softbody.py

A window should appear showing a soft-body cow mesh falling onto a ground plane. To stop the simulation, you can either close the window or press Ctrl+C in the terminal.

You can also pass arguments to customize the simulation. For example, to run in headless mode with n parallel environments using the specified device:

python scripts/tutorials/sim/create_softbody.py --headless --num_envs <n> --device <cuda/cpu>

Now that we have a basic understanding of how to create a soft-body scene, let’s move on to more advanced topics.