File size: 62,802 Bytes
e5f58d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
#include <gazebo/gazebo.hh>
#include <gazebo/physics/physics.hh>
#include <gazebo/common/common.hh>
#include <gazebo/common/Image.hh>
#include <gazebo/sensors/sensors.hh>
#include <gazebo/sensors/CameraSensor.hh>
#include <gazebo/rendering/Camera.hh>
#include <ignition/math/Vector3.hh>
#include <ignition/math/Pose3.hh>

#include <boost/filesystem.hpp>

#include <vector>
#include <string>
#include <cstdlib>
#include <cmath>
#include <fstream>
#include <functional>
#include <sstream>
#include <ctime>
#include <algorithm>
#include <iomanip>
#include <mutex>
#include <cctype>

namespace gazebo
{
class SimpleDronePlugin : public ModelPlugin
{
  struct CachedFrame
  {
    std::vector<unsigned char> data;
    unsigned int width = 0;
    unsigned int height = 0;
    unsigned int depth = 0;
    std::string format;
    common::Time time;
  };

public:
  void Load(physics::ModelPtr model, sdf::ElementPtr sdf) override
  {
    this->model = model;
    this->world = model->GetWorld();

    this->speed = 0.6;
    if (sdf->HasElement("speed"))
      this->speed = sdf->Get<double>("speed");

    // Where to save the captured RGB frames. The run script sets this env var
    // so the model can be reused without hardcoded project paths.
    const char *envImageDir = std::getenv("SIMPLE_DRONE_IMAGE_DIR");
    if (envImageDir && envImageDir[0] != '\0')
    {
      this->imageDir = envImageDir;
    }
    else if (sdf->HasElement("image_dir"))
    {
      this->imageDir = sdf->Get<std::string>("image_dir");
    }
    else
    {
      this->imageDir = "drone_images";
    }

    // (Legacy <capture_period> is ignored: frames are now captured once per
    // waypoint, on arrival, rather than on a fixed time interval.)
    this->capturePeriod = 1.0;
    if (sdf->HasElement("capture_period"))
      this->capturePeriod = sdf->Get<double>("capture_period");

    this->datasetMode = false;
    this->quitOnFinish = false;
    this->rejectGrayImages = true;
    this->grayDelta = this->EnvInt("SIMPLE_DRONE_GRAY_DELTA", 3);
    this->grayMin = this->EnvInt("SIMPLE_DRONE_GRAY_MIN", 120);
    this->grayMax = this->EnvInt("SIMPLE_DRONE_GRAY_MAX", 136);
    this->grayMaxRatio = std::min(
      0.99, std::max(0.0, this->EnvDouble("SIMPLE_DRONE_GRAY_MAX_RATIO", 0.12)));
    this->grayTileRatio = std::min(
      0.99, std::max(0.0, this->EnvDouble("SIMPLE_DRONE_GRAY_TILE_RATIO", 0.90)));
    this->grayScanlineRatio = std::min(
      0.99, std::max(0.0, this->EnvDouble("SIMPLE_DRONE_GRAY_SCANLINE_RATIO", 0.95)));
    this->minLumaStd = this->EnvDouble("SIMPLE_DRONE_MIN_LUMA_STD", 4.0);
    this->minRgbRange = this->EnvInt("SIMPLE_DRONE_MIN_RGB_RANGE", 12);
    this->viewDownTilt = this->EnvDouble("SIMPLE_DRONE_VIEW_DOWN_TILT", 0.55);
    this->minValidImageRatio =
      this->EnvDouble("SIMPLE_DRONE_MIN_VALID_IMAGE_RATIO", 0.001);
    const char *envRejectGrayImages = std::getenv("SIMPLE_DRONE_REJECT_GRAY_IMAGES");
    if (envRejectGrayImages && std::string(envRejectGrayImages) == "0")
      this->rejectGrayImages = false;

    const char *envQuitOnFinish = std::getenv("SIMPLE_DRONE_QUIT_ON_FINISH");
    if (envQuitOnFinish && envQuitOnFinish[0] != '\0' &&
        std::string(envQuitOnFinish) != "0")
      this->quitOnFinish = true;
    const char *envDoneFile = std::getenv("SIMPLE_DRONE_DONE_FILE");
    if (envDoneFile && envDoneFile[0] != '\0')
      this->doneFile = envDoneFile;

    const char *envDatasetRoot = std::getenv("SIMPLE_DRONE_DATASET_ROOT");
    if (envDatasetRoot && envDatasetRoot[0] != '\0')
    {
      this->datasetRoot = envDatasetRoot;
      this->datasetMode = true;
    }
    const char *envDatasetTrajectoryFile =
      std::getenv("SIMPLE_DRONE_DATASET_TRAJECTORY_FILE");
    if (envDatasetTrajectoryFile && envDatasetTrajectoryFile[0] != '\0')
      this->datasetTrajectoryFile = envDatasetTrajectoryFile;

    // The four viewpoints we want to read. The names must match the
    // <sensor> names declared in the model SDF.
    this->cameraNames = {"cam_front", "cam_down", "cam_left", "cam_right"};
    // Output sub-folder for each viewpoint (decoupled from the sensor name,
    // so e.g. cam_front is saved under <image_dir>/front/).
    this->folderNames = this->datasetMode
      ? std::vector<std::string>{"images_front", "images_down", "images_left", "images_right"}
      : std::vector<std::string>{"front", "down", "left", "right"};
    this->cameras.resize(this->cameraNames.size());
    this->imageConnections.resize(this->cameraNames.size());
    this->latestFrames.resize(this->cameraNames.size());

    if (this->datasetMode)
    {
      boost::filesystem::create_directories(this->imageDir);
      gzmsg << "[SimpleDronePlugin] saving dataset RGB frames under: "
            << this->imageDir
            << "/<trajectory>/{images_front,images_down,images_left,images_right}/"
            << std::endl;
    }
    else
    {
      // Each viewpoint gets its own sub-folder, e.g. <image_dir>/front/.
      for (const std::string &name : this->folderNames)
        boost::filesystem::create_directories(this->imageDir + "/" + name);
      gzmsg << "[SimpleDronePlugin] saving RGB frames under: "
            << this->imageDir << "/{" ;
      for (size_t i = 0; i < this->folderNames.size(); ++i)
        gzmsg << this->folderNames[i]
              << (i + 1 < this->folderNames.size() ? "," : "}/\n");
    }

    if (!this->datasetMode)
    {
      // Trajectory log: one row per saved frame set (one per waypoint). The
      // `frame` column matches both the image filename and the waypoint index,
      // e.g. frame 5 <-> front/000005.png <-> waypoints[5].
      const std::string trajPath = this->imageDir + "/trajectory.csv";
      this->trajFile.open(trajPath, std::ios::out | std::ios::trunc);
      this->trajFile << "frame,sim_time,x,y,z,"
                        "roll_rad,pitch_rad,yaw_rad,roll_deg,pitch_deg,yaw_deg,"
                        "qw,qx,qy,qz\n";
      gzmsg << "[SimpleDronePlugin] saving trajectory to: " << trajPath << std::endl;
    }

    if (this->rejectGrayImages)
    {
      gzmsg << "[SimpleDronePlugin] gray-frame rejection enabled: "
            << "gray_delta=" << this->grayDelta
            << ", gray_range=[" << this->grayMin << ',' << this->grayMax << ']'
            << ", max_gray_ratio=" << this->grayMaxRatio
            << ", max_gray_tile_ratio=" << this->grayTileRatio
            << ", max_gray_scanline_ratio=" << this->grayScanlineRatio
            << ", min_luma_std=" << this->minLumaStd
            << ", min_rgb_range=" << this->minRgbRange
            << std::endl;
    }

    this->camerasReady = false;
    this->frameCounter = 0;
    this->commandMode = false;
    this->waitingForCommand = false;
    this->commandYaw = 0.0;

    const char *envCommandFile = std::getenv("SIMPLE_DRONE_COMMAND_FILE");
    if (envCommandFile && envCommandFile[0] != '\0')
    {
      this->commandFile = envCommandFile;
      this->commandMode = true;
    }
    else if (sdf->HasElement("command_file"))
    {
      this->commandFile = sdf->Get<std::string>("command_file");
      this->commandMode = !this->commandFile.empty();
    }

    this->lastCommandMTime = 0;
    if (this->commandMode)
    {
      if (boost::filesystem::exists(this->commandFile))
      {
        this->lastCommandMTime = boost::filesystem::last_write_time(this->commandFile);
        std::ifstream existing(this->commandFile);
        std::ostringstream buf;
        buf << existing.rdbuf();
        this->lastCommandText = buf.str();
      }
      gzmsg << "[SimpleDronePlugin] command mode enabled; waiting for: "
            << this->commandFile << std::endl;
    }

    // Capture happens once per waypoint. Begin in the "settling" state on
    // waypoints[0] (the takeoff/start point): the drone is pinned to the exact
    // waypoint and we wait for the cameras to render a fresh frame from that
    // pose before saving, so the first image+row are the start point and every
    // saved image corresponds to its logged coordinate (not one render earlier).
    this->settling = true;
    this->settleBaselineSet = false;
    this->captureFailureWarned = false;
    this->settleTimeoutWarned = false;
    this->captureYaw = 0.0;
    this->grayRejectWarnCounter = 0;
    this->sweepInProgress = false;
    this->sweepPoseSet = false;
    this->sweepViewIndex = 0;
    this->sweepYawAttempt = 0;
    this->sweepTimeoutWarned = false;
    this->physicalSequenceInProgress = false;
    this->physicalViewIndex = 0;
    this->physicalWarned = false;
    this->physicalViewArmed = false;
    this->physicalBaselineTime = common::Time::Zero;
    this->physicalRejectCount = 0;
    this->physicalFallbackToSweep = false;

    this->returningToStart = false;
    this->currentDatasetTrajectory = 0;

    if (this->datasetMode)
    {
      this->trajectoryDir = this->datasetRoot + "/trajectory";
      this->LoadDatasetTrajectories();
    }

    // Tour of the whole 15x10 apartment. Safe envelope: x in [-6.5,6.5],
    // y in [-4,4], z in [1.2,1.8] (clear of walls, furniture and ceiling).
    // Order: center -> dining -> living -> TV/kitchen front -> bedroom -> back.
    if (this->datasetMode)
    {
      if (!this->BeginDatasetTrajectory(0))
      {
        gzerr << "[SimpleDronePlugin] no dataset trajectories loaded from "
              << this->trajectoryDir << std::endl;
      }
    }
    else
    {
      this->waypoints.push_back(ignition::math::Vector3d(-7.0,  0.6, 1.8)); // takeoff: clear strip on left wall, yaw=0 (+x), overview of whole apartment
    }
    if (!this->commandMode && !this->datasetMode)
    {
      this->waypoints.push_back(ignition::math::Vector3d(-4.5,  -3.0, 1.6));  // dining area
      this->waypoints.push_back(ignition::math::Vector3d(-5.8,  0.0, 1.4));  // living-room corner
      this->waypoints.push_back(ignition::math::Vector3d(-4.4, 3.3, 1.7));  // sofa / TV wall
      this->waypoints.push_back(ignition::math::Vector3d( 0.0, 3.5, 1.5));  // sweep along front wall
      this->waypoints.push_back(ignition::math::Vector3d( 4.0, 3.3, 1.4));  // kitchen
      this->waypoints.push_back(ignition::math::Vector3d( 5.8,  0.0, 1.6));  // toward bedroom
      this->waypoints.push_back(ignition::math::Vector3d( 4.8,  -3.0, 1.7));  // bed / wardrobe
      this->waypoints.push_back(ignition::math::Vector3d( 0.0,  -3.5, 1.5));  // back wall windows
      this->waypoints.push_back(ignition::math::Vector3d( 0.0,  0.0, 1.3));  // back to center
    }

    this->targetIndex = 0;
    this->tourComplete = false;
    this->lastTime = this->world->SimTime();

    this->updateConnection = event::Events::ConnectWorldUpdateBegin(
      std::bind(&SimpleDronePlugin::OnUpdate, this));
  }

private:
  // Look up the four camera sensors by name. Sensors are created after the
  // model is loaded, so this is retried each update until all are found.
  bool InitCameras()
  {
    sensors::SensorManager *mgr = sensors::SensorManager::Instance();
    if (!mgr || !mgr->SensorsInitialized())
      return false;

    bool allFound = true;
    for (size_t i = 0; i < this->cameraNames.size(); ++i)
    {
      if (this->cameras[i])
        continue;

      sensors::SensorPtr s = mgr->GetSensor(this->cameraNames[i]);
      sensors::CameraSensorPtr cam =
        std::dynamic_pointer_cast<sensors::CameraSensor>(s);

      if (cam)
      {
        cam->SetActive(true);
        // Make sure the rendering camera keeps a CPU-side copy of the frame
        // so we can read the RGB bytes / save them.
        if (cam->Camera())
        {
          cam->Camera()->SetCaptureData(true);
          this->imageConnections[i] = cam->Camera()->ConnectNewImageFrame(
            [this, i](const unsigned char *image,
                      unsigned int width,
                      unsigned int height,
                      unsigned int depth,
                      const std::string &format)
            {
              if (!image || width == 0 || height == 0 || depth == 0)
                return;
              CachedFrame frame;
              frame.width = width;
              frame.height = height;
              frame.depth = depth;
              frame.format = format;
              frame.time = this->world ? this->world->SimTime() : common::Time::Zero;
              const size_t bytes =
                static_cast<size_t>(width) * static_cast<size_t>(height) * depth;
              frame.data.assign(image, image + bytes);

              std::lock_guard<std::mutex> lock(this->frameMutex);
              if (i < this->latestFrames.size())
                this->latestFrames[i] = std::move(frame);
            });
        }
        cam->Update(true);
        this->cameras[i] = cam;
      }
      else
      {
        allFound = false;
      }
    }
    return allFound;
  }

  ignition::math::Vector3d RotateYaw(
      const ignition::math::Vector3d &v,
      const double yaw) const
  {
    const double c = std::cos(yaw);
    const double s = std::sin(yaw);
    return ignition::math::Vector3d(
      c * v.X() - s * v.Y(),
      s * v.X() + c * v.Y(),
      v.Z());
  }

  ignition::math::Pose3d ViewPose(
      const ignition::math::Pose3d &base,
      const size_t viewIndex) const
  {
    const ignition::math::Vector3d &p = base.Pos();
    const double yaw = base.Rot().Yaw();
    ignition::math::Vector3d offset;
    double roll = this->viewDownTilt;
    double pitch = 0.0;
    double viewYaw = yaw;

    if (viewIndex == 0)  // front
    {
      offset = this->RotateYaw(ignition::math::Vector3d(0.62, 0.0, 0.0), yaw);
      viewYaw = yaw;
    }
    else if (viewIndex == 1)  // down
    {
      offset = ignition::math::Vector3d(0.0, 0.0, -0.35);
      pitch = ignition::math::Angle::HalfPi.Radian();
      viewYaw = yaw;
    }
    else if (viewIndex == 2)  // left
    {
      offset = this->RotateYaw(ignition::math::Vector3d(0.0, 0.62, 0.0), yaw);
      viewYaw = yaw + ignition::math::Angle::HalfPi.Radian();
    }
    else  // right
    {
      offset = this->RotateYaw(ignition::math::Vector3d(0.0, -0.62, 0.0), yaw);
      viewYaw = yaw - ignition::math::Angle::HalfPi.Radian();
    }

    return ignition::math::Pose3d(
      p.X() + offset.X(),
      p.Y() + offset.Y(),
      p.Z() + offset.Z(),
      roll,
      pitch,
      viewYaw);
  }

  ignition::math::Pose3d SweepModelPose(
      const ignition::math::Pose3d &base,
      const size_t viewIndex,
      const double yawOffset = 0.0) const
  {
    const ignition::math::Vector3d &p = base.Pos();
    const double yaw = base.Rot().Yaw();
    double roll = 0.0;
    double pitch = 0.0;
    double viewYaw = yaw;

    // cam_right looks along the model's right side. Rotate the model in place
    // so that one known-good physical camera provides all required views.
    if (viewIndex == 0)        // front
      viewYaw = yaw + ignition::math::Angle::HalfPi.Radian();
    else if (viewIndex == 1)   // down
      roll = ignition::math::Angle::HalfPi.Radian();
    else if (viewIndex == 2)   // left
      viewYaw = yaw + M_PI;
    else                       // right
      viewYaw = yaw;
    viewYaw += yawOffset;

    return ignition::math::Pose3d(
      p.X(), p.Y(), p.Z(),
      roll, pitch, viewYaw);
  }

  bool RenderViewFrames(
      const ignition::math::Pose3d &basePose,
      std::vector<CachedFrame> &frames)
  {
    if (this->cameras.empty())
      return false;

    // Use cam_right as the capture source. On the target machine this is the
    // only physical camera that consistently produces scene pixels; rotating
    // the model in place is stable, while moving the Ogre camera directly can
    // segfault in gzserver.
    const size_t sourceIndex = std::min<size_t>(3u, this->cameras.size() - 1u);
    sensors::CameraSensorPtr sensor = this->cameras[sourceIndex];
    if (!sensor || !sensor->Camera())
      return false;

    rendering::CameraPtr renderCam = sensor->Camera();
    renderCam->SetCaptureData(true);
    sensor->SetActive(true);
    frames.assign(this->cameraNames.size(), CachedFrame());

    for (size_t i = 0; i < this->cameraNames.size(); ++i)
    {
      const ignition::math::Pose3d pose = this->SweepModelPose(basePose, i);
      this->model->SetWorldPose(pose);
      this->model->SetLinearVel(ignition::math::Vector3d::Zero);
      sensor->Update(true);

      const unsigned char *data = renderCam->ImageData();
      const unsigned int width = renderCam->ImageWidth();
      const unsigned int height = renderCam->ImageHeight();
      const unsigned int depth = renderCam->ImageDepth();
      if (!data || width == 0 || height == 0 || depth < 3)
      {
        if (!this->captureFailureWarned)
        {
          gzerr << "[SimpleDronePlugin] movable render camera not ready for "
                << this->cameraNames[i]
                << "; width=" << width
                << ", height=" << height
                << ", depth=" << depth << std::endl;
          this->captureFailureWarned = true;
        }
        return false;
      }

      CachedFrame frame;
      frame.width = width;
      frame.height = height;
      frame.depth = depth;
      frame.format = renderCam->ImageFormat();
      frame.time = this->world ? this->world->SimTime() : common::Time::Zero;
      const size_t bytes =
        static_cast<size_t>(width) * static_cast<size_t>(height) * depth;
      frame.data.assign(data, data + bytes);
      frames[i] = std::move(frame);
    }

    this->model->SetWorldPose(basePose);
    this->model->SetLinearVel(ignition::math::Vector3d::Zero);

    return true;
  }

  void ResetSingleCameraSweep()
  {
    if (this->sweepInProgress)
    {
      this->model->SetWorldPose(this->sweepBasePose);
      this->model->SetLinearVel(ignition::math::Vector3d::Zero);
    }
    this->sweepInProgress = false;
    this->sweepPoseSet = false;
    this->sweepViewIndex = 0;
    this->sweepYawAttempt = 0;
    this->sweepFrames.clear();
    this->sweepTimeoutWarned = false;
  }

  bool CropGrayBackground(CachedFrame &frame) const
  {
    if (frame.data.empty() || frame.width == 0 || frame.height == 0 ||
        frame.depth != 3)
      return false;

    unsigned int minX = frame.width;
    unsigned int minY = frame.height;
    unsigned int maxX = 0;
    unsigned int maxY = 0;
    size_t validPixels = 0;

    for (unsigned int y = 0; y < frame.height; ++y)
    {
      for (unsigned int x = 0; x < frame.width; ++x)
      {
        const size_t offset =
          (static_cast<size_t>(y) * frame.width + x) * frame.depth;
        const bool isGazeboGray =
          frame.data[offset] == 128 &&
          frame.data[offset + 1] == 128 &&
          frame.data[offset + 2] == 128;
        if (!isGazeboGray)
        {
          minX = std::min(minX, x);
          minY = std::min(minY, y);
          maxX = std::max(maxX, x);
          maxY = std::max(maxY, y);
          ++validPixels;
        }
      }
    }

    const size_t totalPixels =
      static_cast<size_t>(frame.width) * static_cast<size_t>(frame.height);
    const double validRatio =
      static_cast<double>(validPixels) / std::max<size_t>(totalPixels, 1u);
    if (validRatio < this->minValidImageRatio || minX > maxX || minY > maxY)
      return false;

    const unsigned int margin = 4;
    minX = minX > margin ? minX - margin : 0;
    minY = minY > margin ? minY - margin : 0;
    maxX = std::min(frame.width - 1, maxX + margin);
    maxY = std::min(frame.height - 1, maxY + margin);

    const unsigned int cropW = maxX - minX + 1;
    const unsigned int cropH = maxY - minY + 1;
    if (cropW < 4 || cropH < 4)
      return false;

    std::vector<unsigned char> resized(
      static_cast<size_t>(frame.width) * frame.height * 3u);
    for (unsigned int y = 0; y < frame.height; ++y)
    {
      const unsigned int srcY =
        minY + std::min(cropH - 1,
                        static_cast<unsigned int>(
                          (static_cast<unsigned long long>(y) * cropH) /
                          frame.height));
      for (unsigned int x = 0; x < frame.width; ++x)
      {
        const unsigned int srcX =
          minX + std::min(cropW - 1,
                          static_cast<unsigned int>(
                            (static_cast<unsigned long long>(x) * cropW) /
                            frame.width));
        const size_t src =
          (static_cast<size_t>(srcY) * frame.width + srcX) * 3u;
        const size_t dst =
          (static_cast<size_t>(y) * frame.width + x) * 3u;
        resized[dst] = frame.data[src];
        resized[dst + 1] = frame.data[src + 1];
        resized[dst + 2] = frame.data[src + 2];
      }
    }

    unsigned long long sumR = 0;
    unsigned long long sumG = 0;
    unsigned long long sumB = 0;
    size_t fillSourcePixels = 0;
    for (size_t i = 0; i + 2 < resized.size(); i += 3)
    {
      const bool isGazeboGray =
        resized[i] == 128 && resized[i + 1] == 128 && resized[i + 2] == 128;
      if (!isGazeboGray)
      {
        sumR += resized[i];
        sumG += resized[i + 1];
        sumB += resized[i + 2];
        ++fillSourcePixels;
      }
    }
    if (fillSourcePixels == 0)
      return false;
    const unsigned char fillR =
      static_cast<unsigned char>(sumR / fillSourcePixels);
    const unsigned char fillG =
      static_cast<unsigned char>(sumG / fillSourcePixels);
    const unsigned char fillB =
      static_cast<unsigned char>(sumB / fillSourcePixels);
    for (size_t i = 0; i + 2 < resized.size(); i += 3)
    {
      const bool isGazeboGray =
        resized[i] == 128 && resized[i + 1] == 128 && resized[i + 2] == 128;
      if (isGazeboGray)
      {
        resized[i] = fillR;
        resized[i + 1] = fillG;
        resized[i + 2] = fillB;
      }
    }

    frame.data.swap(resized);
    return true;
  }

  bool NormalizeFrameToRgb(
      const CachedFrame &src,
      CachedFrame &dst) const
  {
    if (src.data.empty() || src.width == 0 || src.height == 0 || src.depth < 3)
      return false;

    std::string format = src.format;
    std::transform(format.begin(), format.end(), format.begin(),
                   [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
    const bool bgr =
      format.find("b8g8r8") != std::string::npos ||
      format.find("bgr") != std::string::npos;

    const size_t pixelCount =
      static_cast<size_t>(src.width) * static_cast<size_t>(src.height);
    dst.data.resize(pixelCount * 3u);
    dst.width = src.width;
    dst.height = src.height;
    dst.depth = 3;
    dst.format = "R8G8B8";
    dst.time = src.time;

    for (size_t i = 0; i < pixelCount; ++i)
    {
      const size_t in = i * src.depth;
      const size_t out = i * 3u;
      if (bgr)
      {
        dst.data[out] = src.data[in + 2];
        dst.data[out + 1] = src.data[in + 1];
        dst.data[out + 2] = src.data[in];
      }
      else
      {
        dst.data[out] = src.data[in];
        dst.data[out + 1] = src.data[in + 1];
        dst.data[out + 2] = src.data[in + 2];
      }
    }

    return true;
  }

  bool AdvanceSingleCameraSweep(std::vector<CachedFrame> &frames)
  {
    if (this->cameras.empty())
      return false;

    const size_t sourceIndex = std::min<size_t>(3u, this->cameras.size() - 1u);
    sensors::CameraSensorPtr sensor = this->cameras[sourceIndex];
    if (!sensor || !sensor->Camera())
      return false;

    if (!this->sweepInProgress)
    {
      this->sweepBasePose = this->model->WorldPose();
      this->sweepFrames.assign(this->cameraNames.size(), CachedFrame());
      this->sweepViewIndex = 0;
      this->sweepPoseSet = false;
      this->sweepInProgress = true;
      this->sweepStartTime = this->world ? this->world->SimTime() : common::Time::Zero;
      this->sweepTimeoutWarned = false;
    }

    if (this->sweepViewIndex >= this->cameraNames.size())
    {
      frames = this->sweepFrames;
      this->ResetSingleCameraSweep();
      return true;
    }

    sensor->SetActive(true);
    sensor->Camera()->SetCaptureData(true);

    const double yawOffset =
      static_cast<double>(this->sweepYawAttempt) *
      ignition::math::Angle::HalfPi.Radian() * 0.5;
    const ignition::math::Pose3d pose =
      this->SweepModelPose(this->sweepBasePose, this->sweepViewIndex, yawOffset);
    this->model->SetWorldPose(pose);
    this->model->SetLinearVel(ignition::math::Vector3d::Zero);

    if (!this->sweepPoseSet)
    {
      {
        std::lock_guard<std::mutex> lock(this->frameMutex);
        this->sweepBaselineFrameTime =
          sourceIndex < this->latestFrames.size()
            ? this->latestFrames[sourceIndex].time
            : common::Time::Zero;
      }
      sensor->Update(true);
      this->sweepPoseSet = true;
      return false;
    }

    sensor->Update(true);

    CachedFrame sourceFrame;
    {
      std::lock_guard<std::mutex> lock(this->frameMutex);
      if (sourceIndex < this->latestFrames.size())
        sourceFrame = this->latestFrames[sourceIndex];
    }

    if (sourceFrame.data.empty() ||
        sourceFrame.time <= this->sweepBaselineFrameTime)
    {
      const common::Time now = this->world ? this->world->SimTime() : common::Time::Zero;
      const double wait = (now - this->sweepStartTime).Double();
      if (wait > this->settleTimeout && !this->sweepTimeoutWarned)
      {
        gzerr << "[SimpleDronePlugin] camera sweep timeout at target index "
              << this->targetIndex << "; view=" << this->cameraNames[this->sweepViewIndex]
              << ". Waiting for a fresh frame." << std::endl;
        this->sweepTimeoutWarned = true;
      }
      return false;
    }

    CachedFrame rgbFrame;
    if (!this->NormalizeFrameToRgb(sourceFrame, rgbFrame))
      return false;
    if (!this->CropGrayBackground(rgbFrame))
    {
      ++this->sweepYawAttempt;
      this->sweepPoseSet = false;
      if (this->sweepYawAttempt <= 8)
        return false;

      gzerr << "[SimpleDronePlugin] unable to find non-gray content at target index "
            << this->targetIndex << "; view="
            << this->cameraNames[this->sweepViewIndex] << std::endl;
      this->sweepYawAttempt = 0;
      return false;
    }

    this->sweepFrames[this->sweepViewIndex] = std::move(rgbFrame);
    ++this->sweepViewIndex;
    this->sweepYawAttempt = 0;
    this->sweepPoseSet = false;

    if (this->sweepViewIndex < this->cameraNames.size())
      return false;

    frames = this->sweepFrames;
    this->ResetSingleCameraSweep();
    return true;
  }

  bool ReadPhysicalCameraFrames(std::vector<CachedFrame> &frames)
  {
    std::lock_guard<std::mutex> lock(this->frameMutex);
    frames = this->latestFrames;
    return frames.size() == this->cameraNames.size();
  }

  void ResetPhysicalCameraSequence()
  {
    this->physicalSequenceInProgress = false;
    this->physicalViewIndex = 0;
    this->physicalWarned = false;
    this->physicalViewArmed = false;
    this->physicalBaselineTime = common::Time::Zero;
    this->physicalFrames.clear();
  }

  bool AdvancePhysicalCameraSequence(std::vector<CachedFrame> &frames)
  {
    if (!this->physicalSequenceInProgress)
    {
      this->physicalSequenceInProgress = true;
      this->physicalViewIndex = 0;
      this->physicalWarned = false;
      this->physicalViewArmed = false;
      this->physicalBaselineTime = common::Time::Zero;
      this->physicalFrames.assign(this->cameraNames.size(), CachedFrame());
    }

    if (this->physicalViewIndex >= this->cameraNames.size())
    {
      frames = this->physicalFrames;
      this->ResetPhysicalCameraSequence();
      return true;
    }

    for (size_t i = 0; i < this->cameras.size(); ++i)
    {
      if (!this->cameras[i])
        continue;
      this->cameras[i]->SetActive(i == this->physicalViewIndex);
      if (this->cameras[i]->Camera())
        this->cameras[i]->Camera()->SetCaptureData(i == this->physicalViewIndex);
      if (i == this->physicalViewIndex)
        this->cameras[i]->Update(true);
    }

    if (!this->physicalViewArmed)
    {
      std::lock_guard<std::mutex> lock(this->frameMutex);
      if (this->physicalViewIndex < this->latestFrames.size())
        this->physicalBaselineTime = this->latestFrames[this->physicalViewIndex].time;
      else
        this->physicalBaselineTime = common::Time::Zero;
      this->physicalViewArmed = true;
      return false;
    }

    CachedFrame candidate;
    {
      std::lock_guard<std::mutex> lock(this->frameMutex);
      if (this->physicalViewIndex >= this->latestFrames.size())
        return false;
      candidate = this->latestFrames[this->physicalViewIndex];
    }

    if (candidate.time <= this->physicalBaselineTime)
      return false;

    if (candidate.data.empty() || candidate.width == 0 ||
        candidate.height == 0 || candidate.depth < 3)
      return false;

    std::string reason;
    if (!this->FrameLooksUsable(
          candidate.data.data(),
          candidate.width,
          candidate.height,
          candidate.depth,
          reason))
    {
      if (!this->physicalWarned)
      {
        gzerr << "[SimpleDronePlugin] waiting for usable physical camera frame at target index "
              << this->targetIndex << "; camera="
              << this->cameraNames[this->physicalViewIndex]
              << "; " << reason << std::endl;
        this->physicalWarned = true;
      }
      this->physicalBaselineTime = candidate.time;
      ++this->physicalRejectCount;
      if (this->physicalRejectCount >= 60)
      {
        gzerr << "[SimpleDronePlugin] physical cameras stayed unusable at target index "
              << this->targetIndex
              << "; switching the remainder of this trajectory to single-camera sweep."
              << std::endl;
        this->physicalFallbackToSweep = true;
        this->ResetPhysicalCameraSequence();
      }
      return false;
    }

    this->physicalFrames[this->physicalViewIndex] = std::move(candidate);
    ++this->physicalViewIndex;
    this->physicalWarned = false;
    this->physicalViewArmed = false;
    this->physicalBaselineTime = common::Time::Zero;
    return false;
  }

  // Read the latest RGB frame from each camera and write it to disk as PNG.
  // Returns true only when a complete frame set is written, so images and
  // trajectory rows stay in one-to-one correspondence (sharing one frame index).
  bool CaptureFrames()
  {
    // Capture only once EVERY camera has a rendered frame this tick. During the
    // first few updates the render pipeline is still warming up and ImageData()
    // is null; capturing then would advance the frame counter and log a
    // trajectory row with no PNG on disk, breaking the image<->trajectory
    // pairing. Bail out so this frame index is retried until all views render.
    std::vector<CachedFrame> frames;
    const char *singleCameraSweep = std::getenv("SIMPLE_DRONE_SINGLE_CAMERA_SWEEP");
    const bool useSingleCameraSweep =
      this->physicalFallbackToSweep ||
      (singleCameraSweep && std::string(singleCameraSweep) != "0");
    if (useSingleCameraSweep)
    {
      if (!this->AdvanceSingleCameraSweep(frames))
        return false;
    }
    else
    {
      if (!this->AdvancePhysicalCameraSequence(frames))
        return false;
    }

    for (size_t i = 0; i < this->cameras.size(); ++i)
    {
      if (i >= frames.size() || frames[i].data.empty() ||
          frames[i].width == 0 || frames[i].height == 0 || frames[i].depth < 3)
      {
        if (!this->captureFailureWarned)
        {
          gzerr << "[SimpleDronePlugin] camera frame not ready at target index "
                << this->targetIndex << "; camera=" << this->cameraNames[i]
                << ", movable_frame=" << (i < frames.size() && !frames[i].data.empty())
                << std::endl;
          this->captureFailureWarned = true;
        }
        return false;
      }
    }

    std::string frameName;
    if (this->datasetMode && this->currentDatasetTrajectory < this->datasetTrajectories.size())
    {
      const DatasetTrajectory &traj = this->datasetTrajectories[this->currentDatasetTrajectory];
      const DatasetPoint &pt = traj.points[this->targetIndex];
      std::ostringstream name;
      name << traj.name << "_step_" << std::setw(6) << std::setfill('0') << pt.step << ".png";
      frameName = name.str();
    }

    if (this->rejectGrayImages)
    {
      for (size_t i = 0; i < this->cameras.size(); ++i)
      {
        const CachedFrame &frame = frames[i];
        const unsigned char *data = frame.data.data();
        std::string reason;
        if (!this->FrameLooksUsable(
              data,
              frame.width,
              frame.height,
              frame.depth,
              reason))
        {
          if (this->grayRejectWarnCounter % 100 == 0)
          {
            gzerr << "[SimpleDronePlugin] rejected gray/unusable frame at target index "
                  << this->targetIndex << "; camera=" << this->cameraNames[i]
                  << "; " << reason << ". Waiting for a new frame." << std::endl;
          }
          ++this->grayRejectWarnCounter;
          if (useSingleCameraSweep)
            this->ResetSingleCameraSweep();
          else
            this->ResetPhysicalCameraSequence();
          return false;
        }
      }
    }

    // All four views are ready -- save them under the shared frame index.
    for (size_t i = 0; i < this->cameras.size(); ++i)
    {
      const CachedFrame &frame = frames[i];
      // `cam->ImageData()` is a tightly packed R8G8B8 buffer of size w * h * 3.
      // (Use it here directly if you want to feed it into an algorithm.)

      // ----- save the RGB image as PNG into this camera's sub-folder -----
      char name[300];
      if (this->datasetMode)
      {
        const DatasetTrajectory &traj =
          this->datasetTrajectories[this->currentDatasetTrajectory];
        std::snprintf(name, sizeof(name), "%s/%s/%s/%s",
                      this->imageDir.c_str(),
                      traj.name.c_str(),
                      this->folderNames[i].c_str(),
                      frameName.c_str());
      }
      else
      {
        std::snprintf(name, sizeof(name), "%s/%s/%06u.png",
                      this->imageDir.c_str(),
                      this->folderNames[i].c_str(),
                      this->frameCounter);
      }
      const unsigned char *data = frame.data.data();
      if (!data || frame.data.empty())
      {
        gzerr << "[SimpleDronePlugin] camera image data disappeared before save; camera="
              << this->cameraNames[i] << std::endl;
        return false;
      }
      const size_t pixelCount =
        static_cast<size_t>(frame.width) * static_cast<size_t>(frame.height) * 3u;
      unsigned int minValue = 255;
      unsigned int maxValue = 0;
      unsigned long long sumValue = 0;
      for (size_t pixel = 0; pixel < pixelCount; ++pixel)
      {
        const unsigned int value = static_cast<unsigned int>(data[pixel]);
        minValue = std::min(minValue, value);
        maxValue = std::max(maxValue, value);
        sumValue += value;
      }
      if (std::getenv("SIMPLE_DRONE_DEBUG_CAMERA"))
      {
        gzmsg << "[SimpleDronePlugin] camera buffer "
              << this->cameraNames[i]
              << " frame=" << this->frameCounter
              << " size=" << frame.width << "x" << frame.height
              << " min=" << minValue
              << " max=" << maxValue
              << " mean=" << (static_cast<double>(sumValue) / std::max<size_t>(pixelCount, 1u))
              << " first_rgb="
              << static_cast<unsigned int>(data[0]) << ','
              << static_cast<unsigned int>(data[1]) << ','
              << static_cast<unsigned int>(data[2])
              << std::endl;
      }
      common::Image image;
      image.SetFromData(
        data,
        frame.width,
        frame.height,
        common::Image::RGB_INT8);
      image.SavePNG(std::string(name));
    }

    // ----- log this trajectory point (3D position + orientation) -----
    ignition::math::Pose3d pose = this->model->WorldPose();
    const ignition::math::Vector3d &p = pose.Pos();
    const ignition::math::Quaterniond &q = pose.Rot();
    double roll = q.Roll();
    double pitch = q.Pitch();
    double yaw = q.Yaw();
    const double r2d = 180.0 / M_PI;
    double t = this->world->SimTime().Double();
    if (this->datasetMode && this->currentDatasetTrajectory < this->datasetTrajectories.size())
    {
      DatasetPoint &pt =
        this->datasetTrajectories[this->currentDatasetTrajectory].points[this->targetIndex];
      pt.capturedX = p.X();
      pt.capturedY = p.Y();
      pt.capturedZ = p.Z();
      pt.captureFrame = this->frameCounter;
      pt.capturedYawRad = yaw;
      pt.capturedYawDeg = yaw * r2d;
      pt.imageName = frameName;
      pt.captured = true;
    }
    else if (this->trajFile.is_open())
    {
      this->trajFile << this->frameCounter << ','
                     << t << ','
                     << p.X() << ',' << p.Y() << ',' << p.Z() << ','
                     << roll << ',' << pitch << ',' << yaw << ','
                     << (roll * r2d) << ',' << (pitch * r2d) << ',' << (yaw * r2d) << ','
                     << q.W() << ',' << q.X() << ',' << q.Y() << ',' << q.Z() << '\n';
      this->trajFile.flush();  // persist even if the sim is Ctrl+C'd
    }

    gzmsg << "[SimpleDronePlugin] saved frame set #"
          << this->frameCounter << " (front/down/left/right)" << std::endl;
    this->grayRejectWarnCounter = 0;
    this->physicalRejectCount = 0;
    ++this->frameCounter;
    return true;
  }

  void OnUpdate()
  {
    common::Time now = this->world->SimTime();

    // Tour finished: hold the drone at the final waypoint and record nothing.
    if (this->tourComplete)
    {
      this->model->SetWorldPose(this->holdPose);
      this->model->SetLinearVel(ignition::math::Vector3d::Zero);
      return;
    }

    // Lazily bind the cameras once the sensor manager has created them.
    if (!this->camerasReady)
      this->camerasReady = this->InitCameras();
    if (!this->camerasReady)
      return;  // nothing happens (no motion, no capture) until cameras exist

    if (this->waypoints.empty())
      return;

    // ===== settle-then-capture on each waypoint =====
    // While settling, the drone is pinned to the EXACT waypoint and we wait for
    // every camera to render a brand-new frame from that pinned pose before
    // saving. Gazebo renders the cameras *after* this callback, so without the
    // wait the saved PNG would be the frame rendered one step earlier (during
    // the approach, a few cm short). The wait makes each image truly correspond
    // to its logged coordinate. The start point (waypoints[0]) begins settling.
    if (this->settling)
    {
      const ignition::math::Vector3d &wp = this->waypoints[this->targetIndex];
      const ignition::math::Pose3d snapped(
        wp.X(), wp.Y(), wp.Z(), 0.0, 0.0,
        this->datasetMode ? 0.0 : this->captureYaw);
      this->model->SetWorldPose(snapped);  // re-assert every tick: hold dead still
      this->model->SetLinearVel(ignition::math::Vector3d::Zero);

      // First tick parked here: latch each camera's current render time as the
      // baseline, then yield so the cameras can render from the pinned pose.
      if (!this->settleBaselineSet)
      {
        this->baseRenderTime.resize(this->cameras.size());
        for (size_t i = 0; i < this->cameras.size(); ++i)
        {
          if (this->cameras[i])
          {
            this->cameras[i]->SetActive(true);
            this->cameras[i]->Update(true);
          }
          this->baseRenderTime[i] = this->cameras[i]
            ? this->cameras[i]->LastMeasurementTime() : common::Time::Zero;
        }
        this->settleStartTime = now;
        this->settleBaselineSet = true;
        this->captureFailureWarned = false;
        return;
      }

      // Hold until EVERY camera has produced a new frame strictly after the
      // snap (i.e. rendered from the pinned pose), then capture.
      bool allCamerasRerendered = true;
      for (size_t i = 0; i < this->cameras.size(); ++i)
      {
        if (this->cameras[i])
        {
          this->cameras[i]->SetActive(true);
          this->cameras[i]->Update(true);
        }
        if (!this->cameras[i] ||
            this->cameras[i]->LastMeasurementTime() <= this->baseRenderTime[i])
        {
          allCamerasRerendered = false;
          break;
        }
      }
      if (!allCamerasRerendered)
      {
        const double settleWait = (now - this->settleStartTime).Double();
        if (settleWait < this->settleTimeout)
          return;  // not all cameras have re-rendered yet -- keep waiting

        if (!this->settleTimeoutWarned)
        {
          gzerr << "[SimpleDronePlugin] camera settle timeout after "
                << settleWait << "s at target index " << this->targetIndex
                << "; capturing latest available frames." << std::endl;
          this->settleTimeoutWarned = true;
        }
      }

      if (!this->CaptureFrames())  // also guards against null image buffers
        return;

      this->settling = false;
      this->settleBaselineSet = false;
      this->captureFailureWarned = false;
      this->settleTimeoutWarned = false;
      this->ResetPhysicalCameraSequence();

      if (this->datasetMode)
      {
        this->settling = false;
        this->settleBaselineSet = false;
        this->captureFailureWarned = false;
        this->settleTimeoutWarned = false;
        this->AdvanceDatasetAfterCapture(snapped);
        return;
      }

      if (this->commandMode)
      {
        this->holdPose = snapped;
        this->waitingForCommand = true;
        this->lastTime = now;
        return;
      }

      // That was the last waypoint -> the single-pass tour is done.
      if (this->targetIndex + 1 >= this->waypoints.size())
      {
        this->FinishTour(snapped);
        return;
      }
      ++this->targetIndex;     // head for the next waypoint
      this->lastTime = now;    // keep the first travel dt to one step
      return;
    }

    if (this->commandMode && this->waitingForCommand)
    {
      this->model->SetWorldPose(this->holdPose);
      this->model->SetLinearVel(ignition::math::Vector3d::Zero);
      if (!this->TryLoadCommand())
        return;

      this->waypoints.resize(1);
      this->waypoints.push_back(this->commandTarget);
      this->targetIndex = 1;
      this->waitingForCommand = false;
      this->lastTime = now;
      return;
    }

    // ===== fly toward waypoints[targetIndex] =====
    double dt = (now - this->lastTime).Double();
    this->lastTime = now;
    if (dt <= 0.0)
      return;

    ignition::math::Vector3d pos = this->model->WorldPose().Pos();
    ignition::math::Vector3d diff = this->waypoints[this->targetIndex] - pos;

    if (diff.Length() < 0.08)
    {
      if (this->datasetMode && this->returningToStart)
      {
        size_t nextTrajectory = this->currentDatasetTrajectory + 1;
        if (!this->BeginDatasetTrajectoryAtStart(nextTrajectory))
        {
          this->FinishTour(this->model->WorldPose());
          return;
        }
        return;
      }

      // Arrived: latch the travel heading and start settling on the waypoint.
      if (this->datasetMode && this->currentDatasetTrajectory < this->datasetTrajectories.size())
        this->captureYaw = 0.0;
      else
      this->captureYaw = this->commandMode ? this->commandYaw
                                             : this->model->WorldPose().Rot().Yaw();
      this->settling = true;
      this->settleBaselineSet = false;
      this->captureFailureWarned = false;
      this->settleTimeoutWarned = false;
      return;
    }

    ignition::math::Vector3d dir = diff.Normalized();
    double yaw = this->datasetMode ? 0.0 : std::atan2(dir.Y(), dir.X());
    double travel = this->speed * dt;
    ignition::math::Vector3d newPos;
    if (travel >= diff.Length())
    {
      newPos = this->waypoints[this->targetIndex];
    }
    else
    {
      newPos = pos + dir * travel;
    }
    this->model->SetWorldPose(
      ignition::math::Pose3d(newPos.X(), newPos.Y(), newPos.Z(), 0.0, 0.0, yaw));
    this->model->SetLinearVel(travel >= diff.Length()
      ? ignition::math::Vector3d::Zero
      : dir * this->speed);
  }

  struct DatasetPoint
  {
    int step = 0;
    double x = 0.0;
    double y = 0.0;
    double z = 0.0;
    double yawRad = 0.0;
    double yawDeg = 0.0;
    double capturedX = 0.0;
    double capturedY = 0.0;
    double capturedZ = 0.0;
    unsigned int captureFrame = 0;
    double capturedYawRad = 0.0;
    double capturedYawDeg = 0.0;
    std::string imageName;
    bool captured = false;
  };

  int EnvInt(const char *name, int fallback)
  {
    const char *value = std::getenv(name);
    if (!value || value[0] == '\0')
      return fallback;
    try
    {
      return std::stoi(value);
    }
    catch (...)
    {
      return fallback;
    }
  }

  double EnvDouble(const char *name, double fallback)
  {
    const char *value = std::getenv(name);
    if (!value || value[0] == '\0')
      return fallback;
    try
    {
      return std::stod(value);
    }
    catch (...)
    {
      return fallback;
    }
  }

  bool FrameLooksUsable(
    const unsigned char *data,
    unsigned int width,
    unsigned int height,
    unsigned int depth,
    std::string &reason)
  {
    if (!data || width == 0 || height == 0 || depth < 3)
    {
      reason = "empty image buffer";
      return false;
    }

    const size_t pixelCount =
      static_cast<size_t>(width) * static_cast<size_t>(height);
    unsigned int globalMin = 255;
    unsigned int globalMax = 0;
    size_t grayPixels = 0;
    double lumaSum = 0.0;
    double lumaSqSum = 0.0;

    const unsigned int tilesX = 8;
    const unsigned int tilesY = 8;
    std::vector<size_t> tilePixels(tilesX * tilesY, 0);
    std::vector<size_t> tileGrayPixels(tilesX * tilesY, 0);
    std::vector<unsigned int> tileMin(tilesX * tilesY, 255);
    std::vector<unsigned int> tileMax(tilesX * tilesY, 0);
    std::vector<double> tileLumaSum(tilesX * tilesY, 0.0);
    std::vector<double> tileLumaSqSum(tilesX * tilesY, 0.0);
    std::vector<size_t> rowBufferPixels(height, 0);
    std::vector<size_t> columnBufferPixels(width, 0);

    for (unsigned int y = 0; y < height; ++y)
    {
      for (unsigned int x = 0; x < width; ++x)
      {
        const size_t offset =
          (static_cast<size_t>(y) * static_cast<size_t>(width) + x) * depth;
        const unsigned int r = static_cast<unsigned int>(data[offset]);
        const unsigned int g = static_cast<unsigned int>(data[offset + 1]);
        const unsigned int b = static_cast<unsigned int>(data[offset + 2]);
        const unsigned int cmin = std::min(r, std::min(g, b));
        const unsigned int cmax = std::max(r, std::max(g, b));
        const double luma = (static_cast<double>(r) + g + b) / 3.0;
        const unsigned int tileX = std::min((x * tilesX) / width, tilesX - 1);
        const unsigned int tileY = std::min((y * tilesY) / height, tilesY - 1);
        const size_t tileIndex = static_cast<size_t>(tileY) * tilesX + tileX;

        globalMin = std::min(globalMin, cmin);
        globalMax = std::max(globalMax, cmax);
        lumaSum += luma;
        lumaSqSum += luma * luma;
        ++tilePixels[tileIndex];
        tileMin[tileIndex] = std::min(tileMin[tileIndex], cmin);
        tileMax[tileIndex] = std::max(tileMax[tileIndex], cmax);
        tileLumaSum[tileIndex] += luma;
        tileLumaSqSum[tileIndex] += luma * luma;

        const bool isGray =
          (cmax - cmin <= static_cast<unsigned int>(this->grayDelta)) &&
          (luma >= this->grayMin) &&
          (luma <= this->grayMax);
        if (isGray)
        {
          ++grayPixels;
          ++tileGrayPixels[tileIndex];
        }
        if (r == 128u && g == 128u && b == 128u)
        {
          ++rowBufferPixels[y];
          ++columnBufferPixels[x];
        }
      }
    }

    const unsigned int rgbRange = globalMax - globalMin;
    const double mean = lumaSum / std::max<size_t>(pixelCount, 1u);
    const double variance =
      std::max(0.0, lumaSqSum / std::max<size_t>(pixelCount, 1u) - mean * mean);
    const double lumaStd = std::sqrt(variance);
    const double grayRatio =
      static_cast<double>(grayPixels) / std::max<size_t>(pixelCount, 1u);

    if (rgbRange < static_cast<unsigned int>(this->minRgbRange))
    {
      std::ostringstream out;
      out << "near-uniform image rgb_range=" << rgbRange
          << " luma_std=" << lumaStd;
      reason = out.str();
      return false;
    }

    if (grayRatio > this->grayMaxRatio)
    {
      std::ostringstream out;
      out << "global gray ratio too high ratio=" << grayRatio;
      reason = out.str();
      return false;
    }

    for (unsigned int y = 0; y < height; ++y)
    {
      const double ratio = static_cast<double>(rowBufferPixels[y]) / width;
      if (ratio > this->grayScanlineRatio)
      {
        std::ostringstream out;
        out << "gray render-buffer row ratio too high row=" << y
            << " ratio=" << ratio;
        reason = out.str();
        return false;
      }
    }
    for (unsigned int x = 0; x < width; ++x)
    {
      const double ratio = static_cast<double>(columnBufferPixels[x]) / height;
      if (ratio > this->grayScanlineRatio)
      {
        std::ostringstream out;
        out << "gray render-buffer column ratio too high column=" << x
            << " ratio=" << ratio;
        reason = out.str();
        return false;
      }
    }

    for (size_t i = 0; i < tilePixels.size(); ++i)
    {
      if (tilePixels[i] == 0)
        continue;
      const double tileRatio =
        static_cast<double>(tileGrayPixels[i]) / static_cast<double>(tilePixels[i]);
      const double tileMean =
        tileLumaSum[i] / static_cast<double>(tilePixels[i]);
      const double tileVariance =
        std::max(0.0,
                 tileLumaSqSum[i] / static_cast<double>(tilePixels[i]) -
                 tileMean * tileMean);
      const double tileStd = std::sqrt(tileVariance);
      const unsigned int tileRange = tileMax[i] - tileMin[i];
      if (tileRatio > this->grayTileRatio &&
          tileStd < this->minLumaStd &&
          tileRange < static_cast<unsigned int>(this->minRgbRange))
      {
        std::ostringstream out;
        out << "gray tile ratio too high tile=" << i
            << " ratio=" << tileRatio
            << " tile_range=" << tileRange
            << " tile_luma_std=" << tileStd;
        reason = out.str();
        return false;
      }
    }

    return true;
  }

  struct DatasetTrajectory
  {
    std::string name;
    std::string path;
    std::vector<DatasetPoint> points;
  };

  std::vector<std::string> SplitCsvLine(const std::string &line)
  {
    std::vector<std::string> cols;
    std::string col;
    std::istringstream ss(line);
    while (std::getline(ss, col, ','))
      cols.push_back(col);
    return cols;
  }

  void LoadDatasetTrajectories()
  {
    this->datasetTrajectories.clear();

    std::vector<std::string> csvFiles;
    if (!this->datasetTrajectoryFile.empty())
    {
      if (boost::filesystem::exists(this->datasetTrajectoryFile))
        csvFiles.push_back(this->datasetTrajectoryFile);
    }
    else
    {
      if (!boost::filesystem::exists(this->trajectoryDir))
        return;

      boost::filesystem::directory_iterator end;
      for (boost::filesystem::directory_iterator it(this->trajectoryDir); it != end; ++it)
      {
        if (boost::filesystem::is_regular_file(it->path()) && it->path().extension() == ".csv")
          csvFiles.push_back(it->path().string());
      }
      std::sort(csvFiles.begin(), csvFiles.end());
    }

    for (const std::string &path : csvFiles)
    {
      std::ifstream in(path);
      std::string line;
      if (!std::getline(in, line))
        continue;

      DatasetTrajectory traj;
      boost::filesystem::path p(path);
      traj.name = p.stem().string();
      traj.path = path;

      while (std::getline(in, line))
      {
        if (line.empty())
          continue;
        std::vector<std::string> cols = this->SplitCsvLine(line);
        if (cols.size() < 5)
          continue;

        DatasetPoint pt;
        try
        {
          pt.step = std::stoi(cols[0]);
          pt.x = std::stod(cols[1]);
          pt.y = std::stod(cols[2]);
          pt.z = std::stod(cols[3]);
          pt.yawRad = std::stod(cols[4]);
          pt.yawDeg = cols.size() > 5 ? std::stod(cols[5]) : pt.yawRad * 180.0 / M_PI;
        }
        catch (...)
        {
          continue;
        }
        traj.points.push_back(pt);
      }

      if (!traj.points.empty())
        this->datasetTrajectories.push_back(traj);
    }

    gzmsg << "[SimpleDronePlugin] loaded " << this->datasetTrajectories.size()
          << " dataset trajector"
          << (this->datasetTrajectories.size() == 1 ? "y" : "ies")
          << " from "
          << (this->datasetTrajectoryFile.empty()
                ? this->trajectoryDir
                : this->datasetTrajectoryFile)
          << std::endl;
  }

  bool BeginDatasetTrajectory(size_t index)
  {
    if (index >= this->datasetTrajectories.size())
      return false;

    this->currentDatasetTrajectory = index;
    this->waypoints.clear();
    const DatasetTrajectory &traj = this->datasetTrajectories[index];
    for (const DatasetPoint &pt : traj.points)
      this->waypoints.push_back(ignition::math::Vector3d(pt.x, pt.y, pt.z));

    this->targetIndex = 0;
    this->returningToStart = false;
    this->captureYaw = 0.0;
    this->settling = true;
    this->settleBaselineSet = false;
    this->captureFailureWarned = false;
    this->settleTimeoutWarned = false;
    this->physicalRejectCount = 0;
    this->physicalFallbackToSweep = false;
    this->lastTime = this->world->SimTime();
    gzmsg << "[SimpleDronePlugin] dataset trajectory "
          << (index + 1) << "/" << this->datasetTrajectories.size()
          << ": " << traj.name << " (" << traj.points.size()
          << " points)" << std::endl;

    for (const std::string &folder : this->folderNames)
      boost::filesystem::create_directories(this->imageDir + "/" + traj.name + "/" + folder);

    return true;
  }

  bool BeginDatasetTrajectoryAtStart(size_t index)
  {
    if (index >= this->datasetTrajectories.size())
      return false;

    const DatasetPoint &start = this->datasetTrajectories[index].points.front();
    this->model->SetWorldPose(
      ignition::math::Pose3d(start.x, start.y, start.z, 0.0, 0.0, 0.0));
    this->model->SetLinearVel(ignition::math::Vector3d::Zero);
    return this->BeginDatasetTrajectory(index);
  }

  void AdvanceDatasetAfterCapture(const ignition::math::Pose3d &snapped)
  {
    if (this->currentDatasetTrajectory >= this->datasetTrajectories.size())
      return;

    DatasetTrajectory &traj = this->datasetTrajectories[this->currentDatasetTrajectory];
    this->RewriteDatasetTrajectoryCsv(traj);

    if (this->targetIndex + 1 < traj.points.size())
    {
      ++this->targetIndex;
      this->captureYaw = 0.0;
      this->settling = true;
      this->settleBaselineSet = false;
      this->captureFailureWarned = false;
      this->settleTimeoutWarned = false;
      this->physicalRejectCount = 0;
      this->lastTime = this->world->SimTime();
      return;
    }

    this->FinishTour(snapped);
  }

  void RewriteDatasetTrajectoryCsv(const DatasetTrajectory &traj)
  {
    std::ofstream out(traj.path, std::ios::out | std::ios::trunc);
    out << "step,x,y,z,yaw_rad,yaw_deg,"
           "capture_frame,captured_yaw_rad,captured_yaw_deg,"
           "front_image,down_image,left_image,right_image\n";
    for (const DatasetPoint &pt : traj.points)
    {
      out << pt.step << ','
          << (pt.captured ? pt.capturedX : pt.x) << ','
          << (pt.captured ? pt.capturedY : pt.y) << ','
          << (pt.captured ? pt.capturedZ : pt.z) << ','
          << pt.yawRad << ','
          << pt.yawDeg << ',';
      if (pt.captured)
      {
        out << pt.captureFrame << ','
            << pt.capturedYawRad << ','
            << pt.capturedYawDeg << ','
            << pt.imageName << ','
            << pt.imageName << ','
            << pt.imageName << ','
            << pt.imageName << '\n';
      }
      else
      {
        out << ",,,,,,\n";
      }
    }
    out.flush();
    gzmsg << "[SimpleDronePlugin] updated dataset trajectory CSV: "
          << traj.path << std::endl;
  }

  bool TryLoadCommand()
  {
    if (this->commandFile.empty() || !boost::filesystem::exists(this->commandFile))
      return false;

    std::time_t mtime = boost::filesystem::last_write_time(this->commandFile);
    std::ifstream in(this->commandFile);
    std::ostringstream buf;
    buf << in.rdbuf();
    std::string commandText = buf.str();

    if (mtime <= this->lastCommandMTime && commandText == this->lastCommandText)
      return false;

    std::string line;
    std::istringstream lines(commandText);
    while (std::getline(lines, line))
    {
      if (line.empty() || line.find("x") != std::string::npos)
        continue;

      for (char &c : line)
      {
        if (c == ',')
          c = ' ';
      }

      std::istringstream ss(line);
      double x = 0.0, y = 0.0, z = 0.0, yaw = 0.0;
      if (!(ss >> x >> y >> z >> yaw))
        continue;

      this->commandTarget = ignition::math::Vector3d(
        std::max(-7.0, std::min(6.5, x)),
        std::max(-4.0, std::min(4.0, y)),
        std::max(1.2, std::min(1.8, z)));
      this->commandYaw = yaw;
      this->lastCommandMTime = mtime;
      this->lastCommandText = commandText;
      gzmsg << "[SimpleDronePlugin] command target: "
            << this->commandTarget.X() << ", "
            << this->commandTarget.Y() << ", "
            << this->commandTarget.Z() << ", yaw="
            << this->commandYaw << std::endl;
      return true;
    }

    this->lastCommandMTime = mtime;
    this->lastCommandText = commandText;
    gzerr << "[SimpleDronePlugin] command file changed but no valid x,y,z,yaw found: "
          << this->commandFile << std::endl;
    return false;
  }

  // Called once the final waypoint has been captured. The frame for the last
  // waypoint is already saved by the capture-on-arrival branch, so this only
  // closes the trajectory file and latches the tour as complete (no further
  // motion or recording).
  void FinishTour(const ignition::math::Pose3d &finalPose)
  {
    if (this->trajFile.is_open())
      this->trajFile.close();

    this->holdPose = finalPose;
    this->model->SetLinearVel(ignition::math::Vector3d::Zero);
    this->tourComplete = true;

    gzmsg << "[SimpleDronePlugin] trajectory complete: visited "
          << this->waypoints.size() << " waypoints, saved "
          << this->frameCounter << " frame sets. Recording stopped."
          << std::endl;

    if (this->quitOnFinish)
    {
      if (!this->doneFile.empty())
      {
        std::ofstream done(this->doneFile, std::ios::out | std::ios::trunc);
        done << "done\n";
        done.flush();
        gzmsg << "[SimpleDronePlugin] wrote done file: "
              << this->doneFile << std::endl;
      }
      gzmsg << "[SimpleDronePlugin] SIMPLE_DRONE_QUIT_ON_FINISH set; shutdown requested."
            << std::endl;
      gazebo::shutdown();
    }
  }

private:
  physics::ModelPtr model;
  physics::WorldPtr world;
  event::ConnectionPtr updateConnection;

  // Cameras (front / down / left / right).
  std::vector<std::string> cameraNames;   // sensor names, must match the SDF
  std::vector<std::string> folderNames;   // output sub-folder per camera
  std::vector<sensors::CameraSensorPtr> cameras;
  std::vector<event::ConnectionPtr> imageConnections;
  bool camerasReady;
  std::string imageDir;
  double capturePeriod;          // legacy, unused (capture is per-waypoint now)
  common::Time lastCaptureTime;  // legacy, unused
  unsigned int frameCounter;
  std::ofstream trajFile;

  std::vector<ignition::math::Vector3d> waypoints;
  unsigned int targetIndex;
  // Settle-then-capture state: while parked on a waypoint we wait for the
  // cameras to re-render from the pinned pose before saving, so each image
  // matches its logged coordinate exactly.
  bool settling;                 // true while parked on a waypoint awaiting capture
  bool settleBaselineSet;        // have we latched the pre-settle render times?
  bool captureFailureWarned;     // avoid spamming camera readiness diagnostics
  bool settleTimeoutWarned;      // avoid spamming settle timeout diagnostics
  double captureYaw;             // heading to hold while settling (travel heading)
  std::vector<common::Time> baseRenderTime;  // per-camera render time at snap moment
  common::Time settleStartTime;
  const double settleTimeout = 10.0;
  double speed;
  common::Time lastTime;

  // One-shot tour state: once the last waypoint is reached the drone hovers
  // at `holdPose` and stops capturing.
  bool tourComplete;
  ignition::math::Pose3d holdPose;

  // Dataset trajectory mode. Trajectories are read from
  // <datasetRoot>/trajectory/*.csv. Captures are saved into
  // <datasetRoot>/images/<trajectory_name>/images_{front,down,left,right}/.
  bool datasetMode;
  bool quitOnFinish;
  std::string doneFile;
  bool returningToStart;
  std::string datasetRoot;
  std::string trajectoryDir;
  std::string datasetTrajectoryFile;
  std::vector<DatasetTrajectory> datasetTrajectories;
  size_t currentDatasetTrajectory;

  // File-based Python control mode. After each captured frame set, the drone
  // holds position until Python writes x,y,z,yaw to commandFile.
  bool commandMode;
  bool waitingForCommand;
  std::string commandFile;
  std::string lastCommandText;
  std::time_t lastCommandMTime;
  ignition::math::Vector3d commandTarget;
  double commandYaw;

  bool rejectGrayImages;
  int grayDelta;
  int grayMin;
  int grayMax;
  double grayMaxRatio;
  double grayTileRatio;
  double grayScanlineRatio;
  double minLumaStd;
  int minRgbRange;
  double viewDownTilt;
  double minValidImageRatio;
  unsigned int grayRejectWarnCounter;

  std::mutex frameMutex;
  std::vector<CachedFrame> latestFrames;
  bool physicalSequenceInProgress;
  size_t physicalViewIndex;
  bool physicalWarned;
  bool physicalViewArmed;
  common::Time physicalBaselineTime;
  unsigned int physicalRejectCount;
  bool physicalFallbackToSweep;
  std::vector<CachedFrame> physicalFrames;
  bool sweepInProgress;
  bool sweepPoseSet;
  size_t sweepViewIndex;
  unsigned int sweepYawAttempt;
  bool sweepTimeoutWarned;
  common::Time sweepStartTime;
  common::Time sweepBaselineFrameTime;
  ignition::math::Pose3d sweepBasePose;
  std::vector<CachedFrame> sweepFrames;
};

GZ_REGISTER_MODEL_PLUGIN(SimpleDronePlugin)
}