newton.ModelBuilder#
- class newton.ModelBuilder(up_axis=Axis.Z, gravity=-9.81)[source]#
Bases:
objectA helper class for building simulation models at runtime.
Use the ModelBuilder to construct a simulation scene. The ModelBuilder represents the scene using standard Python data structures like lists, which are convenient but unsuitable for efficient simulation. Call
finalize()to construct a simulation-ready Model.Example
import newton from newton.solvers import SolverXPBD builder = newton.ModelBuilder() # anchor point (zero mass) builder.add_particle((0, 1.0, 0.0), (0.0, 0.0, 0.0), 0.0) # build chain for i in range(1, 10): builder.add_particle((i, 1.0, 0.0), (0.0, 0.0, 0.0), 1.0) builder.add_spring(i - 1, i, 1.0e3, 0.0, 0) # create model model = builder.finalize() state_0, state_1 = model.state(), model.state() control = model.control() solver = SolverXPBD(model) contacts = model.contacts() for i in range(10): state_0.clear_forces() model.collide(state_0, contacts) solver.step(state_0, state_1, control, contacts, dt=1.0 / 60.0) state_0, state_1 = state_1, state_0
World Grouping#
ModelBuilder supports world grouping to organize entities for multi-world simulations. Each entity (particle, body, shape, joint, articulation) has an associated world index:
Index -1: Global entities shared across all worlds (e.g., ground plane)
Index 0, 1, 2, …: World-specific entities
There are two ways to assign world indices:
Direct entity creation: Entities inherit the builder’s current_world value:
builder = ModelBuilder() builder.current_world = -1 # Following entities will be global builder.add_ground_plane() builder.current_world = 0 # Following entities will be in world 0 builder.add_body(...)
Using add_world(): ALL entities from the sub-builder are assigned to a new world:
robot = ModelBuilder() robot.add_body(...) # World assignments here will be overridden main = ModelBuilder() main.add_world(robot) # All robot entities -> world 0 main.add_world(robot) # All robot entities -> world 1
Note
It is strongly recommended to use the ModelBuilder to construct a simulation rather than creating your own Model object directly, however it is possible to do so if desired.
- class CustomAttribute(name, dtype, frequency, assignment=AttributeAssignment.MODEL, namespace=None, references=None, default=None, values=None, usd_attribute_name=None, mjcf_attribute_name=None, urdf_attribute_name=None, usd_value_transformer=None, mjcf_value_transformer=None, urdf_value_transformer=None)#
Bases:
objectRepresents a custom attribute definition for the ModelBuilder. This is used to define custom attributes that are not part of the standard ModelBuilder API. Custom attributes can be defined for the
Model,State,Control, orContactsobjects, depending on theModel.AttributeAssignmentcategory. Custom attributes must be declared before use via thenewton.ModelBuilder.add_custom_attribute()method.See Custom Attributes for more information.
- __init__(name, dtype, frequency, assignment=AttributeAssignment.MODEL, namespace=None, references=None, default=None, values=None, usd_attribute_name=None, mjcf_attribute_name=None, urdf_attribute_name=None, usd_value_transformer=None, mjcf_value_transformer=None, urdf_value_transformer=None)#
- build_array(count, device=None, requires_grad=False)#
Build wp.array (or list for string dtype) from count, dtype, default and overrides.
For string dtype, returns a Python list[str] instead of a Warp array.
- assignment: AttributeAssignment = 0#
Assignment category (see
Model.AttributeAssignment), defaults toModel.AttributeAssignment.MODEL
- dtype: type#
Warp dtype (e.g., wp.float32, wp.int32, wp.bool, wp.vec3) that is compatible with Warp arrays, or
strfor string attributes that remain as Python lists.
- frequency: AttributeFrequency | str#
Frequency category that determines how the attribute is indexed in the Model.
- Can be either:
A
Model.AttributeFrequencyenum value for built-in frequencies (BODY, SHAPE, JOINT, etc.) Uses dict-based storage where keys are entity indices, allowing sparse assignment.A string for custom frequencies (e.g.,
"mujoco:pair"). Uses list-based storage for sequential data appended viaadd_custom_values(). All attributes sharing the same custom frequency must have the same count, validated at finalize time.
- property frequency_key: AttributeFrequency | str#
Return the resolved frequency, with namespace prepended for custom string frequencies.
For string frequencies: returns “namespace:frequency” if namespace is set, otherwise just “frequency”. For enum frequencies: returns the enum value unchanged.
- property is_custom_frequency: bool#
Check if this attribute uses a custom (string) frequency.
- Returns:
True if the frequency is a string (custom frequency), False if it’s a Model.AttributeFrequency enum (built-in frequency like BODY, SHAPE, etc.).
- class JointDofConfig(axis=Axis.X, limit_lower=-MAXVAL, limit_upper=MAXVAL, limit_ke=1e4, limit_kd=1e1, target_pos=0.0, target_vel=0.0, target_ke=0.0, target_kd=0.0, armature=1e-2, effort_limit=1e6, velocity_limit=1e6, friction=0.0, actuator_mode=None)#
Bases:
objectDescribes a joint axis (a single degree of freedom) that can have limits and be driven towards a target.
- classmethod create_unlimited(axis)#
Creates a JointDofConfig with no limits.
- __init__(axis=Axis.X, limit_lower=-MAXVAL, limit_upper=MAXVAL, limit_ke=1e4, limit_kd=1e1, target_pos=0.0, target_vel=0.0, target_ke=0.0, target_kd=0.0, armature=1e-2, effort_limit=1e6, velocity_limit=1e6, friction=0.0, actuator_mode=None)#
- actuator_mode#
Actuator mode for this DOF. Determines which actuators are installed (see
ActuatorMode). If None, the mode is inferred from gains and targets.
- armature#
Artificial inertia added around the joint axis. Defaults to 1e-2.
- axis#
The 3D joint axis in the joint parent anchor frame.
- effort_limit#
Maximum effort (force or torque) the joint axis can exert. Defaults to 1e6.
- friction#
Friction coefficient for the joint axis. Defaults to 0.0.
- limit_kd#
The damping stiffness of the joint axis limits. Defaults to 1e1.
- limit_ke#
The elastic stiffness of the joint axis limits. Defaults to 1e4.
- limit_lower#
The lower position limit of the joint axis. Defaults to -MAXVAL (unlimited).
- limit_upper#
The upper position limit of the joint axis. Defaults to MAXVAL (unlimited).
- target_kd#
The derivative gain of the target drive PD controller. Defaults to 0.0.
- target_ke#
The proportional gain of the target drive PD controller. Defaults to 0.0.
- target_pos#
The target position of the joint axis. If the initial target_pos is outside the limits, it defaults to the midpoint of limit_lower and limit_upper. Otherwise, defaults to 0.0.
- target_vel#
The target velocity of the joint axis.
- velocity_limit#
Maximum velocity the joint axis can achieve. Defaults to 1e6.
- class ShapeConfig(density=1000.0, ke=2500.0, kd=100.0, kf=1000.0, ka=0.0, mu=0.5, restitution=0.0, torsional_friction=0.25, rolling_friction=0.0005, thickness=1e-05, contact_margin=None, is_solid=True, collision_group=1, collision_filter_parent=True, has_shape_collision=True, has_particle_collision=True, is_visible=True, is_site=False, sdf_narrow_band_range=(-0.1, 0.1), sdf_target_voxel_size=None, sdf_max_resolution=None, is_hydroelastic=False, k_hydro=10000000000.0)#
Bases:
objectRepresents the properties of a collision shape used in simulation.
- __init__(density=1000.0, ke=2500.0, kd=100.0, kf=1000.0, ka=0.0, mu=0.5, restitution=0.0, torsional_friction=0.25, rolling_friction=0.0005, thickness=1e-05, contact_margin=None, is_solid=True, collision_group=1, collision_filter_parent=True, has_shape_collision=True, has_particle_collision=True, is_visible=True, is_site=False, sdf_narrow_band_range=(-0.1, 0.1), sdf_target_voxel_size=None, sdf_max_resolution=None, is_hydroelastic=False, k_hydro=10000000000.0)#
- mark_as_site()#
Marks this shape as a site and enforces all site invariants.
Sets: - is_site = True - has_shape_collision = False - has_particle_collision = False - density = 0.0 - collision_group = 0
- validate()#
Validate ShapeConfig parameters.
- collision_filter_parent: bool = True#
Whether to inherit collision filtering from the parent. Defaults to True.
- collision_group: int = 1#
The collision group ID for the shape. Defaults to 1 (default group). Set to 0 to disable collisions for this shape.
- has_particle_collision: bool = True#
Whether the shape can collide with particles. Defaults to True.
- has_shape_collision: bool = True#
Whether the shape can collide with other shapes. Defaults to True.
- is_hydroelastic: bool = False#
Whether the shape collides using SDF-based hydroelastics. For hydroelastic collisions, both participating shapes must have is_hydroelastic set to True. Defaults to False.
Note
Hydroelastic collision handling only works with volumetric shapes and in particular will not work for shapes like flat meshes or cloth. This flag will be automatically set to False for planes and heightfields in
ModelBuilder.add_shape().
- is_site: bool = False#
Indicates whether the shape is a site (non-colliding reference point). Directly setting this to True will NOT enforce site invariants. Use mark_as_site() or set via the flags property to ensure invariants. Defaults to False.
- is_visible: bool = True#
Indicates whether the shape is visible in the simulation. Defaults to True.
- k_hydro: float = 10000000000.0#
Contact stiffness coefficient for hydroelastic collisions. Used by MuJoCo, Featherstone, SemiImplicit when is_hydroelastic is True.
Note
For MuJoCo, stiffness values will internally be scaled by masses. Users should choose k_hydro to match their desired force-to-penetration ratio.
- restitution: float = 0.0#
The coefficient of restitution. Used by XPBD. To take effect, enable restitution in solver constructor via
enable_restitution=True.
- rolling_friction: float = 0.0005#
The coefficient of rolling friction (resistance to rolling motion). Used by XPBD, MuJoCo.
- sdf_narrow_band_range: tuple[float, float] = (-0.1, 0.1)#
The narrow band distance range (inner, outer) for SDF computation. Only used for mesh shapes when SDF is enabled.
- __init__(up_axis=Axis.Z, gravity=-9.81)#
Initializes a new ModelBuilder instance for constructing simulation models.
- Parameters:
up_axis (AxisType, optional) – The axis to use as the “up” direction in the simulation. Defaults to Axis.Z.
gravity (float, optional) – The magnitude of gravity to apply along the up axis. Defaults to -9.81.
- add_articulation(joints, key=None, custom_attributes=None)#
Adds an articulation to the model from a list of joint indices.
The articulation is a set of joints that must be contiguous and monotonically increasing. Some functions, such as forward kinematics
newton.eval_fk(), are parallelized over articulations.- Parameters:
joints (list[int]) – List of joint indices to include in the articulation. Must be contiguous and monotonic.
key (str | None) – The key of the articulation. If None, a default key will be created.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for ARTICULATION frequency attributes.
- Raises:
ValueError – If joints are not contiguous, not monotonic, or belong to different worlds.
Example
link1 = builder.add_link(...) link2 = builder.add_link(...) link3 = builder.add_link(...) joint1 = builder.add_joint_revolute(parent=-1, child=link1) joint2 = builder.add_joint_revolute(parent=link1, child=link2) joint3 = builder.add_joint_revolute(parent=link2, child=link3) # Create articulation from the joints builder.add_articulation([joint1, joint2, joint3])
- add_body(xform=None, armature=None, com=None, inertia=None, mass=0.0, key=None, custom_attributes=None, lock_inertia=False)#
Adds a stand-alone free-floating rigid body to the model.
This is a convenience method that creates a single-body articulation with a free joint, allowing the body to move freely in 6 degrees of freedom. Internally, this method calls:
add_link()to create the bodyadd_joint_free()to add a free joint connecting the body to the worldadd_articulation()to create a new articulation from the joint
For creating articulations with multiple linked bodies, use
add_link(), the appropriate joint methods, andadd_articulation()directly.- Parameters:
xform (tuple[list[float] | tuple[float, float, float] | vec3f, list[float] | tuple[float, float, float, float] | quatf] | transformf | None) – The location of the body in the world frame.
armature (float | None) – Artificial inertia added to the body. If None, the default value from
default_body_armatureis used.com (list[float] | tuple[float, float, float] | vec3f | None) – The center of mass of the body w.r.t its origin. If None, the center of mass is assumed to be at the origin.
inertia (list[float] | mat33f | None) – The 3x3 inertia tensor of the body (specified relative to the center of mass). If None, the inertia tensor is assumed to be zero.
mass (float) – Mass of the body.
key (str | None) – Key of the body. When provided, the auto-created free joint and articulation are assigned keys
{key}_free_jointand{key}_articulationrespectively.custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
lock_inertia (bool) – If True, prevents subsequent shape additions from modifying this body’s mass, center of mass, or inertia. This does not affect merging behavior in
collapse_fixed_joints(), which always accumulates mass and inertia across merged bodies.
- Returns:
The index of the body in the model.
- Return type:
Note
If the mass is zero then the body is treated as kinematic with no dynamics.
- add_builder(builder, xform=None)#
Copies the data from another ModelBuilder into this ModelBuilder.
All entities from the source builder are added to this builder’s current world context (the value of self.current_world). Any world assignments that existed in the source builder are overwritten - all entities will be assigned to the current world.
Example:
main_builder = ModelBuilder() sub_builder = ModelBuilder() sub_builder.add_body(...) sub_builder.add_shape_box(...) # Adds all entities from sub_builder to main_builder's current world (-1 by default) main_builder.add_builder(sub_builder) # With transform main_builder.add_builder(sub_builder, xform=wp.transform((1, 0, 0)))
- Parameters:
builder (ModelBuilder) – The model builder to copy data from.
xform (Transform) – Optional offset transform applied to root bodies.
- add_cloth_grid(pos, rot, vel, dim_x, dim_y, cell_x, cell_y, mass, reverse_winding=False, fix_left=False, fix_right=False, fix_top=False, fix_bottom=False, tri_ke=None, tri_ka=None, tri_kd=None, tri_drag=None, tri_lift=None, edge_ke=None, edge_kd=None, add_springs=False, spring_ke=None, spring_kd=None, particle_radius=None, custom_attributes_particles=None, custom_attributes_edges=None, custom_attributes_triangles=None)#
Helper to create a regular planar cloth grid
Creates a rectangular grid of particles with FEM triangles and bending elements automatically.
- Parameters:
pos (list[float] | tuple[float, float, float] | vec3f) – The position of the cloth in world space
rot (list[float] | tuple[float, float, float, float] | quatf) – The orientation of the cloth in world space
vel (list[float] | tuple[float, float, float] | vec3f) – The velocity of the cloth in world space
dim_x (int) – The number of rectangular cells along the x-axis
dim_y (int) – The number of rectangular cells along the y-axis
cell_x (float) – The width of each cell in the x-direction
cell_y (float) – The width of each cell in the y-direction
mass (float) – The mass of each particle
reverse_winding (bool) – Flip the winding of the mesh
fix_left (bool) – Make the left-most edge of particles kinematic (fixed in place)
fix_right (bool) – Make the right-most edge of particles kinematic
fix_top (bool) – Make the top-most edge of particles kinematic
fix_bottom (bool) – Make the bottom-most edge of particles kinematic
- add_cloth_mesh(pos, rot, scale, vel, vertices, indices, density, tri_ke=None, tri_ka=None, tri_kd=None, tri_drag=None, tri_lift=None, edge_ke=None, edge_kd=None, add_springs=False, spring_ke=None, spring_kd=None, particle_radius=None, custom_attributes_particles=None, custom_attributes_edges=None, custom_attributes_triangles=None, custom_attributes_springs=None)#
Helper to create a cloth model from a regular triangle mesh
Creates one FEM triangle element and one bending element for every face and edge in the input triangle mesh
- Parameters:
pos (list[float] | tuple[float, float, float] | vec3f) – The position of the cloth in world space
rot (list[float] | tuple[float, float, float, float] | quatf) – The orientation of the cloth in world space
vel (list[float] | tuple[float, float, float] | vec3f) – The velocity of the cloth in world space
vertices (list[list[float] | tuple[float, float, float] | vec3f]) – A list of vertex positions
indices (list[int]) – A list of triangle indices, 3 entries per-face
density (float) – The density per-area of the mesh
particle_radius (float | None) – The particle_radius which controls particle based collisions.
custom_attributes_particles (dict[str, Any] | None) – Dictionary of custom attribute names to values for the particles.
custom_attributes_edges (dict[str, Any] | None) – Dictionary of custom attribute names to values for the edges.
custom_attributes_triangles (dict[str, Any] | None) – Dictionary of custom attribute names to values for the triangles.
custom_attributes_springs (dict[str, Any] | None) – Dictionary of custom attribute names to values for the springs.
Note
The mesh should be two-manifold.
- add_constraint_mimic(joint0, joint1, coef0=0.0, coef1=1.0, enabled=True, key=None, custom_attributes=None)#
Adds a mimic constraint to the model.
A mimic constraint enforces that
joint0 = coef0 + coef1 * joint1, following URDF mimic joint semantics. Both scalar (prismatic, revolute) and multi-DOF joints are supported. For multi-DOF joints, the mimic behavior is applied equally to all degrees of freedom.- Parameters:
joint0 (int) – Index of the follower joint (the one being constrained)
joint1 (int) – Index of the leader joint (the one being mimicked)
coef0 (float) – Offset added after scaling
coef1 (float) – Scale factor applied to joint1’s position/angle
enabled (bool) – Whether constraint is active
key (str | None) – Optional constraint name
custom_attributes (dict[str, Any] | None) – Custom attributes to set on the constraint
- Returns:
Constraint index
- Return type:
- add_custom_attribute(attribute)#
Define a custom per-entity attribute to be added to the Model. See Custom Attributes for more information.
- Parameters:
attribute (CustomAttribute) – The custom attribute to add.
Example
builder = newton.ModelBuilder() builder.add_custom_attribute( newton.ModelBuilder.CustomAttribute( name="my_attribute", frequency=newton.Model.AttributeFrequency.BODY, dtype=wp.float32, default=20.0, assignment=newton.Model.AttributeAssignment.MODEL, namespace="my_namespace", ) ) builder.add_body(custom_attributes={"my_namespace:my_attribute": 30.0}) builder.add_body() # we leave out the custom_attributes, so the attribute will use the default value 20.0 model = builder.finalize() # the model has now a Model.AttributeNamespace object with the name "my_namespace" # and an attribute "my_attribute" that is a wp.array of shape (body_count, 1) # with the default value 20.0 assert np.allclose(model.my_namespace.my_attribute.numpy(), [30.0, 20.0])
- add_custom_values(**kwargs)#
Append values to custom attributes with custom string frequencies.
Each keyword argument specifies an attribute key and the value to append. Values are stored in a list and appended sequentially for robust indexing. Only works with attributes that have a custom string frequency (not built-in enum frequencies).
This is useful for custom entity types that aren’t built into the model, such as user-defined groupings or solver-specific data.
- Parameters:
**kwargs (Any) – Mapping of attribute keys to values. Keys should be the full attribute key (e.g.,
"mujoco:pair_geom1"or just"my_attr"if no namespace).- Returns:
Dict mapping attribute keys to the index where each value was added. If all attributes had the same count before the call, all indices will be equal.
- Raises:
AttributeError – If an attribute key is not defined.
TypeError – If an attribute has an enum frequency (must have custom frequency).
- Return type:
Example
builder.add_custom_values( **{ "mujoco:pair_geom1": 0, "mujoco:pair_geom2": 1, "mujoco:pair_world": builder.current_world, } ) # Returns: {'mujoco:pair_geom1': 0, 'mujoco:pair_geom2': 0, 'mujoco:pair_world': 0}
- add_edge(i, j, k, l, rest=None, edge_ke=None, edge_kd=None, custom_attributes=None)#
Adds a bending edge element between two adjacent triangles in the cloth mesh, defined by four vertices.
The bending energy model follows the discrete shell formulation from [Grinspun et al. 2003]. The bending stiffness is controlled by the edge_ke parameter, and the bending damping by the edge_kd parameter.
- Parameters:
i (int) – The index of the first particle, i.e., opposite vertex 0
j (int) – The index of the second particle, i.e., opposite vertex 1
k (int) – The index of the third particle, i.e., vertex 0
l (int) – The index of the fourth particle, i.e., vertex 1
rest (float | None) – The rest angle across the edge in radians, if not specified it will be computed
edge_ke (float | None) – The bending stiffness coefficient
edge_kd (float | None) – The bending damping coefficient
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The index of the edge.
- Return type:
Note
The edge lies between the particles indexed by ‘k’ and ‘l’ parameters with the opposing vertices indexed by ‘i’ and ‘j’. This defines two connected triangles with counterclockwise winding: (i, k, l), (j, l, k).
- add_edges(i, j, k, l, rest=None, edge_ke=None, edge_kd=None, custom_attributes=None)#
Adds bending edge elements between two adjacent triangles in the cloth mesh, defined by four vertices.
The bending energy model follows the discrete shell formulation from [Grinspun et al. 2003]. The bending stiffness is controlled by the edge_ke parameter, and the bending damping by the edge_kd parameter.
- Parameters:
i (list[int]) – The indices of the first particles, i.e., opposite vertex 0
j (list[int]) – The indices of the second particles, i.e., opposite vertex 1
k (list[int]) – The indices of the third particles, i.e., vertex 0
l (list[int]) – The indices of the fourth particles, i.e., vertex 1
rest (list[float] | None) – The rest angles across the edges in radians, if not specified they will be computed
edge_ke (list[float] | None) – The bending stiffness coefficients
edge_kd (list[float] | None) – The bending damping coefficients
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
Note
The edge lies between the particles indexed by ‘k’ and ‘l’ parameters with the opposing vertices indexed by ‘i’ and ‘j’. This defines two connected triangles with counterclockwise winding: (i, k, l), (j, l, k).
- add_equality_constraint(constraint_type, body1=-1, body2=-1, anchor=None, torquescale=None, relpose=None, joint1=-1, joint2=-1, polycoef=None, key=None, enabled=True, custom_attributes=None)#
Generic method to add any type of equality constraint to this ModelBuilder.
- Parameters:
constraint_type (constant) – Type of constraint (‘connect’, ‘weld’, ‘joint’)
body1 (int) – Index of the first body participating in the constraint (-1 for world)
body2 (int) – Index of the second body participating in the constraint (-1 for world)
anchor (Vec3) – Anchor point on body1
torquescale (float) – Scales the angular residual for weld
relpose (Transform) – Relative pose of body2 for weld. If None, the identity transform is used.
joint1 (int) – Index of the first joint for joint coupling
joint2 (int) – Index of the second joint for joint coupling
polycoef (list[float]) – Polynomial coefficients for joint coupling
key (str) – Optional constraint name
enabled (bool) – Whether constraint is active
custom_attributes (dict) – Custom attributes to set on the constraint
- Returns:
Constraint index
- Return type:
- add_equality_constraint_connect(body1=-1, body2=-1, anchor=None, key=None, enabled=True, custom_attributes=None)#
Adds a connect equality constraint to the model. This constraint connects two bodies at a point. It effectively defines a ball joint outside the kinematic tree.
- Parameters:
body1 (int) – Index of the first body participating in the constraint (-1 for world)
body2 (int) – Index of the second body participating in the constraint (-1 for world)
anchor (list[float] | tuple[float, float, float] | vec3f | None) – Anchor point on body1
key (str | None) – Optional constraint name
enabled (bool) – Whether constraint is active
custom_attributes (dict[str, Any] | None) – Custom attributes to set on the constraint
- Returns:
Constraint index
- Return type:
- add_equality_constraint_joint(joint1=-1, joint2=-1, polycoef=None, key=None, enabled=True, custom_attributes=None)#
Adds a joint equality constraint to the model. Constrains the position or angle of one joint to be a quartic polynomial of another joint. Only scalar joint types (prismatic and revolute) can be used.
- Parameters:
joint1 (int) – Index of the first joint
joint2 (int) – Index of the second joint
polycoef (list[float] | None) – Polynomial coefficients for joint coupling
key (str | None) – Optional constraint name
enabled (bool) – Whether constraint is active
custom_attributes (dict[str, Any] | None) – Custom attributes to set on the constraint
- Returns:
Constraint index
- Return type:
- add_equality_constraint_weld(body1=-1, body2=-1, anchor=None, torquescale=None, relpose=None, key=None, enabled=True, custom_attributes=None)#
Adds a weld equality constraint to the model. Attaches two bodies to each other, removing all relative degrees of freedom between them (softly).
- Parameters:
body1 (int) – Index of the first body participating in the constraint (-1 for world)
body2 (int) – Index of the second body participating in the constraint (-1 for world)
anchor (list[float] | tuple[float, float, float] | vec3f | None) – Coordinates of the weld point relative to body2
torquescale (float | None) – Scales the angular residual for weld
relpose (Transform) – Relative pose of body2 relative to body1. If None, the identity transform is used
key (str | None) – Optional constraint name
enabled (bool) – Whether constraint is active
custom_attributes (dict[str, Any] | None) – Custom attributes to set on the constraint
- Returns:
Constraint index
- Return type:
- add_ground_plane(height=0.0, cfg=None, key=None)#
Adds a ground plane collision shape to the model.
- Parameters:
height (float) – The vertical offset of the ground plane along the up-vector axis. Positive values raise the plane, negative values lower it. Defaults to 0.0.
cfg (ShapeConfig | None) – The configuration for the shape’s physical and collision properties. If None,
default_shape_cfgis used. Defaults to None.key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
- Returns:
The index of the newly added shape.
- Return type:
- add_joint(joint_type, parent, child, linear_axes=None, angular_axes=None, key=None, parent_xform=None, child_xform=None, collision_filter_parent=True, enabled=True, custom_attributes=None)#
Generic method to add any type of joint to this ModelBuilder.
- Parameters:
joint_type (JointType) – The type of joint to add (see Joint types).
parent (int) – The index of the parent body (-1 is the world).
child (int) – The index of the child body.
linear_axes (list(
JointDofConfig)) – The linear axes (seeJointDofConfig) of the joint, defined in the joint parent anchor frame.angular_axes (list(
JointDofConfig)) – The angular axes (seeJointDofConfig) of the joint, defined in the joint parent anchor frame.key (str) – The key of the joint (optional).
parent_xform (Transform) – The transform from the parent body frame to the joint parent anchor frame. If None, the identity transform is used.
child_xform (Transform) – The transform from the child body frame to the joint child anchor frame. If None, the identity transform is used.
collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled (not considered by
SolverFeatherstone).custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute keys (see
CustomAttribute.key) to values. Note that custom attributes with frequencyModel.AttributeFrequency.JOINT_DOForModel.AttributeFrequency.JOINT_COORDcan be provided as: (1) lists with length equal to the joint’s DOF or coordinate count, (2) dicts mapping DOF/coordinate indices to values, or (3) scalar values for single-DOF/single-coordinate joints (automatically expanded to lists). Custom attributes with frequencyModel.AttributeFrequency.JOINTrequire a single value to be defined.
- Returns:
The index of the added joint.
- Return type:
- add_joint_ball(parent, child, parent_xform=None, child_xform=None, armature=None, friction=None, key=None, collision_filter_parent=True, enabled=True, custom_attributes=None, actuator_mode=None)#
Adds a ball (spherical) joint to the model. Its position is defined by a 4D quaternion (xyzw) and its velocity is a 3D vector.
- Parameters:
parent (int) – The index of the parent body.
child (int) – The index of the child body.
parent_xform (Transform) – The transform from the parent body frame to the joint parent anchor frame.
child_xform (Transform) – The transform from the child body frame to the joint child anchor frame.
armature (float | None) – Artificial inertia added around the joint axes. If None, the default value from
default_joint_armatureis used.friction (float | None) – Friction coefficient for the joint axes. If None, the default value from
default_joint_cfg.frictionis used.key (str | None) – The key of the joint.
collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for JOINT, JOINT_DOF, or JOINT_COORD frequency attributes.
actuator_mode (ActuatorMode | None) – The actuator mode for this joint’s DOFs. If None, defaults to NONE.
- Returns:
The index of the added joint.
- Return type:
Note
Target position and velocity control for ball joints is currently only supported in
newton.solvers.SolverMuJoCo.
- add_joint_cable(parent, child, parent_xform=None, child_xform=None, stretch_stiffness=None, stretch_damping=None, bend_stiffness=None, bend_damping=None, key=None, collision_filter_parent=True, enabled=True, custom_attributes=None, **kwargs)#
Adds a cable joint to the model. It has two degrees of freedom: one linear (stretch) that constrains the distance between the attachment points, and one angular (bend/twist) that penalizes the relative rotation of the attachment frames.
Note
Cable joints are supported by
newton.solvers.SolverVBD, which uses an AVBD backend for rigid bodies. For cable joints, the stretch and bend behavior is defined by the parent/child attachment transforms; the joint axis stored inJointDofConfigis not currently used directly.- Parameters:
parent (int) – The index of the parent body.
child (int) – The index of the child body.
parent_xform (Transform) – The transform from the parent body frame to the joint parent anchor frame; its translation is the attachment point.
child_xform (Transform) – The transform from the child body frame to the joint child anchor frame; its translation is the attachment point.
stretch_stiffness (float | None) – Cable stretch stiffness (stored as
target_ke) [N/m]. If None, defaults to 1.0e9.stretch_damping (float | None) – Cable stretch damping (stored as
target_kd). Innewton.solvers.SolverVBDthis is a dimensionless (Rayleigh-style) coefficient. If None, defaults to 0.0.bend_stiffness (float | None) – Cable bend/twist stiffness (stored as
target_ke) [N*m] (torque per radian). If None, defaults to 0.0.bend_damping (float | None) – Cable bend/twist damping (stored as
target_kd). Innewton.solvers.SolverVBDthis is a dimensionless (Rayleigh-style) coefficient. If None, defaults to 0.0.key (str | None) – The key of the joint.
collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for JOINT, JOINT_DOF, or JOINT_COORD frequency attributes.
- Returns:
The index of the added joint.
- Return type:
- add_joint_d6(parent, child, linear_axes=None, angular_axes=None, key=None, parent_xform=None, child_xform=None, collision_filter_parent=True, enabled=True, custom_attributes=None, **kwargs)#
Adds a generic joint with custom linear and angular axes. The number of axes determines the number of degrees of freedom of the joint.
- Parameters:
parent (int) – The index of the parent body.
child (int) – The index of the child body.
linear_axes (Sequence[JointDofConfig] | None) – A list of linear axes.
angular_axes (Sequence[JointDofConfig] | None) – A list of angular axes.
key (str | None) – The key of the joint.
parent_xform (Transform) – The transform from the parent body frame to the joint parent anchor frame.
child_xform (Transform) – The transform from the child body frame to the joint child anchor frame.
armature – Artificial inertia added around the joint axes. If None, the default value from
default_joint_armatureis used.collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for JOINT, JOINT_DOF, or JOINT_COORD frequency attributes.
- Returns:
The index of the added joint.
- Return type:
- add_joint_distance(parent, child, parent_xform=None, child_xform=None, min_distance=-1.0, max_distance=1.0, collision_filter_parent=True, enabled=True, custom_attributes=None)#
Adds a distance joint to the model. The distance joint constraints the distance between the joint anchor points on the two bodies (see Forward / Inverse Kinematics) it connects to the interval [min_distance, max_distance]. It has 7 positional degrees of freedom (first 3 linear and then 4 angular dimensions for the orientation quaternion in xyzw notation) and 6 velocity degrees of freedom (first 3 linear and then 3 angular velocity dimensions).
- Parameters:
parent (int) – The index of the parent body.
child (int) – The index of the child body.
parent_xform (Transform) – The transform of the joint in the parent body’s local frame.
child_xform (Transform) – The transform of the joint in the child body’s local frame.
min_distance (float) – The minimum distance between the bodies (no limit if negative).
max_distance (float) – The maximum distance between the bodies (no limit if negative).
collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for JOINT, JOINT_DOF, or JOINT_COORD frequency attributes.
- Returns:
The index of the added joint.
- Return type:
Note
Distance joints are currently only supported in
newton.solvers.SolverXPBD.
- add_joint_fixed(parent, child, parent_xform=None, child_xform=None, key=None, collision_filter_parent=True, enabled=True, custom_attributes=None)#
Adds a fixed (static) joint to the model. It has no degrees of freedom. See
collapse_fixed_joints()for a helper function that removes these fixed joints and merges the connecting bodies to simplify the model and improve stability.- Parameters:
parent (int) – The index of the parent body.
child (int) – The index of the child body.
parent_xform (Transform) – The transform of the joint in the parent body’s local frame.
child_xform (Transform) – The transform of the joint in the child body’s local frame.
key (str | None) – The key of the joint.
collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for JOINT frequency attributes.
- Returns:
The index of the added joint
- Return type:
- add_joint_free(child, parent_xform=None, child_xform=None, parent=-1, key=None, collision_filter_parent=True, enabled=True, custom_attributes=None)#
Adds a free joint to the model. It has 7 positional degrees of freedom (first 3 linear and then 4 angular dimensions for the orientation quaternion in xyzw notation) and 6 velocity degrees of freedom (see Twist conventions in Newton). The positional dofs are initialized by the child body’s transform (see
body_qand thexformargument toadd_body()).- Parameters:
child (int) – The index of the child body.
parent_xform (Transform) – The transform of the joint in the parent body’s local frame.
child_xform (Transform) – The transform of the joint in the child body’s local frame.
parent (int) – The index of the parent body (-1 by default to use the world frame, e.g. to make the child body and its children a floating-base mechanism).
key (str | None) – The key of the joint.
collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for JOINT, JOINT_DOF, or JOINT_COORD frequency attributes.
- Returns:
The index of the added joint.
- Return type:
- add_joint_prismatic(parent, child, parent_xform=None, child_xform=None, axis=Axis.X, target_pos=None, target_vel=None, target_ke=None, target_kd=None, limit_lower=None, limit_upper=None, limit_ke=None, limit_kd=None, armature=None, effort_limit=None, velocity_limit=None, friction=None, actuator_mode=None, key=None, collision_filter_parent=True, enabled=True, custom_attributes=None)#
Adds a prismatic (sliding) joint to the model. It has one degree of freedom.
- Parameters:
parent (int) – The index of the parent body.
child (int) – The index of the child body.
parent_xform (Transform) – The transform from the parent body frame to the joint parent anchor frame.
child_xform (Transform) – The transform from the child body frame to the joint child anchor frame.
axis (AxisType | Vec3 | JointDofConfig) – The axis of translation in the joint parent anchor frame, which is the parent body’s local frame transformed by parent_xform. It can be a
JointDofConfigobject whose settings will be used instead of the other arguments.target_pos (float | None) – The target position of the joint.
target_vel (float | None) – The target velocity of the joint.
target_ke (float | None) – The stiffness of the joint target.
target_kd (float | None) – The damping of the joint target.
limit_lower (float | None) – The lower limit of the joint. If None, the default value from
default_joint_limit_loweris used.limit_upper (float | None) – The upper limit of the joint. If None, the default value from
default_joint_limit_upperis used.limit_ke (float | None) – The stiffness of the joint limit. If None, the default value from
default_joint_limit_keis used.limit_kd (float | None) – The damping of the joint limit. If None, the default value from
default_joint_limit_kdis used.armature (float | None) – Artificial inertia added around the joint axis. If None, the default value from
default_joint_armatureis used.effort_limit (float | None) – Maximum effort (force) the joint axis can exert. If None, the default value from
default_joint_cfg.effort_limitis used.velocity_limit (float | None) – Maximum velocity the joint axis can achieve. If None, the default value from
default_joint_cfg.velocity_limitis used.friction (float | None) – Friction coefficient for the joint axis. If None, the default value from
default_joint_cfg.frictionis used.key (str | None) – The key of the joint.
collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for JOINT, JOINT_DOF, or JOINT_COORD frequency attributes.
- Returns:
The index of the added joint.
- Return type:
- add_joint_revolute(parent, child, parent_xform=None, child_xform=None, axis=None, target_pos=None, target_vel=None, target_ke=None, target_kd=None, limit_lower=None, limit_upper=None, limit_ke=None, limit_kd=None, armature=None, effort_limit=None, velocity_limit=None, friction=None, actuator_mode=None, key=None, collision_filter_parent=True, enabled=True, custom_attributes=None, **kwargs)#
Adds a revolute (hinge) joint to the model. It has one degree of freedom.
- Parameters:
parent (int) – The index of the parent body.
child (int) – The index of the child body.
parent_xform (Transform) – The transform from the parent body frame to the joint parent anchor frame.
child_xform (Transform) – The transform from the child body frame to the joint child anchor frame.
axis (AxisType | Vec3 | JointDofConfig) – The axis of rotation in the joint parent anchor frame, which is the parent body’s local frame transformed by parent_xform. It can be a
JointDofConfigobject whose settings will be used instead of the other arguments.target_pos (float | None) – The target position of the joint.
target_vel (float | None) – The target velocity of the joint.
target_ke (float | None) – The stiffness of the joint target.
target_kd (float | None) – The damping of the joint target.
limit_lower (float | None) – The lower limit of the joint. If None, the default value from
default_joint_limit_loweris used.limit_upper (float | None) – The upper limit of the joint. If None, the default value from
default_joint_limit_upperis used.limit_ke (float | None) – The stiffness of the joint limit. If None, the default value from
default_joint_limit_keis used.limit_kd (float | None) – The damping of the joint limit. If None, the default value from
default_joint_limit_kdis used.armature (float | None) – Artificial inertia added around the joint axis. If None, the default value from
default_joint_armatureis used.effort_limit (float | None) – Maximum effort (force/torque) the joint axis can exert. If None, the default value from
default_joint_cfg.effort_limitis used.velocity_limit (float | None) – Maximum velocity the joint axis can achieve. If None, the default value from
default_joint_cfg.velocity_limitis used.friction (float | None) – Friction coefficient for the joint axis. If None, the default value from
default_joint_cfg.frictionis used.key (str | None) – The key of the joint.
collision_filter_parent (bool) – Whether to filter collisions between shapes of the parent and child bodies.
enabled (bool) – Whether the joint is enabled.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for JOINT, JOINT_DOF, or JOINT_COORD frequency attributes.
- Returns:
The index of the added joint.
- Return type:
- add_link(xform=None, armature=None, com=None, inertia=None, mass=0.0, key=None, custom_attributes=None, lock_inertia=False)#
Adds a link (rigid body) to the model within an articulation.
This method creates a link without automatically adding a joint. To connect this link to the articulation structure, you must explicitly call one of the joint methods (e.g.,
add_joint_revolute(),add_joint_fixed(), etc.) after creating the link.After calling this method and one of the joint methods, ensure that an articulation is created using
add_articulation().- Parameters:
xform (tuple[list[float] | tuple[float, float, float] | vec3f, list[float] | tuple[float, float, float, float] | quatf] | transformf | None) – The location of the body in the world frame.
armature (float | None) – Artificial inertia added to the body. If None, the default value from
default_body_armatureis used.com (list[float] | tuple[float, float, float] | vec3f | None) – The center of mass of the body w.r.t its origin. If None, the center of mass is assumed to be at the origin.
inertia (list[float] | mat33f | None) – The 3x3 inertia tensor of the body (specified relative to the center of mass). If None, the inertia tensor is assumed to be zero.
mass (float) – Mass of the body.
key (str | None) – Key of the body (optional).
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
lock_inertia (bool) – If True, prevents subsequent shape additions from modifying this body’s mass, center of mass, or inertia. This does not affect merging behavior in
collapse_fixed_joints(), which always accumulates mass and inertia across merged bodies.
- Returns:
The index of the body in the model.
- Return type:
Note
If the mass is zero then the body is treated as kinematic with no dynamics.
- add_mjcf(source, *, xform=None, floating=None, base_joint=None, parent_body=-1, armature_scale=1.0, scale=1.0, hide_visuals=False, parse_visuals_as_colliders=False, parse_meshes=True, parse_sites=True, parse_visuals=True, parse_mujoco_options=True, up_axis=Axis.Z, ignore_names=(), ignore_classes=(), visual_classes=('visual',), collider_classes=('collision',), no_class_as_colliders=True, force_show_colliders=False, enable_self_collisions=True, ignore_inertial_definitions=False, ensure_nonstatic_links=True, static_link_mass=1e-2, collapse_fixed_joints=False, verbose=False, skip_equality_constraints=False, convert_3d_hinge_to_ball_joints=False, mesh_maxhullvert=None, ctrl_direct=False, path_resolver=None)#
Parses MuJoCo XML (MJCF) file and adds the bodies and joints to the given ModelBuilder. MuJoCo-specific custom attributes are registered on the builder automatically.
- Parameters:
source (str) – The filename of the MuJoCo file to parse, or the MJCF XML string content.
xform (Transform) – The transform to apply to the imported mechanism.
floating (bool or None) –
Controls the base joint type for the root body.
None(default): Uses format-specific default (honors<freejoint>tags in MJCF, otherwise creates a FIXED joint).True: Creates a FREE joint with 6 DOF (3 translation + 3 rotation). Only valid whenparent_body == -1since FREE joints must connect to world frame.False: Creates a FIXED joint (0 DOF).
Cannot be specified together with
base_joint.base_joint (dict) –
Custom joint specification for connecting the root body to the world (or to
parent_bodyif specified). This parameter enables hierarchical composition with custom mobility. Dictionary with joint parameters as accepted byModelBuilder.add_joint()(e.g., joint type, axes, limits, stiffness).Cannot be specified together with
floating.parent_body (int) –
Parent body index for hierarchical composition. If specified, attaches the imported root body to this existing body, making them part of the same kinematic articulation. The connection type is determined by
floatingorbase_joint. If-1(default), the root connects to the world frame. Restriction: Only the most recently added articulation can be used as parent; attempting to attach to an older articulation will raise aValueError.Note
Valid combinations of
floating,base_joint, andparent_body:floating
base_joint
parent_body
Result
NoneNone-1Format default (MJCF: honors
<freejoint>, else FIXED)TrueNone-1FREE joint to world (6 DOF)
FalseNone-1FIXED joint to world (0 DOF)
None{dict}-1Custom joint to world (e.g., D6)
FalseNonebody_idxFIXED joint to parent body
None{dict}body_idxCustom joint to parent body (e.g., D6)
explicitly set
explicitly set
any
❌ Error: mutually exclusive (cannot specify both)
TrueNonebody_idx❌ Error: FREE joints require world frame
armature_scale (float) – Scaling factor to apply to the MJCF-defined joint armature values.
scale (float) – The scaling factor to apply to the imported mechanism.
hide_visuals (bool) – If True, hide visual shapes after loading them (affects visibility, not loading).
parse_visuals_as_colliders (bool) – If True, the geometry defined under the visual_classes tags is used for collision handling instead of the collider_classes geometries.
parse_meshes (bool) – Whether geometries of type “mesh” should be parsed. If False, geometries of type “mesh” are ignored.
parse_sites (bool) – Whether sites (non-colliding reference points) should be parsed. If False, sites are ignored.
parse_visuals (bool) – Whether visual geometries (non-collision shapes) should be loaded. If False, visual shapes are not loaded (different from hide_visuals which loads but hides them). Default is True.
parse_mujoco_options (bool) – Whether solver options from the MJCF <option> tag should be parsed. If False, solver options are not loaded and custom attributes retain their default values. Default is True.
up_axis (AxisType) – The up axis of the MuJoCo scene. The default is Z up.
ignore_names (Sequence[str]) – A list of regular expressions. Bodies and joints with a name matching one of the regular expressions will be ignored.
ignore_classes (Sequence[str]) – A list of regular expressions. Bodies and joints with a class matching one of the regular expressions will be ignored.
visual_classes (Sequence[str]) – A list of regular expressions. Visual geometries with a class matching one of the regular expressions will be parsed.
collider_classes (Sequence[str]) – A list of regular expressions. Collision geometries with a class matching one of the regular expressions will be parsed.
no_class_as_colliders (bool) – If True, geometries without a class are parsed as collision geometries. If False, geometries without a class are parsed as visual geometries.
force_show_colliders (bool) – If True, the collision shapes are always shown, even if there are visual shapes.
enable_self_collisions (bool) – If True, self-collisions are enabled.
ignore_inertial_definitions (bool) – If True, the inertial parameters defined in the MJCF are ignored and the inertia is calculated from the shape geometry.
ensure_nonstatic_links (bool) – If True, links with zero mass are given a small mass (see static_link_mass) to ensure they are dynamic.
static_link_mass (float) – The mass to assign to links with zero mass (if ensure_nonstatic_links is set to True).
collapse_fixed_joints (bool) – If True, fixed joints are removed and the respective bodies are merged.
verbose (bool) – If True, print additional information about parsing the MJCF.
skip_equality_constraints (bool) – Whether <equality> tags should be parsed. If True, equality constraints are ignored.
convert_3d_hinge_to_ball_joints (bool) – If True, series of three hinge joints are converted to a single ball joint. Default is False.
mesh_maxhullvert (int) – Maximum vertices for convex hull approximation of meshes.
ctrl_direct (bool) – If True, all actuators use
CTRL_DIRECTmode where control comes directly fromcontrol.mujoco.ctrl(MuJoCo-native behavior). See Custom Attributes for details on custom attributes. If False (default), position/velocity actuators useJOINT_TARGETmode where control comes fromnewton.Control.joint_target_posandnewton.Control.joint_target_vel.path_resolver (Callable) – Callback to resolve file paths. Takes (base_dir, file_path) and returns a resolved path. For <include> elements, can return either a file path or XML content directly. For asset elements (mesh, texture, etc.), must return an absolute file path. The default resolver joins paths and returns absolute file paths.
- add_muscle(bodies, positions, f0, lm, lt, lmax, pen)#
Adds a muscle-tendon activation unit.
- Parameters:
bodies (list[int]) – A list of body indices for each waypoint
positions (list[list[float] | tuple[float, float, float] | vec3f]) – A list of positions of each waypoint in the body’s local frame
f0 (float) – Force scaling
lm (float) – Muscle length
lt (float) – Tendon length
lmax (float) – Maximally efficient muscle length
pen (float) – Penalty factor
- Returns:
The index of the muscle in the model
- Return type:
Note
The simulation support for muscles is in progress and not yet fully functional.
- add_particle(pos, vel, mass, radius=None, flags=ParticleFlags.ACTIVE, custom_attributes=None)#
Adds a single particle to the model.
- Parameters:
pos (list[float] | tuple[float, float, float] | vec3f) – The initial position of the particle.
vel (list[float] | tuple[float, float, float] | vec3f) – The initial velocity of the particle.
mass (float) – The mass of the particle.
radius (float | None) – The radius of the particle used in collision handling. If None, the radius is set to the default value (
default_particle_radius).flags (int) – The flags that control the dynamical behavior of the particle, see
newton.ParticleFlags.custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
Note
Set the mass equal to zero to create a ‘kinematic’ particle that is not subject to dynamics.
- Returns:
The index of the particle in the system.
- Return type:
- add_particle_grid(pos, rot, vel, dim_x, dim_y, dim_z, cell_x, cell_y, cell_z, mass, jitter, radius_mean=None, radius_std=0.0, flags=None, custom_attributes=None)#
Adds a regular 3D grid of particles to the model.
This helper function creates a grid of particles arranged in a rectangular lattice, with optional random jitter and per-particle radius variation. The grid is defined by its dimensions along each axis and the spacing between particles.
- Parameters:
pos (list[float] | tuple[float, float, float] | vec3f) – The world-space position of the grid origin.
rot (list[float] | tuple[float, float, float, float] | quatf) – The rotation to apply to the grid (as a quaternion).
vel (list[float] | tuple[float, float, float] | vec3f) – The initial velocity to assign to each particle.
dim_x (int) – Number of particles along the X axis.
dim_y (int) – Number of particles along the Y axis.
dim_z (int) – Number of particles along the Z axis.
cell_x (float) – Spacing between particles along the X axis.
cell_y (float) – Spacing between particles along the Y axis.
cell_z (float) – Spacing between particles along the Z axis.
mass (float) – Mass to assign to each particle.
jitter (float) – Maximum random offset to apply to each particle position.
radius_mean (float | None) – Mean radius for particles. If None, uses the builder’s default.
radius_std (float) – Standard deviation for particle radii. If > 0, radii are sampled from a normal distribution.
flags (list[int] | int | None) – Flags to assign to each particle. If None, uses the builder’s default.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values for the particles.
- Returns:
None
- add_particles(pos, vel, mass, radius=None, flags=None, custom_attributes=None)#
Adds a group of particles to the model.
- Parameters:
pos (list[list[float] | tuple[float, float, float] | vec3f]) – The initial positions of the particles.
vel (list[list[float] | tuple[float, float, float] | vec3f]) – The initial velocities of the particles.
radius (list[float] | None) – The radius of the particles used in collision handling. If None, the radius is set to the default value (
default_particle_radius).flags (list[int] | None) – The flags that control the dynamical behavior of the particles, see
newton.ParticleFlags.custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to lists of values (one value for each particle).
Note
Set the mass equal to zero to create a ‘kinematic’ particle that is not subject to dynamics.
- add_rod(positions, quaternions=None, radius=0.1, cfg=None, stretch_stiffness=None, stretch_damping=None, bend_stiffness=None, bend_damping=None, closed=False, key=None, wrap_in_articulation=True)#
Adds a rod composed of capsule bodies connected by cable joints.
Constructs a chain of capsule bodies from the given centerline points and orientations. Each segment is a capsule aligned by the corresponding quaternion, and adjacent capsules are connected by cable joints providing one linear (stretch) and one angular (bend/twist) degree of freedom.
- Parameters:
positions (list[Vec3]) – Centerline node positions (segment endpoints) in world space. These are the tip/end points of the capsules, with one extra point so that for
Nsegments there areN+1positions.quaternions (list[Quat] | None) – Optional per-segment (per-edge) orientations in world space. If provided, must have
len(positions) - 1elements and each quaternion should align the capsule’s local +Z with the segment directionpositions[i+1] - positions[i]. If None, orientations are computed automatically to align +Z with each segment direction.radius (float) – Capsule radius.
cfg (ShapeConfig | None) – Shape configuration for the capsules. If None,
default_shape_cfgis used.stretch_stiffness (float | None) – Stretch stiffness for the cable joints. For rods, this is treated as a material-like axial/shear stiffness (commonly interpreted as EA) with units [N] and is internally converted to an effective point stiffness [N/m] by dividing by segment length. If None, defaults to 1.0e9.
stretch_damping (float | None) – Stretch damping for the cable joints (applied per-joint; not length-normalized). If None, defaults to 0.0.
bend_stiffness (float | None) – Bend/twist stiffness for the cable joints. For rods, this is treated as a material-like bending/twist stiffness (e.g., EI) with units [N*m^2] and is internally converted to an effective per-joint stiffness [N*m] (torque per radian) by dividing by segment length. If None, defaults to 0.0.
bend_damping (float | None) – Bend/twist damping for the cable joints (applied per-joint; not length-normalized). If None, defaults to 0.0.
closed (bool) – If True, connects the last segment back to the first to form a closed loop. If False, creates an open chain. Note: rods require at least 2 segments.
key (str | None) – Optional key prefix for bodies, shapes, and joints.
wrap_in_articulation (bool) – If True, the created joints are automatically wrapped into a single articulation. Defaults to True to ensure valid simulation models.
- Returns:
(body_indices, joint_indices). For an open chain,
len(joint_indices) == num_segments - 1; for a closed loop,len(joint_indices) == num_segments.- Return type:
- Articulations:
By default (
wrap_in_articulation=True), the created joints are wrapped into a single articulation, which avoids orphan joints duringfinalize(). Ifwrap_in_articulation=False, this method will return the created joint indices but will not wrap them; callers must place them into one or more articulations (viaadd_articulation()) before callingfinalize().
- Raises:
ValueError – If
positionsandquaternionslengths are incompatible.ValueError – If the rod has fewer than 2 segments.
Note
Bend defaults are 0.0 (no bending resistance unless specified). Stretch defaults to a high stiffness (1.0e9), which keeps neighboring capsules closely coupled (approximately inextensible).
Internally, stretch and bend stiffnesses are pre-scaled by dividing by segment length so solver kernels do not need per-segment length normalization.
Damping values are passed through as provided (per joint) and are not length-normalized.
Each segment is implemented as a capsule primitive. The segment’s body transform is placed at the start point
positions[i]with a local center-of-mass offset of(0, 0, half_height)so that the COM lies at the segment midpoint. The capsule shape is added with a local transform of(0, 0, half_height)so it spans from the start to the end along local +Z.
- add_rod_graph(node_positions, edges, radius=0.1, cfg=None, stretch_stiffness=None, stretch_damping=None, bend_stiffness=None, bend_damping=None, key=None, wrap_in_articulation=True, quaternions=None, junction_collision_filter=True)#
Adds a rod/cable graph (supports junctions) from nodes + edges.
This is a generalization of
add_rod()to support branching/junction topologies.Representation:
Each edge becomes a capsule rigid body spanning from
node_positions[u]tonode_positions[v](body frame is placed at the start nodeuand local +Z points towardv).Cable joints are created between edge-bodies that share a node, using a spanning-tree traversal so that each body has a single parent when wrapped into an articulation.
Notes:
If
wrap_in_articulation=True(default), joints are created as a forest (one articulation per connected component). This keeps the joint graph articulation-safe (tree/forest), avoiding cycles at junctions.Cycles in the edge adjacency graph are not explicitly closed with extra joints when
wrap_in_articulation=True(cycles would violate articulation tree constraints). If you need closed loops, build them explicitly without articulation wrapping.If
wrap_in_articulation=False, joints are created directly at each node to connect all incident edges. This can preserve rings/loops, but does not produce an articulation tree (edges may effectively have multiple “parents” in the joint graph).
- Parameters:
node_positions (list[Vec3]) – Junction node positions in world space.
edges (list[tuple[int, int]]) – List of (u, v) node index pairs defining rod segments. Each edge creates one capsule body oriented so its local +Z points from node
uto nodev.radius (float) – Capsule radius.
cfg (ShapeConfig | None) – Shape configuration for the capsules. If None,
default_shape_cfgis used.stretch_stiffness (float | None) – Material-like axial stiffness (EA) [N], normalized by edge length into an effective joint stiffness [N/m]. Defaults to 1.0e9.
stretch_damping (float | None) – Stretch damping (per joint). Defaults to 0.0.
bend_stiffness (float | None) – Material-like bend/twist stiffness (EI) [N*m^2], normalized by edge length into an effective joint stiffness [N*m]. Defaults to 0.0.
bend_damping (float | None) – Bend/twist damping (per joint). Defaults to 0.0.
key (str | None) – Optional key prefix for bodies, shapes, joints, and articulations.
wrap_in_articulation (bool) – If True, wraps the generated joint forest into one articulation per connected component.
quaternions (list[Quat] | None) – Optional per-edge orientations in world space. If provided, must have
len(edges)elements and each quaternion must align the capsule’s local +Z with the corresponding edge directionnode_positions[v] - node_positions[u]. If None, orientations are computed automatically to align +Z with each edge direction.junction_collision_filter (bool) – If True, adds collision filters between non-jointed segment bodies that are incident to a junction node (degree >= 3). This prevents immediate self-collision impulses at welded junctions, even though the joint set is a spanning tree (so not all incident body pairs are directly jointed).
- Returns:
(body_indices, joint_indices) where bodies correspond to edges in the same order as
edges.- Return type:
- add_shape(body, type, xform=None, cfg=None, scale=None, src=None, is_static=False, key=None, custom_attributes=None)#
Adds a generic collision shape to the model.
This is the base method for adding shapes; prefer using specific helpers like
add_shape_sphere()where possible.- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body (e.g., static world geometry).
type (int) – The geometry type of the shape (e.g., GeoType.BOX, GeoType.SPHERE).
xform (Transform | None) – The transform of the shape in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
cfg (ShapeConfig | None) – The configuration for the shape’s physical and collision properties. If None,
default_shape_cfgis used. Defaults to None.scale (Vec3 | None) – The scale of the geometry. The interpretation depends on the shape type. Defaults to (1.0, 1.0, 1.0) if None.
src (SDF | Mesh | Any | None) – The source geometry data, e.g., a
Meshobject for GeoType.MESH or anSDFobject for GeoType.SDF. Defaults to None.is_static (bool) – If True, the shape will have zero mass, and its density property in cfg will be effectively ignored for mass calculation. Typically used for fixed, non-movable collision geometry. Defaults to False.
key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated (e.g., “shape_N”). Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The index of the newly added shape.
- Return type:
- add_shape_box(body, xform=None, hx=0.5, hy=0.5, hz=0.5, cfg=None, as_site=False, key=None, custom_attributes=None)#
Adds a box collision shape or site to a body.
The box is centered at its local origin as defined by xform.
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the box in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
hx (float) – The half-extent of the box along its local X-axis. Defaults to 0.5.
hy (float) – The half-extent of the box along its local Y-axis. Defaults to 0.5.
hz (float) – The half-extent of the box along its local Z-axis. Defaults to 0.5.
cfg (ShapeConfig | None) – The configuration for the shape’s properties. If None, uses
default_shape_cfg(ordefault_site_cfgwhen as_site=True). If as_site=True and cfg is provided, a copy is made and site invariants are enforced via mark_as_site(). Defaults to None.as_site (bool) – If True, creates a site (non-colliding reference point) instead of a collision shape. Defaults to False.
key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The index of the newly added shape or site.
- Return type:
- add_shape_capsule(body, xform=None, radius=1.0, half_height=0.5, cfg=None, as_site=False, key=None, custom_attributes=None)#
Adds a capsule collision shape or site to a body.
The capsule is centered at its local origin as defined by xform. Its length extends along the Z-axis.
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the capsule in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
radius (float) – The radius of the capsule’s hemispherical ends and its cylindrical segment. Defaults to 1.0.
half_height (float) – The half-length of the capsule’s central cylindrical segment (excluding the hemispherical ends). Defaults to 0.5.
cfg (ShapeConfig | None) – The configuration for the shape’s properties. If None, uses
default_shape_cfg(ordefault_site_cfgwhen as_site=True). If as_site=True and cfg is provided, a copy is made and site invariants are enforced via mark_as_site(). Defaults to None.as_site (bool) – If True, creates a site (non-colliding reference point) instead of a collision shape. Defaults to False.
key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The index of the newly added shape or site.
- Return type:
- add_shape_collision_filter_pair(shape_a, shape_b)#
Add a collision filter pair in canonical order.
- add_shape_cone(body, xform=None, radius=1.0, half_height=0.5, cfg=None, as_site=False, key=None, custom_attributes=None)#
Adds a cone collision shape to a body.
The cone’s origin is at its geometric center, with the base at -half_height and apex at +half_height along the Z-axis. The center of mass is located at -half_height/2 from the origin (1/4 of the total height from the base toward the apex).
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the cone in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
radius (float) – The radius of the cone’s base. Defaults to 1.0.
half_height (float) – The half-height of the cone (distance from the geometric center to either the base or apex). The total height is 2*half_height. Defaults to 0.5.
cfg (ShapeConfig | None) – The configuration for the shape’s physical and collision properties. If None,
default_shape_cfgis used. Defaults to None.as_site (bool) – If True, creates a site (non-colliding reference point) instead of a collision shape. Defaults to False.
key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for SHAPE frequency attributes.
- Returns:
The index of the newly added shape.
- Return type:
- add_shape_convex_hull(body, xform=None, mesh=None, scale=None, cfg=None, key=None)#
Adds a convex hull collision shape to a body.
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the convex hull in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
mesh (Mesh | None) – The
Meshobject containing the vertex data for the convex hull. Defaults to None.scale (Vec3 | None) – The scale of the convex hull. Defaults to None, in which case the scale is (1.0, 1.0, 1.0).
cfg (ShapeConfig | None) – The configuration for the shape’s physical and collision properties. If None,
default_shape_cfgis used. Defaults to None.key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
- Returns:
The index of the newly added shape.
- Return type:
- add_shape_cylinder(body, xform=None, radius=1.0, half_height=0.5, cfg=None, as_site=False, key=None, custom_attributes=None)#
Adds a cylinder collision shape or site to a body.
The cylinder is centered at its local origin as defined by xform. Its length extends along the Z-axis.
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the cylinder in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
radius (float) – The radius of the cylinder. Defaults to 1.0.
half_height (float) – The half-length of the cylinder along the Z-axis. Defaults to 0.5.
cfg (ShapeConfig | None) – The configuration for the shape’s properties. If None, uses
default_shape_cfg(ordefault_site_cfgwhen as_site=True). If as_site=True and cfg is provided, a copy is made and site invariants are enforced via mark_as_site(). Defaults to None.as_site (bool) – If True, creates a site (non-colliding reference point) instead of a collision shape. Defaults to False.
key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for SHAPE frequency attributes.
- Returns:
The index of the newly added shape or site.
- Return type:
- add_shape_ellipsoid(body, xform=None, a=1.0, b=0.75, c=0.5, cfg=None, as_site=False, key=None, custom_attributes=None)#
Adds an ellipsoid collision shape or site to a body.
The ellipsoid is centered at its local origin as defined by xform, with semi-axes a, b, c along the local X, Y, Z axes respectively.
Note
Ellipsoid collision is handled by the GJK/MPR collision pipeline, which provides accurate collision detection for all convex shape pairs.
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the ellipsoid in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
a (float) – The semi-axis of the ellipsoid along its local X-axis. Defaults to 1.0.
b (float) – The semi-axis of the ellipsoid along its local Y-axis. Defaults to 0.75.
c (float) – The semi-axis of the ellipsoid along its local Z-axis. Defaults to 0.5.
cfg (ShapeConfig | None) – The configuration for the shape’s properties. If None, uses
default_shape_cfg(ordefault_site_cfgwhen as_site=True). If as_site=True and cfg is provided, a copy is made and site invariants are enforced via mark_as_site(). Defaults to None.as_site (bool) – If True, creates a site (non-colliding reference point) instead of a collision shape. Defaults to False.
key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The index of the newly added shape or site.
- Return type:
Example
Create an ellipsoid with different semi-axes:
builder = newton.ModelBuilder() body = builder.add_body() # Add an ellipsoid with semi-axes 1.0, 0.5, 0.25 builder.add_shape_ellipsoid( body=body, a=1.0, # X semi-axis b=0.5, # Y semi-axis c=0.25, # Z semi-axis ) # A sphere is a special case where a = b = c builder.add_shape_ellipsoid(body=body, a=0.5, b=0.5, c=0.5)
- add_shape_mesh(body, xform=None, mesh=None, scale=None, cfg=None, key=None, custom_attributes=None)#
Adds a triangle mesh collision shape to a body.
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the mesh in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
mesh (Mesh | None) – The
Meshobject containing the vertex and triangle data. Defaults to None.scale (Vec3 | None) – The scale of the mesh. Defaults to None, in which case the scale is (1.0, 1.0, 1.0).
cfg (ShapeConfig | None) – The configuration for the shape’s physical and collision properties. If None,
default_shape_cfgis used. Defaults to None.key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for SHAPE frequency attributes.
- Returns:
The index of the newly added shape.
- Return type:
- add_shape_plane(plane=(0.0, 0.0, 1.0, 0.0), xform=None, width=10.0, length=10.0, body=-1, cfg=None, key=None, custom_attributes=None)#
Adds a plane collision shape to the model.
If xform is provided, it directly defines the plane’s position and orientation. The plane’s collision normal is assumed to be along the local Z-axis of this xform. If xform is None, it will be derived from the plane equation a*x + b*y + c*z + d = 0. Plane shapes added via this method are always static (massless).
- Parameters:
plane (Vec4 | None) – The plane equation (a, b, c, d). If xform is None, this defines the plane. The normal is (a,b,c) and d is the offset. Defaults to (0.0, 0.0, 1.0, 0.0) (an XY ground plane at Z=0) if xform is also None.
xform (Transform | None) – The transform of the plane in the world or parent body’s frame. If None, transform is derived from plane. Defaults to None.
width (float) – The visual/collision extent of the plane along its local X-axis. If 0.0, considered infinite for collision. Defaults to 10.0.
length (float) – The visual/collision extent of the plane along its local Y-axis. If 0.0, considered infinite for collision. Defaults to 10.0.
body (int) – The index of the parent body this shape belongs to. Use -1 for world-static planes. Defaults to -1.
cfg (ShapeConfig | None) – The configuration for the shape’s physical and collision properties. If None,
default_shape_cfgis used. Defaults to None.key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for SHAPE frequency attributes.
- Returns:
The index of the newly added shape.
- Return type:
- add_shape_sdf(body, xform=None, sdf=None, cfg=None, key=None, custom_attributes=None)#
Adds a signed distance field (SDF) collision shape to a body.
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the SDF in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
sdf (SDF | None) – The
SDFobject representing the signed distance field. Defaults to None.cfg (ShapeConfig | None) – The configuration for the shape’s physical and collision properties. If None,
default_shape_cfgis used. Defaults to None.key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute values for SHAPE frequency attributes.
- Returns:
The index of the newly added shape.
- Return type:
- add_shape_sphere(body, xform=None, radius=1.0, cfg=None, as_site=False, key=None, custom_attributes=None)#
Adds a sphere collision shape or site to a body.
- Parameters:
body (int) – The index of the parent body this shape belongs to. Use -1 for shapes not attached to any specific body.
xform (Transform | None) – The transform of the sphere in the parent body’s local frame. The sphere is centered at this transform’s position. If None, the identity transform wp.transform() is used. Defaults to None.
radius (float) – The radius of the sphere. Defaults to 1.0.
cfg (ShapeConfig | None) – The configuration for the shape’s properties. If None, uses
default_shape_cfg(ordefault_site_cfgwhen as_site=True). If as_site=True and cfg is provided, a copy is made and site invariants are enforced via mark_as_site(). Defaults to None.as_site (bool) – If True, creates a site (non-colliding reference point) instead of a collision shape. Defaults to False.
key (str | None) – An optional unique key for identifying the shape. If None, a default key is automatically generated. Defaults to None.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The index of the newly added shape or site.
- Return type:
- add_site(body, xform=None, type=GeoType.SPHERE, scale=(0.01, 0.01, 0.01), key=None, visible=False, custom_attributes=None)#
Adds a site (non-colliding reference point) to a body.
Sites are abstract markers that don’t participate in physics simulation or collision detection. They are useful for: - Sensor attachment points (IMU, camera, etc.) - Frame of reference definitions - Debugging and visualization markers - Spatial tendon attachment points (when exported to MuJoCo)
- Parameters:
body (int) – The index of the parent body this site belongs to. Use -1 for sites not attached to any specific body (for sites defined a at static world position).
xform (Transform | None) – The transform of the site in the parent body’s local frame. If None, the identity transform wp.transform() is used. Defaults to None.
type (int) – The geometry type for visualization (e.g., GeoType.SPHERE, GeoType.BOX). Defaults to GeoType.SPHERE.
scale (Vec3) – The scale/size of the site for visualization. Defaults to (0.01, 0.01, 0.01).
key (str | None) – An optional unique key for identifying the site. If None, a default key is automatically generated. Defaults to None.
visible (bool) – If True, the site will be visible for debugging. If False (default), the site is hidden.
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The index of the newly added site (which is stored as a shape internally).
- Return type:
Example
Add an IMU sensor site to a robot torso:
body = builder.add_body() imu_site = builder.add_site( body, xform=wp.transform((0.0, 0.0, 0.1), wp.quat_identity()), key="imu_sensor", visible=True, # Show for debugging )
- add_soft_grid(pos, rot, vel, dim_x, dim_y, dim_z, cell_x, cell_y, cell_z, density, k_mu, k_lambda, k_damp, fix_left=False, fix_right=False, fix_top=False, fix_bottom=False, tri_ke=0.0, tri_ka=0.0, tri_kd=0.0, tri_drag=0.0, tri_lift=0.0, add_surface_mesh_edges=True, edge_ke=0.0, edge_kd=0.0, particle_radius=None)#
Helper to create a rectangular tetrahedral FEM grid
Creates a regular grid of FEM tetrahedra and surface triangles. Useful for example to create beams and sheets. Each hexahedral cell is decomposed into 5 tetrahedral elements.
- Parameters:
pos (list[float] | tuple[float, float, float] | vec3f) – The position of the solid in world space
rot (list[float] | tuple[float, float, float, float] | quatf) – The orientation of the solid in world space
vel (list[float] | tuple[float, float, float] | vec3f) – The velocity of the solid in world space
dim_x (int) – The number of rectangular cells along the x-axis
dim_y (int) – The number of rectangular cells along the y-axis
dim_z (int) – The number of rectangular cells along the z-axis
cell_x (float) – The width of each cell in the x-direction
cell_y (float) – The width of each cell in the y-direction
cell_z (float) – The width of each cell in the z-direction
density (float) – The density of each particle
k_mu (float) – The first elastic Lame parameter
k_lambda (float) – The second elastic Lame parameter
k_damp (float) – The damping stiffness
fix_left (bool) – Make the left-most edge of particles kinematic (fixed in place)
fix_right (bool) – Make the right-most edge of particles kinematic
fix_top (bool) – Make the top-most edge of particles kinematic
fix_bottom (bool) – Make the bottom-most edge of particles kinematic
tri_ke (float) – Stiffness for surface mesh triangles. Defaults to 0.0.
tri_ka (float) – Area stiffness for surface mesh triangles. Defaults to 0.0.
tri_kd (float) – Damping for surface mesh triangles. Defaults to 0.0.
tri_drag (float) – Drag coefficient for surface mesh triangles. Defaults to 0.0.
tri_lift (float) – Lift coefficient for surface mesh triangles. Defaults to 0.0.
add_surface_mesh_edges (bool) – Whether to create zero-stiffness bending edges on the generated surface mesh. These edges improve collision robustness for VBD solver. Defaults to True.
edge_ke (float) – Bending edge stiffness used when
add_surface_mesh_edgesis True. Defaults to 0.0.edge_kd (float) – Bending edge damping used when
add_surface_mesh_edgesis True. Defaults to 0.0.particle_radius (float | None) – particle’s contact radius (controls rigidbody-particle contact distance)
Note
The generated surface triangles and optional edges are for collision purposes. Their stiffness and damping values default to zero so they do not introduce additional elastic forces. Set the triangle stiffness parameters above to non-zero values if you want the surface to behave like a thin skin.
- add_soft_mesh(pos, rot, scale, vel, vertices, indices, density, k_mu, k_lambda, k_damp, tri_ke=0.0, tri_ka=0.0, tri_kd=0.0, tri_drag=0.0, tri_lift=0.0, add_surface_mesh_edges=True, edge_ke=0.0, edge_kd=0.0, particle_radius=None)#
Helper to create a tetrahedral model from an input tetrahedral mesh
- Parameters:
pos (list[float] | tuple[float, float, float] | vec3f) – The position of the solid in world space
rot (list[float] | tuple[float, float, float, float] | quatf) – The orientation of the solid in world space
vel (list[float] | tuple[float, float, float] | vec3f) – The velocity of the solid in world space
vertices (list[list[float] | tuple[float, float, float] | vec3f]) – A list of vertex positions, array of 3D points
indices (list[int]) – A list of tetrahedron indices, 4 entries per-element, flattened array
density (float) – The density per-area of the mesh
k_mu (float) – The first elastic Lame parameter
k_lambda (float) – The second elastic Lame parameter
k_damp (float) – The damping stiffness
tri_ke (float) – Stiffness for surface mesh triangles. Defaults to 0.0.
tri_ka (float) – Area stiffness for surface mesh triangles. Defaults to 0.0.
tri_kd (float) – Damping for surface mesh triangles. Defaults to 0.0.
tri_drag (float) – Drag coefficient for surface mesh triangles. Defaults to 0.0.
tri_lift (float) – Lift coefficient for surface mesh triangles. Defaults to 0.0.
add_surface_mesh_edges (bool) – Whether to create zero-stiffness bending edges on the generated surface mesh. These edges improve collision robustness for VBD solver. Defaults to True.
edge_ke (float) – Bending edge stiffness used when
add_surface_mesh_edgesis True. Defaults to 0.0.edge_kd (float) – Bending edge damping used when
add_surface_mesh_edgesis True. Defaults to 0.0.particle_radius (float | None) – particle’s contact radius (controls rigidbody-particle contact distance)
Note
The generated surface triangles and optional edges are for collision purposes. Their stiffness and damping values default to zero so they do not introduce additional elastic forces. Set the stiffness parameters above to non-zero values if you want the surface to behave like a thin skin.
- add_spring(i, j, ke, kd, control, custom_attributes=None)#
Adds a spring between two particles in the system
- Parameters:
i (int) – The index of the first particle
j (int) – The index of the second particle
ke (float) – The elastic stiffness of the spring
kd (float) – The damping stiffness of the spring
control (float) – The actuation level of the spring
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
Note
The spring is created with a rest-length based on the distance between the particles in their initial configuration.
- add_tetrahedron(i, j, k, l, k_mu=1.0e3, k_lambda=1.0e3, k_damp=0.0, custom_attributes=None)#
Adds a tetrahedral FEM element between four particles in the system.
Tetrahedra are modeled as viscoelastic elements with a NeoHookean energy density based on [Smith et al. 2018].
- Parameters:
i (int) – The index of the first particle
j (int) – The index of the second particle
k (int) – The index of the third particle
l (int) – The index of the fourth particle
k_mu (float) – The first elastic Lame parameter
k_lambda (float) – The second elastic Lame parameter
k_damp (float) – The element’s damping stiffness
custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The volume of the tetrahedron
- Return type:
Note
The tetrahedron is created with a rest-pose based on the particle’s initial configuration
- add_triangle(i, j, k, tri_ke=None, tri_ka=None, tri_kd=None, tri_drag=None, tri_lift=None, custom_attributes=None)#
Adds a triangular FEM element between three particles in the system.
Triangles are modeled as viscoelastic elements with elastic stiffness and damping parameters specified on the model. See
tri_ke,tri_kd.- Parameters:
i (int) – The index of the first particle.
j (int) – The index of the second particle.
k (int) – The index of the third particle.
tri_ke (float | None) – The elastic stiffness of the triangle. If None, the default value (
default_tri_ke) is used.tri_ka (float | None) – The area stiffness of the triangle. If None, the default value (
default_tri_ka) is used.tri_kd (float | None) – The damping stiffness of the triangle. If None, the default value (
default_tri_kd) is used.tri_drag (float | None) – The drag coefficient of the triangle. If None, the default value (
default_tri_drag) is used.tri_lift (float | None) – The lift coefficient of the triangle. If None, the default value (
default_tri_lift) is used.custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The area of the triangle
- Return type:
Note
The triangle is created with a rest-length based on the distance between the particles in their initial configuration.
- add_triangles(i, j, k, tri_ke=None, tri_ka=None, tri_kd=None, tri_drag=None, tri_lift=None, custom_attributes=None)#
Adds triangular FEM elements between groups of three particles in the system.
Triangles are modeled as viscoelastic elements with elastic stiffness and damping Parameters specified on the model. See model.tri_ke, model.tri_kd.
- Parameters:
i (list[int] | ndarray[Any, dtype[Any]]) – The indices of the first particle
j (list[int] | ndarray[Any, dtype[Any]]) – The indices of the second particle
k (list[int] | ndarray[Any, dtype[Any]]) – The indices of the third particle
tri_ke (list[float] | None) – The elastic stiffness of the triangles. If None, the default value (
default_tri_ke) is used.tri_ka (list[float] | None) – The area stiffness of the triangles. If None, the default value (
default_tri_ka) is used.tri_kd (list[float] | None) – The damping stiffness of the triangles. If None, the default value (
default_tri_kd) is used.tri_drag (list[float] | None) – The drag coefficient of the triangles. If None, the default value (
default_tri_drag) is used.tri_lift (list[float] | None) – The lift coefficient of the triangles. If None, the default value (
default_tri_lift) is used.custom_attributes (dict[str, Any] | None) – Dictionary of custom attribute names to values.
- Returns:
The areas of the triangles
- Return type:
Note
A triangle is created with a rest-length based on the distance between the particles in their initial configuration.
- add_urdf(source, *, xform=None, floating=None, base_joint=None, parent_body=-1, scale=1.0, hide_visuals=False, parse_visuals_as_colliders=False, up_axis=Axis.Z, force_show_colliders=False, enable_self_collisions=True, ignore_inertial_definitions=False, ensure_nonstatic_links=True, static_link_mass=1e-2, joint_ordering='dfs', bodies_follow_joint_ordering=True, collapse_fixed_joints=False, mesh_maxhullvert=None, force_position_velocity_actuation=False)#
Parses a URDF file and adds the bodies and joints to the given ModelBuilder.
- Parameters:
source (str) – The filename of the URDF file to parse, or the URDF XML string content.
xform (Transform) – The transform to apply to the root body. If None, the transform is set to identity.
floating (bool or None) –
Controls the base joint type for the root body.
None(default): Uses format-specific default (creates a FIXED joint for URDF).True: Creates a FREE joint with 6 DOF (3 translation + 3 rotation). Only valid whenparent_body == -1since FREE joints must connect to world frame.False: Creates a FIXED joint (0 DOF).
Cannot be specified together with
base_joint.base_joint (dict) –
Custom joint specification for connecting the root body to the world (or to
parent_bodyif specified). This parameter enables hierarchical composition with custom mobility. Dictionary with joint parameters as accepted byModelBuilder.add_joint()(e.g., joint type, axes, limits, stiffness).Cannot be specified together with
floating.parent_body (int) –
Parent body index for hierarchical composition. If specified, attaches the imported root body to this existing body, making them part of the same kinematic articulation. The connection type is determined by
floatingorbase_joint. If-1(default), the root connects to the world frame. Restriction: Only the most recently added articulation can be used as parent; attempting to attach to an older articulation will raise aValueError.Note
Valid combinations of
floating,base_joint, andparent_body:floating
base_joint
parent_body
Result
NoneNone-1Format default (URDF: FIXED joint)
TrueNone-1FREE joint to world (6 DOF)
FalseNone-1FIXED joint to world (0 DOF)
None{dict}-1Custom joint to world (e.g., D6)
FalseNonebody_idxFIXED joint to parent body
None{dict}body_idxCustom joint to parent body (e.g., D6)
explicitly set
explicitly set
any
❌ Error: mutually exclusive (cannot specify both)
TrueNonebody_idx❌ Error: FREE joints require world frame
scale (float) – The scaling factor to apply to the imported mechanism.
hide_visuals (bool) – If True, hide visual shapes.
parse_visuals_as_colliders (bool) – If True, the geometry defined under the <visual> tags is used for collision handling instead of the <collision> geometries.
up_axis (AxisType) – The up axis of the URDF. This is used to transform the URDF to the builder’s up axis. It also determines the up axis of capsules and cylinders in the URDF. The default is Z.
force_show_colliders (bool) – If True, the collision shapes are always shown, even if there are visual shapes.
enable_self_collisions (bool) – If True, self-collisions are enabled.
ignore_inertial_definitions (bool) – If True, the inertial parameters defined in the URDF are ignored and the inertia is calculated from the shape geometry.
ensure_nonstatic_links (bool) – If True, links with zero mass are given a small mass (see static_link_mass) to ensure they are dynamic.
static_link_mass (float) – The mass to assign to links with zero mass (if ensure_nonstatic_links is set to True).
joint_ordering (str) – The ordering of the joints in the simulation. Can be either “bfs” or “dfs” for breadth-first or depth-first search, or
Noneto keep joints in the order in which they appear in the URDF. Default is “dfs”.bodies_follow_joint_ordering (bool) – If True, the bodies are added to the builder in the same order as the joints (parent then child body). Otherwise, bodies are added in the order they appear in the URDF. Default is True.
collapse_fixed_joints (bool) – If True, fixed joints are removed and the respective bodies are merged.
mesh_maxhullvert (int) – Maximum vertices for convex hull approximation of meshes.
force_position_velocity_actuation (bool) – If True and both position (stiffness) and velocity (damping) gains are non-zero, joints use
POSITION_VELOCITYactuation mode. If False (default), actuator modes are inferred per joint vianewton.ActuatorMode.from_gains():POSITIONif stiffness > 0,VELOCITYif only damping > 0,EFFORTif a drive is present but both gains are zero (direct torque control), orNONEif no drive/actuation is applied.
- add_usd(source, *, xform=None, floating=None, base_joint=None, parent_body=-1, only_load_enabled_rigid_bodies=False, only_load_enabled_joints=True, joint_drive_gains_scaling=1.0, verbose=False, ignore_paths=None, collapse_fixed_joints=False, enable_self_collisions=True, apply_up_axis_from_stage=False, root_path='/', joint_ordering='dfs', bodies_follow_joint_ordering=True, skip_mesh_approximation=False, load_sites=True, load_visual_shapes=True, hide_collision_shapes=False, parse_mujoco_options=True, mesh_maxhullvert=None, schema_resolvers=None, force_position_velocity_actuation=False)#
Parses a Universal Scene Description (USD) stage containing UsdPhysics schema definitions for rigid-body articulations and adds the bodies, shapes and joints to the given ModelBuilder.
The USD description has to be either a path (file name or URL), or an existing USD stage instance that implements the Stage interface.
See USD Parsing and Schema Resolver System for more information.
- Parameters:
source (str | pxr.Usd.Stage) – The file path to the USD file, or an existing USD stage instance.
xform (Transform) – The transform to apply to the entire scene.
floating (bool or None) –
Controls the base joint type for the root body (bodies not connected as a child to any joint).
None(default): Uses format-specific default (creates a FREE joint for USD bodies without joints).True: Creates a FREE joint with 6 DOF (3 translation + 3 rotation). Only valid whenparent_body == -1since FREE joints must connect to world frame.False: Creates a FIXED joint (0 DOF).
Cannot be specified together with
base_joint.base_joint (dict) –
Custom joint specification for connecting the root body to the world (or to
parent_bodyif specified). This parameter enables hierarchical composition with custom mobility. Dictionary with joint parameters as accepted byModelBuilder.add_joint()(e.g., joint type, axes, limits, stiffness).Cannot be specified together with
floating.parent_body (int) –
Parent body index for hierarchical composition. If specified, attaches the imported root body to this existing body, making them part of the same kinematic articulation. The connection type is determined by
floatingorbase_joint. If-1(default), the root connects to the world frame. Restriction: Only the most recently added articulation can be used as parent; attempting to attach to an older articulation will raise aValueError.Note
Valid combinations of
floating,base_joint, andparent_body:floating
base_joint
parent_body
Result
NoneNone-1Format default (USD: FREE joint for bodies without joints)
TrueNone-1FREE joint to world (6 DOF)
FalseNone-1FIXED joint to world (0 DOF)
None{dict}-1Custom joint to world (e.g., D6)
FalseNonebody_idxFIXED joint to parent body
None{dict}body_idxCustom joint to parent body (e.g., D6)
explicitly set
explicitly set
any
❌ Error: mutually exclusive (cannot specify both)
TrueNonebody_idx❌ Error: FREE joints require world frame
only_load_enabled_rigid_bodies (bool) – If True, only rigid bodies which do not have physics:rigidBodyEnabled set to False are loaded.
only_load_enabled_joints (bool) – If True, only joints which do not have physics:jointEnabled set to False are loaded.
joint_drive_gains_scaling (float) – The default scaling of the PD control gains (stiffness and damping), if not set in the PhysicsScene with as “newton:joint_drive_gains_scaling”.
verbose (bool) – If True, print additional information about the parsed USD file. Default is False.
ignore_paths (List[str]) – A list of regular expressions matching prim paths to ignore.
collapse_fixed_joints (bool) – If True, fixed joints are removed and the respective bodies are merged. Only considered if not set on the PhysicsScene as “newton:collapse_fixed_joints”.
enable_self_collisions (bool) – Determines the default behavior of whether self-collisions are enabled for all shapes within an articulation. If an articulation has the attribute
physxArticulation:enabledSelfCollisionsdefined, this attribute takes precedence.apply_up_axis_from_stage (bool) – If True, the up axis of the stage will be used to set
newton.ModelBuilder.up_axis. Otherwise, the stage will be rotated such that its up axis aligns with the builder’s up axis. Default is False.root_path (str) – The USD path to import, defaults to “/”.
joint_ordering (str) – The ordering of the joints in the simulation. Can be either “bfs” or “dfs” for breadth-first or depth-first search, or
Noneto keep joints in the order in which they appear in the USD. Default is “dfs”.bodies_follow_joint_ordering (bool) – If True, the bodies are added to the builder in the same order as the joints (parent then child body). Otherwise, bodies are added in the order they appear in the USD. Default is True.
skip_mesh_approximation (bool) – If True, mesh approximation is skipped. Otherwise, meshes are approximated according to the
physics:approximationattribute defined on the UsdPhysicsMeshCollisionAPI (if it is defined). Default is False.load_sites (bool) – If True, sites (prims with MjcSiteAPI) are loaded as non-colliding reference points. If False, sites are ignored. Default is True.
load_visual_shapes (bool) – If True, non-physics visual geometry is loaded. If False, visual-only shapes are ignored (sites are still controlled by
load_sites). Default is True.hide_collision_shapes (bool) – If True, collision shapes are hidden. Default is False.
parse_mujoco_options (bool) – Whether MuJoCo solver options from the PhysicsScene should be parsed. If False, solver options are not loaded and custom attributes retain their default values. Default is True.
mesh_maxhullvert (int) – Maximum vertices for convex hull approximation of meshes. Note that an authored
newton:maxHullVerticesattribute on any shape with aNewtonMeshCollisionAPIwill take priority over this value.schema_resolvers (list[SchemaResolver]) –
Resolver instances in priority order. Default is to only parse Newton-specific attributes. Schema resolvers collect per-prim “solver-specific” attributes, see 1. Solver Attribute Remapping for more information. These include namespaced attributes such as
newton:*,physx*(e.g.,physxScene:*,physxRigidBody:*,physxSDFMeshCollision:*), andmjc:*that are authored in the USD but not strictly required to build the simulation. This is useful for inspection, experimentation, or custom pipelines that read these values vianewton.usd.SchemaResolverManager.schema_attrs.Note
Using the
schema_resolversargument is an experimental feature that may be removed or changed significantly in the future.force_position_velocity_actuation (bool) – If True and both stiffness (kp) and damping (kd) are non-zero, joints use
POSITION_VELOCITYactuation mode. If False (default), actuator modes are inferred per joint vianewton.ActuatorMode.from_gains():POSITIONif stiffness > 0,VELOCITYif only damping > 0,EFFORTif a drive is present but both gains are zero (direct torque control), orNONEif no drive/actuation is applied.
- Returns:
Dictionary with the following entries:
"fps"USD stage frames per second
"duration"Difference between end time code and start time code of the USD stage
"up_axis"Axisrepresenting the stage’s up axis (“X”, “Y”, or “Z”)"path_body_map"Mapping from prim path (str) of a rigid body prim (e.g. that implements the PhysicsRigidBodyAPI) to the respective body index in
ModelBuilder"path_joint_map"Mapping from prim path (str) of a joint prim (e.g. that implements the PhysicsJointAPI) to the respective joint index in
ModelBuilder"path_shape_map"Mapping from prim path (str) of the UsdGeom to the respective shape index in
ModelBuilder"path_shape_scale"Mapping from prim path (str) of the UsdGeom to its respective 3D world scale
"mass_unit"The stage’s Kilograms Per Unit (KGPU) definition (1.0 by default)
"linear_unit"The stage’s Meters Per Unit (MPU) definition (1.0 by default)
"scene_attributes"Dictionary of all attributes applied to the PhysicsScene prim
"collapse_results"Dictionary returned by
newton.ModelBuilder.collapse_fixed_joints()ifcollapse_fixed_jointsis True, otherwise None."physics_dt"The resolved physics scene time step (float or None)
"schema_attrs"Dictionary of collected per-prim schema attributes (dict)
"max_solver_iterations"The resolved maximum solver iterations (int or None)
"path_body_relative_transform"Mapping from prim path to relative transform for bodies merged via
collapse_fixed_joints"path_original_body_map"Mapping from prim path to original body index before
collapse_fixed_joints- Return type:
- add_world(builder, xform=None)#
Add a builder as a new world.
This is a convenience method that combines
begin_world(),add_builder(), andend_world()into a single call. It’s the recommended way to add homogeneous worlds (multiple instances of the same scene/robot).- Parameters:
builder (ModelBuilder) – The builder containing entities to add as a new world.
xform (Transform | None) – Optional transform to apply to all root bodies in the builder. Useful for spacing out worlds visually.
- Raises:
RuntimeError – If called when already in a world context (via begin_world).
Example:
# Create a robot blueprint robot = ModelBuilder() robot.add_body(...) robot.add_shape_box(...) # Create main scene with multiple robot instances scene = ModelBuilder() scene.add_ground_plane() # Global ground plane # Add multiple robot worlds for i in range(3): scene.add_world(robot) # Each robot is a separate world
- approximate_meshes(method='convex_hull', shape_indices=None, raise_on_failure=False, keep_visual_shapes=False, **remeshing_kwargs)#
Approximates the mesh shapes of the model.
The following methods are supported:
Method
Description
"coacd"Convex decomposition using CoACD
"vhacd"Convex decomposition using V-HACD
"bounding_sphere"Approximate the mesh with a sphere
"bounding_box"Approximate the mesh with an oriented bounding box
"convex_hull"Approximate the mesh with a convex hull (default)
<remeshing_method>Any remeshing method supported by
newton.geometry.remesh_mesh()Note
The
coacdandvhacdmethods require additional dependencies (coacdortrimeshandvhacdxrespectively) to be installed. The convex hull approximation requiresscipyto be installed.- The
raise_on_failureparameter controls the behavior when the remeshing fails: If True, an exception is raised when the remeshing fails.
- If False, a warning is logged, and the method falls back to the next available method in the order of preference:
If convex decomposition via CoACD or V-HACD fails or dependencies are not available, the method will fall back to using the
convex_hullmethod.If convex hull approximation fails, it will fall back to the
bounding_boxmethod.
- Parameters:
method (Literal['coacd', 'vhacd', 'bounding_sphere', 'bounding_box', 'ftetwild', 'alphashape', 'quadratic', 'convex_hull', 'poisson']) – The method to use for approximating the mesh shapes.
shape_indices (list[int] | None) – The indices of the shapes to simplify. If None, all mesh shapes that have the
ShapeFlags.COLLIDE_SHAPESflag set are simplified.raise_on_failure (bool) – If True, raises an exception if the remeshing fails. If False, it will log a warning and continue with the fallback method.
**remeshing_kwargs (dict[str, Any]) – Additional keyword arguments passed to the remeshing function.
- Returns:
A set of indices of the shapes that were successfully remeshed.
- Return type:
- The
- begin_world(key=None, attributes=None, gravity=None)#
Begin a new world context for adding entities.
This method starts a new world scope where all subsequently added entities (bodies, shapes, joints, particles, etc.) will be assigned to this world. Use
end_world()to close the world context and return to the global scope.Important: Worlds cannot be nested. You must call
end_world()before callingbegin_world()again.- Parameters:
key (str | None) – Optional unique identifier for this world. If None, a default key “world_{index}” will be generated.
attributes (dict[str, Any] | None) – Optional custom attributes to associate with this world for later use.
gravity (Vec3 | None) – Optional gravity vector for this world. If None, the world will use the builder’s default gravity (computed from
self.gravityandself.up_vector).
- Raises:
RuntimeError – If called when already inside a world context (current_world != -1).
Example:
builder = ModelBuilder() # Add global ground plane builder.add_ground_plane() # Added to world -1 (global) # Create world 0 with default gravity builder.begin_world(key="robot_0") builder.add_body(...) # Added to world 0 builder.add_shape_box(...) # Added to world 0 builder.end_world() # Create world 1 with custom zero gravity builder.begin_world(key="robot_1", gravity=(0.0, 0.0, 0.0)) builder.add_body(...) # Added to world 1 builder.add_shape_box(...) # Added to world 1 builder.end_world()
- collapse_fixed_joints(verbose=wp.config.verbose)#
Removes fixed joints from the model and merges the bodies they connect. This is useful for simplifying the model for faster and more stable simulation.
- color(include_bending=False, balance_colors=True, target_max_min_color_ratio=1.1, coloring_algorithm=ColoringAlgorithm.MCS)#
Runs coloring algorithm to generate coloring information.
This populates both
particle_color_groups(for particles) andbody_color_groups(for rigid bodies) on the builder, which are consumed bynewton.solvers.SolverVBD.Call
color()(orset_coloring()) beforefinalize()when usingnewton.solvers.SolverVBD;finalize()does not implicitly color the model.- Parameters:
include_bending – Whether to include bending edges in the coloring graph. Set to True if your model contains bending edges (added via
add_edge()) that participate in bending constraints. When enabled, the coloring graph includes connections between opposite vertices of each edge (o1-o2), ensuring proper dependency handling for parallel bending computations. Leave as False if your model has no bending edges or if bending edges should not affect the coloring.balance_colors – Whether to apply the color balancing algorithm to balance the size of each color
target_max_min_color_ratio – the color balancing algorithm will stop when the ratio between the largest color and the smallest color reaches this value
algorithm – Value should be an enum type of ColoringAlgorithm, otherwise it will raise an error. ColoringAlgorithm.mcs means using the MCS coloring algorithm, while ColoringAlgorithm.ordered_greedy means using the degree-ordered greedy algorithm. The MCS algorithm typically generates 30% to 50% fewer colors compared to the ordered greedy algorithm, while maintaining the same linear complexity. Although MCS has a constant overhead that makes it about twice as slow as the greedy algorithm, it produces significantly better coloring results. We recommend using MCS, especially if coloring is only part of the preprocessing.
Note
References to the coloring algorithm:
MCS: Pereira, F. M. Q., & Palsberg, J. (2005, November). Register allocation via coloring of chordal graphs. In Asian Symposium on Programming Languages and Systems (pp. 315-329). Berlin, Heidelberg: Springer Berlin Heidelberg.
Ordered Greedy: Ton-That, Q. M., Kry, P. G., & Andrews, S. (2023). Parallel block Neo-Hookean XPBD using graph clustering. Computers & Graphics, 110, 1-10.
- end_world()#
End the current world context and return to global scope.
After calling this method, subsequently added entities will be assigned to the global world (-1) until
begin_world()is called again.- Raises:
RuntimeError – If called when not in a world context (current_world == -1).
Example:
builder = ModelBuilder() builder.begin_world() builder.add_body(...) # Added to current world builder.end_world() # Return to global scope builder.add_ground_plane() # Added to world -1 (global)
- finalize(device=None, requires_grad=False, skip_all_validations=False, skip_validation_worlds=False, skip_validation_joints=False, skip_validation_shapes=False, skip_validation_structure=False, skip_validation_joint_ordering=True)#
Finalize the builder and create a concrete
Modelfor simulation.This method transfers all simulation data from the builder to device memory, returning a Model object ready for simulation. It should be called after all elements (particles, bodies, shapes, joints, etc.) have been added to the builder.
- Parameters:
device (Device | str | None) – The simulation device to use (e.g., ‘cpu’, ‘cuda’). If None, uses the current Warp device.
requires_grad (bool) – If True, enables gradient computation for the model (for differentiable simulation).
skip_all_validations (bool) – If True, skips all validation checks. Use for maximum performance when you are confident the model is valid. Default is False.
skip_validation_worlds (bool) – If True, skips validation of world ordering and contiguity. Default is False.
skip_validation_joints (bool) – If True, skips validation of joints belonging to an articulation. Default is False.
skip_validation_shapes (bool) – If True, skips validation of shapes having valid contact margins. Default is False.
skip_validation_structure (bool) – If True, skips validation of structural invariants (body/joint references, array lengths, monotonicity). Default is False.
skip_validation_joint_ordering (bool) – If True, skips validation of DFS topological joint ordering within articulations. Default is True (opt-in) because this check has O(n log n) complexity.
- Returns:
A fully constructed Model object containing all simulation data on the specified device.
- Return type:
Notes
Performs validation and correction of rigid body inertia and mass properties.
Closes all start-index arrays (e.g., for muscles, joints, articulations) with sentinel values.
Sets up all arrays and properties required for simulation, including particles, bodies, shapes, joints, springs, muscles, constraints, and collision/contact data.
- find_shape_contact_pairs(model)#
Identifies and stores all potential shape contact pairs for collision detection.
This method examines the collision groups and collision masks of all shapes in the model to determine which pairs of shapes should be considered for contact generation. It respects any user-specified collision filter pairs to avoid redundant or undesired contacts.
The resulting contact pairs are stored in the model as a 2D array of shape indices.
Uses the exact same filtering logic as the broad phase kernels (test_world_and_group_pair) to ensure consistency between EXPLICIT mode (precomputed pairs) and NXN/SAP modes.
- Parameters:
model (Model) – The simulation model to which the contact pairs will be assigned.
- Side Effects:
Sets model.shape_contact_pairs to a wp.array of shape pairs (wp.vec2i).
Sets model.shape_contact_pair_count to the number of contact pairs found.
- get_custom_attributes_by_frequency(frequencies)#
Get custom attributes by frequency. This is useful for processing custom attributes for different kinds of simulation objects. For example, you can get all the custom attributes for bodies, shapes, joints, etc.
- Parameters:
frequencies (Sequence[Model.AttributeFrequency]) – The frequencies to get custom attributes for.
- Returns:
A list of custom attributes.
- Return type:
- get_custom_frequency_keys()#
Return set of custom frequency keys (string frequencies) defined in this builder.
- has_custom_attribute(key)#
Check if a custom attribute is defined.
- plot_articulation(show_body_keys=True, show_joint_keys=True, show_joint_types=True, plot_shapes=True, show_shape_keys=True, show_shape_types=True, show_legend=True)#
Visualizes the model’s articulation graph using matplotlib and networkx. Uses the spring layout algorithm from networkx to arrange the nodes. Bodies are shown as orange squares, shapes are shown as blue circles.
- Parameters:
show_body_keys (bool) – Whether to show the body keys or indices
show_joint_keys (bool) – Whether to show the joint keys or indices
show_joint_types (bool) – Whether to show the joint types
plot_shapes (bool) – Whether to render the shapes connected to the rigid bodies
show_shape_keys (bool) – Whether to show the shape keys or indices
show_shape_types (bool) – Whether to show the shape geometry types
show_legend (bool) – Whether to show a legend
- replicate(builder, num_worlds, spacing=(0.0, 0.0, 0.0))#
Replicates the given builder multiple times, offsetting each copy according to the supplied spacing.
This method is useful for creating multiple instances of a sub-model (e.g., robots, scenes) arranged in a regular grid or along a line. Each copy is offset in space by a multiple of the specified spacing vector, and all entities from each copy are assigned to a new world.
Note
For visual separation of worlds, it is recommended to use the viewer’s set_world_offsets() method instead of physical spacing. This improves numerical stability by keeping all worlds at the origin in the physics simulation.
- Parameters:
builder (ModelBuilder) – The builder to replicate. All entities from this builder will be copied.
num_worlds (int) – The number of worlds to create.
spacing (tuple[float, float, float], optional) – The spacing between each copy along each axis. For example, (5.0, 5.0, 0.0) arranges copies in a 2D grid in the XY plane. Defaults to (0.0, 0.0, 0.0).
- request_contact_attributes(*attributes)#
Request that specific contact attributes be allocated when creating a Contacts object from the finalized Model.
- Parameters:
*attributes (str) – Variable number of attribute names (strings).
- request_state_attributes(*attributes)#
Request that specific state attributes be allocated when creating a State object from the finalized Model.
See Extended State Attributes for details and usage.
- Parameters:
*attributes (str) – Variable number of attribute names (strings).
- set_coloring(particle_color_groups)#
Sets coloring information with user-provided coloring.
- Parameters:
particle_color_groups – A list of list or np.array with dtype`=`int. The length of the list is the number of colors and each list or np.array contains the indices of vertices with this color.
- validate_joint_ordering()#
Validate that joints within articulations follow DFS topological ordering.
This check ensures that joints are ordered such that parent bodies are processed before child bodies within each articulation. This ordering is required by some solvers (e.g., MuJoCo) for correct kinematic computations.
This method is public and opt-in because the check has O(n log n) complexity due to topological sorting. It is skipped by default in finalize().
- Warns:
UserWarning – If joints are not in DFS topological order.
- Returns:
True if joints are correctly ordered, False otherwise.
- Return type:
- property articulation_count#
The number of articulations in the model.
- balance_inertia: bool#
Whether to automatically correct rigid body inertia tensors that violate the triangle inequality. When True, adds a scalar multiple of the identity matrix to preserve rotation structure while ensuring physical validity (I1 + I2 >= I3 for principal moments). Default: True.
- property body_count#
The number of rigid bodies in the model.
- bound_inertia: float | None#
Minimum allowed eigenvalue for rigid body inertia tensors. If set, ensures all principal moments of inertia are at least this value. Set to None to disable inertia eigenvalue clamping. Default: None.
- bound_mass: float | None#
Minimum allowed mass value for rigid bodies. If set, any body mass below this value will be clamped to this minimum. Set to None to disable mass clamping. Default: None.
- property default_site_cfg: ShapeConfig#
Returns a ShapeConfig configured for sites (non-colliding reference points).
This config has all site invariants enforced: - is_site = True - has_shape_collision = False - has_particle_collision = False - density = 0.0 - collision_group = 0
- Returns:
A new configuration suitable for creating sites.
- Return type:
- property edge_count#
The number of edges (for bending) in the model.
- property joint_count#
The number of joints in the model.
- property muscle_count#
The number of muscles in the model.
- property particle_count#
The number of particles in the model.
- property shape_count#
The number of shapes in the model.
- property spring_count#
The number of springs in the model.
- property tet_count#
The number of tetrahedra in the model.
- property tri_count#
The number of triangles in the model.
- property up_vector: list[float] | tuple[float, float, float] | vec3f#
Returns the 3D unit vector corresponding to the current up axis (read-only).
This property computes the up direction as a 3D vector based on the value of
up_axis. For example, ifup_axisisAxis.Z, this returns(0, 0, 1).- Returns:
The 3D up vector corresponding to the current up axis.
- Return type:
Vec3
- validate_inertia_detailed: bool#
Whether to use detailed (slower) inertia validation that provides per-body warnings. When False, uses a fast GPU kernel that reports only the total number of corrected bodies and directly assigns the corrected arrays to the Model (ModelBuilder state is not updated). When True, uses a CPU implementation that reports specific issues for each body and updates the ModelBuilder’s internal state. Default: False.