Fast Simulations#

ovphysx can simulate very large scenes. In the following scene, it moves 100,000 boxes along 400 conveyor belts, with all of the work on the GPU:

A factory floor of conveyor belts, each carrying a line of boxes.

These tips make a simulation run faster. Before you change anything, time a few hundred steps of your loop with time.perf_counter(), then time them again after each change. Profiling shows which calls take the time. The numbers on this page come from one computer with an NVIDIA RTX A6000. Yours will differ.

Work While a Step Runs#

step_sync waits for each step to finish. step queues the step and returns at once, so your program can do its own work while PhysX simulates:

Two timelines of four loops, measured with 4,000 boxes on the GPU. When the program waits for each step and then does 2 ms of its own work, the four loops take 18.2 ms. When it starts each step, does its work while the step runs, and then waits for the step, they take 10.2 ms, 8.0 ms sooner.

Use that time for work that does not need the new results, such as preparing the next commands. Then call wait_task(task) to report any error of the step. Calls on the same PhysX object, such as reads, wait for the queued step anyway. Because step returns at once, time whole loops, not the step call alone.

Read Many Objects at Once#

A read of 400 boxes takes about as long as a read of one box. This program, fast_simulations_reads.py, reads the positions of 400 boxes, first with one read, then with one read per box:

import time

import ovstage
from ovphysx.population import physics_population_descs
from ovphysx import PhysX
from ovphysx.samples.python_samples.schema_support import physx_schema_paths
from ovphysx.types import SimObjectType

COUNT = 400

HEADER = """#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"
    }
"""

BOX = """
    def Cube "Box{i}" (
        prepend apiSchemas = ["PhysicsRigidBodyAPI", "PhysicsCollisionAPI"]
    )
    {{
        double size = 0.5
        double3 xformOp:translate = ({x}, {y}, 1)
        uniform token[] xformOpOrder = ["xformOp:translate"]
    }}
"""

# 400 boxes in a 20 x 20 grid, 1 m apart and 1 m above the ground.
BOXES = "".join(BOX.format(i=i, x=i % 20, y=i // 20) for i in range(COUNT))
SCENE = HEADER + BOXES + "}\n"


def read_all(physx):
    """Read the positions of all boxes with one read."""
    with physx.read_sync(SimObjectType.RIGID_BODY, ["position"]) as result:
        return result.groups[0].tensors[0].numpy().copy()


def read_one(physx, i):
    """Read the position of one box."""
    with physx.read_sync(
        SimObjectType.RIGID_BODY, ["position"], pattern=f"/World/Box{i}"
    ) as result:
        return result.groups[0].tensors[0].numpy().copy()


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

stage = ovstage.Stage("fast_reads")
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))
# The first read also loads NVIDIA Warp, so time the reads after it.
read_all(physx)

start = time.perf_counter()
read_all(physx)
one_read = time.perf_counter() - start

start = time.perf_counter()
for i in range(COUNT):
    read_one(physx, i)
many_reads = time.perf_counter() - start

print(f"one read of {COUNT} boxes: {one_read * 1000:7.1f} ms")
print(f"{COUNT} reads of one box:  {many_reads * 1000:7.1f} ms")

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

It printed:

one read of 400 boxes:     0.6 ms
400 reads of one box:    135.0 ms

One read of all the boxes was more than 100 times faster than 400 small reads. To read only some objects, select them all with one pattern, as Selecting Objects shows.

More Tips#

Tip

Helps When

Read More

Simulate on the GPU.

The scene has thousands of objects. With stacked boxes, the CPU was faster at 400 boxes and the GPU at 4,000.

CPU and GPU

Keep one query and read through it at every step.

You read the same objects at every step. Each read took about a third less time.

Keeping a Query

Keep the results in GPU memory with DirectGPU, and replay repeated GPU work with a CUDA graph.

Your code works on the results on the GPU.

Data on the GPU, CUDA graphs

Use spheres, capsules, and boxes before convex hulls, and convex hulls before triangle and signed distance field (SDF) meshes.

Objects have detailed shapes. Simple shapes cost the least.

Colliders

Cap the solver iterations with physxScene:maxPositionIterationCount.

The motion still looks right with fewer. Rigid bodies use 16 by default, and a cap of 4 cut the step time of 4,000 boxes by a quarter to a third.

Physics Solver

Keep shapes from overlapping needlessly.

Every touching pair that can collide costs time. Shapes that overlap at the start also jump apart.

What to Change

More Detail#