mln-rs-engine 0.0.21

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
//! A map in a registered projection, as its views, conversions and camera
//! helpers see 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::{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();
    }
    Map::with_file_source(
        StubFileSource::on_queue(run_loop, ResponseType::Asynchronous),
        MapOptions { size: Size::new(size, size), ..Default::default() },
        builder.build(),
        &crate::map::tests::pool(),
    )
    .expect("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);
    }
}

#[test]
fn a_view_of_the_identity_places_its_center_in_the_identity_square() {
    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));

    // Tile 1/1/0 of the identity spans lng 0..90 and lat 0..90, and fills
    // the view; Mercator would put 45° N well above the view's middle.
    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 = projection.lat_lng_for_pixel(&ScreenCoordinate::new(0.0, 0.0), 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);
}

#[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 `type_`, whose rings are `rings` in
/// tile coordinates.
struct TileFeature {
    type_: 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.type_
    }

    fn value(&self, _key: &str) -> Option<mln_style::feature::Value> {
        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(type_: mln_style::feature::FeatureType, rings: &[&[(i16, i16)]]) -> TileFeature {
    let rings = rings.iter().map(|ring| ring.iter().map(|&(x, y)| geometry::Point::new(x, y)).collect::<Vec<_>>());
    TileFeature { type_, rings: mln_style::feature::GeometryCollection::from(rings.collect::<Vec<_>>()) }
}

/// GL JS's
/// "[query returns geometry through the transform projection](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/data/feature_index.test.ts#L119-L134)"
/// (`src/data/feature_index.test.ts`): 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; 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])
    );
}

/// GL JS's
/// "[fits the cap north of 60N with the pole at the center](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/ui/map_tests/map_projection.test.ts#L125-L132)"
/// (`src/ui/map_tests/map_projection.test.ts`): the cap's corners are the
/// pole and two points on its edge, but its world box 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 converter that records how many positions each call of its `forward`
/// takes.
struct CountedForward {
    converter: Box<dyn mln_style::crs::CrsConverter>,
    calls: std::sync::Arc<parking_lot::Mutex<Vec<usize>>>,
}

impl mln_style::crs::CrsConverter for CountedForward {
    fn forward(&self, lng_lats: &[[f64; 2]], positions: &mut [[f64; 2]]) {
        self.calls.lock().push(lng_lats.len());
        self.converter.forward(lng_lats, positions);
    }

    fn inverse(&self, positions: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
        self.converter.inverse(positions, lng_lats);
    }
}

// gtest: Map.LatLngBoundsToCameraInAPolarProjection
// The box is fitted by its samples, the 17 by 17 grid and the halfway
// points of its edges, which go through the converter in one call.
#[test]
fn a_box_is_fitted_by_its_samples_in_one_batch() {
    let run_loop = Queue::<()>::new();
    let calls = std::sync::Arc::default();
    let polar = crs::north_polar_stereographic("test:polar-fit");
    let converter = Box::new(CountedForward { converter: polar.converter, calls: std::sync::Arc::clone(&calls) });
    let mut map = map(512, vec![mln_style::crs::Crs { converter, ..polar }], &run_loop);
    map.load_style_json(&style("test:polar-fit", [0.0, 70.0], 2.0));
    calls.lock().clear();

    // Its corners are the pole and one point on its edge, but the cap north
    // of 60 N is a disc around the pole.
    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);
    let calls = calls.lock();
    assert!(calls.contains(&(17 * 17 + 4 * 16)), "{calls:?}");
    assert!(calls.len() < 17 * 17, "{calls:?}");
}

/// GL JS's
/// [`cameraForBoxAndBearing`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/camera/mercator_camera_motions.ts#L69-L141)
/// fits a box 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: 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. GL JS keeps the whole view
/// inside them, which `ConstrainMode::Screen` does
/// (`src/camera/mercator_camera_math.test.ts`,
/// "[keeps the viewport inside explicit max bounds set inside the square](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/camera/mercator_camera_math.test.ts#L1391-L1403)").
#[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 = Map::with_file_source(
            StubFileSource::on_queue(&run_loop, ResponseType::Asynchronous),
            options,
            crate::tests::registry(),
            &crate::map::tests::pool(),
        )
        .unwrap();
        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);
    }
}

/// GL JS's
/// "[keeps a center on the far side of the pole inside maxBounds of the cap north of 60N](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/ui/map_tests/map_projection.test.ts#L134-L142)"
/// (`src/ui/map_tests/map_projection.test.ts`).
#[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);
}

/// Meters per pixel as GL JS's
/// [geolocate control](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/ui/control/geolocate_control.ts#L585-L596)
/// measures them in a registered projection: the ground distance from a
/// location to the place 100 pixels from it along the screen's x axis, on
/// the sphere of GL JS's
/// [`LngLat.distanceTo`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/lng_lat.ts#L133-L140),
/// over 100, in pixels of the flat map, whatever the pitch. The numbers are
/// GL JS's for its
/// [test polar stereographic projection](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/util/test/util.ts#L565-L583)
/// 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 gl_js = |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));
        gl_js(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));
    gl_js(meters, MapProjection::new(&map).meters_per_pixel_at(&location));
    // At the latitude, on the center's meridian.
    gl_js(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, as GL JS measures it 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 GL JS's 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);
}

/// GL JS's
/// "[setProjection accepts the registered name](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/ui/map_tests/map_projection.test.ts#L87-L94)"
/// (`src/ui/map_tests/map_projection.test.ts`), from Rust: a style edit
/// sets the 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(&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);
    }
}