Repository navigation
Expand file tree
/
Copy pathplanner.rs
More file actions
2628 lines (2518 loc) · 129 KB
/
Copy pathplanner.rs
File metadata and controls
2628 lines (2518 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The planner. Its layers cover the region of the settings: `planner/osm` is the OSM of the
//! region, `planner/osm/bounds` its cut to the bounds and a margin, `planner/basemap` the offline
//! Protomaps map, `planner/terrain` the terrain of the maps, `planner/routing` the routing package
//! with its grid, and `planner/search/dump` the search records of the OSM. `planner/overlays`,
//! `planner/assets`, `planner/model`, `planner/places`, the other `planner/search/*` layers and
//! the optional layers `planner/climate`, `planner/snow` and `planner/trailview-*`
//! are Python steps.
//! Each map producer is intermediate. Its `/grid` step partitions and packs the client tiles.
//! The release document, the public files and the grid indexes are the files that a client finds
//! by name; `planner/catalog` points at them. `data/planner.toml` holds the options that are the
//! same for each region.
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::Path;
use obc_bake::coverage::Coverage;
use obc_data::engine::{snapshot_files, Client, Input, Layer, LayerFile, Reader, Run, Shape, Step};
use obc_data::ground::GroundSource;
use obc_data::prepared::Manifest;
use obc_data::product::{version, Inputs, Pointer, Product, Steps, Unplanned, Wanted};
use obc_data::regions::{geofabrik, Area, Regions};
use obc_data::release::{Output, Release};
use obc_data::sources::{attribution, embedded};
use obc_data::store::Store;
use obc_dem::reference::TILE_LOG2;
use obc_dem::step::GLO30;
use obc_map_core::grid::CellId;
use planner_router_build::grid::{mercator, tile_bounds};
use planner_router_build::step;
use serde::Deserialize;
use serde_json::json;
use crate::device::{invalid, text, Models, TILE_LIST};
use crate::readers::{self, DOWNLOADS_SERVICE, IOS, IOS_OFFLINE_ROUTER, ROUTER_SERVICE, SEARCH_SERVICE, WEB_PLANNER};
use crate::region_sources::OSM;
use crate::{functions, python};
/// The OSM extracts whose coastlines and summits shape the terrain. Its policy is `manual`, so a
/// newer extract of `geofabrik-extracts` does not bake the terrain again.
const TERRAIN_OSM: &str = "terrain-osm";
/// The offline Protomaps map, with its fonts and sprites.
pub static PLANNER_BASEMAP: Layer = whole("planner/basemap", 1, &[&WEB_PLANNER, &IOS]);
/// The terrain of the maps and of TrailView: its format is that of the terrain tiles of
/// `specs/planner-release.md`.
pub static PLANNER_TERRAIN: Layer =
Layer { revision: 4, ..whole("planner/terrain", 2, &[&WEB_PLANNER, &readers::PLANNER_TRAILVIEW_FEATURES]) };
/// The work layers of the routing bake, each of the step of its name: the source, the roads and the
/// costs of `planner_router_build::step`. A change of their bytes changes their format (`work`), a
/// change of their content their revision: of the import rules the source, of the split, the order
/// or the terrain the roads, of the cost code the costs.
pub static PLANNER_ROUTING_SOURCE: Layer = Layer { revision: 2, ..work(step::SOURCE) };
pub static PLANNER_ROUTING_ROADS: Layer = work(step::ROADS);
pub static PLANNER_ROUTING_COSTS: Layer = Layer { revision: 2, ..work(step::COSTS) };
/// The routing package, its grid and the route network overlays.
pub static PLANNER_ROUTING: Layer = Layer {
revision: 37,
..whole("planner/routing", planner_router::package::FORMAT, &[&ROUTER_SERVICE, &IOS_OFFLINE_ROUTER])
};
/// The facts of the catalog routes for the search of the Explore page, `specs/route-catalog.md`,
/// section "Facts files". Its format is `FORMAT` of `planner_router_build::facts`.
pub static PLANNER_ROUTE_FACTS: Layer = whole(step::FACTS, planner_router_build::facts::FORMAT, &[&WEB_PLANNER]);
/// The search databases and the query model. Its format is the search schema of
/// `specs/planner-release.md`.
pub static PLANNER_SEARCH: Layer = Layer { revision: 3, ..whole("planner/search", 6, &[&SEARCH_SERVICE]) };
/// The rider places of the search.
pub static PLANNER_PLACES: Layer = whole("planner/places", 1, &[&WEB_PLANNER]);
pub static PLANNER_CLIMATE: Layer = whole("planner/climate", 1, &[&WEB_PLANNER]);
/// The snow archives of `specs/planner-snow-tiles.md`.
pub static PLANNER_SNOW: Layer = whole("planner/snow", 2, &[&WEB_PLANNER]);
/// Its format is `features_format` of `specs/trailview-features.md`. Its step `planner/trailview-stamps`
/// holds what the stamp worker makes of the tiles; `stamp_version` of `specs/trailview-tiles.md` says
/// which stamp code made it.
pub static PLANNER_TRAILVIEW_FEATURES: Layer =
Layer { revision: 35, ..whole("planner/trailview-features", 4, &[&WEB_PLANNER]) };
/// The TrailView ruleset, `rules.json` of `specs/trailview-tiles.md`. Its format is `format` of
/// `rules.json`, `FORMAT` of `tools/trailview/rules.py`.
pub static PLANNER_TRAILVIEW_RULES: Layer =
whole("planner/trailview-rules", 3, &[&WEB_PLANNER, &readers::PLANNER_TRAILVIEW_GROUND]);
/// The TrailView ground tiles: the material, the lithology and the region in one tile. Its format is
/// `trailview_format` of the ground archive in `specs/trailview-tiles.md`.
pub static PLANNER_TRAILVIEW_GROUND: Layer =
Layer { revision: 2, ..whole("planner/trailview-ground", 3, &[&WEB_PLANNER]) };
/// The TrailView colour tiles. Its format is `trailview_format` of a colour archive in
/// `specs/trailview-tiles.md`.
pub static PLANNER_TRAILVIEW_COLOUR: Layer = whole("planner/trailview-colour", 2, &[&WEB_PLANNER]);
/// Its format is `canopy_format` of `specs/trailview-tiles.md`.
pub static PLANNER_TRAILVIEW_CANOPY: Layer = whole("planner/trailview-canopy", 1, &[&WEB_PLANNER]);
/// The offline catalog with its cell files, the release document, the joined fonts of every planner
/// layer and the pointer. Its format is that of the offline files and of `search/<region>.grid.json`,
/// which the downloads and search services check: a change of either file format changes it, and
/// `INDEX_FORMAT` of `tools/planner_runtime.py` and `GRID` of `planner/search/installation.mjs`.
pub static PLANNER_INDEX: Layer =
Layer { revision: 3, ..whole("planner/index", 4, &[&WEB_PLANNER, &IOS, &SEARCH_SERVICE, &DOWNLOADS_SERVICE]) };
const WORLDCOVER_GRID: &str = "esa-worldcover-grid";
const fn whole(name: &'static str, format: u32, readers: &'static [&'static Reader]) -> Layer {
Layer { name, shape: Shape::Whole, format, revision: 1, readers, cache: false }
}
/// The files of a work layer hold router types: the closure sets, `Point` and the postcard
/// `CostBasis` of the dictionary. Its format is the sum of the router `FORMAT` and the format of
/// its own files, 1; each only grows.
const fn work(name: &'static str) -> Layer {
Layer {
name,
shape: Shape::Whole,
format: planner_router::package::FORMAT + 1,
revision: 1,
readers: &[],
cache: true,
}
}
const BASEMAP_SOURCES: [&str; 7] = [
"protomaps-basemaps",
"natural-earth",
"water-polygons",
"land-polygons",
"daylight-landcover",
"qrank",
"pgf-encoding",
];
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Config {
osm: Osm,
routing: Routing,
climate: Climate,
snow: Snow,
trailview: TrailView,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct TrailView {
colour_year: u16,
colour: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Climate {
first_year: u16,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Snow {
seasons: [u16; 2],
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Osm {
margin_m: f64,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Routing {
profiles: Vec<String>,
}
pub(crate) mod catalog;
fn config() -> Result<Config, String> {
toml::from_str(include_str!("../../../data/planner.toml")).map_err(|e| format!("data/planner.toml: {e}"))
}
/// `snow.seasons` of `data/planner.toml`: the first and the last season of the snow layer.
pub fn snow_seasons() -> Result<[u16; 2], String> {
Ok(config()?.snow.seasons)
}
/// `climate.first_year` of `data/planner.toml`: the first of the ten years that the climate layer reads.
pub fn climate_first_year() -> Result<u16, String> {
Ok(config()?.climate.first_year)
}
/// `trailview.colour_year` of `data/planner.toml`: the year of the satellite colour.
pub fn colour_year() -> Result<u16, String> {
Ok(config()?.trailview.colour_year)
}
pub struct Planner;
impl Product for Planner {
fn name(&self) -> &'static str {
"planner"
}
fn status_steps(&self, root: &Path, inputs: &Inputs, regions: &Regions, store: &Store) -> Result<Steps, Unplanned> {
self.steps_with_tool(root, inputs, regions, store, Ok(()))
}
fn pointer(&self) -> Pointer {
Pointer { key: "planner/catalog.json", step: catalog::STEP, path: "catalog.json" }
}
/// The sources of the step table of `specs/obc-data.md`, and the ground sources that are
/// fetched: `osm-planet` of the ground chain is `planner/osm`.
fn reads(&self, root: &Path) -> Vec<String> {
let mut reads: Vec<String> = [
"geofabrik-extracts",
"geofabrik-poly",
"geofabrik-index",
"terrain-osm",
"protomaps-basemaps",
"natural-earth",
"water-polygons",
"land-polygons",
"daylight-landcover",
"qrank",
"pgf-encoding",
"terrain",
GLO30,
TILE_LIST,
"protomaps-assets",
"tangrams-icons",
"query-model",
"nominatim-country-data",
"wiki",
"climate",
crate::snow_reference::ID,
"esa-worldcover",
WORLDCOVER_GRID,
crate::forest_reference::ID,
]
.map(str::to_string)
.into();
let ground = obc_data::ground::Ground::load(root).map(|ground| {
let chains = ground.material.sources.into_iter().chain(ground.lithology.sources);
chains.map(|step| step.source).filter(|id| id != "osm-planet").collect::<Vec<_>>()
});
for id in ground.unwrap_or_default() {
if !reads.contains(&id) {
reads.push(id);
}
}
reads.extend(route_sources(root).into_iter().flatten().map(|source| source.id));
reads
}
fn named(&self, outputs: &[Output]) -> Result<Vec<(String, LayerFile)>, String> {
catalog::named(outputs.iter().map(|output| (output.step.as_str(), output.files.as_slice())))
}
fn verify(&self, root: &Path, previous: Option<&Release>, release: &Release, store: &Store) -> Result<(), String> {
catalog::verify(root, previous, release, store)
}
fn optional(&self) -> &'static [&'static str] {
&[
"map",
"routing",
"route-facts",
"route-sources",
"search",
"climate",
"snow",
"trailview-features",
"trailview-rules",
"trailview-ground",
"trailview-colour",
"trailview-canopy",
]
}
/// The planner bakes while one of its parts is on.
fn on(&self, settings: &obc_data::settings::Settings) -> bool {
settings.layers.iter().any(|layer| self.optional().contains(&layer.as_str()))
}
fn steps(&self, root: &Path, inputs: &Inputs, regions: &Regions, store: &Store) -> Result<Steps, Unplanned> {
let osmium = obc_osm::ShardRunner::check(&obc_osm::OsmiumRunner::default());
self.steps_with_tool(root, inputs, regions, store, osmium)
}
}
impl Planner {
/// Its steps. `osmium` says whether Osmium runs here: more than one source area, a box and the
/// TrailView features need it.
pub fn steps_with_tool(
&self,
root: &Path,
inputs: &Inputs,
regions: &Regions,
store: &Store,
osmium: Result<(), String>,
) -> Result<Steps, Unplanned> {
let config = config().map_err(Unplanned::Failed)?;
let origins = catalog::publication(root).map_err(Unplanned::Failed)?;
let id = &inputs.settings.region;
let region = regions.get(id).ok_or_else(|| Unplanned::Failed(format!("no region `{id}`")))?;
// A region without a time zone, such as a box, gives the times of the search in UTC.
let time_zone = region.time_zone.as_deref().unwrap_or("UTC");
let on = |layer: &str| inputs.settings.layers.iter().any(|name| name == layer);
let mut wanted = Vec::new();
let glo30 = version(inputs, store, GLO30, &[]).map_err(Unplanned::Failed)?.map_err(|fetch| wanted.push(fetch));
let selection = crate::region_sources::resolve(inputs, regions, store, &mut wanted)?;
let tile_list = text(inputs, store, TILE_LIST, &[], &mut wanted)?;
let assets = vec![
snapshot(inputs, store, "protomaps-assets", Vec::new(), &mut wanted)?,
snapshot(inputs, store, "tangrams-icons", Vec::new(), &mut wanted)?,
];
let model = snapshot(inputs, store, "query-model", Vec::new(), &mut wanted)?;
let country_data = snapshot(inputs, store, "nominatim-country-data", Vec::new(), &mut wanted)?;
let (Some(selection), Some(tile_list), Ok(glo30)) = (selection, tile_list, glo30) else {
return Err(Unplanned::NeedsFetch(wanted));
};
let countries = match ®ion.countries[..] {
[] => {
let Some(body) = text(inputs, store, crate::device::catalog::INDEX, &[], &mut wanted)? else {
return Err(Unplanned::NeedsFetch(wanted));
};
let index = geofabrik::parse(body.as_bytes()).map_err(Unplanned::Failed)?;
let mut countries: Vec<String> = selection
.sources
.iter()
.filter_map(|source| index.get(&source.id))
.flat_map(|area| area.countries.clone())
.collect();
countries.sort();
countries.dedup();
countries
}
countries => countries.to_vec(),
};
if countries.is_empty() {
return Err(invalid(format!("the Geofabrik areas of region `{id}` name no country, which search needs")));
}
let land: HashSet<&str> = tile_list.lines().map(str::trim).collect();
let requested = obc_bake::coverage::Coverage::union(&selection.outlines.iter().collect::<Vec<_>>())
.ok_or_else(|| Unplanned::Failed("cannot union planner region coverage".into()))?;
let (west, south, east, north) = requested.bbox();
let bounds = [west, south, east, north].map(|udeg| udeg as f64 / 1e6);
let coverage = zoom_10_neighbourhood(bounds);
let source_steps = crate::region_sources::inputs("planner", &selection);
let osm = if selection.sources.len() == 1 {
Step {
layer: &OSM,
name: "planner/osm".into(),
inputs: vec![Input::Step { name: source_steps[0].name.clone(), files: vec!["source.osm.pbf".into()] }],
options: json!({"path": "osm.pbf"}),
outputs: vec!["osm.pbf".into()],
run: Run::Rust(&obc_data::engine::PASS),
client: Client::None,
}
} else {
osmium.clone().map_err(Unplanned::Invalid)?;
crate::region_sources::combined("planner/osm", &source_steps)
};
// The TrailView steps read `planner/osm`: they look past the bounds. A region without a box
// is its whole extracts, so it passes them on as they are.
let leaves = regions.leaves(id).map_err(Unplanned::Failed)?;
let boxed =
leaves.iter().any(|leaf| regions.get(leaf).is_some_and(|leaf| matches!(leaf.area, Area::Box { .. })));
let (run, options) = match boxed {
true => {
osmium.clone().map_err(Unplanned::Invalid)?;
(&functions::CUT, json!({"bbox": around(bounds, config.osm.margin_m)}))
}
false => (&obc_data::engine::PASS, json!({"path": "osm.pbf"})),
};
let cut = Step {
layer: &OSM,
name: "planner/osm/bounds".into(),
inputs: vec![Input::step(osm.name.clone())],
options,
outputs: vec!["osm.pbf".into()],
run: Run::Rust(run),
client: Client::None,
};
let mut reads = vec![Input::step(cut.name.clone())];
for source in BASEMAP_SOURCES {
let mut input = snapshot(inputs, store, source, Vec::new(), &mut wanted)?;
if let Input::Snapshot { files, .. } = &mut input {
if source == "protomaps-basemaps" {
*files = vec![obc_data::fetch::basemap_jar()];
}
}
reads.push(input);
}
let credit = ["osm-planet", "natural-earth", "daylight-landcover"].map(attribution).join("; ");
let basemap = python(
&PLANNER_BASEMAP,
"planner/basemap",
reads,
json!({"bounds": bounds, "attribution": credit}),
("tools.planner_basemap", None),
&["basemap.pmtiles"],
);
let reference = reference(inputs, store, coverage, &mut wanted)?;
// One step per area, so that each area keeps its own version; more than one area merge as
// `planner/osm` does.
let mut shapes = Vec::new();
for source in &selection.sources {
let extract = snapshot(inputs, store, TERRAIN_OSM, vec![("area".into(), source.id.clone())], &mut wanted)?;
shapes.push(Step {
layer: &OSM,
name: format!("planner/{TERRAIN_OSM}/{}", source.id),
inputs: vec![extract],
options: json!({"path": "source.osm.pbf"}),
outputs: vec!["source.osm.pbf".into()],
run: Run::Rust(&obc_data::engine::PASS),
client: Client::None,
});
}
if shapes.len() > 1 {
let merged = crate::region_sources::combined(&format!("planner/{TERRAIN_OSM}"), &shapes);
shapes.push(merged);
}
let terrain = Step {
layer: &PLANNER_TERRAIN,
name: "planner/terrain".into(),
inputs: tiles(coverage, &land, &glo30)
.into_iter()
.chain(reference.iter().map(|step| Input::step(&step.name)))
.chain(shapes.last().map(|step| Input::step(&step.name)))
.collect(),
options: json!({"bounds": coverage, "attribution": attribution(GLO30), "osm_attribution": attribution("osm-planet")}),
outputs: vec!["terrain.mbtiles".into()],
run: Run::Rust(&functions::PLANNER_TERRAIN),
client: Client::All,
};
// The last part of the id: the old planner names its files after it.
let name = region.id.rsplit('/').next();
// A bad profile of the routing fails before any bake.
if on("routing") {
let profiles: Vec<&str> = config.routing.profiles.iter().map(String::as_str).collect();
planner_router_build::profiles(&profiles)
.and_then(|profiles| planner_router_build::catalog::check(&profiles))
.map_err(|reason| invalid(format!("the routing of region `{id}`: {reason}")))?;
}
let work = |layer: &'static Layer, inputs: Vec<Input>, options, run| Step {
layer,
name: layer.name.into(),
inputs,
options,
outputs: vec![step::folder_name(layer.name).into()],
run: Run::Rust(run),
client: Client::None,
};
let routing_source = work(
&PLANNER_ROUTING_SOURCE,
vec![Input::step(cut.name.clone())],
json!({"bounds": bounds}),
&functions::ROUTING_SOURCE,
);
let routing_roads = work(
&PLANNER_ROUTING_ROADS,
std::iter::once(Input::step(step::SOURCE))
.chain(tiles(bounds, &land, &glo30))
.chain(reference.iter().map(|step| Input::step(&step.name)))
.collect(),
json!({"bounds": bounds, "terrain_attribution": attribution(GLO30)}),
&functions::ROUTING_ROADS,
);
let routing_costs = work(
&PLANNER_ROUTING_COSTS,
vec![Input::step(step::SOURCE), Input::step(step::ROADS)],
json!({"bounds": bounds, "profiles": config.routing.profiles}),
&functions::ROUTING_COSTS,
);
// The part `route-sources` adds the routes of the second sources to the catalog.
let route_sources = match on("route-sources") {
true if !on("routing") => return Err(invalid("the layer route-sources reads routing: name both".into())),
true => route_source_step(root, inputs, store, (countries.as_slice(), bounds), &mut wanted)?,
false => None,
};
let routing = Step {
layer: &PLANNER_ROUTING,
name: "planner/routing".into(),
inputs: [step::SOURCE, step::ROADS, step::COSTS]
.into_iter()
.chain(route_sources.as_ref().map(|step| step.name.as_str()))
.map(Input::step)
.collect(),
options: json!({
"region": name,
"bounds": bounds,
"attribution": attribution("osm-planet"),
}),
outputs: vec!["routing".into(), "blocks".into(), "routes".into()],
run: Run::Rust(&functions::ROUTING),
client: Client::All,
};
let overlays = python(
&PLANNER_ROUTING,
"planner/overlays",
vec![Input::step(routing.name.clone())],
json!({"attribution": attribution("osm-planet")}),
("tools.planner_overlays", Some("planner-maps")),
&["overlays.pmtiles"],
);
let assets =
python(&PLANNER_BASEMAP, "planner/assets", assets, json!({}), ("tools.planner_assets", None), &["assets"]);
let model = python(
&PLANNER_SEARCH,
"planner/model",
vec![model],
json!({}),
("planner/search/setup.py", None),
&["model"],
);
let policy = Step {
client: Client::None,
..python(
&PLANNER_SEARCH,
"planner/search/policy",
vec![country_data],
json!({}),
("host/obc-search-bake/policy.py", Some("planner-search")),
&["policy.json", "country_osm_grid.sql.gz"],
)
};
let dump = Step {
layer: &PLANNER_SEARCH,
name: "planner/search/dump".into(),
inputs: vec![Input::step(cut.name.clone()), Input::step(policy.name.clone())],
options: json!({"country": countries[0].to_lowercase()}),
outputs: vec!["search.jsonl.zst".into()],
run: Run::Rust(&functions::SEARCH),
client: Client::None,
};
let records = Step {
client: Client::None,
..python(
&PLANNER_SEARCH,
"planner/search/records",
vec![Input::step(dump.name.clone())],
json!({}),
("planner/search/split.py", Some("planner-search")),
&["pois.jsonl.zst", "addresses.jsonl.zst"],
)
};
let content = crate::device::content_declarations(inputs, store, &selection)?;
let content_inputs = || {
content
.steps
.iter()
.map(|step| step.name.clone())
.chain(content.blocked.iter().map(|blocked| blocked.step.clone()))
.map(|name| Input::Step {
files: vec![if name.contains("landmark-content") {
"landmarks/content.json".into()
} else {
"peaks/peaks.json".into()
}],
name,
})
.collect::<Vec<_>>()
};
// One search database per component: the POIs and the addresses.
let search = |component: &str| {
python(
&PLANNER_SEARCH,
&format!("planner/search/{component}"),
std::iter::once(layer_files(&records.name, &[&format!("{component}.jsonl.zst")]))
.chain((component == "pois").then(content_inputs).into_iter().flatten())
.collect(),
json!({
"component": component,
"region": name,
"bounds": bounds,
"countries": countries,
"time_zone": time_zone,
"attribution": attribution("osm-planet"),
}),
("planner/search/build.py", Some("planner-search")),
&[component],
)
};
let (pois, addresses) = (search("pois"), search("addresses"));
let places = python(
&PLANNER_PLACES,
"planner/places",
vec![Input::step(pois.name.clone())],
json!({}),
("tools.planner_places", Some("planner-maps")),
&["places.pmtiles"],
);
let mut steps = source_steps;
steps.extend(shapes);
steps.extend(content.steps);
steps.extend(reference);
steps.extend(route_sources);
steps.extend([
osm,
cut,
terrain,
routing_source,
routing_roads,
routing_costs,
routing,
overlays,
assets,
model,
policy,
dump,
records,
pois,
addresses,
places,
basemap,
]);
if on("climate") {
steps.extend(climate(inputs, store, (bounds, &requested), config.climate.first_year, &mut wanted)?);
}
if on("snow") {
if let Some(step) = snow(inputs, store, (bounds, &requested), config.snow.seasons, &mut wanted)? {
let grids = SNOW_ARCHIVES.map(|archive| map_grid(&step, archive, Some(archive), bounds));
steps.push(Step { client: Client::None, ..step });
steps.extend(grids);
}
}
if on("trailview-features") {
osmium.map_err(Unplanned::Invalid)?;
let kinds: serde_json::Value = serde_json::from_str(include_str!("../../../data/trailview/kinds.json"))
.map_err(|e| Unplanned::Failed(format!("data/trailview/kinds.json: {e}")))?;
let roads: serde_json::Value = serde_json::from_str(include_str!("../../../data/trailview/roads.json"))
.map_err(|e| Unplanned::Failed(format!("data/trailview/roads.json: {e}")))?;
let waterways: serde_json::Value =
serde_json::from_str(include_str!("../../../data/trailview/waterways.json"))
.map_err(|e| Unplanned::Failed(format!("data/trailview/waterways.json: {e}")))?;
let finishes: serde_json::Value =
serde_json::from_str(include_str!("../../../data/trailview/finishes.json"))
.map_err(|e| Unplanned::Failed(format!("data/trailview/finishes.json: {e}")))?;
let parts: serde_json::Value = serde_json::from_str(include_str!("../../../data/trailview/parts.json"))
.map_err(|e| Unplanned::Failed(format!("data/trailview/parts.json: {e}")))?;
// The heights of roads, rivers and lakes come from the master terrain, by the class rules of the
// roads; the sea, which OSM maps only as coastlines, from the water polygons.
let sea = snapshot(inputs, store, "water-polygons", Vec::new(), &mut wanted)?;
let plan: serde_json::Value = serde_json::from_str(include_str!("../../../data/trailview/plan.json"))
.map_err(|e| Unplanned::Failed(format!("data/trailview/plan.json: {e}")))?;
// The rules of the ground plan's levels that the bake runs, as the solver's rows of the roads.
let levels = obc_trailview_features::kinds::level_rows(&roads, &waterways, &plan);
let roads = obc_trailview_features::kinds::solver_rows(&roads);
let waterways = obc_trailview_features::kinds::waterway_rows(&waterways);
let finishes = obc_trailview_features::kinds::finish_rows(&finishes);
let parts = obc_trailview_features::kinds::part_rows(&parts);
steps.push(Step {
layer: &PLANNER_TRAILVIEW_FEATURES,
name: "planner/trailview-features".into(),
inputs: vec![Input::step("planner/osm"), Input::step("planner/terrain/grid"), sea],
options: json!({"bounds": bounds, "kinds": kinds, "roads": roads, "finishes": finishes,
"waterways": waterways, "levels": levels, "parts": parts,
"attribution": attribution("osm-planet")}),
outputs: vec!["trailview-features.pmtiles".into()],
run: Run::Rust(&functions::TRAILVIEW_FEATURES),
client: Client::All,
});
steps.push(Step {
layer: &PLANNER_TRAILVIEW_FEATURES,
name: "planner/trailview-stamps".into(),
inputs: vec![Input::step("planner/trailview-features")],
// A change of the stamp code stales this step only; the feature tiles stay.
options: json!({"bounds": bounds, "attribution": attribution("osm-planet"),
"stamp_sources": stamp_sources(root).map_err(Unplanned::Failed)?}),
outputs: vec!["trailview-stamps.pmtiles".into()],
run: Run::Rust(&functions::TRAILVIEW_STAMPS),
client: Client::All,
});
}
steps.extend(trailview(root, inputs, store, &on, (bounds, &requested), &config.trailview, &mut wanted)?);
if on("trailview-canopy") {
steps.extend(trailview_canopy(inputs, store, (bounds, &requested), &mut wanted)?);
}
if on("route-facts") {
if !on("routing") {
return Err(invalid("the layer route-facts reads routing: name both".into()));
}
let listed =
["planner/trailview-canopy", "planner/snow"].map(|name| steps.iter().any(|step| step.name == name));
steps.extend(route_facts(bounds, tiles(bounds, &land, &glo30), listed));
}
let maps = [
"basemap",
"places",
"terrain",
"overlays",
"climate",
"trailview-features",
"trailview-stamps",
"trailview-ground",
"trailview-canopy",
];
let grids = steps
.iter_mut()
.filter_map(|step| {
let kind = step.name.strip_prefix("planner/")?;
if !maps.contains(&kind) {
return None;
}
step.client = Client::None;
Some(map_grid(step, kind, None, bounds))
})
.collect::<Vec<_>>();
steps.extend(grids);
for kind in ["routing", "assets", "model", "search/pois", "search/addresses"] {
let source = steps.iter_mut().find(|step| step.name == format!("planner/{kind}")).unwrap();
source.client = Client::None;
let (source, layer) = (source.name.clone(), source.layer);
let search = kind.strip_prefix("search/");
let (module, group) = match search {
Some(_) => ("tools.planner_grid_search", Some("planner-search")),
None => ("tools.planner_grid_pack", None),
};
let options = match search {
Some(component) => json!({"kind": component, "component": component, "bounds": bounds}),
None => json!({"kind": kind}),
};
steps.push(Step {
client: Client::Paths(vec!["objects".into(), "index.json".into()]),
..python(
layer,
&format!("{source}/grid"),
vec![Input::step(source)],
options,
(module, group),
&["objects", "index.json"],
)
});
}
steps.push(Step {
client: Client::Paths(vec!["objects".into(), "index.json".into()]),
..python(
&PLANNER_INDEX,
"planner/fonts/grid",
["basemap", "places", "overlays", "assets"]
.map(|kind| Input::step(format!("planner/{kind}/grid")))
.into(),
json!({"kind": "fonts"}),
("tools.planner_grid_fonts", Some("planner-maps")),
&["objects", "index.json"],
)
});
let overlays = steps.iter_mut().find(|step| step.name == "planner/overlays/grid").unwrap();
overlays.inputs.push(layer_files("planner/routing/grid", &["index.json"]));
let indexes =
|grids: &[String]| grids.iter().map(|grid| layer_files(grid, &["index.json"])).collect::<Vec<_>>();
let release = json!({
"region": name, "name": region.name, "bounds": bounds,
"attribution": attribution("osm-planet"),
"landcover_attribution": attribution("daylight-landcover"),
});
// The offline files read the grids of the core parts and the fonts, so an optional layer
// does not change them.
let core: Vec<String> =
PARTS.iter().flat_map(|(_, roots)| *roots).chain(&["planner/fonts/grid"]).map(|s| s.to_string()).collect();
steps.push(Step {
client: Client::Paths(vec!["objects".into(), "index.json".into()]),
..python(
&PLANNER_INDEX,
OFFLINE,
indexes(&core),
release.clone(),
("tools.planner_grid_offline", None),
&["objects", "index.json"],
)
});
let grids: Vec<String> =
steps.iter().filter(|step| step.name.ends_with("/grid")).map(|step| step.name.clone()).collect();
steps.push(Step {
client: Client::Paths(["objects", "release.json", "public"].map(String::from).into()),
..python(
&PLANNER_INDEX,
"planner/index",
indexes(&grids),
release,
("tools.planner_grid_index", None),
&["objects", "release.json", "public"],
)
});
steps.push(Step {
layer: &PLANNER_INDEX,
name: catalog::STEP.into(),
inputs: std::iter::once(Input::step("planner/index")).chain(indexes(&grids)).collect(),
options: json!({"origins": origins}),
outputs: vec!["catalog.json".into()],
run: Run::Rust(&functions::PLANNER_CATALOG),
client: Client::All,
});
prune(&mut steps, &on);
// Without the terrain, no step reads `terrain-osm`: its extracts are not fetched.
if !steps.iter().any(|step| step.name == "planner/terrain") {
wanted.retain(|wanted| wanted.source != TERRAIN_OSM);
}
match wanted.is_empty() {
true => {
let mut listed: Steps = steps.into();
listed.blocked.extend(content.blocked);
listed.block_dependents();
Ok(listed)
}
false => Err(Unplanned::NeedsFetch(wanted)),
}
}
}
/// The steps that make each core part of the planner. The other parts are optional layers whose
/// steps are listed only while they are on.
const PARTS: [(&str, &[&str]); 3] = [
("map", &["planner/basemap/grid", "planner/places/grid", "planner/assets/grid", "planner/terrain/grid"]),
("routing", &["planner/routing/grid", "planner/overlays/grid"]),
("search", &["planner/model/grid", "planner/search/pois/grid", "planner/search/addresses/grid"]),
];
/// The step that writes the offline catalog and its cell files from the other step indexes.
const OFFLINE: &str = "planner/offline/grid";
/// The steps that gather what the other steps make. They read only the steps that stay.
const GATHERERS: [&str; 4] = ["planner/fonts/grid", OFFLINE, "planner/index", catalog::STEP];
/// Remove the steps of each core part that is off, and then each step that no step reads any more.
/// A step that a part that is on reads stays, such as the terrain that the TrailView features read or the POIs
/// that the places of the map read.
fn prune(steps: &mut Vec<Step>, on: &dyn Fn(&str) -> bool) {
let reads = |steps: &[Step]| -> HashSet<String> {
let names = steps.iter().flat_map(|step| &step.inputs);
names.filter_map(|input| if let Input::Step { name, .. } = input { Some(name.clone()) } else { None }).collect()
};
let gatherer = |step: &Step| GATHERERS.contains(&step.name.as_str());
let mut gone: HashSet<String> = PARTS
.iter()
.filter(|(part, _)| !on(part))
.flat_map(|(_, roots)| roots.iter().map(|root| root.to_string()))
.collect();
// Only a step that lost its readers goes, never one that no step read before.
let mut collectable = reads(steps);
collectable.extend(gone.iter().cloned());
while !gone.is_empty() {
for step in steps.iter_mut().filter(|step| gatherer(step)) {
step.inputs.retain(|input| !matches!(input, Input::Step { name, .. } if gone.contains(name)));
}
let read = reads(steps);
steps.retain(|step| !gone.contains(&step.name) || read.contains(&step.name));
let read = reads(steps);
let unread = |step: &Step| collectable.contains(&step.name) && !read.contains(&step.name);
let empty = |step: &Step| gatherer(step) && step.inputs.is_empty();
gone = steps
.iter()
.filter(|step| step.name != catalog::STEP && (unread(step) || empty(step)))
.map(|step| step.name.clone())
.collect();
}
}
/// A route source of `data/routes/`: its id, the countries of its routes and the text of its
/// description.
struct RouteSource {
id: String,
countries: Vec<String>,
text: String,
}
/// The route sources of `data/routes/`, in the order of their rows in `data/sources.toml`. A
/// description without a row fails.
fn route_sources(root: &Path) -> Result<Vec<RouteSource>, String> {
#[derive(Deserialize)]
struct Description {
countries: Vec<String>,
}
let folder = root.join("data/routes");
let mut found = BTreeMap::new();
for entry in std::fs::read_dir(&folder).map_err(|e| format!("{}: {e}", folder.display()))? {
let path = entry.map_err(|e| e.to_string())?.path();
let Some(id) =
path.file_stem().and_then(|stem| stem.to_str()).filter(|_| path.extension() == Some("toml".as_ref()))
else {
continue;
};
let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
let countries = toml::from_str::<Description>(&text).map_err(|e| format!("{}: {e}", path.display()))?.countries;
found.insert(id.to_string(), RouteSource { id: id.into(), countries, text });
}
let sources = obc_data::sources::all().iter().filter_map(|row| found.remove(&row.id)).collect();
match found.into_keys().next() {
Some(id) => Err(format!("data/routes/{id}.toml has no row in data/sources.toml")),
None => Ok(sources),
}
}
/// The step `planner/route-sources`: it reads the route sources whose `countries` share a code
/// with those of the region and whose extent meets its bounds. `None` when no source does.
fn route_source_step(
root: &Path,
inputs: &Inputs,
store: &Store,
(countries, bounds): (&[String], [f64; 4]),
wanted: &mut Vec<Wanted>,
) -> Result<Option<Step>, Unplanned> {
let read = |source: &RouteSource| {
source.countries.iter().any(|code| countries.contains(code)) && embedded(&source.id).meets(bounds)
};
let sources: Vec<RouteSource> = route_sources(root).map_err(Unplanned::Failed)?.into_iter().filter(read).collect();
if sources.is_empty() {
return Ok(None);
}
let snapshots = sources.iter().map(|source| snapshot(inputs, store, &source.id, Vec::new(), wanted));
let snapshots: Vec<Input> = snapshots.collect::<Result<_, _>>()?;
let options: Vec<_> = sources
.iter()
.zip(&snapshots)
.map(|(source, input)| {
// `{year}` is the year of the version that the step reads.
let year = match input {
Input::Snapshot { version, .. } => version.get(..4).unwrap_or_default(),
Input::Step { .. } => "",
};
let credit = attribution(&source.id).replace("{year}", year);
json!({"id": source.id, "credit": credit, "description": source.text})
})
.collect();
Ok(Some(Step {
client: Client::None,
..python(
&PLANNER_ROUTING,
step::ROUTE_SOURCES,
snapshots,
json!({"bounds": bounds, "sources": options}),
("tools.planner_route_sources", Some("route-sources")),
&[planner_router_build::catalog::sources::FILE],
)
}))
}
/// The route facts and their grid. The facts read the canopy and the `snow-seasons` archive when
/// `listed` says that their steps are in the list.
fn route_facts(bounds: [f64; 4], glo30: Vec<Input>, [canopy, snow]: [bool; 2]) -> [Step; 2] {
let reads = ["planner/osm/bounds", step::SOURCE, "planner/routing"].map(Input::step);
let canopy = canopy.then(|| layer_files("planner/trailview-canopy", &["trailview-canopy.pmtiles"]));
let snow = snow.then(|| layer_files("planner/snow", &["snow-seasons.pmtiles"]));
let facts = Step {
layer: &PLANNER_ROUTE_FACTS,
name: step::FACTS.into(),
inputs: reads.into_iter().chain(glo30).chain(canopy).chain(snow).collect(),
options: json!({"bounds": bounds, "terrain_attribution": attribution(GLO30)}),
outputs: vec!["facts".into()],
run: Run::Rust(&functions::ROUTE_FACTS),
client: Client::None,
};
let grid = Step {
client: Client::Paths(vec!["objects".into(), "index.json".into()]),
..python(
&PLANNER_ROUTE_FACTS,
&format!("{}/grid", step::FACTS),
vec![Input::step(step::FACTS)],
json!({"kind": "facts"}),
("tools.planner_grid_pack", None),
&["objects", "index.json"],
)
};
[facts, grid]
}
fn layer_files(name: &str, files: &[&str]) -> Input {
Input::Step { name: name.into(), files: files.iter().map(|file| (*file).into()).collect() }
}
/// A map's transport objects and its small index ship; the index is input to the offline catalog too.
/// With `archive`, the grid reads only `<archive>.pmtiles` of a step that writes more than one.
fn map_grid(source: &Step, kind: &str, archive: Option<&str>, bounds: [f64; 4]) -> Step {
let bounds = source.options.get("bounds").cloned().unwrap_or_else(|| json!(bounds));
let (name, input, options) = match archive {
None => {
(format!("{}/grid", source.name), Input::step(source.name.clone()), json!({"kind": kind, "bounds": bounds}))
}
Some(archive) => (
format!("{}/{archive}/grid", source.name),
layer_files(&source.name, &[&format!("{archive}.pmtiles")]),
json!({"kind": kind, "bounds": bounds, "step": source.name}),
),
};
Step {
client: Client::Paths(vec!["objects".into(), "index.json".into()]),
..python(
source.layer,
&name,
vec![input],
options,
("tools.planner_grid_maps", Some("planner-maps")),
&["objects", "index.json"],
)
}
}
/// The input of the fetch of `source` with `params`, at its version. While the store lacks that
/// fetch, `wanted` names it, and the input has no version: the step list is not used then.
fn snapshot(
inputs: &Inputs,
store: &Store,
source: &str,
params: Vec<(String, String)>,
wanted: &mut Vec<Wanted>,
) -> Result<Input, Unplanned> {
let version = version(inputs, store, source, ¶ms).map_err(Unplanned::Failed)?.unwrap_or_else(|fetch| {
wanted.push(fetch);
String::new()