-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathdetail_sdf_parser.cc
More file actions
3125 lines (2814 loc) · 131 KB
/
Copy pathdetail_sdf_parser.cc
File metadata and controls
3125 lines (2814 loc) · 131 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
#include "drake/multibody/parsing/detail_sdf_parser.h"
#include <cmath>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <variant>
#include <vector>
#include <sdf/Error.hh>
#include <sdf/Frame.hh>
#include <sdf/Joint.hh>
#include <sdf/JointAxis.hh>
#include <sdf/Link.hh>
#include <sdf/Model.hh>
#include <sdf/ParserConfig.hh>
#include <sdf/Root.hh>
#include <sdf/World.hh>
#include "drake/common/text_logging.h"
#include "drake/common/trajectories/piecewise_constant_curvature_trajectory.h"
#include "drake/geometry/geometry_instance.h"
#include "drake/math/rigid_transform.h"
#include "drake/math/roll_pitch_yaw.h"
#include "drake/math/rotation_matrix.h"
#include "drake/multibody/parsing/detail_ignition.h"
#include "drake/multibody/parsing/detail_make_model_name.h"
#include "drake/multibody/parsing/detail_path_utils.h"
#include "drake/multibody/parsing/detail_sdf_diagnostic.h"
#include "drake/multibody/parsing/detail_sdf_geometry.h"
#include "drake/multibody/parsing/detail_urdf_parser.h"
#include "drake/multibody/parsing/scoped_names.h"
#include "drake/multibody/tree/ball_rpy_joint.h"
#include "drake/multibody/tree/curvilinear_joint.h"
#include "drake/multibody/tree/fixed_offset_frame.h"
#include "drake/multibody/tree/geometry_spatial_inertia.h"
#include "drake/multibody/tree/planar_joint.h"
#include "drake/multibody/tree/prismatic_joint.h"
#include "drake/multibody/tree/prismatic_spring.h"
#include "drake/multibody/tree/revolute_joint.h"
#include "drake/multibody/tree/revolute_spring.h"
#include "drake/multibody/tree/scoped_name.h"
#include "drake/multibody/tree/screw_joint.h"
#include "drake/multibody/tree/spatial_inertia.h"
#include "drake/multibody/tree/uniform_gravity_field_element.h"
#include "drake/multibody/tree/universal_joint.h"
#include "drake/multibody/tree/weld_joint.h"
namespace drake {
namespace multibody {
namespace internal {
using drake::internal::DiagnosticDetail;
using drake::internal::DiagnosticPolicy;
using Eigen::Matrix3d;
using Eigen::Translation3d;
using Eigen::Vector3d;
using geometry::GeometryInstance;
using math::RigidTransformd;
using math::RollPitchYawd;
using math::RotationMatrixd;
using std::unique_ptr;
// Unnamed namespace for free functions local to this file.
namespace {
// A short summary of parsing stages in libsdformat:
//
// When we load a model using `sdf::Root::Load`, the following happens:
// * libsdformat parses the XML into `sdf::ElementPtr` objects. Included
// SDFormat models are expanded during this process. If the included model is
// not an SDFormat file type and there are custom parsers registered in the
// passed in `ParserConfig`, the contents of the `<include>` tag are saved for
// later processing
// * DOM objects are created from `sdf::ElementPtr` objects. During the creation
// of `sdf::World` and `sdf::Model`, custom parsers are called on the
// non-SDFormat included files mentioned above. This is what's called the
// Interface API.
// * Drake's custom parser (eg. detail_urdf_parser) parses the files into a
// MultibodyPlant.
// * The frame bearing elements (Links, Joints, Frames, and Models) are read
// back from the MultibodyPlant and returned to libsdformat via the Interface
// API data structures.
// * Once DOM object creation is complete, libsdformat constructs the frame and
// pose graph for the entire model.
// * `sdf::Root::Load` returns and Drake starts its parsing stage where it
// populates the MultibodyPlant using the DOM objects created above (e.g.
// AddModelsFromSpecification).
// `ModelInstanceIndexRange` is a data structure to hold model instances that
// were created during libsdformat's Interface API callback for handling merged
// models. When handling merged models during libsdformat's Interface API
// callback, we have to create model instances of parents of merged models since
// the parent models are regular SDFormat elements and will only be handled at a
// later stage of parsing. This data structure is used to store these parent
// model instances so that when we're going through Drake's parsing stage (last
// step in the parsing stage summary above), we are aware of these model
// instances and not try to recreate them.
using ModelInstanceIndexRange =
std::pair<ModelInstanceIndex, ModelInstanceIndex>;
// Returns the model instance name for the given `instance`, unless it's the
// world model instance in which case returns the empty string.
std::string GetInstanceScopeNameIgnoringWorld(
const MultibodyPlant<double>& plant, ModelInstanceIndex instance) {
if (instance != plant.world_body().model_instance()) {
return plant.GetModelInstanceName(instance);
} else {
return "";
}
}
// Given a @p relative_nested_name to an object, this function returns the model
// instance that is an immediate parent of the object and the local name of the
// object. The local name of the object does not have any scoping delimiters.
//
// @param[in] relative_nested_name
// The name of the object in the scope of the model associated with the given
// @p model_instance. The relative nested name can contain the scope delimiter
// to reference objects nested in child models.
// @param[in] model_instance
// The model instance in whose scope @p relative_nested_name is defined.
// @param[in] plant
// The MultibodyPlant object that contains the model instance identified by @p
// model_instance.
// @returns A pair containing the resolved model instance and the local name of
// the object referenced by @p relative_nested_name.
std::pair<ModelInstanceIndex, std::string> GetResolvedModelInstanceAndLocalName(
const std::string& relative_nested_name, ModelInstanceIndex model_instance,
const MultibodyPlant<double>& plant) {
auto [parent_name, unscoped_local_name] =
sdf::SplitName(relative_nested_name);
ModelInstanceIndex resolved_model_instance = model_instance;
if (!parent_name.empty()) {
// If the parent is in the world_model_instance, the name can be looked up
// from the plant without creating an absolute name.
if (world_model_instance() == model_instance) {
resolved_model_instance = plant.GetModelInstanceByName(parent_name);
} else {
const std::string parent_model_absolute_name = sdf::JoinName(
plant.GetModelInstanceName(model_instance), parent_name);
resolved_model_instance =
plant.GetModelInstanceByName(parent_model_absolute_name);
}
}
return {resolved_model_instance, unscoped_local_name};
}
// Calculates the scoped name of a body relative to the model instance @p
// relative_to_model_instance. If the body is a direct child of the model,
// this simply returns the local name of the body. However, if the body is
// a child of a nested model, the local name of the body is prefixed with the
// scoped name of the nested model. If the relative_to_model_instance is the
// world_model_instance, the local name of the body is prefixed with the model
// name.
std::string GetRelativeBodyName(const RigidBody<double>& body,
ModelInstanceIndex relative_to_model_instance,
const MultibodyPlant<double>& plant) {
const std::string& relative_to_model_absolute_name =
plant.GetModelInstanceName(relative_to_model_instance);
// If the relative_to_model instance is the world_model_instance, we need to
// prefix the body name with the model name
if (relative_to_model_instance == world_model_instance()) {
const std::string& model_absolute_name =
plant.GetModelInstanceName(body.model_instance());
return sdf::JoinName(model_absolute_name, body.name());
} else if (body.model_instance() != relative_to_model_instance) {
// If the body is inside a nested model, we need to prefix the
// name with the relative name of the nested model.
const std::string& nested_model_absolute_name =
plant.GetModelInstanceName(body.model_instance());
// The relative_to_model_absolute_name must be a prefix of the
// nested_model_absolute_name. Otherwise the nested model is not a
// descendent of the model relative to which we are computing the name.
const std::string required_prefix =
relative_to_model_absolute_name + std::string(sdf::kScopeDelimiter);
DRAKE_DEMAND(nested_model_absolute_name.starts_with(required_prefix));
const std::string nested_model_relative_name =
nested_model_absolute_name.substr(required_prefix.size());
return sdf::JoinName(nested_model_relative_name, body.name());
} else {
return body.name();
}
}
// This takes an `sdf::SemanticPose`, which defines a pose relative to a frame,
// and resolves its value with respect to another frame.
math::RigidTransformd ResolveRigidTransform(
const SDFormatDiagnostic& diagnostic,
const sdf::SemanticPose& semantic_pose,
const std::string& relative_to = "") {
gz::math::Pose3d pose;
sdf::Errors errors = semantic_pose.Resolve(pose, relative_to);
diagnostic.PropagateErrors(errors);
return ToRigidTransform(pose);
}
Eigen::Vector3d ResolveAxisXyz(const SDFormatDiagnostic& diagnostic,
const sdf::JointAxis& axis) {
gz::math::Vector3d xyz;
sdf::Errors errors = axis.ResolveXyz(xyz);
diagnostic.PropagateErrors(errors);
return ToVector3(xyz);
}
std::string ResolveJointParentLinkName(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint) {
std::string link;
sdf::Errors errors = joint.ResolveParentLink(link);
diagnostic.PropagateErrors(errors);
return link;
}
std::string ResolveJointChildLinkName(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint) {
std::string link;
sdf::Errors errors = joint.ResolveChildLink(link);
diagnostic.PropagateErrors(errors);
return link;
}
// Helper method to extract the SpatialInertia M_BBo_B of body B, about its body
// frame origin Bo and, expressed in body frame B, from a gz::Inertial
// object.
SpatialInertia<double> ExtractSpatialInertiaAboutBoExpressedInB(
const SDFormatDiagnostic& diagnostic, const sdf::ElementPtr link_element,
const gz::math::Inertiald& Inertial_BBcm_Bi) {
double mass = Inertial_BBcm_Bi.MassMatrix().Mass();
// Pose of the "<inertial>" frame Bi in the body frame B.
// TODO(amcastro-tri): Verify we don't get funny results when X_BBi is not
// the identity matrix.
// TODO(amcastro-tri): SDF seems to provide <inertial><frame/></inertial>
// together with <inertial><pose/></inertial>. It'd seem then the frame B
// in X_BI could be another frame. We rely on Inertial::Pose() to ALWAYS
// give us X_BI. Verify this.
const RigidTransformd X_BBi = ToRigidTransform(Inertial_BBcm_Bi.Pose());
// TODO(amcastro-tri): Verify that gz::math::Inertial::MOI() ALWAYS is
// expresed in the body frame B, regardless of how a user might have
// specified frames in the sdf file. That is, that it always returns R_BBcm_B.
// TODO(amcastro-tri): Verify that gz::math::Inertial::MassMatrix()
// ALWAYS is in the inertial frame Bi, regardless of how a user might have
// specified frames in the sdf file. That is, that it always returns
// M_BBcm_Bi.
const gz::math::Matrix3d I = Inertial_BBcm_Bi.MassMatrix().Moi();
return ParseSpatialInertia(diagnostic.MakePolicyForNode(*link_element), X_BBi,
mass,
{.ixx = I(0, 0),
.iyy = I(1, 1),
.izz = I(2, 2),
.ixy = I(1, 0),
.ixz = I(2, 0),
.iyz = I(2, 1)});
}
// Helper method to retrieve a Body given the name of the link specification.
const RigidBody<double>& GetBodyByLinkSpecificationName(
const std::string& link_name, ModelInstanceIndex model_instance,
const MultibodyPlant<double>& plant) {
// SDF's convention to indicate a joint is connected to the world is to either
// name the corresponding link "world" or just leave it unnamed.
// Thus this the "if" statement in the following line.
if (link_name.empty() || link_name == "world") {
return plant.world_body();
} else {
const auto [parent_model_instance, local_name] =
GetResolvedModelInstanceAndLocalName(link_name, model_instance, plant);
return plant.GetBodyByName(local_name, parent_model_instance);
}
}
// Extracts a Vector3d representation of the joint axis for joints with an axis.
Vector3d ExtractJointAxis(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint_spec) {
DRAKE_DEMAND(joint_spec.Type() == sdf::JointType::REVOLUTE ||
joint_spec.Type() == sdf::JointType::SCREW ||
joint_spec.Type() == sdf::JointType::PRISMATIC ||
joint_spec.Type() == sdf::JointType::CONTINUOUS);
// Axis specification.
const sdf::JointAxis* axis = joint_spec.Axis();
if (axis == nullptr) {
std::string message = fmt::format(
"An axis must be specified for joint '{}'", joint_spec.Name());
diagnostic.Error(joint_spec.Element(), std::move(message));
return Vector3d(0, 0, 1);
}
// Joint axis in the joint frame J.
Vector3d axis_J = ResolveAxisXyz(diagnostic, *axis);
return axis_J;
}
// Extracts a Vector3d representation of `axis` and `axis2` for joints with both
// attributes. Both axes are required. Otherwise, an error is triggered.
std::pair<Vector3d, Vector3d> ExtractJointAxisAndAxis2(
const SDFormatDiagnostic& diagnostic, const sdf::Joint& joint_spec) {
DRAKE_DEMAND(joint_spec.Type() == sdf::JointType::REVOLUTE2 ||
joint_spec.Type() == sdf::JointType::UNIVERSAL);
// Axis specification.
const sdf::JointAxis* axis = joint_spec.Axis(0);
const sdf::JointAxis* axis2 = joint_spec.Axis(1);
if (axis == nullptr || axis2 == nullptr) {
std::string message =
fmt::format("Both axis and axis2 must be specified for joint '{}'",
joint_spec.Name());
diagnostic.Error(joint_spec.Element(), std::move(message));
return std::make_pair(Vector3d(1, 0, 0), Vector3d(0, 1, 0));
}
// Joint axis and axis2 in the joint frame J.
Vector3d axis_J = ResolveAxisXyz(diagnostic, *axis);
Vector3d axis2_J = ResolveAxisXyz(diagnostic, *axis2);
return std::make_pair(axis_J, axis2_J);
}
// Helper to parse the damping for a given joint specification.
// Right now we only parse the <damping> tag.
double ParseJointDamping(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint_spec) {
DRAKE_DEMAND(joint_spec.Type() == sdf::JointType::REVOLUTE ||
joint_spec.Type() == sdf::JointType::PRISMATIC ||
joint_spec.Type() == sdf::JointType::SCREW ||
joint_spec.Type() == sdf::JointType::UNIVERSAL ||
joint_spec.Type() == sdf::JointType::BALL ||
joint_spec.Type() == sdf::JointType::CONTINUOUS);
// If the axis is missing, we'll rely on ExtractJointAxis to tell the user.
// For our purposes in this function, it's OK to just bail and return zero.
const sdf::JointAxis* axis = joint_spec.Axis();
if (axis == nullptr) {
return 0.0;
}
const double damping = axis->Damping();
if (damping < 0) {
std::string message = fmt::format(
"Joint damping is negative for joint '{}'. "
"Joint damping must be a non-negative number.",
joint_spec.Name());
diagnostic.Error(joint_spec.Element(), std::move(message));
return 0.0;
}
// If there are more than one axis (e.g. universal joint), we ignore the
// damping specified for the second axis.
const sdf::JointAxis* axis2 = joint_spec.Axis(1);
if (axis2 != nullptr) {
const double damping2 = axis2->Damping();
if (damping2 != damping) {
std::string message = fmt::format(
"Joint damping must be equal for both axes for joint {}. "
"The damping coefficient for 'axis' ({}) is used. The "
"value for 'axis2' ({}) is ignored. The damping coefficient "
"for 'axis2' should be explicitly defined as {} to match that for "
"'axis'.",
joint_spec.Name(), damping, damping2, damping);
diagnostic.Warning(joint_spec.Element(), std::move(message));
}
}
return damping;
}
// We interpret a value of exactly zero to specify un-actuated joints. Thus, the
// user would say <effort>0</effort>. The effort_limit should be non-negative.
// SDFormat internally interprets a negative effort limit as infinite and only
// returns non-negative values.
double GetEffortLimit(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint_spec, int axis_index) {
DRAKE_DEMAND(axis_index == 0 || axis_index == 1);
const sdf::JointAxis* axis = joint_spec.Axis(axis_index);
if (axis == nullptr) {
std::string message =
fmt::format("An axis{} must be specified for joint '{}'",
axis_index > 0 ? "2" : "", joint_spec.Name());
diagnostic.Warning(joint_spec.Element(), std::move(message));
return 0.0;
}
return axis->Effort();
}
// Extracts the effort limit from a joint specification and adds an actuator if
// the value is non-zero. In SDFormat, effort limits are specified in
// <joint><axis><limit><effort>. In Drake, we understand that joints with an
// effort limit of zero are not actuated. For joint types that do not have an
// actuator implementation available in Drake, produces a diagnostic warning.
void AddJointActuatorFromSpecification(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint_spec,
const Joint<double>& joint,
MultibodyPlant<double>* plant) {
DRAKE_THROW_UNLESS(plant != nullptr);
DRAKE_DEMAND(joint_spec.Type() == sdf::JointType::BALL ||
joint_spec.Type() == sdf::JointType::SCREW ||
joint_spec.Type() == sdf::JointType::UNIVERSAL ||
joint_spec.Type() == sdf::JointType::PRISMATIC ||
joint_spec.Type() == sdf::JointType::REVOLUTE ||
joint_spec.Type() == sdf::JointType::CONTINUOUS);
// Ball joints do not have an axis (nor actuation). However, Drake still
// permits the declaration of a first axis in order to specify damping, but
// it should not have actuation, nor should there be a second axis.
if (joint_spec.Type() == sdf::JointType::BALL) {
if (joint_spec.Axis(0) != nullptr) {
std::string message = fmt::format(
"A ball joint axis will be ignored. Only the dynamic parameters"
" and limits will be considered.",
joint_spec.Name());
diagnostic.Warning(joint_spec.Element(), std::move(message));
if (GetEffortLimit(diagnostic, joint_spec, 0) != 0) {
std::string effort_message = fmt::format(
"Actuation (via non-zero effort limits) for ball joint '{}' is"
" not implemented yet and will be ignored.",
joint_spec.Name());
diagnostic.Warning(joint_spec.Element(), std::move(effort_message));
}
}
if (joint_spec.Axis(1) != nullptr) {
std::string message = fmt::format(
"An axis2 may not be specified for ball joint '{}' and will be "
"ignored",
joint_spec.Name());
diagnostic.Warning(joint_spec.Element(), std::move(message));
}
return;
}
// Universal joints should have both axes defined per SDFormat, but Drake
// does not yet implement a 2-dof actuator for this joint type.
if (joint_spec.Type() == sdf::JointType::UNIVERSAL) {
if (GetEffortLimit(diagnostic, joint_spec, 0) != 0 ||
GetEffortLimit(diagnostic, joint_spec, 1) != 0) {
std::string message = fmt::format(
"Actuation (via non-zero effort limits) for universal joint '{}' is"
" not implemented yet and will be ignored.",
joint_spec.Name());
diagnostic.Warning(joint_spec.Element(), std::move(message));
}
return;
}
// Prismatic, screw, revolute, and continuous joints have a single axis.
const double effort_limit = GetEffortLimit(diagnostic, joint_spec, 0);
if (effort_limit != 0) {
const JointActuator<double>& actuator =
plant->AddJointActuator(joint_spec.Name(), joint, effort_limit);
// Parse and add the optional drake:rotor_inertia parameter.
if (joint_spec.Element()->HasElement("drake:rotor_inertia")) {
plant->get_mutable_joint_actuator(actuator.index())
.set_default_rotor_inertia(
joint_spec.Element()->Get<double>("drake:rotor_inertia"));
}
// Parse and add the optional drake:gear_ratio parameter.
if (joint_spec.Element()->HasElement("drake:gear_ratio")) {
plant->get_mutable_joint_actuator(actuator.index())
.set_default_gear_ratio(
joint_spec.Element()->Get<double>("drake:gear_ratio"));
}
// Parse and add the optional drake:controller_gains parameter.
if (joint_spec.Element()->HasElement("drake:controller_gains")) {
sdf::ElementPtr controller_gains =
joint_spec.Element()->GetElement("drake:controller_gains");
const bool has_p = controller_gains->HasAttribute("p");
const bool has_d = controller_gains->HasAttribute("d");
if (!has_p) {
std::string message =
"<drake:controller_gains>: Unable to find the 'p' attribute.";
diagnostic.Error(controller_gains, std::move(message));
}
if (!has_d) {
std::string message =
"<drake:controller_gains>: Unable to find the 'd' attribute.";
diagnostic.Error(controller_gains, std::move(message));
}
if (has_p && has_d) {
const double p = controller_gains->Get<double>("p");
const double d = controller_gains->Get<double>("d");
plant->get_mutable_joint_actuator(actuator.index())
.set_controller_gains({p, d});
}
}
}
if (joint_spec.Axis(1) != nullptr) {
std::string message = fmt::format(
"An axis2 may not be specified for 1-dof joint '{}' and will be "
"ignored",
joint_spec.Name());
diagnostic.Warning(joint_spec.Element(), std::move(message));
}
}
// Extracts the spring stiffness and the spring reference from a joint
// specification and adds a prismatic spring force element with the
// corresponding spring reference if the spring stiffness is nonzero.
// Only available for "prismatic" joints. The units for spring
// reference is meter and the units for spring stiffness is N/m.
void AddPrismaticSpringFromSpecification(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint_spec,
const PrismaticJoint<double>& joint,
MultibodyPlant<double>* plant) {
DRAKE_THROW_UNLESS(plant != nullptr);
DRAKE_THROW_UNLESS(joint_spec.Type() == sdf::JointType::PRISMATIC);
// Axis specification.
const sdf::JointAxis* axis = joint_spec.Axis();
if (axis == nullptr) {
std::string message = fmt::format(
"An axis must be specified for joint '{}'.", joint_spec.Name());
diagnostic.Error(joint_spec.Element(), std::move(message));
return;
}
const double spring_reference = axis->SpringReference();
const double spring_stiffness = axis->SpringStiffness();
// We add a force element if stiffness is positive, report error
// if the stiffness is negative, and pass if the stiffness is zero
if (spring_stiffness > 0) {
plant->AddForceElement<PrismaticSpring>(joint, spring_reference,
spring_stiffness);
} else if (spring_stiffness < 0) {
std::string message = fmt::format(
"The stiffness specified for joint '{}' must be non-negative.",
joint_spec.Name());
diagnostic.Error(joint_spec.Element(), std::move(message));
}
}
// Extracts the spring stiffness and the spring reference from a joint
// specification and adds a revolute spring force element with the
// corresponding spring reference if the spring stiffness is nonzero.
// Only available for "revolute" and "continuous" joints. The units for spring
// reference is radians and the units for spring stiffness is N⋅m/rad.
// When the error diagnostic policy is not set to throw this function will
// return false on errors.
bool AddRevoluteSpringFromSpecification(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint_spec,
const RevoluteJoint<double>& joint,
MultibodyPlant<double>* plant) {
DRAKE_THROW_UNLESS(plant != nullptr);
DRAKE_THROW_UNLESS(joint_spec.Type() == sdf::JointType::REVOLUTE ||
joint_spec.Type() == sdf::JointType::CONTINUOUS);
// Axis specification.
const sdf::JointAxis* axis = joint_spec.Axis();
if (axis == nullptr) {
std::string message =
"An axis must be specified for joint '" + joint_spec.Name() + "'";
diagnostic.Error(joint_spec.Element(), std::move(message));
return false;
}
const double spring_reference = axis->SpringReference();
const double spring_stiffness = axis->SpringStiffness();
// We don't add a force element if stiffness is zero.
// If a negative value is passed in, RevoluteSpring will
// throw an error.
if (spring_stiffness != 0) {
plant->AddForceElement<RevoluteSpring>(joint, spring_reference,
spring_stiffness);
}
return true;
}
// Returns joint limits as the tuple (lower_limit, upper_limit,
// velocity_limit, acceleration_limit). The units of the limits depend on the
// particular joint type. For prismatic joints, units are meters for the
// position limits and m/s for the velocity limit. For revolute, units
// are radians for the position limits and rad/s for the velocity limit. For
// continuous, positions limits are infinities and velocity limits have units
// rad/s. Velocity and acceleration limits are always >= 0. This method throws
// an exception if the joint type is not one of revolute, prismatic, or
// continuous. When the diagnostic policy is not set to throw it will return
// std::nullopt on errors.
std::optional<std::tuple<double, double, double, double>> ParseJointLimits(
const SDFormatDiagnostic& diagnostic, const sdf::Joint& joint_spec) {
DRAKE_THROW_UNLESS(joint_spec.Type() == sdf::JointType::REVOLUTE ||
joint_spec.Type() == sdf::JointType::PRISMATIC ||
joint_spec.Type() == sdf::JointType::CONTINUOUS);
// Axis specification.
const sdf::JointAxis* axis = joint_spec.Axis();
if (axis == nullptr) {
std::string message =
"An axis must be specified for joint '" + joint_spec.Name() + "'";
diagnostic.Error(joint_spec.Element(), std::move(message));
return std::nullopt;
}
// As of libsdformat13, ±∞ are used for axes with no position limits,
// so no special handling is needed.
const double lower_limit = axis->Lower();
const double upper_limit = axis->Upper();
if (lower_limit > upper_limit) {
std::string message =
"The lower limit must be lower (or equal) than "
"the upper limit for joint '" +
joint_spec.Name() + "'.";
diagnostic.Error(joint_spec.Element(), std::move(message));
return std::nullopt;
}
// SDFormat internally interprets a negative velocity limit as infinite and
// only returns non-negative values.
const double velocity_limit = axis->MaxVelocity();
// Read Drake-namespaced acceleration limit if present. If not, default to
// ±numeric_limits<double>::infinity().
double acceleration_limit = std::numeric_limits<double>::infinity();
if (axis->Element()->HasElement("limit")) {
const auto limit_element = axis->Element()->GetElement("limit");
const std::set<std::string> supported_limit_elements{
"drake:acceleration", "effort", "lower",
"stiffness", "upper", "velocity"};
CheckSupportedElements(diagnostic, limit_element, supported_limit_elements);
if (limit_element->HasElement("drake:acceleration")) {
acceleration_limit = limit_element->Get<double>("drake:acceleration");
if (acceleration_limit < 0) {
std::string message = "Acceleration limit is negative for joint '" +
joint_spec.Name() +
"'. Aceleration limit must be a non-negative"
" number.";
diagnostic.Error(limit_element, std::move(message));
return std::tuple<double, double, double, double>();
}
}
}
return std::make_tuple(lower_limit, upper_limit, velocity_limit,
acceleration_limit);
}
// Helper method to add joints to a MultibodyPlant given an sdf::Joint
// specification object. X_WM should be an identity when adding a world
// joint (is_model_joint = false) since a world joint doesn't have a
// containing model, hence M = W.
// If the diagnostic error policy is not set to throw it returns false
// when an error occurs.
bool AddJointFromSpecification(const SDFormatDiagnostic& diagnostic,
const RigidTransformd& X_WM,
const sdf::Joint& joint_spec,
ModelInstanceIndex model_instance,
MultibodyPlant<double>* plant,
std::set<sdf::JointType>* joint_types,
bool is_model_joint = true) {
const std::set<std::string> supported_joint_elements{"axis",
"axis2",
"child",
"drake:rotor_inertia",
"drake:gear_ratio",
"drake:controller_gains",
"drake:mimic",
"parent",
"pose",
"screw_thread_pitch"};
CheckSupportedElements(diagnostic, joint_spec.Element(),
supported_joint_elements);
// Axis elements should be fully supported, let sdformat validate those.
const RigidBody<double>& parent_body = GetBodyByLinkSpecificationName(
ResolveJointParentLinkName(diagnostic, joint_spec), model_instance,
*plant);
const RigidBody<double>& child_body = GetBodyByLinkSpecificationName(
ResolveJointChildLinkName(diagnostic, joint_spec), model_instance,
*plant);
// Get the pose of frame J in the frame of the child link C, as specified in
// <joint> <pose> ... </pose></joint>. The default `relative_to` pose of a
// joint will be the child link.
const RigidTransformd X_CJ = ResolveRigidTransform(
diagnostic, joint_spec.SemanticPose(),
GetRelativeBodyName(child_body, model_instance, *plant));
// Pose of the frame J in the parent body frame P.
std::optional<RigidTransformd> X_PJ;
// We need to treat the world case separately since sdformat does not create
// a "world" link from which we can request its pose (which in that case would
// be the identity).
const std::string relative_to = (is_model_joint) ? "__model__" : "world";
if (parent_body.index() == world_index()) {
const RigidTransformd X_MJ = ResolveRigidTransform(
diagnostic, joint_spec.SemanticPose(), relative_to);
X_PJ = X_WM * X_MJ; // Since P == W.
} else {
X_PJ = ResolveRigidTransform(
diagnostic, joint_spec.SemanticPose(),
GetRelativeBodyName(parent_body, model_instance, *plant));
}
// If P and J are coincident, we won't create a new frame for J, but use frame
// P directly. We indicate that by passing a nullopt.
if (X_PJ.value().IsExactlyIdentity()) X_PJ = std::nullopt;
// These will only be populated for prismatic and revolute joints.
double lower_limit = 0;
double upper_limit = 0;
double velocity_limit = 0;
double acceleration_limit = 0;
switch (joint_spec.Type()) {
case sdf::JointType::FIXED: {
plant->AddJoint<WeldJoint>(joint_spec.Name(), parent_body, X_PJ,
child_body, X_CJ,
RigidTransformd::Identity() /* X_JpJc */);
break;
}
case sdf::JointType::PRISMATIC: {
const double damping = ParseJointDamping(diagnostic, joint_spec);
Vector3d axis_J = ExtractJointAxis(diagnostic, joint_spec);
std::optional<std::tuple<double, double, double, double>> joint_limits =
ParseJointLimits(diagnostic, joint_spec);
if (!joint_limits.has_value()) return false;
std::tie(lower_limit, upper_limit, velocity_limit, acceleration_limit) =
*joint_limits;
const auto& joint = plant->AddJoint<PrismaticJoint>(
joint_spec.Name(), parent_body, X_PJ, child_body, X_CJ, axis_J,
lower_limit, upper_limit, damping);
plant->get_mutable_joint(joint.index())
.set_velocity_limits(Vector1d(-velocity_limit),
Vector1d(velocity_limit));
plant->get_mutable_joint(joint.index())
.set_acceleration_limits(Vector1d(-acceleration_limit),
Vector1d(acceleration_limit));
AddJointActuatorFromSpecification(diagnostic, joint_spec, joint, plant);
AddPrismaticSpringFromSpecification(diagnostic, joint_spec, joint, plant);
break;
}
case sdf::JointType::REVOLUTE: {
const double damping = ParseJointDamping(diagnostic, joint_spec);
Vector3d axis_J = ExtractJointAxis(diagnostic, joint_spec);
std::optional<std::tuple<double, double, double, double>> joint_limits =
ParseJointLimits(diagnostic, joint_spec);
if (!joint_limits.has_value()) return false;
std::tie(lower_limit, upper_limit, velocity_limit, acceleration_limit) =
*joint_limits;
const auto& joint = plant->AddJoint<RevoluteJoint>(
joint_spec.Name(), parent_body, X_PJ, child_body, X_CJ, axis_J,
lower_limit, upper_limit, damping);
plant->get_mutable_joint(joint.index())
.set_velocity_limits(Vector1d(-velocity_limit),
Vector1d(velocity_limit));
plant->get_mutable_joint(joint.index())
.set_acceleration_limits(Vector1d(-acceleration_limit),
Vector1d(acceleration_limit));
AddJointActuatorFromSpecification(diagnostic, joint_spec, joint, plant);
if (!AddRevoluteSpringFromSpecification(diagnostic, joint_spec, joint,
plant)) {
return false;
}
break;
}
case sdf::JointType::UNIVERSAL: {
const double damping = ParseJointDamping(diagnostic, joint_spec);
// In Drake's implementation of universal joint, the rotation axes are
// built into the frames M and F; the first rotation is about Fx and the
// second is about My. Therefore, we can't arbitrarily set M and F to be
// J. We have to be more careful on how we define F and M so that the
// joint imposes the correct kinematics.
// Construct frame I and find X_PI and X_CI. See definition of frame I in
// the class doc of UniversalJoint.
auto [Ix_J, Iy_J] = ExtractJointAxisAndAxis2(diagnostic, joint_spec);
// Safe to normalize as libsdformat parser would have generated an error
// if the axes are zero.
Ix_J.normalize();
Iy_J.normalize();
const Vector3d Iz_J = Ix_J.cross(Iy_J);
Matrix3d R_JI;
R_JI.col(0) = Ix_J;
R_JI.col(1) = Iy_J;
R_JI.col(2) = Iz_J;
// We require that axis and axis2 are orthogonal. As a result, R_JI should
// be a valid rotation matrix.
if (!math::RotationMatrixd::IsValid(R_JI)) {
std::string message =
fmt::format("axis and axis2 must be orthogonal for joint '{}'",
joint_spec.Name());
diagnostic.Error(joint_spec.Element(), std::move(message));
} else {
const RigidTransformd X_JI(math::RotationMatrix<double>{R_JI});
// The value of X_PJ is the identity if X_PJ == nullopt.
const RigidTransformd X_PI = X_PJ.has_value() ? (*X_PJ) * X_JI : X_JI;
const RigidTransformd X_CI = X_CJ * X_JI;
// Frames M and F should both coincide with I when rotation angles are
// zero.
const RigidTransformd& X_PF = X_PI;
const RigidTransformd& X_CM = X_CI;
const auto& joint = plant->AddJoint<UniversalJoint>(
joint_spec.Name(), parent_body, X_PF, child_body, X_CM, damping);
// At most, this prints a warning (it does not add an actuator).
AddJointActuatorFromSpecification(diagnostic, joint_spec, joint, plant);
}
break;
}
case sdf::JointType::BALL: {
const double damping = ParseJointDamping(diagnostic, joint_spec);
const auto& joint = plant->AddJoint<BallRpyJoint>(
joint_spec.Name(), parent_body, X_PJ, child_body, X_CJ, damping);
// At most, this prints a warning (it does not add an actuator).
AddJointActuatorFromSpecification(diagnostic, joint_spec, joint, plant);
break;
}
case sdf::JointType::CONTINUOUS: {
const double damping = ParseJointDamping(diagnostic, joint_spec);
Vector3d axis_J = ExtractJointAxis(diagnostic, joint_spec);
std::optional<std::tuple<double, double, double, double>> joint_limits =
ParseJointLimits(diagnostic, joint_spec);
if (!joint_limits.has_value()) return false;
std::tie(lower_limit, upper_limit, velocity_limit, acceleration_limit) =
*joint_limits;
const auto& joint =
plant->AddJoint<RevoluteJoint>(joint_spec.Name(), parent_body, X_PJ,
child_body, X_CJ, axis_J, damping);
plant->get_mutable_joint(joint.index())
.set_velocity_limits(Vector1d(-velocity_limit),
Vector1d(velocity_limit));
plant->get_mutable_joint(joint.index())
.set_acceleration_limits(Vector1d(-acceleration_limit),
Vector1d(acceleration_limit));
AddJointActuatorFromSpecification(diagnostic, joint_spec, joint, plant);
if (!AddRevoluteSpringFromSpecification(diagnostic, joint_spec, joint,
plant)) {
return false;
}
break;
}
case sdf::JointType::SCREW: {
const double damping = ParseJointDamping(diagnostic, joint_spec);
// The ScrewThreadPitch() API uses the same representation as
// Drake's ScrewJoint class (meters / revolution, right-handed).
const double screw_thread_pitch = joint_spec.ScrewThreadPitch();
Vector3d axis_J = ExtractJointAxis(diagnostic, joint_spec);
const auto& joint = plant->AddJoint<ScrewJoint>(
joint_spec.Name(), parent_body, X_PJ, child_body, X_CJ, axis_J,
screw_thread_pitch, damping);
AddJointActuatorFromSpecification(diagnostic, joint_spec, joint, plant);
break;
}
case sdf::JointType::GEARBOX: {
// TODO(jwnimmer-tri) Demote this to a warning, possibly adding a
// RevoluteJoint as an approximation (stopgap) in that case.
std::string message =
fmt::format("Joint type (gearbox) not supported for joint '{}'.",
joint_spec.Name());
diagnostic.Error(joint_spec.Element(), std::move(message));
break;
}
case sdf::JointType::REVOLUTE2: {
// TODO(jwnimmer-tri) Demote this to a warning, possibly adding a
// UniversalJoint as an approximation (stopgap) in that case.
std::string message =
fmt::format("Joint type (revolute2) not supported for joint '{}'.",
joint_spec.Name());
diagnostic.Error(joint_spec.Element(), std::move(message));
break;
}
case sdf::JointType::INVALID: {
// In probably all cases, libsdformat will have already detected
// this error and so Drake won't get an INVALID joint.
DRAKE_UNREACHABLE();
}
}
joint_types->insert(joint_spec.Type());
return true;
}
// Helper method to parse a custom drake:mimic tag.
bool ParseMimicTag(const SDFormatDiagnostic& diagnostic,
const sdf::Joint& joint_spec,
ModelInstanceIndex model_instance,
MultibodyPlant<double>* plant) {
if (!joint_spec.Element()->HasElement("drake:mimic")) return true;
// Only warn for non-SAP discrete solvers; continuous plants have different
// error reporting.
if (plant->is_discrete() &&
plant->get_discrete_contact_solver() != DiscreteContactSolver::kSap) {
diagnostic.Warning(
joint_spec.Element(),
fmt::format("Joint '{}' specifies a drake:mimic element that will be "
"ignored. Mimic elements are currently only supported by "
"MultibodyPlant with a discrete time step and using "
"DiscreteContactSolver::kSap, or by continuous time plants "
"using the CENIC integrator.",
joint_spec.Name()));
return true;
}
sdf::ElementPtr mimic_node = joint_spec.Element()->GetElement("drake:mimic");
if (!mimic_node->HasAttribute("joint")) {
diagnostic.Error(
mimic_node, fmt::format("Joint '{}' drake:mimic element is missing the "
"required 'joint' attribute.",
joint_spec.Name()));
return false;
}
const std::string joint_to_mimic = mimic_node->Get<std::string>("joint");
if (!plant->HasJointNamed(joint_to_mimic, model_instance)) {
diagnostic.Error(
mimic_node,
fmt::format("Joint '{}' drake:mimic element specifies joint '{}' which"
" does not exist.",
joint_spec.Name(), joint_to_mimic));
return false;
}
if (joint_to_mimic == joint_spec.Name()) {
diagnostic.Error(mimic_node,
fmt::format("Joint '{}' drake:mimic element specifies "
"joint '{}'. Joints cannot mimic themselves.",
joint_spec.Name(), joint_to_mimic));
return false;
}
if (!mimic_node->HasAttribute("multiplier")) {
diagnostic.Error(
mimic_node, fmt::format("Joint '{}' drake:mimic element is missing the "
"required 'multiplier' attribute.",
joint_spec.Name()));
return false;
}
if (!mimic_node->HasAttribute("offset")) {
diagnostic.Error(
mimic_node, fmt::format("Joint '{}' drake:mimic element is missing the "
"required 'offset' attribute.",
joint_spec.Name()));
return false;
}
const double gear_ratio = mimic_node->Get<double>("multiplier");
const double offset = mimic_node->Get<double>("offset");
const Joint<double>& joint0 =
plant->GetJointByName(joint_spec.Name(), model_instance);
const Joint<double>& joint1 =
plant->GetJointByName(joint_to_mimic, model_instance);
if (joint0.num_velocities() != 1 || joint1.num_velocities() != 1) {
// The URDF documentation is ambiguous as to whether multi-dof joints
// are supported by the mimic tag (which the drake:mimic tag is analogous
// to). So we only raise a warning, not an error.
diagnostic.Warning(
mimic_node,
fmt::format("Drake only supports the drake:mimic element for "
"single-dof joints. The joint '{}' (with {} "
"dofs) is attempting to mimic joint '{}' (with "
"{} dofs). The drake:mimic element will be ignored.",
joint0.name(), joint0.num_velocities(), joint_to_mimic,
joint1.num_velocities()));
} else {
plant->AddCouplerConstraint(joint0, joint1, gear_ratio, offset);
}
return true;
}
// Helper method to load an SDF file and read the contents into an sdf::Root
// object.
[[nodiscard]] sdf::Errors LoadSdf(const SDFormatDiagnostic& diagnostic,
sdf::Root* root,
const DataSource& data_source,
const sdf::ParserConfig& parser_config) {
sdf::Errors errors;
if (data_source.IsFilename()) {
const std::string full_path = data_source.GetAbsolutePath();
errors = root->Load(full_path, parser_config);
} else {
errors = root->LoadSdfString(data_source.contents(), parser_config);
}
if (errors.empty()) {
const std::set<std::string> supported_root_elements{"model", "world"};
CheckSupportedElements(diagnostic, root->Element(),