-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathbuilder.py
More file actions
4559 lines (3988 loc) · 199 KB
/
builder.py
File metadata and controls
4559 lines (3988 loc) · 199 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: Copyright (c) 2025 The Newton Developers
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A module for building Newton models."""
from __future__ import annotations
import copy
import ctypes
import itertools
import math
import warnings
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
import warp as wp
from ..core.types import (
Axis,
AxisType,
Devicelike,
Mat33,
Quat,
Sequence,
Transform,
Vec3,
Vec4,
axis_to_vec3,
flag_to_int,
nparray,
)
from ..geometry import (
MESH_MAXHULLVERT,
SDF,
GeoType,
Mesh,
ParticleFlags,
ShapeFlags,
compute_shape_inertia,
compute_shape_radius,
transform_inertia,
)
from ..geometry.inertia import validate_and_correct_inertia_kernel, verify_and_correct_inertia
from ..geometry.utils import RemeshingMethod, compute_obb, remesh_mesh
from .graph_coloring import ColoringAlgorithm, color_trimesh, combine_independent_particle_coloring
from .joints import (
EqType,
JointMode,
JointType,
get_joint_dof_count,
)
from .model import Model
class ModelBuilder:
"""A 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 :meth:`finalize` to construct a simulation-ready Model.
Example
-------
.. testcode::
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)
for i in range(10):
state_0.clear_forces()
contacts = model.collide(state_0)
solver.step(state_0, state_1, control, contacts, dt=1.0 / 60.0)
state_0, state_1 = state_1, state_0
Environment Grouping
--------------------
ModelBuilder supports environment grouping to organize entities for multi-environment simulations.
Each entity (particle, body, shape, joint, articulation) has an associated group index:
- Group -1: Global entities shared across all environments (e.g., ground plane)
- Group 0, 1, 2, ...: Environment-specific entities
There are two ways to assign environment groups:
1. **Direct entity creation**: Entities inherit the builder's `current_env_group` value::
builder = ModelBuilder()
builder.current_env_group = -1 # Following entities will be global
builder.add_ground_plane()
builder.current_env_group = 0 # Following entities will be in environment 0
builder.add_body(...)
2. **Using add_builder()**: ALL entities from the sub-builder are assigned to the specified group::
robot = ModelBuilder()
robot.add_body(...) # Group assignments here will be overridden
main = ModelBuilder()
main.add_builder(robot, environment=0) # All robot entities -> group 0
main.add_builder(robot, environment=1) # All robot entities -> group 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.
"""
@dataclass
class ShapeConfig:
"""
Represents the properties of a collision shape used in simulation.
"""
density: float = 1000.0
"""The density of the shape material."""
ke: float = 1.0e5
"""The contact elastic stiffness."""
kd: float = 1000.0
"""The contact damping stiffness."""
kf: float = 1000.0
"""The contact friction stiffness."""
ka: float = 0.0
"""The contact adhesion distance."""
mu: float = 0.5
"""The coefficient of friction."""
restitution: float = 0.0
"""The coefficient of restitution."""
thickness: float = 1e-5
"""The thickness of the shape."""
is_solid: bool = True
"""Indicates whether the shape is solid or hollow. Defaults to True."""
collision_group: int = -1
"""The collision group ID for the shape. Defaults to -1."""
collision_filter_parent: bool = True
"""Whether to inherit collision filtering from the parent. Defaults to True."""
has_shape_collision: bool = True
"""Whether the shape can collide with other shapes. Defaults to True."""
has_particle_collision: bool = True
"""Whether the shape can collide with particles. Defaults to True."""
is_visible: bool = True
"""Indicates whether the shape is visible in the simulation. Defaults to True."""
@property
def flags(self) -> int:
"""Returns the flags for the shape."""
shape_flags = ShapeFlags.VISIBLE if self.is_visible else 0
shape_flags |= ShapeFlags.COLLIDE_SHAPES if self.has_shape_collision else 0
shape_flags |= ShapeFlags.COLLIDE_PARTICLES if self.has_particle_collision else 0
return shape_flags
@flags.setter
def flags(self, value: int):
"""Sets the flags for the shape."""
self.is_visible = bool(value & ShapeFlags.VISIBLE)
self.has_shape_collision = bool(value & ShapeFlags.COLLIDE_SHAPES)
self.has_particle_collision = bool(value & ShapeFlags.COLLIDE_PARTICLES)
def copy(self) -> ModelBuilder.ShapeConfig:
return copy.copy(self)
class JointDofConfig:
"""
Describes a joint axis (a single degree of freedom) that can have limits and be driven towards a target.
"""
def __init__(
self,
axis: AxisType | Vec3 = Axis.X,
limit_lower: float = -1e6,
limit_upper: float = 1e6,
limit_ke: float = 1e4,
limit_kd: float = 1e1,
target: float = 0.0,
target_ke: float = 0.0,
target_kd: float = 0.0,
mode: int = JointMode.TARGET_POSITION,
armature: float = 1e-2,
effort_limit: float = 1e6,
velocity_limit: float = 1e6,
friction: float = 0.0,
):
self.axis = wp.normalize(axis_to_vec3(axis))
"""The 3D axis that this JointDofConfig object describes."""
self.limit_lower = limit_lower
"""The lower position limit of the joint axis. Defaults to -1e6."""
self.limit_upper = limit_upper
"""The upper position limit of the joint axis. Defaults to 1e6."""
self.limit_ke = limit_ke
"""The elastic stiffness of the joint axis limits. Defaults to 1e4."""
self.limit_kd = limit_kd
"""The damping stiffness of the joint axis limits. Defaults to 1e1."""
self.target = target
"""The target position or velocity (depending on the mode) of the joint axis.
If `mode` is `JointMode.TARGET_POSITION` and the initial `target` is outside the limits,
it defaults to the midpoint of `limit_lower` and `limit_upper`. Otherwise, defaults to 0.0."""
self.target_ke = target_ke
"""The proportional gain of the target drive PD controller. Defaults to 0.0."""
self.target_kd = target_kd
"""The derivative gain of the target drive PD controller. Defaults to 0.0."""
self.mode = mode
"""The mode of the joint axis (e.g., `JointMode.TARGET_POSITION` or `JointMode.TARGET_VELOCITY`). Defaults to `JointMode.TARGET_POSITION`."""
self.armature = armature
"""Artificial inertia added around the joint axis. Defaults to 1e-2."""
self.effort_limit = effort_limit
"""Maximum effort (force or torque) the joint axis can exert. Defaults to 1e6."""
self.velocity_limit = velocity_limit
"""Maximum velocity the joint axis can achieve. Defaults to 1e6."""
self.friction = friction
"""Friction coefficient for the joint axis. Defaults to 0.0."""
if self.mode == JointMode.TARGET_POSITION and (
self.target > self.limit_upper or self.target < self.limit_lower
):
self.target = 0.5 * (self.limit_lower + self.limit_upper)
@classmethod
def create_unlimited(cls, axis: AxisType | Vec3) -> ModelBuilder.JointDofConfig:
"""Creates a JointDofConfig with no limits."""
return ModelBuilder.JointDofConfig(
axis=axis,
limit_lower=-1e6,
limit_upper=1e6,
target=0.0,
target_ke=0.0,
target_kd=0.0,
armature=0.0,
limit_ke=0.0,
limit_kd=0.0,
mode=JointMode.NONE,
)
def __init__(self, up_axis: AxisType = Axis.Z, gravity: float = -9.81):
"""
Initializes a new ModelBuilder instance for constructing simulation models.
Args:
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.
"""
self.num_envs = 0
# region defaults
self.default_shape_cfg = ModelBuilder.ShapeConfig()
self.default_joint_cfg = ModelBuilder.JointDofConfig()
# Default particle settings
self.default_particle_radius = 0.1
# Default triangle soft mesh settings
self.default_tri_ke = 100.0
self.default_tri_ka = 100.0
self.default_tri_kd = 10.0
self.default_tri_drag = 0.0
self.default_tri_lift = 0.0
# Default distance constraint properties
self.default_spring_ke = 100.0
self.default_spring_kd = 0.0
# Default edge bending properties
self.default_edge_ke = 100.0
self.default_edge_kd = 0.0
# Default body settings
self.default_body_armature = 0.0
# endregion
# region compiler settings (similar to MuJoCo)
self.balance_inertia = True
"""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."""
self.bound_mass = 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."""
self.bound_inertia = 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."""
self.validate_inertia_detailed = False
"""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."""
# endregion
# particles
self.particle_q = []
self.particle_qd = []
self.particle_mass = []
self.particle_radius = []
self.particle_flags = []
self.particle_max_velocity = 1e5
self.particle_color_groups: list[nparray] = []
self.particle_group = [] # environment group index for each particle
# shapes (each shape has an entry in these arrays)
self.shape_key = [] # shape keys
# transform from shape to body
self.shape_transform = []
# maps from shape index to body index
self.shape_body = []
self.shape_flags = []
self.shape_type = []
self.shape_scale = []
self.shape_source = []
self.shape_is_solid = []
self.shape_thickness = []
self.shape_material_ke = []
self.shape_material_kd = []
self.shape_material_kf = []
self.shape_material_ka = []
self.shape_material_mu = []
self.shape_material_restitution = []
# collision groups within collisions are handled
self.shape_collision_group = []
self.shape_collision_group_map = {}
self.last_collision_group = 0
# radius to use for broadphase collision checking
self.shape_collision_radius = []
# environment group index for each shape
self.shape_group = []
# filtering to ignore certain collision pairs
self.shape_collision_filter_pairs = set()
# springs
self.spring_indices = []
self.spring_rest_length = []
self.spring_stiffness = []
self.spring_damping = []
self.spring_control = []
# triangles
self.tri_indices = []
self.tri_poses = []
self.tri_activations = []
self.tri_materials = []
self.tri_areas = []
# edges (bending)
self.edge_indices = []
self.edge_rest_angle = []
self.edge_rest_length = []
self.edge_bending_properties = []
# tetrahedra
self.tet_indices = []
self.tet_poses = []
self.tet_activations = []
self.tet_materials = []
# muscles
self.muscle_start = []
self.muscle_params = []
self.muscle_activations = []
self.muscle_bodies = []
self.muscle_points = []
# tendons (fixed)
self.tendon_start = [] # start index in tendon_joints for each tendon
self.tendon_params = [] # (stiffness, damping, rest_length, lower_limit, upper_limit) for each tendon
self.tendon_joints = [] # joint indices attached to tendons
self.tendon_gearings = [] # gearing coefficients for each joint attachment
self.tendon_key = [] # string key for each tendon
# rigid bodies
self.body_mass = []
self.body_inertia = []
self.body_inv_mass = []
self.body_inv_inertia = []
self.body_com = []
self.body_q = []
self.body_qd = []
self.body_key = []
self.body_shapes = {} # mapping from body to shapes
self.body_group = [] # environment group index for each body
# rigid joints
self.joint_parent = [] # index of the parent body (constant)
self.joint_parents = {} # mapping from joint to parent bodies
self.joint_child = [] # index of the child body (constant)
self.joint_axis = [] # joint axis in child joint frame (constant)
self.joint_X_p = [] # frame of joint in parent (constant)
self.joint_X_c = [] # frame of child com (in child coordinates) (constant)
self.joint_q = []
self.joint_qd = []
self.joint_f = []
self.joint_type = []
self.joint_key = []
self.joint_armature = []
self.joint_target_ke = []
self.joint_target_kd = []
self.joint_dof_mode = []
self.joint_limit_lower = []
self.joint_limit_upper = []
self.joint_limit_ke = []
self.joint_limit_kd = []
self.joint_target = []
self.joint_effort_limit = []
self.joint_velocity_limit = []
self.joint_friction = []
self.joint_twist_lower = []
self.joint_twist_upper = []
self.joint_enabled = []
self.joint_q_start = []
self.joint_qd_start = []
self.joint_dof_dim = []
self.joint_group = [] # environment group index for each joint
self.articulation_start = []
self.articulation_key = []
self.articulation_group = [] # environment group index for each articulation
self.joint_dof_count = 0
self.joint_coord_count = 0
# current environment group index for entities being added directly to this builder.
# set to -1 to create global entities shared across all environments.
# note: this value is temporarily overridden when using add_builder().
self.current_env_group = -1
self.up_axis: Axis = Axis.from_any(up_axis)
self.gravity: float = gravity
# contacts to be generated within the given distance margin to be generated at
# every simulation substep (can be 0 if only one PBD solver iteration is used)
self.rigid_contact_margin = 0.1
# torsional friction coefficient (only considered by XPBD so far)
self.rigid_contact_torsional_friction = 0.5
# rolling friction coefficient (only considered by XPBD so far)
self.rigid_contact_rolling_friction = 0.001
# number of rigid contact points to allocate in the model during self.finalize() per environment
# if setting is None, the number of worst-case number of contacts will be calculated in self.finalize()
self.num_rigid_contacts_per_env = None
# equality constraints
self.equality_constraint_type = []
self.equality_constraint_body1 = []
self.equality_constraint_body2 = []
self.equality_constraint_anchor = []
self.equality_constraint_relpose = []
self.equality_constraint_torquescale = []
self.equality_constraint_joint1 = []
self.equality_constraint_joint2 = []
self.equality_constraint_polycoef = []
self.equality_constraint_key = []
self.equality_constraint_enabled = []
@property
def up_vector(self) -> Vec3:
"""
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 :attr:`up_axis`.
For example, if ``up_axis`` is ``Axis.Z``, this returns ``(0, 0, 1)``.
Returns:
Vec3: The 3D up vector corresponding to the current up axis.
"""
return axis_to_vec3(self.up_axis)
@up_vector.setter
def up_vector(self, _):
raise AttributeError(
"The 'up_vector' property is read-only and cannot be set. Instead, use 'up_axis' to set the up axis."
)
# region counts
@property
def shape_count(self):
"""
The number of shapes in the model.
"""
return len(self.shape_type)
@property
def body_count(self):
"""
The number of rigid bodies in the model.
"""
return len(self.body_q)
@property
def joint_count(self):
"""
The number of joints in the model.
"""
return len(self.joint_type)
@property
def particle_count(self):
"""
The number of particles in the model.
"""
return len(self.particle_q)
@property
def tri_count(self):
"""
The number of triangles in the model.
"""
return len(self.tri_poses)
@property
def tet_count(self):
"""
The number of tetrahedra in the model.
"""
return len(self.tet_poses)
@property
def edge_count(self):
"""
The number of edges (for bending) in the model.
"""
return len(self.edge_rest_angle)
@property
def spring_count(self):
"""
The number of springs in the model.
"""
return len(self.spring_rest_length)
@property
def muscle_count(self):
"""
The number of muscles in the model.
"""
return len(self.muscle_start)
@property
def articulation_count(self):
"""
The number of articulations in the model.
"""
return len(self.articulation_start)
# endregion
def _compute_replicate_offsets(self, num_copies: int, spacing: tuple[float, float, float]):
# compute positional offsets per environment
spacing = np.array(spacing)
nonzeros = np.nonzero(spacing)[0]
num_dim = nonzeros.shape[0]
if num_dim > 0:
side_length = int(np.ceil(num_copies ** (1.0 / num_dim)))
spacings = []
if num_dim == 1:
for i in range(num_copies):
spacings.append(i * spacing)
elif num_dim == 2:
for i in range(num_copies):
d0 = i // side_length
d1 = i % side_length
offset = np.zeros(3)
offset[nonzeros[0]] = d0 * spacing[nonzeros[0]]
offset[nonzeros[1]] = d1 * spacing[nonzeros[1]]
spacings.append(offset)
elif num_dim == 3:
for i in range(num_copies):
d0 = i // (side_length * side_length)
d1 = (i // side_length) % side_length
d2 = i % side_length
offset = np.zeros(3)
offset[0] = d0 * spacing[0]
offset[1] = d1 * spacing[1]
offset[2] = d2 * spacing[2]
spacings.append(offset)
spacings = np.array(spacings)
else:
spacings = np.zeros((num_copies, 3))
min_offsets = np.min(spacings, axis=0)
correction = min_offsets + (np.max(spacings, axis=0) - min_offsets) / 2.0
# ensure the envs are not shifted below the ground plane
correction[Axis.from_any(self.up_axis)] = 0.0
spacings -= correction
return spacings
def replicate(
self,
builder: ModelBuilder,
num_copies: int,
spacing: tuple[float, float, float] = (5.0, 5.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, environments)
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 environment group.
Args:
builder (ModelBuilder): The builder to replicate. All entities from this builder will be copied.
num_copies (int): The number of copies 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 (5.0, 5.0, 0.0).
"""
offsets = self._compute_replicate_offsets(num_copies, spacing)
for i in range(num_copies):
self.add_builder(builder, xform=wp.transform(offsets[i], wp.quat_identity()))
def add_articulation(self, key: str | None = None):
# an articulation is a set of contiguous bodies bodies from articulation_start[i] to articulation_start[i+1]
# these are used for computing forward kinematics e.g.:
# articulations are automatically 'closed' when calling finalize
self.articulation_start.append(self.joint_count)
self.articulation_key.append(key or f"articulation_{self.articulation_count}")
self.articulation_group.append(self.current_env_group)
# region importers
def add_urdf(
self,
source: str,
xform: Transform | None = None,
floating: bool = False,
base_joint: dict | str | None = None,
scale: float = 1.0,
hide_visuals: bool = False,
parse_visuals_as_colliders: bool = False,
up_axis: AxisType = Axis.Z,
force_show_colliders: bool = False,
enable_self_collisions: bool = True,
ignore_inertial_definitions: bool = True,
ensure_nonstatic_links: bool = True,
static_link_mass: float = 1e-2,
collapse_fixed_joints: bool = False,
mesh_maxhullvert: int = MESH_MAXHULLVERT,
):
"""
Parses a URDF file and adds the bodies and joints to the given ModelBuilder.
Args:
source (str): The filename of the URDF file to parse.
xform (Transform): The transform to apply to the root body. If None, the transform is set to identity.
floating (bool): If True, the root body is a free joint. If False, the root body is connected via a fixed joint to the world, unless a `base_joint` is defined.
base_joint (Union[str, dict]): The joint by which the root body is connected to the world. This can be either a string defining the joint axes of a D6 joint with comma-separated positional and angular axis names (e.g. "px,py,rz" for a D6 joint with linear axes in x, y and an angular axis in z) or a dict with joint parameters (see :meth:`ModelBuilder.add_joint`).
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).
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.
"""
from ..utils.import_urdf import parse_urdf # noqa: PLC0415
return parse_urdf(
self,
source,
xform,
floating,
base_joint,
scale,
hide_visuals,
parse_visuals_as_colliders,
up_axis,
force_show_colliders,
enable_self_collisions,
ignore_inertial_definitions,
ensure_nonstatic_links,
static_link_mass,
collapse_fixed_joints,
mesh_maxhullvert,
)
def add_usd(
self,
source,
xform: Transform | None = None,
only_load_enabled_rigid_bodies: bool = False,
only_load_enabled_joints: bool = True,
joint_drive_gains_scaling: float = 1.0,
invert_rotations: bool = True,
verbose: bool = False,
ignore_paths: list[str] | None = None,
cloned_env: str | None = None,
collapse_fixed_joints: bool = False,
enable_self_collisions: bool = True,
apply_up_axis_from_stage: bool = False,
root_path: str = "/",
joint_ordering: Literal["bfs", "dfs"] | None = "dfs",
bodies_follow_joint_ordering: bool = True,
skip_mesh_approximation: bool = False,
load_non_physics_prims: bool = True,
hide_collision_shapes: bool = False,
mesh_maxhullvert: int = MESH_MAXHULLVERT,
) -> dict[str, Any]:
"""
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 <https://openusd.org/dev/api/class_usd_stage.html>`_ interface.
Args:
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.
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".
invert_rotations (bool): If True, inverts any rotations defined in the shape transforms.
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.
cloned_env (str): The prim path of an environment which is cloned within this USD file. Siblings of this environment prim will not be parsed but instead be replicated via `ModelBuilder.add_builder(builder, xform)` to speed up the loading of many instantiated environments.
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. If a shape has the attribute ``physxArticulation:enabledSelfCollisions`` defined, this attribute takes precedence.
apply_up_axis_from_stage (bool): If True, the up axis of the stage will be used to set :attr:`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 ``None`` to 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:approximation`` attribute defined on the UsdPhysicsMeshCollisionAPI (if it is defined). Default is False.
load_non_physics_prims (bool): If True, prims that are children of a rigid body that do not have a UsdPhysics schema applied are loaded as visual shapes in a separate pass (may slow down the loading process). Otherwise, non-physics prims are ignored. Default is True.
hide_collision_shapes (bool): If True, collision shapes are hidden. Default is False.
mesh_maxhullvert (int): Maximum vertices for convex hull approximation of meshes.
Returns:
dict: Dictionary with the following entries:
.. list-table::
:widths: 25 75
* - "fps"
- USD stage frames per second
* - "duration"
- Difference between end time code and start time code of the USD stage
* - "up_axis"
- :class:`Axis` representing the stage's up axis ("X", "Y", or "Z")
* - "path_shape_map"
- Mapping from prim path (str) of the UsdGeom to the respective shape index in :class:`ModelBuilder`
* - "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 :class:`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 :meth:`newton.ModelBuilder.collapse_fixed_joints` if `collapse_fixed_joints` is True, otherwise None.
"""
from ..utils.import_usd import parse_usd # noqa: PLC0415
return parse_usd(
self,
source,
xform,
only_load_enabled_rigid_bodies,
only_load_enabled_joints,
joint_drive_gains_scaling,
invert_rotations,
verbose,
ignore_paths,
cloned_env,
collapse_fixed_joints,
enable_self_collisions,
apply_up_axis_from_stage,
root_path,
joint_ordering,
bodies_follow_joint_ordering,
skip_mesh_approximation,
load_non_physics_prims,
hide_collision_shapes,
mesh_maxhullvert,
)
def add_mjcf(
self,
source: str,
xform: Transform | None = None,
floating: bool | None = None,
base_joint: dict | str | None = None,
armature_scale: float = 1.0,
scale: float = 1.0,
hide_visuals: bool = False,
parse_visuals_as_colliders: bool = False,
parse_meshes: bool = True,
up_axis: AxisType = Axis.Z,
ignore_names: Sequence[str] = (),
ignore_classes: Sequence[str] = (),
visual_classes: Sequence[str] = ("visual",),
collider_classes: Sequence[str] = ("collision",),
no_class_as_colliders: bool = True,
force_show_colliders: bool = False,
enable_self_collisions: bool = False,
ignore_inertial_definitions: bool = True,
ensure_nonstatic_links: bool = True,
static_link_mass: float = 1e-2,
collapse_fixed_joints: bool = False,
verbose: bool = False,
skip_equality_constraints: bool = False,
mesh_maxhullvert: int = MESH_MAXHULLVERT,
):
"""
Parses MuJoCo XML (MJCF) file and adds the bodies and joints to the given ModelBuilder.
Args:
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): If True, the articulation is treated as a floating base. If False, the articulation is treated as a fixed base. If None, the articulation is treated as a floating base if a free joint is found in the MJCF, otherwise it is treated as a fixed base.
base_joint (Union[str, dict]): The joint by which the root body is connected to the world. This can be either a string defining the joint axes of a D6 joint with comma-separated positional and angular axis names (e.g. "px,py,rz" for a D6 joint with linear axes in x, y and an angular axis in z) or a dict with joint parameters (see :meth:`ModelBuilder.add_joint`).
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.
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.
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: 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.
mesh_maxhullvert (int): Maximum vertices for convex hull approximation of meshes.
"""
from ..utils.import_mjcf import parse_mjcf # noqa: PLC0415
return parse_mjcf(
self,
source,
xform,
floating,
base_joint,
armature_scale,
scale,
hide_visuals,
parse_visuals_as_colliders,
parse_meshes,
up_axis,
ignore_names,
ignore_classes,
visual_classes,
collider_classes,
no_class_as_colliders,
force_show_colliders,
enable_self_collisions,
ignore_inertial_definitions,
ensure_nonstatic_links,
static_link_mass,
collapse_fixed_joints,
verbose,
skip_equality_constraints,
mesh_maxhullvert,
)
# endregion
def add_builder(
self,
builder: ModelBuilder,
xform: Transform | None = None,
update_num_env_count: bool = True,
separate_collision_group: bool = True,
environment: int | None = None,
):
"""Copies the data from `builder`, another `ModelBuilder` to this `ModelBuilder`.
**Environment Group Behavior:**
When adding a builder, ALL entities from the source builder will be assigned to the same
environment group, overriding any group assignments that existed in the source builder.
This ensures that all entities from a sub-builder are grouped together as a single environment.
To create global entities that are shared across all environments, set the main builder's
`current_env_group` to -1 before adding entities directly (not via add_builder).
Example::
main_builder = ModelBuilder()
# Create global ground plane
main_builder.current_env_group = -1
main_builder.add_ground_plane()
# Create robot builder
robot_builder = ModelBuilder()
robot_builder.add_body(...) # These group assignments will be overridden
# Add multiple robot instances
main_builder.add_builder(robot_builder, environment=0) # All entities -> group 0
main_builder.add_builder(robot_builder, environment=1) # All entities -> group 1
Args:
builder (ModelBuilder): a model builder to add model data from.
xform (Transform): offset transform applied to root bodies.
update_num_env_count (bool): if True, the number of environments is updated appropriately.
For non-global entities (environment >= 0), this either increments num_envs (when environment is None)
or ensures num_envs is at least environment+1. Global entities (environment=-1) do not affect num_envs.
separate_collision_group (bool): if True, the shapes from the articulations in `builder` will all be put into a single new collision group, otherwise, only the shapes in collision group > -1 will be moved to a new group.
environment (int | None): environment group index to assign to ALL entities from this builder.
If None, uses the current environment count as the group index. Use -1 for global entities.
Note: environment=-1 does not increase num_envs even when update_num_env_count=True.
"""
if builder.up_axis != self.up_axis:
raise ValueError("Cannot add a builder with a different up axis.")
# Set the environment group for entities being added
if environment is None:
# Use the current environment count as the group index if not specified
group_idx = self.num_envs if update_num_env_count else self.current_env_group
else:
group_idx = environment
# Save the previous environment group
prev_env_group = self.current_env_group
self.current_env_group = group_idx
# explicitly resolve the transform multiplication function to avoid
# repeatedly resolving builtin overloads during shape transformation
transform_mul_cfunc = wp.context.runtime.core.wp_builtin_mul_transformf_transformf
# dispatches two transform multiplies to the native implementation
def transform_mul(a, b):
out = wp.transformf()
transform_mul_cfunc(a, b, ctypes.byref(out))
return out
start_particle_idx = self.particle_count
if builder.particle_count:
self.particle_max_velocity = builder.particle_max_velocity
if xform is not None:
pos_offset = wp.transform_get_translation(xform)
else:
pos_offset = np.zeros(3)
self.particle_q.extend((np.array(builder.particle_q) + pos_offset).tolist())
# other particle attributes are added below
if builder.spring_count:
self.spring_indices.extend((np.array(builder.spring_indices, dtype=np.int32) + start_particle_idx).tolist())
if builder.edge_count:
# Update edge indices by adding offset, preserving -1 values
edge_indices = np.array(builder.edge_indices, dtype=np.int32)
mask = edge_indices != -1
edge_indices[mask] += start_particle_idx
self.edge_indices.extend(edge_indices.tolist())
if builder.tri_count:
self.tri_indices.extend((np.array(builder.tri_indices, dtype=np.int32) + start_particle_idx).tolist())
if builder.tet_count:
self.tet_indices.extend((np.array(builder.tet_indices, dtype=np.int32) + start_particle_idx).tolist())
builder_coloring_translated = [group + start_particle_idx for group in builder.particle_color_groups]