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::error::Error;
11use mln_style::geo::{LatLng, WrapMode};
12use mln_style::size::Size;
13use mln_style::types::ProjectionDefinition;
14
15use crate::camera::camera::FreeCameraOptions;
16use crate::camera::camera_pose::CameraPose;
17use crate::camera::constants::DEFAULT_FOV;
18use crate::camera::map_view::{Camera, LogicalExtent, MapView, Viewport};
19use crate::camera::mode::ConstrainMode;
20use crate::camera::projection::{ProjectionData, mercator_tile_matrix};
21use crate::camera::projection_mode::{AxonometricMode, ProjectionMode};
22use crate::camera::tile_coordinate::TileCoordinate;
23use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
24pub use crate::geo::NorthOrientation;
25use crate::geo::constants::M2PI;
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 map_offset(center: &LatLng, scale: f64, globe: bool) -> (f64, f64) {
61 let world_size = Projection::world_size(scale);
62 let latitude = mln_style::math::deg2rad(center.latitude());
63 let m = 1.0 - 1e-15;
64 let f = mln_style::math::clamp_f64(latitude.sin(), -m, m);
65 let x = -center.longitude() * (world_size / 360.0);
66 let cc = world_size / M2PI;
67 let y = if globe { cc * latitude.tan().asinh() } else { 0.5 * cc * ((1.0 + f) / (1.0 - f)).ln() };
68 (x, y)
69}
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, Copy, 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_definition: ProjectionDefinition,
96 pub(crate) projection_transition: f64,
98 pub(crate) padding: EdgeInsets,
99 pub(crate) x: f64,
102 pub(crate) y: f64,
103 pub(crate) center_altitude: f64,
106 pub(crate) scale: f64,
107 pub(crate) angle: f64,
110 pub(crate) pitch: f64,
111 pub(crate) roll: f64,
112 pub(crate) fov: f64,
113 pub(crate) x_skew: f64,
114 pub(crate) y_skew: f64,
115 pub(crate) axonometric: bool,
116 pub(crate) center_wrap: WrapMode,
118 pub(crate) terrain_min_elevation: Option<f64>,
121}
122
123impl ViewParams {
124 pub(crate) fn new(constrain_mode: ConstrainMode) -> Self {
125 ViewParams {
126 size: Size::default(),
127 frustum_offset: EdgeInsets::default(),
128 north_orientation: NorthOrientation::Upwards,
129 constrain_mode,
130 center_clamped_to_ground: true,
131 globe_free_bearing: false,
132 projection_definition: ProjectionDefinition::default(),
133 projection_transition: 0.0,
134 padding: EdgeInsets::default(),
135 x: 0.0,
136 y: 0.0,
137 center_altitude: 0.0,
138 scale: 1.0,
139 angle: 0.0,
140 pitch: 0.0,
141 roll: 0.0,
142 fov: DEFAULT_FOV,
143 x_skew: 0.0,
144 y_skew: 1.0,
145 axonometric: false,
146 center_wrap: WrapMode::Unwrapped,
147 terrain_min_elevation: None,
148 }
149 }
150}
151
152#[derive(Clone, Copy, Debug)]
155struct Matrices {
156 projection: DMat4,
157 inv_projection: DMat4,
158 coord: DMat4,
159 inverted_from_center: DMat4,
163 globe_view_projection: DMat4,
164 inv_globe_view_projection: DMat4,
165 globe_clipping_plane: DVec4,
166 globe_camera_position: DVec3,
167}
168
169impl Matrices {
170 const ZERO: Matrices = Matrices {
171 projection: DMat4::ZERO,
172 inv_projection: DMat4::ZERO,
173 coord: DMat4::ZERO,
174 inverted_from_center: DMat4::ZERO,
175 globe_view_projection: DMat4::ZERO,
176 inv_globe_view_projection: DMat4::ZERO,
177 globe_clipping_plane: DVec4::ZERO,
178 globe_camera_position: DVec3::ZERO,
179 };
180}
181
182#[derive(Clone, Debug)]
189pub struct View {
190 params: ViewParams,
191 matrices: Matrices,
192}
193
194impl PartialEq for View {
195 fn eq(&self, other: &Self) -> bool {
197 self.params == other.params
198 }
199}
200
201impl Default for View {
202 fn default() -> Self {
203 View::new(ViewParams::new(ConstrainMode::HeightOnly))
204 }
205}
206
207impl View {
208 pub(crate) fn new(params: ViewParams) -> Self {
209 let mut view = View { params, matrices: Matrices::ZERO };
210 view.matrices = view.compute_matrices();
211 view
212 }
213
214 pub(crate) fn params(&self) -> &ViewParams {
215 &self.params
216 }
217
218 fn compute_matrices(&self) -> Matrices {
220 if self.params.size.is_empty() {
221 return Matrices::ZERO;
222 }
223 let projection = self.projection_matrix_with(self.near_z(), false);
224 let coord = self.coordinate_point_matrix(&projection);
225 let from_center = coord * DMat4::from_translation(self.center_coordinate());
226 let (Some(inv_projection), Some(inverted_from_center)) = (projection.try_inverse(), from_center.try_inverse())
227 else {
228 return Matrices::ZERO;
229 };
230 let mut matrices = Matrices { projection, inv_projection, coord, inverted_from_center, ..Matrices::ZERO };
231 if self.is_globe() {
232 let globe_radius = VerticalPerspectiveProjection::globe_radius_pixels(
233 Projection::world_size(self.params.scale),
234 self.center(WrapMode::Unwrapped).latitude(),
235 );
236 let globe_view_projection = VerticalPerspectiveProjection::globe_view_projection_matrix(self, globe_radius);
237 matrices.globe_view_projection = globe_view_projection;
238 matrices.inv_globe_view_projection = globe_view_projection.try_inverse().unwrap_or(DMat4::IDENTITY);
239 matrices.globe_clipping_plane = VerticalPerspectiveProjection::clipping_plane(self, globe_radius);
240 matrices.globe_camera_position = VerticalPerspectiveProjection::camera_position(self, globe_radius);
241 }
242 matrices
243 }
244
245 #[must_use]
249 pub fn size(&self) -> Size {
250 self.params.size
251 }
252
253 #[must_use]
255 pub(crate) fn frustum_offset(&self) -> EdgeInsets {
256 self.params.frustum_offset
257 }
258
259 #[must_use]
261 pub(crate) fn padding(&self) -> EdgeInsets {
262 self.params.padding
263 }
264
265 #[must_use]
266 pub(crate) fn north_orientation(&self) -> NorthOrientation {
267 self.params.north_orientation
268 }
269
270 #[must_use]
272 pub(crate) fn north_orientation_angle(&self) -> f64 {
273 match self.params.north_orientation {
274 NorthOrientation::Upwards => 0.0,
275 NorthOrientation::Rightwards => PI / 2.0,
276 NorthOrientation::Downwards => PI,
277 NorthOrientation::Leftwards => -PI / 2.0,
278 }
279 }
280
281 #[must_use]
284 pub(crate) fn center_clamped_to_ground(&self) -> bool {
285 self.params.center_clamped_to_ground
286 }
287
288 #[must_use]
291 pub(crate) fn globe_free_bearing(&self) -> bool {
292 self.params.globe_free_bearing
293 }
294
295 pub(crate) fn center_offset(&self) -> ScreenCoordinate {
298 let padding = &self.params.padding;
299 ScreenCoordinate::new(0.5 * (padding.left - padding.right), 0.5 * (padding.top - padding.bottom))
300 }
301
302 #[must_use]
307 pub fn center(&self, wrap_mode: WrapMode) -> LatLng {
308 let world_size = Projection::world_size(self.params.scale);
309 LatLng::saturating(
310 mln_style::math::rad2deg(2.0 * (self.params.y / (world_size / M2PI)).exp().atan() - 0.5 * PI),
311 -self.params.x / (world_size / 360.0),
312 wrap_mode,
313 )
314 }
315
316 #[must_use]
319 pub fn lat_lng_near_center(&self, location: &LatLng) -> LatLng {
320 let center = self.center(WrapMode::Unwrapped);
321 let wrapped_center = center.wrapped();
322 let mut nearest = location.wrapped();
323 nearest.unwrap_for_shortest_path(&wrapped_center);
324 LatLng::saturating(
325 nearest.latitude(),
326 nearest.longitude() + center.longitude() - wrapped_center.longitude(),
327 WrapMode::Unwrapped,
328 )
329 }
330
331 #[must_use]
333 pub fn center_altitude(&self) -> f64 {
334 self.params.center_altitude
335 }
336
337 pub(crate) fn meters_per_pixel(&self) -> f64 {
341 Projection::meters_per_pixel_at_latitude(self.center(WrapMode::Unwrapped).latitude(), self.zoom())
342 }
343
344 fn center_altitude_pixels(&self) -> f64 {
346 if self.params.center_altitude == 0.0 {
349 return self.params.center_altitude;
350 }
351 self.params.center_altitude / self.meters_per_pixel()
352 }
353
354 #[must_use]
355 pub fn zoom(&self) -> f64 {
356 scale_zoom(self.params.scale)
357 }
358
359 #[must_use]
361 pub fn integer_zoom(&self) -> u8 {
362 f64::max(0.0, self.zoom()) as u8
363 }
364
365 #[must_use]
367 #[cfg(test)]
368 pub(crate) fn zoom_fraction(&self) -> f64 {
369 self.zoom() - f64::from(self.integer_zoom())
370 }
371
372 #[must_use]
374 pub(crate) fn scale(&self) -> f64 {
375 self.params.scale
376 }
377
378 #[must_use]
381 pub(crate) fn x(&self) -> f64 {
382 self.params.x
383 }
384
385 #[must_use]
387 pub(crate) fn y(&self) -> f64 {
388 self.params.y
389 }
390
391 #[must_use]
393 pub fn angle(&self) -> f64 {
394 self.params.angle
395 }
396
397 #[must_use]
399 pub fn pitch(&self) -> f64 {
400 self.params.pitch
401 }
402
403 #[must_use]
404 pub fn roll(&self) -> f64 {
405 self.params.roll
406 }
407
408 #[must_use]
410 pub(crate) fn fov(&self) -> f64 {
411 self.params.fov
412 }
413
414 pub(crate) fn perspective_fov(&self) -> f64 {
421 f64::from(self.params.fov as f32)
422 }
423
424 #[must_use]
426 pub fn camera_to_center_distance(&self) -> f64 {
427 0.5 * f64::from(self.params.size.height) / (self.params.fov / 2.0).tan()
428 }
429
430 #[must_use]
435 pub(crate) fn mercator_horizon(&self) -> f64 {
436 let pitch = self.params.pitch;
437 self.camera_to_center_distance()
438 * f64::min((PI / 2.0 - pitch).tan() * 0.85, (max_mercator_horizon_angle() - pitch).tan())
439 }
440
441 #[must_use]
442 pub(crate) fn projection_mode(&self) -> ProjectionMode {
443 ProjectionMode {
444 axonometric: Some(AxonometricMode::from(self.params.axonometric)),
445 x_skew: Some(self.params.x_skew),
446 y_skew: Some(self.params.y_skew),
447 }
448 }
449
450 #[must_use]
452 pub(crate) fn camera(&self) -> Camera {
453 Camera {
454 center: self.center(self.params.center_wrap),
455 center_altitude: self.center_altitude(),
456 padding: self.params.padding,
457 zoom: self.zoom(),
458 bearing: mln_style::math::rad2deg(-self.params.angle),
459 pitch: mln_style::math::rad2deg(self.params.pitch),
460 roll: mln_style::math::rad2deg(self.params.roll),
461 fov: mln_style::math::rad2deg(self.params.fov),
462 }
463 }
464
465 #[must_use]
468 pub fn map_view(&self, scale_factor: f64) -> MapView {
469 MapView {
470 camera: self.camera(),
471 extent: LogicalExtent { size: self.params.size, scale_factor },
472 projection_mode: self.projection_mode(),
473 viewport: Viewport {
474 north_orientation: self.params.north_orientation,
475 constrain_mode: self.params.constrain_mode,
476 center_clamped_to_ground: self.params.center_clamped_to_ground,
477 globe_free_bearing: self.params.globe_free_bearing,
478 frustum_offset: self.params.frustum_offset,
479 },
480 projection: self.params.projection_definition,
481 }
482 }
483
484 #[must_use]
486 pub(crate) fn is_valid(&self) -> bool {
487 !self.params.size.is_empty() && self.params.scale.is_finite() && self.params.scale > 0.0
488 }
489
490 pub(crate) fn camera_pose(&self) -> CameraPose {
493 if !self.is_valid() {
494 return CameraPose::default();
495 }
496 let world_size = Projection::world_size(self.params.scale);
497 let center = DVec3::new(
500 0.5 * world_size - self.params.x,
501 0.5 * world_size - self.params.y,
502 self.center_altitude_pixels(),
503 );
504 let mut camera = CameraPose::from_angles(DVec3::ZERO, self.params.roll, self.params.pitch, self.params.angle);
507 camera.position = (center - camera.forward() * self.camera_to_center_distance()) / world_size;
508 camera
509 }
510
511 #[must_use]
513 pub(crate) fn free_camera_options(&self) -> FreeCameraOptions {
514 let camera = self.camera_pose();
515 FreeCameraOptions { position: Some(camera.position), orientation: Some(camera.orientation) }
516 }
517
518 #[must_use]
525 pub(crate) fn eye_position(&self) -> DVec3 {
526 if self.is_globe() && self.is_valid() {
527 let eye = self.matrices.globe_camera_position;
528 return VerticalPerspectiveProjection::sphere_point_to_world(self, eye).unwrap_or(eye);
529 }
530 let position = self.camera_pose().position;
531 let world_size = Projection::world_size(self.params.scale);
532 DVec3::new(position.x, position.y, position.z * world_size * self.meters_per_pixel())
533 }
534
535 #[must_use]
542 pub(crate) fn near_plane_points(&self) -> [DVec3; 9] {
543 let eye = self.eye_position();
544 if self.matrices.projection == DMat4::ZERO {
545 return [eye; 9];
546 }
547 let clip = |index: usize| DVec3::new((index % 3) as f64 - 1.0, (index / 3) as f64 - 1.0, -1.0);
548 if self.is_globe() {
549 let inverse = self.matrices.inv_globe_view_projection;
550 return std::array::from_fn(|index| {
551 let point = inverse.project_point3(clip(index));
552 VerticalPerspectiveProjection::sphere_point_to_world(self, point).unwrap_or(eye)
553 });
554 }
555 let world_size = Projection::world_size(self.params.scale);
556 std::array::from_fn(|index| {
557 let point = self.matrices.inv_projection.project_point3(clip(index));
558 DVec3::new(point.x / world_size, point.y / world_size, point.z)
559 })
560 }
561
562 #[must_use]
566 pub(crate) fn projection_transition(&self) -> f64 {
567 self.params.projection_transition
568 }
569
570 #[must_use]
573 pub fn is_globe(&self) -> bool {
574 self.params.projection_transition > 0.0
575 }
576
577 #[must_use]
579 pub fn projection(&self) -> crate::camera::Projection {
580 if self.is_globe() {
581 crate::camera::Projection::VerticalPerspective
582 } else {
583 crate::camera::Projection::Mercator
584 }
585 }
586
587 #[must_use]
590 pub(crate) fn mercator(&self) -> View {
591 if !self.is_globe() {
592 return self.clone();
593 }
594 View::new(ViewParams { projection_transition: 0.0, ..self.params })
595 }
596
597 #[must_use]
599 pub(crate) fn tile_matrix(&self, tile_id: &UnwrappedTileID) -> DMat4 {
600 mercator_tile_matrix(tile_id, self.params.scale)
601 }
602
603 #[must_use]
605 pub(crate) fn projection_data_with(&self, tile_id: &UnwrappedTileID, proj_matrix: &DMat4) -> ProjectionData {
606 let mercator_matrix = *proj_matrix * self.tile_matrix(tile_id);
607 self.projection().projection_data(self, tile_id, &mercator_matrix)
608 }
609
610 #[must_use]
612 pub fn projection_data(&self, tile_id: &UnwrappedTileID) -> ProjectionData {
613 self.projection_data_with(tile_id, &self.matrices.projection)
614 }
615
616 #[must_use]
619 pub(crate) fn projection_data_for_matrix(
620 &self,
621 tile_id: &UnwrappedTileID,
622 mercator_matrix: &DMat4,
623 ) -> ProjectionData {
624 self.projection().projection_data(self, tile_id, mercator_matrix)
625 }
626
627 #[must_use]
631 pub fn terrain_min_elevation(&self) -> Option<f64> {
632 self.params.terrain_min_elevation
633 }
634
635 #[must_use]
640 pub(crate) fn near_z(&self) -> f64 {
641 match self.params.terrain_min_elevation {
642 Some(_) => f64::from(self.params.size.height) / 50.0,
643 None => 1.0,
644 }
645 }
646
647 #[must_use]
652 pub(crate) fn camera_to_sea_level_distance(&self) -> f64 {
653 let camera_to_center_distance = self.camera_to_center_distance();
654 let limited_pitch = self.params.pitch.min(max_mercator_horizon_angle());
655 f64::max(
656 camera_to_center_distance / 2.0,
657 camera_to_center_distance + self.center_altitude_pixels() / limited_pitch.cos(),
658 )
659 }
660
661 #[must_use]
669 pub(crate) fn far_z(&self) -> f64 {
670 let params = &self.params;
671 let camera_to_center_distance = self.camera_to_center_distance();
672 let pixels_per_meter = 1.0 / self.meters_per_pixel();
673
674 let ground = params.terrain_min_elevation.unwrap_or(0.0) * pixels_per_meter;
676 let center_altitude = self.center_altitude_pixels();
677 let limited_pitch = params.pitch.min(max_mercator_horizon_angle());
678 let camera_to_sea_level_distance = self.camera_to_sea_level_distance();
679 let camera_altitude = params.pitch.cos() * camera_to_center_distance + center_altitude;
680 let lowest = center_altitude.min(ground).min(camera_altitude - 100.0 * pixels_per_meter);
681 let lowest_plane = if lowest < 0.0 {
682 camera_to_sea_level_distance - lowest / limited_pitch.cos()
683 } else {
684 camera_to_sea_level_distance
685 };
686
687 let ground_angle = PI / 2.0 + params.pitch;
691 let distance_past_center = |angle: f64| {
692 angle.sin() * lowest_plane / mln_style::math::clamp_f64(PI - ground_angle - angle, 0.01, PI - 0.01).sin()
693 };
694 let top_half_distance = distance_past_center(self.tan_fov_above_center().atan())
695 .min(distance_past_center(self.fov_center_to_horizon()));
696
697 (limited_pitch.sin() * top_half_distance + lowest_plane) * 1.01
698 }
699
700 #[must_use]
703 pub(crate) fn shows_horizon(&self) -> bool {
704 self.fov_center_to_horizon() < self.tan_fov_above_center().atan()
705 }
706
707 fn tan_fov_above_center(&self) -> f64 {
712 let params = &self.params;
713 let half_width = 0.5 * f64::from(params.size.width);
714 let half_height = 0.5 * f64::from(params.size.height);
715 let offset = self.center_offset();
716 let (left, right) = (half_width + offset.x, half_width - offset.x);
718 let (top, bottom) = (half_height + offset.y - params.frustum_offset.top, half_height - offset.y);
719 let up = self.up_the_map();
720 let reach = (up.x * right).max(-up.x * left) + (up.y * top).max(-up.y * bottom);
721 reach / half_height * (params.fov / 2.0).tan()
722 }
723
724 fn fov_center_to_horizon(&self) -> f64 {
732 let camera_to_center = self.camera_to_center_distance();
733 let horizon = self.mercator_horizon();
734 let min_horizon_angle = PI / 2.0 - max_mercator_horizon_angle();
735 if (horizon / camera_to_center).atan() <= min_horizon_angle {
736 return min_horizon_angle;
737 }
738 let offset = self.center_offset();
739 let offset_up = DVec2::new(-offset.x, offset.y).dot(self.up_the_map());
740 let farthest = camera_to_center * (max_mercator_horizon_angle() - self.params.pitch).tan();
741 (mln_style::math::clamp_f64(horizon + offset_up, 0.0, farthest) / camera_to_center).atan()
742 }
743
744 fn up_the_map(&self) -> DVec2 {
748 let (sin, cos) = self.params.roll.sin_cos();
749 DVec2::from_angle(-self.north_orientation_angle()).rotate(DVec2::new(-sin, cos))
750 }
751
752 #[must_use]
755 pub(crate) fn projection_matrix_with(&self, near_z: f64, aligned: bool) -> DMat4 {
756 let params = &self.params;
757 if params.size.is_empty() {
758 return DMat4::ZERO;
759 }
760
761 let offset = self.center_offset();
762 let width = f64::from(params.size.width);
763 let height = f64::from(params.size.height);
764
765 let camera = self.camera_pose();
766 let pixels_per_meter = 1.0 / self.meters_per_pixel();
767 let world_to_camera = camera.world_to_camera(params.scale, pixels_per_meter);
768 let mut camera_to_clip = perspective(self.perspective_fov(), width / height, near_z, self.far_z());
769
770 if !params.axonometric {
773 camera_to_clip.z_axis.x = -offset.x * 2.0 / width;
774 camera_to_clip.z_axis.y = offset.y * 2.0 / height;
775 }
776
777 if params.north_orientation != NorthOrientation::Upwards {
778 camera_to_clip *= DMat4::from_rotation_z(-self.north_orientation_angle());
779 }
780
781 let mut proj_matrix = camera_to_clip * world_to_camera;
782
783 if params.axonometric {
784 proj_matrix.z_axis.w = 0.0;
786 proj_matrix.z_axis.x = params.x_skew * pixels_per_meter;
787 proj_matrix.z_axis.y = params.y_skew * pixels_per_meter;
788 }
789
790 if aligned {
795 let world_size = Projection::world_size(params.scale);
796 let dx = params.x - 0.5 * world_size;
797 let dy = params.y - 0.5 * world_size;
798
799 let x_shift = f64::from(params.size.width % 2) / 2.0;
800 let y_shift = f64::from(params.size.height % 2) / 2.0;
801 let angle_cos = params.angle.cos();
802 let angle_sin = params.angle.sin();
803 let dxa = -modf_fraction(dx) + angle_cos * x_shift + angle_sin * y_shift;
804 let dya = -modf_fraction(dy) + angle_cos * y_shift + angle_sin * x_shift;
805 proj_matrix *= DMat4::from_translation(DVec3::new(
806 if dxa > 0.5 { dxa - 1.0 } else { dxa },
807 if dya > 0.5 { dya - 1.0 } else { dya },
808 0.0,
809 ));
810 }
811 proj_matrix
812 }
813
814 #[cfg(any(test, feature = "bench"))]
817 #[must_use]
818 pub(crate) fn projection_matrix(&self) -> DMat4 {
819 self.matrices.projection
820 }
821
822 #[must_use]
823 pub(crate) fn inverse_projection_matrix(&self) -> DMat4 {
824 self.matrices.inv_projection
825 }
826
827 #[must_use]
830 pub(crate) fn globe_view_projection_matrix(&self) -> DMat4 {
831 self.matrices.globe_view_projection
832 }
833
834 #[must_use]
835 pub(crate) fn inverse_globe_view_projection_matrix(&self) -> DMat4 {
836 self.matrices.inv_globe_view_projection
837 }
838
839 #[must_use]
842 pub(crate) fn globe_clipping_plane(&self) -> DVec4 {
843 self.matrices.globe_clipping_plane
844 }
845
846 #[must_use]
848 pub fn globe_camera_position(&self) -> DVec3 {
849 self.matrices.globe_camera_position
850 }
851
852 fn center_coordinate(&self) -> DVec3 {
855 let world_size = Projection::world_size(self.params.scale);
856 DVec3::new(
857 (0.5 * world_size - self.params.x) / TILE_SIZE_D,
858 (0.5 * world_size - self.params.y) / TILE_SIZE_D,
859 0.0,
860 )
861 }
862
863 fn coordinate_point_matrix(&self, proj_matrix: &DMat4) -> DMat4 {
865 let size = self.params.size;
866 let pixel_matrix =
867 DMat4::from_scale(DVec3::new(f64::from(size.width) / 2.0, -f64::from(size.height) / 2.0, 1.0))
868 * DMat4::from_translation(DVec3::new(1.0, -1.0, 0.0));
869 pixel_matrix * *proj_matrix * DMat4::from_scale(DVec3::new(TILE_SIZE_D, TILE_SIZE_D, 1.0))
870 }
871
872 #[must_use]
876 pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
877 self.lat_lng_to_screen_coordinate_at(lat_lng, 0.0)
878 }
879
880 #[must_use]
884 pub(crate) fn lat_lng_to_screen_coordinate_at(&self, lat_lng: &LatLng, height: f64) -> ScreenCoordinate {
885 self.clip_point_at(lat_lng, height).0
886 }
887
888 #[must_use]
891 #[cfg(test)]
892 pub(crate) fn lat_lng_to_screen_coordinate_with_clip(&self, lat_lng: &LatLng) -> (ScreenCoordinate, DVec4) {
893 self.clip_point_at(lat_lng, 0.0)
894 }
895
896 fn clip_point_at(&self, lat_lng: &LatLng, height: f64) -> (ScreenCoordinate, DVec4) {
901 if self.params.size.is_empty() {
902 return (ScreenCoordinate::new(0.0, 0.0), DVec4::ZERO);
903 }
904
905 if self.is_globe() {
906 return VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(self, lat_lng, height);
907 }
908
909 let pt = Projection::project(lat_lng, self.params.scale);
910 let p = self.matrices.coord * DVec4::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D, height, 1.0);
911 (ScreenCoordinate::new(p.x / p.w, f64::from(self.params.size.height) - p.y / p.w), p)
912 }
913
914 #[must_use]
917 pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
918 if self.params.size.is_empty() || !self.is_globe() {
919 return false;
920 }
921 let surface = VerticalPerspectiveProjection::surface_vector(lat_lng);
922 self.globe_clipping_plane().dot(surface.extend(1.0)) < 0.0
923 }
924
925 #[must_use]
928 pub(crate) fn screen_coordinate_to_tile_coordinate(&self, point: &ScreenCoordinate, at_zoom: u8) -> TileCoordinate {
929 if self.params.size.is_empty() {
930 return TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 };
931 }
932
933 if self.is_globe() {
934 return match VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(
935 self,
936 point,
937 0.0,
938 WrapMode::Unwrapped,
939 ) {
940 Some(lat_lng) => TileCoordinate::from_lat_lng(f64::from(at_zoom), &lat_lng),
941 None => TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 },
942 };
943 }
944
945 self.mercator_screen_coordinate_to_tile_coordinate(point, at_zoom, 0.0)
946 }
947
948 fn mercator_screen_coordinate_to_tile_coordinate(
952 &self,
953 point: &ScreenCoordinate,
954 at_zoom: u8,
955 height: f64,
956 ) -> TileCoordinate {
957 let flipped_y = f64::from(self.params.size.height) - point.y;
958
959 let inverted = self.matrices.inverted_from_center;
962 let offset0 = inverted.project_point3(DVec3::new(point.x, flipped_y, 0.0));
963 let offset1 = inverted.project_point3(DVec3::new(point.x, flipped_y, 1.0));
964
965 let z0 = offset0.z;
966 let z1 = offset1.z;
967 let t = if z0 <= z1 { 0.0 } else { -(z0 - height) / (z1 - z0) };
969
970 let offset = offset0 + (offset1 - offset0) * t;
971 let center = self.center_coordinate();
972 let factor = f64::from(1i32.wrapping_shl(u32::from(at_zoom)));
973 let scale = self.params.scale;
974 TileCoordinate {
975 p: Point::new((center.x + offset.x) / scale * factor, (center.y + offset.y) / scale * factor),
976 z: f64::from(at_zoom),
977 }
978 }
979
980 pub(crate) fn screen_coordinate_to_lat_lng(
984 &self,
985 point: &ScreenCoordinate,
986 wrap_mode: WrapMode,
987 ) -> Result<LatLng, Error> {
988 self.screen_coordinate_to_lat_lng_at(point, 0.0, wrap_mode)
989 }
990
991 pub fn screen_coordinate_to_lat_lng_at(
999 &self,
1000 point: &ScreenCoordinate,
1001 height: f64,
1002 wrap_mode: WrapMode,
1003 ) -> Result<LatLng, Error> {
1004 if self.is_globe() && !self.params.size.is_empty() {
1006 if point.x.is_nan() || point.y.is_nan() {
1007 return Err(Error::invalid_argument("screen coordinate must not be NaN"));
1008 }
1009 if !point.x.is_finite() || !point.y.is_finite() {
1010 return Err(Error::invalid_argument("screen coordinate must not be infinite"));
1011 }
1012 return VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(self, point, height, wrap_mode)
1013 .ok_or_else(|| Error::invalid_argument("the camera shows no location"));
1014 }
1015 let coord = if self.params.size.is_empty() {
1016 self.screen_coordinate_to_tile_coordinate(point, 0)
1017 } else {
1018 self.mercator_screen_coordinate_to_tile_coordinate(point, 0, height)
1019 };
1020 Projection::unproject(&coord.p, 1.0 / TILE_SIZE_D, wrap_mode)
1021 }
1022
1023 #[must_use]
1029 pub fn line_of_sight(&self, point: &ScreenCoordinate) -> Option<(DVec3, DVec3)> {
1030 if self.is_globe() || self.matrices.projection == DMat4::ZERO {
1031 return None;
1032 }
1033 let flipped_y = f64::from(self.params.size.height) - point.y;
1034 let inverted = self.matrices.inverted_from_center;
1037 let center = self.center_coordinate();
1038 let scale = self.params.scale;
1039 let world = |depth: f64| {
1040 let offset = inverted.project_point3(DVec3::new(point.x, flipped_y, depth));
1041 DVec3::new((center.x + offset.x) / scale, (center.y + offset.y) / scale, offset.z)
1042 };
1043 let (near, far) = (world(-1.0), world(1.0));
1044 (near.is_finite() && far.is_finite()).then_some((near, far))
1045 }
1046
1047 #[must_use]
1051 pub(crate) fn max_pitch_scale_factor(&self) -> f64 {
1052 if self.params.size.is_empty() {
1053 return 0.0;
1054 }
1055 let corner = self.mercator_screen_coordinate_to_tile_coordinate(
1058 &ScreenCoordinate::new(0.0, f64::from(self.params.size.height)),
1059 0,
1060 0.0,
1061 );
1062 let Ok(lat_lng) = Projection::unproject(&corner.p, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped) else {
1064 return 0.0;
1065 };
1066
1067 let scale = self.params.scale;
1068 let pt = if self.is_globe() {
1069 Point::new(corner.p.x * scale, corner.p.y * scale)
1070 } else {
1071 let pt = Projection::project(&lat_lng, scale);
1072 Point::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D)
1073 };
1074 let top_point = self.matrices.coord * DVec4::new(pt.x, pt.y, 0.0, 1.0);
1075 top_point.w / self.camera_to_center_distance()
1076 }
1077}