File: RigidRepresentationTest.cpp

package info (click to toggle)
opensurgsim 0.7.0-11
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 23,744 kB
  • sloc: cpp: 135,363; ansic: 4,206; python: 3,934; makefile: 38
file content (1138 lines) | stat: -rw-r--r-- 42,838 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// 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.

#include <string>

#include <gtest/gtest.h>

#include "SurgSim/DataStructures/Location.h"
#include "SurgSim/DataStructures/BufferedValue.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/FrameworkConvert.h"
#include "SurgSim/Math/Matrix.h"
#include "SurgSim/Math/MeshShape.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/Quaternion.h"
#include "SurgSim/Math/RigidTransform.h"
#include "SurgSim/Math/PlaneShape.h"
#include "SurgSim/Math/Shape.h"
#include "SurgSim/Math/SphereShape.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Math/Valid.h"
#include "SurgSim/Physics/Localization.h"
#include "SurgSim/Physics/RigidCollisionRepresentation.h"
#include "SurgSim/Physics/RigidRepresentation.h"

using SurgSim::DataStructures::Location;
using SurgSim::Framework::Component;
using SurgSim::Framework::Runtime;
using SurgSim::Math::Matrix33d;
using SurgSim::Math::Matrix66d;
using SurgSim::Math::makeRigidTransform;
using SurgSim::Math::Quaterniond;
using SurgSim::Math::PlaneShape;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Shape;
using SurgSim::Math::SphereShape;
using SurgSim::Math::Vector3d;
using SurgSim::Math::Vector6d;

namespace
{
const double epsilon = 1e-10;
}

namespace SurgSim
{
namespace Physics
{

class RigidRepresentationTest : public ::testing::Test
{
public:
	void SetUp()
	{
		m_dt = 1e-3;

		m_radius = 0.1;
		m_density = 9000.0;
		m_mass = 4.0 / 3.0 * M_PI * m_radius * m_radius * m_radius * m_density;
		double coef = 2.0 / 5.0 * m_mass * m_radius * m_radius;
		m_inertia << coef, 0.0, 0.0, 0.0, coef, 0.0, 0.0, 0.0, coef;
		m_id33.setIdentity();
		m_zero33.setZero();
		m_invalidInertia.setRandom();
		m_invalidInertia = m_invalidInertia + m_invalidInertia.transpose().eval(); // make symmetric
		m_invalidInertia(0, 0) = -12.3; // Negative value on hte diagonal (invalid)
		m_sphere = std::make_shared<SphereShape>(m_radius);

		Quaterniond q(0.5, 0.4, 0.3, 0.2);
		q.normalize();
		Vector3d t(1.2, 2.1, 12.21);
		m_state.setAngularVelocity(Vector3d(1, 2, 3));
		m_state.setLinearVelocity(Vector3d(3, 2, 1));
		m_state.setPose(SurgSim::Math::makeRigidTransform(q, t));

		m_maxNumSimulationStepTest = 100;
	}

	void TearDown()
	{
	}

	// Time step
	double m_dt;

	// Sphere radius (in m)
	double m_radius;

	// Sphere density (in Kg.m-3)
	double m_density;

	// Sphere mass (in Kg)
	double m_mass;

	// Sphere inertia matrix
	SurgSim::Math::Matrix33d m_inertia;

	// Identity matrix 3x3 (for convenience)
	SurgSim::Math::Matrix33d m_id33;

	// Zero matrix 3x3 (for convenience)
	SurgSim::Math::Matrix33d m_zero33;

	// Invalid inertia matrix
	SurgSim::Math::Matrix33d m_invalidInertia;

	// SphereShape
	std::shared_ptr<SphereShape> m_sphere;

	// Rigid representation state
	RigidState m_state;

	// Rigid representation default state
	RigidState m_defaultState;

	// Max number of simulation step for testing
	int m_maxNumSimulationStepTest;
};

TEST_F(RigidRepresentationTest, ConstructorTest)
{
	ASSERT_NO_THROW(RigidRepresentation rigidBody("Rigid"));
}

TEST_F(RigidRepresentationTest, ResetTest)
{
	// Create the rigid body
	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");

	rigidBody->setInitialState(m_state);
	rigidBody->setLocalActive(false);
	rigidBody->setIsGravityEnabled(false);
	rigidBody->setLocalPose(RigidTransform3d::Identity());

	// reset the representation state
	rigidBody->resetState();

	// isActive unchanged
	EXPECT_FALSE(rigidBody->isActive());
	// isGravityEnable flag unchanged
	EXPECT_FALSE(rigidBody->isGravityEnabled());
	// current state = initial state
	EXPECT_TRUE(rigidBody->getInitialState() == rigidBody->getCurrentState());
	// previous state = initial state
	EXPECT_TRUE(rigidBody->getInitialState() == rigidBody->getPreviousState());
}

TEST_F(RigidRepresentationTest, SetGetAndDefaultValueTest)
{
	// Create the rigid body
	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");

	// Get state (current, initial)
	EXPECT_TRUE(m_defaultState == rigidBody->getCurrentState());
	EXPECT_TRUE(m_defaultState == rigidBody->getPreviousState());
	EXPECT_TRUE(m_defaultState == rigidBody->getInitialState());
	rigidBody->setInitialState(m_state);
	EXPECT_TRUE(m_state == rigidBody->getInitialState());
	EXPECT_TRUE(m_state == rigidBody->getCurrentState());
	EXPECT_TRUE(m_state == rigidBody->getPreviousState());

	// Mass density [default = 0]
	EXPECT_NEAR(0.0, rigidBody->getDensity(), epsilon);
	// Mass [default = qNaA]
	EXPECT_FALSE(SurgSim::Math::isValid(rigidBody->getMass()));
	// Inertia 3x3 symmetric matrix [default = qNaN values]
	EXPECT_FALSE(SurgSim::Math::isValid(rigidBody->getLocalInertia()));
	// Linear damping [default = 0]
	EXPECT_NEAR(0.0, rigidBody->getLinearDamping(), epsilon);
	// Angular damping [default = 0]
	EXPECT_NEAR(0.0, rigidBody->getAngularDamping(), epsilon);
	// Shape [default = nullptr]
	EXPECT_EQ(nullptr, rigidBody->getShape());

	// Mass density
	rigidBody->setDensity(m_density);
	EXPECT_NEAR(m_density, rigidBody->getDensity(), epsilon);
	rigidBody->setDensity(0.0);
	EXPECT_NEAR(0.0, rigidBody->getDensity(), epsilon);

	// Linear damping
	rigidBody->setLinearDamping(5.5);
	EXPECT_NEAR(5.5, rigidBody->getLinearDamping(), epsilon);
	rigidBody->setLinearDamping(0.0);
	EXPECT_NEAR(0.0, rigidBody->getLinearDamping(), epsilon);

	// Angular damping
	rigidBody->setAngularDamping(5.5);
	EXPECT_NEAR(5.5, rigidBody->getAngularDamping(), epsilon);
	rigidBody->setAngularDamping(0.0);
	EXPECT_NEAR(0.0, rigidBody->getAngularDamping(), epsilon);

	// Shape
	rigidBody->setShape(m_sphere);
	EXPECT_EQ(m_sphere, rigidBody->getShape());
	rigidBody->setShape(nullptr);
	EXPECT_EQ(nullptr, rigidBody->getShape());

	// Get/Set active flag [default = true]
	EXPECT_TRUE(rigidBody->isActive());
	EXPECT_TRUE(rigidBody->isLocalActive());
	rigidBody->setLocalActive(false);
	ASSERT_FALSE(rigidBody->isActive());
	ASSERT_FALSE(rigidBody->isLocalActive());
	rigidBody->setLocalActive(true);
	ASSERT_TRUE(rigidBody->isActive());
	ASSERT_TRUE(rigidBody->isLocalActive());

	// Get numDof = 6
	ASSERT_EQ(6u, rigidBody->getNumDof());

	// Set/Get isGravityEnabled [default = true]
	EXPECT_TRUE(rigidBody->isGravityEnabled());
	rigidBody->setIsGravityEnabled(false);
	ASSERT_FALSE(rigidBody->isGravityEnabled());
	rigidBody->setIsGravityEnabled(true);
	ASSERT_TRUE(rigidBody->isGravityEnabled());
}

TEST_F(RigidRepresentationTest, AddExternalGeneralizedForceOnMassCenterTest)
{
	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
	rigidBody->setShape(m_sphere);

	Vector6d F = 6.4 * Vector6d::Ones();
	Matrix66d K = 0.4 * Matrix66d::Ones() + 8.3 * Matrix66d::Identity();
	Matrix66d D = -0.6 * Matrix66d::Ones() + 4.1 * Matrix66d::Identity();

	rigidBody->addExternalGeneralizedForce(F, K, D);
	EXPECT_TRUE(rigidBody->getExternalGeneralizedForce().unsafeGet().isApprox(F));
	EXPECT_TRUE(rigidBody->getExternalGeneralizedStiffness().isApprox(K));
	EXPECT_TRUE(rigidBody->getExternalGeneralizedDamping().isApprox(D));
}

namespace
{
// Extra force/torque that should be added
Vector6d computeExtraTorque(const Vector6d& inputForce, const Vector3d& anchorLocalPoint,
							const Vector6d& dofPosition, const Vector6d& dofVelocity)
{
	Vector6d f = inputForce;

	auto C = dofPosition.segment<3>(0);               // Mass center
	auto rotVector = dofPosition.segment<3>(3);       // Rotation vector

	double angle;
	Vector3d axis = rotVector;
	angle = axis.norm();
	if (std::abs(angle) < 1e-8)
	{
		axis.setZero();
	}
	else
	{
		axis.normalize();
	}
	Matrix33d R = SurgSim::Math::makeRotationMatrix(angle, axis);

	Vector3d anchorPoint = C + R * anchorLocalPoint;
	Vector3d lever = anchorPoint - C;

	f.segment<3>(3) += lever.cross(f.segment<3>(0));

	return f;
}

Matrix66d computeExtraStiffness(const Vector6d& inputForce, const Vector3d& anchorLocalPoint,
								const Vector6d& dofPosition, const Vector6d& dofVelocity)
{
	Matrix66d K = Matrix66d::Zero();
	const double epsilon = 1e-8;

	for (size_t column = 0; column < 6; ++column)
	{
		Vector6d dofX = dofPosition;
		dofX[column] += 2.0 * epsilon;
		Vector6d fXPlus2H = computeExtraTorque(inputForce, anchorLocalPoint, dofX, dofVelocity);

		dofX = dofPosition;
		dofX[column] += epsilon;
		Vector6d fXPlusH = computeExtraTorque(inputForce, anchorLocalPoint, dofX, dofVelocity);

		dofX = dofPosition;
		dofX[column] -= epsilon;
		Vector6d fXMinusH = computeExtraTorque(inputForce, anchorLocalPoint, dofX, dofVelocity);

		dofX = dofPosition;
		dofX[column] -= 2.0 * epsilon;
		Vector6d fXMinus2H = computeExtraTorque(inputForce, anchorLocalPoint, dofX, dofVelocity);

		K.col(column) = - (-fXPlus2H + 8.0 * fXPlusH - 8.0 * fXMinusH + fXMinus2H) / (12.0 * epsilon);
	}

	return K;
}

Matrix66d computeExtraDamping(const Vector6d& inputForce, const Vector3d& anchorLocalPoint,
							  const Vector6d& dofPosition, const Vector6d& dofVelocity)
{
	Matrix66d D = Matrix66d::Zero();
	const double epsilon = 1e-8;

	for (size_t column = 0; column < 6; ++column)
	{
		Vector6d dofV = dofVelocity;
		dofV[column] += 2.0 * epsilon;
		Vector6d fXPlus2H = computeExtraTorque(inputForce, anchorLocalPoint, dofPosition, dofV);

		dofV = dofVelocity;
		dofV[column] += epsilon;
		Vector6d fXPlusH = computeExtraTorque(inputForce, anchorLocalPoint, dofPosition, dofV);

		dofV = dofVelocity;
		dofV[column] -= epsilon;
		Vector6d fXMinusH = computeExtraTorque(inputForce, anchorLocalPoint, dofPosition, dofV);

		dofV = dofVelocity;
		dofV[column] -= 2.0 * epsilon;
		Vector6d fXMinus2H = computeExtraTorque(inputForce, anchorLocalPoint, dofPosition, dofV);

		D.col(column) = - (-fXPlus2H + 8.0 * fXPlusH - 8.0 * fXMinusH + fXMinus2H) / (12.0 * epsilon);
	}

	return D;
}
}; // namespace anonymous

TEST_F(RigidRepresentationTest, AddExternalGeneralizedForceExtraTermsTest)
{
	{
		SCOPED_TRACE("Non identity pose");

		Eigen::AngleAxisd angleAxis(0.34512, Vector3d(1.1, -1.4, 3.23).normalized());
		Vector3d t(1.1, 2.2, 3.3);
		RigidTransform3d transform = makeRigidTransform(Quaterniond(angleAxis), t);

		Vector6d inputForce = Vector6d::LinSpaced(1.1, 6.6);
		Vector6d dofX = Vector6d::Zero();
		dofX.segment<3>(0) = transform.translation();
		Eigen::AngleAxisd angleAxis2(transform.rotation());
		dofX.segment<3>(3) = angleAxis2.axis() * angleAxis2.angle();
		Vector6d dofV = Vector6d::Zero();
		Vector3d anchorLocalPoint = Vector3d::Ones();

		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setShape(m_sphere);
		SurgSim::Physics::RigidState initialState;
		initialState.setPose(transform);
		rigidBody->setInitialState(initialState);
		SurgSim::DataStructures::Location location(anchorLocalPoint);

		Vector6d Fnumeric = computeExtraTorque(inputForce, anchorLocalPoint, dofX, dofV);
		Matrix66d Knumeric = computeExtraStiffness(inputForce, anchorLocalPoint, dofX, dofV);
		Matrix66d Dnumeric = computeExtraDamping(inputForce, anchorLocalPoint, dofX, dofV);

		Vector6d F = inputForce;
		Matrix66d K = Matrix66d::Zero(), D = Matrix66d::Zero();
		rigidBody->addExternalGeneralizedForce(location, F, K, D);
		F = rigidBody->getExternalGeneralizedForce().unsafeGet();
		K = rigidBody->getExternalGeneralizedStiffness();
		D = rigidBody->getExternalGeneralizedDamping();

		EXPECT_LE((F - Fnumeric).cwiseAbs().maxCoeff(), 5e-7);
		EXPECT_LE((K - Knumeric).cwiseAbs().maxCoeff(), 5e-7);
		EXPECT_LE((D - Dnumeric).cwiseAbs().maxCoeff(), 5e-7);
	}

	{
		SCOPED_TRACE("Exactly Identity pose");

		Vector6d inputForce = Vector6d::LinSpaced(1.1, 6.6);
		Vector6d dofX = Vector6d::Zero();
		Vector6d dofV = Vector6d::Zero();
		Vector3d anchorLocalPoint = Vector3d::Ones();

		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setShape(m_sphere);
		SurgSim::DataStructures::Location location(anchorLocalPoint);

		Vector6d Fnumeric = computeExtraTorque(inputForce, anchorLocalPoint, dofX, dofV);
		Matrix66d Knumeric = computeExtraStiffness(inputForce, anchorLocalPoint, dofX, dofV);
		Matrix66d Dnumeric = computeExtraDamping(inputForce, anchorLocalPoint, dofX, dofV);

		Vector6d F = inputForce;
		Matrix66d K = Matrix66d::Zero(), D = Matrix66d::Zero();
		rigidBody->addExternalGeneralizedForce(location, F, K, D);
		F = rigidBody->getExternalGeneralizedForce().unsafeGet();
		K = rigidBody->getExternalGeneralizedStiffness();
		D = rigidBody->getExternalGeneralizedDamping();

		EXPECT_LE((F - Fnumeric).cwiseAbs().maxCoeff(), 5e-7);
		EXPECT_LE((K - Knumeric).cwiseAbs().maxCoeff(), 5e-7);
		EXPECT_LE((D - Dnumeric).cwiseAbs().maxCoeff(), 5e-7);
	}

	{
		SCOPED_TRACE("Almost Identity pose, limitted development not used yet");

		Eigen::AngleAxisd angleAxis(5e-8, Vector3d(1.1, -1.4, 3.23).normalized());
		Vector3d t(1.1, 2.2, 3.3);
		RigidTransform3d transform = makeRigidTransform(Quaterniond(angleAxis), t);

		Vector6d inputForce = Vector6d::LinSpaced(1.1, 6.6);
		Vector6d dofX = Vector6d::Zero();
		dofX.segment<3>(0) = transform.translation();
		Eigen::AngleAxisd angleAxis2(transform.rotation());
		dofX.segment<3>(3) = angleAxis2.angle() * angleAxis2.axis();
		Vector6d dofV = Vector6d::Zero();
		Vector3d anchorLocalPoint = Vector3d::Ones();

		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setShape(m_sphere);
		SurgSim::Physics::RigidState initialState;
		initialState.setPose(transform);
		rigidBody->setInitialState(initialState);
		SurgSim::DataStructures::Location location(anchorLocalPoint);

		Vector6d Fnumeric = computeExtraTorque(inputForce, anchorLocalPoint, dofX, dofV);
		Matrix66d Knumeric = computeExtraStiffness(inputForce, anchorLocalPoint, dofX, dofV);
		Matrix66d Dnumeric = computeExtraDamping(inputForce, anchorLocalPoint, dofX, dofV);
		Vector6d F = inputForce;
		Matrix66d K = Matrix66d::Zero(), D = Matrix66d::Zero();
		rigidBody->addExternalGeneralizedForce(location, F, K, D);
		F = rigidBody->getExternalGeneralizedForce().unsafeGet();
		K = rigidBody->getExternalGeneralizedStiffness();
		D = rigidBody->getExternalGeneralizedDamping();

		EXPECT_LE((F - Fnumeric).cwiseAbs().maxCoeff(), 5e-7);
		EXPECT_LE((K - Knumeric).cwiseAbs().maxCoeff(), 5e-7); // Epsilon set by trial and error
		EXPECT_LE((D - Dnumeric).cwiseAbs().maxCoeff(), 5e-7);
	}

	{
		SCOPED_TRACE("Almost Identity pose, limitted development in use");

		Eigen::AngleAxisd angleAxis(5e-8, Vector3d(1.1, -1.4, 3.23).normalized());
		Vector3d t(1.1, 2.2, 3.3);
		RigidTransform3d transform = makeRigidTransform(Quaterniond(angleAxis), t);

		Vector6d inputForce = Vector6d::LinSpaced(1.1, 6.6);
		Vector6d dofX = Vector6d::Zero();
		dofX.segment<3>(0) = transform.translation();
		Eigen::AngleAxisd angleAxis2(transform.rotation());
		dofX.segment<3>(3) = angleAxis2.angle() * angleAxis2.axis();
		Vector6d dofV = Vector6d::Zero();
		Vector3d anchorLocalPoint = Vector3d::Ones();

		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setShape(m_sphere);
		SurgSim::Physics::RigidState initialState;
		initialState.setPose(transform);
		rigidBody->setInitialState(initialState);
		SurgSim::DataStructures::Location location(anchorLocalPoint);

		Vector6d Fnumeric = computeExtraTorque(inputForce, anchorLocalPoint, dofX, dofV);
		Matrix66d Knumeric = computeExtraStiffness(inputForce, anchorLocalPoint, dofX, dofV);
		Matrix66d Dnumeric = computeExtraDamping(inputForce, anchorLocalPoint, dofX, dofV);

		Vector6d F = inputForce;
		Matrix66d K = Matrix66d::Zero(), D = Matrix66d::Zero();
		rigidBody->addExternalGeneralizedForce(location, F, K, D);
		F = rigidBody->getExternalGeneralizedForce().unsafeGet();
		K = rigidBody->getExternalGeneralizedStiffness();
		D = rigidBody->getExternalGeneralizedDamping();

		EXPECT_LE((F - Fnumeric).cwiseAbs().maxCoeff(), 5e-7);
		EXPECT_LE((K - Knumeric).cwiseAbs().maxCoeff(), 5e-7);
		EXPECT_LE((D - Dnumeric).cwiseAbs().maxCoeff(), 5e-7);
	}
}

namespace
{
Vector6d computeSpringForce(double linearStiffness, double linearDamping,
							double angularStiffness, double angularDamping,
							Vector3d targetPosition, Vector3d targetLinearVelocity,
							Vector3d targetRotationVector, Vector3d targetAngularVelocity,
							Vector6d dofX, Vector6d dofV,
							bool doComputeExtraTorque = false, Vector3d localApplicationPoint = Vector3d::Zero())
{
	Vector6d f = Vector6d::Zero();

	f.segment<3>(0) += linearStiffness * (targetPosition - dofX.segment<3>(0));
	f.segment<3>(0) += linearDamping * (targetLinearVelocity - dofV.segment<3>(0));

	f.segment<3>(3) += angularStiffness * (targetRotationVector - dofX.segment<3>(3));
	f.segment<3>(3) += angularDamping * (targetAngularVelocity - dofV.segment<3>(3));
	if (doComputeExtraTorque)
	{
		Vector3d rotationVector = dofX.segment<3>(3);
		Matrix33d R;
		double angle = rotationVector.norm();
		if (std::abs(angle) < 1e-8)
		{
			R.setIdentity();
		}
		else
		{
			Vector3d axis = rotationVector / angle;
			R = cos(angle) * Matrix33d::Identity() +
				sin(angle) * SurgSim::Math::makeSkewSymmetricMatrix(axis) +
				(1.0 - cos(angle)) * axis * axis.transpose();
		}
		Vector3d applicationPoint = dofX.segment<3>(0) + R * localApplicationPoint;
		Vector3d lever = applicationPoint - dofX.segment<3>(0);
		f.segment<3>(3) += lever.cross(f.segment<3>(0));
	}

	return f;
}

Matrix66d computeSpringStiffness(double linearStiffness, double linearDamping,
								 double angularStiffness, double angularDamping,
								 Vector3d targetPosition, Vector3d targetLinearVelocity,
								 Vector3d targetRotationVector, Vector3d targetAngularVelocity,
								 Vector6d dofPosition, Vector6d dofVelocity,
								 bool doComputeExtraTorque = false, Vector3d localApplicationPoint = Vector3d::Zero())
{
	Matrix66d K = Matrix66d::Zero();
	const double epsilon = 1e-8;

	for (size_t column = 0; column < 6; ++column)
	{
		Vector6d dofX = dofPosition;
		dofX[column] += 2.0 * epsilon;
		Vector6d fXPlus2H = computeSpringForce(linearStiffness, linearDamping, angularStiffness, angularDamping,
											   targetPosition, targetLinearVelocity, targetRotationVector,
											   targetAngularVelocity, dofX, dofVelocity,
											   doComputeExtraTorque, localApplicationPoint);

		dofX = dofPosition;
		dofX[column] += epsilon;
		Vector6d fXPlusH = computeSpringForce(linearStiffness, linearDamping, angularStiffness, angularDamping,
											  targetPosition, targetLinearVelocity, targetRotationVector,
											  targetAngularVelocity, dofX, dofVelocity,
											  doComputeExtraTorque, localApplicationPoint);

		dofX = dofPosition;
		dofX[column] -= epsilon;
		Vector6d fXMinusH = computeSpringForce(linearStiffness, linearDamping, angularStiffness, angularDamping,
											   targetPosition, targetLinearVelocity, targetRotationVector,
											   targetAngularVelocity, dofX, dofVelocity,
											   doComputeExtraTorque, localApplicationPoint);

		dofX = dofPosition;
		dofX[column] -= 2.0 * epsilon;
		Vector6d fXMinus2H = computeSpringForce(linearStiffness, linearDamping, angularStiffness, angularDamping,
												targetPosition, targetLinearVelocity, targetRotationVector,
												targetAngularVelocity, dofX, dofVelocity,
												doComputeExtraTorque, localApplicationPoint);

		K.col(column) = - (-fXPlus2H + 8.0 * fXPlusH - 8.0 * fXMinusH + fXMinus2H) / (12.0 * epsilon);
	}

	return K;
}

Matrix66d computeSpringDamping(double linearStiffness, double linearDamping,
							   double angularStiffness, double angularDamping,
							   Vector3d targetPosition, Vector3d targetLinearVelocity,
							   Vector3d targetRotationVector, Vector3d targetAngularVelocity,
							   Vector6d dofPosition, Vector6d dofVelocity,
							   bool doComputeExtraTorque = false, Vector3d localApplicationPoint = Vector3d::Zero())
{
	Matrix66d D = Matrix66d::Zero();
	const double epsilon = 1e-8;

	for (size_t column = 0; column < 6; ++column)
	{
		Vector6d dofV = dofVelocity;
		dofV[column] += 2.0 * epsilon;
		Vector6d fXPlus2H = computeSpringForce(linearStiffness, linearDamping, angularStiffness, angularDamping,
											   targetPosition, targetLinearVelocity, targetRotationVector,
											   targetAngularVelocity, dofPosition, dofV,
											   doComputeExtraTorque, localApplicationPoint);

		dofV = dofVelocity;
		dofV[column] += epsilon;
		Vector6d fXPlusH = computeSpringForce(linearStiffness, linearDamping, angularStiffness, angularDamping,
											  targetPosition, targetLinearVelocity, targetRotationVector,
											  targetAngularVelocity, dofPosition, dofV,
											  doComputeExtraTorque, localApplicationPoint);

		dofV = dofVelocity;
		dofV[column] -= epsilon;
		Vector6d fXMinusH = computeSpringForce(linearStiffness, linearDamping, angularStiffness, angularDamping,
											   targetPosition, targetLinearVelocity, targetRotationVector,
											   targetAngularVelocity, dofPosition, dofV,
											   doComputeExtraTorque, localApplicationPoint);

		dofV = dofVelocity;
		dofV[column] -= 2.0 * epsilon;
		Vector6d fXMinus2H = computeSpringForce(linearStiffness, linearDamping, angularStiffness, angularDamping,
												targetPosition, targetLinearVelocity, targetRotationVector,
												targetAngularVelocity, dofPosition, dofV,
												doComputeExtraTorque, localApplicationPoint);

		D.col(column) = - (-fXPlus2H + 8.0 * fXPlusH - 8.0 * fXMinusH + fXMinus2H) / (12.0 * epsilon);
	}

	return D;
}
}; // namespace anonymous

TEST_F(RigidRepresentationTest, AddExternalGeneralizedForceTest)
{
	double linearStiffness = 1.1;
	double linearDamping = 1.2;
	double angularStiffness = 1.3;
	double angularDamping = 1.4;
	Vector3d targetPosition = Vector3d::Ones();
	Vector3d targetLinearVelocity = Vector3d::Ones() / 100.0;
	double angle = 1.2354;
	Vector3d axis = Vector3d(1.2, 0.4, 5.2).normalized();
	Vector3d targetRotationVector = axis * angle;
	Vector3d targetAngularVelocity = Vector3d::Ones() / 200.0;
	Vector3d localAnchorPoint = Vector3d::Ones();

	{
		SCOPED_TRACE("With stiffness, with damping");

		Eigen::AngleAxisd angleAxis(0.34512, Vector3d(1.1, -1.4, 3.23).normalized());
		Vector3d t(1.1, 0.9, 1.02);
		RigidTransform3d transform = makeRigidTransform(Quaterniond(angleAxis), t);

		Vector6d dofX = Vector6d::Zero();
		dofX.segment<3>(0) = transform.translation();
		Eigen::AngleAxisd angleAxis2(transform.rotation());
		dofX.segment<3>(3) = angleAxis2.axis() * angleAxis2.angle();
		Vector6d dofV = Vector6d::Zero();

		Vector6d FWithoutExtraTorque = computeSpringForce(linearStiffness, linearDamping,
									   angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									   targetRotationVector, targetAngularVelocity, dofX, dofV);
		Matrix66d KWithoutExtraTorque = computeSpringStiffness(linearStiffness, linearDamping,
										angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
										targetRotationVector, targetAngularVelocity, dofX, dofV);
		Matrix66d DWithoutExtraTorque = computeSpringDamping(linearStiffness, linearDamping,
										angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
										targetRotationVector, targetAngularVelocity, dofX, dofV);

		Vector6d FWithExtraTorque = computeSpringForce(linearStiffness, linearDamping,
									angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									targetRotationVector, targetAngularVelocity, dofX, dofV, true, localAnchorPoint);
		Matrix66d KWithExtraTorque = computeSpringStiffness(linearStiffness, linearDamping,
									 angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									 targetRotationVector, targetAngularVelocity, dofX, dofV, true, localAnchorPoint);
		Matrix66d DWithExtraTorque = computeSpringDamping(linearStiffness, linearDamping,
									 angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									 targetRotationVector, targetAngularVelocity, dofX, dofV, true, localAnchorPoint);

		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setShape(m_sphere);
		SurgSim::Physics::RigidState initialState;
		initialState.setPose(transform);
		rigidBody->setInitialState(initialState);
		SurgSim::DataStructures::Location location(localAnchorPoint);

		Vector6d F = FWithoutExtraTorque;
		Matrix66d K = KWithoutExtraTorque, D = DWithoutExtraTorque;
		rigidBody->addExternalGeneralizedForce(location, F, K, D);
		F = rigidBody->getExternalGeneralizedForce().unsafeGet();
		K = rigidBody->getExternalGeneralizedStiffness();
		D = rigidBody->getExternalGeneralizedDamping();

		EXPECT_LE((F - FWithExtraTorque).cwiseAbs().maxCoeff(), 1e-7);
		EXPECT_LE((K - KWithExtraTorque).cwiseAbs().maxCoeff(), 1e-7);
		EXPECT_LE((D - DWithExtraTorque).cwiseAbs().maxCoeff(), 1e-7);
	}

	{
		SCOPED_TRACE("With stiffness, without damping");

		Eigen::AngleAxisd angleAxis(0.34512, Vector3d(1.1, -1.4, 3.23).normalized());
		Vector3d t(1.1, 0.9, 1.02);
		RigidTransform3d transform = makeRigidTransform(Quaterniond(angleAxis), t);

		Vector6d dofX = Vector6d::Zero();
		dofX.segment<3>(0) = transform.translation();
		Eigen::AngleAxisd angleAxis2(transform.rotation());
		dofX.segment<3>(3) = angleAxis2.axis() * angleAxis2.angle();
		Vector6d dofV = Vector6d::Zero();

		Vector6d FWithoutExtraTorque = computeSpringForce(linearStiffness, linearDamping,
									   angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									   targetRotationVector, targetAngularVelocity, dofX, dofV);
		Matrix66d KWithoutExtraTorque = computeSpringStiffness(linearStiffness, linearDamping,
										angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
										targetRotationVector, targetAngularVelocity, dofX, dofV);

		Vector6d FWithExtraTorque = computeSpringForce(linearStiffness, linearDamping,
									angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									targetRotationVector, targetAngularVelocity, dofX, dofV, true, localAnchorPoint);
		Matrix66d KWithExtraTorque = computeSpringStiffness(linearStiffness, linearDamping,
									 angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									 targetRotationVector, targetAngularVelocity, dofX, dofV, true, localAnchorPoint);

		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setShape(m_sphere);
		SurgSim::Physics::RigidState initialState;
		initialState.setPose(transform);
		rigidBody->setInitialState(initialState);
		SurgSim::DataStructures::Location location(localAnchorPoint);

		Vector6d F = FWithoutExtraTorque;
		Matrix66d K = KWithoutExtraTorque;
		rigidBody->addExternalGeneralizedForce(location, F, K);
		F = rigidBody->getExternalGeneralizedForce().unsafeGet();
		K = rigidBody->getExternalGeneralizedStiffness();

		EXPECT_LE((F - FWithExtraTorque).cwiseAbs().maxCoeff(), 1e-7);
		EXPECT_LE((K - KWithExtraTorque).cwiseAbs().maxCoeff(), 1e-7);
	}

	{
		SCOPED_TRACE("Without stiffness, without damping");

		Eigen::AngleAxisd angleAxis(0.34512, Vector3d(1.1, -1.4, 3.23).normalized());
		Vector3d t(1.1, 0.9, 1.02);
		RigidTransform3d transform = makeRigidTransform(Quaterniond(angleAxis), t);

		Vector6d dofX = Vector6d::Zero();
		dofX.segment<3>(0) = transform.translation();
		Eigen::AngleAxisd angleAxis2(transform.rotation());
		dofX.segment<3>(3) = angleAxis2.axis() * angleAxis2.angle();
		Vector6d dofV = Vector6d::Zero();

		Vector6d FWithoutExtraTorque = computeSpringForce(linearStiffness, linearDamping,
									   angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									   targetRotationVector, targetAngularVelocity, dofX, dofV);

		Vector6d FWithExtraTorque = computeSpringForce(linearStiffness, linearDamping,
									angularStiffness, angularDamping, targetPosition, targetLinearVelocity,
									targetRotationVector, targetAngularVelocity, dofX, dofV, true, localAnchorPoint);

		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setShape(m_sphere);
		SurgSim::Physics::RigidState initialState;
		initialState.setPose(transform);
		rigidBody->setInitialState(initialState);
		SurgSim::DataStructures::Location location(localAnchorPoint);

		Vector6d F = FWithoutExtraTorque;
		rigidBody->addExternalGeneralizedForce(location, F);
		F = rigidBody->getExternalGeneralizedForce().unsafeGet();

		EXPECT_LE((F - FWithExtraTorque).cwiseAbs().maxCoeff(), 1e-7);
	}
}

TEST_F(RigidRepresentationTest, NoForceTorqueTest)
{
	// Create the rigid body
	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");

	// Setup phase
	rigidBody->setLocalActive(true);
	rigidBody->setIsGravityEnabled(false);
	rigidBody->setDensity(m_density);
	rigidBody->setShape(m_sphere);

	// Run few time steps
	for (int timeStep = 0; timeStep < m_maxNumSimulationStepTest; timeStep++)
	{
		rigidBody->beforeUpdate(m_dt);
		rigidBody->update(m_dt);
		rigidBody->afterUpdate(m_dt);
	}

	const Vector3d    G = rigidBody->getCurrentState().getPose().translation();
	const Matrix33d&  R = rigidBody->getCurrentState().getPose().linear();
	const Quaterniond q = Quaterniond(R);
	const Vector3d    v = rigidBody->getCurrentState().getLinearVelocity();
	const Vector3d    w = rigidBody->getCurrentState().getAngularVelocity();
	ASSERT_EQ(Vector3d::Zero(), G);
	ASSERT_TRUE(q.isApprox(Quaterniond::Identity()));
	ASSERT_EQ(Vector3d::Zero(), v);
	ASSERT_EQ(Vector3d::Zero(), w);
}

TEST_F(RigidRepresentationTest, GravityTest)
{
	// Create the rigid body
	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
	Vector3d gravity(0.0, -9.81, 0.0);

	// Setup phase
	rigidBody->setLocalActive(true);
	rigidBody->setIsGravityEnabled(true);
	rigidBody->setDensity(m_density);
	rigidBody->setShape(m_sphere);

	// Run few time steps
	for (int timeStep = 0; timeStep < m_maxNumSimulationStepTest; timeStep++)
	{
		rigidBody->beforeUpdate(m_dt);
		rigidBody->update(m_dt);
		rigidBody->afterUpdate(m_dt);

		const Vector3d    G = rigidBody->getCurrentState().getPose().translation();
		const Matrix33d&  R = rigidBody->getCurrentState().getPose().linear();
		const Quaterniond q = Quaterniond(R);
		const Vector3d    v = rigidBody->getCurrentState().getLinearVelocity();
		const Vector3d    w = rigidBody->getCurrentState().getAngularVelocity();

		const Vector3d    Gprev = rigidBody->getPreviousState().getPose().translation();
		const Vector3d    vprev = rigidBody->getPreviousState().getLinearVelocity();

		// Implicit numerical integration gives v(t+dt) = v(t) + dt.a(t+dt) = v(t) + dt.g
		//                                      p(t+dt) = p(t) + dt.v(t+dt) = p(t) + dt.v(t) + dt^2.g
		Vector3d tmpV = vprev + gravity * m_dt;
		double diffV = (v - tmpV).norm();
		Vector3d tmpG = Gprev + tmpV * m_dt;
		double diffG = (G - tmpG).norm();

		ASSERT_NEAR(0.0, diffG, epsilon);
		ASSERT_TRUE(q.isApprox(Quaterniond::Identity()));
		ASSERT_NEAR(0.0, diffV, epsilon);
		ASSERT_EQ(Vector3d::Zero(), w);
	}
}

TEST_F(RigidRepresentationTest, PreviousStateDifferentFromCurrentTest)
{
	// Create the rigid body
	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
	Vector3d gravity(0.0, -9.81, 0.0);

	// Setup phase
	rigidBody->setLocalActive(true);
	rigidBody->setIsGravityEnabled(true);
	rigidBody->setDensity(m_density);
	rigidBody->setShape(m_sphere);

	// Run few time steps
	for (int timeStep = 0; timeStep < m_maxNumSimulationStepTest; timeStep++)
	{
		rigidBody->beforeUpdate(m_dt);
		rigidBody->update(m_dt);
		rigidBody->afterUpdate(m_dt);

		ASSERT_NE(rigidBody->getPreviousState(), rigidBody->getCurrentState());
	}
}

void disableWhenDivergeTest(std::shared_ptr<RigidRepresentation> rigidBody,
							const RigidState& state, double dt)
{
	// Setup phase
	rigidBody->setLocalActive(true);
	rigidBody->setIsGravityEnabled(true);
	rigidBody->setInitialState(state);

	// Run 1 time step and make sure that the rigid body has been disabled
	// The rotation explode under the angular velocity too strong !
	{
		ASSERT_TRUE(rigidBody->isActive());

		rigidBody->beforeUpdate(dt);
		rigidBody->update(dt);
		rigidBody->afterUpdate(dt);

		ASSERT_FALSE(rigidBody->isActive());
	}
}

TEST_F(RigidRepresentationTest, DisableWhenDivergeTest)
{
	Quaterniond q  = Quaterniond::Identity();
	Vector3d vZero = Vector3d::Zero();
	Vector3d vMax  = Vector3d::Constant(std::numeric_limits<double>::max());

	// Test linear failure (with Signaling Nan)
	{
		// Create the rigid body
		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setDensity(m_density);
		rigidBody->setShape(m_sphere);

		// Sets the state
		m_state.reset();
		m_state.setPose(SurgSim::Math::makeRigidTransform(q, vMax));
		m_state.setLinearVelocity(Vector3d::Constant(std::numeric_limits<double>::signaling_NaN()));

		SCOPED_TRACE("Testing linear with Signaling Nan");
		disableWhenDivergeTest(rigidBody, m_state, m_dt);
	}

	// Test linear failure (with quiet Nan)
	{
		// Create the rigid body
		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setDensity(m_density);
		rigidBody->setShape(m_sphere);

		// Sets the state
		m_state.reset();
		m_state.setPose(makeRigidTransform(q, vMax));
		m_state.setLinearVelocity(Vector3d::Constant(std::numeric_limits<double>::quiet_NaN()));

		SCOPED_TRACE("Testing linear with Quiet Nan");
		disableWhenDivergeTest(rigidBody, m_state, m_dt);
	}

	// Test linear failure (with numerical maximum value)
	{
		// Create the rigid body
		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setDensity(m_density);
		rigidBody->setShape(m_sphere);

		// Sets the state
		m_state.reset();
		m_state.setPose(makeRigidTransform(q, vMax));
		m_state.setLinearVelocity(Vector3d::Constant(std::numeric_limits<double>::max()));

		SCOPED_TRACE("Testing linear with double max");
		disableWhenDivergeTest(rigidBody, m_state, m_dt);
	}

	// Test angular failure (with Signaling Nan)
	{
		// Create the rigid body
		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setDensity(m_density);
		rigidBody->setShape(m_sphere);

		// Sets the state
		m_state.reset();
		m_state.setPose(makeRigidTransform(q, vZero));
		m_state.setAngularVelocity(Vector3d::Constant(std::numeric_limits<double>::signaling_NaN()));

		SCOPED_TRACE("Testing angular with Signaling Nan");
		disableWhenDivergeTest(rigidBody, m_state, m_dt);
	}

	// Test angular failure (with quiet Nan)
	{
		// Create the rigid body
		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setDensity(m_density);
		rigidBody->setShape(m_sphere);

		// Sets the state
		m_state.reset();
		m_state.setPose(makeRigidTransform(q, vZero));
		m_state.setAngularVelocity(Vector3d::Constant(std::numeric_limits<double>::quiet_NaN()));

		SCOPED_TRACE("Testing angular with Quiet Nan");
		disableWhenDivergeTest(rigidBody, m_state, m_dt);
	}

	// Test angular failure (with numerical maximum value)
	{
		// Create the rigid body
		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setDensity(m_density);
		rigidBody->setShape(m_sphere);

		// Sets the state
		m_state.reset();
		m_state.setPose(makeRigidTransform(q, vZero));
		m_state.setAngularVelocity(Vector3d::Constant(std::numeric_limits<double>::max()));

		SCOPED_TRACE("Testing angular with double max");
		disableWhenDivergeTest(rigidBody, m_state, m_dt);
	}
}

TEST_F(RigidRepresentationTest, LocalizationCreation)
{
	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
	Location loc(Vector3d(3.0, 2.0, 1.0));

	std::shared_ptr<Localization> localization = rigidBody->createLocalization(loc);
	EXPECT_TRUE(localization->getRepresentation() == rigidBody);

	Vector3d globalPos = rigidBody->getCurrentState().getPose() * loc.rigidLocalPosition.getValue();

	EXPECT_TRUE(globalPos.isApprox(localization->calculatePosition(0.0)));
	EXPECT_TRUE(globalPos.isApprox(localization->calculatePosition(1.0)));

}

TEST_F(RigidRepresentationTest, InvalidShapes)
{
	std::shared_ptr<Shape> shapeWithNoVolume = std::make_shared<PlaneShape>();
	std::shared_ptr<Runtime> runtime = std::make_shared<Runtime>();

	{
		std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
		rigidBody->setShape(shapeWithNoVolume);

		std::shared_ptr<Component> component = rigidBody;
		EXPECT_THROW(component->initialize(runtime), SurgSim::Framework::AssertionFailure);
	}
}

TEST_F(RigidRepresentationTest, WithMeshShape)
{
	std::shared_ptr<Runtime> runtime = std::make_shared<Runtime>("config.txt");

	std::shared_ptr<SurgSim::Math::MeshShape> shape = std::make_shared<SurgSim::Math::MeshShape>();
	shape->load("Geometry/staple_collision.ply");
	EXPECT_TRUE(shape->isValid());

	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");
	rigidBody->setShape(shape);

	EXPECT_NO_THROW(rigidBody->initialize(runtime));
	EXPECT_TRUE(shape->isValid());

	std::shared_ptr<RigidRepresentation> rigidBody2 = std::make_shared<RigidRepresentation>("Rigid2");
	rigidBody2->setShape(shape);
	EXPECT_NO_THROW(rigidBody2->initialize(runtime));
}

TEST_F(RigidRepresentationTest, CollisionRepresentationTest)
{
	auto rigidBody(std::make_shared<RigidRepresentation>("Rigid"));

	auto collision1(std::make_shared<RigidCollisionRepresentation>("collision1"));
	auto collision2(std::make_shared<RigidCollisionRepresentation>("collision2"));

	EXPECT_EQ(nullptr, rigidBody->getCollisionRepresentation());
	EXPECT_NO_THROW(rigidBody->setCollisionRepresentation(collision1));
	EXPECT_EQ(collision1, rigidBody->getCollisionRepresentation());
	EXPECT_EQ(rigidBody, collision1->getRigidRepresentation());

	// Change the collision object
	EXPECT_NO_THROW(rigidBody->setCollisionRepresentation(collision2));
	EXPECT_EQ(collision2, rigidBody->getCollisionRepresentation());
	EXPECT_EQ(rigidBody, collision2->getRigidRepresentation());
	EXPECT_EQ(nullptr, collision1->getRigidRepresentation());

	// Clear the collision representation
	EXPECT_NO_THROW(rigidBody->setCollisionRepresentation(nullptr));
	EXPECT_EQ(nullptr, rigidBody->getCollisionRepresentation());
	EXPECT_EQ(nullptr, collision1->getRigidRepresentation());
	EXPECT_EQ(nullptr, collision2->getRigidRepresentation());
}

TEST_F(RigidRepresentationTest, DensityWithSphereShapeTest)
{
	std::shared_ptr<RigidRepresentation> rigidBody = std::make_shared<RigidRepresentation>("Rigid");

	// Mass density
	rigidBody->setDensity(m_density);

	// Shape
	rigidBody->setShape(m_sphere);

	// Test inertia
	EXPECT_TRUE(rigidBody->getLocalInertia().isApprox(m_inertia));

	// Test mass
	EXPECT_EQ(m_mass, rigidBody->getMass());

	// Test mass center
	EXPECT_TRUE(rigidBody->getMassCenter().isZero());
}


TEST_F(RigidRepresentationTest, SerializationTest)
{
	{
		SCOPED_TRACE("Encode/Decode as shared_ptr<>, should be OK");
		auto rigidRepresentation = std::make_shared<RigidRepresentation>("TestRigidRepresentation");
		YAML::Node node;
		ASSERT_NO_THROW(
			node = YAML::convert<std::shared_ptr<SurgSim::Framework::Component>>::encode(rigidRepresentation));

		std::shared_ptr<RigidRepresentation> newRepresentation;
		EXPECT_NO_THROW(newRepresentation =	std::dynamic_pointer_cast<RigidRepresentation>
											(node.as<std::shared_ptr<SurgSim::Framework::Component>>()));
	}

	{
		SCOPED_TRACE("Encode a RigidRepresentation object without a shape, should throw.");
		auto rigidRepresentation = std::make_shared<RigidRepresentation>("TestRigidRepresentation");
		auto rigidCollisionRepresentation =
			std::make_shared<RigidCollisionRepresentation>("RigidCollisionRepresentation");

		rigidRepresentation->setCollisionRepresentation(rigidCollisionRepresentation);

		EXPECT_ANY_THROW(YAML::convert<SurgSim::Framework::Component>::encode(*rigidRepresentation));
	}

	{
		SCOPED_TRACE("Encode a RigidRepresentation object with valid RigidCollisionRepresentation and shape, no throw");
		auto rigidRepresentation = std::make_shared<RigidRepresentation>("TestRigidRepresentation");
		auto rigidCollisionRepresentation =
			std::make_shared<RigidCollisionRepresentation>("RigidCollisionRepresentation");

		rigidRepresentation->setCollisionRepresentation(rigidCollisionRepresentation);
		rigidRepresentation->setDensity(0.1);
		rigidRepresentation->setLinearDamping(0.2);
		rigidRepresentation->setAngularDamping(0.3);
		rigidRepresentation->setShape(m_sphere);

		YAML::Node node;
		EXPECT_NO_THROW(node = YAML::convert<SurgSim::Framework::Component>::encode(*rigidRepresentation));

		std::shared_ptr<RigidRepresentation> newRepresentation;
		newRepresentation =
			std::dynamic_pointer_cast<RigidRepresentation>(node.as<std::shared_ptr<SurgSim::Framework::Component>>());
		EXPECT_NE(nullptr, newRepresentation->getCollisionRepresentation());
		EXPECT_NEAR(0.1, newRepresentation->getValue<double>("Density"), epsilon);
		EXPECT_NEAR(0.2, newRepresentation->getValue<double>("LinearDamping"), epsilon);
		EXPECT_NEAR(0.3, newRepresentation->getValue<double>("AngularDamping"), epsilon);

		// Shape is encoded/decoded as concrete object instead of reference/shared_ptr<>.
		EXPECT_NE(m_sphere, newRepresentation->getValue<std::shared_ptr<SurgSim::Math::Shape>>("Shape"));

		auto decodedShape = newRepresentation->getValue<std::shared_ptr<SurgSim::Math::Shape>>("Shape");
		EXPECT_EQ(m_sphere->getClassName(), decodedShape->getClassName());
		EXPECT_NEAR(m_sphere->getVolume(), decodedShape->getVolume(), epsilon);

		auto newCollisionRepresentation =
			std::dynamic_pointer_cast<RigidCollisionRepresentation>(newRepresentation->getCollisionRepresentation());
		EXPECT_EQ(newRepresentation, newCollisionRepresentation->getRigidRepresentation());
	}
}

}; // namespace Physics
}; // namespace SurgSim