bywind-viz 0.2.0

GUI editor and search visualiser for the `bywind` sailing-route optimiser.
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
use super::{
    BoatConfig, SCALE_MAX, Tool, Topology, WaypointCount, draw_fuel_curve, format_delta,
    format_duration_breakdown, format_fitness_magnitude, format_fuel, format_land_km,
    format_scale_value, int_slider_with_steppers, log_slider_with_steppers, min_render_scale,
    paint_endpoint_highlight, parse_scale_value,
};
use crate::app::BywindApp;
use crate::search::SummarySelection;

impl BywindApp {
    /// Right-side stats panel. Always rendered (so it acts as the
    /// central panel's right boundary even before any search). With no
    /// stats yet, the Summary / Segments headings show with a single
    /// "(no search yet)" line each; with a completed search, the full
    /// Summary totals + benchmark deltas and scrollable per-segment
    /// breakdown render in the bottom-up layout.
    pub(crate) fn render_stats_panel(&mut self, ui: &mut egui::Ui) {
        let mut toggle_summary = false;
        // Resolve the current summary view-source up front so both the
        // Summary block and the Segments scroll below it agree. A
        // dangling `Realization(k)` (cohort shrank but we haven't
        // observed it yet via the poll arm) falls through to None
        // rather than panicking.
        let (stats, selected_fitness) = match self.outputs.summary_selection {
            SummarySelection::Gbest => (
                self.outputs.segment_stats.clone(),
                self.outputs.best_fitness,
            ),
            SummarySelection::Realization(k) => match self.outputs.realization_runs.get(k) {
                Some(run) => (Some(run.segment_stats.clone()), Some(run.fitness)),
                None => (None, None),
            },
        };
        // Top-down layout inside the right panel: Summary + view selector
        // size to their actual current content at the top, the Segments
        // ScrollArea fills the rest. The visual flip relative to the old
        // "Summary at bottom" layout is intentional — pinning the summary
        // via `Panel::bottom` regressed: the panel state's stored `rect`
        // gets reused on each frame, so a one-time-tall summary (ensemble
        // spread + bench grid + ~30-row route) locked the panel at the
        // tall height and squished the segments list above it. Nested
        // `bottom_up` + `top_down` sub-uis had cursor / rect-overlap
        // issues we couldn't tame. A plain top-down flow + a single
        // ScrollArea with `auto_shrink([_, false])` is the version that
        // actually distributes the leftover height to the scroll, frame
        // after frame.
        egui::Panel::right("stats_panel").show_inside(ui, |ui| {
            toggle_summary = self.render_stats_summary(ui, stats.as_deref(), selected_fitness);
            ui.separator();
            ui.heading("Segments");
            ui.separator();
            egui::ScrollArea::vertical()
                .id_salt("segment_stats_scroll")
                .auto_shrink([true, false])
                .show(ui, |ui| match stats.as_deref() {
                    Some(stats) => self.render_segment_rows(ui, stats),
                    None => {
                        ui.label("(no search yet)");
                    }
                });
        });
        if toggle_summary {
            self.view.total_time_breakdown = !self.view.total_time_breakdown;
            self.view.total_fuel_tonnes = !self.view.total_fuel_tonnes;
        }
    }

    /// Top-down summary block for the right-panel's bottom sub-panel:
    /// the source selector (Main gbest vs per realization), totals
    /// for the selected source, and — only when viewing the main
    /// gbest — the benchmark / ensemble-spread blocks. Returns true
    /// if the Summary heading was right-clicked this frame so the
    /// caller can toggle the unit display.
    fn render_stats_summary(
        &mut self,
        ui: &mut egui::Ui,
        stats: Option<&[bywind::SegmentMetrics]>,
        selected_fitness: Option<f64>,
    ) -> bool {
        let toggle_summary = ui.heading("Summary").secondary_clicked();
        ui.separator();
        // View selector anchored right under the heading so it stays put
        // when the rest of the summary's height changes (bench grid +
        // ensemble spread vs. realization-comparison grid have very
        // different vertical footprints). Only rendered when there's
        // actually a cohort to pick from.
        if !self.outputs.realization_runs.is_empty() {
            self.render_summary_selector(ui);
            ui.separator();
        }
        let Some(stats) = stats else {
            ui.label("(no search yet)");
            return toggle_summary;
        };
        let total_time: f64 = stats.iter().map(|m| m.time).sum();
        let total_fuel: f64 = stats.iter().map(|m| m.fuel).sum();
        let total_land_metres: f64 = stats.iter().map(|m| m.land_metres).sum();
        let is_gbest = self.outputs.summary_selection == SummarySelection::Gbest;
        let bake_duration = self.outputs.bake_duration;
        let search_duration = self.outputs.search_duration;
        let total_time_str = if self.view.total_time_breakdown {
            format_duration_breakdown(total_time)
        } else {
            format!("{total_time:.1}s")
        };
        let total_fuel_str = format_fuel(total_fuel, self.view.total_fuel_tonnes);
        let segment_in_tonnes = self.view.total_fuel_tonnes;
        ui.label(format!("Total time: {total_time_str}"));
        ui.label(format!("Total fuel: {total_fuel_str}"));
        ui.label(format!("Total land: {}", format_land_km(total_land_metres)));
        self.render_wind_horizon_warning(ui, total_time);
        // Bake / Search timings only describe the main search. We
        // don't track per-realization timings (the cohort shares a
        // single bake and the K wallclock is dominated by the loop
        // total, not per-realization), so hide both when the user has
        // switched the dropdown to a realization.
        if is_gbest {
            if let Some(d) = bake_duration {
                ui.label(format!("Bake:       {:.2}s", d.as_secs_f64()));
            }
            if let Some(d) = search_duration {
                ui.label(format!("Search:     {:.2}s", d.as_secs_f64()));
            }
        }
        if let Some(fit) = selected_fitness {
            let fit_str = if self.view.total_time_breakdown {
                format_fitness_magnitude(fit)
            } else {
                format!("{fit:.4}")
            };
            ui.label(format!("Fitness:    {fit_str}"));
        }
        // Benchmark + ensemble-spread blocks are both about the main
        // converged gbest — they don't make sense for a realization's
        // independent search. Instead, for a realization view we show
        // a "Main:" delta grid so the user can read how the
        // per-realization optimum compares to the ensemble-chosen
        // route (analogous to Main view's Bench grid).
        if !is_gbest {
            self.render_main_comparison(
                ui,
                total_time,
                total_fuel,
                total_land_metres,
                selected_fitness,
                segment_in_tonnes,
            );
            return toggle_summary;
        }
        // Benchmark group sits below the gbest summary, separated by a
        // divider. The two cells per row are split into a Grid so the
        // "(PSO X% better)" deltas land in their own column and stay
        // vertically aligned even when the bench labels have wildly
        // different lengths (`"Bench time: 1h32m"` vs `"Bench fuel: 12.345 t"`).
        if let Some(b) = self.outputs.benchmark.as_ref() {
            ui.separator();
            egui::Grid::new("bench_pso_grid")
                .num_columns(2)
                .spacing([12.0, 4.0])
                .show(ui, |ui| {
                    let bench_time_str = if self.view.total_time_breakdown {
                        format_duration_breakdown(b.total_time)
                    } else {
                        format!("{:.1}s", b.total_time)
                    };
                    ui.label(format!("Bench time: {bench_time_str}"));
                    ui.label(format!(
                        "({})",
                        format_delta(total_time, b.total_time, false, "PSO"),
                    ));
                    ui.end_row();

                    let bench_fuel_str = format_fuel(b.total_fuel, segment_in_tonnes);
                    ui.label(format!("Bench fuel: {bench_fuel_str}"));
                    ui.label(format!(
                        "({})",
                        format_delta(total_fuel, b.total_fuel, false, "PSO"),
                    ));
                    ui.end_row();

                    ui.label(format!(
                        "Bench land: {}",
                        format_land_km(b.total_land_metres)
                    ));
                    ui.label(format!(
                        "({})",
                        format_delta(total_land_metres, b.total_land_metres, false, "PSO"),
                    ));
                    ui.end_row();

                    let bench_fit_str = if self.view.total_time_breakdown {
                        format_fitness_magnitude(b.fitness)
                    } else {
                        format!("{:.4}", b.fitness)
                    };
                    ui.label(format!("Bench fit:  {bench_fit_str}"));
                    if let Some(fit) = selected_fitness {
                        ui.label(format!("({})", format_delta(fit, b.fitness, true, "PSO")));
                    } else {
                        ui.label("");
                    }
                    ui.end_row();
                });
        }
        if let Some(ens) = self.outputs.ensemble.as_ref() {
            self.render_ensemble_spread(ui, ens, segment_in_tonnes);
        }
        toggle_summary
    }

    /// Warn when the route's total duration exceeds the loaded wind's
    /// data horizon. Past `(nt-1) · t_step`, the time query in
    /// `BakedWindMap::sample_wind` enters a crossfade tail (frame N-1
    /// → frame 0) and then loops, so a route longer than the data is
    /// being evaluated against repeated / synthesized weather rather
    /// than the actual forecast. Fine for smoke testing the pipeline;
    /// misleading when judging route quality. No-op when no search
    /// has run, when the baked map has < 2 frames (no time axis),
    /// or when the route fits inside the horizon.
    fn render_wind_horizon_warning(&self, ui: &mut egui::Ui, total_time: f64) {
        let Some(baked) = self.outputs.baked_wind_map.as_ref() else {
            return;
        };
        if baked.nt() < 2 {
            return;
        }
        let data_end = (baked.nt() - 1) as f64 * baked.t_step_seconds();
        if total_time <= data_end {
            return;
        }
        let crossfade = baked.crossfade_seconds();
        let cycle = data_end + crossfade;
        let loops = if cycle > 0.0 { total_time / cycle } else { 0.0 };
        // Mustard / amber palette — visible against the default egui
        // panel fill without being as harsh as the SDF-overlay red.
        let warn_color = egui::Color32::from_rgb(220, 180, 60);
        ui.colored_label(
            warn_color,
            format!(
                "(route runs {} past the {} wind horizon — looped ~{loops:.1}×)",
                format_duration_breakdown(total_time - data_end),
                format_duration_breakdown(data_end),
            ),
        )
        .on_hover_text(format!(
            "The loaded wind covers {} of real data; the route runs {}. \
             Past the data end the search interpolates between frame N-1 \
             and frame 0 across a {} crossfade, then loops every {}. A \
             route that exceeds the wind horizon is being evaluated \
             against repeated / synthesized weather, not actual forecast \
             data — fine for smoke tests, unreliable for judging route \
             quality. Fetch a longer-horizon wind dataset to silence this.",
            format_duration_breakdown(data_end),
            format_duration_breakdown(total_time),
            format_duration_breakdown(crossfade),
            format_duration_breakdown(cycle),
        ));
    }

    /// Counterpart to the Main view's Bench grid, shown on a
    /// realization view. The selected realization's totals are passed
    /// in (already summed by the caller); we sum the main gbest's
    /// totals from `outputs.segment_stats` here and render each row as
    /// "Main <metric>:  <value>  (Main X% better/worse)". The
    /// parenthetical reads from *Main's* perspective so it qualifies
    /// the "Main <metric>:" label on the same row — "Main 1.1% worse"
    /// means the main gbest's metric is 1.1% worse than the selected
    /// realization's. Equivalent in content to "Realization X%
    /// better" but locally consistent with the row label.
    ///
    /// Hidden when the main gbest's metadata isn't around — re-load
    /// of an old session before any search runs, for example.
    fn render_main_comparison(
        &self,
        ui: &mut egui::Ui,
        realization_total_time: f64,
        realization_total_fuel: f64,
        realization_total_land: f64,
        realization_fitness: Option<f64>,
        segment_in_tonnes: bool,
    ) {
        let Some(main_stats) = self.outputs.segment_stats.as_deref() else {
            return;
        };
        let main_total_time: f64 = main_stats.iter().map(|m| m.time).sum();
        let main_total_fuel: f64 = main_stats.iter().map(|m| m.fuel).sum();
        let main_total_land: f64 = main_stats.iter().map(|m| m.land_metres).sum();
        let main_fitness = self.outputs.best_fitness;
        ui.separator();
        egui::Grid::new("main_compare_grid")
            .num_columns(2)
            .spacing([12.0, 4.0])
            .show(ui, |ui| {
                let main_time_str = if self.view.total_time_breakdown {
                    format_duration_breakdown(main_total_time)
                } else {
                    format!("{main_total_time:.1}s")
                };
                ui.label(format!("Main time: {main_time_str}"));
                // Args are `(subject, other, larger_is_better, label)`;
                // pass main first so the percentage qualifies "Main".
                ui.label(format!(
                    "({})",
                    format_delta(main_total_time, realization_total_time, false, "Main"),
                ));
                ui.end_row();

                let main_fuel_str = format_fuel(main_total_fuel, segment_in_tonnes);
                ui.label(format!("Main fuel: {main_fuel_str}"));
                ui.label(format!(
                    "({})",
                    format_delta(main_total_fuel, realization_total_fuel, false, "Main"),
                ));
                ui.end_row();

                ui.label(format!("Main land: {}", format_land_km(main_total_land),));
                ui.label(format!(
                    "({})",
                    format_delta(main_total_land, realization_total_land, false, "Main"),
                ));
                ui.end_row();

                if let Some(mf) = main_fitness {
                    let main_fit_str = if self.view.total_time_breakdown {
                        format_fitness_magnitude(mf)
                    } else {
                        format!("{mf:.4}")
                    };
                    ui.label(format!("Main fit:  {main_fit_str}"));
                    if let Some(rf) = realization_fitness {
                        // `larger_is_better=true` flips the delta
                        // sign (fitness is negated cost — higher is
                        // better), matching the Bench grid's Fit row.
                        ui.label(format!("({})", format_delta(mf, rf, true, "Main")));
                    } else {
                        ui.label("");
                    }
                    ui.end_row();
                }
            });
    }

    /// View-source selector: a combo box that picks between the main
    /// converged gbest and any of the per-realization cohort entries.
    /// Hidden when there's no realization cohort to choose from —
    /// nothing for the user to pick.
    fn render_summary_selector(&mut self, ui: &mut egui::Ui) {
        if self.outputs.realization_runs.is_empty() {
            return;
        }
        let current_label: String = match self.outputs.summary_selection {
            SummarySelection::Gbest => "Main (gbest)".to_owned(),
            SummarySelection::Realization(k) => self
                .outputs
                .realization_runs
                .get(k)
                .map(|run| format!("Realization: {}", run.name))
                .unwrap_or_else(|| "Main (gbest)".to_owned()),
        };
        ui.horizontal(|ui| {
            ui.label("View:");
            egui::ComboBox::from_id_salt("summary_view_source")
                .selected_text(current_label)
                .show_ui(ui, |ui| {
                    ui.selectable_value(
                        &mut self.outputs.summary_selection,
                        SummarySelection::Gbest,
                        "Main (gbest)",
                    );
                    for (idx, run) in self.outputs.realization_runs.iter().enumerate() {
                        ui.selectable_value(
                            &mut self.outputs.summary_selection,
                            SummarySelection::Realization(idx),
                            format!("Realization: {}", run.name),
                        );
                    }
                });
        });
    }

    /// Per-member spread for the converged gbest path under an ensemble
    /// search. Mean / min / max / sd of fitness, time, and fuel across
    /// members, plus the best- and worst-case member names — narrow
    /// spread → robust; wide spread → brittle.
    fn render_ensemble_spread(
        &self,
        ui: &mut egui::Ui,
        ens: &bywind::EnsembleSpread,
        segment_in_tonnes: bool,
    ) {
        let k = ens.per_member.len();
        if k == 0 {
            return;
        }
        let (fit_mean, fit_min, fit_max, fit_sd) = ens.stats(|m| m.fitness);
        let (time_mean, time_min, time_max, time_sd) = ens.stats(|m| m.time_s);
        let (fuel_mean, fuel_min, fuel_max, fuel_sd) = ens.stats(|m| m.fuel_kg);
        let fmt_time = |t: f64| {
            if self.view.total_time_breakdown {
                format_duration_breakdown(t)
            } else {
                format!("{t:.1}s")
            }
        };
        let fmt_fit = |f: f64| {
            if self.view.total_time_breakdown {
                format_fitness_magnitude(f)
            } else {
                format!("{f:.4}")
            }
        };
        ui.separator();
        ui.label(egui::RichText::new(format!("Ensemble spread (K={k})")).strong());
        egui::Grid::new("ensemble_spread_grid")
            .num_columns(2)
            .spacing([12.0, 4.0])
            .show(ui, |ui| {
                ui.label("Fit  (mean / sd):");
                ui.label(format!("{}  ± {}", fmt_fit(fit_mean), fmt_fit(fit_sd)));
                ui.end_row();
                ui.label("Fit  (min / max):");
                ui.label(format!("{} / {}", fmt_fit(fit_min), fmt_fit(fit_max)));
                ui.end_row();
                ui.label("Time (mean / sd):");
                ui.label(format!("{}  ± {:.0}s", fmt_time(time_mean), time_sd));
                ui.end_row();
                ui.label("Time (min / max):");
                ui.label(format!("{} / {}", fmt_time(time_min), fmt_time(time_max)));
                ui.end_row();
                ui.label("Fuel (mean / sd):");
                ui.label(format!(
                    "{}  ± {}",
                    format_fuel(fuel_mean, segment_in_tonnes),
                    format_fuel(fuel_sd, segment_in_tonnes),
                ));
                ui.end_row();
                ui.label("Fuel (min / max):");
                ui.label(format!(
                    "{} / {}",
                    format_fuel(fuel_min, segment_in_tonnes),
                    format_fuel(fuel_max, segment_in_tonnes),
                ));
                ui.end_row();
            });
        let worst = ens.per_member.iter().min_by(|a, b| {
            a.fitness
                .partial_cmp(&b.fitness)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        let best = ens.per_member.iter().max_by(|a, b| {
            a.fitness
                .partial_cmp(&b.fitness)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        if let (Some(w), Some(b)) = (worst, best) {
            ui.label(format!(
                "Worst: {} ({})    Best: {} ({})",
                w.name,
                fmt_fit(w.fitness),
                b.name,
                fmt_fit(b.fitness),
            ));
        }
    }

    fn render_segment_rows(&self, ui: &mut egui::Ui, stats: &[bywind::SegmentMetrics]) {
        let segment_in_tonnes = self.view.total_fuel_tonnes;
        for (i, m) in stats.iter().enumerate() {
            ui.label(format!(
                "[{i}] {:.1}s\nmotor={:.2}\nfuel={}\nspeed={:.1} km/h",
                m.time,
                m.mcr_01,
                format_fuel(m.fuel, segment_in_tonnes),
                m.speed_kmh,
            ));
            ui.separator();
        }
    }

    /// Frame index covering the end of the current route's ETA, scaled
    /// by `step_seconds`. Used to extend the time slider's range past
    /// the loaded wind-map data when a search has produced a route
    /// that runs longer than the data covers. Returns 0 if no route
    /// is loaded or the ETA is non-finite.
    fn route_max_frame(&self, step_seconds: f32) -> usize {
        let Some(re) = self.outputs.route_evolution.as_ref() else {
            return 0;
        };
        let Some(gbest) = re.gbest_at(self.outputs.iteration) else {
            return 0;
        };
        // Final waypoint's `t` is the route's total elapsed time. ETA
        // is usually monotonic but we max over the whole slice to
        // tolerate noisy mid-iteration paths.
        let route_eta = gbest.ts.iter().copied().fold(0.0_f64, f64::max) as f32;
        if !route_eta.is_finite() || step_seconds <= 0.0 {
            return 0;
        }
        (route_eta / step_seconds).ceil() as usize
    }

    /// Left-side tools panel: tool picker, generate sub-panel, time slider,
    /// search-parameter grid and Run Search button, view-scale sliders.
    pub(crate) fn render_tools_panel(&mut self, ui: &mut egui::Ui) {
        egui::Panel::left("tools_panel").show_inside(ui, |ui| {
            // Wrap the whole panel body in a ScrollArea so expanding the
            // Boat / Generate / Advanced collapsing headers can't push
            // the panel's content past the window height — without this
            // the egui panel would grow the outer ui to fit, which in
            // turn shoves the central panel's rect downward and the
            // minimap (anchored to `panel_rect.bottom()`) scrolls off
            // screen even though it's on the opposite side.
            egui::ScrollArea::vertical()
                .id_salt("tools_panel_scroll")
                .show(ui, |ui| self.tools_panel_body(ui));
        });
    }

    fn tools_panel_body(&mut self, ui: &mut egui::Ui) {
        self.render_tool_picker(ui);

        ui.separator();
        ui.heading("View");
        let has_map = self.wind_map.is_some();
        if ui
            .add_enabled(has_map, egui::Button::new("Fit to view"))
            .clicked()
        {
            self.view.autoscale_pending = true;
        }
        let min_scale = min_render_scale(self.view.last_panel_height);
        self.view.render_scale = self.view.render_scale.max(min_scale);
        // Snapshot the scale around the Scale-mutating widgets so we can
        // recentre the view on the panel centre after the user changes
        // it. Mouse-wheel zoom already pivots around the cursor; the
        // slider / steppers / typed value should pivot around the view
        // centre so the visible region stays roughly where the user
        // expects rather than drifting toward the projection origin.
        let scale_before = self.view.render_scale;
        // "Scale:" label outside the edit box so the box itself shows only
        // the value (`"1 px : 10 km"`). `DragValue` with `speed(0.0)`
        // keeps click-to-type and disables drag-scrubbing — a linear drag
        // on a log scale feels awful — while the slider+steppers below
        // do the live adjusting.
        ui.horizontal(|ui| {
            ui.label("Scale:");
            ui.add(
                egui::DragValue::new(&mut self.view.render_scale)
                    .range(min_scale..=SCALE_MAX)
                    .speed(0.0)
                    .custom_formatter(|v, _| format_scale_value(v as f32))
                    .custom_parser(parse_scale_value),
            );
        });
        log_slider_with_steppers(ui, &mut self.view.render_scale, min_scale, SCALE_MAX);
        if (self.view.render_scale - scale_before).abs() > f32::EPSILON {
            self.zoom_around_panel_centre(scale_before);
        }

        // Iteration scrubber: was a bottom panel; moved here so it sits
        // next to the other view-state controls (which gbest snapshot the
        // central panel renders is conceptually a view setting). Always
        // shown so the central panel's bottom edge stays stable; disabled
        // with a `0 / 0` caption when no search has run yet. The current
        // index lives in its own `DragValue` so the user can type a
        // specific iteration directly instead of dragging the slider to
        // the right value.
        let iter_count = self
            .outputs
            .route_evolution
            .as_ref()
            .map_or(0, |e| e.iter_count());
        let max_iter = iter_count.saturating_sub(1);
        ui.add_enabled_ui(iter_count > 0, |ui| {
            ui.horizontal(|ui| {
                ui.label("Iteration:");
                ui.add(
                    egui::DragValue::new(&mut self.outputs.iteration)
                        .range(0..=max_iter)
                        .speed(0.0),
                );
                ui.label(format!("/ {max_iter}"));
            });
            int_slider_with_steppers(ui, &mut self.outputs.iteration, max_iter);
        });

        // Time slider: snaps to integer frame indices so edit brushes
        // always land on a real frame rather than an interpolated
        // mid-point. The slider's max extends past the wind-map data
        // when a search has produced a route that runs longer than
        // the loaded data — frames past `data_max_frame` are
        // synthesised on the fly via the crossfade-aware
        // `TimedWindMap::query`, so the user can scrub through what
        // the search "sees" past the data end.
        if let Some(wind_map) = &self.wind_map {
            let data_max_frame = wind_map.frame_count().saturating_sub(1);
            let step_seconds = wind_map.step_seconds();
            let route_max_frame = self.route_max_frame(step_seconds);
            let slider_max = data_max_frame.max(route_max_frame);
            let t_seconds = self.editor.current_frame as f32 * step_seconds;
            let in_wrap = self.editor.current_frame > data_max_frame;
            ui.separator();
            ui.heading("Time");
            let wrap_marker = if in_wrap { "  (wrapped)" } else { "" };
            ui.label(format!(
                "Frame {} / {} ({:.2}h){}",
                self.editor.current_frame,
                slider_max,
                t_seconds / 3600.0,
                wrap_marker,
            ));
            match wind_map.time_range() {
                Some((start, end)) => {
                    // Monospace so the `From:` / `To: ` labels (which
                    // differ by one character) still line up the
                    // timestamps in a single column.
                    ui.monospace(format!("From: {}", start.format("%Y-%m-%d %H:%M UTC")));
                    ui.monospace(format!("To:   {}", end.format("%Y-%m-%d %H:%M UTC")));
                }
                None => {
                    ui.label("(no UTC range)");
                }
            }
            ui.add_enabled_ui(slider_max > 0, |ui| {
                int_slider_with_steppers(ui, &mut self.editor.current_frame, slider_max);
            });
            // Below-slider visual cue showing data vs wrap regions.
            // The slider itself is one continuous bar regardless of
            // value, so this strip is the cheapest way to make the
            // wrap region visible without recreating egui's slider
            // widget. Aligned to the slider's full horizontal extent.
            if slider_max > data_max_frame && data_max_frame > 0 {
                let (rect, _) = ui.allocate_exact_size(
                    egui::Vec2::new(ui.available_width(), 4.0),
                    egui::Sense::hover(),
                );
                let data_color = egui::Color32::from_rgb(80, 140, 200);
                let wrap_color = egui::Color32::from_rgb(220, 150, 60);
                let split_x =
                    rect.left() + rect.width() * (data_max_frame as f32 / slider_max as f32);
                ui.painter().rect_filled(
                    egui::Rect::from_min_max(rect.min, egui::Pos2::new(split_x, rect.bottom())),
                    1.0,
                    data_color,
                );
                ui.painter().rect_filled(
                    egui::Rect::from_min_max(egui::Pos2::new(split_x, rect.top()), rect.max),
                    1.0,
                    wrap_color,
                );
            }
        }

        ui.separator();
        self.render_search_section(ui);
    }

    /// Tool selector at the top of the tools panel, plus any per-tool
    /// secondary controls (currently only the Endpoint tool has them).
    fn render_tool_picker(&mut self, ui: &mut egui::Ui) {
        ui.heading("Tools");
        ui.separator();
        ui.selectable_value(&mut self.editor.selected_tool, Tool::Pointer, "Pointer");
        // Picking Set Endpoints or Set Route Bounds with no values set
        // leaves the user staring at an empty map even though the search
        // would run with implicit defaults (the wind-map bbox corners /
        // bbox). Pre-populate from those defaults the moment the tool is
        // selected so the UI shows what the search would do, with
        // markers/rectangle ready to drag.
        let endpoint_resp = ui.selectable_value(
            &mut self.editor.selected_tool,
            Tool::Endpoint,
            "Set Endpoints",
        );
        if endpoint_resp.changed() {
            self.populate_endpoint_defaults_if_unset();
            // The user is acting on the "missing endpoints" prompt;
            // the animated highlight has served its purpose.
            self.editor.highlight_endpoint_tool = false;
        }
        if self.editor.highlight_endpoint_tool {
            paint_endpoint_highlight(ui, endpoint_resp.rect);
            ui.ctx().request_repaint();
        }
        if ui
            .selectable_value(
                &mut self.editor.selected_tool,
                Tool::RouteBounds,
                "Set Route Bounds",
            )
            .changed()
        {
            self.populate_route_bbox_default_if_unset();
        }
        ui.selectable_value(
            &mut self.editor.selected_tool,
            Tool::Speed,
            "Edit Wind Speed",
        );
        ui.selectable_value(
            &mut self.editor.selected_tool,
            Tool::Direction,
            "Edit Wind Direction",
        );
        ui.selectable_value(
            &mut self.editor.selected_tool,
            Tool::WaypointEdit,
            "Edit Waypoint Position",
        );
        ui.selectable_value(
            &mut self.editor.selected_tool,
            Tool::WaypointTime,
            "Set Time From Waypoint",
        );
        if self.editor.selected_tool == Tool::Endpoint {
            ui.label("Left-click: start, right-click: end");
            let has_endpoints =
                self.editor.start_waypoint.is_some() || self.editor.end_waypoint.is_some();
            // Swap is enabled when at least one endpoint exists — swapping
            // a `(Some, None)` pair into `(None, Some)` is still useful as
            // it relabels which corner the user already placed.
            ui.horizontal(|ui| {
                if ui
                    .add_enabled(has_endpoints, egui::Button::new("Clear"))
                    .clicked()
                {
                    self.editor.start_waypoint = None;
                    self.editor.end_waypoint = None;
                }
                if ui
                    .add_enabled(has_endpoints, egui::Button::new("Swap"))
                    .clicked()
                {
                    std::mem::swap(
                        &mut self.editor.start_waypoint,
                        &mut self.editor.end_waypoint,
                    );
                }
            });
        }
        if self.editor.selected_tool == Tool::RouteBounds {
            ui.label("Drag to define, right-click to clear");
            let has_bbox = self.editor.route_bbox.is_some();
            if ui
                .add_enabled(has_bbox, egui::Button::new("Clear bounds"))
                .clicked()
            {
                self.editor.route_bbox = None;
                self.editor.route_bbox_auto = false;
            }
            // Auto-set is only meaningful with both endpoints placed and a
            // wind map loaded (otherwise we have nothing to derive bounds
            // around or to clamp against).
            let can_auto = self.wind_map.is_some()
                && self.editor.start_waypoint.is_some()
                && self.editor.end_waypoint.is_some();
            let auto_label = if self.editor.route_bbox_auto {
                "Auto-set bounds (active)"
            } else {
                "Auto-set bounds"
            };
            if ui
                .add_enabled(can_auto, egui::Button::new(auto_label))
                .on_hover_text(
                    "Derive a sensible search rectangle from the placed endpoints \
                     using the A* sea-path finder, plus a 20% / 3° margin so the \
                     PSO can find faster wind-aware detours. Recomputes when \
                     endpoints move, until you manually drag or clear the bbox.",
                )
                .clicked()
            {
                self.auto_set_route_bbox();
            }
        }
    }

    /// "Two-tier SDF" row of the Advanced Settings grid: a checkbox
    /// that toggles between single-tier and two-tier landmass, plus a
    /// `DragValue` for the fine cell size when two-tier is on.
    /// Extracted from `render_advanced_settings_window` to keep that
    /// function under clippy's `too_many_lines` cap.
    fn render_two_tier_row(&mut self, ui: &mut egui::Ui) {
        ui.label("Two-tier SDF").on_hover_text(
            "Enable a high-resolution SDF tier over each strait \
             carve-out's neighbourhood. Visual carve-out tubes shrink \
             proportionally to (coarse / fine) — e.g., at coarse=0.5° \
             and fine=0.1° the Bosporus tube is ~13 km instead of \
             ~132 km. Per-search cost goes up roughly linearly with \
             (coarse / fine) due to finer substep cadence near coasts.",
        );
        let mut two_tier_enabled = self.search.fine_sdf_resolution_deg.is_some();
        ui.horizontal(|ui| {
            if ui.checkbox(&mut two_tier_enabled, "").changed() {
                self.search.fine_sdf_resolution_deg =
                    if two_tier_enabled { Some(0.1) } else { None };
            }
            if let Some(fine) = self.search.fine_sdf_resolution_deg.as_mut() {
                ui.add(
                    egui::DragValue::new(fine)
                        .range(0.01..=self.search.sdf_resolution_deg)
                        .speed(0.01)
                        .prefix("fine = ")
                        .suffix("°"),
                );
            } else {
                ui.weak("(single-tier)");
            }
        });
        ui.end_row();
    }

    /// "Ensemble" pair of rows in the Advanced Settings grid: text
    /// field for the directory of `.wcav` files (one per member,
    /// produced by `bywind-cli fetch-ensemble`) and a combo box
    /// selecting the aggregation mode. Mutually exclusive with the
    /// regular wind-map selection — when an ensemble path is set, the
    /// wind-map slot is ignored at search time.
    fn render_ensemble_rows(&mut self, ui: &mut egui::Ui) {
        use bywind::EnsembleMode;
        ui.label("Ensemble dir").on_hover_text(
            "Path to a directory of ensemble `.wcav` files (output of \
             `bywind-cli fetch-ensemble`). When set, the search runs \
             against the K-member ensemble instead of the loaded wind \
             map. Leave empty for single-deterministic search.",
        );
        ui.horizontal(|ui| {
            // Inline editable text field — file-dialog widgets on egui
            // are platform-specific and not in this crate yet, so users
            // paste the path. A clear button below the row resets.
            let mut path_str = self
                .search
                .ensemble_path
                .as_ref()
                .map(|p| p.display().to_string())
                .unwrap_or_default();
            let response = ui.add(
                egui::TextEdit::singleline(&mut path_str)
                    .hint_text("(none — single-deterministic)")
                    .desired_width(220.0),
            );
            if response.changed() {
                self.search.ensemble_path = if path_str.trim().is_empty() {
                    None
                } else {
                    Some(std::path::PathBuf::from(path_str.trim()))
                };
            }
            if ui
                .button("Clear")
                .on_hover_text("Reset to single-deterministic")
                .clicked()
            {
                self.search.ensemble_path = None;
            }
        });
        ui.end_row();

        ui.label("Ensemble mode").on_hover_text(
            "Aggregation strategy when an ensemble directory is set. \
             `Full` runs K-fold robust fitness (currently mean of \
             per-member fitnesses); `Fast mean` pre-computes a single \
             mean wind map and runs the existing single-deterministic \
             search against it. Fast mean is ~K× faster but \
             `E[f(x,wind)] ≠ f(x, E[wind])` — for routes in the \
             linear-polar regime the gap is typically <1 %.",
        );
        ui.horizontal(|ui| {
            let enabled = self.search.ensemble_path.is_some();
            ui.add_enabled_ui(enabled, |ui| {
                let mut mode = self.search.ensemble_mode;
                egui::ComboBox::from_id_salt("ensemble_mode")
                    .selected_text(match mode {
                        EnsembleMode::Full => "Full (K-fold)",
                        EnsembleMode::FastMean => "Fast mean",
                    })
                    .show_ui(ui, |ui| {
                        ui.selectable_value(&mut mode, EnsembleMode::Full, "Full (K-fold)");
                        ui.selectable_value(&mut mode, EnsembleMode::FastMean, "Fast mean");
                    });
                self.search.ensemble_mode = mode;
            });
            if !enabled {
                ui.weak("(set ensemble dir to enable)");
            }
        });
        ui.end_row();
    }

    /// Search-section block of the tools panel: waypoint count, the
    /// fitness-weights / PSO-parameter grid, and the Run Search button.
    /// Extracted from `render_tools_panel` purely to keep that function
    /// under clippy's `too_many_lines` cap.
    fn render_search_section(&mut self, ui: &mut egui::Ui) {
        ui.heading("Search");

        let is_searching = self.search_job.is_running();
        let can_run = self.wind_map.is_some();
        // Run Search is the section's primary action — full-width and
        // saturated green so it pops out of the panel's grey-and-text
        // wash. While a search is running it morphs into a red Cancel
        // Search button; clicking detaches the worker's receiver via
        // `AsyncJob::cancel` so the UI is responsive immediately (the
        // background thread runs to completion, its send becomes a
        // no-op). Keep this (and "Show all particles") above the
        // collapsing headers so the routine workflow stays one click
        // away even when every collapsible is closed.
        let (label, fill, enabled) = if is_searching {
            // Whole-second elapsed suffix so the button reads
            // "Cancel Search (27s)" while the worker is busy. Falls
            // back to plain "Cancel Search" if the start instant is
            // somehow missing (shouldn't happen — set together with
            // `search_job.set_running`).
            let elapsed_label = self
                .search_started_at
                .map(|t| format!("Cancel Search ({}s)", t.elapsed().as_secs()))
                .unwrap_or_else(|| "Cancel Search".to_owned());
            (elapsed_label, egui::Color32::from_rgb(180, 60, 60), true)
        } else {
            (
                "Run Search".to_owned(),
                egui::Color32::from_rgb(70, 150, 70),
                can_run,
            )
        };
        let button_resp = ui
            .add_enabled_ui(enabled, |ui| {
                ui.add_sized(
                    [ui.available_width(), 28.0],
                    egui::Button::new(egui::RichText::new(label).size(15.0).strong()).fill(fill),
                )
            })
            .inner;
        if button_resp.clicked() {
            if is_searching {
                self.search_job.cancel();
                self.search_started_at = None;
            } else {
                self.run_search(ui.ctx());
            }
        }
        if is_searching {
            ui.horizontal(|ui| {
                ui.spinner();
                // Phase-specific label tells the user *what* is taking
                // time — bake / benchmark / search — instead of a
                // generic "Searching…" during the multi-second pre-PSO
                // pipeline. Fallback covers the gap between worker
                // spawn and the first Phase event.
                let label = self
                    .current_search_phase
                    .map_or("searching…", bywind::SearchPhase::label);
                ui.label(label);
                // During the main PSO phase, show the per-iteration
                // progress badge — visible convergence cue alongside
                // the live route overlay. Best-fit included so the
                // user can spot when the search has plateaued.
                if let Some(live) = self.outputs.live_gbest.as_ref() {
                    let fit_str = if self.view.total_time_breakdown {
                        format_fitness_magnitude(live.best_fit)
                    } else {
                        format!("{:.0}", live.best_fit)
                    };
                    ui.weak(format!(
                        "(iter {}/{}, fit {fit_str})",
                        live.iter_idx + 1,
                        live.total_iters,
                    ));
                }
            });
        }

        // "Run per realization" is the secondary action that only
        // makes sense after a main search has converged against an
        // ensemble — gating on `route_evolution.is_some()` hides the
        // button entirely (rather than disabled-greyed) when neither
        // condition holds, so the routine single-deterministic
        // workflow doesn't show a control that has nothing to do.
        if self.search.ensemble_path.is_some() && self.outputs.route_evolution.is_some() {
            let realization_running = self.realization_job.is_running();
            let realization_label = if realization_running {
                self.realization_started_at
                    .map(|t| format!("Cancel ({}s)", t.elapsed().as_secs()))
                    .unwrap_or_else(|| "Cancel".to_owned())
            } else {
                "Run per realization".to_owned()
            };
            let realization_fill = if realization_running {
                egui::Color32::from_rgb(180, 60, 60)
            } else {
                egui::Color32::from_rgb(70, 110, 160)
            };
            let realization_resp = ui
                .add_sized(
                    [ui.available_width(), 24.0],
                    egui::Button::new(egui::RichText::new(realization_label).size(14.0))
                        .fill(realization_fill),
                )
                .on_hover_text(
                    "Run K independent single-deterministic searches, one per \
                     realization (ensemble member viewed as ground truth), so \
                     you can see what alternate routes each realization's wind \
                     would produce. K× wallclock; runs in the background. \
                     Result lands as a translucent overlay; switch the Summary \
                     dropdown to a realization to see its totals.",
                );
            if realization_resp.clicked() {
                if realization_running {
                    self.realization_job.cancel();
                    self.realization_started_at = None;
                } else {
                    self.run_realizations(ui.ctx());
                }
            }
            if realization_running {
                ui.horizontal(|ui| {
                    ui.spinner();
                    ui.label("Per-realization run in progress…");
                });
            }
        }

        ui.checkbox(&mut self.view.show_all_particles, "Show all particles");
        ui.checkbox(
            &mut self.view.show_realization_routes,
            "Show realization routes",
        )
        .on_hover_text(
            "Overlay the K per-realization routes on the central panel. \
                 Each route is a translucent polyline in a per-realization \
                 palette colour. No-op until you've run \"Run per realization\".",
        );
        ui.checkbox(&mut self.view.show_sdf_overlay, "Show SDF cells")
            .on_hover_text(
                "Overlay the rasterised landmass SDF on top of the coastlines. \
                 Blue cells are sea, red are land — diagnostic for why a route \
                 the search reports as 0 land visibly clips coastline.",
            );

        egui::CollapsingHeader::new("Parameters")
            .default_open(false)
            .show(ui, |ui| self.search_parameters(ui));
        egui::CollapsingHeader::new("Boat")
            .default_open(false)
            .show(ui, |ui| self.boat_panel(ui));
    }

    /// PSO parameter grid: waypoint count, fitness weights, swarm sizes,
    /// iteration counts, inertia / cognitive / social coefficients,
    /// path-kick knobs, and the outer-PSO topology. Pulled out so the
    /// Run Search call site stays compact and the parameters can be
    /// folded behind a collapsing header.
    fn search_parameters(&mut self, ui: &mut egui::Ui) {
        egui::ComboBox::from_label("Waypoints")
            .selected_text(format!("{}", self.search.waypoint_count.as_usize()))
            .show_ui(ui, |ui| {
                for &wc in &WaypointCount::ALL {
                    ui.selectable_value(
                        &mut self.search.waypoint_count,
                        wc,
                        format!("{}", wc.as_usize()),
                    );
                }
            });
        egui::Grid::new("fitness_weights_grid")
            .num_columns(2)
            .spacing([8.0, 4.0])
            .show(ui, |ui| {
                ui.label("Time weight");
                ui.add(egui::DragValue::new(&mut self.search.time_weight).range(0.0..=f64::MAX).speed(0.1));
                ui.end_row();
                ui.label("Fuel weight");
                ui.add(egui::DragValue::new(&mut self.search.fuel_weight).range(0.0..=f64::MAX).speed(0.1));
                ui.end_row();
                ui.label("Land weight").on_hover_text(
                    "Penalty per metre of route segment over land. 0 disables landmass avoidance. \
                     Units match time/fuel weight: pick a value where land-metres dominate the cost \
                     ratio you want to enforce.",
                );
                ui.add(egui::DragValue::new(&mut self.search.land_weight).range(0.0..=f64::MAX).speed(0.01));
                ui.end_row();
                ui.label("Particles (space)");
                ui.add(egui::DragValue::new(&mut self.search.particles_space).range(1..=usize::MAX));
                ui.end_row();
                ui.label("Particles (time)");
                ui.add(egui::DragValue::new(&mut self.search.particles_time).range(1..=usize::MAX));
                ui.end_row();
                ui.label("Iterations (space)");
                ui.add(egui::DragValue::new(&mut self.search.iter_space).range(1..=usize::MAX));
                ui.end_row();
                ui.label("Iterations (time)");
                ui.add(egui::DragValue::new(&mut self.search.iter_time).range(1..=usize::MAX));
                ui.end_row();
                ui.label("Inertia");
                ui.add(egui::DragValue::new(&mut self.search.inertia).range(0.0..=f64::MAX).speed(0.01));
                ui.end_row();
                ui.label("Cognitive coeff");
                ui.add(egui::DragValue::new(&mut self.search.cognitive_coeff).range(0.0..=f64::MAX).speed(0.01));
                ui.end_row();
                ui.label("Social coeff");
                ui.add(egui::DragValue::new(&mut self.search.social_coeff).range(0.0..=f64::MAX).speed(0.01));
                ui.end_row();
                ui.label("Path-kick prob").on_hover_text(
                    "Per-particle, per-iteration chance of applying a coherent path-shape \
                     kick (a sine-profile perpendicular offset that lets the search jump into \
                     tacking topologies). 0 disables.",
                );
                ui.add(egui::DragValue::new(&mut self.search.path_kick_probability).range(0.0..=1.0).speed(0.01));
                ui.end_row();
                ui.label("Path-kick γ₀").on_hover_text(
                    "Initial kick magnitude as a fraction of the route's straight-line \
                     length. Cosine-decays toward γ_min across iterations.",
                );
                ui.add(
                    egui::DragValue::new(&mut self.search.path_kick_gamma_0_fraction)
                        .range(0.0..=1.0)
                        .speed(0.005),
                );
                ui.end_row();
                ui.label("Path-kick γ_min").on_hover_text(
                    "Floor kick magnitude as a fraction of route length, reached at the \
                     last iteration. Must be ≤ γ₀.",
                );
                ui.add(
                    egui::DragValue::new(&mut self.search.path_kick_gamma_min_fraction)
                        .range(0.0..=1.0)
                        .speed(0.001),
                );
                ui.end_row();
            });
        ui.horizontal(|ui| {
            ui.label("Topology").on_hover_text(
                "Outer-PSO swarm topology. `gbest` is the stock single-attractor PSO; \
                 the others trade convergence speed for corridor diversity.",
            );
            egui::ComboBox::from_id_salt("search_topology_combo")
                .selected_text(self.search.topology.as_str())
                .show_ui(ui, |ui| {
                    for &t in Topology::ALL {
                        ui.selectable_value(&mut self.search.topology, t, t.as_str());
                    }
                });
        });
        // Restores only the fields the Parameters section exposes; the
        // Advanced Params window has its own Reset for the precision /
        // determinism knobs so toggling one doesn't surprise the user by
        // wiping the other.
        if ui.button("Reset to defaults").clicked() {
            let defaults = bywind::SearchConfig::default();
            self.search.waypoint_count = defaults.waypoint_count;
            self.search.time_weight = defaults.time_weight;
            self.search.fuel_weight = defaults.fuel_weight;
            self.search.land_weight = defaults.land_weight;
            self.search.particles_space = defaults.particles_space;
            self.search.particles_time = defaults.particles_time;
            self.search.iter_space = defaults.iter_space;
            self.search.iter_time = defaults.iter_time;
            self.search.inertia = defaults.inertia;
            self.search.cognitive_coeff = defaults.cognitive_coeff;
            self.search.social_coeff = defaults.social_coeff;
            self.search.path_kick_probability = defaults.path_kick_probability;
            self.search.path_kick_gamma_0_fraction = defaults.path_kick_gamma_0_fraction;
            self.search.path_kick_gamma_min_fraction = defaults.path_kick_gamma_min_fraction;
            self.search.topology = defaults.topology;
        }
    }

    /// Precision / determinism knobs for `SearchConfig`. Opened from
    /// `Advanced → Advanced Params`; changes take effect on the next
    /// Run Search. Tooltips on each control explain the tradeoff.
    pub(crate) fn render_advanced_settings_window(&mut self, ctx: &egui::Context) {
        if !self.editor.advanced_settings_open {
            return;
        }
        let mut open = self.editor.advanced_settings_open;
        egui::Window::new("Advanced Params")
            .open(&mut open)
            .resizable(false)
            .collapsible(true)
            .show(ctx, |ui| {
                ui.label(
                    "Precision and determinism knobs that aren't part of the routine \
                     Search panel. Lower step / cell sizes give better fitness fidelity \
                     at higher per-search cost. Changes take effect on the next Run Search.",
                );
                ui.separator();

                egui::Grid::new("advanced_settings_grid")
                    .num_columns(2)
                    .spacing([8.0, 4.0])
                    .show(ui, |ui| {
                        ui.label("Step distance fraction").on_hover_text(
                            "Substep size for wind / landmass integration along each \
                             segment, as a fraction of the route bbox diagonal. The single \
                             biggest fitness-accuracy knob: 0.005 doubles per-segment \
                             precision at ~2× per-fitness cost. Default 0.01.",
                        );
                        ui.add(
                            egui::DragValue::new(&mut self.search.step_distance_fraction)
                                .range(1e-6..=1.0)
                                .speed(0.001),
                        );
                        ui.end_row();

                        ui.label("Bake step (°)").on_hover_text(
                            "Cell size of the search-side baked wind grid, in degrees \
                             of lon / lat. Quadratic memory in this value; the bake-bounds \
                             builder grows it past the requested value if needed to stay \
                             under the per-axis cell cap. Default 0.25° (typical GFS \
                             resolution).",
                        );
                        ui.add(
                            egui::DragValue::new(&mut self.search.bake_step_deg)
                                .range(1e-3..=10.0)
                                .speed(0.01),
                        );
                        ui.end_row();

                        ui.label("SDF resolution (°)").on_hover_text(
                            "Landmass SDF cell size in degrees. Finer resolutions \
                             improve coastline-following baselines and the land-metres \
                             penalty integral; each distinct resolution pays a one-shot \
                             rasterise + SDF build (~sub-second) and is cached for the \
                             rest of the session. Default 0.5°.",
                        );
                        ui.add(
                            egui::DragValue::new(&mut self.search.sdf_resolution_deg)
                                .range(0.05..=5.0)
                                .speed(0.05),
                        );
                        ui.end_row();

                        self.render_two_tier_row(ui);

                        self.render_ensemble_rows(ui);

                        ui.label("Range K").on_hover_text(
                            "Departure-time samples per segment in the inner time-PSO \
                             lookup table. Higher values reduce time-axis interpolation \
                             error at the cost of a bigger table build per outer \
                             particle. Must be ≥ 2. Default 8.",
                        );
                        ui.add(egui::DragValue::new(&mut self.search.range_k).range(2..=64));
                        ui.end_row();

                        ui.label("K_MCR").on_hover_text(
                            "Throttle (`mcr_01`) samples per departure-time bucket in \
                             the inner time-PSO lookup table. Lower values trade fitness \
                             fidelity for wallclock (k_mcr=4 → ~11% wallclock saving, \
                             ≤2.1% fitness regression on profiling). Must be ≥ 2. \
                             Default 8.",
                        );
                        ui.add(egui::DragValue::new(&mut self.search.k_mcr).range(2..=64));
                        ui.end_row();

                        ui.label("Deterministic seed").on_hover_text(
                            "When enabled, fixes the RNG seed so identical inputs \
                             reproduce the exact same swarm trajectory. When disabled, \
                             each run draws a fresh seed and shows it below after the \
                             search starts. Toggling the box off parks the current \
                             value so re-checking restores it; check the box after a \
                             fresh-entropy run to recover that run's seed.",
                        );
                        ui.horizontal(|ui| {
                            let mut use_seed = self.search.seed.is_some();
                            if ui.checkbox(&mut use_seed, "").changed() {
                                if use_seed {
                                    // Re-check prefers the explicitly parked
                                    // value, falling back to the seed used by
                                    // the most recent run so the user can
                                    // reproduce a fresh-entropy result with
                                    // one click. Final fallback: 0.
                                    let restored = self
                                        .editor
                                        .parked_seed
                                        .or(self.outputs.last_search_seed)
                                        .unwrap_or(0);
                                    self.search.seed = Some(restored);
                                } else {
                                    self.editor.parked_seed = self.search.seed;
                                    self.search.seed = None;
                                }
                            }
                            if let Some(seed) = self.search.seed.as_mut() {
                                ui.add(egui::DragValue::new(seed).speed(1.0));
                            } else if let Some(last) = self.outputs.last_search_seed {
                                // Read-only display of the seed used by the
                                // most recent fresh-entropy run.
                                let mut shown = last;
                                ui.add_enabled(false, egui::DragValue::new(&mut shown).speed(0.0));
                            } else {
                                ui.weak("(fresh entropy)");
                            }
                        });
                        ui.end_row();
                    });

                ui.separator();
                if ui.button("Reset to defaults").clicked() {
                    let defaults = bywind::SearchConfig::default();
                    self.search.step_distance_fraction = defaults.step_distance_fraction;
                    self.search.bake_step_deg = defaults.bake_step_deg;
                    self.search.sdf_resolution_deg = defaults.sdf_resolution_deg;
                    self.search.fine_sdf_resolution_deg = defaults.fine_sdf_resolution_deg;
                    self.search.range_k = defaults.range_k;
                    self.search.k_mcr = defaults.k_mcr;
                    self.search.seed = defaults.seed;
                    self.search.ensemble_path = defaults.ensemble_path.clone();
                    self.search.ensemble_mode = defaults.ensemble_mode;
                }
            });
        // Mirror `open` back so the title-bar X toggles the flag.
        self.editor.advanced_settings_open = open;
    }

    /// Renders the Boat section in the tools panel: parameter inputs for the
    /// engine, polar curve, and fuel-rate model. The next search and any
    /// reload of a saved solution will pick these up via
    /// [`bywind::BoatConfig::to_boat`].
    fn boat_panel(&mut self, ui: &mut egui::Ui) {
        egui::Grid::new("boat_grid")
            .num_columns(2)
            .spacing([8.0, 4.0])
            .show(ui, |ui| {
                ui.label("MCR (kW)");
                ui.add(
                    egui::DragValue::new(&mut self.boat.mcr_kw)
                        .range(0.0..=f64::MAX)
                        .speed(1.0),
                );
                ui.end_row();
                ui.label("Drag k");
                ui.add(
                    egui::DragValue::new(&mut self.boat.k)
                        .range(0.0..=f64::MAX)
                        .speed(10.0),
                );
                ui.end_row();
                ui.label("Polar c");
                ui.add(
                    egui::DragValue::new(&mut self.boat.polar_c)
                        .range(0.0..=f64::MAX)
                        .speed(0.01),
                );
                ui.end_row();
                ui.label("Polar sin power");
                ui.add(
                    egui::DragValue::new(&mut self.boat.polar_sin_power)
                        .range(0.0..=f64::MAX)
                        .speed(0.05),
                );
                ui.end_row();
                ui.label("Fuel a");
                ui.add(egui::DragValue::new(&mut self.boat.fuel_a).speed(0.001));
                ui.end_row();
                ui.label("Fuel b");
                ui.add(egui::DragValue::new(&mut self.boat.fuel_b).speed(0.001));
                ui.end_row();
                ui.label("Fuel c");
                ui.add(egui::DragValue::new(&mut self.boat.fuel_c).speed(0.001));
                ui.end_row();
            });
        draw_fuel_curve(ui, self.boat.fuel_a, self.boat.fuel_b, self.boat.fuel_c);
        if ui.button("Reset to defaults").clicked() {
            self.boat = BoatConfig::default();
        }
    }
}