1use std::f64::consts::PI;
5
6use glam::dcamera::rh::proj::opengl::perspective;
7use glam::{DMat4, DVec2, DVec3, DVec4};
8use mln_style::constants::TILE_SIZE_D;
9use mln_style::crs::WorldMapping;
10use mln_style::error::Error;
11use mln_style::geo::{LatLng, WrapMode};
12use mln_style::geometry::Point;
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;
69
70fn modf_fraction(x: f64) -> f64 {
72 if x.is_infinite() {
73 return 0.0f64.copysign(x);
74 }
75 (x - x.trunc()).copysign(x)
76}
77
78#[derive(Clone, Debug, PartialEq)]
80pub(crate) struct ViewParams {
81 pub(crate) size: Size,
82 pub(crate) frustum_offset: EdgeInsets,
83 pub(crate) north_orientation: NorthOrientation,
84 pub(crate) constrain_mode: ConstrainMode,
87 pub(crate) center_clamped_to_ground: bool,
90 pub(crate) globe_free_bearing: bool,
93 pub(crate) projection: ViewProjection,
96 pub(crate) padding: EdgeInsets,
97 pub(crate) x: f64,
100 pub(crate) y: f64,
101 pub(crate) center_altitude: f64,
104 pub(crate) scale: f64,
105 pub(crate) angle: f64,
108 pub(crate) pitch: f64,
109 pub(crate) roll: f64,
110 pub(crate) fov: f64,
111 pub(crate) x_skew: f64,
112 pub(crate) y_skew: f64,
113 pub(crate) axonometric: bool,
114 pub(crate) center_wrap: WrapMode,
116 pub(crate) terrain_min_elevation: Option<f64>,
119}
120
121impl ViewParams {
122 pub(crate) fn new(constrain_mode: ConstrainMode) -> Self {
123 ViewParams {
124 size: Size::default(),
125 frustum_offset: EdgeInsets::default(),
126 north_orientation: NorthOrientation::Upwards,
127 constrain_mode,
128 center_clamped_to_ground: true,
129 globe_free_bearing: false,
130 projection: ViewProjection::BuiltIn(ProjectionDefinition::default()),
131 padding: EdgeInsets::default(),
132 x: 0.0,
133 y: 0.0,
134 center_altitude: 0.0,
135 scale: 1.0,
136 angle: 0.0,
137 pitch: 0.0,
138 roll: 0.0,
139 fov: DEFAULT_FOV,
140 x_skew: 0.0,
141 y_skew: 1.0,
142 axonometric: false,
143 center_wrap: WrapMode::Unwrapped,
144 terrain_min_elevation: None,
145 }
146 }
147}
148
149#[derive(Clone, Copy, Debug)]
152struct Matrices {
153 projection: DMat4,
154 inv_projection: DMat4,
155 coord: DMat4,
156 inverted_from_center: DMat4,
160 globe_view_projection: DMat4,
161 inv_globe_view_projection: DMat4,
162 globe_clipping_plane: DVec4,
163 globe_camera_position: DVec3,
164}
165
166impl Matrices {
167 const ZERO: Matrices = Matrices {
168 projection: DMat4::ZERO,
169 inv_projection: DMat4::ZERO,
170 coord: DMat4::ZERO,
171 inverted_from_center: DMat4::ZERO,
172 globe_view_projection: DMat4::ZERO,
173 inv_globe_view_projection: DMat4::ZERO,
174 globe_clipping_plane: DVec4::ZERO,
175 globe_camera_position: DVec3::ZERO,
176 };
177}
178
179#[derive(Clone, Debug)]
186pub struct View {
187 params: ViewParams,
188 matrices: Matrices,
189}
190
191impl PartialEq for View {
192 fn eq(&self, other: &Self) -> bool {
194 self.params == other.params
195 }
196}
197
198impl Default for View {
199 fn default() -> Self {
200 View::new(ViewParams::new(ConstrainMode::HeightOnly))
201 }
202}
203
204impl View {
205 pub(crate) fn new(params: ViewParams) -> Self {
206 let mut view = View { params, matrices: Matrices::ZERO };
207 view.matrices = view.compute_matrices();
208 view
209 }
210
211 pub(crate) fn params(&self) -> &ViewParams {
212 &self.params
213 }
214
215 fn compute_matrices(&self) -> Matrices {
217 if self.params.size.is_empty() {
218 return Matrices::ZERO;
219 }
220 let projection = self.projection_matrix_with(self.near_z(), false);
221 let coord = self.coordinate_point_matrix(&projection);
222 let from_center = coord * DMat4::from_translation(self.center_coordinate());
223 let (Some(inv_projection), Some(inverted_from_center)) = (projection.try_inverse(), from_center.try_inverse())
224 else {
225 return Matrices::ZERO;
226 };
227 let mut matrices = Matrices { projection, inv_projection, coord, inverted_from_center, ..Matrices::ZERO };
228 if self.is_globe() {
229 let globe_radius = VerticalPerspectiveProjection::globe_radius_pixels(
230 Projection::world_size(self.params.scale),
231 self.center(WrapMode::Unwrapped).latitude(),
232 );
233 let globe_view_projection = VerticalPerspectiveProjection::globe_view_projection_matrix(self, globe_radius);
234 matrices.globe_view_projection = globe_view_projection;
235 matrices.inv_globe_view_projection = globe_view_projection.try_inverse().unwrap_or(DMat4::IDENTITY);
236 matrices.globe_clipping_plane = VerticalPerspectiveProjection::clipping_plane(self, globe_radius);
237 matrices.globe_camera_position = VerticalPerspectiveProjection::camera_position(self, globe_radius);
238 }
239 matrices
240 }
241
242 #[must_use]
246 pub fn size(&self) -> Size {
247 self.params.size
248 }
249
250 #[must_use]
252 pub(crate) fn frustum_offset(&self) -> EdgeInsets {
253 self.params.frustum_offset
254 }
255
256 #[must_use]
258 pub(crate) fn padding(&self) -> EdgeInsets {
259 self.params.padding
260 }
261
262 #[must_use]
263 pub(crate) fn north_orientation(&self) -> NorthOrientation {
264 self.params.north_orientation
265 }
266
267 #[must_use]
269 pub(crate) fn north_orientation_angle(&self) -> f64 {
270 match self.params.north_orientation {
271 NorthOrientation::Upwards => 0.0,
272 NorthOrientation::Rightwards => PI / 2.0,
273 NorthOrientation::Downwards => PI,
274 NorthOrientation::Leftwards => -PI / 2.0,
275 }
276 }
277
278 #[must_use]
281 pub(crate) fn center_clamped_to_ground(&self) -> bool {
282 self.params.center_clamped_to_ground
283 }
284
285 #[must_use]
288 pub(crate) fn globe_free_bearing(&self) -> bool {
289 self.params.globe_free_bearing
290 }
291
292 pub(crate) fn center_offset(&self) -> ScreenCoordinate {
295 let padding = &self.params.padding;
296 ScreenCoordinate::new(0.5 * (padding.left - padding.right), 0.5 * (padding.top - padding.bottom))
297 }
298
299 #[must_use]
304 pub fn center(&self, wrap_mode: WrapMode) -> LatLng {
305 let offset = Point::new(-self.params.x, -self.params.y);
306 self.params.projection.world().unproject_from_center(&offset, self.params.scale, wrap_mode)
307 }
308
309 #[must_use]
312 pub fn lat_lng_near_center(&self, location: &LatLng) -> LatLng {
313 if !self.params.projection.world().wraps() {
314 return *location;
315 }
316 let center = self.center(WrapMode::Unwrapped);
317 let wrapped_center = center.wrapped();
318 let mut nearest = location.wrapped();
319 nearest.unwrap_for_shortest_path(&wrapped_center);
320 LatLng::saturating(
321 nearest.latitude(),
322 nearest.longitude() + center.longitude() - wrapped_center.longitude(),
323 WrapMode::Unwrapped,
324 )
325 }
326
327 #[must_use]
329 pub fn center_altitude(&self) -> f64 {
330 self.params.center_altitude
331 }
332
333 pub(crate) fn meters_per_pixel(&self) -> f64 {
337 let scale = 2.0f64.powf(mln_style::math::clamp_f64(self.zoom(), MIN_ZOOM, MAX_ZOOM));
340 self.params.projection.world().height_meters_per_world_unit(&self.center(WrapMode::Unwrapped))
341 / Projection::world_size(scale)
342 }
343
344 #[must_use]
352 pub fn ground_meters_per_world_unit_at(&self, lat_lng: &LatLng) -> f64 {
353 self.ground_meters_per_world_unit_at_lng_lat([lat_lng.longitude(), lat_lng.latitude()])
354 }
355
356 fn ground_meters_per_world_unit_at_lng_lat(&self, lng_lat: [f64; 2]) -> f64 {
359 let world = self.params.projection.world();
360 let mut place = [[0.0; 2]];
361 world.world_from_lng_lats(&[lng_lat], &mut place);
362 let [dx, dy] = self.screen_x_axis_at(&Point::new(place[0][0], place[0][1]));
363 let span = SCALE_SPAN_PX / Projection::world_size(self.params.scale);
364 world.ground_meters_per_world_unit(lng_lat, [dx * span, dy * span])
365 }
366
367 #[must_use]
373 pub fn meters_per_pixel_at(&self, lat_lng: &LatLng) -> f64 {
374 self.meters_per_pixel_at_lng_lat([lat_lng.longitude(), lat_lng.latitude()])
375 }
376
377 pub(crate) fn meters_per_pixel_at_lng_lat(&self, lng_lat: [f64; 2]) -> f64 {
380 let scale = 2.0f64.powf(mln_style::math::clamp_f64(self.zoom(), MIN_ZOOM, MAX_ZOOM));
381 self.ground_meters_per_world_unit_at_lng_lat(lng_lat) / Projection::world_size(scale)
382 }
383
384 fn screen_x_axis_at(&self, at: &Point<f64>) -> [f64; 2] {
388 let screen = self.world_to_screen_coordinate(at);
389 let next = self.screen_coordinate_to_world_at(&ScreenCoordinate::new(screen.x + 1.0, screen.y), 0.0);
390 let (dx, dy) = (next.x - at.x, next.y - at.y);
391 let length = dx.hypot(dy);
392 if length > 0.0 && length.is_finite() { [dx / length, dy / length] } else { [1.0, 0.0] }
393 }
394
395 fn center_altitude_pixels(&self) -> f64 {
397 if self.params.center_altitude == 0.0 {
400 return self.params.center_altitude;
401 }
402 self.params.center_altitude / self.meters_per_pixel()
403 }
404
405 #[must_use]
406 pub fn zoom(&self) -> f64 {
407 scale_zoom(self.params.scale)
408 }
409
410 #[must_use]
412 pub fn integer_zoom(&self) -> u8 {
413 f64::max(0.0, self.zoom()) as u8
414 }
415
416 #[must_use]
418 pub(crate) fn scale(&self) -> f64 {
419 self.params.scale
420 }
421
422 #[must_use]
425 pub(crate) fn x(&self) -> f64 {
426 self.params.x
427 }
428
429 #[must_use]
431 pub(crate) fn y(&self) -> f64 {
432 self.params.y
433 }
434
435 #[must_use]
438 pub fn world(&self) -> &WorldMapping {
439 self.params.projection.world()
440 }
441
442 pub(crate) fn center_world(&self) -> Point<f64> {
444 let world_size = Projection::world_size(self.params.scale);
445 Point::new(0.5 - self.params.x / world_size, 0.5 - self.params.y / world_size)
446 }
447
448 #[must_use]
452 pub fn world_copy_longitude(&self) -> f64 {
453 if self.params.projection.world().wraps() { self.center(WrapMode::Unwrapped).longitude() } else { 0.0 }
454 }
455
456 #[must_use]
458 pub fn angle(&self) -> f64 {
459 self.params.angle
460 }
461
462 #[must_use]
464 pub fn pitch(&self) -> f64 {
465 self.params.pitch
466 }
467
468 #[must_use]
469 pub fn roll(&self) -> f64 {
470 self.params.roll
471 }
472
473 #[must_use]
475 pub(crate) fn fov(&self) -> f64 {
476 self.params.fov
477 }
478
479 pub(crate) fn perspective_fov(&self) -> f64 {
486 f64::from(self.params.fov as f32)
487 }
488
489 #[must_use]
491 pub fn camera_to_center_distance(&self) -> f64 {
492 0.5 * f64::from(self.params.size.height) / (self.params.fov / 2.0).tan()
493 }
494
495 #[must_use]
500 pub(crate) fn mercator_horizon(&self) -> f64 {
501 let pitch = self.params.pitch;
502 self.camera_to_center_distance()
503 * f64::min((PI / 2.0 - pitch).tan() * 0.85, (max_mercator_horizon_angle() - pitch).tan())
504 }
505
506 #[must_use]
507 pub(crate) fn projection_mode(&self) -> ProjectionMode {
508 ProjectionMode {
509 axonometric: Some(AxonometricMode::from(self.params.axonometric)),
510 x_skew: Some(self.params.x_skew),
511 y_skew: Some(self.params.y_skew),
512 }
513 }
514
515 #[must_use]
517 pub(crate) fn camera(&self) -> Camera {
518 Camera {
519 center: self.center(self.params.center_wrap),
520 center_altitude: self.center_altitude(),
521 padding: self.params.padding,
522 zoom: self.zoom(),
523 bearing: mln_style::math::rad2deg(-self.params.angle),
524 pitch: mln_style::math::rad2deg(self.params.pitch),
525 roll: mln_style::math::rad2deg(self.params.roll),
526 fov: mln_style::math::rad2deg(self.params.fov),
527 }
528 }
529
530 #[must_use]
533 pub fn map_view(&self, scale_factor: f64) -> MapView {
534 MapView {
535 camera: self.camera(),
536 extent: LogicalExtent { size: self.params.size, scale_factor },
537 projection_mode: self.projection_mode(),
538 viewport: Viewport {
539 north_orientation: self.params.north_orientation,
540 constrain_mode: self.params.constrain_mode,
541 center_clamped_to_ground: self.params.center_clamped_to_ground,
542 globe_free_bearing: self.params.globe_free_bearing,
543 frustum_offset: self.params.frustum_offset,
544 },
545 projection: self.params.projection.clone(),
546 }
547 }
548
549 #[must_use]
551 pub(crate) fn is_valid(&self) -> bool {
552 !self.params.size.is_empty() && self.params.scale.is_finite() && self.params.scale > 0.0
553 }
554
555 pub(crate) fn camera_pose(&self) -> CameraPose {
558 if !self.is_valid() {
559 return CameraPose::default();
560 }
561 let world_size = Projection::world_size(self.params.scale);
562 let center = DVec3::new(
565 0.5 * world_size - self.params.x,
566 0.5 * world_size - self.params.y,
567 self.center_altitude_pixels(),
568 );
569 let mut camera = CameraPose::from_angles(DVec3::ZERO, self.params.roll, self.params.pitch, self.params.angle);
572 camera.position = (center - camera.forward() * self.camera_to_center_distance()) / world_size;
573 camera
574 }
575
576 #[must_use]
578 pub(crate) fn free_camera_options(&self) -> FreeCameraOptions {
579 let camera = self.camera_pose();
580 FreeCameraOptions { position: Some(camera.position), orientation: Some(camera.orientation) }
581 }
582
583 #[must_use]
591 pub(crate) fn eye_position(&self) -> DVec3 {
592 if self.is_globe() && self.is_valid() {
593 let eye = self.matrices.globe_camera_position;
594 return VerticalPerspectiveProjection::sphere_point_to_world(self, eye).unwrap_or(eye);
595 }
596 let position = self.camera_pose().position;
597 let world_size = Projection::world_size(self.params.scale);
598 DVec3::new(position.x, position.y, position.z * world_size * self.meters_per_pixel())
599 }
600
601 #[must_use]
612 pub(crate) fn near_plane_points(&self) -> [DVec3; 9] {
613 let eye = self.eye_position();
614 if self.matrices.projection == DMat4::ZERO {
615 return [eye; 9];
616 }
617 let clip = |index: usize| DVec3::new((index % 3) as f64 - 1.0, (index / 3) as f64 - 1.0, 0.0);
618 if self.is_globe() {
619 let inverse = self.matrices.inv_globe_view_projection;
620 return std::array::from_fn(|index| {
621 let point = inverse.project_point3(clip(index));
622 VerticalPerspectiveProjection::sphere_point_to_world(self, point).unwrap_or(eye)
623 });
624 }
625 let world_size = Projection::world_size(self.params.scale);
626 std::array::from_fn(|index| {
627 let point = self.matrices.inv_projection.project_point3(clip(index));
628 DVec3::new(point.x / world_size, point.y / world_size, point.z)
629 })
630 }
631
632 #[must_use]
636 pub(crate) fn projection_transition(&self) -> f64 {
637 self.params.projection.transition()
638 }
639
640 #[must_use]
643 pub fn is_globe(&self) -> bool {
644 self.params.projection.transition() > 0.0
645 }
646
647 #[must_use]
649 pub fn projection(&self) -> crate::camera::Projection {
650 if self.is_globe() {
651 crate::camera::Projection::VerticalPerspective
652 } else {
653 crate::camera::Projection::Mercator
654 }
655 }
656
657 #[must_use]
660 pub(crate) fn mercator(&self) -> View {
661 if !self.is_globe() {
662 return self.clone();
663 }
664 View::new(ViewParams {
665 projection: ViewProjection::BuiltIn(ProjectionDefinition::default()),
666 ..self.params.clone()
667 })
668 }
669
670 #[must_use]
672 pub(crate) fn tile_matrix(&self, tile_id: &UnwrappedTileID) -> DMat4 {
673 mercator_tile_matrix(tile_id, self.params.scale)
674 }
675
676 #[must_use]
678 pub(crate) fn projection_data_with(&self, tile_id: &UnwrappedTileID, proj_matrix: &DMat4) -> ProjectionData {
679 let mercator_matrix = *proj_matrix * self.tile_matrix(tile_id);
680 self.projection().projection_data(self, tile_id, &mercator_matrix)
681 }
682
683 #[must_use]
685 pub fn projection_data(&self, tile_id: &UnwrappedTileID) -> ProjectionData {
686 self.projection_data_with(tile_id, &self.matrices.projection)
687 }
688
689 #[must_use]
692 pub(crate) fn projection_data_for_matrix(
693 &self,
694 tile_id: &UnwrappedTileID,
695 mercator_matrix: &DMat4,
696 ) -> ProjectionData {
697 self.projection().projection_data(self, tile_id, mercator_matrix)
698 }
699
700 #[must_use]
704 pub fn terrain_min_elevation(&self) -> Option<f64> {
705 self.params.terrain_min_elevation
706 }
707
708 #[must_use]
713 pub(crate) fn near_z(&self) -> f64 {
714 match self.params.terrain_min_elevation {
715 Some(_) => f64::from(self.params.size.height) / 50.0,
716 None => 1.0,
717 }
718 }
719
720 #[must_use]
724 pub(crate) fn camera_to_sea_level_distance(&self) -> f64 {
725 let camera_to_center_distance = self.camera_to_center_distance();
726 let limited_pitch = self.params.pitch.min(max_mercator_horizon_angle());
727 f64::max(
728 camera_to_center_distance / 2.0,
729 camera_to_center_distance + self.center_altitude_pixels() / limited_pitch.cos(),
730 )
731 }
732
733 #[must_use]
740 pub(crate) fn far_z(&self) -> f64 {
741 let params = &self.params;
742 let camera_to_center_distance = self.camera_to_center_distance();
743 let pixels_per_meter = 1.0 / self.meters_per_pixel();
744
745 let ground = params.terrain_min_elevation.unwrap_or(0.0) * pixels_per_meter;
747 let center_altitude = self.center_altitude_pixels();
748 let limited_pitch = params.pitch.min(max_mercator_horizon_angle());
749 let camera_to_sea_level_distance = self.camera_to_sea_level_distance();
750 let camera_altitude = params.pitch.cos() * camera_to_center_distance + center_altitude;
751 let lowest = center_altitude.min(ground).min(camera_altitude - 100.0 * pixels_per_meter);
752 let lowest_plane = if lowest < 0.0 {
753 camera_to_sea_level_distance - lowest / limited_pitch.cos()
754 } else {
755 camera_to_sea_level_distance
756 };
757
758 let ground_angle = PI / 2.0 + params.pitch;
762 let distance_past_center = |angle: f64| {
763 angle.sin() * lowest_plane / mln_style::math::clamp_f64(PI - ground_angle - angle, 0.01, PI - 0.01).sin()
764 };
765 let top_half_distance = distance_past_center(self.tan_fov_above_center().atan())
766 .min(distance_past_center(self.fov_center_to_horizon()));
767
768 (limited_pitch.sin() * top_half_distance + lowest_plane) * 1.01
769 }
770
771 #[must_use]
774 pub(crate) fn shows_horizon(&self) -> bool {
775 self.fov_center_to_horizon() < self.tan_fov_above_center().atan()
776 }
777
778 fn tan_fov_above_center(&self) -> f64 {
783 let params = &self.params;
784 let half_width = 0.5 * f64::from(params.size.width);
785 let half_height = 0.5 * f64::from(params.size.height);
786 let offset = self.center_offset();
787 let (left, right) = (half_width + offset.x, half_width - offset.x);
789 let (top, bottom) = (half_height + offset.y - params.frustum_offset.top, half_height - offset.y);
790 let up = self.up_the_map();
791 let reach = (up.x * right).max(-up.x * left) + (up.y * top).max(-up.y * bottom);
792 reach / half_height * (params.fov / 2.0).tan()
793 }
794
795 fn fov_center_to_horizon(&self) -> f64 {
803 let camera_to_center = self.camera_to_center_distance();
804 let horizon = self.mercator_horizon();
805 let min_horizon_angle = PI / 2.0 - max_mercator_horizon_angle();
806 if (horizon / camera_to_center).atan() <= min_horizon_angle {
807 return min_horizon_angle;
808 }
809 let offset = self.center_offset();
810 let offset_up = DVec2::new(-offset.x, offset.y).dot(self.up_the_map());
811 let farthest = camera_to_center * (max_mercator_horizon_angle() - self.params.pitch).tan();
812 (mln_style::math::clamp_f64(horizon + offset_up, 0.0, farthest) / camera_to_center).atan()
813 }
814
815 fn up_the_map(&self) -> DVec2 {
819 let (sin, cos) = self.params.roll.sin_cos();
820 DVec2::from_angle(-self.north_orientation_angle()).rotate(DVec2::new(-sin, cos))
821 }
822
823 #[must_use]
826 pub(crate) fn projection_matrix_with(&self, near_z: f64, aligned: bool) -> DMat4 {
827 let params = &self.params;
828 if params.size.is_empty() {
829 return DMat4::ZERO;
830 }
831
832 let offset = self.center_offset();
833 let width = f64::from(params.size.width);
834 let height = f64::from(params.size.height);
835
836 let camera = self.camera_pose();
837 let pixels_per_meter = 1.0 / self.meters_per_pixel();
838 let world_to_camera = camera.world_to_camera(params.scale, pixels_per_meter);
839 let mut camera_to_clip = perspective(self.perspective_fov(), width / height, near_z, self.far_z());
840
841 if !params.axonometric {
844 camera_to_clip.z_axis.x = -offset.x * 2.0 / width;
845 camera_to_clip.z_axis.y = offset.y * 2.0 / height;
846 }
847
848 if params.north_orientation != NorthOrientation::Upwards {
849 camera_to_clip *= DMat4::from_rotation_z(-self.north_orientation_angle());
850 }
851
852 let mut proj_matrix = camera_to_clip * world_to_camera;
853
854 if params.axonometric {
855 proj_matrix.z_axis.w = 0.0;
857 proj_matrix.z_axis.x = params.x_skew * pixels_per_meter;
858 proj_matrix.z_axis.y = params.y_skew * pixels_per_meter;
859 }
860
861 if aligned {
866 let world_size = Projection::world_size(params.scale);
867 let dx = params.x - 0.5 * world_size;
868 let dy = params.y - 0.5 * world_size;
869
870 let x_shift = f64::from(params.size.width % 2) / 2.0;
871 let y_shift = f64::from(params.size.height % 2) / 2.0;
872 let angle_cos = params.angle.cos();
873 let angle_sin = params.angle.sin();
874 let dxa = -modf_fraction(dx) + angle_cos * x_shift + angle_sin * y_shift;
875 let dya = -modf_fraction(dy) + angle_cos * y_shift + angle_sin * x_shift;
876 proj_matrix *= DMat4::from_translation(DVec3::new(
877 if dxa > 0.5 { dxa - 1.0 } else { dxa },
878 if dya > 0.5 { dya - 1.0 } else { dya },
879 0.0,
880 ));
881 }
882 proj_matrix
883 }
884
885 #[cfg(any(test, feature = "bench"))]
888 #[must_use]
889 pub(crate) fn projection_matrix(&self) -> DMat4 {
890 self.matrices.projection
891 }
892
893 #[must_use]
894 pub(crate) fn inverse_projection_matrix(&self) -> DMat4 {
895 self.matrices.inv_projection
896 }
897
898 #[must_use]
901 pub(crate) fn globe_view_projection_matrix(&self) -> DMat4 {
902 self.matrices.globe_view_projection
903 }
904
905 #[must_use]
906 pub(crate) fn inverse_globe_view_projection_matrix(&self) -> DMat4 {
907 self.matrices.inv_globe_view_projection
908 }
909
910 #[must_use]
913 pub(crate) fn globe_clipping_plane(&self) -> DVec4 {
914 self.matrices.globe_clipping_plane
915 }
916
917 #[must_use]
919 pub fn globe_camera_position(&self) -> DVec3 {
920 self.matrices.globe_camera_position
921 }
922
923 fn center_coordinate(&self) -> DVec3 {
926 let world_size = Projection::world_size(self.params.scale);
927 DVec3::new(
928 (0.5 * world_size - self.params.x) / TILE_SIZE_D,
929 (0.5 * world_size - self.params.y) / TILE_SIZE_D,
930 0.0,
931 )
932 }
933
934 fn coordinate_point_matrix(&self, proj_matrix: &DMat4) -> DMat4 {
936 let size = self.params.size;
937 let pixel_matrix =
938 DMat4::from_scale(DVec3::new(f64::from(size.width) / 2.0, -f64::from(size.height) / 2.0, 1.0))
939 * DMat4::from_translation(DVec3::new(1.0, -1.0, 0.0));
940 pixel_matrix * *proj_matrix * DMat4::from_scale(DVec3::new(TILE_SIZE_D, TILE_SIZE_D, 1.0))
941 }
942
943 #[must_use]
947 pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
948 self.lat_lng_to_screen_coordinate_at(lat_lng, 0.0)
949 }
950
951 #[must_use]
955 pub(crate) fn lat_lng_to_screen_coordinate_at(&self, lat_lng: &LatLng, height: f64) -> ScreenCoordinate {
956 self.clip_point_at(lat_lng, height).0
957 }
958
959 #[must_use]
962 #[cfg(test)]
963 pub(crate) fn lat_lng_to_screen_coordinate_with_clip(&self, lat_lng: &LatLng) -> (ScreenCoordinate, DVec4) {
964 self.clip_point_at(lat_lng, 0.0)
965 }
966
967 fn clip_point_at(&self, lat_lng: &LatLng, height: f64) -> (ScreenCoordinate, DVec4) {
972 if self.params.size.is_empty() {
973 return (ScreenCoordinate::new(0.0, 0.0), DVec4::ZERO);
974 }
975
976 if self.is_globe() {
977 return VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(self, lat_lng, height);
978 }
979
980 let pt = self.params.projection.world().project(lat_lng, self.params.scale);
981 let p = self.matrices.coord * DVec4::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D, height, 1.0);
982 (ScreenCoordinate::new(p.x / p.w, f64::from(self.params.size.height) - p.y / p.w), p)
983 }
984
985 pub(crate) fn world_to_screen_coordinate(&self, world: &Point<f64>) -> ScreenCoordinate {
989 if self.params.size.is_empty() {
990 return ScreenCoordinate::new(0.0, 0.0);
991 }
992 let world_size = Projection::world_size(self.params.scale);
993 let p = self.matrices.coord
994 * DVec4::new(world.x * world_size / TILE_SIZE_D, world.y * world_size / TILE_SIZE_D, 0.0, 1.0);
995 ScreenCoordinate::new(p.x / p.w, f64::from(self.params.size.height) - p.y / p.w)
996 }
997
998 #[must_use]
1001 pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
1002 if self.params.size.is_empty() || !self.is_globe() {
1003 return false;
1004 }
1005 let surface = VerticalPerspectiveProjection::surface_vector(lat_lng);
1006 self.globe_clipping_plane().dot(surface.extend(1.0)) < 0.0
1007 }
1008
1009 #[must_use]
1011 pub(crate) fn screen_coordinate_to_tile_coordinate(&self, point: &ScreenCoordinate, at_zoom: u8) -> TileCoordinate {
1012 if self.params.size.is_empty() {
1013 return TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 };
1014 }
1015
1016 if self.is_globe() {
1017 return match VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(
1018 self,
1019 point,
1020 0.0,
1021 WrapMode::Unwrapped,
1022 ) {
1023 Some(lat_lng) => TileCoordinate::from_lat_lng(f64::from(at_zoom), &lat_lng),
1024 None => TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 },
1025 };
1026 }
1027
1028 self.mercator_screen_coordinate_to_tile_coordinate(point, at_zoom, 0.0)
1029 }
1030
1031 fn mercator_screen_coordinate_to_tile_coordinate(
1035 &self,
1036 point: &ScreenCoordinate,
1037 at_zoom: u8,
1038 height: f64,
1039 ) -> TileCoordinate {
1040 let flipped_y = f64::from(self.params.size.height) - point.y;
1041
1042 let inverted = self.matrices.inverted_from_center;
1045 let offset0 = inverted.project_point3(DVec3::new(point.x, flipped_y, 0.0));
1046 let offset1 = inverted.project_point3(DVec3::new(point.x, flipped_y, 1.0));
1047
1048 let z0 = offset0.z;
1049 let z1 = offset1.z;
1050 let t = if z0 <= z1 { 0.0 } else { -(z0 - height) / (z1 - z0) };
1052
1053 let offset = offset0 + (offset1 - offset0) * t;
1054 let center = self.center_coordinate();
1055 let factor = f64::from(1i32.wrapping_shl(u32::from(at_zoom)));
1056 let scale = self.params.scale;
1057 TileCoordinate {
1058 p: Point::new((center.x + offset.x) / scale * factor, (center.y + offset.y) / scale * factor),
1059 z: f64::from(at_zoom),
1060 }
1061 }
1062
1063 pub(crate) fn screen_coordinate_to_lat_lng(
1067 &self,
1068 point: &ScreenCoordinate,
1069 wrap_mode: WrapMode,
1070 ) -> Result<LatLng, Error> {
1071 self.screen_coordinate_to_lat_lng_at(point, 0.0, wrap_mode)
1072 }
1073
1074 pub fn screen_coordinate_to_lat_lng_at(
1082 &self,
1083 point: &ScreenCoordinate,
1084 height: f64,
1085 wrap_mode: WrapMode,
1086 ) -> Result<LatLng, Error> {
1087 if self.is_globe() && !self.params.size.is_empty() {
1089 if point.x.is_nan() || point.y.is_nan() {
1090 return Err(Error::invalid_argument("screen coordinate must not be NaN"));
1091 }
1092 if !point.x.is_finite() || !point.y.is_finite() {
1093 return Err(Error::invalid_argument("screen coordinate must not be infinite"));
1094 }
1095 return VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(self, point, height, wrap_mode)
1096 .ok_or_else(|| Error::invalid_argument("the camera shows no location"));
1097 }
1098 let coord = if self.params.size.is_empty() {
1099 self.screen_coordinate_to_tile_coordinate(point, 0)
1100 } else {
1101 self.mercator_screen_coordinate_to_tile_coordinate(point, 0, height)
1102 };
1103 self.params.projection.world().unproject(&coord.p, 1.0 / TILE_SIZE_D, wrap_mode)
1104 }
1105
1106 pub(crate) fn has_lat_lng_at(&self, point: &ScreenCoordinate, height: f64) -> bool {
1113 self.is_globe()
1114 || self.params.projection.world().has_lat_lng(&self.screen_coordinate_to_world_at(point, height))
1115 }
1116
1117 #[must_use]
1123 pub fn screen_coordinate_to_world_at(&self, point: &ScreenCoordinate, height: f64) -> Point<f64> {
1124 self.mercator_screen_coordinate_to_tile_coordinate(point, 0, height).p
1125 }
1126
1127 #[must_use]
1133 pub fn line_of_sight(&self, point: &ScreenCoordinate) -> Option<(DVec3, DVec3)> {
1134 if self.is_globe() || self.matrices.projection == DMat4::ZERO {
1135 return None;
1136 }
1137 let flipped_y = f64::from(self.params.size.height) - point.y;
1138 let inverted = self.matrices.inverted_from_center;
1141 let center = self.center_coordinate();
1142 let scale = self.params.scale;
1143 let world = |depth: f64| {
1144 let offset = inverted.project_point3(DVec3::new(point.x, flipped_y, depth));
1145 DVec3::new((center.x + offset.x) / scale, (center.y + offset.y) / scale, offset.z)
1146 };
1147 let (near, far) = (world(-1.0), world(1.0));
1148 (near.is_finite() && far.is_finite()).then_some((near, far))
1149 }
1150
1151 #[must_use]
1155 pub(crate) fn max_pitch_scale_factor(&self) -> f64 {
1156 if self.params.size.is_empty() {
1157 return 0.0;
1158 }
1159 let corner = self.mercator_screen_coordinate_to_tile_coordinate(
1162 &ScreenCoordinate::new(0.0, f64::from(self.params.size.height)),
1163 0,
1164 0.0,
1165 );
1166 let world = self.params.projection.world();
1168 let Ok(lat_lng) = world.unproject(&corner.p, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped) else {
1169 return 0.0;
1170 };
1171
1172 let scale = self.params.scale;
1173 let pt = if self.is_globe() {
1174 Point::new(corner.p.x * scale, corner.p.y * scale)
1175 } else {
1176 let pt = world.project(&lat_lng, scale);
1177 Point::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D)
1178 };
1179 let top_point = self.matrices.coord * DVec4::new(pt.x, pt.y, 0.0, 1.0);
1180 top_point.w / self.camera_to_center_distance()
1181 }
1182}