-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathGameLogicPlugin.cc
3109 lines (2680 loc) · 112 KB
/
GameLogicPlugin.cc
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) 2019 Open Source Robotics Foundation
*
* 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 <yaml-cpp/yaml.h>
#include <ros/ros.h>
#include <rosbag/recorder.h>
#include <ignition/msgs/boolean.pb.h>
#include <ignition/msgs/float.pb.h>
#include <ignition/msgs/stringmsg.pb.h>
#include <ignition/plugin/Register.hh>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <map>
#include <mutex>
#include <utility>
#include <ignition/gazebo/Link.hh>
#include <ignition/gazebo/components/AngularVelocity.hh>
#include <ignition/gazebo/components/HaltMotion.hh>
#include <ignition/gazebo/components/CanonicalLink.hh>
#include <ignition/gazebo/components/Inertial.hh>
#include <ignition/gazebo/components/Link.hh>
#include <ignition/gazebo/components/LinearVelocity.hh>
#include <ignition/gazebo/components/BatterySoC.hh>
#include <ignition/gazebo/components/DetachableJoint.hh>
#include <ignition/gazebo/components/Performer.hh>
#include <ignition/gazebo/components/Model.hh>
#include <ignition/gazebo/components/Name.hh>
#include <ignition/gazebo/components/DepthCamera.hh>
#include <ignition/gazebo/components/GpuLidar.hh>
#include <ignition/gazebo/components/RgbdCamera.hh>
#include <ignition/gazebo/components/ParentEntity.hh>
#include <ignition/gazebo/components/ParticleEmitter.hh>
#include <ignition/gazebo/components/Pose.hh>
#include <ignition/gazebo/components/Sensor.hh>
#include <ignition/gazebo/components/Static.hh>
#include <ignition/gazebo/components/SourceFilePath.hh>
#include <ignition/gazebo/components/World.hh>
#include <ignition/gazebo/Conversions.hh>
#include <ignition/gazebo/EntityComponentManager.hh>
#include <ignition/gazebo/Events.hh>
#include <ignition/gazebo/Util.hh>
#include <ignition/common/Console.hh>
#include <ignition/common/Util.hh>
#include <ignition/common/Time.hh>
#include <ignition/math/Pose3.hh>
#include <ignition/math/Quaternion.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/transport/Node.hh>
#include <sdf/sdf.hh>
#include <geometry_msgs/PoseStamped.h>
#include "subt_ros/ArtifactReport.h"
#include "subt_ros/KinematicStates.h"
#include "subt_ros/RegionEvent.h"
#include "subt_ros/Robot.h"
#include "subt_ros/RobotEvent.h"
#include "subt_ros/RunStatistics.h"
#include "subt_ros/RunStatus.h"
#include "subt_ign/Common.hh"
#include "subt_ign/GameLogicPlugin.hh"
#include "subt_ign/protobuf/artifact.pb.h"
#include "subt_ign/RobotPlatformTypes.hh"
IGNITION_ADD_PLUGIN(
subt::GameLogicPlugin,
ignition::gazebo::System,
subt::GameLogicPlugin::ISystemConfigure,
subt::GameLogicPlugin::ISystemPreUpdate,
subt::GameLogicPlugin::ISystemPostUpdate)
using namespace ignition;
using namespace gazebo;
using namespace systems;
using namespace subt;
/// \brief Kinetic energy information used to determine when a crash occurs.
class KineticEnergyInfo
{
/// \brief Value of the previous iteration's kinetic energy.
public: double prevKineticEnergy{0.0};
/// \brief Threshold past which a crash has happened. Negative number
/// indicates that unlimited kinetic energy is allowed.
public: double kineticEnergyThreshold{-1.0};
/// \brief The link used to get kinetic energy.
public: gazebo::Entity link;
/// \brief Name of the robot.
public: std::string robotName;
};
class subt::GameLogicPluginPrivate
{
/// \brief Write a simulation timestamp to a logfile.
/// \param[in] _simTime Current sim time.
/// \return A file stream that can be used to write additional
/// information to the logfile.
public: std::ofstream &Log(const ignition::msgs::Time &_simTime);
/// \brief Calculate the score of a new artifact request.
/// \param[in] _simTime Simulation time.
/// \param[in] _type The object type. See ArtifactType.
/// \param[in] _pose The object pose.
/// \return A tuple where the first parameter is the score obtained for this
/// report, and the second parameter is true if the artifact report is a
/// duplicate and false otherwise.
public: std::tuple<double, bool> ScoreArtifact(
const ignition::msgs::Time &_simTime,
const subt::ArtifactType &_type,
const ignition::msgs::Pose &_pose,
subt_ros::ArtifactReport &_artifactMsg);
/// \brief Callback executed to process a new artifact request
/// sent by a team.
/// \param[in] _req The service request.
public: bool OnNewArtifact(const subt::msgs::Artifact &_req,
subt::msgs::ArtifactScore &_resp);
/// \brief Publish the score.
/// \param[in] _event Unused.
public: void PublishScore();
/// \brief Log robot pos data
public: void LogRobotPosData();
/// \brief Log robot and artifact data
/// \param[in] _simTime Current sim time.
/// \param[in] _realElapsed Elapsed real time in seconds.
/// \param[in] _simElapsed Elapsed sim time in seconds.
public: void LogRobotArtifactData(
const ignition::msgs::Time &_simTime,
int _realElapsed,
int _simElapsed) const;
/// \brief Finish game and generate log files
/// \param[in] _simTime Simulation time.
public: void Finish(const ignition::msgs::Time &_simTime);
/// \brief Ignition service callback triggered when the service is called.
/// \param[in] _req The message containing the robot name.
/// \param[out] _res The response message.
/// \return true on success.
public: bool OnPoseFromArtifact(
const ignition::msgs::StringMsg &_req,
ignition::msgs::Pose &_res);
/// \brief Update the score.yml and summary.yml files. This function also
/// returns the time point used to calculate the elapsed real time. By
/// returning this time point, we can make sure that the ::Finish function
/// uses the same time point.
/// \param[in] _simTime Current sim time.
/// \return The time point used to calculate the elapsed real time.
public: std::chrono::steady_clock::time_point UpdateScoreFiles(
const ignition::msgs::Time &_simTime);
/// \brief Performer detector subscription callback.
/// \param[in] _msg Pose message of the event.
public: void OnEvent(const ignition::msgs::Pose &_msg);
/// \brief Log an event to the eventStream.
/// \param[in] _event The event to log.
public: void LogEvent(const std::string &_event);
/// \brief Publish a robot event.
/// \param[in] _simTime Current sim time.
/// \param[in] _type Event type.
/// \param[in] _robot Robot name.
/// \param[in] _eventId Unique ID of the event.
public: void PublishRobotEvent(
const ignition::msgs::Time &_simTime,
const std::string &_type,
const std::string &_robot,
int _eventId);
/// \brief Publish a region event.
/// \param[in] _simTime Current sim time.
/// \param[in] _type Event type.
/// \param[in] _robot Robot name.
/// \param[in] _eventId Unique ID of the event.
public: void PublishRegionEvent(
const ignition::msgs::Time &_simTime,
const std::string &_type,
const std::string &_robot, const std::string &_detector,
const std::string &_state,
int _eventId);
/// \brief Marsupial detach subscription callback.
/// \param[in] _msg Detach message.
/// \param[in] _info Message information.
public: void OnDetachEvent(const ignition::msgs::Empty &_msg,
const transport::MessageInfo &_info);
/// \brief Breadcrumb deploy subscription callback.
/// \param[in] _msg Deploy message.
/// \param[in] _info Message information.
public: void OnBreadcrumbDeployEvent(const ignition::msgs::Empty &_msg,
const transport::MessageInfo &_info);
/// \brief Breadcrumb remaining subscription callback.
/// \param[in] _msg Remaining count.
/// \param[in] _info Message information.
public: void OnBreadcrumbDeployRemainingEvent(
const ignition::msgs::Int32 &_msg,
const transport::MessageInfo &_info);
/// \brief Dynamic collapse remaining subscription callback.
/// \param[in] _msg Remaining count.
/// \param[in] _info Message information.
public: void OnDynamicCollapseDeployRemainingEvent(
const ignition::msgs::Int32 &_msg,
const transport::MessageInfo &_info);
/// \brief Fog command subscription callback.
/// \param[in] _msg Particle emitter message.
/// \param[in] _info Message information.
public: void OnFogCmdEvent(
const ignition::msgs::ParticleEmitter &_msg,
const transport::MessageInfo &_info);
/// \brief Rock fall remaining subscription callback.
/// \param[in] _msg Remaining count.
/// \param[in] _info Message information.
public: void OnRockFallDeployRemainingEvent(
const ignition::msgs::Int32 &_msg,
const transport::MessageInfo &_info);
/// \brief Battery subscription callback.
/// \param[in] _msg Battery message.
/// \param[in] _info Message information.
public: void OnBatteryMsg(const ignition::msgs::BatteryState &_msg,
const transport::MessageInfo &_info);
private: bool PoseFromArtifactHelper(const std::string &_robot,
ignition::math::Pose3d &_result);
/// \brief Ignition service callback triggered when the service is called.
/// \param[in] _req The message containing a flag telling if the game
/// is to start.
/// \param[out] _res The response message.
public: bool OnStartCall(const ignition::msgs::Boolean &_req,
ignition::msgs::Boolean &_res);
/// \brief Helper function to start the competition.
/// \param[in] _simTime Simulation time.
/// \return True if the run was started.
public: bool Start(const ignition::msgs::Time &_simTime);
/// \brief Ignition service callback triggered when the service is called.
/// \param[in] _req The message containing a flag telling if the game is to
/// be finished.
/// \param[out] _res The response message.
public: bool OnFinishCall(const ignition::msgs::Boolean &_req,
ignition::msgs::Boolean &_res);
/// \brief Checks if a robot has flipped.
public: void CheckRobotFlip();
/// \brief Round input number n down to the nearest mulitple of m
/// \param[in] _n input number
/// \param[in] _m the input number will be rounded down to the nearest
/// multiple of this number.
/// \return Result
public: double FloorMultiple(double _n, double _m);
/// \brief Convert a world pose to be in the artifact origin frame.
/// \param[in] _pose Pose to convert.
/// \return Pose in the artifact origin frame.
public: ignition::math::Pose3d ConvertToArtifactOrigin(
const ignition::math::Pose3d &_pose) const;
/// \brief Ignition Transport node.
public: transport::Node node;
/// \brief Current simulation time.
public: ignition::msgs::Time simTime;
/// \brief Amount of allowed warmup time in seconds.
public: int warmupTimeSec = 900;
/// \brief The simulation time of the start call.
public: ignition::msgs::Time startSimTime;
/// \brief Number of simulation seconds allowed.
public: std::chrono::seconds runDuration{0};
/// \brief Thread on which scores are published
public: std::unique_ptr<std::thread> publishThread = nullptr;
/// \brief Thread on which the ROS bag recorder runs.
public: std::unique_ptr<std::thread> bagThread = nullptr;
/// \brief Whether the task has started.
public: bool started = false;
/// \brief Whether the task has finished.
public: bool finished = false;
/// \brief Start time used for scoring.
public: std::chrono::steady_clock::time_point startTime;
/// \brief Store all artifacts.
/// The key is the object type. See ArtifactType for all supported values.
/// The value is another map, where the key is the model name and the value
/// is a Model pointer.
public: std::map<subt::ArtifactType,
std::map<std::string, ignition::math::Pose3d>> artifacts;
/// \brief Artifacts that were found.
public: std::set<std::string> foundArtifacts;
public: std::map<std::string, ignition::math::Pose3d> poses;
/// \brief Counter to track unique identifiers.
public: uint32_t reportCount = 0u;
/// \brief Counter to track duplicate artifact reports
public: uint32_t duplicateReportCount = 0u;
/// The maximum number of times that a team can attempt an
/// artifact report.
public: uint32_t reportCountLimit = 40u;
/// \brief The total number of artifacts.
public: uint32_t artifactCount = 20u;
/// \brief Total score.
public: double totalScore = 0.0;
/// \brief Closest artifact report. The elements are: artifact name, type,
/// true pos, reported pos, distance between true pos and reported pos
public: std::tuple<std::string, std::string, ignition::math::Vector3d,
ignition::math::Vector3d, double> closestReport =
{"", "", ignition::math::Vector3d(), ignition::math::Vector3d(), -1};
/// \brief First artifact report time
public: double firstReportTime = -1;
/// \brief Last artifact report time
public: double lastReportTime = -1;
/// \brief A map of robot name and a vector of timestamped position data
public: std::map<std::string, std::vector<std::pair<
std::chrono::steady_clock::duration, ignition::math::Pose3d>>>
robotPoseData;
/// \brief A map of robot name and its starting pose
public: std::map<std::string, ignition::math::Pose3d> robotStartPose;
/// \brief A map of robot name and distance traveled
public: std::map<std::string, double> robotDistance;
/// \brief Step size for elevation gain / loss
public: double elevationStepSize = 5.0;
/// \brief A map of robot name and elevation gain (cumulative)
public: std::map<std::string, double> robotElevationGain;
/// \brief A map of robot name and elevation loss (cumulative)
public: std::map<std::string, double> robotElevationLoss;
/// \brief A map of robot name and max euclidean distance traveled
public: std::map<std::string, double> robotMaxEuclideanDistance;
/// \brief A map of robot name and its average velocity
public: std::map<std::string, double> robotAvgVel;
/// \brief A map of robot name and its previous pose
public: std::map<std::string, ignition::math::Pose3d> robotPrevPose;
/// \brief A map of robot name to its flip information.
/// The value is a pair stating the sim time where the most recent flip started,
/// and if the robot is currently flipped.
public: std::map<std::string, std::pair<int64_t, bool>> robotFlipInfo;
/// \brief Robot name with the max velocity
public: std::pair<std::string, double> maxRobotVel = {"", 0};
/// \brief Robot name with the max average velocity
public: std::pair<std::string, double> maxRobotAvgVel = {"", 0};
/// \brief Robot name with the max distance traveled;
public: std::pair<std::string, double> maxRobotDistance = {"", 0};
/// \brief Robot name with the max euclidean distance from starting area;
public: std::pair<std::string, double> maxRobotEuclideanDistance = {"", 0};
/// \brief Robot name with the max cumulative elevation gain;
public: std::pair<std::string, double> maxRobotElevationGain = {"", 0};
/// \brief Robot name with the max cumulative elevation loss;
public: std::pair<std::string, double> maxRobotElevationLoss = {"", 0};
/// \brief Robot name with the max elevation reached;
public: std::pair<std::string, double> maxRobotElevation = {"", 0};
/// \brief Robot name with the min elevation reached;
public: std::pair<std::string, double> minRobotElevation = {"", 0};
/// \brief Total distanced traveled by all robots
public: double robotsTotalDistance = 0;
/// \brief Total cumulative elevation gain by all robots
public: double robotsTotalElevationGain = 0;
/// \brief Total cumulative elevation loss by all robots
public: double robotsTotalElevationLoss = 0;
/// \brief A map of robot name and its pos output stream
public: std::map<std::string, std::shared_ptr<std::ofstream>> robotPosStream;
/// \brief A mutex.
public: std::mutex logMutex;
/// \brief A mutex.
public: std::mutex mutex;
/// \brief Mutex to protect the poses data structure.
public: std::mutex posesMutex;
/// \brief Log file output stream.
public: std::ofstream logStream;
/// \brief Event file output stream.
public: std::ofstream eventStream;
/// \brief Mutex to protect the eventStream.
public: std::mutex eventMutex;
/// \brief The pose of the object marking the origin of the artifacts.
public: ignition::math::Pose3d artifactOriginPose;
/// \brief Ignition transport start publisher. This is needed by cloudsim
/// to know when a run has been started.
public: transport::Node::Publisher startPub;
/// \brief Ignition transport competition clock publisher.
public: transport::Node::Publisher competitionClockPub;
/// \brief Ignition transport for the remaining artifact reports.
public: transport::Node::Publisher artifactReportPub;
/// \brief Ignition transport that publishes robot name and type info.
public: transport::Node::Publisher robotPub;
/// \brief Logpath.
public: std::string logPath{"/dev/null"};
/// \brief Names of the spawned robots.
public: std::set<std::string> robotNames;
/// \brief Robot types for keeping track of unique robot platform types.
public: std::set<std::string> robotTypes;
/// \brief Map of robot name to {platform, config}. For example:
/// {"MY_ROBOT_NAME", {"X1", "X1 SENSOR CONFIG 1"}}.
public: std::map<std::string, std::pair<std::string, std::string>>
robotFullTypes;
/// \brief The unique artifact reports received, and the score it received.
public: std::map<std::string, double> uniqueReports;
/// \brief Current state.
public: std::string state="init";
/// \brief Time at which the last status publication took place.
public: std::chrono::steady_clock::time_point lastStatusPubTime;
/// \brief Time at which the summary.yaml file was last updated.
public: mutable std::chrono::steady_clock::time_point lastUpdateScoresTime;
/// \brief Distance from the base station after which the competition is
/// automatically started, and a robot can no longer receive the artifact
/// origin frame.
public: const double allowedDistanceFromBase = 21.0;
/// \brief The world name.
public: std::string worldName = "default";
/// \brief Offsets from each artifact's origin to its localization point.
/// The gas artifact has a location point of zero because it is placed at
/// the center point of the entry door threshold at floor level.
///
/// Refer to:
/// https://subtchallenge.com/resources/SubT_Urban_Artifacts_Specification.pdf
public: std::map<subt::ArtifactType, ignition::math::Vector3d>
artifactOffsets =
{
{subt::ArtifactType::TYPE_BACKPACK,
ignition::math::Vector3d(0, -0.12766, 0.25668)},
{subt::ArtifactType::TYPE_DRILL,
ignition::math::Vector3d(0, 0.059073, 0.158863)},
{subt::ArtifactType::TYPE_EXTINGUISHER,
ignition::math::Vector3d(-0.03557, -0.03509, 0.3479)},
{subt::ArtifactType::TYPE_GAS,
ignition::math::Vector3d(0, 0, 0)},
{subt::ArtifactType::TYPE_HELMET,
ignition::math::Vector3d(0, 0, 0.165)},
{subt::ArtifactType::TYPE_PHONE,
ignition::math::Vector3d(0, -0.004, 0.08)},
{subt::ArtifactType::TYPE_RESCUE_RANDY,
ignition::math::Vector3d(-0.071305, 0.021966, 0.39217)},
{subt::ArtifactType::TYPE_ROPE,
ignition::math::Vector3d(0.004, -0.03, 0.095)},
{subt::ArtifactType::TYPE_VENT,
ignition::math::Vector3d(0, 0, 0.138369)},
{subt::ArtifactType::TYPE_CUBE,
ignition::math::Vector3d(0, 0, 0.2)}
};
/// \brief Event manager for pausing simulation
public: EventManager *eventManager;
/// \brief The set of marsupial pairs.
public: std::map<std::string, std::string> marsupialPairs;
/// \brief Models with dead batteries.
public: std::set<std::string> deadBatteries;
/// \brief Map of model name to {sim_time_sec, deployments_over_max}. This
/// map is used to log when no more rock falls are possible for a rock
/// fall model.
public: std::map<std::string, std::pair<int, int>> rockFallsMax;
/// \brief Map of model name to bool. This map is used to log when no more
/// dynamic collapses are possible.
public: std::map<std::string, bool> dynamicCollapseMax;
/// \brief Map of model name to deployments_over_max. This map
/// is used to log when no more breadcrumb deployments are possible.
public: std::map<std::string, int> breadcrumbsMax;
/// \brief The ROS node handler used for communications.
public: std::unique_ptr<ros::NodeHandle> rosnode;
public: ros::Publisher rosStatsPub;
public: ros::Publisher rosStatusPub;
public: ros::Publisher rosArtifactPub;
public: ros::Publisher rosRobotEventPub;
public: ros::Publisher rosRegionEventPub;
public: std::map<std::string, ros::Publisher> rosRobotPosePubs;
public: std::map<std::string, ros::Publisher> rosRobotKinematicPubs;
/// \brief Pointer to the ROS bag recorder.
public: std::unique_ptr<rosbag::Recorder> rosRecorder;
public: std::string prevPhase = "";
/// \brief Counter to create unique id for events
public: int eventCounter = 0;
/// \brief Mutex to protect the eventCounter.
public: std::mutex eventCounterMutex;
/// \brief Kinetic energy information for each robot.
public: std::map<gazebo::Entity, KineticEnergyInfo> keInfo;
// \brief Height used to determine the KE threshold.
// Increasing this value will lower the threshold, meaning a
// less violent collision will disable the robot. This value can be
// adjusted via this plugin's SDF parameters.
public: double keHeight = 0.077;
/// \brief The fog emitters.
public: std::set<std::string> fogEmitters;
};
//////////////////////////////////////////////////
GameLogicPlugin::GameLogicPlugin()
: dataPtr(new GameLogicPluginPrivate)
{
}
//////////////////////////////////////////////////
GameLogicPlugin::~GameLogicPlugin()
{
this->dataPtr->Finish(this->dataPtr->simTime);
if (this->dataPtr->publishThread)
this->dataPtr->publishThread->join();
}
//////////////////////////////////////////////////
void GameLogicPlugin::Configure(const ignition::gazebo::Entity & /*_entity*/,
const std::shared_ptr<const sdf::Element> &_sdf,
ignition::gazebo::EntityComponentManager & /*_ecm*/,
ignition::gazebo::EventManager & _eventMgr)
{
this->dataPtr->eventManager = &_eventMgr;
// Check if the game logic plugin has a <logging> element.
// The <logging> element can contain a <filename_prefix> child element.
// The <filename_prefix> is used to specify the log filename prefix. For
// example:
// <logging>
// <path>/tmp</path>
// <filename_prefix>subt_tunnel_qual</filename_prefix>
// </logging>
const sdf::ElementPtr loggingElem =
const_cast<sdf::Element*>(_sdf.get())->GetElement("logging");
std::string filenamePrefix;
if (loggingElem && loggingElem->HasElement("filename_prefix"))
{
// Get the log filename prefix.
filenamePrefix =
loggingElem->Get<std::string>("filename_prefix", "subt").first;
// Get the logpath from the <path> element, if it exists.
if (loggingElem->HasElement("path"))
{
this->dataPtr->logPath =
loggingElem->Get<std::string>("path", "/dev/null").first;
}
else
{
// Make sure that we can access the HOME environment variable.
char *homePath = getenv("HOME");
if (!homePath)
{
ignerr << "Unable to get HOME environment variable. Report this error "
<< "to https://github.com/osrf/subt/issues/new. "
<< "SubT logging will be disabled.\n";
}
else
{
this->dataPtr->logPath = homePath;
}
}
// Read elevation step size. Elevation data will be discretized and
// rounded down to the nearest multiple of the input step size
// during logging
if (loggingElem->HasElement("elevation_step_size"))
{
this->dataPtr->elevationStepSize =
loggingElem->Get<double>("elevation_step_size",
this->dataPtr->elevationStepSize).first;
}
}
this->dataPtr->keHeight =
_sdf->Get<double>("ke_height", this->dataPtr->keHeight).first;
const sdf::ElementPtr rosElem =
const_cast<sdf::Element*>(_sdf.get())->GetElement("ros");
if (rosElem)
{
std::string value = rosElem->Get<std::string>();
std::transform(value.begin(), value.end(), value.begin(), ::toupper);
if (value == "TRUE" || value == "1")
{
std::map<std::string, std::string> args;
ros::init(args, "subt_stats", ros::init_options::NoSigintHandler);
// Initialize the ROS node.
this->dataPtr->rosnode.reset(new ros::NodeHandle("subt"));
this->dataPtr->rosStatusPub =
this->dataPtr->rosnode->advertise<subt_ros::RunStatus>(
"status", 100, true);
this->dataPtr->rosStatsPub =
this->dataPtr->rosnode->advertise<subt_ros::RunStatistics>(
"run_statistics", 100);
this->dataPtr->rosArtifactPub =
this->dataPtr->rosnode->advertise<subt_ros::ArtifactReport>(
"artifact_reports", 100);
this->dataPtr->rosRobotEventPub =
this->dataPtr->rosnode->advertise<subt_ros::RobotEvent>(
"robot_event", 100);
this->dataPtr->rosRegionEventPub =
this->dataPtr->rosnode->advertise<subt_ros::RegionEvent>(
"region_event", 100);
// Setup a ros bag recorder.
rosbag::RecorderOptions recorderOptions;
recorderOptions.append_date=false;
recorderOptions.prefix = ignition::common::joinPaths(
this->dataPtr->logPath, "cloudsim");
recorderOptions.regex=true;
recorderOptions.topics.push_back("/subt/.*");
// Spawn thread for recording /subt/ data to rosbag.
this->dataPtr->rosRecorder.reset(new rosbag::Recorder(recorderOptions));
this->dataPtr->bagThread.reset(new std::thread([&](){
this->dataPtr->rosRecorder->run();
}));
}
}
// Open the log file.
this->dataPtr->logStream.open(
(this->dataPtr->logPath + "/" + filenamePrefix + "_" +
ignition::common::systemTimeISO() + ".log").c_str(), std::ios::out);
// Open the event log file.
this->dataPtr->eventStream.open(
(this->dataPtr->logPath + "/events.yml").c_str(), std::ios::out);
// Advertise the service to receive artifact reports.
// Note that we're setting the scope to this service to SCOPE_T, so only
// nodes within the same process will be able to reach this plugin.
// The reason for this is to avoid the teams to use this service directly.
ignition::transport::AdvertiseServiceOptions opts;
opts.SetScope(ignition::transport::Scope_t::PROCESS);
this->dataPtr->node.Advertise(kNewArtifactSrv,
&GameLogicPluginPrivate::OnNewArtifact, this->dataPtr.get(), opts);
// Get the duration seconds.
if (_sdf->HasElement("duration_seconds"))
{
this->dataPtr->runDuration = std::chrono::seconds(
_sdf->Get<int>("duration_seconds"));
ignmsg << "Run duration set to " << this->dataPtr->runDuration.count()
<< " seconds.\n";
}
if (_sdf->HasElement("world_name"))
{
this->dataPtr->worldName =
_sdf->Get<std::string>("world_name", "subt").first;
}
else
{
ignerr << "Missing <world_name>, the GameLogicPlugin will assume a "
<< " world name of 'default'. This could lead to incorrect scoring\n";
}
this->dataPtr->node.Advertise("/subt/pose_from_artifact_origin",
&GameLogicPluginPrivate::OnPoseFromArtifact, this->dataPtr.get());
this->dataPtr->node.Advertise("/subt/start",
&GameLogicPluginPrivate::OnStartCall, this->dataPtr.get());
this->dataPtr->node.Advertise("/subt/finish",
&GameLogicPluginPrivate::OnFinishCall, this->dataPtr.get());
this->dataPtr->startPub =
this->dataPtr->node.Advertise<ignition::msgs::StringMsg>("/subt/start");
this->dataPtr->competitionClockPub =
this->dataPtr->node.Advertise<ignition::msgs::Clock>("/subt/run_clock");
this->dataPtr->artifactReportPub =
this->dataPtr->node.Advertise<ignition::msgs::Int32>("/subt/artifact_reports_remaining");
this->dataPtr->robotPub =
this->dataPtr->node.Advertise<ignition::msgs::Param_V>("/subt/robots");
this->dataPtr->publishThread.reset(new std::thread(
&GameLogicPluginPrivate::PublishScore, this->dataPtr.get()));
this->dataPtr->node.Subscribe("/subt_performer_detector",
&GameLogicPluginPrivate::OnEvent, this->dataPtr.get());
ignmsg << "Starting SubT" << std::endl;
// Set the report limit to 25 for final worlds.
this->dataPtr->reportCountLimit =
this->dataPtr->worldName.find("final") != std::string::npos ? 25 :
this->dataPtr->reportCountLimit;
// Make sure that there are score files.
this->dataPtr->UpdateScoreFiles(this->dataPtr->simTime);
}
//////////////////////////////////////////////////
void GameLogicPluginPrivate::OnBatteryMsg(
const ignition::msgs::BatteryState &_msg,
const transport::MessageInfo &_info)
{
ignition::msgs::Time localSimTime(this->simTime);
if (_msg.percentage() <= 0)
{
std::vector<std::string> topicParts = common::split(_info.Topic(), "/");
std::string name = "_unknown_";
// Get the name of the model from the topic name, where the topic name
// look like '/model/{model_name}/detach'.
if (topicParts.size() > 1)
name = topicParts[1];
// Make sure the event is logged once.
if (this->deadBatteries.find(name) == this->deadBatteries.end())
{
this->deadBatteries.emplace(name);
{
std::lock_guard<std::mutex> lock(this->eventCounterMutex);
std::ostringstream stream;
stream
<< "- event:\n"
<< " id: " << this->eventCounter << "\n"
<< " type: dead_battery\n"
<< " time_sec: " << localSimTime.sec() << "\n"
<< " robot: " << name << std::endl;
this->LogEvent(stream.str());
this->PublishRobotEvent(localSimTime, "dead_battery", name,
this->eventCounter);
this->eventCounter++;
}
}
}
}
//////////////////////////////////////////////////
void GameLogicPluginPrivate::OnBreadcrumbDeployEvent(
const ignition::msgs::Empty &/*_msg*/,
const transport::MessageInfo &_info)
{
ignition::msgs::Time localSimTime(this->simTime);
std::vector<std::string> topicParts = common::split(_info.Topic(), "/");
std::string name = "_unknown_";
// Get the name of the model from the topic name, where the topic name
// look like '/model/{model_name}/deploy'.
if (topicParts.size() > 1)
name = topicParts[1];
{
std::lock_guard<std::mutex> lock(this->eventCounterMutex);
std::ostringstream stream;
stream
<< "- event:\n"
<< " id: " << this->eventCounter << "\n"
<< " type: breadcrumb_deploy\n"
<< " time_sec: " << localSimTime.sec() << "\n"
<< " robot: " << name << std::endl;
this->LogEvent(stream.str());
// Only publish if max breadcrumbs has not been reached.
if (this->breadcrumbsMax.find(name) == this->breadcrumbsMax.end() ||
this->breadcrumbsMax[name] <= 0)
{
this->PublishRobotEvent(localSimTime, "breadcrumb_deploy", name,
this->eventCounter);
}
this->eventCounter++;
}
}
//////////////////////////////////////////////////
void GameLogicPluginPrivate::OnBreadcrumbDeployRemainingEvent(
const ignition::msgs::Int32 &_msg,
const transport::MessageInfo &_info)
{
ignition::msgs::Time localSimTime(this->simTime);
if (_msg.data() == 0)
{
std::vector<std::string> topicParts = common::split(_info.Topic(), "/");
std::string name = "_unknown_";
// Get the name of the model from the topic name, where the topic name
// look like '/model/{model_name}/deploy'.
if (topicParts.size() > 1)
name = topicParts[1];
if (this->breadcrumbsMax[name] > 0)
{
std::lock_guard<std::mutex> lock(this->eventCounterMutex);
std::ostringstream stream;
stream
<< "- event:\n"
<< " id: " << this->eventCounter++ << "\n"
<< " type: max_breadcrumb_deploy\n"
<< " time_sec: " << localSimTime.sec() << "\n"
<< " robot: " << name << std::endl;
this->LogEvent(stream.str());
// Do not publish if max breadcrumbs have already been deployed
// if (this->breadcrumbsMax[name] == 1)
// this->PublishRobotEvent(localSimTime, "max_breadcrumb_deploy", name);
}
this->breadcrumbsMax[name]++;
}
}
//////////////////////////////////////////////////
void GameLogicPluginPrivate::OnDynamicCollapseDeployRemainingEvent(
const ignition::msgs::Int32 &/*_msg*/,
const transport::MessageInfo &_info)
{
ignition::msgs::Time localSimTime(this->simTime);
std::vector<std::string> topicParts = common::split(_info.Topic(), "/");
std::string name = "_unknown_";
// Get the name of the model from the topic name, where the topic name
// look like '/model/{model_name}/deploy'.
if (topicParts.size() > 1)
name = topicParts[1];
if (!this->dynamicCollapseMax[name])
{
std::lock_guard<std::mutex> lock(this->eventCounterMutex);
std::ostringstream stream;
stream
<< "- event:\n"
<< " id: " << this->eventCounter << "\n"
<< " type: dynamic_collapse\n"
<< " time_sec: " << localSimTime.sec() << "\n"
<< " model: " << name << std::endl;
this->LogEvent(stream.str());
this->PublishRegionEvent(localSimTime, "dynamic_collapse", "", name,
"dynamic_collapse", this->eventCounter);
this->eventCounter++;
this->dynamicCollapseMax[name] = true;
}
}
//////////////////////////////////////////////////
void GameLogicPluginPrivate::OnFogCmdEvent(
const ignition::msgs::ParticleEmitter &_msg,
const transport::MessageInfo &_info)
{
ignition::msgs::Time localSimTime(this->simTime);
std::vector<std::string> topicParts = common::split(_info.Topic(), "/");
std::string name = "_unknown_";
// Get the name of the model from the topic name, where the topic name
// look like '/model/{model_name}/...
if (topicParts.size() > 1)
name = topicParts[1];
if (_msg.has_emitting() && _msg.emitting().data())
{
std::lock_guard<std::mutex> lock(this->eventCounterMutex);
std::ostringstream stream;
stream
<< "- event:\n"
<< " id: " << this->eventCounter << "\n"
<< " type: fog\n"
<< " time_sec: " << localSimTime.sec() << "\n"
<< " model: " << name << std::endl;
this->LogEvent(stream.str());
this->PublishRegionEvent(localSimTime, "fog", "", name, "fog",
this->eventCounter);
this->eventCounter++;
}
}
//////////////////////////////////////////////////
void GameLogicPluginPrivate::OnRockFallDeployRemainingEvent(
const ignition::msgs::Int32 &_msg,
const transport::MessageInfo &_info)
{
ignition::msgs::Time localSimTime(this->simTime);
std::vector<std::string> topicParts = common::split(_info.Topic(), "/");
std::string name = "_unknown_";
// Get the name of the model from the topic name, where the topic name
// look like '/model/{model_name}/deploy'.
if (topicParts.size() > 1)
name = topicParts[1];
if (_msg.data() == 0)
{
// Sim time is used to make sure that we report only once per rock fall,
// and not once for every rock in the rock fall.
if (this->rockFallsMax[name].first != localSimTime.sec())
{
if (this->rockFallsMax[name].second == 1)
{
std::lock_guard<std::mutex> lock(this->eventCounterMutex);
std::ostringstream stream;
stream
<< "- event:\n"
<< " id: " << this->eventCounter++ << "\n"
<< " type: max_rock_falls\n"
<< " time_sec: " << localSimTime.sec() << "\n"
<< " model: " << name << std::endl;
this->LogEvent(stream.str());
// Don't publish this event.
// this->PublishRegionEvent(localSimTime, "max_rock_falls", "n/a", name,
// "max_rock_falls");
}
else if (this->rockFallsMax[name].second == 0)
{
std::lock_guard<std::mutex> lock(this->eventCounterMutex);