Skip to main content

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