Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
1977 lines (1832 loc) · 107 KB
/
Copy pathmain.cpp
File metadata and controls
1977 lines (1832 loc) · 107 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
// MPI SynChrono lunar construction demo: one rank per site sector, each running a
// Polaris-based collector that harvests rocks and a tracked builder that lays them
// into a wall. Deliberately named for the task and not for the vehicle or the
// terrain model, both of which have changed under it more than once.
// Rank 0 is the global sensor/visualization rank. Robot physics starts on rank 1.
#include <mpi.h>
#include <chrono>
#include <algorithm>
#include <array>
#include <cmath>
#include <ctime>
#include <filesystem>
#include <limits>
#include <memory>
#include <random>
#include <sstream>
#include <string>
#include <vector>
#include "chrono/ChConfig.h"
#include "chrono/assets/ChVisualShapeBox.h"
#include "chrono/assets/ChVisualShapeTriangleMesh.h"
#include "chrono/core/ChRealtimeStep.h"
#include "chrono/core/ChDataPath.h"
#include "chrono/core/ChTypes.h"
#include "chrono/physics/ChBody.h"
#include "chrono/physics/ChContactMaterial.h"
#include "chrono/physics/ChSystemSMC.h"
#include "chrono/solver/ChSolverAPGD.h"
#include "chrono/solver/ChSolverBB.h"
#include "chrono/timestepper/ChTimestepper.h"
#include "chrono_vehicle/ChVehicleDataPath.h"
#include <unordered_set>
#include "chrono_vehicle/terrain/SCMTerrain.h"
#include "chrono_vehicle/tracked_vehicle/ChTrackAssembly.h"
#include "chrono_vehicle/tracked_vehicle/ChTrackShoe.h"
#include "chrono_vehicle/tracked_vehicle/ChTrackedVehicle.h"
#include "chrono_vehicle/wheeled_vehicle/ChWheeledVehicleVisualSystemVSG.h"
#include "chrono_sensor/ChSensorManager.h"
#include "chrono_sensor/filters/ChFilterSave.h"
#include "chrono_sensor/filters/ChFilterVisualize.h"
#include "chrono_sensor/sensors/ChCameraSensor.h"
#include "chrono_synchrono/SynChronoManager.h"
#include "chrono_synchrono/agent/SynEnvironmentAgent.h"
#include "chrono_synchrono/agent/SynTrackedVehicleAgent.h"
#include "chrono_synchrono/agent/SynWheeledVehicleAgent.h"
#include "chrono_synchrono/communication/mpi/SynMPICommunicator.h"
#include "chrono_synchrono/utils/SynLog.h"
#include "chrono_thirdparty/cxxopts/ChCLI.h"
#include "src/BuilderRig.h"
#include "src/LrvArm.h"
#include "src/MaterialUtils.h"
#include "src/RockField.h"
#include "src/ScmRecorder.h"
#include "src/RobotLayout.h"
#include "src/RobotRig.h"
#include "src/SynAgents.h"
#include "src/TrackSoilMesh.h"
#include "src/TrajectoryRecorder.h"
using namespace chrono;
using namespace chrono::sensor;
using namespace chrono::synchrono;
using namespace chrono::vehicle;
using namespace amd_uw;
namespace {
// Simulation defaults shared by all MPI ranks.
const ChContactMethod contact_method = ChContactMethod::SMC;
// SMC penalty contact integrates stiff normal forces, so it needs a finer step
// than NSC (which used 2e-3 / 1e-3). Mirrors the Python demo's 5e-4 SMC step.
double step_size = 5e-4;
double tire_step_size = 2.5e-4;
double end_time = 1000.0;
double heartbeat = 1e-2;
double render_step_size = 1.0 / 50.0;
double settle_time = 1.0;
double motion_log_rate = 0.0;
// Sim-time period of the rank-local performance probe (0 disables it).
double perf_log_period = 0.0;
// Pose-capture rate for --record_dir. 60 Hz because the output is meant to be re-rendered
// as animation; anything below the target frame rate has to be interpolated, and rocks
// tipping out of a bed do not interpolate well.
double record_rate_hz = 60.0;
// Deformed-ground capture rate. Far below record_rate_hz on purpose: the SCM file carries
// only nodes whose height CHANGED since the previous sample, so a higher rate refines when
// a rut appeared, never whether it appeared.
double scm_record_rate_hz = 10.0;
// How often the SCM file re-states every deformed node instead of only the changes. Heights
// are absolute and consumers accumulate by overwrite, so a keyframe is idempotent with the
// diffs around it; it just lets a consumer seek or survive a dropped frame.
//
// THIS, NOT scm_record_rate_hz, IS WHAT THE FILE SIZE IS MADE OF. Each keyframe re-states
// every node touched since t=0, so the file grows with the SQUARE of run length. Measured on
// rank 12 of a 1500 s 15-robot run: 300 keyframes carried 666.4 M of 670.5 M node rows (99.4%)
// against 4.0 M rows for all 1200 delta frames. Turning the sample rate down shrinks the 0.6%.
// At 5 s this projected ~520 GiB site-wide for a 6000 s run; 60 s costs a twelfth of that.
const double scm_keyframe_period = 60.0;
const double terrain_resolution_scale = 4.0;
const double terrain_pixels_x = 256.0;
const double terrain_pixels_y = 256.0;
// Graded work pad, from tools/make_graded_pad.py. Ungraded, terrain2.bmp puts the site rings
// on a 5% hillside: the builder orbit swung 3.96 m at a 17% peak along-path grade, more than
// the single-pin tracks want to climb under load. Graded it swings 0.57 m at ~2%.
//
// Must be 16-bit PNG, not BMP: 8 bits quantizes this 50 m range into 0.196 m steps, which
// would terrace the flat pad into 20 cm stairs. Set to "terrain/terrain2.bmp" for the
// ungraded site.
const std::string terrain_heightmap_file = "terrain/terrain2_graded.png";
const double terrain_height_offset = 0.0;
const double terrain_min_height = -25.0;
const double terrain_max_height = 25.0;
const double terrain_height_probe_clearance = 10.0;
// SCM grid spacing over the whole 1024 x 1024 m patch. Read the cost before changing it.
// At 0.10 m that is 10241^2 = 104.9 M nodes, whose undeformed heights SCMLoader holds in ONE
// DENSE double matrix: 839 MB per rank, allocated whether or not a node is touched. Memory
// scales as 1/delta^2.
//
// The visualization mesh (~13.5 GB per rank at this delta) is what does not fit, so it is
// built only on ranks that render -- see scm_visualization_mesh. A headless rank pays the
// 839 MB and nothing more.
const double terrain_scm_delta_default = 0.10;
// Bekker-Wong soil parameters for the lunar regolith analogue, carried over from the
// earlier SCM branch. elastic_K must exceed Bekker_Kphi or SCM's yield test never
// engages, so the two move together.
const double scm_bekker_kphi = 2.8e6; // frictional modulus [Pa/m^n]
const double scm_bekker_kc = 14e3; // cohesive modulus [Pa/m^(n-1)]
const double scm_bekker_n = 1.0; // sinkage exponent
const double scm_mohr_cohesion = 1000.0; // cohesion for shear failure [Pa]
const double scm_mohr_friction = 35.0; // friction angle for shear failure [deg]
const double scm_janosi_shear = 0.02; // Janosi-Hanamoto shear parameter [m]
const double scm_elastic_k = 2e8; // elastic stiffness [Pa/m]
const double scm_damping_r = 3e4; // vertical damping [Pa.s/m]
// NOT const: --rock_first_distance / --rock_distance_step override the line geometry so
// a harvest cycle can be exercised in a fraction of the sim time. Defaults are unchanged.
RockFieldConfig rock_field_config;
const float global_camera_update_rate = 30.0f;
// 1080p. Same 16:9 aspect as the previous 1280x720, so the framing is unchanged and only
// the pixel count moves -- 0.92 Mpx to 2.07 Mpx, so budget ~2.25x the OptiX render cost
// on the sensor rank. That rank shares the SynChrono heartbeat with every robot rank, so
// if it becomes the pacing rank the whole job slows; global_camera_update_rate is the
// knob for that (24 Hz is still fine for video).
const unsigned int global_camera_width = 1920;
const unsigned int global_camera_height = 1080;
const float global_camera_fov = static_cast<float>(CH_PI_3);
const ChVector3d global_camera_position(-100.0, 30.0, 30.0);
const ChVector3d global_camera_target(30.0, 0.0, 5.0);
const char* sensor_star_map = "sensor/textures/starmap_2020_4k.hdr";
// Provisional lift of the chassis reference above the probed terrain surface.
// This only needs to be large enough that no wheel of the tractor or trailer
// starts buried in the terrain; the rig is then re-seated precisely (see
// seat_clearance) so the actual drop height no longer matters.
const double vehicle_start_clearance = 1.50;
// Final gap left between the LOWEST wheel of the whole rig (a trailer wheel)
// and the terrain after re-seating. Small enough that the touchdown is an
// effectively zero-velocity settle -- no impact, so even rigid tires on the
// light trailer don't bounce.
const double seat_clearance = 0.025;
const double builder_ride_height = 0.7;
// Sim time for which the builder holds full brake and ignores every ROS command, so its
// single-pin track settles onto the terrain before a controller can move it.
const double builder_settle_time = 1.5;
// Site geometry (centre, work circle, builder orbit, collector ring) lives in
// src/RobotLayout.h so the placement of every rank's builder and collector comes
// from one source.
// Physics ranks register rover, trailer, rocks, tracked builder, arm, then trailer
// bed -- in that order. SynChronoManager::AddAgent hands out agent ids sequentially
// from 1 in call order, so these constants must match the AddAgent sequence below,
// and every AddZombie must use the same id as the agent it shadows.
const int trailer_agent_id = 2;
const int rock_agent_id = 3;
const int tracked_builder_agent_id = 4;
const int builder_arm_agent_id = 5;
const int trailer_bed_agent_id = 6;
const int rover_arm_agent_id = 7;
// Highest id a robot rank hands out -- ranks that draw no zombies register one inert
// placeholder per remote agent, so this must cover every AddAgent below.
const int last_agent_id = rover_arm_agent_id;
// Mesh directory and geometry scale per manipulator; the sensor rank must rebuild
// each arm exactly as its owning rank did.
const char* const builder_arm_shapes_dir = "m113_builder_arm/m113_builder_arm_shapes/";
const char* const rover_arm_shapes_dir = "lrv_robotarm/lrv_arm_shapes/";
const double builder_arm_geometry_scale = 2.0;
const double rover_arm_geometry_scale = 1.0;
ChVector3d track_point(0.0, 0.0, 1.0);
ChQuaternion<> SensorLookAtRotation(const ChVector3d& camera_pos, const ChVector3d& target_pos) {
const ChVector3d forward = (target_pos - camera_pos).GetNormalized();
ChMatrix33<> rot;
rot.SetFromAxisX(forward, VECT_Y);
return rot.GetQuaternion();
}
// Seat the builder on a FITTED TERRAIN PLANE rather than a single height probe.
//
// The ground under the builder's 5.4 x 2.7 m footprint tilts 2.4-9.5 degrees depending on
// lane position, so a level hull seated off one centre probe is out by 0.23-0.82 m across the
// footprint -- shoes buried at the high end, in the air at the low end. Under SMC a buried
// shoe is a penalty force with nowhere to go (the same trap the pinned hull hits, see
// BuilderRig's constructor). Fitting a plane and matching pitch and roll cuts worst-case
// seating error to 0.019-0.077 m at every radius.
//
// Those figures are for the ungraded map. On terrain2_graded.png the pad holds the lane to
// 1.1 deg of tilt and 0.102 m of level-hull error, so the fit is mostly insurance now -- it
// earns its keep again the moment the heightmap constant points back at terrain2.bmp.
struct BuilderSeating {
ChCoordsys<> pose;
double level_error; // worst seating error the old single-probe placement would give
double plane_error; // worst residual about the fitted plane
double tilt_deg;
double lift;
};
BuilderSeating SeatBuilderOnTerrainPlane(ChTerrain& terrain,
double center_x,
double center_y,
double yaw,
double ride_height,
double height_probe_z) {
// Hull footprint in the chassis frame, from Chassis.obj. Note it is NOT centred on
// the chassis reference (-4.903 .. +0.498), which is why the plane fit below has to
// centre on the sample centroid rather than on the builder's own origin.
constexpr double hull_x_min = -4.903;
constexpr double hull_x_max = 0.498;
constexpr double hull_y_half = 1.343;
constexpr int nx = 9;
constexpr int ny = 5;
const double cos_yaw = std::cos(yaw);
const double sin_yaw = std::sin(yaw);
std::vector<ChVector3d> samples;
samples.reserve(nx * ny);
for (int i = 0; i < nx; ++i) {
const double lx = hull_x_min + (hull_x_max - hull_x_min) * i / (nx - 1.0);
for (int j = 0; j < ny; ++j) {
const double ly = -hull_y_half + 2.0 * hull_y_half * j / (ny - 1.0);
const double wx = center_x + lx * cos_yaw - ly * sin_yaw;
const double wy = center_y + lx * sin_yaw + ly * cos_yaw;
samples.emplace_back(wx, wy, terrain.GetHeight(ChVector3d(wx, wy, height_probe_z)));
}
}
const double n = static_cast<double>(samples.size());
double mean_x = 0.0, mean_y = 0.0, mean_z = 0.0;
for (const auto& s : samples) {
mean_x += s.x();
mean_y += s.y();
mean_z += s.z();
}
mean_x /= n;
mean_y /= n;
mean_z /= n;
double sxx = 0.0, sxy = 0.0, syy = 0.0, sxz = 0.0, syz = 0.0;
for (const auto& s : samples) {
const double ex = s.x() - mean_x, ey = s.y() - mean_y, ez = s.z() - mean_z;
sxx += ex * ex;
sxy += ex * ey;
syy += ey * ey;
sxz += ex * ez;
syz += ey * ez;
}
const double det = sxx * syy - sxy * sxy;
double slope_x = 0.0, slope_y = 0.0;
if (std::abs(det) > 1e-12) {
slope_x = (syy * sxz - sxy * syz) / det;
slope_y = (sxx * syz - sxy * sxz) / det;
}
const auto plane_z = [&](double x, double y) {
return mean_z + slope_x * (x - mean_x) + slope_y * (y - mean_y);
};
const double center_probe = terrain.GetHeight(ChVector3d(center_x, center_y, height_probe_z));
double level_error = 0.0, plane_error = 0.0, max_residual = 0.0;
for (const auto& s : samples) {
level_error = std::max(level_error, std::abs(s.z() - center_probe));
const double residual = s.z() - plane_z(s.x(), s.y());
plane_error = std::max(plane_error, std::abs(residual));
max_residual = std::max(max_residual, residual);
}
// Local Z on the plane normal, yaw preserved: SetFromAxisZ orthogonalises the
// suggested X against the normal, so the tangential heading survives the tilt.
ChMatrix33<> rot;
rot.SetFromAxisZ(ChVector3d(-slope_x, -slope_y, 1.0).GetNormalized(),
ChVector3d(cos_yaw, sin_yaw, 0.0));
BuilderSeating seating;
// Lift by the largest bump above the fitted plane so the highest sample only just
// touches, instead of starting inside a track shoe.
seating.pose = ChCoordsys<>(
ChVector3d(center_x, center_y, plane_z(center_x, center_y) + ride_height + max_residual),
rot.GetQuaternion());
seating.level_error = level_error;
seating.plane_error = plane_error;
seating.tilt_deg = std::atan(std::hypot(slope_x, slope_y)) * CH_RAD_TO_DEG;
seating.lift = max_residual;
return seating;
}
void AddOrbitVisualRing(ChSystem* system,
ChTerrain& terrain,
double center_x,
double center_y,
double radius,
double height_probe_z,
const ChColor& color,
const std::string& name) {
constexpr int segments = 180;
constexpr double width = 0.12;
constexpr double thickness = 0.04;
constexpr double surface_offset = 0.08;
const double segment_angle = CH_2PI / static_cast<double>(segments);
const double segment_length =
2.0 * radius * std::sin(0.5 * segment_angle) * 1.02;
auto ring = chrono_types::make_shared<ChBody>();
// Radius is appended rather than baked into the caller's literal: the previous
// names said 30m/40m/50m for rings that were actually at 30/35/40.
ring->SetName(name + "_" + std::to_string(std::lround(radius)) + "m");
ring->SetFixed(true);
ring->EnableCollision(false);
for (int segment = 0; segment < segments; ++segment) {
const double angle = (segment + 0.5) * segment_angle;
const double x = center_x + radius * std::cos(angle);
const double y = center_y + radius * std::sin(angle);
const double z =
terrain.GetHeight(ChVector3d(x, y, height_probe_z)) +
surface_offset;
auto shape = chrono_types::make_shared<ChVisualShapeBox>(
segment_length, width, thickness);
shape->SetColor(color);
ring->AddVisualShape(
shape,
ChFramed(
ChVector3d(x, y, z),
QuatFromAngleZ(angle + 0.5 * CH_PI)));
}
system->AddBody(ring);
}
// A 10 x 10 m pad at the site centre, as four 5 x 5 m tiles. Visual only: fixed,
// collision-free, terrain untouched -- a marker, not a surface to drive on.
void AddCenterPad(ChSystem* system, ChTerrain& terrain, double height_probe_z) {
constexpr double tile = 5.0; // one tile edge; four of them make 10 x 10
constexpr double pad_thickness = 0.06;
constexpr double surface_offset = 0.06;
// Two dark greys in a checker, so this reads as four tiles and doubles as a 5 m
// scale reference. Values look darker than they render: diffuse colour is linear
// and the image is gamma-encoded, so 0.16 comes out ~100/255, the same as this
// terrain. 0.03 measures ~45/255.
const ChColor tile_dark(0.030f, 0.030f, 0.034f);
const ChColor tile_light(0.055f, 0.055f, 0.060f);
auto pad = chrono_types::make_shared<ChBody>();
pad->SetName("center_pad_10x10");
pad->SetFixed(true);
pad->EnableCollision(false);
// Highest terrain sample under the footprint: a flat slab on slope must clip one
// edge or float at the other, and burying it hides the pad itself.
double pad_z = -std::numeric_limits<double>::infinity();
for (int ix = -2; ix <= 2; ++ix) {
for (int iy = -2; iy <= 2; ++iy) {
const double x = site_center_x + 0.25 * ix * 2.0 * tile;
const double y = site_center_y + 0.25 * iy * 2.0 * tile;
pad_z = std::max(pad_z, terrain.GetHeight(ChVector3d(x, y, height_probe_z)));
}
}
pad_z += surface_offset;
for (int ix = 0; ix < 2; ++ix) {
for (int iy = 0; iy < 2; ++iy) {
const double cx = site_center_x + (ix == 0 ? -0.5 : 0.5) * tile;
const double cy = site_center_y + (iy == 0 ? -0.5 : 0.5) * tile;
auto shape = chrono_types::make_shared<ChVisualShapeBox>(tile, tile, pad_thickness);
shape->SetColor(((ix + iy) % 2 == 0) ? tile_dark : tile_light);
pad->AddVisualShape(shape, ChFramed(ChVector3d(cx, cy, pad_z), QUNIT));
}
}
system->AddBody(pad);
}
// Scenery rock clumps inside each rank's builder reach, so a work area reads as a real site.
//
// VISUAL ONLY: everything goes on ONE fixed, collision-disabled body per rank (as AddCenterPad
// does), so a few hundred rocks cost render time and nothing in the solver.
//
// Placed by the ARM's reach -- 3.0-4.2 m from the arm base, fanned about the outward radial.
// That puts them outboard of the hull, clear of the tracks (builder_path_radius +/- 1.343 m),
// and off the collector's radial approach, since the arm base already sits 2.5 m off the ray.
//
// Every rank builds every rank's clumps, like the rings, because the sensor rank must see them
// all; placement is seeded per rank so each rank's VSG agrees with the global camera.
void AddSpawnRockClumps(ChSystem* system,
ChTerrain& terrain,
const std::string& chrono_data_path,
int num_robots,
double height_probe_z) {
if (num_robots <= 0)
return;
// These are SCENERY -- background rubble, not feedstock. The rocks the builder
// actually picks up are real bodies laid out by AddBuilderPileRocks, in heaps on the
// outward radial at 36.6 m.
//
// Which is why this fan is now offset CLOCKWISE instead of centred on that radial.
// Centred, it put decorative clumps within 1.3 m of the first working heap -- closer
// than the sum of their spreads, so the two interpenetrated. The builder starts at
// slot 0 and works counter-clockwise, so everything clockwise of its ray is ground it
// never occupies; putting the rubble there keeps it out of both the heap line and the
// lane while still reading as debris beside the machine.
constexpr double reach_min = 3.4;
constexpr double reach_max = 5.0;
constexpr double arm_base_offset = -2.5; // along the builder hull, from RobotLayout
constexpr double fan_center = -55.0 * CH_DEG_TO_RAD;
constexpr double fan_half_angle = 25.0 * CH_DEG_TO_RAD;
constexpr int pyramid_clumps = 2;
constexpr int cluster_clumps = 4;
constexpr double cluster_spread = 0.9;
// Three Curiosity rocks at three sizes, indexed [size][variant]. LoadRockMesh bakes the
// scale into the mesh and drops its base to z=0, so a shape placed at terrain height
// rests on the ground. Sizes are picked explicitly -- large on the bottom layer of a
// pyramid, small on top -- which is why this is a 2D table and not one flat list.
const std::array<std::string, 3> files = {
chrono_data_path + "robot/curiosity/rocks/rock1.obj",
chrono_data_path + "robot/curiosity/rocks/rock2.obj",
chrono_data_path + "robot/curiosity/rocks/rock3.obj",
};
const std::array<double, 3> scales = {0.12, 0.20, 0.30}; // small, medium, large
struct RockShape {
std::shared_ptr<ChVisualShapeTriangleMesh> shape;
double top = 0.0; // scaled height, for stacking one layer on the next
double radius = 0.0; // scaled horizontal half-extent, for nesting within a layer
};
auto rock_material = CreateLunarHapkeMaterial();
std::array<std::vector<RockShape>, 3> by_size;
for (size_t s = 0; s < scales.size(); ++s) {
for (const auto& file : files) {
auto mesh = LoadRockMesh(file, true, scales[s]);
if (!mesh)
continue;
RockShape entry;
for (const auto& v : mesh->GetCoordsVertices()) {
entry.top = std::max(entry.top, v.z());
entry.radius = std::max(entry.radius, std::hypot(v.x(), v.y()));
}
entry.shape = chrono_types::make_shared<ChVisualShapeTriangleMesh>();
entry.shape->SetMesh(mesh);
entry.shape->SetBackfaceCull(true);
entry.shape->SetMutable(false);
entry.shape->AddMaterial(rock_material);
by_size[s].push_back(entry);
}
}
if (by_size[0].empty() || by_size[1].empty() || by_size[2].empty())
return;
auto scenery = chrono_types::make_shared<ChBody>();
scenery->SetName("builder_reach_rock_clumps");
scenery->SetFixed(true);
scenery->EnableCollision(false);
int placed = 0;
for (int robot_index = 0; robot_index < num_robots; ++robot_index) {
// Same seed on every rank, different per rank.
std::mt19937 rng(90210u + 7919u * static_cast<unsigned>(robot_index));
std::uniform_real_distribution<double> unit(-1.0, 1.0);
std::uniform_real_distribution<double> yaw(-CH_PI, CH_PI);
std::uniform_real_distribution<double> reach(reach_min, reach_max);
std::uniform_real_distribution<double> fan(-fan_half_angle, fan_half_angle);
std::uniform_int_distribution<int> base_layer_count(3, 4);
std::uniform_int_distribution<int> mid_layer_count(2, 3);
std::uniform_int_distribution<int> cluster_count(7, 9);
const double ray = RankRayAngleRad(robot_index, num_robots);
const ChVector3d outward(std::cos(ray), std::sin(ray), 0.0);
// The builder parks tangent to its lane; its hull +X is the tangential direction.
const double hull_heading = BuilderOrbitHeadingRad(robot_index, num_robots);
const ChVector3d hull_axis(std::cos(hull_heading), std::sin(hull_heading), 0.0);
const ChVector3d arm_base =
BuilderOrbitGroundPosition(robot_index, num_robots) + hull_axis * arm_base_offset;
auto pick = [&](int size) -> const RockShape& {
std::uniform_int_distribution<int> v(0, static_cast<int>(by_size[size].size()) - 1);
return by_size[size][v(rng)];
};
auto place = [&](const RockShape& r, const ChVector3d& xy, double z) {
scenery->AddVisualShape(r.shape,
ChFramed(ChVector3d(xy.x(), xy.y(), z), QuatFromAngleZ(yaw(rng))));
++placed;
};
// Clump centre: fanned clockwise of the outward radial, clear of the working heaps.
auto clump_center = [&]() {
const double angle = ray + fan_center + fan(rng);
return arm_base + ChVector3d(std::cos(angle), std::sin(angle), 0.0) * reach(rng);
};
for (int clump = 0; clump < pyramid_clumps; ++clump) {
const ChVector3d center = clump_center();
const double ground = terrain.GetHeight(ChVector3d(center.x(), center.y(), height_probe_z));
// Bottom layer: several LARGE rocks in a ring, spaced so neighbours just touch.
const int n_base = base_layer_count(rng);
double base_top = 0.0;
double base_radius = 0.0;
for (int i = 0; i < n_base; ++i) {
const RockShape& r = pick(2);
// Ring radius that makes n_base rocks of this size sit shoulder to shoulder.
const double ring = (n_base > 1) ? r.radius / std::sin(CH_PI / n_base) : 0.0;
const double a = CH_2PI * i / n_base + 0.3 * unit(rng);
place(r, center + ChVector3d(std::cos(a), std::sin(a), 0.0) * ring, ground);
base_top = std::max(base_top, r.top);
base_radius = std::max(base_radius, ring);
}
// Middle layer: MEDIUM rocks nested into the hollows of the layer below, so they
// sit at 70% of its height rather than perched on top of it.
const int n_mid = mid_layer_count(rng);
double mid_top = 0.0;
const double mid_z = ground + 0.70 * base_top;
for (int i = 0; i < n_mid; ++i) {
const RockShape& r = pick(1);
const double ring = 0.45 * base_radius;
const double a = CH_2PI * i / n_mid + CH_PI / n_mid + 0.3 * unit(rng);
place(r, center + ChVector3d(std::cos(a), std::sin(a), 0.0) * ring, mid_z);
mid_top = std::max(mid_top, r.top);
}
// Capstone: one SMALL rock.
place(pick(0), center + ChVector3d(0.12 * unit(rng), 0.12 * unit(rng), 0.0),
mid_z + 0.70 * mid_top);
}
for (int clump = 0; clump < cluster_clumps; ++clump) {
const ChVector3d center = clump_center();
const int n = cluster_count(rng);
for (int i = 0; i < n; ++i) {
// Mixed sizes lying about, each settled a little into the regolith.
std::uniform_int_distribution<int> size(0, 2);
const RockShape& r = pick(size(rng));
const ChVector3d xy =
center + ChVector3d(cluster_spread * unit(rng), cluster_spread * unit(rng), 0.0);
const double ground = terrain.GetHeight(ChVector3d(xy.x(), xy.y(), height_probe_z));
place(r, xy, ground - 0.15 * r.top);
}
}
}
system->AddBody(scenery);
SynLog() << "Builder-reach rock clumps: " << placed << " rocks on 1 fixed collision-free body ("
<< pyramid_clumps << " pyramids + " << cluster_clumps << " clusters x " << num_robots
<< " ranks).\n";
}
// Rocks already LAID on the work circle behind each builder -- the start of the wall it
// is building, so the site reads as work in progress rather than untouched ground.
//
// Deliberately not scattered: these are placed, so they sit exactly on
// work_circle_radius, evenly spaced by their own width, yaw aligned to the circle's
// tangent. That reads as deliberate construction; jitter would make it look like spill.
//
// "Behind" means clockwise of the rank's ray, because builders orbit counter-clockwise --
// so the laid section trails the machine that laid it.
//
// Visual only, on the same fixed collision-free body rationale as the clumps.
void AddPlacedWallRocks(ChSystem* system,
ChTerrain& terrain,
const std::string& chrono_data_path,
int num_robots,
double height_probe_z) {
if (num_robots <= 0)
return;
constexpr int rocks_per_rank = 5;
// Scale and pitch BOTH match the rocks the builder actually lays (rock_field_config's
// mesh_scale, wall_slot_pitch_rad), because these are the same course. The builder
// starts laying at slot 0 -- exactly on the rank's ray -- and works counter-clockwise
// from there; this is the section already behind it. At the old 0.30 scale and its own
// independent spacing, the decoration's leading stone sat 0.48 m from slot 0 and the
// first rock the builder laid landed on top of it.
const double wall_rock_scale = rock_field_config.mesh_scale;
auto material = CreateLunarHapkeMaterial();
const std::array<std::string, 3> files = {
chrono_data_path + "robot/curiosity/rocks/rock1.obj",
chrono_data_path + "robot/curiosity/rocks/rock2.obj",
chrono_data_path + "robot/curiosity/rocks/rock3.obj",
};
std::vector<std::shared_ptr<ChVisualShapeTriangleMesh>> shapes;
for (const auto& file : files) {
auto mesh = LoadRockMesh(file, true, wall_rock_scale);
if (!mesh)
continue;
auto shape = chrono_types::make_shared<ChVisualShapeTriangleMesh>();
shape->SetMesh(mesh);
shape->SetBackfaceCull(true);
shape->SetMutable(false);
shape->AddMaterial(material);
shapes.push_back(shape);
}
if (shapes.empty())
return;
auto wall = chrono_types::make_shared<ChBody>();
wall->SetName("work_circle_placed_rocks");
wall->SetFixed(true);
wall->EnableCollision(false);
int placed = 0;
for (int robot_index = 0; robot_index < num_robots; ++robot_index) {
const double ray = RankRayAngleRad(robot_index, num_robots);
for (int i = 0; i < rocks_per_rank; ++i) {
// Trailing the ray: i = 0 is the stone immediately before slot 0, running
// clockwise from there, one full pitch clear of the builder's first slot.
const double angle = ray - (i + 1) * wall_slot_pitch_rad;
const double x = site_center_x + work_circle_radius * std::cos(angle);
const double y = site_center_y + work_circle_radius * std::sin(angle);
const double z = terrain.GetHeight(ChVector3d(x, y, height_probe_z));
// Yaw follows the tangent so the course curves with the circle. Alternating
// meshes keeps five identical stones from looking cloned.
const auto& shape = shapes[(robot_index + i) % shapes.size()];
wall->AddVisualShape(shape, ChFramed(ChVector3d(x, y, z),
QuatFromAngleZ(angle + CH_PI_2)));
++placed;
}
}
system->AddBody(wall);
SynLog() << "Work-circle placed rocks: " << placed << " on 1 fixed collision-free body ("
<< rocks_per_rank << " per rank x " << num_robots << " ranks, r=" << work_circle_radius
<< " m).\n";
}
// No rigid extension strips here, unlike the RigidTerrain build this replaced.
// SCM's patch extends to infinity in the x-y plane -- outside the initialized area a
// node takes the height of the nearest initialized one -- so the rock lines run off the
// heightmap onto flat ground of the right elevation with nothing to stitch. At the
// current 1024 m patch it was a no-op anyway: the furthest rock on a six-rock line sits
// ~207 m from the centre, well inside the 512 m half-extent.
// Rank-local performance probe.
//
// Two things make the naive measurement useless here. First, the demo only
// printed a *cumulative* wall/sim average, which smears the moment a cost starts
// growing across the whole run. Second, ChSystem's own timers are reset at the
// top of every DoStepDynamics, so they report the last step only and cannot be
// differenced across a window -- they have to be summed every step.
//
// So: accumulate wall clock per loop section and sum Chrono's per-step timers,
// then report the window totals as a fraction of the window's sim time (i.e.
// each number is that section's own contribution to wall/sim).
struct PerfAccum {
double syn = 0.0; // SynChrono MPI exchange
double robot_sync = 0.0; // rover Synchronize + terrain + VSG Synchronize
double bldr_sync = 0.0; // builder Synchronize (ROS bridges + vehicle sync)
double robot_adv = 0.0; // rover Advance (owns the main system's step)
double bldr_adv = 0.0; // builder Advance (owns the builder system's step)
double sensor = 0.0; // Chrono::Sensor update
double render = 0.0; // VSG render
double spin = 0.0; // real-time throttle
// Summed per-step Chrono timers for the rank's one shared system.
double sys_step = 0.0;
double sys_coll = 0.0;
double sys_broad = 0.0;
double sys_narrow = 0.0;
double sys_setup = 0.0;
double sys_solve = 0.0;
double sys_update = 0.0;
void Reset() { *this = PerfAccum(); }
void AddSystemStep(const ChSystem* sys) {
if (!sys)
return;
sys_step += sys->GetTimerStep();
sys_coll += sys->GetTimerCollision();
sys_broad += sys->GetTimerCollisionBroad();
sys_narrow += sys->GetTimerCollisionNarrow();
sys_setup += sys->GetTimerSetup();
sys_solve += sys->GetTimerLSsolve();
sys_update += sys->GetTimerUpdate();
}
};
// ONE SCM active domain covering a tracked vehicle's running gear. A domain only selects which
// grid nodes fire rays, and rays hit whatever shape is above them, so one box over the footprint
// serves all ~130 shoes for a single ray-OBB test instead of 130 domains.
//
// Sized from the shoe body positions, not constants, so it follows whatever track assembly is
// fitted: the shoes trace the whole loop, so their x extent is the true contact span and their
// y extent the two track centre lines. Measured at 0.1 m spacing, 1478 nodes/step against 4049
// for the old hand-set 7.5 x 4.5 m hull box.
//
// Do NOT narrow this to two boxes hugging the tracks. That is cheaper still (1267 nodes/step)
// but uncovers the soil BETWEEN them; rays from those nodes reach the hull underside and return
// reaction to the chassis. Removing them destabilised the single-pin track and killed rank 2 at
// t=18.43 and t=22.57 in two 45 s A/B runs. The belly stays covered.
//
// Attitude is safe: UpdateActiveDomain takes the axis-aligned hull of the rotated OOBB's corners,
// so pitch and roll only ever widen the region.
//
// Returns the number of domains registered (1, or 0 if the vehicle has no track shoes).
int AddTrackActiveDomains(SCMTerrain& terrain, ChTrackedVehicle* vehicle, int rank) {
if (!vehicle)
return 0;
const ChFrame<>& chassis_ref = vehicle->GetChassisBody()->GetFrameRefToAbs();
ChVector3d lo(std::numeric_limits<double>::max());
ChVector3d hi(std::numeric_limits<double>::lowest());
size_t n_shoes = 0;
for (int side = 0; side < 2; ++side) {
auto track = vehicle->GetTrackAssembly(static_cast<VehicleSide>(side));
if (!track)
continue;
for (size_t i = 0; i < track->GetNumTrackShoes(); ++i) {
// Shoe frame expressed in the chassis reference frame -- the frame AddActiveDomain
// measures its OOBB centre in.
const ChVector3d p =
chassis_ref.TransformPointParentToLocal(track->GetTrackShoe(i)->GetShoeBody()->GetPos());
for (int k = 0; k < 3; ++k) {
lo[k] = std::min(lo[k], p[k]);
hi[k] = std::max(hi[k], p[k]);
}
++n_shoes;
}
}
if (n_shoes == 0)
return 0;
const double m = scm_track_domain_margin;
const ChVector3d center(0.5 * (lo.x() + hi.x()), 0.5 * (lo.y() + hi.y()), 0.5 * (lo.z() + hi.z()));
const ChVector3d dims((hi.x() - lo.x()) + 2 * m, //
(hi.y() - lo.y()) + 2 * m, //
(hi.z() - lo.z()) + 2 * scm_track_domain_z_pad //
);
terrain.AddActiveDomain(vehicle->GetChassisBody(), center, dims);
SynLog() << "Rank " << rank << " SCM running-gear domain from " << n_shoes << " shoes: " << dims.x() << " x "
<< dims.y() << " m at (" << center.x() << ", " << center.y() << "), "
<< static_cast<long>(dims.x() * dims.y() / (0.02 * 0.02)) << " nodes at 2 cm (hull box was 84375)\n";
return 1;
}
// Invariant: a rock carries an SCM active domain IFF it can still move.
//
// A laid or frozen rock is SetFixed(true) and needs no soil reaction, but its domain would keep
// selecting every grid node under it every step for the rest of the run. A construction run only
// lays more wall, so that cost grows monotonically. (This also drops the builder's six seed-pile
// rocks, fixed from placement, at t=0.)
//
// Reconciled every step rather than hooked onto SetFixed: the fixed/dynamic flag is flipped from
// five places across four files (RobotRig dump and settle-freeze, LrvArm pick and place,
// BuilderArmRosBridge), and a missed hook fails silently and badly -- a dynamic rock with no
// domain gets no soil support and falls through the terrain. Re-asserting cannot drift.
//
// Every creation path registers a domain, so a rock first seen here is assumed to hold one; this
// only acts on transitions.
struct ScmRockDomains {
std::unordered_set<const ChBody*> seen; // rocks this has looked at at least once
std::unordered_set<const ChBody*> holds; // rocks believed to hold a domain right now
long added = 0;
long removed = 0;
};
void ReconcileRockDomains(SCMTerrain& terrain,
const std::vector<std::shared_ptr<ChBodyAuxRef>>& rocks,
ScmRockDomains& state,
double time,
int rank) {
for (const auto& rock : rocks) {
if (!rock)
continue;
const ChBody* key = rock.get();
if (state.seen.insert(key).second)
state.holds.insert(key); // registered by whichever path created it
const bool wants = !rock->IsFixed();
const bool has = state.holds.count(key) > 0;
if (wants == has)
continue;
if (wants) {
terrain.AddActiveDomain(rock, scm_rock_domain_center, scm_rock_domain_dims);
state.holds.insert(key);
++state.added;
} else {
terrain.RemoveActiveDomain(rock);
state.holds.erase(key);
++state.removed;
}
// Rare -- a rock changes state a handful of times per harvest cycle -- and worth having in
// the log, because a domain count that does not fall as the wall goes up is the symptom
// this is here to prevent.
SynLog() << "Rank " << rank << " SCM rock domain " << (wants ? "added" : "removed") << " at t=" << time
<< " (" << rock->GetName() << "); " << terrain.GetNumActiveDomains() << " domains now.\n";
}
}
// Wall-clock stopwatch that adds its own lifetime to an accumulator field.
class ScopedTimer {
public:
explicit ScopedTimer(double& sink) : m_sink(sink), m_start(std::chrono::steady_clock::now()) {}
~ScopedTimer() { m_sink += std::chrono::duration<double>(std::chrono::steady_clock::now() - m_start).count(); }
private:
double& m_sink;
std::chrono::steady_clock::time_point m_start;
};
// Small adapter so the simulation loop can stay headless unless this rank owns a VSG window.
class VsgAppWrapper {
public:
void Set(std::shared_ptr<ChWheeledVehicleVisualSystemVSG> app) { m_app = app; }
bool IsOk() const { return m_app ? m_app->Run() : true; }
void Synchronize(double time, const DriverInputs& driver_inputs) {
if (m_app)
m_app->Synchronize(time, driver_inputs);
}
void Advance(double step) {
if (m_app)
m_app->Advance(step);
}
void Render() {
if (!m_app)
return;
m_app->Render();
// VSG counterpart of --sensor_frame_dir.
if (!m_frame_dir.empty() && m_frames_left > 0) {
--m_frames_left;
m_app->WriteImageToFile(m_frame_dir + "vsg_frame_" + std::to_string(m_frame_index++) + ".png");
}
}
// Writes the first `count` rendered frames into `dir`, then stops.
void SaveFrames(const std::string& dir, int count) {
m_frame_dir = dir;
m_frames_left = count;
}
private:
std::shared_ptr<ChWheeledVehicleVisualSystemVSG> m_app;
std::string m_frame_dir;
int m_frames_left = 0;
int m_frame_index = 0;
};
// Command-line options used by the demo.
void AddCommandLineOptions(ChCLI& cli) {
cli.AddOption<double>("Simulation", "s,step_size", "Step size", std::to_string(step_size));
cli.AddOption<double>("Simulation", "e,end_time", "End time", std::to_string(end_time));
cli.AddOption<double>("Simulation", "b,heartbeat", "SynChrono heartbeat", std::to_string(heartbeat));
cli.AddOption<double>("Simulation", "settle_time", "Pre-run time with full brake before Synchrono starts",
std::to_string(settle_time));
cli.AddOption<double>("Diagnostics", "motion_log_rate",
"Rank-local chassis and tire-force log rate in Hz (0 disables logging)",
std::to_string(motion_log_rate));
cli.AddOption<double>("Diagnostics", "perf_log",
"Sim-time period (s) of the per-rank instantaneous cost breakdown (0 disables it)",
std::to_string(perf_log_period));
cli.AddOption<bool>("Diagnostics", "builder_no_arm", "Build the builder without its manipulator (cost bisection)");
// Divergence bisection: is the builder involved at all? Skipping it also skips its
// two AddAgent calls, which SHIFTS every later SynChrono agent id, so a rank that
// builds real zombies would mis-key them. Use with --no_sensor.
cli.AddOption<bool>("Diagnostics", "no_builder",
"Omit the tracked builder entirely (divergence bisection; shifts SynChrono agent "
"ids, so use with --no_sensor)");
// Separates the builder's DRIVE from its BUILD: the arm is only offered a pick while
// the builder counts as parked, so suppressing that leaves it orbiting and idle.
cli.AddOption<bool>("Diagnostics", "no_build",
"Builder drives its lane but never picks or places (cost/divergence "
"bisection)");
// SCM's HIP ray-cast backend.
//
// It is not a free speedup, it is a DIFFERENT SET OF BODIES. When it succeeds it
// replaces the CPU ray-cast loop for that whole step (SCMTerrain.cpp ~1446), and it
// only ever intersects ChCollisionShape::TRIANGLEMESH. Everything that has to feel
// soil now carries one: the lugged tyres (Polaris_LuggedTire.json), the rocks
// (RockField.cpp), and the track shoes' soil-facing pads (TrackSoilMesh.cpp).
//
// The M113 CHASSIS is still a convex hull, deliberately: the hull only reaches soil
// if the vehicle has bellied out, which is its own bug. Under this flag such a
// belly-out would sink rather than be supported.
cli.AddOption<bool>("Simulation", "scm_raycast_gpu",
"Use SCM's HIP GPU ray-cast backend (needs triangle-mesh collision "
"geometry on every body that must feel soil; the M113 chassis hull is "
"excluded, so a bellied-out hull would sink)");
// SCM's contact-force GPU backend is enabled by default in Chrono but only fires on a step
// whose hit count reaches scm_gpu::Config::min_hits (8192). Our footprints are far smaller
// than that at delta=0.10, so the path never runs. Expose the threshold so a run can measure
// whether the GPU wins at our hit counts instead of assuming Chrono's default applies here.
cli.AddOption<double>("Simulation", "scm_delta",
"SCM grid spacing in m. Cost of the ray-cast term grows as 1/delta^2 and "
"the height matrix as (patch/delta)^2, so this is the single knob that "
"decides whether a run fits", std::to_string(terrain_scm_delta_default));
cli.AddOption<int>("Simulation", "scm_gpu_min_hits",
"Hit-count threshold above which SCM's contact-force GPU backend runs "
"(Chrono default 8192; lower it to let smaller footprints qualify)", "8192");
cli.AddOption<std::string>("Diagnostics", "solver", "Robot-rank solver: bb, apgd, or default", "bb");
cli.AddOption<int>("Diagnostics", "solver_iterations", "Max solver iterations for the robot ranks", "100");
cli.AddOption<std::vector<int>>("VSG", "vsg", "MPI ranks that should open VSG visualization", "-1");
cli.AddOption<bool>("Simulation", "no_sensor",
"Disable the sensor/render rank 0 (it just syncs) -- measure physics without rendering");
// Save frames instead of opening a window, so either view can be checked from a
// script with no display. The sensor rank draws zombies and VSG draws the real
// bodies, so the two can legitimately differ.
cli.AddOption<std::string>("Diagnostics", "sensor_frame_dir",
"Save global-camera frames as PNG to this directory instead of opening a window", "");
// Shorten the harvest round trip for testing. The whole collector-to-builder hand-off
// -- return leg, tangential run-in, dump, freeze, builder pick -- cannot be exercised
// without a complete harvest cycle, and at the defaults that is about 400 s of SIM per
// cycle, nearly all of it a loaded rover crawling back from 87 m at 0.2-0.5 m/s. That
// is 2.5 hours of wall time per attempt at this machine's ~22x, which is not a
// practical edit-test loop for anything downstream of the dump. These move the rocks
// in without touching any default.
cli.AddOption<double>("Diagnostics", "rock_first_distance",
"Metres from the drop point to the first rock (default 20)", "20.0");
cli.AddOption<double>("Diagnostics", "rock_distance_step",
"Metres between successive rocks on a rank's line (default 30)", "30.0");
cli.AddOption<int>("Diagnostics", "rocks_per_rank",
"Pin every rank's rock line to this many rocks (0 = the default per-rank 2-6)", "0");
// GLOBAL rock size. Multiplies every harvest and wall rock; the per-variant
// normalisation in RockField.cpp is applied on top and only equalises the three OBJs
// against each other. Exposed because rock size against the vehicles' 0.41 m wheel
// clearance is the parameter most worth sweeping after a jackknife, and rebuilding
// to try 0.18 is a poor way to spend twenty minutes. It was already written into the
// recording metadata; only the flag was missing.
cli.AddOption<double>("Diagnostics", "rock_mesh_scale",
"Scale applied to every rock mesh (default 0.2)", "0.2");
// Absolute-pose capture for offline re-rendering. ON BY DEFAULT: a run nobody can
// re-render afterwards is a run that has to be repeated, and at this terrain size a
// repeat is expensive. Opt OUT with --no_record.
cli.AddOption<std::string>("Recording", "record_dir",
"Write every moving body's world pose to this directory "
"(default: <record_root>/run_<timestamp>)", "");
cli.AddOption<std::string>("Recording", "record_root",
"Parent directory for timestamp-named runs, used when --record_dir is not given",
"recordings");
cli.AddOption<bool>("Recording", "no_record", "Disable pose recording (recording is on by default)");
// Deformed ground, alongside the poses. 10 Hz because soil deformation is a slowly
// growing footprint, not a fast signal -- and because the file is a diff, so the rate
// buys resolution in TIME, not in coverage. 0 disables it.
cli.AddOption<double>("Recording", "scm_record_rate",
"SCM deformation capture rate in Hz (0 disables it)",
std::to_string(scm_record_rate_hz));
cli.AddOption<double>("Recording", "record_rate", "Pose capture rate in Hz", std::to_string(record_rate_hz));
}
} // namespace
int main(int argc, char* argv[]) {
// MPI/SynChrono setup. Each MPI rank owns one real Polaris vehicle.
auto communicator = chrono_types::make_shared<SynMPICommunicator>(argc, argv);
const int rank = communicator->GetRank();
const int num_ranks = communicator->GetNumRanks();
SynChronoManager syn_manager(rank, num_ranks, communicator);
ChCLI cli(argv[0]);
AddCommandLineOptions(cli);
if (!cli.Parse(argc, argv, rank == 0))
return 0;
step_size = cli.GetAsType<double>("step_size");
end_time = cli.GetAsType<double>("end_time");
heartbeat = cli.GetAsType<double>("heartbeat");
settle_time = cli.GetAsType<double>("settle_time");
motion_log_rate = cli.GetAsType<double>("motion_log_rate");
perf_log_period = cli.GetAsType<double>("perf_log");
BuilderRig::Options builder_options;
builder_options.with_arm = !cli.CheckOption("builder_no_arm");
const bool no_builder = cli.CheckOption("no_builder");
const bool no_build = cli.CheckOption("no_build");
const bool no_sensor = cli.CheckOption("no_sensor");
const std::string sensor_frame_dir = cli.GetAsType<std::string>("sensor_frame_dir");
const bool scm_raycast_gpu = cli.CheckOption("scm_raycast_gpu");
const int scm_gpu_min_hits = cli.GetAsType<int>("scm_gpu_min_hits");
const double terrain_scm_delta = cli.GetAsType<double>("scm_delta");