-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
2024 lines (1550 loc) · 73.6 KB
/
model.py
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
# Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved.
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
"""A module for building simulation models and state.
"""
from operator import pos
from warp.sim.articulation import eval_articulation_fk
import warp as wp
import math
import numpy as np
from typing import Tuple
from typing import List
Vec3 = List[float]
Vec4 = List[float]
Quat = List[float]
Mat33 = List[float]
Transform = Tuple[Vec3, Quat]
# shape geometry types
GEO_SPHERE = wp.constant(0)
GEO_BOX = wp.constant(1)
GEO_CAPSULE = wp.constant(2)
GEO_MESH = wp.constant(3)
GEO_SDF = wp.constant(4)
GEO_PLANE = wp.constant(5)
GEO_NONE = wp.constant(6)
GEO_DENSE_SDF = wp.constant(7)
# body joint types
JOINT_PRISMATIC = wp.constant(0)
JOINT_REVOLUTE = wp.constant(1)
JOINT_BALL = wp.constant(2)
JOINT_FIXED = wp.constant(3)
JOINT_FREE = wp.constant(4)
JOINT_COMPOUND = wp.constant(5)
JOINT_UNIVERSAL = wp.constant(6)
class Mesh:
"""Describes a triangle collision mesh for simulation
Attributes:
vertices (List[Vec3]): Mesh vertices
indices (List[int]): Mesh indices
I (Mat33): Inertia tensor of the mesh assuming density of 1.0 (around the center of mass)
mass (float): The total mass of the body assuming density of 1.0
com (Vec3): The center of mass of the body
"""
def __init__(self, vertices: List[Vec3], indices: List[int], compute_inertia=True):
"""Construct a Mesh object from a triangle mesh
The mesh center of mass and inertia tensor will automatically be
calculated using a density of 1.0. This computation is only valid
if the mesh is closed (two-manifold).
Args:
vertices: List of vertices in the mesh
indices: List of triangle indices, 3 per-element
"""
self.vertices = vertices
self.indices = indices
if compute_inertia:
# compute com and inertia (using density=1.0)
com = np.mean(vertices, 0)
num_tris = int(len(indices) / 3)
# compute signed inertia for each tetrahedron
# formed with the interior point, using an order-2
# quadrature: https://www.sciencedirect.com/science/article/pii/S0377042712001604#br000040
weight = 0.25
alpha = math.sqrt(5.0) / 5.0
I = np.zeros((3, 3))
mass = 0.0
for i in range(num_tris):
p = np.array(vertices[indices[i * 3 + 0]])
q = np.array(vertices[indices[i * 3 + 1]])
r = np.array(vertices[indices[i * 3 + 2]])
mid = (com + p + q + r) / 4.0
pcom = p - com
qcom = q - com
rcom = r - com
Dm = np.matrix((pcom, qcom, rcom)).T
volume = np.linalg.det(Dm) / 6.0
# quadrature points lie on the line between the
# centroid and each vertex of the tetrahedron
quads = (mid + (p - mid) * alpha, mid + (q - mid) * alpha, mid + (r - mid) * alpha, mid + (com - mid) * alpha)
for j in range(4):
# displacement of quadrature point from COM
d = quads[j] - com
I += weight * volume * (wp.dot(d,d) * np.eye(3, 3) - np.outer(d, d))
mass += weight * volume
self.I = I
self.mass = mass
self.com = com
else:
self.I = np.eye(3, dtype=np.float32)
self.mass = 1.0
self.com = np.array((0.0, 0.0, 0.0))
# construct simulation ready buffers from points
def finalize(self, device):
pos = wp.array(self.vertices, dtype=wp.vec3, device=device)
vel = wp.zeros_like(pos)
indices = wp.array(self.indices, dtype=wp.int32, device=device)
self.mesh = wp.Mesh(points=pos, velocities=vel, indices=indices)
return self.mesh.id
class DenseVolume:
def __init__(
self,
data: np.ndarray,
position: np.ndarray,
scale: np.ndarray,
mesh: Mesh = None,
I: np.ndarray = None,
mass: float = None,
com: np.ndarray = None,
):
self.data = data
self.position = position
self.scale = scale
self.mesh = mesh # for rendering
if I is not None:
self.I = np.asanyarray(I).astype(np.float32)
elif mesh:
self.I = mesh.I
if mass is not None:
self.mass = mass
elif mesh:
self.mass = mesh.mass
if com is not None:
self.com = np.asanyarray(com).astype(np.float32)
elif mesh:
self.com = mesh.com
assert self.mass is not None
assert self.I.shape == (3, 3)
assert self.com.shape == (3,)
def finalize(self, device):
self.dense_volume = wp.DenseVolume(self.data, self.position, (0, 0, 0, 1), self.scale, device=device)
return self.dense_volume.id
class State:
"""The State object holds all *time-varying* data for a model.
Time-varying data includes particle positions, velocities, rigid body states, and
anything that is output from the integrator as derived data, e.g.: forces.
The exact attributes depend on the contents of the model. State objects should
generally be created using the :func:`Model.state()` function.
Attributes:
particle_q (wp.array): Tensor of particle positions
particle_qd (wp.array): Tensor of particle velocities
body_q (wp.array): Tensor of body coordinates
body_qd (wp.array): Tensor of body velocities
"""
def __init__(self):
self.particle_count = 0
self.body_count = 0
def clear_forces(self):
if self.particle_count:
self.particle_f.zero_()
if self.body_count:
self.body_f.zero_()
def flatten(self):
"""Returns a list of Tensors stored by the state
This function is intended to be used internal-only but can be used to obtain
a set of all tensors owned by the state.
"""
tensors = []
# build a list of all tensor attributes
for attr, value in self.__dict__.items():
if (wp.is_tensor(value)):
tensors.append(value)
return tensors
class Model:
"""Holds the definition of the simulation model
This class holds the non-time varying description of the system, i.e.:
all geometry, constraints, and parameters used to describe the simulation.
Attributes:
particle_q (wp.array): Particle positions, shape [particle_count, 3], float
particle_qd (wp.array): Particle velocities, shape [particle_count, 3], float
particle_mass (wp.array): Particle mass, shape [particle_count], float
particle_inv_mass (wp.array): Particle inverse mass, shape [particle_count], float
shape_transform (wp.array): Rigid shape transforms, shape [shape_count, 7], float
shape_body (wp.array): Rigid shape body index, shape [shape_count], int
shape_geo_type (wp.array): Rigid shape geometry type, [shape_count], int
shape_geo_src (wp.array): Rigid shape geometry source, shape [shape_count], int
shape_geo_scale (wp.array): Rigid shape geometry scale, shape [shape_count, 3], float
shape_materials (wp.array): Rigid shape contact materials, shape [shape_count, 4], float
spring_indices (wp.array): Particle spring indices, shape [spring_count*2], int
spring_rest_length (wp.array): Particle spring rest length, shape [spring_count], float
spring_stiffness (wp.array): Particle spring stiffness, shape [spring_count], float
spring_damping (wp.array): Particle spring damping, shape [spring_count], float
spring_control (wp.array): Particle spring activation, shape [spring_count], float
tri_indices (wp.array): Triangle element indices, shape [tri_count*3], int
tri_poses (wp.array): Triangle element rest pose, shape [tri_count, 2, 2], float
tri_activations (wp.array): Triangle element activations, shape [tri_count], float
edge_indices (wp.array): Bending edge indices, shape [edge_count*2], int
edge_rest_angle (wp.array): Bending edge rest angle, shape [edge_count], float
tet_indices (wp.array): Tetrahedral element indices, shape [tet_count*4], int
tet_poses (wp.array): Tetrahedral rest poses, shape [tet_count, 3, 3], float
tet_activations (wp.array): Tetrahedral volumetric activations, shape [tet_count], float
tet_materials (wp.array): Tetrahedral elastic parameters in form :math:`k_{mu}, k_{lambda}, k_{damp}`, shape [tet_count, 3]
body_com (wp.array): Rigid body center of mass (in local frame), shape [body_count, 7], float
body_inertia (wp.array): Rigid body inertia tensor (relative to COM), shape [body_count, 3, 3], float
joint_type (wp.array): Joint type, shape [joint_count], int
joint_parent (wp.array): Joint parent, shape [joint_count], int
joint_X_pj (wp.array): Joint transform in parent frame, shape [joint_count, 7], float
joint_X_cm (wp.array): Joint mass frame in child frame, shape [joint_count, 7], float
joint_axis (wp.array): Joint axis in child frame, shape [joint_count, 3], float
joint_armature (wp.array): Armature for each joint, shape [joint_count], float
joint_target_ke (wp.array): Joint stiffness, shape [joint_count], float
joint_target_kd (wp.array): Joint damping, shape [joint_count], float
joint_target (wp.array): Joint target, shape [joint_count], float
particle_count (int): Total number of particles in the system
body_count (int): Total number of bodies in the system
shape_count (int): Total number of shapes in the system
tri_count (int): Total number of triangles in the system
tet_count (int): Total number of tetrahedra in the system
edge_count (int): Total number of edges in the system
spring_count (int): Total number of springs in the system
contact_count (int): Total number of contacts in the system
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.
"""
def __init__(self, device):
self.particle_q = None
self.particle_qd = None
self.particle_mass = None
self.particle_inv_mass = None
self.shape_transform = None
self.shape_body = None
self.shape_geo_type = None
self.shape_geo_src = None
self.shape_geo_scale = None
self.shape_materials = None
self.spring_indices = None
self.spring_rest_length = None
self.spring_stiffness = None
self.spring_damping = None
self.spring_control = None
self.tri_indices = None
self.tri_poses = None
self.tri_activations = None
self.tri_materials = None
self.edge_indices = None
self.edge_rest_angle = None
self.edge_bending_properties = None
self.tet_indices = None
self.tet_poses = None
self.tet_activations = None
self.tet_materials = None
self.body_com = None
self.body_inertia = None
self.joint_type = None
self.joint_parent = None
self.joint_child = None
self.joint_X_p = None
self.joint_X_c = None
self.joint_axis = None
self.joint_armature = None
self.joint_target_ke = None
self.joint_target_kd = None
self.joint_target = None
# todo: per-joint values?
self.joint_attach_ke = 1.e+3
self.joint_attach_kd = 1.e+2
self.particle_count = 0
self.body_count = 0
self.shape_count = 0
self.tri_count = 0
self.tet_count = 0
self.edge_count = 0
self.spring_count = 0
self.contact_count = 0
self.gravity = np.array((0.0, -9.8, 0.0))
self.soft_contact_distance = 0.1
self.soft_contact_margin = 0.2
self.soft_contact_ke = 1.e+3
self.soft_contact_kd = 10.0
self.soft_contact_kf = 1.e+3
self.soft_contact_mu = 0.5
self.edge_bending_properties = None
self.particle_radius = 0.0
self.particle_ke = 1.e+3
self.particle_kd = 1.e+2
self.particle_kf = 1.e+2
self.particle_mu = 0.5
self.particle_cohesion = 0.0
self.particle_adhesion = 0.0
self.particle_grid = None
self.device = device
def state(self, requires_grad=False) -> State:
"""Returns a state object for the model
The returned state will be initialized with the initial configuration given in
the model description.
"""
s = State()
s.particle_count = self.particle_count
s.body_count = self.body_count
#--------------------------------
# dynamic state (input, output)
s.particle_q = None
s.particle_qd = None
s.particle_f = None
s.body_q = None
s.body_qd = None
s.body_f = None
# particles
if (self.particle_count):
s.particle_q = wp.clone(self.particle_q)
s.particle_qd = wp.clone(self.particle_qd)
s.particle_f = wp.zeros_like(self.particle_qd)
s.particle_q.requires_grad = requires_grad
s.particle_qd.requires_grad = requires_grad
s.particle_f.requires_grad = requires_grad
# articulations
if (self.body_count):
s.body_q = wp.clone(self.body_q)
s.body_qd = wp.clone(self.body_qd)
s.body_f = wp.zeros_like(self.body_qd)
s.body_q.requires_grad = requires_grad
s.body_qd.requires_grad = requires_grad
s.body_f.requires_grad = requires_grad
return s
def flatten(self):
"""Returns a list of Tensors stored by the model
This function is intended to be used internal-only but can be used to obtain
a set of all tensors owned by the model.
"""
tensors = []
# build a list of all tensor attributes
for attr, value in self.__dict__.items():
if (wp.is_tensor(value)):
tensors.append(value)
return tensors
# builds contacts
def collide(self, state: State):
"""Constructs a set of contacts between rigid bodies and ground
This method performs collision detection between rigid body vertices in the scene and updates
the model's set of contacts stored as the following attributes:
* **contact_body0**: Tensor of ints with first rigid body index
* **contact_body1**: Tensor of ints with second rigid body index (currently always -1 to indicate ground)
* **contact_point0**: Tensor of Vec3 representing contact point in local frame of body0
* **contact_dist**: Tensor of float values representing the distance to maintain
* **contact_material**: Tensor contact material indices
Args:
state: The state of the simulation at which to perform collision detection
Note:
Currently this method uses an 'all pairs' approach to contact generation that is
state independent. In the future this will change and will create a node in
the computational graph to propagate gradients as a function of state.
Todo:
Only ground-plane collision is currently implemented. Since the ground is static
it is acceptable to call this method once at initialization time.
"""
body0 = []
body1 = []
point = []
dist = []
mat = []
def add_contact(b0, b1, t, p0, d, m):
body0.append(b0)
body1.append(b1)
point.append(wp.transform_point(t, np.array(p0)))
dist.append(d)
mat.append(m)
# pull shape data back to CPU
shape_transform = self.shape_transform.to("cpu").numpy()
shape_body = self.shape_body.to("cpu").numpy()
shape_geo_type = self.shape_geo_type.to("cpu").numpy()
shape_geo_scale = self.shape_geo_scale.to("cpu").numpy()
shape_geo_src = self.shape_geo_src # already numpy
for i in range(self.shape_count):
# transform from shape to body
X_bs = wp.transform_expand(shape_transform[i].tolist())
geo_type = shape_geo_type[i].item()
if (geo_type == GEO_SPHERE):
radius = shape_geo_scale[i][0].item()
add_contact(shape_body[i], -1, X_bs, (0.0, 0.0, 0.0), radius, i)
elif (geo_type == GEO_CAPSULE):
radius = shape_geo_scale[i][0].item()
half_width = shape_geo_scale[i][1].item()
add_contact(shape_body[i], -1, X_bs, (-half_width, 0.0, 0.0), radius, i)
add_contact(shape_body[i], -1, X_bs, (half_width, 0.0, 0.0), radius, i)
elif (geo_type == GEO_BOX):
edges = shape_geo_scale[i].tolist()
add_contact(shape_body[i], -1, X_bs, (-edges[0], -edges[1], -edges[2]), 0.0, i)
add_contact(shape_body[i], -1, X_bs, ( edges[0], -edges[1], -edges[2]), 0.0, i)
add_contact(shape_body[i], -1, X_bs, (-edges[0], edges[1], -edges[2]), 0.0, i)
add_contact(shape_body[i], -1, X_bs, (edges[0], edges[1], -edges[2]), 0.0, i)
add_contact(shape_body[i], -1, X_bs, (-edges[0], -edges[1], edges[2]), 0.0, i)
add_contact(shape_body[i], -1, X_bs, (edges[0], -edges[1], edges[2]), 0.0, i)
add_contact(shape_body[i], -1, X_bs, (-edges[0], edges[1], edges[2]), 0.0, i)
add_contact(shape_body[i], -1, X_bs, (edges[0], edges[1], edges[2]), 0.0, i)
elif (geo_type == GEO_MESH):
mesh = shape_geo_src[i]
scale = shape_geo_scale[i]
for v in mesh.vertices:
p = (v[0] * scale[0], v[1] * scale[1], v[2] * scale[2])
add_contact(shape_body[i], -1, X_bs, p, 0.0, i)
# send to wp
self.contact_body0 = wp.array(body0, dtype=wp.int32, device=self.device)
self.contact_body1 = wp.array(body1, dtype=wp.int32, device=self.device)
self.contact_point0 = wp.array(point, dtype=wp.vec3, device=self.device)
self.contact_dist = wp.array(dist, dtype=wp.float32, device=self.device)
self.contact_material = wp.array(mat, dtype=wp.int32, device=self.device)
self.contact_count = len(body0)
class ModelBuilder:
"""A helper class for building simulation models at runtime.
Use the ModelBuilder to construct a simulation scene. The ModelBuilder
and builds the scene representation using standard Python data structures (lists),
this means it is not differentiable. Once :func:`finalize()`
has been called the ModelBuilder transfers all data to Warp tensors and returns
an object that may be used for simulation.
Example:
>>> import wp as wp
>>>
>>> builder = wp.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.e+3, 0.0, 0)
>>>
>>> # create model
>>> model = builder.finalize()
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.
"""
default_tri_ke = 100.0
default_tri_ka = 100.0
default_tri_kd = 10.0
default_tri_drag = 0.0
default_tri_lift = 0.0
# Default edge bending properties
default_edge_ke = 100.0
default_edge_kd = 0.0
def __init__(self):
# particles
self.particle_q = []
self.particle_qd = []
self.particle_mass = []
# shapes
self.shape_transform = []
self.shape_body = []
self.shape_geo_type = []
self.shape_geo_scale = []
self.shape_geo_src = []
self.shape_materials = []
# geometry
self.geo_meshes = []
self.geo_sdfs = []
# 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 = []
# edges (bending)
self.edge_indices = []
self.edge_rest_angle = []
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_activation = []
self.muscle_bodies = []
self.muscle_points = []
# rigid bodies
self.body_mass = []
self.body_inertia = []
self.body_com = []
self.body_q = []
self.body_qd = []
# rigid joints
self.joint_parent = [] # index of the parent body (constant)
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_type = []
self.joint_armature = []
self.joint_target_ke = []
self.joint_target_kd = []
self.joint_target = []
self.joint_limit_lower = []
self.joint_limit_upper = []
self.joint_limit_ke = []
self.joint_limit_kd = []
self.joint_act = []
self.joint_q_start = []
self.joint_qd_start = []
self.articulation_start = []
self.joint_count = 0
self.joint_dof_count = 0
self.joint_coord_count = 0
# 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.:
#
# model.eval_articulation_fk()
# model.eval_articulation_j()
# model.eval_articulation_m()
#
# articulations are automatically 'closed' when calling finalize
def add_articulation(self):
self.articulation_start.append(self.joint_count)
def add_rigid_articulation(self, articulation, xform=None):
"""Copies a rigid articulation from `articulation`, another `ModelBuilder`.
Args:
articulation: a model builder to add rigid articulation from.
xform: root position of this body (overrides that in the articulation_builder)
"""
if xform is not None:
if articulation.joint_type[0] == wp.sim.JOINT_FREE:
start = articulation.joint_q_start[0]
articulation.joint_q[start + 0] = xform.p[0]
articulation.joint_q[start + 1] = xform.p[1]
articulation.joint_q[start + 2] = xform.p[2]
articulation.joint_q[start + 3] = xform.q[0]
articulation.joint_q[start + 4] = xform.q[1]
articulation.joint_q[start + 5] = xform.q[2]
articulation.joint_q[start + 6] = xform.q[3]
else:
articulation.joint_X_p[0] = xform
self.add_articulation()
start_body_idx = len(self.body_mass)
# offset the indices
self.joint_parent.extend([p + self.joint_count if p != -1 else -1 for p in articulation.joint_parent])
self.joint_child.extend([c + self.joint_count for c in articulation.joint_child])
self.joint_q_start.extend([c + self.joint_coord_count for c in articulation.joint_q_start])
self.joint_qd_start.extend([c + self.joint_dof_count for c in articulation.joint_qd_start])
self.shape_body.extend([b + start_body_idx for b in articulation.shape_body])
rigid_articulation_attrs = [
"body_inertia",
"body_mass",
"body_com",
"body_q",
"body_qd",
"joint_type",
"joint_X_p",
"joint_X_c",
"joint_armature",
"joint_axis",
"joint_q",
"joint_qd",
"joint_act",
"joint_limit_lower",
"joint_limit_upper",
"joint_limit_ke",
"joint_limit_kd",
"joint_target_ke",
"joint_target_kd",
"joint_target",
"shape_transform",
"shape_geo_type",
"shape_geo_scale",
"shape_geo_src",
"shape_materials",
]
for attr in rigid_articulation_attrs:
getattr(self, attr).extend(getattr(articulation, attr))
self.joint_count += articulation.joint_count
self.joint_dof_count += articulation.joint_dof_count
self.joint_coord_count += articulation.joint_coord_count
# register a rigid body and return its index.
def add_body(
self,
origin : Transform,
parent : int=-1,
joint_xform : Transform=wp.transform(), # transform of joint in parent space
joint_xform_child: Transform=wp.transform(),
joint_axis : Vec3=(0.0, 0.0, 0.0),
joint_type : wp.constant=JOINT_FREE,
joint_target_ke: float=0.0,
joint_target_kd: float=0.0,
joint_limit_ke: float=100.0,
joint_limit_kd: float=10.0,
joint_limit_lower: float=-1.e+3,
joint_limit_upper: float=1.e+3,
joint_armature: float=0.0,
com: Vec3=np.zeros(3),
I_m: Mat33=np.zeros((3, 3)),
m: float=0.0) -> int:
"""Adds a rigid body to the model.
Args:
parent: The index of the parent body
origin: The location of the joint in the parent's local frame connecting this body
axis: The joint axis
type: The type of joint, should be one of: JOINT_PRISMATIC, JOINT_REVOLUTE, JOINT_BALL, JOINT_FIXED, or JOINT_FREE
armature: Additional inertia around the joint axis
stiffness: Spring stiffness that attempts to return joint to zero position
damping: Spring damping that attempts to remove joint velocity
com: The center of mass of the body w.r.t its origin
I_m: The 3x3 inertia tensor of the body (specified relative to the center of mass)
m: The mass of the body
Returns:
The index of the body in the model
Note:
If the mass (m) is zero then the body is treated as kinematic with no dynamics
"""
child = len(self.body_mass)
# body data
self.body_inertia.append(I_m + np.eye(3)*joint_armature)
self.body_mass.append(m)
self.body_com.append(com)
self.body_q.append(origin)
self.body_qd.append(wp.spatial_vector())
# joint data
self.joint_type.append(joint_type.val)
self.joint_parent.append(parent)
self.joint_child.append(child)
self.joint_X_p.append(joint_xform)
self.joint_X_c.append(joint_xform_child)
self.joint_armature.append(joint_armature)
self.joint_axis.append(np.array(joint_axis))
if (joint_type == JOINT_PRISMATIC):
dof_count = 1
coord_count = 1
elif (joint_type == JOINT_REVOLUTE):
dof_count = 1
coord_count = 1
elif (joint_type == JOINT_BALL):
dof_count = 3
coord_count = 4
elif (joint_type == JOINT_FREE):
dof_count = 6
coord_count = 7
elif (joint_type == JOINT_FIXED):
dof_count = 0
coord_count = 0
elif (joint_type == JOINT_COMPOUND):
dof_count = 3
coord_count = 3
elif (joint_type == JOINT_UNIVERSAL):
dof_count = 2
coord_count = 2
# convert coefficients to np.arrays() so we can index into them for
# compound joints, this just allows user to pass scalars or arrays
# coefficients will be automatically padded to number of dofs
joint_target_ke = np.resize(np.atleast_1d(joint_target_ke), dof_count)
joint_target_kd = np.resize(np.atleast_1d(joint_target_kd), dof_count)
joint_limit_ke = np.resize(np.atleast_1d(joint_limit_ke), dof_count)
joint_limit_kd = np.resize(np.atleast_1d(joint_limit_kd), dof_count)
joint_limit_lower = np.resize(np.atleast_1d(joint_limit_lower), dof_count)
joint_limit_upper = np.resize(np.atleast_1d(joint_limit_upper), dof_count)
for i in range(coord_count):
self.joint_q.append(0.0)
for i in range(dof_count):
self.joint_qd.append(0.0)
self.joint_act.append(0.0)
self.joint_limit_lower.append(joint_limit_lower[i])
self.joint_limit_upper.append(joint_limit_upper[i])
self.joint_limit_ke.append(joint_limit_ke[i])
self.joint_limit_kd.append(joint_limit_kd[i])
self.joint_target_ke.append(joint_target_ke[i])
self.joint_target_kd.append(joint_target_kd[i])
self.joint_target.append(0.0)
self.joint_q_start.append(self.joint_coord_count)
self.joint_qd_start.append(self.joint_dof_count)
self.joint_count += 1
self.joint_dof_count += dof_count
self.joint_coord_count += coord_count
# return index of child body / joint
return child
# muscles
def add_muscle(self, bodies: List[int], positions: List[Vec3], f0: float, lm: float, lt: float, lmax: float, pen: float) -> float:
"""Adds a muscle-tendon activation unit
Args:
bodies: A list of body indices for each waypoint
positions: A list of positions of each waypoint in the body's local frame
f0: Force scaling
lm: Muscle length
lt: Tendon length
lmax: Maximally efficient muscle length
Returns:
The index of the muscle in the model
"""
n = len(bodies)
self.muscle_start.append(len(self.muscle_bodies))
self.muscle_params.append((f0, lm, lt, lmax, pen))
self.muscle_activation.append(0.0)
for i in range(n):
self.muscle_bodies.append(bodies[i])
self.muscle_points.append(positions[i])
# return the index of the muscle
return len(self.muscle_start)-1
# shapes
def add_shape_plane(self, plane: Vec4=(0.0, 1.0, 0.0, 0.0), ke: float=1.e+5, kd: float=1000.0, kf: float=1000.0, mu: float=0.5):
"""Adds a plane collision shape
Args:
plane: The plane equation in form a*x + b*y + c*z + d = 0
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
"""
self._add_shape(-1, (0.0, 0.0, 0.0), (0.0, 0.0, 0.0), GEO_PLANE, plane, None, 0.0, ke, kd, kf, mu)
def add_shape_sphere(self, body, pos: Vec3=(0.0, 0.0, 0.0), rot: Quat=(0.0, 0.0, 0.0, 1.0), radius: float=1.0, density: float=1000.0, ke: float=1.e+5, kd: float=1000.0, kf: float=1000.0, mu: float=0.5):
"""Adds a sphere collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the sphere
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
"""
self._add_shape(body, pos, rot, GEO_SPHERE, (radius, 0.0, 0.0, 0.0), None, density, ke, kd, kf, mu)
def add_shape_box(self,
body : int,
pos: Vec3=(0.0, 0.0, 0.0),
rot: Quat=(0.0, 0.0, 0.0, 1.0),
hx: float=0.5,
hy: float=0.5,
hz: float=0.5,
density: float=1000.0,
ke: float=1.e+5,
kd: float=1000.0,
kf: float=1000.0,
mu: float=0.5):
"""Adds a box collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
hx: The half-extents along the x-axis
hy: The half-extents along the y-axis
hz: The half-extents along the z-axis
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
"""
self._add_shape(body, pos, rot, GEO_BOX, (hx, hy, hz, 0.0), None, density, ke, kd, kf, mu)
def add_shape_capsule(self,
body: int,
pos: Vec3=(0.0, 0.0, 0.0),
rot: Quat=(0.0, 0.0, 0.0, 1.0),
radius: float=1.0,
half_width: float=0.5,
density: float=1000.0,
ke: float=1.e+5,
kd: float=1000.0,
kf: float=1000.0,
mu: float=0.5):
"""Adds a capsule collision shape to a body.
Args:
body: The index of the parent body this shape belongs to
pos: The location of the shape with respect to the parent frame
rot: The rotation of the shape with respect to the parent frame
radius: The radius of the capsule
half_width: The half length of the center cylinder along the x-axis
density: The density of the shape
ke: The contact elastic stiffness
kd: The contact damping stiffness
kf: The contact friction stiffness
mu: The coefficient of friction
"""
self._add_shape(body, pos, rot, GEO_CAPSULE, (radius, half_width, 0.0, 0.0), None, density, ke, kd, kf, mu)
def add_shape_mesh(self,
body: int,
pos: Vec3=(0.0, 0.0, 0.0),
rot: Quat=(0.0, 0.0, 0.0, 1.0),