mln-rs-renderer 0.0.13

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
// The label-plane matrices and the CPU line-label projection. Symbols are
// not instanced (C++'s `MLN_USE_SYMBOL_INSTANCING` is off): each glyph has
// four dynamic vertices.

use geometry::Point;
use glam::Vec2;
use mln_map_types::{ProjectedTilePoint, TileProjector, TransformState};
use mln_text::glyph::WritingModeType;
use mln_tile_id::geometry_tile_data::GeometryCoordinate;
use mln_util::constants::ONE_EM;
use mln_util::mat4::{Mat4, matrix};
use mln_util::vectors::Vec4;

use crate::buckets::symbol_bucket::{
    PlacedSymbol, PlacedSymbolPools, SymbolBucket, SymbolDynamicLayoutVertex, SymbolSizeBinder, ZoomEvaluatedSize,
};
use crate::render_tile::RenderTile;

pub(crate) fn get_tile_skew_vectors(state: &TransformState) -> ([f64; 2], [f64; 2]) {
    let cos_roll = state.get_roll().cos();
    let sin_roll = state.get_roll().sin();
    let cos_pitch = state.get_pitch().cos();
    let cos_bearing = (-state.get_bearing()).cos();
    let sin_bearing = (-state.get_bearing()).sin();
    let mut vec_south = [
        -cos_bearing * cos_pitch * sin_roll - sin_bearing * cos_roll,
        -sin_bearing * cos_pitch * sin_roll + cos_bearing * cos_roll,
    ];
    let vec_south_len = vec_south[0].hypot(vec_south[1]);
    if vec_south_len < 1.0e-9 {
        vec_south = [0.0, 0.0];
    } else {
        vec_south[0] /= vec_south_len;
        vec_south[1] /= vec_south_len;
    }
    let mut vec_east = [
        cos_bearing * cos_pitch * cos_roll - sin_bearing * sin_roll,
        sin_bearing * cos_pitch * cos_roll + cos_bearing * sin_roll,
    ];
    let vec_east_len = vec_east[0].hypot(vec_east[1]);
    if vec_east_len < 1.0e-9 {
        vec_east = [0.0, 0.0];
    } else {
        vec_east[0] /= vec_east_len;
        vec_east[1] /= vec_east_len;
    }
    (vec_east, vec_south)
}

pub(crate) fn get_tile_skew_matrix(state: &TransformState) -> Mat4 {
    let (vec_east, vec_south) = get_tile_skew_vectors(state);
    let mut m: Mat4 = [0.0; 16];
    matrix::identity(&mut m);
    m[0] = vec_east[0];
    m[1] = vec_east[1];
    m[4] = vec_south[0];
    m[5] = vec_south[1];
    m
}

/// A matrix for converting to the label coordinate space, from tile units
/// when pitched with the map and from clip space otherwise; the shaders apply
/// the tile's projection themselves.
pub(crate) fn get_label_plane_matrix(
    pitch_with_map: bool,
    rotate_with_map: bool,
    state: &TransformState,
    pixels_to_tile_units: f32,
) -> Mat4 {
    let mut m: Mat4 = [0.0; 16];
    matrix::identity(&mut m);
    if pitch_with_map {
        let s = f64::from(1.0 / pixels_to_tile_units);
        let a = m;
        matrix::scale(&mut m, &a, s, s, 1.0);
        if !rotate_with_map {
            let skew = get_tile_skew_matrix(state);
            let mut inverted = skew;
            matrix::invert(&mut inverted, &skew);
            let a = m;
            matrix::multiply(&mut m, &a, &inverted);
        }
    } else {
        let size = state.get_size();
        let a = m;
        matrix::scale(&mut m, &a, f64::from(size.width) / 2.0, -(f64::from(size.height) / 2.0), 1.0);
        let a = m;
        matrix::translate(&mut m, &a, 1.0, -1.0, 0.0);
    }
    m
}

/// A matrix for converting from the label coordinate space back to tile
/// units when pitched with the map, and to GL coordinates otherwise.
pub(crate) fn get_gl_coord_matrix(
    pitch_with_map: bool,
    rotate_with_map: bool,
    state: &TransformState,
    pixels_to_tile_units: f32,
) -> Mat4 {
    let mut m: Mat4 = [0.0; 16];
    matrix::identity(&mut m);
    if pitch_with_map {
        let s = f64::from(pixels_to_tile_units);
        let a = m;
        matrix::scale(&mut m, &a, s, s, 1.0);
        if !rotate_with_map {
            let a = m;
            matrix::multiply(&mut m, &a, &get_tile_skew_matrix(state));
        }
    } else {
        let size = state.get_size();
        let a = m;
        matrix::scale(&mut m, &a, 1.0, -1.0, 1.0);
        let a = m;
        matrix::translate(&mut m, &a, -1.0, -1.0, 0.0);
        let a = m;
        matrix::scale(&mut m, &a, 2.0 / f64::from(size.width), 2.0 / f64::from(size.height), 1.0);
    }
    m
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct TileDistance {
    pub(crate) prev_tile_distance: f32,
    pub(crate) last_segment_viewport_distance: f32,
}

impl TileDistance {
    #[must_use]
    pub(crate) fn new(prev_tile_distance: f32, last_segment_viewport_distance: f32) -> Self {
        TileDistance { prev_tile_distance, last_segment_viewport_distance }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct PlacedGlyph {
    pub(crate) point: Vec2,
    pub(crate) angle: f32,
    pub(crate) tile_distance: Option<TileDistance>,
}

impl PlacedGlyph {
    #[must_use]
    pub(crate) fn new(point: Vec2, angle: f32, tile_distance: Option<TileDistance>) -> Self {
        PlacedGlyph { point, angle, tile_distance }
    }
}

pub(crate) type PointAndCameraDistance = (Vec2, f32);

fn to_vec2(p: Point<i16>) -> Vec2 {
    Vec2::new(f32::from(p.x), f32::from(p.y))
}

/// `project(point, matrix)`.
#[must_use]
pub(crate) fn project(point: Vec2, matrix: &Mat4) -> PointAndCameraDistance {
    let mut pos: Vec4 = [f64::from(point.x), f64::from(point.y), 0.0, 1.0];
    let a = pos;
    matrix::transform_mat4(&mut pos, &a, matrix);
    (Vec2::new((pos[0] / pos[3]) as f32, (pos[1] / pos[3]) as f32), pos[3] as f32)
}

#[must_use]
pub(crate) fn evaluate_size_for_feature(zoom_evaluated_size: &ZoomEvaluatedSize, placed_symbol: &PlacedSymbol) -> f32 {
    if zoom_evaluated_size.is_feature_constant {
        zoom_evaluated_size.size
    } else if zoom_evaluated_size.is_zoom_constant {
        placed_symbol.lower_size
    } else {
        placed_symbol.lower_size + zoom_evaluated_size.size_t * (placed_symbol.upper_size - placed_symbol.lower_size)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PlacementResult {
    Ok,
    NotEnoughRoom,
    NeedsFlipping,
    UseVertical,
}

/// Projects tile points to the label plane a symbol is laid out in, through
/// the tile's projection.
#[derive(Clone)]
pub(crate) struct LabelPlaneProjector<'a> {
    tile: TileProjector<'a>,
    pitch_with_map: bool,
    translation: Vec2,
    pitched_label_plane_matrix: Mat4,
    pitched_label_plane_matrix_inverse: Mat4,
    width: f32,
    height: f32,
    /// The symbol's `symbol-height-offset`, in meters.
    elevation: f64,
}

impl<'a> LabelPlaneProjector<'a> {
    /// A projector into the label plane. C++ defaults `translation` to
    /// (0, 0).
    #[must_use]
    pub(crate) fn new(
        tile: &TileProjector<'a>,
        pitch_with_map: bool,
        rotate_with_map: bool,
        pixels_to_tile_units: f32,
        translation: Vec2,
    ) -> Self {
        let size = tile.get_transform_state().get_size();
        let mut pitched_label_plane_matrix: Mat4 = [0.0; 16];
        let mut pitched_label_plane_matrix_inverse: Mat4 = [0.0; 16];
        // Only pitched labels lay out in the pitched plane; the others go
        // through the projection.
        if pitch_with_map {
            pitched_label_plane_matrix =
                get_label_plane_matrix(true, rotate_with_map, tile.get_transform_state(), pixels_to_tile_units);
            matrix::invert(&mut pitched_label_plane_matrix_inverse, &pitched_label_plane_matrix);
        } else {
            matrix::identity(&mut pitched_label_plane_matrix);
            matrix::identity(&mut pitched_label_plane_matrix_inverse);
        }
        LabelPlaneProjector {
            tile: *tile,
            pitch_with_map,
            translation,
            pitched_label_plane_matrix,
            pitched_label_plane_matrix_inverse,
            width: size.width as f32,
            height: size.height as f32,
            elevation: 0.0,
        }
    }

    /// This projector for a symbol `height_offset` meters above the ground.
    /// The pitched label plane is the same at any height; the shaders raise
    /// it.
    #[must_use]
    pub(crate) fn raised(&self, height_offset: f32) -> Self {
        LabelPlaneProjector { elevation: f64::from(height_offset), ..self.clone() }
    }

    /// Tile units to the label plane; distance and occlusion come from the
    /// projection.
    #[must_use]
    pub(crate) fn project(&self, tile_point: Vec2) -> ProjectedTilePoint {
        let translated = tile_point + self.translation;
        if self.pitch_with_map {
            let projected = project(translated, &self.pitched_label_plane_matrix);
            return ProjectedTilePoint {
                point: Point::new(f64::from(projected.0.x), f64::from(projected.0.y)),
                signed_distance_from_camera: f64::from(projected.1),
                occluded: false,
            };
        }
        let mut projected =
            self.tile.project(&Point::new(f64::from(translated.x), f64::from(translated.y)), self.elevation);
        projected.point = Point::new(
            (projected.point.x * 0.5 + 0.5) * f64::from(self.width),
            (-projected.point.y * 0.5 + 0.5) * f64::from(self.height),
        );
        projected
    }

    /// Label plane to clip space, for orientation checks.
    #[must_use]
    pub(crate) fn to_clip_space(&self, label_plane_point: Vec2) -> Vec2 {
        if self.pitch_with_map {
            let tile_point = project(label_plane_point, &self.pitched_label_plane_matrix_inverse).0;
            let projected =
                self.tile.project(&Point::new(f64::from(tile_point.x), f64::from(tile_point.y)), self.elevation);
            return Vec2::new(projected.point.x as f32, projected.point.y as f32);
        }
        Vec2::new((label_plane_point.x / self.width) * 2.0 - 1.0, 1.0 - (label_plane_point.y / self.height) * 2.0)
    }

    /// Tile units straight to clip space.
    #[must_use]
    pub(crate) fn to_clip_space_from_tile(&self, tile_point: Vec2) -> ProjectedTilePoint {
        self.tile.project(&Point::new(f64::from(tile_point.x), f64::from(tile_point.y)), self.elevation)
    }
}

/// The projections of one symbol's line vertices, so each vertex is
/// projected once however many glyphs walk it.
#[derive(Debug, Default)]
pub(crate) struct LineProjectionCache {
    points: Vec<Option<ProjectedTilePoint>>,
    occluded: bool,
}

impl LineProjectionCache {
    pub(crate) fn reset(&mut self, vertex_count: usize) {
        self.points.clear();
        self.points.resize(vertex_count, None);
        self.occluded = false;
    }

    pub(crate) fn get(
        &mut self,
        index: usize,
        line: &[GeometryCoordinate],
        label_plane: &LabelPlaneProjector<'_>,
    ) -> ProjectedTilePoint {
        if let Some(cached) = self.points[index] {
            return cached;
        }
        let projected = label_plane.project(to_vec2(line[index]));
        self.occluded |= projected.occluded;
        self.points[index] = Some(projected);
        projected
    }

    /// Whether any vertex projected so far is behind the globe's horizon.
    #[must_use]
    pub(crate) fn any_occluded(&self) -> bool {
        self.occluded
    }
}

/// Whether the anchor, in clip space, is within `clipping_buffer` of the
/// origin.
fn is_visible(anchor_pos: &Point<f64>, clipping_buffer: &[f64; 2]) -> bool {
    let x = anchor_pos.x;
    let y = anchor_pos.y;
    x >= -clipping_buffer[0] && x <= clipping_buffer[0] && y >= -clipping_buffer[1] && y <= clipping_buffer[1]
}

pub(crate) fn add_dynamic_attributes(
    anchor_point: Vec2,
    angle: f32,
    dynamic_attribute_data: &mut Vec<SymbolDynamicLayoutVertex>,
) {
    let dynamic_attributes = SymbolBucket::dynamic_layout_attributes(anchor_point, angle);
    dynamic_attribute_data.push(dynamic_attributes);
    dynamic_attribute_data.push(dynamic_attributes);
    dynamic_attribute_data.push(dynamic_attributes);
    dynamic_attribute_data.push(dynamic_attributes);
}

pub(crate) fn hide_glyphs(num_glyphs: usize, dynamic_vertex_array: &mut Vec<SymbolDynamicLayoutVertex>) {
    let count = 4;
    let offscreen_point = Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY);
    if dynamic_vertex_array.is_empty() {
        dynamic_vertex_array.reserve(count * num_glyphs);
    }
    for _ in 0..num_glyphs {
        add_dynamic_attributes(offscreen_point, 0.0, dynamic_vertex_array);
    }
}

/// Projects a truncated line segment; `project_point` takes a tile point to
/// the space the line is laid out in.
fn project_truncated_line_segment(
    previous_tile_point: Vec2,
    current_tile_point: Vec2,
    previous_projected_point: Vec2,
    minimum_length: f32,
    project_point: impl Fn(Vec2) -> Vec2,
) -> Vec2 {
    // We are assuming "previousTilePoint" won't project to a point within one
    // unit of the camera plane If it did, that would mean our label extended
    // all the way out from within the viewport to a (very distant) point near
    // the plane of the camera. We wouldn't be able to render the label anyway
    // once it crossed the plane of the camera.
    let projected_unit_vertex =
        project_point(previous_tile_point + (previous_tile_point - current_tile_point).normalize_or_zero());
    let projected_unit_segment = previous_projected_point - projected_unit_vertex;

    previous_projected_point + projected_unit_segment * (minimum_length / projected_unit_segment.length())
}

#[expect(
    clippy::too_many_arguments,
    reason = "the glyph's offsets, the anchor in both spaces, the line and its distances, and the projection and its cache"
)]
fn place_glyph_along_line(
    offset_x: f32,
    line_offset_x: f32,
    line_offset_y: f32,
    flip: bool,
    projected_anchor_point: Vec2,
    tile_anchor_point: Vec2,
    anchor_segment: u16,
    line: &[GeometryCoordinate],
    tile_distances: &[f32],
    label_plane: &LabelPlaneProjector<'_>,
    projections: &mut LineProjectionCache,
    return_tile_distance: bool,
) -> Option<PlacedGlyph> {
    let combined_offset_x = if flip { offset_x - line_offset_x } else { offset_x + line_offset_x };

    let mut dir: i16 = if combined_offset_x > 0.0 { 1 } else { -1 };

    let mut angle: f32 = 0.0;
    if flip {
        // The label needs to be flipped to keep text upright.
        // Iterate in the reverse direction.
        dir *= -1;
        angle = std::f32::consts::PI;
    }

    if dir < 0 {
        angle += std::f32::consts::PI;
    }

    let mut current_index: i32 = if dir > 0 { i32::from(anchor_segment) } else { i32::from(anchor_segment) + 1 };

    let initial_index = current_index;
    let mut current = projected_anchor_point;
    let mut prev = projected_anchor_point;
    let mut distance_to_prev: f32 = 0.0;
    let mut current_segment_distance: f32 = 0.0;
    let abs_offset_x = combined_offset_x.abs();

    while distance_to_prev + current_segment_distance <= abs_offset_x {
        current_index += i32::from(dir);

        // offset does not fit on the projected line
        if current_index < 0 || current_index >= line.len() as i32 {
            return None;
        }

        prev = current;
        let projection = projections.get(current_index as usize, line, label_plane);
        if projection.signed_distance_from_camera > 0.0 {
            current = Vec2::new(projection.point.x as f32, projection.point.y as f32);
        } else {
            // The vertex is behind the plane of the camera, so we can't project it
            // Instead, we'll create a vertex along the line that's far enough to include the glyph
            let previous_tile_point = if distance_to_prev == 0.0 {
                tile_anchor_point
            } else {
                to_vec2(line[(current_index - i32::from(dir)) as usize])
            };
            let current_tile_point = to_vec2(line[current_index as usize]);
            current = project_truncated_line_segment(
                previous_tile_point,
                current_tile_point,
                prev,
                abs_offset_x - distance_to_prev + 1.0,
                |p| {
                    let projected = label_plane.project(p);
                    Vec2::new(projected.point.x as f32, projected.point.y as f32)
                },
            );
        }

        distance_to_prev += current_segment_distance;
        current_segment_distance = prev.distance(current);
    }

    // The point is on the current segment. Interpolate to find it.
    let segment_interpolation_t = (abs_offset_x - distance_to_prev) / current_segment_distance;
    let prev_to_current = current - prev;
    let mut p = prev_to_current * segment_interpolation_t + prev;

    // offset the point from the line to text-offset and icon-offset
    // (`util::mag` defaults to a double result: the float sqrt promoted.)
    let mag = f64::from(prev_to_current.length());
    p += prev_to_current.perp() * ((f64::from(line_offset_y * f32::from(dir)) / mag) as f32);

    let segment_angle = angle + (current.y - prev.y).atan2(current.x - prev.x);

    Some(PlacedGlyph::new(
        p,
        segment_angle,
        if return_tile_distance {
            Some(TileDistance::new(
                if (current_index - i32::from(dir)) == initial_index {
                    0.0
                } else {
                    tile_distances[(current_index - i32::from(dir)) as usize]
                },
                abs_offset_x - distance_to_prev,
            ))
        } else {
            None
        },
    ))
}

#[expect(
    clippy::too_many_arguments,
    reason = "the label's offsets, the anchor in both spaces, the symbol, and the projection and its cache"
)]
pub(crate) fn place_first_and_last_glyph(
    font_scale: f32,
    line_offset_x: f32,
    line_offset_y: f32,
    flip: bool,
    anchor_point: Vec2,
    tile_anchor_point: Vec2,
    symbol: &PlacedSymbol,
    pools: &PlacedSymbolPools,
    label_plane: &LabelPlaneProjector<'_>,
    projections: &mut LineProjectionCache,
    return_tile_distance: bool,
) -> Option<(PlacedGlyph, PlacedGlyph)> {
    let glyph_offsets = pools.glyph_offsets(symbol);
    let (Some(&first_glyph_offset), Some(&last_glyph_offset)) = (glyph_offsets.first(), glyph_offsets.last()) else {
        debug_assert!(false);
        return None;
    };

    let first_placed_glyph = place_glyph_along_line(
        font_scale * first_glyph_offset,
        line_offset_x,
        line_offset_y,
        flip,
        anchor_point,
        tile_anchor_point,
        symbol.segment as u16,
        pools.line(symbol),
        pools.tile_distances(symbol),
        label_plane,
        projections,
        return_tile_distance,
    )?;

    let last_placed_glyph = place_glyph_along_line(
        font_scale * last_glyph_offset,
        line_offset_x,
        line_offset_y,
        flip,
        anchor_point,
        tile_anchor_point,
        symbol.segment as u16,
        pools.line(symbol),
        pools.tile_distances(symbol),
        label_plane,
        projections,
        return_tile_distance,
    )?;
    // A line label with any vertex behind the planet is hidden whole.
    if projections.any_occluded() {
        return None;
    }

    Some((first_placed_glyph, last_placed_glyph))
}

fn requires_orientation_change(
    writing_modes: WritingModeType,
    first_point: Vec2,
    last_point: Vec2,
    aspect_ratio: f32,
) -> Option<PlacementResult> {
    if writing_modes == (WritingModeType::Horizontal | WritingModeType::Vertical) {
        // On top of choosing whether to flip, choose whether to render this
        // version of the glyphs or the alternate vertical glyphs. We can't just
        // filter out vertical glyphs in the horizontal range because the
        // horizontal and vertical versions can have slightly different
        // projections which could lead to angles where both or neither showed.
        let rise = (last_point.y - first_point.y).abs();
        let run = (last_point.x - first_point.x).abs() * aspect_ratio;
        if rise > run {
            return Some(PlacementResult::UseVertical);
        }
    }

    if if writing_modes == WritingModeType::Vertical {
        first_point.y < last_point.y
    } else {
        first_point.x > last_point.x
    } {
        // Includes "horizontalOnly" case for labels without vertical glyphs
        return Some(PlacementResult::NeedsFlipping);
    }
    None
}

#[expect(
    clippy::too_many_arguments,
    reason = "the symbol, its size and orientation flags, the projection and its cache, and the vertices it writes"
)]
fn place_glyphs_along_line(
    symbol: &PlacedSymbol,
    pools: &PlacedSymbolPools,
    font_size: f32,
    flip: bool,
    keep_upright: bool,
    rotate_to_line: bool,
    label_plane: &LabelPlaneProjector<'_>,
    projections: &mut LineProjectionCache,
    dynamic_vertex_array: &mut Vec<SymbolDynamicLayoutVertex>,
    projected_anchor_point: Vec2,
    aspect_ratio: f32,
) -> PlacementResult {
    let font_scale = font_size / ONE_EM;
    let line_offset_x = symbol.line_offset[0] * font_scale;
    let line_offset_y = symbol.line_offset[1] * font_scale;
    let line = pools.line(symbol);
    let tile_distances = pools.tile_distances(symbol);
    let glyph_offsets = pools.glyph_offsets(symbol);

    let mut placed_glyphs: Vec<PlacedGlyph> = Vec::new();
    if glyph_offsets.len() > 1 {
        let Some(first_and_last_glyph) = place_first_and_last_glyph(
            font_scale,
            line_offset_x,
            line_offset_y,
            flip,
            projected_anchor_point,
            symbol.anchor_point,
            symbol,
            pools,
            label_plane,
            projections,
            false,
        ) else {
            return PlacementResult::NotEnoughRoom;
        };

        let first_point = label_plane.to_clip_space(first_and_last_glyph.0.point);
        let last_point = label_plane.to_clip_space(first_and_last_glyph.1.point);

        if keep_upright
            && !flip
            && let Some(orientation_change) =
                requires_orientation_change(symbol.writing_modes, first_point, last_point, aspect_ratio)
        {
            return orientation_change;
        }

        placed_glyphs.reserve(glyph_offsets.len());
        placed_glyphs.push(first_and_last_glyph.0);
        for &glyph_offset_x in &glyph_offsets[1..glyph_offsets.len() - 1] {
            // Since first and last glyph fit on the line, we're sure that the
            // rest of the glyphs can be placed
            let placed_glyph = place_glyph_along_line(
                glyph_offset_x * font_scale,
                line_offset_x,
                line_offset_y,
                flip,
                projected_anchor_point,
                symbol.anchor_point,
                symbol.segment as u16,
                line,
                tile_distances,
                label_plane,
                projections,
                false,
            );
            match placed_glyph {
                Some(placed_glyph) => placed_glyphs.push(placed_glyph),
                None => {
                    placed_glyphs.push(PlacedGlyph::new(Vec2::new(f32::NEG_INFINITY, f32::NEG_INFINITY), 0.0, None));
                }
            }
        }
        placed_glyphs.push(first_and_last_glyph.1);
    } else if glyph_offsets.len() == 1 {
        // Only a single glyph to place
        // So, determine whether to flip based on projected angle of the line segment it's on
        if keep_upright && !flip {
            let to_clip = |p: Vec2| {
                let projected = label_plane.to_clip_space_from_tile(p);
                Vec2::new(projected.point.x as f32, projected.point.y as f32)
            };
            let a = to_clip(symbol.anchor_point);
            let tile_segment_end = to_vec2(line[symbol.segment + 1]);
            let projected_vertex = label_plane.to_clip_space_from_tile(tile_segment_end);
            // We know the anchor will be in the viewport, but the end of the
            // line segment may be behind the plane of the camera, in which case
            // we can use a point at any arbitrary (closer) point on the
            // segment.
            let b = if projected_vertex.signed_distance_from_camera > 0.0 {
                Vec2::new(projected_vertex.point.x as f32, projected_vertex.point.y as f32)
            } else {
                project_truncated_line_segment(symbol.anchor_point, tile_segment_end, a, 1.0, to_clip)
            };

            if let Some(orientation_change) = requires_orientation_change(symbol.writing_modes, a, b, aspect_ratio) {
                return orientation_change;
            }
        }
        let glyph_offset_x = glyph_offsets[0];
        let single_glyph = place_glyph_along_line(
            font_scale * glyph_offset_x,
            line_offset_x,
            line_offset_y,
            flip,
            projected_anchor_point,
            symbol.anchor_point,
            symbol.segment as u16,
            line,
            tile_distances,
            label_plane,
            projections,
            false,
        );
        let Some(single_glyph) = single_glyph.filter(|_| !projections.any_occluded()) else {
            return PlacementResult::NotEnoughRoom;
        };

        placed_glyphs.push(single_glyph);
    }

    // The number of placedGlyphs must equal the number of glyphOffsets, which
    // must correspond to the number of glyph vertices There may be 0 glyphs
    // here, if a label consists entirely of glyphs that have 0x0 dimensions
    if dynamic_vertex_array.is_empty() {
        dynamic_vertex_array.reserve(4 * placed_glyphs.len());
    }
    for placed_glyph in &placed_glyphs {
        let angle = if rotate_to_line { placed_glyph.angle } else { 0.0 };
        add_dynamic_attributes(placed_glyph.point, angle, dynamic_vertex_array);
    }

    PlacementResult::Ok
}

/// Places each glyph of the line labels along its line, for the current
/// camera. Glyphs that rotate with the map turn to follow the line; others
/// (`text-rotation-alignment: viewport-glyph`) stay level with the viewport.
#[expect(
    clippy::too_many_arguments,
    reason = "the tile's symbols, projector and size binder, the alignment flags and the vertices it writes"
)]
pub(crate) fn reproject_line_labels(
    dynamic_vertex_array: &mut Vec<SymbolDynamicLayoutVertex>,
    placed_symbols: &[PlacedSymbol],
    pools: &PlacedSymbolPools,
    tile_projector: &TileProjector<'_>,
    pitch_with_map: bool,
    rotate_with_map: bool,
    keep_upright: bool,
    tile: &RenderTile,
    size_binder: &SymbolSizeBinder,
    state: &TransformState,
    translation: Vec2,
) {
    let partially_evaluated_size = size_binder.evaluate_for_zoom(state.get_zoom() as f32);

    let size = state.get_size();
    let clipping_buffer: [f64; 2] =
        [256.0 / f64::from(size.width) * 2.0 + 1.0, 256.0 / f64::from(size.height) * 2.0 + 1.0];

    let pixels_to_tile_units = tile.id.pixels_to_tile_units(1.0, state.get_zoom() as f32);

    let label_plane =
        LabelPlaneProjector::new(tile_projector, pitch_with_map, rotate_with_map, pixels_to_tile_units, translation);

    dynamic_vertex_array.clear();

    let mut use_vertical = false;
    let mut projections = LineProjectionCache::default();

    for placed_symbol in placed_symbols {
        // Don't do calculations for vertical glyphs unless the previous symbol
        // was horizontal and we determined that vertical glyphs were necessary.
        // Also don't do calculations for symbols that are collided and fully
        // faded out
        if placed_symbol.hidden || (placed_symbol.writing_modes == WritingModeType::Vertical && !use_vertical) {
            hide_glyphs(placed_symbol.glyph_offsets.len(), dynamic_vertex_array);
            continue;
        }
        // Awkward... but we're counting on the paired "vertical" symbol coming
        // immediately after its horizontal counterpart
        use_vertical = false;

        let tile_anchor = Point::new(f64::from(placed_symbol.anchor_point.x), f64::from(placed_symbol.anchor_point.y));
        let anchor_pos = tile_projector.project(&tile_anchor, 0.0);

        // Don't bother calculating the correct point for invisible labels.
        if anchor_pos.occluded || !is_visible(&anchor_pos.point, &clipping_buffer) {
            hide_glyphs(placed_symbol.glyph_offsets.len(), dynamic_vertex_array);
            continue;
        }

        let camera_to_anchor_distance = anchor_pos.signed_distance_from_camera as f32;
        let perspective_ratio = 0.5 + 0.5 * (camera_to_anchor_distance / state.get_camera_to_center_distance());

        let font_size = evaluate_size_for_feature(&partially_evaluated_size, placed_symbol);
        let pitch_scaled_font_size = if pitch_with_map {
            font_size * perspective_ratio * tile_projector.pitched_text_correction(&tile_anchor) as f32
        } else {
            font_size / perspective_ratio
        };

        let projected_anchor = label_plane.project(placed_symbol.anchor_point).point;
        let anchor_point = Vec2::new(projected_anchor.x as f32, projected_anchor.y as f32);

        projections.reset(placed_symbol.line.len());
        let place_unflipped = place_glyphs_along_line(
            placed_symbol,
            pools,
            pitch_scaled_font_size,
            false, /*unflipped*/
            keep_upright,
            rotate_with_map,
            &label_plane,
            &mut projections,
            dynamic_vertex_array,
            anchor_point,
            size.aspect_ratio(),
        );

        use_vertical = place_unflipped == PlacementResult::UseVertical;

        if place_unflipped == PlacementResult::NotEnoughRoom
            || use_vertical
            || (place_unflipped == PlacementResult::NeedsFlipping
                && place_glyphs_along_line(
                    placed_symbol,
                    pools,
                    pitch_scaled_font_size,
                    true, /*flipped*/
                    keep_upright,
                    rotate_with_map,
                    &label_plane,
                    &mut projections,
                    dynamic_vertex_array,
                    anchor_point,
                    size.aspect_ratio(),
                ) == PlacementResult::NotEnoughRoom)
        {
            hide_glyphs(placed_symbol.glyph_offsets.len(), dynamic_vertex_array);
        }
    }
}