1use std::f64::consts::PI;
5
6use geometry::Point;
7use glam::dcamera::rh::proj::opengl::perspective;
8use glam::{DMat4, DVec2, DVec3, DVec4};
9use mln_style::constants::TILE_SIZE_D;
10use mln_style::crs::WorldMapping;
11use mln_style::error::Error;
12use mln_style::geo::{LatLng, WrapMode};
13use mln_style::size::Size;
14use mln_style::types::ProjectionDefinition;
15
16use crate::camera::camera::FreeCameraOptions;
17use crate::camera::camera_pose::CameraPose;
18use crate::camera::constants::{DEFAULT_FOV, MAX_ZOOM, MIN_ZOOM};
19use crate::camera::map_view::{Camera, LogicalExtent, MapView, ViewProjection, Viewport};
20use crate::camera::mode::ConstrainMode;
21use crate::camera::projection::{ProjectionData, mercator_tile_matrix};
22use crate::camera::projection_mode::{AxonometricMode, ProjectionMode};
23use crate::camera::tile_coordinate::TileCoordinate;
24use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
25pub use crate::geo::NorthOrientation;
26use crate::geo::projection::Projection;
27use crate::geo::{EdgeInsets, ScreenCoordinate};
28use crate::tile::UnwrappedTileID;
29
30pub(crate) fn max_mercator_horizon_angle() -> f64 {
34 mln_style::math::deg2rad(89.25)
35}
36
37fn round_for_accuracy(x: f64) -> f64 {
40 let round_x = x.round();
41 let diff = (round_x - x).abs();
42 if diff < 1e-9 && diff > 0.0 { round_x } else { x }
43}
44
45#[must_use]
47pub fn zoom_scale(zoom: f64) -> f64 {
48 round_for_accuracy(2.0f64.powf(zoom))
49}
50
51#[must_use]
53pub fn scale_zoom(scale: f64) -> f64 {
54 round_for_accuracy(scale.log2())
55}
56
57pub(crate) fn center_offset(world: &WorldMapping, center: &LatLng, scale: f64) -> Option<(f64, f64)> {
62 let point = world.project_from_center(center, scale);
63 (point.x.is_finite() && point.y.is_finite()).then_some((-point.x, -point.y))
64}
65
66const SCALE_SPAN_PX: f64 = 100.0;
70
71fn modf_fraction(x: f64) -> f64 {
73 if x.is_infinite() {
74 return 0.0f64.copysign(x);
75 }
76 (x - x.trunc()).copysign(x)
77}
78
79#[derive(Clone, Debug, PartialEq)]
81pub(crate) struct ViewParams {
82 pub(crate) size: Size,
83 pub(crate) frustum_offset: EdgeInsets,
84 pub(crate) north_orientation: NorthOrientation,
85 pub(crate) constrain_mode: ConstrainMode,
88 pub(crate) center_clamped_to_ground: bool,
91 pub(crate) globe_free_bearing: bool,
94 pub(crate) projection: ViewProjection,
97 pub(crate) padding: EdgeInsets,
98 pub(crate) x: f64,
101 pub(crate) y: f64,
102 pub(crate) center_altitude: f64,
105 pub(crate) scale: f64,
106 pub(crate) angle: f64,
109 pub(crate) pitch: f64,
110 pub(crate) roll: f64,
111 pub(crate) fov: f64,
112 pub(crate) x_skew: f64,
113 pub(crate) y_skew: f64,
114 pub(crate) axonometric: bool,
115 pub(crate) center_wrap: WrapMode,
117 pub(crate) terrain_min_elevation: Option<f64>,
120}
121
122impl ViewParams {
123 pub(crate) fn new(constrain_mode: ConstrainMode) -> Self {
124 ViewParams {
125 size: Size::default(),
126 frustum_offset: EdgeInsets::default(),
127 north_orientation: NorthOrientation::Upwards,
128 constrain_mode,
129 center_clamped_to_ground: true,
130 globe_free_bearing: false,
131 projection: ViewProjection::BuiltIn(ProjectionDefinition::default()),
132 padding: EdgeInsets::default(),
133 x: 0.0,
134 y: 0.0,
135 center_altitude: 0.0,
136 scale: 1.0,
137 angle: 0.0,
138 pitch: 0.0,
139 roll: 0.0,
140 fov: DEFAULT_FOV,
141 x_skew: 0.0,
142 y_skew: 1.0,
143 axonometric: false,
144 center_wrap: WrapMode::Unwrapped,
145 terrain_min_elevation: None,
146 }
147 }
148}
149
150#[derive(Clone, Copy, Debug)]
153struct Matrices {
154 projection: DMat4,
155 inv_projection: DMat4,
156 coord: DMat4,
157 inverted_from_center: DMat4,
161 globe_view_projection: DMat4,
162 inv_globe_view_projection: DMat4,
163 globe_clipping_plane: DVec4,
164 globe_camera_position: DVec3,
165}
166
167impl Matrices {
168 const ZERO: Matrices = Matrices {
169 projection: DMat4::ZERO,
170 inv_projection: DMat4::ZERO,
171 coord: DMat4::ZERO,
172 inverted_from_center: DMat4::ZERO,
173 globe_view_projection: DMat4::ZERO,
174 inv_globe_view_projection: DMat4::ZERO,
175 globe_clipping_plane: DVec4::ZERO,
176 globe_camera_position: DVec3::ZERO,
177 };
178}
179
180#[derive(Clone, Debug)]
187pub struct View {
188 params: ViewParams,
189 matrices: Matrices,
190}
191
192impl PartialEq for View {
193 fn eq(&self, other: &Self) -> bool {
195 self.params == other.params
196 }
197}
198
199impl Default for View {
200 fn default() -> Self {
201 View::new(ViewParams::new(ConstrainMode::HeightOnly))
202 }
203}
204
205impl View {
206 pub(crate) fn new(params: ViewParams) -> Self {
207 let mut view = View { params, matrices: Matrices::ZERO };
208 view.matrices = view.compute_matrices();
209 view
210 }
211
212 pub(crate) fn params(&self) -> &ViewParams {
213 &self.params
214 }
215
216 fn compute_matrices(&self) -> Matrices {
218 if self.params.size.is_empty() {
219 return Matrices::ZERO;
220 }
221 let projection = self.projection_matrix_with(self.near_z(), false);
222 let coord = self.coordinate_point_matrix(&projection);
223 let from_center = coord * DMat4::from_translation(self.center_coordinate());
224 let (Some(inv_projection), Some(inverted_from_center)) = (projection.try_inverse(), from_center.try_inverse())
225 else {
226 return Matrices::ZERO;
227 };
228 let mut matrices = Matrices { projection, inv_projection, coord, inverted_from_center, ..Matrices::ZERO };
229 if self.is_globe() {
230 let globe_radius = VerticalPerspectiveProjection::globe_radius_pixels(
231 Projection::world_size(self.params.scale),
232 self.center(WrapMode::Unwrapped).latitude(),
233 );
234 let globe_view_projection = VerticalPerspectiveProjection::globe_view_projection_matrix(self, globe_radius);
235 matrices.globe_view_projection = globe_view_projection;
236 matrices.inv_globe_view_projection = globe_view_projection.try_inverse().unwrap_or(DMat4::IDENTITY);
237 matrices.globe_clipping_plane = VerticalPerspectiveProjection::clipping_plane(self, globe_radius);
238 matrices.globe_camera_position = VerticalPerspectiveProjection::camera_position(self, globe_radius);
239 }
240 matrices
241 }
242
243 #[must_use]
247 pub fn size(&self) -> Size {
248 self.params.size
249 }
250
251 #[must_use]
253 pub(crate) fn frustum_offset(&self) -> EdgeInsets {
254 self.params.frustum_offset
255 }
256
257 #[must_use]
259 pub(crate) fn padding(&self) -> EdgeInsets {
260 self.params.padding
261 }
262
263 #[must_use]
264 pub(crate) fn north_orientation(&self) -> NorthOrientation {
265 self.params.north_orientation
266 }
267
268 #[must_use]
270 pub(crate) fn north_orientation_angle(&self) -> f64 {
271 match self.params.north_orientation {
272 NorthOrientation::Upwards => 0.0,
273 NorthOrientation::Rightwards => PI / 2.0,
274 NorthOrientation::Downwards => PI,
275 NorthOrientation::Leftwards => -PI / 2.0,
276 }
277 }
278
279 #[must_use]
282 pub(crate) fn center_clamped_to_ground(&self) -> bool {
283 self.params.center_clamped_to_ground
284 }
285
286 #[must_use]
289 pub(crate) fn globe_free_bearing(&self) -> bool {
290 self.params.globe_free_bearing
291 }
292
293 pub(crate) fn center_offset(&self) -> ScreenCoordinate {
296 let padding = &self.params.padding;
297 ScreenCoordinate::new(0.5 * (padding.left - padding.right), 0.5 * (padding.top - padding.bottom))
298 }
299
300 #[must_use]
305 pub fn center(&self, wrap_mode: WrapMode) -> LatLng {
306 let offset = Point::new(-self.params.x, -self.params.y);
307 self.params.projection.world().unproject_from_center(&offset, self.params.scale, wrap_mode)
308 }
309
310 #[must_use]
313 pub fn lat_lng_near_center(&self, location: &LatLng) -> LatLng {
314 if !self.params.projection.world().wraps() {
315 return *location;
316 }
317 let center = self.center(WrapMode::Unwrapped);
318 let wrapped_center = center.wrapped();
319 let mut nearest = location.wrapped();
320 nearest.unwrap_for_shortest_path(&wrapped_center);
321 LatLng::saturating(
322 nearest.latitude(),
323 nearest.longitude() + center.longitude() - wrapped_center.longitude(),
324 WrapMode::Unwrapped,
325 )
326 }
327
328 #[must_use]
330 pub fn center_altitude(&self) -> f64 {
331 self.params.center_altitude
332 }
333
334 pub(crate) fn meters_per_pixel(&self) -> f64 {
338 let scale = 2.0f64.powf(mln_style::math::clamp_f64(self.zoom(), MIN_ZOOM, MAX_ZOOM));
341 self.params.projection.world().height_meters_per_world_unit(&self.center(WrapMode::Unwrapped))
342 / Projection::world_size(scale)
343 }
344
345 #[must_use]
355 pub fn ground_meters_per_world_unit_at(&self, lat_lng: &LatLng) -> f64 {
356 self.ground_meters_per_world_unit_at_lng_lat([lat_lng.longitude(), lat_lng.latitude()])
357 }
358
359 fn ground_meters_per_world_unit_at_lng_lat(&self, lng_lat: [f64; 2]) -> f64 {
362 let world = self.params.projection.world();
363 let mut place = [[0.0; 2]];
364 world.world_from_lng_lats(&[lng_lat], &mut place);
365 let [dx, dy] = self.screen_x_axis_at(&Point::new(place[0][0], place[0][1]));
366 let span = SCALE_SPAN_PX / Projection::world_size(self.params.scale);
367 world.ground_meters_per_world_unit(lng_lat, [dx * span, dy * span])
368 }
369
370 #[must_use]
376 pub fn meters_per_pixel_at(&self, lat_lng: &LatLng) -> f64 {
377 self.meters_per_pixel_at_lng_lat([lat_lng.longitude(), lat_lng.latitude()])
378 }
379
380 pub(crate) fn meters_per_pixel_at_lng_lat(&self, lng_lat: [f64; 2]) -> f64 {
383 let scale = 2.0f64.powf(mln_style::math::clamp_f64(self.zoom(), MIN_ZOOM, MAX_ZOOM));
384 self.ground_meters_per_world_unit_at_lng_lat(lng_lat) / Projection::world_size(scale)
385 }
386
387 fn screen_x_axis_at(&self, at: &Point<f64>) -> [f64; 2] {
391 let screen = self.world_to_screen_coordinate(at);
392 let next = self.screen_coordinate_to_world_at(&ScreenCoordinate::new(screen.x + 1.0, screen.y), 0.0);
393 let (dx, dy) = (next.x - at.x, next.y - at.y);
394 let length = dx.hypot(dy);
395 if length > 0.0 && length.is_finite() { [dx / length, dy / length] } else { [1.0, 0.0] }
396 }
397
398 fn center_altitude_pixels(&self) -> f64 {
400 if self.params.center_altitude == 0.0 {
403 return self.params.center_altitude;
404 }
405 self.params.center_altitude / self.meters_per_pixel()
406 }
407
408 #[must_use]
409 pub fn zoom(&self) -> f64 {
410 scale_zoom(self.params.scale)
411 }
412
413 #[must_use]
415 pub fn integer_zoom(&self) -> u8 {
416 f64::max(0.0, self.zoom()) as u8
417 }
418
419 #[must_use]
421 #[cfg(test)]
422 pub(crate) fn zoom_fraction(&self) -> f64 {
423 self.zoom() - f64::from(self.integer_zoom())
424 }
425
426 #[must_use]
428 pub(crate) fn scale(&self) -> f64 {
429 self.params.scale
430 }
431
432 #[must_use]
435 pub(crate) fn x(&self) -> f64 {
436 self.params.x
437 }
438
439 #[must_use]
441 pub(crate) fn y(&self) -> f64 {
442 self.params.y
443 }
444
445 #[must_use]
448 pub fn world(&self) -> &WorldMapping {
449 self.params.projection.world()
450 }
451
452 pub(crate) fn center_world(&self) -> Point<f64> {
454 let world_size = Projection::world_size(self.params.scale);
455 Point::new(0.5 - self.params.x / world_size, 0.5 - self.params.y / world_size)
456 }
457
458 #[must_use]
462 pub fn world_copy_longitude(&self) -> f64 {
463 if self.params.projection.world().wraps() { self.center(WrapMode::Unwrapped).longitude() } else { 0.0 }
464 }
465
466 #[must_use]
468 pub fn angle(&self) -> f64 {
469 self.params.angle
470 }
471
472 #[must_use]
474 pub fn pitch(&self) -> f64 {
475 self.params.pitch
476 }
477
478 #[must_use]
479 pub fn roll(&self) -> f64 {
480 self.params.roll
481 }
482
483 #[must_use]
485 pub(crate) fn fov(&self) -> f64 {
486 self.params.fov
487 }
488
489 pub(crate) fn perspective_fov(&self) -> f64 {
496 f64::from(self.params.fov as f32)
497 }
498
499 #[must_use]
501 pub fn camera_to_center_distance(&self) -> f64 {
502 0.5 * f64::from(self.params.size.height) / (self.params.fov / 2.0).tan()
503 }
504
505 #[must_use]
510 pub(crate) fn mercator_horizon(&self) -> f64 {
511 let pitch = self.params.pitch;
512 self.camera_to_center_distance()
513 * f64::min((PI / 2.0 - pitch).tan() * 0.85, (max_mercator_horizon_angle() - pitch).tan())
514 }
515
516 #[must_use]
517 pub(crate) fn projection_mode(&self) -> ProjectionMode {
518 ProjectionMode {
519 axonometric: Some(AxonometricMode::from(self.params.axonometric)),
520 x_skew: Some(self.params.x_skew),
521 y_skew: Some(self.params.y_skew),
522 }
523 }
524
525 #[must_use]
527 pub(crate) fn camera(&self) -> Camera {
528 Camera {
529 center: self.center(self.params.center_wrap),
530 center_altitude: self.center_altitude(),
531 padding: self.params.padding,
532 zoom: self.zoom(),
533 bearing: mln_style::math::rad2deg(-self.params.angle),
534 pitch: mln_style::math::rad2deg(self.params.pitch),
535 roll: mln_style::math::rad2deg(self.params.roll),
536 fov: mln_style::math::rad2deg(self.params.fov),
537 }
538 }
539
540 #[must_use]
543 pub fn map_view(&self, scale_factor: f64) -> MapView {
544 MapView {
545 camera: self.camera(),
546 extent: LogicalExtent { size: self.params.size, scale_factor },
547 projection_mode: self.projection_mode(),
548 viewport: Viewport {
549 north_orientation: self.params.north_orientation,
550 constrain_mode: self.params.constrain_mode,
551 center_clamped_to_ground: self.params.center_clamped_to_ground,
552 globe_free_bearing: self.params.globe_free_bearing,
553 frustum_offset: self.params.frustum_offset,
554 },
555 projection: self.params.projection.clone(),
556 }
557 }
558
559 #[must_use]
561 pub(crate) fn is_valid(&self) -> bool {
562 !self.params.size.is_empty() && self.params.scale.is_finite() && self.params.scale > 0.0
563 }
564
565 pub(crate) fn camera_pose(&self) -> CameraPose {
568 if !self.is_valid() {
569 return CameraPose::default();
570 }
571 let world_size = Projection::world_size(self.params.scale);
572 let center = DVec3::new(
575 0.5 * world_size - self.params.x,
576 0.5 * world_size - self.params.y,
577 self.center_altitude_pixels(),
578 );
579 let mut camera = CameraPose::from_angles(DVec3::ZERO, self.params.roll, self.params.pitch, self.params.angle);
582 camera.position = (center - camera.forward() * self.camera_to_center_distance()) / world_size;
583 camera
584 }
585
586 #[must_use]
588 pub(crate) fn free_camera_options(&self) -> FreeCameraOptions {
589 let camera = self.camera_pose();
590 FreeCameraOptions { position: Some(camera.position), orientation: Some(camera.orientation) }
591 }
592
593 #[must_use]
601 pub(crate) fn eye_position(&self) -> DVec3 {
602 if self.is_globe() && self.is_valid() {
603 let eye = self.matrices.globe_camera_position;
604 return VerticalPerspectiveProjection::sphere_point_to_world(self, eye).unwrap_or(eye);
605 }
606 let position = self.camera_pose().position;
607 let world_size = Projection::world_size(self.params.scale);
608 DVec3::new(position.x, position.y, position.z * world_size * self.meters_per_pixel())
609 }
610
611 #[must_use]
622 pub(crate) fn near_plane_points(&self) -> [DVec3; 9] {
623 let eye = self.eye_position();
624 if self.matrices.projection == DMat4::ZERO {
625 return [eye; 9];
626 }
627 let clip = |index: usize| DVec3::new((index % 3) as f64 - 1.0, (index / 3) as f64 - 1.0, 0.0);
628 if self.is_globe() {
629 let inverse = self.matrices.inv_globe_view_projection;
630 return std::array::from_fn(|index| {
631 let point = inverse.project_point3(clip(index));
632 VerticalPerspectiveProjection::sphere_point_to_world(self, point).unwrap_or(eye)
633 });
634 }
635 let world_size = Projection::world_size(self.params.scale);
636 std::array::from_fn(|index| {
637 let point = self.matrices.inv_projection.project_point3(clip(index));
638 DVec3::new(point.x / world_size, point.y / world_size, point.z)
639 })
640 }
641
642 #[must_use]
646 pub(crate) fn projection_transition(&self) -> f64 {
647 self.params.projection.transition()
648 }
649
650 #[must_use]
653 pub fn is_globe(&self) -> bool {
654 self.params.projection.transition() > 0.0
655 }
656
657 #[must_use]
659 pub fn projection(&self) -> crate::camera::Projection {
660 if self.is_globe() {
661 crate::camera::Projection::VerticalPerspective
662 } else {
663 crate::camera::Projection::Mercator
664 }
665 }
666
667 #[must_use]
670 pub(crate) fn mercator(&self) -> View {
671 if !self.is_globe() {
672 return self.clone();
673 }
674 View::new(ViewParams {
675 projection: ViewProjection::BuiltIn(ProjectionDefinition::default()),
676 ..self.params.clone()
677 })
678 }
679
680 #[must_use]
682 pub(crate) fn tile_matrix(&self, tile_id: &UnwrappedTileID) -> DMat4 {
683 mercator_tile_matrix(tile_id, self.params.scale)
684 }
685
686 #[must_use]
688 pub(crate) fn projection_data_with(&self, tile_id: &UnwrappedTileID, proj_matrix: &DMat4) -> ProjectionData {
689 let mercator_matrix = *proj_matrix * self.tile_matrix(tile_id);
690 self.projection().projection_data(self, tile_id, &mercator_matrix)
691 }
692
693 #[must_use]
695 pub fn projection_data(&self, tile_id: &UnwrappedTileID) -> ProjectionData {
696 self.projection_data_with(tile_id, &self.matrices.projection)
697 }
698
699 #[must_use]
702 pub(crate) fn projection_data_for_matrix(
703 &self,
704 tile_id: &UnwrappedTileID,
705 mercator_matrix: &DMat4,
706 ) -> ProjectionData {
707 self.projection().projection_data(self, tile_id, mercator_matrix)
708 }
709
710 #[must_use]
714 pub fn terrain_min_elevation(&self) -> Option<f64> {
715 self.params.terrain_min_elevation
716 }
717
718 #[must_use]
723 pub(crate) fn near_z(&self) -> f64 {
724 match self.params.terrain_min_elevation {
725 Some(_) => f64::from(self.params.size.height) / 50.0,
726 None => 1.0,
727 }
728 }
729
730 #[must_use]
735 pub(crate) fn camera_to_sea_level_distance(&self) -> f64 {
736 let camera_to_center_distance = self.camera_to_center_distance();
737 let limited_pitch = self.params.pitch.min(max_mercator_horizon_angle());
738 f64::max(
739 camera_to_center_distance / 2.0,
740 camera_to_center_distance + self.center_altitude_pixels() / limited_pitch.cos(),
741 )
742 }
743
744 #[must_use]
752 pub(crate) fn far_z(&self) -> f64 {
753 let params = &self.params;
754 let camera_to_center_distance = self.camera_to_center_distance();
755 let pixels_per_meter = 1.0 / self.meters_per_pixel();
756
757 let ground = params.terrain_min_elevation.unwrap_or(0.0) * pixels_per_meter;
759 let center_altitude = self.center_altitude_pixels();
760 let limited_pitch = params.pitch.min(max_mercator_horizon_angle());
761 let camera_to_sea_level_distance = self.camera_to_sea_level_distance();
762 let camera_altitude = params.pitch.cos() * camera_to_center_distance + center_altitude;
763 let lowest = center_altitude.min(ground).min(camera_altitude - 100.0 * pixels_per_meter);
764 let lowest_plane = if lowest < 0.0 {
765 camera_to_sea_level_distance - lowest / limited_pitch.cos()
766 } else {
767 camera_to_sea_level_distance
768 };
769
770 let ground_angle = PI / 2.0 + params.pitch;
774 let distance_past_center = |angle: f64| {
775 angle.sin() * lowest_plane / mln_style::math::clamp_f64(PI - ground_angle - angle, 0.01, PI - 0.01).sin()
776 };
777 let top_half_distance = distance_past_center(self.tan_fov_above_center().atan())
778 .min(distance_past_center(self.fov_center_to_horizon()));
779
780 (limited_pitch.sin() * top_half_distance + lowest_plane) * 1.01
781 }
782
783 #[must_use]
786 pub(crate) fn shows_horizon(&self) -> bool {
787 self.fov_center_to_horizon() < self.tan_fov_above_center().atan()
788 }
789
790 fn tan_fov_above_center(&self) -> f64 {
795 let params = &self.params;
796 let half_width = 0.5 * f64::from(params.size.width);
797 let half_height = 0.5 * f64::from(params.size.height);
798 let offset = self.center_offset();
799 let (left, right) = (half_width + offset.x, half_width - offset.x);
801 let (top, bottom) = (half_height + offset.y - params.frustum_offset.top, half_height - offset.y);
802 let up = self.up_the_map();
803 let reach = (up.x * right).max(-up.x * left) + (up.y * top).max(-up.y * bottom);
804 reach / half_height * (params.fov / 2.0).tan()
805 }
806
807 fn fov_center_to_horizon(&self) -> f64 {
815 let camera_to_center = self.camera_to_center_distance();
816 let horizon = self.mercator_horizon();
817 let min_horizon_angle = PI / 2.0 - max_mercator_horizon_angle();
818 if (horizon / camera_to_center).atan() <= min_horizon_angle {
819 return min_horizon_angle;
820 }
821 let offset = self.center_offset();
822 let offset_up = DVec2::new(-offset.x, offset.y).dot(self.up_the_map());
823 let farthest = camera_to_center * (max_mercator_horizon_angle() - self.params.pitch).tan();
824 (mln_style::math::clamp_f64(horizon + offset_up, 0.0, farthest) / camera_to_center).atan()
825 }
826
827 fn up_the_map(&self) -> DVec2 {
831 let (sin, cos) = self.params.roll.sin_cos();
832 DVec2::from_angle(-self.north_orientation_angle()).rotate(DVec2::new(-sin, cos))
833 }
834
835 #[must_use]
838 pub(crate) fn projection_matrix_with(&self, near_z: f64, aligned: bool) -> DMat4 {
839 let params = &self.params;
840 if params.size.is_empty() {
841 return DMat4::ZERO;
842 }
843
844 let offset = self.center_offset();
845 let width = f64::from(params.size.width);
846 let height = f64::from(params.size.height);
847
848 let camera = self.camera_pose();
849 let pixels_per_meter = 1.0 / self.meters_per_pixel();
850 let world_to_camera = camera.world_to_camera(params.scale, pixels_per_meter);
851 let mut camera_to_clip = perspective(self.perspective_fov(), width / height, near_z, self.far_z());
852
853 if !params.axonometric {
856 camera_to_clip.z_axis.x = -offset.x * 2.0 / width;
857 camera_to_clip.z_axis.y = offset.y * 2.0 / height;
858 }
859
860 if params.north_orientation != NorthOrientation::Upwards {
861 camera_to_clip *= DMat4::from_rotation_z(-self.north_orientation_angle());
862 }
863
864 let mut proj_matrix = camera_to_clip * world_to_camera;
865
866 if params.axonometric {
867 proj_matrix.z_axis.w = 0.0;
869 proj_matrix.z_axis.x = params.x_skew * pixels_per_meter;
870 proj_matrix.z_axis.y = params.y_skew * pixels_per_meter;
871 }
872
873 if aligned {
878 let world_size = Projection::world_size(params.scale);
879 let dx = params.x - 0.5 * world_size;
880 let dy = params.y - 0.5 * world_size;
881
882 let x_shift = f64::from(params.size.width % 2) / 2.0;
883 let y_shift = f64::from(params.size.height % 2) / 2.0;
884 let angle_cos = params.angle.cos();
885 let angle_sin = params.angle.sin();
886 let dxa = -modf_fraction(dx) + angle_cos * x_shift + angle_sin * y_shift;
887 let dya = -modf_fraction(dy) + angle_cos * y_shift + angle_sin * x_shift;
888 proj_matrix *= DMat4::from_translation(DVec3::new(
889 if dxa > 0.5 { dxa - 1.0 } else { dxa },
890 if dya > 0.5 { dya - 1.0 } else { dya },
891 0.0,
892 ));
893 }
894 proj_matrix
895 }
896
897 #[cfg(any(test, feature = "bench"))]
900 #[must_use]
901 pub(crate) fn projection_matrix(&self) -> DMat4 {
902 self.matrices.projection
903 }
904
905 #[must_use]
906 pub(crate) fn inverse_projection_matrix(&self) -> DMat4 {
907 self.matrices.inv_projection
908 }
909
910 #[must_use]
913 pub(crate) fn globe_view_projection_matrix(&self) -> DMat4 {
914 self.matrices.globe_view_projection
915 }
916
917 #[must_use]
918 pub(crate) fn inverse_globe_view_projection_matrix(&self) -> DMat4 {
919 self.matrices.inv_globe_view_projection
920 }
921
922 #[must_use]
925 pub(crate) fn globe_clipping_plane(&self) -> DVec4 {
926 self.matrices.globe_clipping_plane
927 }
928
929 #[must_use]
931 pub fn globe_camera_position(&self) -> DVec3 {
932 self.matrices.globe_camera_position
933 }
934
935 fn center_coordinate(&self) -> DVec3 {
938 let world_size = Projection::world_size(self.params.scale);
939 DVec3::new(
940 (0.5 * world_size - self.params.x) / TILE_SIZE_D,
941 (0.5 * world_size - self.params.y) / TILE_SIZE_D,
942 0.0,
943 )
944 }
945
946 fn coordinate_point_matrix(&self, proj_matrix: &DMat4) -> DMat4 {
948 let size = self.params.size;
949 let pixel_matrix =
950 DMat4::from_scale(DVec3::new(f64::from(size.width) / 2.0, -f64::from(size.height) / 2.0, 1.0))
951 * DMat4::from_translation(DVec3::new(1.0, -1.0, 0.0));
952 pixel_matrix * *proj_matrix * DMat4::from_scale(DVec3::new(TILE_SIZE_D, TILE_SIZE_D, 1.0))
953 }
954
955 #[must_use]
959 pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
960 self.lat_lng_to_screen_coordinate_at(lat_lng, 0.0)
961 }
962
963 #[must_use]
967 pub(crate) fn lat_lng_to_screen_coordinate_at(&self, lat_lng: &LatLng, height: f64) -> ScreenCoordinate {
968 self.clip_point_at(lat_lng, height).0
969 }
970
971 #[must_use]
974 #[cfg(test)]
975 pub(crate) fn lat_lng_to_screen_coordinate_with_clip(&self, lat_lng: &LatLng) -> (ScreenCoordinate, DVec4) {
976 self.clip_point_at(lat_lng, 0.0)
977 }
978
979 fn clip_point_at(&self, lat_lng: &LatLng, height: f64) -> (ScreenCoordinate, DVec4) {
984 if self.params.size.is_empty() {
985 return (ScreenCoordinate::new(0.0, 0.0), DVec4::ZERO);
986 }
987
988 if self.is_globe() {
989 return VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(self, lat_lng, height);
990 }
991
992 let pt = self.params.projection.world().project(lat_lng, self.params.scale);
993 let p = self.matrices.coord * DVec4::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D, height, 1.0);
994 (ScreenCoordinate::new(p.x / p.w, f64::from(self.params.size.height) - p.y / p.w), p)
995 }
996
997 pub(crate) fn world_to_screen_coordinate(&self, world: &Point<f64>) -> ScreenCoordinate {
1001 if self.params.size.is_empty() {
1002 return ScreenCoordinate::new(0.0, 0.0);
1003 }
1004 let world_size = Projection::world_size(self.params.scale);
1005 let p = self.matrices.coord
1006 * DVec4::new(world.x * world_size / TILE_SIZE_D, world.y * world_size / TILE_SIZE_D, 0.0, 1.0);
1007 ScreenCoordinate::new(p.x / p.w, f64::from(self.params.size.height) - p.y / p.w)
1008 }
1009
1010 #[must_use]
1013 pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
1014 if self.params.size.is_empty() || !self.is_globe() {
1015 return false;
1016 }
1017 let surface = VerticalPerspectiveProjection::surface_vector(lat_lng);
1018 self.globe_clipping_plane().dot(surface.extend(1.0)) < 0.0
1019 }
1020
1021 #[must_use]
1024 pub(crate) fn screen_coordinate_to_tile_coordinate(&self, point: &ScreenCoordinate, at_zoom: u8) -> TileCoordinate {
1025 if self.params.size.is_empty() {
1026 return TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 };
1027 }
1028
1029 if self.is_globe() {
1030 return match VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(
1031 self,
1032 point,
1033 0.0,
1034 WrapMode::Unwrapped,
1035 ) {
1036 Some(lat_lng) => TileCoordinate::from_lat_lng(f64::from(at_zoom), &lat_lng),
1037 None => TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 },
1038 };
1039 }
1040
1041 self.mercator_screen_coordinate_to_tile_coordinate(point, at_zoom, 0.0)
1042 }
1043
1044 fn mercator_screen_coordinate_to_tile_coordinate(
1048 &self,
1049 point: &ScreenCoordinate,
1050 at_zoom: u8,
1051 height: f64,
1052 ) -> TileCoordinate {
1053 let flipped_y = f64::from(self.params.size.height) - point.y;
1054
1055 let inverted = self.matrices.inverted_from_center;
1058 let offset0 = inverted.project_point3(DVec3::new(point.x, flipped_y, 0.0));
1059 let offset1 = inverted.project_point3(DVec3::new(point.x, flipped_y, 1.0));
1060
1061 let z0 = offset0.z;
1062 let z1 = offset1.z;
1063 let t = if z0 <= z1 { 0.0 } else { -(z0 - height) / (z1 - z0) };
1065
1066 let offset = offset0 + (offset1 - offset0) * t;
1067 let center = self.center_coordinate();
1068 let factor = f64::from(1i32.wrapping_shl(u32::from(at_zoom)));
1069 let scale = self.params.scale;
1070 TileCoordinate {
1071 p: Point::new((center.x + offset.x) / scale * factor, (center.y + offset.y) / scale * factor),
1072 z: f64::from(at_zoom),
1073 }
1074 }
1075
1076 pub(crate) fn screen_coordinate_to_lat_lng(
1080 &self,
1081 point: &ScreenCoordinate,
1082 wrap_mode: WrapMode,
1083 ) -> Result<LatLng, Error> {
1084 self.screen_coordinate_to_lat_lng_at(point, 0.0, wrap_mode)
1085 }
1086
1087 pub fn screen_coordinate_to_lat_lng_at(
1095 &self,
1096 point: &ScreenCoordinate,
1097 height: f64,
1098 wrap_mode: WrapMode,
1099 ) -> Result<LatLng, Error> {
1100 if self.is_globe() && !self.params.size.is_empty() {
1102 if point.x.is_nan() || point.y.is_nan() {
1103 return Err(Error::invalid_argument("screen coordinate must not be NaN"));
1104 }
1105 if !point.x.is_finite() || !point.y.is_finite() {
1106 return Err(Error::invalid_argument("screen coordinate must not be infinite"));
1107 }
1108 return VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(self, point, height, wrap_mode)
1109 .ok_or_else(|| Error::invalid_argument("the camera shows no location"));
1110 }
1111 let coord = if self.params.size.is_empty() {
1112 self.screen_coordinate_to_tile_coordinate(point, 0)
1113 } else {
1114 self.mercator_screen_coordinate_to_tile_coordinate(point, 0, height)
1115 };
1116 self.params.projection.world().unproject(&coord.p, 1.0 / TILE_SIZE_D, wrap_mode)
1117 }
1118
1119 pub(crate) fn has_lat_lng_at(&self, point: &ScreenCoordinate, height: f64) -> bool {
1126 self.is_globe()
1127 || self.params.projection.world().has_lat_lng(&self.screen_coordinate_to_world_at(point, height))
1128 }
1129
1130 #[must_use]
1136 pub fn screen_coordinate_to_world_at(&self, point: &ScreenCoordinate, height: f64) -> Point<f64> {
1137 self.mercator_screen_coordinate_to_tile_coordinate(point, 0, height).p
1138 }
1139
1140 #[must_use]
1146 pub fn line_of_sight(&self, point: &ScreenCoordinate) -> Option<(DVec3, DVec3)> {
1147 if self.is_globe() || self.matrices.projection == DMat4::ZERO {
1148 return None;
1149 }
1150 let flipped_y = f64::from(self.params.size.height) - point.y;
1151 let inverted = self.matrices.inverted_from_center;
1154 let center = self.center_coordinate();
1155 let scale = self.params.scale;
1156 let world = |depth: f64| {
1157 let offset = inverted.project_point3(DVec3::new(point.x, flipped_y, depth));
1158 DVec3::new((center.x + offset.x) / scale, (center.y + offset.y) / scale, offset.z)
1159 };
1160 let (near, far) = (world(-1.0), world(1.0));
1161 (near.is_finite() && far.is_finite()).then_some((near, far))
1162 }
1163
1164 #[must_use]
1168 pub(crate) fn max_pitch_scale_factor(&self) -> f64 {
1169 if self.params.size.is_empty() {
1170 return 0.0;
1171 }
1172 let corner = self.mercator_screen_coordinate_to_tile_coordinate(
1175 &ScreenCoordinate::new(0.0, f64::from(self.params.size.height)),
1176 0,
1177 0.0,
1178 );
1179 let world = self.params.projection.world();
1181 let Ok(lat_lng) = world.unproject(&corner.p, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped) else {
1182 return 0.0;
1183 };
1184
1185 let scale = self.params.scale;
1186 let pt = if self.is_globe() {
1187 Point::new(corner.p.x * scale, corner.p.y * scale)
1188 } else {
1189 let pt = world.project(&lat_lng, scale);
1190 Point::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D)
1191 };
1192 let top_point = self.matrices.coord * DVec4::new(pt.x, pt.y, 0.0, 1.0);
1193 top_point.w / self.camera_to_center_distance()
1194 }
1195}