Skip to main content

mln_map/transform/
transition.rs

1//! Camera commands as transitions that own the camera fields they set,
2//! and the reports of their ends.
3
4use std::time::Duration;
5
6use glam::DVec3;
7use mln_map_types::{
8    AnimationOptions, CameraOptions, CameraVelocity, Elevation, TransformState, TransitionEnd, TransitionOutcome,
9    VerticalPerspectiveProjection,
10};
11use mln_util::constants::{DEFAULT_TRANSITION_EASE, TILE_SIZE_D};
12use mln_util::geo::{LatLng, ScreenCoordinate, WrapMode};
13use mln_util::projection::Projection;
14use mln_util::time::Instant;
15
16use super::anchor::sees_plane;
17use super::momentum::MomentumState;
18use super::{
19    ALTITUDE, BEARING, CENTER, CameraCommandId, CommandEnd, FOV, PADDING, PITCH, ROLL, Transform, TransformEvent, ZOOM,
20    camera_fields, max_pitch_for_padding,
21};
22use crate::log_target;
23use crate::map_event::{CameraChange, CameraChangeMode, CameraChangeSource};
24
25/// A command's camera at an eased progress: every field set, except a
26/// center or padding the frame could not compute (logged), which keeps the
27/// current one.
28pub(super) type FrameFn = Box<dyn Fn(&TransformState, f64) -> CameraOptions>;
29
30/// How far along its path a command's center is at an eased progress below
31/// 1, as a share of the path, where that isn't the eased progress itself.
32pub(super) type AlongFn = Box<dyn Fn(f64) -> f64>;
33
34/// One camera command.
35pub(super) struct Transition {
36    /// Remaining property ownership; replacement removes fields from this
37    /// mask.
38    pub(super) fields: u16,
39    /// Replacing any coupled field relinquishes all coupled fields together.
40    coupled_fields: u16,
41    /// Properties classified as moving at command start; intersected with
42    /// `fields` when reporting movement, so replaced properties no longer
43    /// contribute. A momentum adds the fields its settling moves.
44    pub(super) moving_fields: u16,
45    start: Instant,
46    /// A momentum extends it for its settling.
47    pub(super) duration: Duration,
48    animation: AnimationOptions,
49    frame: FrameFn,
50    /// How far along its path the center is ([`Transition::share`]), or
51    /// `None` for the eased progress.
52    along: Option<AlongFn>,
53    anchor: Option<ScreenCoordinate>,
54    anchor_lat_lng: LatLng,
55    /// The height in meters of the plane, or on the globe the sphere, the
56    /// anchor holds its location on ([`Transform::anchor_height`]).
57    anchor_height: f64,
58    /// Set for a momentum, which moves the camera relative to where it
59    /// stands instead of through `frame`.
60    pub(super) momentum: Option<MomentumState>,
61    /// Why the command ends, once something other than time ends it:
62    /// `Cancelled`, or `Replaced` when later commands took all its fields.
63    /// Set through [`Transition::ended_by`], where cancellation wins.
64    stopped: Option<TransitionOutcome>,
65    /// What started the command, which the change that ends it reports.
66    source: CameraChangeSource,
67    /// The command whose end this transition's end reports, if any.
68    pub(super) command: Option<CameraCommandId>,
69    /// For a gesture's momentum, the gesture's serial: its end ends the
70    /// gesture, unless another one started since.
71    pub(super) gesture: Option<u64>,
72}
73
74impl Transition {
75    /// A command without coupled fields, anchor, momentum, end to report or
76    /// gesture.
77    pub(super) fn new(
78        fields: u16,
79        moving_fields: u16,
80        start: Instant,
81        duration: Duration,
82        animation: &AnimationOptions,
83        frame: FrameFn,
84        source: CameraChangeSource,
85    ) -> Transition {
86        Transition {
87            fields,
88            coupled_fields: 0,
89            moving_fields,
90            start,
91            duration,
92            animation: *animation,
93            frame,
94            along: None,
95            anchor: None,
96            anchor_lat_lng: LatLng::default(),
97            anchor_height: 0.0,
98            momentum: None,
99            stopped: None,
100            source,
101            command: None,
102            gesture: None,
103        }
104    }
105
106    /// Whether a camera command started the transition, not a gesture's
107    /// own move or its momentum.
108    pub(super) fn is_command(&self) -> bool {
109        self.source == CameraChangeSource::Command && self.momentum.is_none()
110    }
111
112    /// Where the command leaves the center, as the frame whose camera is
113    /// `frame` sees it: the center it heads for, or for an anchored command,
114    /// the center that stands on `ground` in its camera at the end with the
115    /// anchor's location under the anchor ([`anchored_end`]).
116    pub(super) fn end_center(&self, state: &TransformState, frame: &CameraOptions, ground: &dyn Elevation) -> LatLng {
117        let end = (self.frame)(state, 1.0);
118        match self.anchor {
119            Some(anchor) => {
120                let mut camera = *frame;
121                compose(&mut camera, &end, self.fields);
122                anchored_end(state, &camera, &anchor, &self.anchor_lat_lng, self.anchor_height, ground)
123            }
124            None => end.center.or(frame.center).unwrap_or_else(|| state.view().center(WrapMode::Unwrapped)).wrapped(),
125        }
126    }
127
128    fn mode(&self) -> CameraChangeMode {
129        if self.duration == Duration::ZERO { CameraChangeMode::Immediate } else { CameraChangeMode::Animated }
130    }
131
132    /// Records why the command stops: `Cancelled` or `Replaced`. A
133    /// cancellation wins over a replacement, as the C API reports
134    /// it.
135    fn ended_by(&mut self, outcome: TransitionOutcome) {
136        if self.stopped != Some(TransitionOutcome::Cancelled) {
137            self.stopped = Some(outcome);
138        }
139    }
140
141    /// How the command ended, with a momentum's leftover speed: why it
142    /// stopped, else `Replaced` if later commands took every momentum part,
143    /// else `Completed`.
144    fn end(&self) -> TransitionEnd {
145        let (velocity, momentum_replaced) =
146            self.momentum.as_ref().map_or((CameraVelocity::default(), false), MomentumState::end);
147        let outcome = self.stopped.unwrap_or(if momentum_replaced {
148            TransitionOutcome::Replaced
149        } else {
150            TransitionOutcome::Completed
151        });
152        TransitionEnd { outcome, velocity, generation: 0 }
153    }
154
155    /// The elapsed share of the duration at `now`, in [0, 1]; 1 for an
156    /// immediate command, or without a clock.
157    fn progress(&self, now: Option<Instant>) -> f64 {
158        let duration = self.duration;
159        match now {
160            Some(now) if !duration.is_zero() => {
161                mln_math::clamp_f64(now.saturating_duration_since(self.start).div_duration_f64(duration), 0.0, 1.0)
162            }
163            _ => 1.0,
164        }
165    }
166
167    /// The progress at `now` through the command's easing, which its camera
168    /// is at: 1 at its end.
169    fn eased_progress(&self, now: Option<Instant>) -> f64 {
170        let t = self.progress(now);
171        let ease = self.animation.easing.unwrap_or(DEFAULT_TRANSITION_EASE);
172        if t == 1.0 { 1.0 } else { ease.solve(t, 0.001) }
173    }
174
175    /// How far along its path the command's center is at `now`, as a share
176    /// of the path: 0 before it starts, 1 from its end on.
177    pub(super) fn share(&self, now: Option<Instant>) -> f64 {
178        let k = self.eased_progress(now);
179        match &self.along {
180            Some(along) if k < 1.0 => along(k),
181            _ => k,
182        }
183    }
184
185    /// The time left of the command at `now`: none without a clock.
186    pub(super) fn remaining(&self, now: Option<Instant>) -> Duration {
187        self.duration.saturating_sub(self.elapsed(now))
188    }
189
190    /// The time since the command started, at `now`; zero before it, and
191    /// `Duration::MAX` without a clock, which ends every command.
192    pub(super) fn elapsed(&self, now: Option<Instant>) -> Duration {
193        now.map_or(Duration::MAX, |now| now.saturating_duration_since(self.start))
194    }
195
196    /// Whether the command's time has run out at `now`.
197    fn has_run_out(&self, now: Option<Instant>) -> bool {
198        now.is_none_or(|now| now >= self.start && self.elapsed(Some(now)) >= self.duration)
199    }
200}
201
202/// Takes onto `camera` the fields of a command's camera `value` that
203/// `fields` names, but a center or padding it lacks (see [`FrameFn`]).
204fn compose(camera: &mut CameraOptions, value: &CameraOptions, fields: u16) {
205    if fields & CENTER != 0 && value.center.is_some() {
206        camera.center = value.center;
207    }
208    if fields & ZOOM != 0 {
209        camera.zoom = value.zoom;
210    }
211    if fields & BEARING != 0 {
212        camera.bearing = value.bearing;
213    }
214    if fields & PITCH != 0 {
215        camera.pitch = value.pitch;
216    }
217    if fields & PADDING != 0 && value.padding.is_some() {
218        camera.padding = value.padding;
219    }
220    if fields & ALTITUDE != 0 {
221        camera.center_altitude = value.center_altitude;
222    }
223    if fields & ROLL != 0 {
224        camera.roll = value.roll;
225    }
226    if fields & FOV != 0 {
227        camera.fov = value.fov;
228    }
229}
230
231/// Puts `camera`, composed over `current`, the camera of `state`, on
232/// `state` within its limits. In particular, padding and field of view
233/// determine the pitch limit, and center and zoom jointly determine the
234/// geographic bounds, which constrain `camera`.
235///
236/// The angles no command changed stay as they are, so that converting
237/// them to degrees and back doesn't move them.
238fn place(state: &mut TransformState, current: &CameraOptions, camera: &mut CameraOptions) {
239    let padding = camera.padding.unwrap_or_default();
240    state.set_padding(&padding);
241    if let Some(fov) = camera.fov.filter(|_| camera.fov != current.fov) {
242        state.set_fov(mln_math::deg2rad(fov));
243    }
244    if let Some(bearing) = camera.bearing.filter(|_| camera.bearing != current.bearing) {
245        state.set_angle(mln_math::deg2rad(-bearing));
246    }
247    if let Some(roll) = camera.roll.filter(|_| camera.roll != current.roll) {
248        state.set_roll(mln_math::deg2rad(roll));
249    }
250    let pitch = match camera.pitch.filter(|_| camera.pitch != current.pitch) {
251        Some(pitch) => mln_math::deg2rad(pitch),
252        None => state.view().pitch(),
253    };
254    state.set_pitch(f64::min(max_pitch_for_padding(state, &padding), pitch));
255    // Before the center, so that an anchor holds at the new altitude.
256    state.set_center_altitude(camera.center_altitude.unwrap_or_default());
257    let mut zoom = camera.zoom.unwrap_or_default();
258    state.constrain_camera_and_zoom_to_bounds(camera, &mut zoom);
259    state.set_lat_lng_zoom(&camera.center.unwrap_or_default(), zoom);
260}
261
262/// Where an anchored command leaves the center over `ground`, in `camera`,
263/// its camera at the end, with `location`, `height` meters up, under
264/// `anchor` (y up).
265///
266/// Moving that camera along the anchor's line of sight keeps `location`
267/// under the anchor, so its center stands on a line along that line of
268/// sight at whatever altitude it has: the end is where that line meets the
269/// ground, or where it meets none, the center at the altitude it has now. A
270/// camera that can't hold the anchor turns around its center, as the frames
271/// do (see `Transform::hold_anchor`); so does the globe, which has no
272/// straight line of sight to slide along.
273fn anchored_end(
274    state: &TransformState,
275    camera: &CameraOptions,
276    anchor: &ScreenCoordinate,
277    location: &LatLng,
278    height: f64,
279    ground: &dyn Elevation,
280) -> LatLng {
281    let mut state = state.clone();
282    let current = state.camera_options(None);
283    let altitude = current.center_altitude;
284    place(&mut state, &current, &mut CameraOptions { center_altitude: altitude, ..*camera });
285    if state.view().is_globe() || !sees_plane(state.view(), anchor, height) {
286        return state.view().center(WrapMode::Wrapped);
287    }
288    // The anchor had a location at the start, so it has one here.
289    let _ = state.move_lat_lng_at(location, anchor, height);
290    let view = state.view();
291    let center = view.center(WrapMode::Unwrapped);
292    let on_ground = view.line_of_sight(anchor).and_then(|(near, far)| {
293        let world = Projection::project(&center, 1.0 / TILE_SIZE_D);
294        let at = DVec3::new(world.x, world.y, view.center_altitude());
295        view.ground_along(at - (far - near), at + (far - near), ground)
296    });
297    on_ground.map_or(center, |hit| hit.location(WrapMode::Unwrapped)).wrapped()
298}
299
300/// A command made of several transitions, which ends once with the
301/// outcome that covers them all: cancelled if any was, otherwise closed if
302/// any was, otherwise replaced if any was.
303pub(super) struct JointEnd {
304    command: CameraCommandId,
305    remaining: u32,
306    outcome: TransitionOutcome,
307}
308
309impl Transform {
310    /// Starts one camera command. `camera` is the command as given: the
311    /// fields it sets are the fields it takes over from the running
312    /// commands. A flight couples center and zoom; an anchored command
313    /// couples center with its fields. Replacing any field of a coupled
314    /// group stops the whole group, and a command left with no fields
315    /// finishes. Over terrain that clamps the center, the ground decides the
316    /// altitude, and a command given one starts as it would without it.
317    /// `along` tells how far along its path the command's center is, if
318    /// that isn't its eased progress.
319    pub(super) fn start_transition(
320        &mut self,
321        camera: &CameraOptions,
322        animation: &AnimationOptions,
323        frame: FrameFn,
324        along: Option<AlongFn>,
325        duration: Duration,
326        flight: bool,
327    ) {
328        let mut fields = camera_fields(camera);
329        if self.clamped() {
330            fields &= !ALTITUDE;
331        }
332        let mut coupled_fields = if flight { CENTER | ZOOM } else { 0 };
333        fields |= coupled_fields;
334
335        // An anchor controls center together with the properties it
336        // transforms. An explicit center takes precedence over an anchor.
337        let mut anchor = if camera.center.is_some() { None } else { camera.anchor };
338        let mut anchor_lat_lng = LatLng::default();
339        let mut anchor_height = 0.0;
340        if let Some(a) = anchor.as_mut() {
341            anchor_height = self.anchor_height(a, a);
342            a.y = f64::from(self.state.view().size().height) - a.y;
343            // An anchor that has no LatLng (NaN or infinite) is logged and
344            // ignored.
345            match self.state.view().screen_coordinate_to_lat_lng_at(a, anchor_height, WrapMode::Unwrapped) {
346                Ok(lat_lng) => {
347                    anchor_lat_lng = lat_lng;
348                    fields |= CENTER;
349                    coupled_fields = fields;
350                }
351                Err(e) => {
352                    log::error!(target: log_target::GENERAL, "{}", e.message);
353                    anchor = None;
354                }
355            }
356        }
357
358        let target = frame(&self.state, 1.0);
359        let panning = flight || anchor.is_some() || camera.center != Some(self.view().center(WrapMode::Unwrapped));
360        let scaling = flight || target.zoom != Some(self.view().zoom());
361        let rotating = target.bearing != Some(-mln_math::rad2deg(self.view().angle()));
362        let moving_fields = (if panning { CENTER } else { 0 })
363            | (if scaling { ZOOM } else { 0 })
364            | (if rotating { BEARING } else { 0 });
365
366        let start = self.now();
367        let duration = if fields != 0 { duration } else { Duration::ZERO };
368        let transition = Transition {
369            coupled_fields,
370            along,
371            anchor,
372            anchor_lat_lng,
373            anchor_height,
374            command: self.reporting(),
375            ..Transition::new(fields, moving_fields, start, duration, animation, frame, self.source)
376        };
377        let mode = transition.mode();
378
379        let finished = self.release_fields(fields);
380        self.transitions.push(transition);
381        self.update_movement_flags();
382        self.finish_transitions(finished);
383
384        self.emit(TransformEvent::CameraWillChange(CameraChange { mode, source: self.source }));
385
386        if duration == Duration::ZERO {
387            let index = self.transitions.len() - 1;
388            self.apply_transitions(Some(index), Some(start));
389            let transition = self.transitions.remove(index);
390            self.update_movement_flags();
391            self.finish_transitions(vec![transition]);
392        }
393    }
394
395    /// Composes the current camera with the camera of each running command
396    /// that isn't a momentum, or only of the one at `only`, at `now`, for
397    /// the fields it still owns, then applies the result.
398    fn apply_transitions(&mut self, only: Option<usize>, now: Option<Instant>) {
399        // The center is unwrapped, or wrapped on the globe without bounds
400        // (TransformState::camera_options).
401        let current = self.state.camera_options(None);
402        let mut camera = current;
403
404        let active = match only {
405            Some(index) => &self.transitions[index..=index],
406            None => &self.transitions[..],
407        };
408        for transition in active.iter().filter(|transition| transition.momentum.is_none()) {
409            let k = transition.eased_progress(now);
410            compose(&mut camera, &(transition.frame)(&self.state, k), transition.fields);
411        }
412        let lands = self.ease_altitude(&mut camera, now);
413
414        // An active anchor also applies to immediate changes of other
415        // properties.
416        let anchored = self.transitions.iter().enumerate().rev().find_map(|(index, transition)| {
417            let anchor = transition.anchor.filter(|_| transition.fields & CENTER != 0)?;
418            Some((anchor, transition.anchor_lat_lng, transition.anchor_height, index))
419        });
420
421        // On the globe the anchor is re-read every frame, on the sphere at
422        // its height, and the zoom around it is GL JS's blend of the exact
423        // solution and a damped heuristic; the exact solution alone jumps
424        // near the horizon. An anchor with no LatLng in a frame is logged,
425        // and the anchor's location at the start stands in.
426        let globe_zoom_around = match anchored {
427            Some((anchor, anchor_lat_lng, height, _)) if self.globe_on_screen() => {
428                let location = self
429                    .state
430                    .view()
431                    .screen_coordinate_to_lat_lng_at(&anchor, height, WrapMode::Unwrapped)
432                    .unwrap_or_else(|e| {
433                        log::error!(target: log_target::GENERAL, "{}", e.message);
434                        anchor_lat_lng
435                    });
436                Some((location, self.state.view().zoom()))
437            }
438            _ => None,
439        };
440
441        // The altitude is set before the anchor holds its location, so that it
442        // holds at the frame's altitude (see `place`).
443        place(&mut self.state, &current, &mut camera);
444        if let Some((anchor, anchor_lat_lng, height, index)) = anchored {
445            match globe_zoom_around {
446                Some((location, zoom_before)) if self.state.view().zoom() != zoom_before => {
447                    let zoom_delta = self.state.view().zoom() - zoom_before;
448                    let free_bearing = self.state.view().globe_free_bearing();
449                    VerticalPerspectiveProjection::zoom_around_point(
450                        &mut self.state,
451                        &anchor,
452                        &location,
453                        height,
454                        zoom_delta,
455                        free_bearing,
456                    );
457                }
458                _ => self.hold_anchor(&anchor_lat_lng, &anchor, height, &current, index),
459            }
460        }
461        if lands {
462            self.stand_on_ground();
463        }
464        // Last, so that the eye stays clear.
465        self.keep_clear_of_ground();
466    }
467
468    /// Moves the center so that `location`, `height` meters up, is at
469    /// `anchor` (y up) again, for the command at `index`. The anchor had a
470    /// `LatLng` at the start; a frame that has none logs it, as
471    /// `frame_edge_insets` does.
472    ///
473    /// On a Mercator view, a frame whose camera can't hold it there
474    /// ([`sees_plane`]), such as one whose pitch carries the anchor above the
475    /// horizon, moves around the view's center instead: the center stays
476    /// where it was, in `before`, and the command gives up its anchor and
477    /// the center.
478    fn hold_anchor(
479        &mut self,
480        location: &LatLng,
481        anchor: &ScreenCoordinate,
482        height: f64,
483        before: &CameraOptions,
484        index: usize,
485    ) {
486        if !self.view().is_globe() && !sees_plane(self.view(), anchor, height) {
487            let zoom = self.view().zoom();
488            self.state.set_lat_lng_zoom(&before.center.unwrap_or_default(), zoom);
489            let transition = &mut self.transitions[index];
490            transition.anchor = None;
491            transition.fields &= !CENTER;
492            return;
493        }
494        if let Err(e) = self.state.move_lat_lng_at(location, anchor, height) {
495            log::error!(target: log_target::GENERAL, "{}", e.message);
496        }
497    }
498
499    /// Records the fields the running commands move.
500    pub(super) fn update_movement_flags(&mut self) {
501        self.moving = self.transitions.iter().fold(0, |moving, t| moving | (t.fields & t.moving_fields));
502    }
503
504    /// Ends `finished`: the gestures whose momentum they are, then the
505    /// camera on the ground once nothing moves it ([`Self::come_to_rest`]),
506    /// and last their ends and changes, which report that move too.
507    pub(super) fn finish_transitions(&mut self, finished: Vec<Transition>) {
508        for transition in &finished {
509            self.end_gesture_momentum(transition.gesture);
510        }
511        if !finished.is_empty() {
512            self.come_to_rest();
513        }
514        for transition in finished {
515            self.report_end(transition.command, transition.animation.transition_id, transition.end());
516            // This notification ends a command, not necessarily all camera
517            // motion.
518            let change = CameraChange { mode: transition.mode(), source: transition.source };
519            self.emit(TransformEvent::CameraDidChange(change));
520        }
521    }
522
523    /// Whether any camera command is still animating.
524    #[must_use]
525    pub fn in_transition(&self) -> bool {
526        !self.transitions.is_empty()
527    }
528
529    /// Moves the camera to where its commands are at `now`, and ends the
530    /// ones that have run out; `None`, for a map without a clock, ends them all.
531    pub fn update_transitions(&mut self, now: Option<Instant>) {
532        if self.transitions.is_empty() {
533            return;
534        }
535
536        if self.transitions.iter().any(|t| t.momentum.is_none()) {
537            self.apply_transitions(None, now);
538        }
539        for index in 0..self.transitions.len() {
540            self.advance_momentum(index, now);
541        }
542        if self.transitions.iter().any(|t| t.momentum.is_some()) {
543            self.keep_clear_of_ground();
544        }
545
546        let finished: Vec<_> = self.transitions.extract_if(.., |t| t.has_run_out(now) || t.fields == 0).collect();
547        self.update_movement_flags();
548        if !self.transitions.is_empty() {
549            self.emit(TransformEvent::CameraIsChanging);
550        }
551
552        self.finish_transitions(finished);
553    }
554
555    /// Takes `fields` from the running commands, and returns the ones left
556    /// with no fields, which the caller finishes.
557    pub(super) fn release_fields(&mut self, fields: u16) -> Vec<Transition> {
558        for active in &mut self.transitions {
559            let mut replaced = fields;
560            // Only the fields it still owns are coupled: one that gave up its
561            // anchor and its center keeps the rest.
562            let coupled = active.coupled_fields & active.fields;
563            if coupled & replaced != 0 {
564                replaced |= coupled;
565            }
566            active.fields &= !replaced;
567            if let Some(momentum) = &mut active.momentum {
568                active.fields = momentum.retain(active.fields);
569            }
570            if active.fields == 0 {
571                active.ended_by(TransitionOutcome::Replaced);
572            }
573        }
574        self.transitions.extract_if(.., |active| active.fields == 0).collect()
575    }
576
577    /// Runs `start` as a camera command, and returns the command. The
578    /// transitions that `start` starts report their end to it, as does a
579    /// command that fails or has nothing to move. Within a command being
580    /// started, `start` is part of that command.
581    pub(super) fn command(&mut self, start: impl FnOnce(&mut Self)) -> CameraCommandId {
582        if let Some(command) = self.command {
583            start(self);
584            return command;
585        }
586        let command = CameraCommandId(self.next_command);
587        self.next_command += 1;
588        self.command = Some(command);
589        start(self);
590        self.command = None;
591        command
592    }
593
594    /// The command that the transitions being started report their end to.
595    pub(super) fn reporting(&self) -> Option<CameraCommandId> {
596        self.command.filter(|_| !self.silent)
597    }
598
599    /// Makes the command being started end once, when `count` of its ends
600    /// have been reported.
601    pub(super) fn join_ends(&mut self, count: u32) {
602        if let Some(command) = self.reporting().filter(|_| count > 1) {
603            self.joint_ends.push(JointEnd { command, remaining: count, outcome: TransitionOutcome::Completed });
604        }
605    }
606
607    /// Reports an end of `command`, which ends it unless it waits for more
608    /// (see [`Self::join_ends`]).
609    fn report_end(&mut self, command: Option<CameraCommandId>, transition_id: Option<u64>, mut end: TransitionEnd) {
610        let Some(command) = command else { return };
611        if let Some(index) = self.joint_ends.iter().position(|joint| joint.command == command) {
612            let joint = &mut self.joint_ends[index];
613            joint.remaining -= 1;
614            joint.outcome = match (joint.outcome, end.outcome) {
615                (TransitionOutcome::Cancelled, _) | (_, TransitionOutcome::Cancelled) => TransitionOutcome::Cancelled,
616                (TransitionOutcome::Closed, _) | (_, TransitionOutcome::Closed) => TransitionOutcome::Closed,
617                (TransitionOutcome::Replaced, _) | (_, TransitionOutcome::Replaced) => TransitionOutcome::Replaced,
618                _ => TransitionOutcome::Completed,
619            };
620            if joint.remaining > 0 {
621                return;
622            }
623            end.outcome = joint.outcome;
624            self.joint_ends.swap_remove(index);
625        }
626        self.emit(TransformEvent::CommandEnded(CommandEnd { command, transition_id, end }));
627    }
628
629    /// Ends a command that started no transition: one that failed before it
630    /// moved the camera, or a momentum with nothing to move.
631    pub(super) fn end_unstarted(&mut self, animation: &AnimationOptions, outcome: TransitionOutcome) {
632        self.report_end(
633            self.reporting(),
634            animation.transition_id,
635            TransitionEnd { outcome, ..TransitionEnd::default() },
636        );
637    }
638
639    pub(crate) fn cancel_transitions(&mut self) {
640        let mut finished = std::mem::take(&mut self.transitions);
641        for transition in &mut finished {
642            transition.ended_by(TransitionOutcome::Cancelled);
643        }
644        self.update_movement_flags();
645        self.finish_transitions(finished);
646    }
647
648    /// Cancels the commands whose [`AnimationOptions::transition_id`] equals
649    /// `transition_id`, leaves the others running, and returns whether any
650    /// command ended.
651    pub fn cancel_transitions_with_id(&mut self, transition_id: u64) -> bool {
652        let mut finished: Vec<_> = self
653            .transitions
654            .extract_if(.., |transition| transition.animation.transition_id == Some(transition_id))
655            .collect();
656        if finished.is_empty() {
657            return false;
658        }
659        for transition in &mut finished {
660            transition.ended_by(TransitionOutcome::Cancelled);
661        }
662        self.update_movement_flags();
663        self.finish_transitions(finished);
664        true
665    }
666
667    /// Ends the running commands as closed, without a camera change. A map's
668    /// owner calls it before it drops the map, so that it hears every
669    /// command's end.
670    pub fn close(&mut self) {
671        for transition in std::mem::take(&mut self.transitions) {
672            let end = TransitionEnd { outcome: TransitionOutcome::Closed, ..transition.end() };
673            self.report_end(transition.command, transition.animation.transition_id, end);
674        }
675        self.update_movement_flags();
676    }
677}