Zero-Copy Memory Model & View Lifetimes

This page documents only what the C++ implementation in include/joltsim/aligned_buffer.hpp, src/world.cpp, src/vec_world.cpp, and src/python/module.cpp enforces.

AlignedBuffer<T, Alignment>

State buffers in World and VecWorld are stored in joltsim::AlignedBuffer<T, Alignment> (include/joltsim/aligned_buffer.hpp):

  • State arrays (qpos_, qvel_, ctrl_, qfrc_, joint_error_, body_pos_, body_quat_, body_linvel_, body_angvel_, contacts_, contact_counts_): 64-byte aligned (Alignment = 64), allocated via ::operator new[](count * sizeof(T), std::align_val_t(kAlignment), std::nothrow) and zero-initialized on allocation.

  • Ray hit buffer (ray_hits_): 32-byte aligned (AlignedBuffer<RayHit, 32>).

  • Soft-body vertex/face buffers (vertices_world, faces): 64-byte aligned per soft body.

  • Packed structs:

    • ContactEvent: alignas(64), static_assert(sizeof(ContactEvent) == 64) (CONTACT_DTYPE).

    • RayHit: alignas(32), static_assert(sizeof(RayHit) == 32) (RAY_HIT_DTYPE).


NumPy Ownership & View Lifetime

All array properties (qpos, qvel, ctrl, qfrc_motor, joint_error, body_pos, body_quat, body_linvel, body_angvel, contacts, raycast_batch, soft_body_vertices, soft_body_faces) return nanobind NumPy ndarray views bound with nb::rv_policy::reference_internal (or owner handle on structured byte-cast views in make_contact_view, make_rayhit_view_1d, make_rayhit_view_2d).

  • Owner lifetime: Holding any NumPy view keeps the parent World or VecWorld Python object alive until the view is garbage-collected.

  • During step(), reset(), load_state(), load_keyframe(): Backing state buffers are updated in place without reallocation. Existing views of qpos, qvel, ctrl, qfrc_motor, joint_error, body_pos, body_quat, body_linvel, and body_angvel remain valid across simulation steps.

  • When views ARE invalidated:

    1. Adding scene topology (add_ground_plane, add_body, add_articulation) calls World::reallocate_buffers() or VecWorld::sync_dimensions_and_buffers(), which frees old AlignedBuffer allocations and allocates new ones. Re-fetch array properties after modifying scene topology.

    2. contacts returns a view sliced to the current contact_count() (total_contact_count() on VecWorld), which changes every step—re-read w.contacts after step().

    3. raycast_batch reallocates ray_hits_ whenever the requested ray count exceeds the previously allocated capacity.


PyTorch CUDA Transfers (torch_bridge.py)

joltsim.to_torch(array, device="cuda", non_blocking=True):

  1. Calls np.ascontiguousarray(array).

  2. Wraps it in a CPU tensor via torch.from_numpy(...).

  3. If device starts with "cuda" and torch.cuda.is_available(), transfers via .pin_memory().to(device=device, non_blocking=non_blocking).

If non_blocking=True, standard PyTorch CUDA stream ordering applies: do not mutate or free the intermediate host tensor before the CUDA stream consumes it (or synchronize via torch.cuda.synchronize()).