Changing the Scene#

Your program can change the scene while it runs: add an object, remove one, or change a setting such as a body’s mass. You make the change in the ovstage stage, then tell ovphysx to apply it.

A timeline from 0 to 2 s starts with ordinal 1 sealed, and a box falls and lands on the ground. At 1 s, the simulation pauses while the program creates /World/Box2 directly in the stage at ordinal 2, seals ordinal 2, and calls update_from_ovstage(2, 2). Only then does the second box appear in the simulation and fall.

Three Steps#

With a scene attached, every change uses a new ordinal, the edit number from Concepts:

  1. Edit the stage at an ordinal higher than any ordinal you sealed before.

  2. Seal that ordinal with stage.advance_write_floor.

  3. Apply the edits: wait for the task of physx.update_from_ovstage(first, last), which takes the range of new ordinals.

Seal before you update. An update reads only sealed edits, and ovphysx does not read an ordinal again after an update has covered it.

Moving a Body Through the Stage#

For this stage-edit workflow, use a CPU scene or GPU dynamics with CPU readback (DirectGPU disabled). Edit the body’s local transform, omni:xform, then seal and apply the edit as above. omni:resetXformStack controls whether that transform inherits its parents’ transforms.

If omni:fabric:worldMatrix already exists, update it to the matching resolved world pose at the same ordinal, including any affected descendants. Population can create this column even when your application has never published it; leaving it stale can keep the body at its old pose despite the local edit.

For DirectGPU pose control, use the position and orientation writes in Writing Values, after the first step. These teleport the body. To drive a kinematic support that carries other bodies, leave DirectGPU disabled and follow Kinematic Support Geometry.

Changing only omni:fabric:worldMatrix does not move a body in physics. That column holds a derived world pose; update_from_ovstage does not treat its changes as authored movement. See Transform Inputs for the distinction between triggering an update and reading its resolved pose.

Add a Box While the Scene Runs#

This program, changing_the_scene_add_box.py, drops a box, as in Your First Simulation. Halfway through its 2 s, it creates a second box directly in the stage at ordinal 2:

The imports and the starting scene, in USD
import ovstage
from ovphysx import PhysX
from ovphysx.population import physics_population_descs
from ovphysx.population import create_rigid_body_cubes
from ovphysx.samples.python_samples.schema_support import physx_schema_paths
from ovphysx.types import SimObjectType

# A ground plane and a 1 m box whose center starts 2 m above it.
SCENE = """#usda 1.0
(
    metersPerUnit = 1
    kilogramsPerUnit = 1
    upAxis = "Z"
)

def Xform "World"
{
    def PhysicsScene "PhysicsScene" {}

    def Plane "Ground" (
        prepend apiSchemas = ["PhysicsCollisionAPI"]
    )
    {
        uniform token axis = "Z"
    }

    def Cube "Box" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI"]
    )
    {
        double size = 1
        double3 xformOp:translate = (0, 0, 2)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }
}
"""


def box_heights(physx):
    """Read the position of every rigid body and return its z, keyed by path."""
    heights = {}
    with physx.read_sync(SimObjectType.RIGID_BODY, ["position"]) as result:
        for group in result.groups:
            paths = result.dictionary.get_path_strings(group.prim_list)
            for path, position in zip(paths, group.tensors[0].numpy()):
                heights[path] = float(position[2])
    return heights


def add_second_box(stage, physx):
    """Create a 1 m box in the stage at ordinal 2, seal it, and apply it."""
    # The starting pose, a 4 by 4 matrix written row by row. Its last row
    # holds the position: 1.5 m beside the first box and 2 m up.
    start = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1.5, 0, 2, 1]
    create_rigid_body_cubes(
        stage,
        ovstage.PathDictionary(stage),  # maps path names to stage IDs
        ["/World/Box2"],
        ordinal=2,
        cube={"size": [1.0], "local_matrix": [start]},
        ancestors=False,  # /World is already in the stage
    )
    stage.advance_write_floor(ordinal=2).wait()
    physx.wait_task(physx.update_from_ovstage(2, 2))


def print_heights(time, heights):
    boxes = "  ".join(
        f"{path} z = {z:.3f} m" for path, z in sorted(heights.items())
    )
    print(f"t={time:.2f} s  {boxes}")


ovstage.population.register_usd_schemas([str(p) for p in physx_schema_paths()])

# Load the scene and seal it at ordinal 1, as in the first program.
stage = ovstage.Stage("changing_the_scene")
ovstage.population.open_usd_from_string_with_desc(
    stage,
    SCENE,
    ordinal=1,
    time=ovstage.population.DEFAULT_TIME,
    descs=physics_population_descs(rendering=True),
)
stage.advance_write_floor(ordinal=1).wait()

physx = PhysX()
physx.wait_task(physx.attach_ovstage(stage, read_ordinal=1))

print_heights(0.0, box_heights(physx))
for step in range(1, 121):
    physx.step_sync(1.0 / 60.0)
    if step == 60:  # halfway through the 2 s run
        add_second_box(stage, physx)
        print("Added /World/Box2 at ordinal 2")
    if step % 15 == 0:
        print_heights(step / 60, box_heights(physx))

physx.wait_task(physx.detach_ovstage())
physx.destroy()
stage.destroy()

It prints:

t=0.00 s  /World/Box z = 2.000 m
t=0.25 s  /World/Box z = 1.692 m
t=0.50 s  /World/Box z = 0.771 m
t=0.75 s  /World/Box z = 0.500 m
Added /World/Box2 at ordinal 2
t=1.00 s  /World/Box z = 0.500 m  /World/Box2 z = 2.000 m
t=1.25 s  /World/Box z = 0.500 m  /World/Box2 z = 1.692 m
t=1.50 s  /World/Box z = 0.500 m  /World/Box2 z = 0.771 m
t=1.75 s  /World/Box z = 0.500 m  /World/Box2 z = 0.500 m
t=2.00 s  /World/Box z = 0.500 m  /World/Box2 z = 0.500 m

Notice the following:

  • create_rigid_body_cubes from ovphysx.population writes the box straight into the stage at ordinal 2: its path, its size, and its starting pose. The pose is a 4 by 4 matrix whose last row holds the position. ancestors=False leaves the /World prim that is already in the stage as it is.

  • The box needs no mass setting: ovphysx computes its mass from its size and a default density, which gives 1,000 kg for this 1 m box. To set a mass, also pass physics_mass_api={"mass": [2.0]}.

  • Right after the update, a read returns both boxes.

Other Changes#

Every change takes the same three steps. Only the edit differs:

To

Edit the Stage With

Add an object

A helper from ovphysx.population, such as create_rigid_body_cubes

Change a value, such as physics:mass on a body with PhysicsMassAPI

stage.write_attribute, with an ovstage query for the object

Remove an object

stage.delete_attributes, with an ovstage query for the object and no attribute names

A setting changes only when the object has the schema that defines it, such as PhysicsMassAPI for physics:mass. A new mass, density, center of mass, or inertia takes effect at the next step, not at the update.

Deleting only some attributes of an object that stays, by passing attribute names to stage.delete_attributes, is not recommended: the value physics keeps for them is undefined (see Known limitations). Write the value you want instead.

Changing the Scene or Writing Values#

You can also change a running simulation by writing values, such as a velocity or a force:

Change the Scene

Write Values

Use it to

Add or remove objects, or change their settings

Move, push, or steer objects, often at every step

What changes

The stage, then the simulation

The simulation only

When ovphysx applies it

At update_from_ovstage, but a mass change takes effect at the next step

When your program commits the write

Seen by other libraries that read the stage

Yes

No

More Detail#

Next: Contacts