Python 适配层参考¶
本页从 Python 源码提取公开签名与英文 docstring,中文使用教程见 模型与仿真循环。 参数默认值来自当前源码,而不是推测的推荐值。
LogCallback¶
Callable interface used to receive native solver log messages.
set_log_callback¶
Register a Python callback for native solver log messages.
get_assets¶
Return the asset root, cloning the repository on first use.
Set STYLE3D_SIM_ASSETS_DIR to use an existing checkout instead. The asset repository root must contain the asset groups directly.
get_asset¶
Return an asset path, refreshing a stale default checkout when needed.
ModelBuilder¶
Build Newton models with particle proxies for dynamic rigid bodies.
Four vector-valued particles store the ABD generalized coordinates of every dynamic body: its center of mass followed by the three columns of its affine matrix. The native solver can preserve the frame with six proxy-edge springs, the original ABD orthogonality potential, or M-ABD-style co-rotated linear elasticity. A four-by-four scalar block mass matrix preserves the body's translational mass and inertia tensor in affine coordinates.
The proxy topology is added immediately before finalization, after attached shapes have contributed their mass properties. The resulting particles are ordinary Newton particles and are therefore visible in Newton viewers.
__init__¶
__init__(self, up_axis: Any=_newton.Axis.Z, gravity: float=-9.81, *, affine_body_particle_radius: float | None=None) -> None
Create a builder that generates affine-body particle proxies.
Args:
up_axis: Newton model up axis.
gravity: Gravitational acceleration along the negative up axis.
affine_body_particle_radius: Viewer and collision radius of proxy
particles. None uses Newton's default particle radius.
add_body_spring¶
add_body_spring(self, body0: int, body1: int, point0: Any=(0.0, 0.0, 0.0), point1: Any=(0.0, 0.0, 0.0), *, stiffness: float=100000.0, rest_length: float | None=None) -> int
Add a spring between rigid-body points or a world-space anchor.
Args:
body0: Newton body index containing the first point, or -1 for
a fixed world-space point.
body1: Newton body index containing the second point, or -1 for
a fixed world-space point.
point0: First point in body0 local coordinates, or world
coordinates when body0 is -1.
point1: Second point in body1 local coordinates, or world
coordinates when body1 is -1.
stiffness: Spring stiffness in newtons per meter.
rest_length: Unstrained length in meters. None uses the distance
between the two points in the finalized initial pose.
Returns: The index of the appended body spring.
add_body_distance_constraint¶
add_body_distance_constraint(self, body0: int, body1: int, point0: Any=(0.0, 0.0, 0.0), point1: Any=(0.0, 0.0, 0.0), *, rest_length: float | None=None) -> int
Add an augmented-Lagrangian hard distance constraint.
Args:
body0: Newton body index containing the first point, or -1 for
a fixed world-space point.
body1: Newton body index containing the second point, or -1 for
a fixed world-space point.
point0: First point in body0 local coordinates, or world
coordinates when body0 is -1.
point1: Second point in body1 local coordinates, or world
coordinates when body1 is -1.
rest_length: Constrained length in meters. None uses the
distance between the two points in the finalized initial pose.
Returns: The index of the appended body distance constraint.
add_body_point_line¶
add_body_point_line(self, point_body: int, line_body: int, point: Any=(0.0, 0.0, 0.0), line_endpoint0: Any=(-0.5, 0.0, 0.0), line_endpoint1: Any=(0.5, 0.0, 0.0), *, stiffness: float=100000.0, damping: float=0.0) -> int
Constrain a body point to a body-local or world-space segment.
The force uses the point's projection onto the segment. A projection outside the segment is clamped to its nearest endpoint, where the constraint becomes a zero-rest-length point spring.
Args:
point_body: Newton body index containing the constrained point.
line_body: Newton body index containing both segment endpoints, or
-1 when the endpoints are fixed in world space.
point: Point in point_body local coordinates.
line_endpoint0: First endpoint in line_body local coordinates,
or world coordinates when line_body is -1.
line_endpoint1: Second endpoint in line_body local coordinates,
or world coordinates when line_body is -1.
stiffness: Constraint stiffness in newtons per meter.
damping: Constraint-normal damping in newton-seconds per meter.
Returns: The index of the appended body point-line constraint.
finalize¶
finalize(self, device: Any | None=None, *, requires_grad: bool=False, skip_all_validations: bool=False, skip_validation_worlds: bool=False, skip_validation_joints: bool=False, skip_validation_shapes: bool=False, skip_validation_structure: bool=False, skip_validation_joint_ordering: bool=True) -> Any
Add affine-body proxies and finalize one Newton model.
The returned model carries explicit body-id and particle-index arrays
consumed by :class:style3d_sim.NewtonSolver. This builder is one-shot because
appending bodies after proxy indices are fixed would invalidate them.
NewtonSolver¶
Expose the native Style3D Sim solver through Newton's solver interface.
The adapter passes Newton-owned Warp CUDA arrays to Style3D Sim as non-owning device-memory spans. Newton continues to own every model and state array.
The native solver supports particles, tetrahedral soft bodies, Style3D cloth, dynamic affine bodies, and rigid and soft contacts from Newton's collision pipeline. Newton ball, revolute, prismatic, fixed, free, and equivalent D6 joints are assembled from affine-body point-point and point-line constraints. Joint controls and Newton collision-pipeline contacts are passed to the native backend. Native work uses Newton's active CUDA stream and can therefore participate in graph capture.
| 属性 | 类型 | 说明 |
|---|---|---|
synreal_model |
Model |
Return the native model containing non-owning Newton array views. |
native_solver |
Solver |
Return the wrapped native solver. |
config |
Config |
Return the mutable native configuration used by subsequent steps. |
joint_drive_effort |
Any | None |
Return the optional motor-effort CUDA array, indexed like control.joint_f. Values are signed along each DOF axis: N for prismatic drives and Nm for angular drives. Values are joint_f plus the mode-aware, clipped actuator effort at the beginning of the step, matching MuJoCo's force evaluation. They exclude passive damping, contact, and joint reactions. Unsupported DOFs contain zero. Copy after each step to retain history; CUDA graph replay also overwrites this independent array. No State fields are added or changed. |
__init__¶
__init__(self, model: Any, *, joint_damping: float=100.0, joint_attachment_distance: float=0.1, joint_line_half_length: float=10.0, joint_drive_armature: float=0.0) -> None
Create a Style3D Sim-backed solver for a Newton model.
Args:
model: Particle, tetrahedral soft-body, or Style3D cloth
newton.Model on a CUDA device.
joint_damping: Normal damping used for generated point-line constraints.
joint_attachment_distance: Separation between attachment points that
constrain joint orientation.
joint_line_half_length: Half-length of generated slider guide segments.
joint_drive_armature: Isotropic rotational inertia added to bodies
connected to active joint drives. This optional legacy
regularization is separate from model.joint_armature,
which adds inertia to each supported relative joint coordinate.
Raises: ValueError: If the model is not allocated on CUDA or required particle or tetrahedron arrays are invalid. RuntimeError: If Style3D Sim authentication fails. NotImplementedError: If generic Newton surface elasticity is enabled without Style3D attributes.
enable_joint_drive_feedback¶
Enable recording of the pre-integration motor effort for each step.
Call before CUDA graph capture. The independent CUDA output array does not add State fields or change the state, parameters, or dynamics solve.
disable_joint_drive_feedback¶
Disable feedback; discard captured graphs referencing the output before calling.
Existing CUDA graphs keep their captured output address and must be rebuilt after enabling or disabling feedback, just as after configuration changes.
compute_joint_drive_effort¶
compute_joint_drive_effort(self, state: Any, control: Any | None, out: Any | None=None, *, previous_state: Any | None=None, dt: float | None=None, _advance_angle_state: bool=False) -> Any
Evaluate the supplied state's instantaneous motor effort without changing it.
Velocity comes from body twists, while :meth:step records this value
before integration. previous_state and dt remain accepted for
compatibility but do not replace the instantaneous velocity with a secant.
A supplied previous pose seeds the angular branch when it is uninitialized.
Pass a preallocated float32 out array during CUDA graph capture.
sync_affine_body_state¶
Update affine proxy positions and velocities from Newton body state.
Call this after eval_fk(), an environment reset, or any direct edit
of body_q/body_qd. The operation stays on the active CUDA stream
and is safe to include in CUDA graph capture. It must not be called
before every regular step because that would discard the proxy state
integrated by the native solver.
step¶
step(self, state_in: Any, state_out: Any, control: Any | None, contacts: Any | None, dt: float) -> None
Advance Newton state arrays through the native Style3D Sim solver.
Args: state_in: Newton input state. state_out: Newton output state. control: Newton generalized joint-control input. contacts: Newton collision-pipeline contact data. dt: Time-step duration in seconds.
When affine-body inertial prediction is enabled, Python integrates the
rigid-body inertia state including the applied body wrench, then converts
its pose displacement into affine-proxy secant velocities. Joint
actuator forces use MuJoCo's mode and actuator-limit semantics. Position
error is evaluated before integration; actuator and passive damping are
linearized implicitly in velocity, as in MuJoCo's implicitfast.
Gravity, particle forces, joint constraints, and contacts retain their
native paths.
The native solver then applies affine rigidity, joints, and contacts to
Cartesian particle positions and velocities. On return, both particle-
position buffers contain the new positions, while Python reconstructs
state_out.body_q and state_out.body_qd from the resulting proxy
position and linear-velocity fields. In InertiaMode.NONE, the
returned proxy velocities are projected onto the rigid velocity field
represented by state_out.body_qd so the two representations round-trip.
notify_model_changed¶
Refresh native views after Newton model arrays are modified.
configure_fluid¶
configure_fluid(model, particle_indices, *, smoothing_radius: float, rest_density: float=1000.0, bulk_modulus: float=200000.0, viscosity: float=0.0, boundary_positions=None, boundary_volumes=None) -> None
Select fluid particles before constructing NewtonSolver.
The particles retain their existing masses, positions, velocities, and collision
radii. Density pressure and viscosity participate in the native Newton/PCG solve.
viscosity is dynamic viscosity in Pa*s; bulk_modulus is in Pa. The kernel
has compact support at smoothing_radius meters. Neighbor search excludes all
unselected particles, including cloth and affine coordinates.
Optional fixed boundary samples contribute their quadrature volume to density. Author collision shapes separately to prevent penetration. Boundary samples are static world-space data, not moving rigid-body or cloth boundary attachments. Multiple Newton worlds are isolated; fixed samples are shared world-space geometry. Calling this again replaces the material and its selection on the model.
configure_granular¶
configure_granular(model, particle_indices, *, contact_stiffness: float=2000.0, friction: float=0.5, friction_damping: float=20.0, cohesion: float=200.0, bond_damping: float=0.0, yield_strain: float=0.03, max_compaction: float=0.4, break_strain: float=0.1, bond_radius: float | None=None, bond_indices=None, adhesion: float=0.0, bond_formation_gap: float=0.0, bond_formation_speed: float=1.0, max_dynamic_bonds: int=12) -> None
Select granular particles before constructing NewtonSolver.
Particle radii define spherical contact cores. Normal contact stiffness and
cohesive bond stiffness (cohesion) are in N/m; friction is a Coulomb
coefficient and friction_damping its low-speed regularization in N*s/m.
Grain contacts participate in Newton/PCG even when self collision is disabled.
Enable self collision separately for contacts with other particles or cloth.
Shape contacts use the model's ordinary soft-contact and shape materials.
Initial pairs within bond_radius are bonded, respecting world boundaries.
Its default is 2.5 times the largest selected particle radius. Zero cohesion
disables bonds. Bonds resist relative distance changes; compression beyond
yield_strain times the initial length permanently shortens their rest
length, up to max_compaction of the initial length. Tension beyond
break_strain times the committed rest length breaks the bond irreversibly.
Explicit bond_indices (N, 2) can replace the initial radius selection.
They reference model particle IDs; their rest lengths come from initial positions.
bond_damping is axial Kelvin-Voigt damping in N*s/m for intact initial and
contact-created bonds. It opposes bond length changes, preserves rigid motion,
and ceases on fracture. Its default of zero preserves undamped bond behavior.
Positive adhesion enables new contact bonds in N/m, after accepted steps.
Pairs must approach within their summed radii plus bond_formation_gap and
relative speed at most bond_formation_speed. New bonds start stress-free.
Each lower-index grain owns at most max_dynamic_bonds contact bonds (1..64).
Full slots skip additional adhesion; repulsive contacts remain uncapped.
Authored bonds never heal. Broken contact bonds can reform after separation
beyond the formation gap and later recontact. By default adhesion is disabled.
This is a coarse grain model, without grain rotations,
persistent tangential friction history, temperature, or phase changes.
Plastic and fracture history belongs to the solver and advances once per substep. Reconstruct the solver to reset history; restoring only particle positions and velocities does not reset it. Calling this function again replaces the selection and authored material for subsequently created solvers.
ParticleSurfaceMesh¶
Triangle mesh with optional interpolated initial particle coordinates for material mapping.
Indices are a flat int32 array with three entries per face. Buffers may be reused by the next reconstruction; copy them before retaining a mesh across rebuilds.
ParticleSurface¶
Reconstruct closed particle surfaces with a weighted-center field and marching cubes.
initial_positions and every rebuild input must contain the same selected
particles in the same order, excluding solver auxiliaries and boundary samples.
CUDA is required. Reconstruction synchronizes and allocates dynamically, so call
it outside a simulation CUDA graph. Defaults use a voxel size of spacing / 3,
support radius of 2 * spacing, and surface radius of 0.6 * spacing.
Optional bonds (vec2i indices into the selection) and broken flags (int32, nonzero
for broken) reconstruct connected material pieces separately, including after
recontact. Without bonds, nearby fluid particles can merge naturally. Enable
interpolate_rest_positions to map persistent material onto newly exposed faces.
__init__¶
__init__(self, spacing: float, initial_positions: wp.array, *, voxel_size: float | None=None, support_radius: float | None=None, surface_radius: float | None=None, bonds: wp.array | None=None, broken: wp.array | None=None, interpolate_rest_positions: bool=False)
rebuild¶
Build a mesh following current positions, with flat triangle indices and optional rest coordinates.
log_surface_mesh¶
log_surface_mesh(viewer, name: str, mesh: ParticleSurfaceMesh, *, uvs=None, texture=None, color=None, roughness=None, metallic=None, texture_lookup: bool=False)
Log changing mesh topology to Newton viewers; lookup textures disable spatial mipmap filtering.
transform_shape_vertices_kernel¶
transform_shape_vertices_kernel(index: wp.int32, scale_vertices: wp.int32, vertices_in: wp.array[wp.vec3], scaling3d: wp.array[wp.vec3], transforms: wp.array[wp.transform], vertices_out: wp.array[wp.vec3])
transform_to_mat4x4_kernel¶
apply_particle_picking_force_kernel¶
apply_particle_picking_force_kernel(particle_q: wp.array[wp.vec3], particle_f: wp.array[wp.vec3], particle_flags: wp.array[wp.int32], particle_mass: wp.array[float], pick_particles: wp.array[int], pick_weights: wp.array[float], pick_target: wp.array[wp.vec3], pick_stiffness: float, pick_max_force: float)
ViewerPolyscope¶
Polyscope-backed viewer for Newton models.
__init__¶
Initialize a 3D renderer with customizable window properties. Args: window_size (Tuple[int, int]): Window dimensions (width, height)
set_model¶
Register Newton model geometry with Polyscope.
log_state¶
Update registered Polyscope structures from the current Newton state.
is_key_down¶
is_running¶
is_paused¶
should_step¶
begin_frame¶
end_frame¶
requests_close¶
shut_dwon¶
frame_tick¶
exit¶
run¶
apply_forces¶
log_array¶
log_instances¶
log_instances(self, name: str, mesh: Mesh, xforms, scales, colors, materials, hidden: bool=False) -> None
log_lines¶
log_mesh¶
log_mesh(self, name: str, points, indices, normals=None, uvs=None, texture=None, hidden: bool=False, backface_culling: bool=True) -> None
log_points¶
Log or update a Polyscope point cloud without clobbering UI-edited display settings.