mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
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
//! A map whose style names a registered projection: the map finds it in its
//! registry, and its views, conversions and camera helpers follow it.

use approx::{assert_abs_diff_eq, assert_relative_eq};
use mln_style::crs::WorldMapping;
use mln_style::error::ErrorKind;
use mln_style::geo::{LatLng, LatLngBounds, WrapMode};
use mln_style::size::Size;

use crate::camera::{BoundOptions, CameraFitOptions, CameraOptions, ConstrainMode, MapProjection, ViewProjection};
use crate::exec::queue::Queue;
use crate::geo::ScreenCoordinate;
use crate::geo::projection::Projection;
use crate::map::{Map, MapOptions};
use crate::storage::stub_file_source::{ResponseType, StubFileSource};
use crate::tests::log_capture::LogCapture;
use crate::tests::{crs, registry_builder};

/// A map of `size` pixels square whose registry has the built-in projections
/// and `extra`.
fn map(size: u32, extra: Vec<mln_style::crs::Crs>, run_loop: &Queue<()>) -> Map {
    let mut builder = registry_builder();
    for crs in extra {
        builder.add_projection(crs).unwrap();
    }
    let map = Map::with_file_source(
        StubFileSource::on_queue(run_loop, ResponseType::Asynchronous),
        MapOptions { size: Size::new(size, size), ..Default::default() },
        builder.build(),
        &super::pool(),
    )
    .expect("map");
    super::hold_clock(&map);
    map
}

/// A style without sources in the projection `projection`, centered on
/// `[lng, lat]` at `zoom`.
fn style(projection: &str, [lng, lat]: [f64; 2], zoom: f64) -> String {
    format!(
        r#"{{"version":8,"projection":{{"type":"{projection}"}},"center":[{lng},{lat}],"zoom":{zoom},"sources":{{}},"layers":[]}}"#
    )
}

fn ll(lat: f64, lng: f64) -> LatLng {
    LatLng::new(lat, lng).unwrap()
}

#[test]
fn a_projection_from_a_view_converts_in_its_registered_projection() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, vec![crs::north_polar_stereographic("test:polar")], &run_loop);
    map.load_style_json(&style("test:polar", [45.0, 70.0], 3.0));
    map.jump_to(&CameraOptions { bearing: Some(20.0), pitch: Some(30.0), ..CameraOptions::default() });

    let view = map.snapshot().view;
    assert_eq!(ViewProjection::Registered(map.transform_state().view().world().clone()), view.projection);
    let projection = MapProjection::from_view(&view).unwrap();
    let from_map = MapProjection::new(&map);
    for lat_lng in [ll(70.0, 45.0), ll(75.0, 10.0), ll(66.0, 80.0)] {
        let expected = from_map.pixel_for_lat_lng(&lat_lng);
        let actual = projection.pixel_for_lat_lng(&lat_lng);
        assert_abs_diff_eq!(actual.x, expected.x, epsilon = 1e-6);
        assert_abs_diff_eq!(actual.y, expected.y, epsilon = 1e-6);
        let back = projection.lat_lng_for_pixel(&actual, WrapMode::Unwrapped).unwrap();
        assert_abs_diff_eq!(lat_lng.latitude(), back.latitude(), epsilon = 1e-9);
        assert_abs_diff_eq!(lat_lng.longitude(), back.longitude(), epsilon = 1e-9);
    }
    assert_eq!(map.snapshot().view, view.to_view().unwrap().map_view(view.extent.scale_factor));
}

/// A view says in one value what it draws in, so a view that a map drew on
/// the globe, kept until after the map switched to the identity, still
/// converts on the globe, and the map's views of the identity convert flat:
/// no view pairs the globe's transition with a registered projection. A
/// degree of latitude at 20 N spans 2048 / 180 pixels of the identity at
/// zoom 2, and about half that on the globe.
#[test]
fn a_kept_globe_view_draws_the_globe_and_the_maps_new_views_draw_flat() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, Vec::new(), &run_loop);
    let degree_of_latitude = |projection: &MapProjection| {
        projection.pixel_for_lat_lng(&ll(21.0, 10.0)).y - projection.pixel_for_lat_lng(&ll(20.0, 10.0)).y
    };
    map.load_style_json(&style("globe", [10.0, 20.0], 2.0));
    let kept = map.snapshot().view;
    assert!(matches!(kept.projection, ViewProjection::BuiltIn(_)), "{:?}", kept.projection);
    let on_the_globe = degree_of_latitude(&MapProjection::from_view(&kept).unwrap()).abs();
    assert!(on_the_globe < 7.0, "{on_the_globe}");

    map.load_style_json(&style("identity", [10.0, 20.0], 2.0));
    let flat = map.snapshot().view;
    assert!(matches!(flat.projection, ViewProjection::Registered(_)), "{:?}", flat.projection);
    assert_eq!(on_the_globe, degree_of_latitude(&MapProjection::from_view(&kept).unwrap()).abs());
    let kept_camera_flat = crate::camera::MapView { projection: flat.projection.clone(), ..kept };
    for view in [flat, kept_camera_flat] {
        let projection = MapProjection::from_view(&view).unwrap();
        assert_relative_eq!(degree_of_latitude(&projection).abs(), 2048.0 / 180.0, max_relative = 1e-6);
    }
}

/// Tile 1/1/0 of the identity spans lng 0..90 and lat 0..90, and fills the
/// view of a style centered on its middle at zoom 1, in the map's and its
/// views' conversions alike; Mercator would put 45° N well above the view's
/// middle.
#[test]
fn a_style_draws_in_the_registered_projection_it_names() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, Vec::new(), &run_loop);
    map.load_style_json(&style("identity", [45.0, 45.0], 1.0));
    let view = map.transform_state().view();
    assert_eq!("identity", view.world().name());
    assert_eq!(ll(45.0, 45.0), view.center(WrapMode::Unwrapped));

    let projection = MapProjection::from_view(&map.snapshot().view).unwrap();
    let middle = projection.pixel_for_lat_lng(&ll(45.0, 45.0));
    assert_abs_diff_eq!(256.0, middle.x, epsilon = 1e-9);
    assert_abs_diff_eq!(256.0, middle.y, epsilon = 1e-9);
    let top_left = ScreenCoordinate::new(0.0, 0.0);
    for top_left in [
        projection.lat_lng_for_pixel(&top_left, WrapMode::Unwrapped).unwrap(),
        map.lat_lng_for_pixel(&top_left, WrapMode::Unwrapped).unwrap(),
    ] {
        assert_abs_diff_eq!(90.0, top_left.latitude(), epsilon = 1e-6);
        assert_abs_diff_eq!(0.0, top_left.longitude(), epsilon = 1e-6);
    }
    let bottom_right = map.pixel_for_lat_lng(&ll(0.0, 90.0));
    assert_abs_diff_eq!(512.0, bottom_right.x, epsilon = 1e-5);
    assert_abs_diff_eq!(512.0, bottom_right.y, epsilon = 1e-5);
}

/// A style that names a projection the registry doesn't have draws in
/// Mercator, and the map warns once.
#[test]
fn an_unregistered_projection_draws_mercator_with_a_warning() {
    let log = LogCapture::new();
    let run_loop = Queue::<()>::new();
    let mut map = map(512, Vec::new(), &run_loop);
    map.load_style_json(&style("test:unknown", [10.0, 60.0], 3.0));

    let view = map.transform_state().view();
    assert!(view.world().wraps());
    assert_abs_diff_eq!(60.0, view.center(WrapMode::Unwrapped).latitude(), epsilon = 1e-9);
    assert_eq!(
        1,
        log.count(
            tracing::Level::WARN,
            "mln_engine::general",
            "The style's projection isn't registered: the map draws in Mercator name=test:unknown"
        )
    );
}

/// The map finds a projection in its own registry, and the projection keeps
/// its mapping while the style keeps naming it; a style that drops it
/// draws Mercator, with the center where it was.
#[test]
fn the_map_finds_a_projection_in_its_own_registry_and_leaves_it_with_the_style() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, vec![crs::north_polar_stereographic("test:polar")], &run_loop);
    map.load_style_json(&style("test:polar", [45.0, 70.0], 3.0));

    let view = map.transform_state().view();
    assert_eq!("test:polar", view.world().name());
    assert_abs_diff_eq!(70.0, view.center(WrapMode::Unwrapped).latitude(), epsilon = 1e-9);
    assert_abs_diff_eq!(45.0, view.center(WrapMode::Unwrapped).longitude(), epsilon = 1e-9);

    let world = view.world().clone();
    map.edit_style(|style| style.set_root_property_json("projection", r#"{"type":"test:polar"}"#)).unwrap();
    assert_eq!(world, *map.transform_state().view().world());
    map.edit_style(|style| style.set_root_property_json("projection", r#"{"type":"mercator"}"#)).unwrap();
    let view = map.transform_state().view();
    assert!(view.world().wraps());
    assert_abs_diff_eq!(70.0, view.center(WrapMode::Unwrapped).latitude(), epsilon = 1e-9);
    assert_abs_diff_eq!(45.0, view.center(WrapMode::Unwrapped).longitude(), epsilon = 1e-9);
}

#[test]
fn a_view_whose_center_the_projection_has_no_place_for_is_refused() {
    let northern = crs::crs(
        "test:northern",
        |[lng, lat]| if lat < 0.0 { [f64::NAN; 2] } else { [lng, lat] },
        |position| position,
        [-90.0, 90.0],
        180.0,
    );
    let run_loop = Queue::<()>::new();
    let map = map(256, Vec::new(), &run_loop);
    let mut view = map.snapshot().view;
    view.camera.center = ll(-10.0, 0.0);
    view.projection = ViewProjection::Registered(crs::mapping(northern));

    let error = MapProjection::from_view(&view).err().map(|error| error.kind);
    assert_eq!(Some(ErrorKind::InvalidArgument), error);
}

/// A feature of tile `z/x/y` of type `kind`, whose rings are `rings` in
/// tile coordinates.
struct TileFeature {
    kind: mln_style::feature::FeatureType,
    rings: mln_style::feature::GeometryCollection,
}

impl mln_style::feature::GeometryTileFeature for TileFeature {
    fn feature_type(&self) -> mln_style::feature::FeatureType {
        self.kind
    }

    fn value_ref(&self, _key: &str) -> Option<mln_style::feature::ValueRef<'_>> {
        None
    }

    fn geometries(
        &self,
    ) -> Result<std::borrow::Cow<'_, mln_style::feature::GeometryCollection>, mln_style::error::Error> {
        Ok(std::borrow::Cow::Borrowed(&self.rings))
    }
}

fn tile_feature(kind: mln_style::feature::FeatureType, rings: &[&[(i16, i16)]]) -> TileFeature {
    let rings =
        rings.iter().map(|ring| ring.iter().map(|&(x, y)| mln_style::geometry::Point::new(x, y)).collect::<Vec<_>>());
    TileFeature { kind, rings: mln_style::feature::GeometryCollection::from(rings.collect::<Vec<_>>()) }
}

/// A queried feature is located through the projection: the top left of
/// tile 2/1/2 is a quarter of the way across the identity's square and
/// halfway down, at 45° W on the equator, where Web Mercator puts it at
/// 90° W.
#[test]
fn a_queried_feature_has_the_location_the_identity_gives_its_tile_coordinates() {
    use mln_style::feature::{FeatureType, GeometryTileFeature};

    let tile = mln_style::tile_id::CanonicalTileID::new(2, 1, 2);
    let point = tile_feature(FeatureType::Point, &[&[(0, 0)]]);
    let converted =
        crate::tile::convert_feature(&point, &point.geometries().unwrap(), &tile, &crs::identity()).unwrap();
    assert_eq!(Some(geo_types::Geometry::Point(geo_types::Point::new(-45.0, 0.0))), converted.geometry);
    let mercator =
        crate::tile::convert_feature(&point, &point.geometries().unwrap(), &tile, &WorldMapping::default()).unwrap();
    let Some(geo_types::Geometry::Point(mercator)) = mercator.geometry else { panic!("a point: {mercator:?}") };
    assert_eq!(-90.0, mercator.x());
    assert_abs_diff_eq!(0.0, mercator.y(), epsilon = 1e-12);

    // A square with a square hole, its rings in order, each corner where the
    // identity puts it: a tile's 8192 units are 45 degrees at zoom 2.
    let square = &[(0, 0), (8192, 0), (8192, 8192), (0, 8192), (0, 0)][..];
    let hole = &[(2048, 2048), (2048, 6144), (6144, 6144), (6144, 2048), (2048, 2048)][..];
    let polygon = tile_feature(FeatureType::Polygon, &[square, hole]);
    let converted =
        crate::tile::convert_feature(&polygon, &polygon.geometries().unwrap(), &tile, &crs::identity()).unwrap();
    let Some(geo_types::Geometry::Polygon(converted)) = converted.geometry else {
        panic!("a polygon: {converted:?}");
    };
    let lng_lats =
        |ring: &geo_types::LineString<f64>| ring.0.iter().map(|coord| (coord.x, coord.y)).collect::<Vec<_>>();
    assert_eq!(
        vec![(-45.0, 0.0), (0.0, 0.0), (0.0, -45.0), (-45.0, -45.0), (-45.0, 0.0)],
        lng_lats(converted.exterior())
    );
    assert_eq!(
        vec![(-33.75, -11.25), (-33.75, -33.75), (-11.25, -33.75), (-11.25, -11.25), (-33.75, -11.25)],
        lng_lats(&converted.interiors()[0])
    );
}

/// The camera for the cap north of 60° N centers on the pole: the box's
/// corners are the pole and two points on its edge, but it is fitted by
/// samples across it, whose box in the world is the square around the
/// pole.
#[test]
fn the_camera_for_a_polar_cap_centers_on_the_pole() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, vec![crs::polar_stereographic("test:polar")], &run_loop);
    map.load_style_json(&style("test:polar", [0.0, 70.0], 2.0));

    let cap = LatLngBounds::hull(ll(60.0, -180.0), ll(90.0, 180.0));
    let camera = map.camera_for_lat_lng_bounds(&cap, &CameraFitOptions::default()).unwrap();
    assert_abs_diff_eq!(90.0, camera.center.unwrap().latitude(), epsilon = 1e-6);

    // The fitted camera shows the whole cap: its edge at 60° N, down the
    // view along the projection's central meridian, is just inside the
    // view's bottom edge, as far inside as the box grew by how far its
    // edges curve between samples.
    map.jump_to(&camera);
    let edge = map.pixel_for_lat_lng(&ll(60.0, -45.0));
    assert!(500.0 < edge.y && edge.y <= 512.0, "{edge:?}");
}

/// A box is fitted at a bearing by its samples turned with the view: a
/// polar cap, round about its pole, fits at the same zoom at any bearing,
/// where the corners of its world box would stick out at 45° and fit it
/// half a zoom level out.
#[test]
fn the_camera_for_a_polar_cap_fits_it_at_any_bearing() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, vec![crs::polar_stereographic("test:polar")], &run_loop);
    map.load_style_json(&style("test:polar", [0.0, 70.0], 2.0));

    let cap = LatLngBounds::hull(ll(60.0, -180.0), ll(90.0, 180.0));
    let at = |bearing: f64| {
        let options = CameraFitOptions { bearing: Some(bearing), ..CameraFitOptions::default() };
        map.camera_for_lat_lng_bounds(&cap, &options).unwrap()
    };
    let (north_up, turned) = (at(0.0), at(45.0));
    assert_abs_diff_eq!(north_up.zoom.unwrap(), turned.zoom.unwrap(), epsilon = 1e-9);
    assert_abs_diff_eq!(45.0, turned.bearing.unwrap(), epsilon = 1e-9);
    assert_abs_diff_eq!(90.0, turned.center.unwrap().latitude(), epsilon = 1e-6);
}

/// A box of the identity is the rectangle of its corners: lng 0..90 and lat
/// 0..90, half the square across, fill a 512-pixel view at zoom 1.
#[test]
fn the_camera_for_a_box_of_the_identity_fills_the_view_with_it() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, Vec::new(), &run_loop);
    map.load_style_json(&style("identity", [0.0, 0.0], 0.0));

    let quarter = LatLngBounds::hull(ll(0.0, 0.0), ll(90.0, 90.0));
    let camera = map.camera_for_lat_lng_bounds(&quarter, &CameraFitOptions::default()).unwrap();
    assert_abs_diff_eq!(45.0, camera.center.unwrap().latitude(), epsilon = 1e-9);
    assert_abs_diff_eq!(45.0, camera.center.unwrap().longitude(), epsilon = 1e-9);
    assert_abs_diff_eq!(1.0, camera.zoom.unwrap(), epsilon = 1e-6);
}

/// The view's corners in a registered projection: north is up at the
/// center's meridian only, so the area's eastmost location is at the view's
/// top-right corner, not at its bottom-right one.
#[test]
fn the_bounds_a_camera_shows_hold_every_corner_of_the_view() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, vec![crs::north_polar_stereographic("test:polar")], &run_loop);
    map.load_style_json(&style("test:polar", [0.0, 70.0], 3.0));

    let bounds = map.lat_lng_bounds_for_camera(&CameraOptions::default()).unwrap();
    for (x, y) in [(0.0, 0.0), (512.0, 0.0), (512.0, 512.0), (0.0, 512.0)] {
        let corner = map.lat_lng_for_pixel(&ScreenCoordinate::new(x, y), WrapMode::Unwrapped).unwrap();
        assert!(bounds.contains(&corner), "{corner:?} isn't in {bounds:?}");
    }
    let top_right = map.lat_lng_for_pixel(&ScreenCoordinate::new(512.0, 0.0), WrapMode::Unwrapped).unwrap();
    let bottom_right = map.lat_lng_for_pixel(&ScreenCoordinate::new(512.0, 512.0), WrapMode::Unwrapped).unwrap();
    assert!(top_right.longitude() > bottom_right.longitude(), "{top_right:?} {bottom_right:?}");
    assert_eq!(bounds, map.lat_lng_bounds_for_camera_unwrapped(&CameraOptions::default()).unwrap());
}

/// Max bounds keep the center inside them, as Mercator's do, or with
/// `ConstrainMode::Screen` the whole view: at zoom 4 the identity's 180
/// degrees are 8192 pixels, and a 200-pixel view centered on the bounds'
/// corner reaches 100 pixels past it.
#[test]
fn max_bounds_inside_the_identity_keep_the_center_or_with_screen_the_view() {
    for (mode, corner) in [(ConstrainMode::HeightOnly, 10.0), (ConstrainMode::Screen, 10.0 - 100.0 * 180.0 / 8192.0)] {
        let run_loop = Queue::<()>::new();
        let options = MapOptions { size: Size::new(200, 200), constrain_mode: mode, ..Default::default() };
        let mut map = super::test_map(StubFileSource::on_queue(&run_loop, ResponseType::Asynchronous), options);
        map.load_style_json(&style("identity", [0.0, 0.0], 4.0));
        let bounds = LatLngBounds::hull(ll(-10.0, -10.0), ll(10.0, 10.0));
        map.set_bounds(&BoundOptions { bounds: Some(bounds), ..BoundOptions::default() }).unwrap();

        map.jump_to(&CameraOptions { center: Some(ll(80.0, 80.0)), ..CameraOptions::default() });
        let center = map.transform_state().view().center(WrapMode::Unwrapped);
        assert_abs_diff_eq!(corner, center.latitude(), epsilon = 1e-6);
        assert_abs_diff_eq!(corner, center.longitude(), epsilon = 1e-6);
    }
}

/// A center past the pole, inside max bounds of the cap north of 60° N,
/// stays where it is: the cap holds it, though the box of its corners
/// doesn't.
#[test]
fn a_center_beyond_the_pole_stays_inside_the_max_bounds_of_a_polar_cap() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, vec![crs::polar_stereographic("test:polar")], &run_loop);
    map.load_style_json(&style("test:polar", [0.0, 70.0], 3.0));
    let cap = LatLngBounds::hull(ll(60.0, -180.0), ll(90.0, 180.0));
    map.set_bounds(&BoundOptions { bounds: Some(cap), ..BoundOptions::default() }).unwrap();

    map.jump_to(&CameraOptions { center: Some(ll(70.0, 45.0)), ..CameraOptions::default() });
    let center = map.transform_state().view().center(WrapMode::Unwrapped);
    assert_abs_diff_eq!(70.0, center.latitude(), epsilon = 1e-6);
    assert_abs_diff_eq!(45.0, center.longitude(), epsilon = 1e-6);
}

/// In a registered projection, meters per pixel are the ground distance on
/// a sphere of 6,371,008.8 m from a location to the place 100 pixels from
/// it along the screen's x axis, over 100, in pixels of the flat map,
/// whatever the pitch; here of a polar stereographic projection at bearing
/// 0. Mercator keeps its scale at the latitude.
#[test]
fn meters_per_pixel_are_the_projections() {
    let run_loop = Queue::<()>::new();
    let mut mercator = map(512, Vec::new(), &run_loop);
    mercator.load_style_json(&style("mercator", [10.0, 40.0], 3.5));
    let mercator = MapProjection::new(&mercator);
    for latitude in [0.0, 40.0, -70.0] {
        let scale = Projection::meters_per_pixel_at_latitude(latitude, 3.5);
        assert_eq!(scale, mercator.meters_per_pixel_at_latitude(latitude));
        assert_eq!(scale, mercator.meters_per_pixel_at(&ll(latitude, 20.0)));
    }

    let assert_meters = |expected: f64, actual: f64| {
        assert_relative_eq!(actual, expected, max_relative = 1e-9);
    };
    let mut map = map(512, vec![crs::polar_stereographic("test:polar")], &run_loop);
    map.load_style_json(&style("test:polar", [-45.0, 70.0], 4.0));
    let camera = |center, zoom, bearing, pitch| CameraOptions {
        center: Some(center),
        zoom: Some(zoom),
        bearing: Some(bearing),
        pitch: Some(pitch),
        ..CameraOptions::default()
    };
    let cameras = [
        (ll(70.0, -45.0), 4.0, ll(70.0, -45.0), 1_022.832_584_048_677_6),
        (ll(80.0, 30.0), 6.0, ll(81.0, 40.0), 261.998_661_983_620_9),
        (ll(60.0, -100.0), 8.0, ll(60.1, -100.2), 61.535_774_394_909_105),
    ];
    for (center, zoom, location, meters) in cameras {
        map.jump_to(&camera(center, zoom, 0.0, 0.0));
        assert_meters(meters, MapProjection::new(&map).meters_per_pixel_at(&location));
    }
    let (center, zoom, location, meters) = cameras[0];
    map.jump_to(&camera(center, zoom, 0.0, 45.0));
    assert_meters(meters, MapProjection::new(&map).meters_per_pixel_at(&location));
    // At the latitude, on the center's meridian.
    assert_meters(meters, MapProjection::new(&map).meters_per_pixel_at_latitude(location.latitude()));
}

/// In the identity projection, a degree of longitude spans less ground than
/// a degree of latitude away from the equator. At bearing 0 the screen's x
/// axis runs along the parallel at 20 N; at bearing 90 it runs south, and
/// 100 pixels at zoom 2, where the square's 180 degrees are 2048 pixels,
/// span that many degrees of a meridian, on the sphere of 6,371,008.8 m.
#[test]
fn meters_per_pixel_follow_the_screens_x_axis() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, Vec::new(), &run_loop);
    map.load_style_json(&style("identity", [10.0, 20.0], 2.0));
    let location = ll(20.0, 10.0);
    assert_abs_diff_eq!(9_182.565_332_549_524, MapProjection::new(&map).meters_per_pixel_at(&location), epsilon = 1e-6);

    map.jump_to(&CameraOptions { bearing: Some(90.0), ..CameraOptions::default() });
    let degrees = 100.0 * 180.0 / 2048.0;
    let along_the_meridian = 6_371_008.8 * f64::to_radians(degrees) / 100.0;
    assert_abs_diff_eq!(along_the_meridian, MapProjection::new(&map).meters_per_pixel_at(&location), epsilon = 1e-6);
}

/// At zoom 25, the 100 pixels that the identity's meters per pixel are
/// measured across are 6 cm of the parallel at 60 N, which the spherical law
/// of cosines rounds to no distance at all: a pixel still spans its share of
/// the parallel, whose length is half the earth's mean circumference there.
#[test]
fn meters_per_pixel_hold_at_the_highest_zoom() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, Vec::new(), &run_loop);
    map.load_style_json(&style("identity", [10.0, 60.0], 2.0));
    let mut view = map.snapshot().view;
    view.camera.zoom = 25.0;
    let projection = MapProjection::from_view(&view).unwrap();
    let half_parallel = std::f64::consts::PI * 6_371_008.8 * 60f64.to_radians().cos();
    let expected = half_parallel / (512.0 * 2f64.powi(25));
    assert_relative_eq!(expected, projection.meters_per_pixel_at(&ll(60.0, 10.0)), max_relative = 1e-6);
}

/// A style edit sets a registered projection by its name, as it sets a
/// built-in one, and the map draws in it, its center where it was.
#[test]
fn a_registered_projection_set_from_rust_draws_the_map_in_it() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, vec![crs::north_polar_stereographic("test:polar")], &run_loop);
    map.load_style_json(&style("mercator", [45.0, 70.0], 3.0));
    assert!(map.transform_state().view().world().wraps());

    let mut projection = mln_style::projection::Projection::new();
    projection.set_registered_name("test:polar").unwrap();
    map.edit_style(|style| style.apply(mln_style::Edit::SetProjection(projection))).unwrap();

    let view = map.transform_state().view();
    assert_eq!("test:polar", view.world().name());
    assert_eq!(Some("test:polar"), map.style().projection().registered_name());
    assert_abs_diff_eq!(70.0, view.center(WrapMode::Unwrapped).latitude(), epsilon = 1e-9);
    assert_abs_diff_eq!(45.0, view.center(WrapMode::Unwrapped).longitude(), epsilon = 1e-9);
}

/// Over terrain in a registered projection, the ground a screen point shows
/// is located through the projection, and a location stands on the ground
/// drawn at its place in the projection's world square: here ground that
/// rises eastward across the identity's square.
#[test]
fn ground_hits_are_located_through_the_registered_projection() {
    let run_loop = Queue::<()>::new();
    let mut map = map(512, Vec::new(), &run_loop);
    map.load_style_json(&style("identity", [45.0, 45.0], 1.0));
    map.jump_to(&CameraOptions { pitch: Some(50.0), ..CameraOptions::default() });
    // The identity's world is 180 m wide: the eye is about 90 m up.
    let ground = super::ground::Slope { x: 0.5, height: 10.0, rise: 20.0 };
    let view = map.transform_state().view();

    for (x, y) in [(256.0, 256.0), (100.0, 150.0), (400.0, 60.0)] {
        // Measured from the bottom edge.
        let point = ScreenCoordinate::new(x, y);
        let hit = view.ground_under(&point, &ground).expect("the ground");
        let location = view.screen_coordinate_to_lat_lng_on(&point, &ground, WrapMode::Unwrapped).unwrap();
        let expected =
            view.world().lat_lng_from_world(&mln_style::geometry::Point::new(hit.world.x, hit.world.y)).unwrap();
        assert_eq!(expected, location);
        assert_eq!(expected, hit.location(view.world(), WrapMode::Unwrapped));

        let drawn = view.drawn_height_at(&location, &ground).unwrap();
        assert_abs_diff_eq!(hit.height, drawn, epsilon = 1e-3);
        let back = view.lat_lng_to_screen_coordinate_on(&location, &ground);
        assert_abs_diff_eq!(x, back.x, epsilon = 1e-4);
        assert_abs_diff_eq!(y, back.y, epsilon = 1e-4);
    }
}