re_viewer_context 0.32.2

Rerun viewer state that is shared with the viewer's code components.
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
use re_chunk::TimelineName;
use re_log_types::{AbsoluteTimeRange, AbsoluteTimeRangeF, TimeReal, TimeType};
use re_sdk_types::blueprint::components::{LoopMode, PlayState};

use crate::NeedsRepaint;
use crate::blueprint_helpers::BlueprintContext;

use super::blueprint_ext::TimeBlueprintExt as _;
use super::{TimeControl, TimeControlDb, TimeControlResponse, TimeState, TimeView};

/// Direction for time movement commands.
#[derive(Debug, Clone, Copy)]
pub enum MoveDirection {
    Back,
    Forward,
}

/// Speed for time movement commands.
#[derive(Debug, Clone, Copy)]
pub enum MoveSpeed {
    Normal,
    Fast,
}

/// A command used to mutate `TimeControl`.
///
/// Can be sent using [`crate::SystemCommand::TimeControlCommands`].
#[derive(Debug)]
pub enum TimeControlCommand {
    HighlightRange(AbsoluteTimeRange),
    ClearHighlightedRange,

    /// Reset the active timeline to instead be automatically assigned.
    ResetActiveTimeline,
    SetActiveTimeline(TimelineName),

    /// Set the current looping state.
    SetLoopMode(LoopMode),
    SetPlayState(PlayState),
    Pause,
    TogglePlayPause,
    StepTimeBack,
    StepTimeForward,
    Move {
        direction: MoveDirection,
        speed: MoveSpeed,
    },
    MoveBeginning,
    MoveEnd,

    /// Restart the time cursor to the start.
    ///
    /// Stops any ongoing following.
    Restart,

    /// Set playback speed.
    SetSpeed(f32),

    /// Set playback fps.
    SetFps(f32),

    /// Set the current time selection without enabling looping.
    SetTimeSelection(AbsoluteTimeRange),

    /// Remove the current time selection.
    ///
    /// If the current loop mode is selection, turns off looping.
    RemoveTimeSelection,

    /// Sets the current time cursor.
    SetTime(TimeReal),

    /// Set the range of time we are currently zoomed in on.
    SetTimeView(TimeView),

    /// Reset the range of time we are currently zoomed in on.
    ///
    /// The view will instead fall back to the default which is
    /// showing all received data.
    ResetTimeView,
}

impl TimeControlCommand {
    /// Convert the temporal parts of a URL fragment into time-control commands.
    ///
    /// A temporal `when=…` anchor represents a fixed time cursor, so applying it
    /// must always pause playback before seeking.
    pub fn from_url_fragment(fragment: &re_uri::Fragment) -> Vec<Self> {
        let mut time_commands = Vec::new();

        if let Some(time_selection) = &fragment.time_selection {
            time_commands.push(Self::SetActiveTimeline(*time_selection.timeline.name()));
            time_commands.push(Self::SetTimeSelection(time_selection.range));
            time_commands.push(Self::SetLoopMode(LoopMode::Selection));
        }

        if let Some((timeline, timecell)) = &fragment.when {
            time_commands.push(Self::SetActiveTimeline(*timeline));
            time_commands.push(Self::SetPlayState(PlayState::Paused));
            time_commands.push(Self::SetTime(timecell.value.into()));
        }

        time_commands
    }
}

impl TimeControl {
    pub fn handle_time_commands(
        &mut self,
        blueprint_ctx: Option<&impl BlueprintContext>,
        db: &dyn TimeControlDb,
        commands: &[TimeControlCommand],
    ) -> TimeControlResponse {
        let mut response = TimeControlResponse {
            needs_repaint: NeedsRepaint::No,
            playing_change: None,
            timeline_change: None,
            time_change: None,
        };

        let (old_playing, old_timeline, old_state) = (
            self.playing,
            self.timeline().copied(),
            self.states.get(self.timeline_name()).copied(),
        );

        for command in commands {
            let needs_repaint = self.handle_time_command(blueprint_ctx, db, command);

            if needs_repaint == NeedsRepaint::Yes {
                response.needs_repaint = NeedsRepaint::Yes;
            }
        }

        self.diff_with(&mut response, old_timeline, old_playing, old_state);

        response
    }

    /// Applies a time command with respect to the current timeline.
    ///
    /// If `blueprint_ctx` is some, this also writes to that blueprint
    /// for applicable commands.
    ///
    /// Returns if the command should cause a repaint.
    fn handle_time_command(
        &mut self,
        blueprint_ctx: Option<&impl BlueprintContext>,
        db: &dyn TimeControlDb,
        command: &TimeControlCommand,
    ) -> NeedsRepaint {
        match command {
            // TODO(isse): Changing the highlighted range should technically cause a repaint. But this causes issues
            // because right now the selection panel wants to clear the range if it's some each frame, and maybe set
            // it again at later point.
            //
            // This is (right now) always caused by hovering on something, so the mouse movement will cause repaints
            // in all current cases.
            //
            // A better fix for this would be to collect all time commands before handling them, and for highlight
            // ranges only keep the last one. And requesting a repaint here again.
            TimeControlCommand::HighlightRange(range) => {
                self.highlighted_range = Some(*range);
                NeedsRepaint::No
            }
            TimeControlCommand::ClearHighlightedRange => {
                self.highlighted_range = None;
                NeedsRepaint::No
            }
            TimeControlCommand::ResetActiveTimeline => {
                if let Some(blueprint_ctx) = blueprint_ctx {
                    blueprint_ctx.clear_timeline();
                }
                if let Some(timeline) = self
                    .timeline()
                    .copied()
                    .or_else(|| db.timelines().into_values().next())
                {
                    self.timeline = super::ActiveTimeline::Auto(timeline);
                }
                self.select_valid_timeline(db);

                NeedsRepaint::Yes
            }
            TimeControlCommand::SetActiveTimeline(timeline_name) => {
                if let Some(blueprint_ctx) = blueprint_ctx {
                    blueprint_ctx.set_timeline(*timeline_name);
                }

                if let Some(timeline) = db.timelines().get(timeline_name).copied() {
                    self.timeline = super::ActiveTimeline::UserEdited(timeline);
                } else {
                    self.timeline = super::ActiveTimeline::Pending(*timeline_name);
                }

                if let Some(state) = self.states.get(timeline_name) {
                    // Use the new timeline's cached time selection.
                    if let Some(blueprint_ctx) = blueprint_ctx {
                        match state.time_selection {
                            Some(selection) => blueprint_ctx.set_time_selection(selection.to_int()),
                            None => blueprint_ctx.clear_time_selection(),
                        }
                    }
                } else if let Some(full_range) = db.time_range_for(timeline_name) {
                    self.states
                        .insert(*timeline_name, TimeState::new(full_range.min));
                }

                NeedsRepaint::Yes
            }
            TimeControlCommand::SetLoopMode(loop_mode) => {
                if self.loop_mode == *loop_mode {
                    NeedsRepaint::No
                } else {
                    if let Some(blueprint_ctx) = blueprint_ctx {
                        blueprint_ctx.set_loop_mode(*loop_mode);
                    }
                    self.loop_mode = *loop_mode;
                    if self.loop_mode != LoopMode::Off {
                        if self.play_state() == PlayState::Following {
                            self.set_play_state(Some(db), PlayState::Playing, blueprint_ctx);
                        }

                        // It makes no sense with looping and follow.
                        self.following = false;
                    }

                    NeedsRepaint::Yes
                }
            }
            TimeControlCommand::SetPlayState(play_state) => {
                if self.play_state() == *play_state {
                    NeedsRepaint::No
                } else {
                    self.set_play_state(Some(db), *play_state, blueprint_ctx);

                    if self.following {
                        if let Some(blueprint_ctx) = blueprint_ctx {
                            blueprint_ctx.set_loop_mode(LoopMode::Off);
                        }
                        self.loop_mode = LoopMode::Off;
                    }

                    NeedsRepaint::Yes
                }
            }
            TimeControlCommand::Pause => {
                if self.playing {
                    self.pause(blueprint_ctx);
                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }

            TimeControlCommand::TogglePlayPause => {
                self.toggle_play_pause(db, blueprint_ctx);

                NeedsRepaint::Yes
            }
            TimeControlCommand::StepTimeBack => {
                self.step_time_back(db, blueprint_ctx);

                NeedsRepaint::Yes
            }
            TimeControlCommand::StepTimeForward => {
                self.step_time_fwd(db, blueprint_ctx);

                NeedsRepaint::Yes
            }
            TimeControlCommand::Move { direction, speed } => {
                self.move_time(db, blueprint_ctx, *direction, *speed);
                NeedsRepaint::Yes
            }
            TimeControlCommand::MoveBeginning => {
                if let Some(full_range) = db.time_range_for(self.timeline_name()) {
                    self.states
                        .entry(*self.timeline_name())
                        .or_insert_with(|| TimeState::new(full_range.min))
                        .time = full_range.min.into();

                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
            TimeControlCommand::MoveEnd => {
                if let Some(full_range) = db.time_range_for(self.timeline_name()) {
                    self.states
                        .entry(*self.timeline_name())
                        .or_insert_with(|| TimeState::new(full_range.max))
                        .time = full_range.max.into();
                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
            TimeControlCommand::Restart => {
                if let Some(full_range) = db.time_range_for(self.timeline_name()) {
                    self.following = false;

                    if let Some(state) = self.states.get_mut(self.timeline.name()) {
                        state.time = full_range.min.into();
                    }

                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
            TimeControlCommand::SetSpeed(speed) => {
                if *speed == self.speed {
                    NeedsRepaint::No
                } else {
                    self.speed = *speed;

                    if let Some(blueprint_ctx) = blueprint_ctx {
                        blueprint_ctx.set_playback_speed(*speed as f64);
                    }

                    NeedsRepaint::Yes
                }
            }
            TimeControlCommand::SetFps(fps) => {
                if let Some(state) = self.states.get_mut(self.timeline.name())
                    && state.fps != *fps
                {
                    state.fps = *fps;

                    if let Some(blueprint_ctx) = blueprint_ctx {
                        blueprint_ctx.set_fps(*fps as f64);
                    }

                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
            TimeControlCommand::SetTimeSelection(time_range) => {
                let timeline_range = db
                    .time_range_for(self.timeline_name())
                    .unwrap_or(AbsoluteTimeRange::EVERYTHING);

                let Some(time_range) = timeline_range.intersection(*time_range) else {
                    return self.handle_time_command(
                        blueprint_ctx,
                        db,
                        &TimeControlCommand::RemoveTimeSelection,
                    );
                };

                if let Some(blueprint_ctx) = blueprint_ctx {
                    blueprint_ctx.set_time_selection(time_range);
                }

                let state = self
                    .states
                    .entry(*self.timeline_name())
                    .or_insert_with(|| TimeState::new(time_range.min));

                let repaint = state.time_selection.map(|r| r.to_int()) != Some(time_range);

                state.time_selection = Some((time_range).into());

                if repaint {
                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
            TimeControlCommand::RemoveTimeSelection => {
                if let Some(state) = self.states.get_mut(self.timeline.name()) {
                    if let Some(blueprint_ctx) = blueprint_ctx {
                        blueprint_ctx.clear_time_selection();
                    }
                    state.time_selection = None;
                    if self.loop_mode == LoopMode::Selection {
                        self.loop_mode = LoopMode::Off;

                        if let Some(blueprint_ctx) = blueprint_ctx {
                            blueprint_ctx.set_loop_mode(self.loop_mode);
                        }
                    }

                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
            TimeControlCommand::SetTime(time) => {
                let timeline_range = db
                    .time_range_for(self.timeline_name())
                    .unwrap_or(AbsoluteTimeRange::EVERYTHING);

                // If the floating point time is inside the range, use that.
                let timeline_rangef = AbsoluteTimeRangeF::from(timeline_range);
                let clamped_time = if timeline_rangef.contains(*time) {
                    *time
                } else {
                    (*time).clamp(timeline_rangef.min, timeline_rangef.max)
                };

                let time_int = clamped_time.floor();

                let repaint = self.time_int() != Some(time_int);

                let state = self
                    .states
                    .entry(*self.timeline_name())
                    .or_insert_with(|| TimeState::new(clamped_time));
                state.time = clamped_time;

                self.exit_follow_mode(db, blueprint_ctx);
                self.start_buffering();

                if repaint {
                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
            TimeControlCommand::SetTimeView(time_view) => {
                if let Some(state) = self.states.get_mut(self.timeline.name()) {
                    state.view = Some(*time_view);

                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
            TimeControlCommand::ResetTimeView => {
                if let Some(state) = self.states.get_mut(self.timeline.name()) {
                    state.view = None;

                    NeedsRepaint::Yes
                } else {
                    NeedsRepaint::No
                }
            }
        }
    }

    fn step_time_back(
        &mut self,
        db: &dyn TimeControlDb,
        blueprint_ctx: Option<&impl BlueprintContext>,
    ) {
        re_tracing::profile_function!();
        self.pause(blueprint_ctx);
        self.step_time_back_no_pause(db);
    }

    fn step_time_fwd(
        &mut self,
        db: &dyn TimeControlDb,
        blueprint_ctx: Option<&impl BlueprintContext>,
    ) {
        re_tracing::profile_function!();
        self.pause(blueprint_ctx);
        self.step_time_fwd_no_pause(db);
    }

    fn step_time_back_no_pause(&mut self, db: &dyn TimeControlDb) {
        if let Some(time) = self.time() {
            let timeline = self.timeline_name();
            let prev = db.prev_time_on_timeline(timeline, time.ceil());

            let new_time = if let Some(loop_range) = self.active_loop_selection() {
                if let Some(prev) = prev
                    && TimeReal::from(prev) >= loop_range.min
                {
                    prev.into()
                } else {
                    // Wrap to end of loop
                    if let Some(prev_from_end) =
                        db.prev_time_on_timeline(timeline, loop_range.max.ceil())
                    {
                        prev_from_end.into()
                    } else {
                        loop_range.max
                    }
                }
            } else if let Some(prev) = prev {
                prev.into()
            } else {
                // Wrap to the end
                if let Some(range) = db.time_range_for(timeline) {
                    range.max.into()
                } else {
                    return;
                }
            };

            if let Some(state) = self.states.get_mut(self.timeline.name()) {
                state.time = new_time;
            }
        }
    }

    fn step_time_fwd_no_pause(&mut self, db: &dyn TimeControlDb) {
        if let Some(time) = self.time() {
            let timeline = self.timeline_name();
            let next = db.next_time_on_timeline(timeline, time.floor());

            let new_time = if let Some(loop_range) = self.active_loop_selection() {
                if let Some(next) = next
                    && TimeReal::from(next) <= loop_range.max
                {
                    next.into()
                } else {
                    // Wrap to start of loop
                    if let Some(next_from_start) =
                        db.next_time_on_timeline(timeline, loop_range.min.floor())
                    {
                        next_from_start.into()
                    } else {
                        loop_range.min
                    }
                }
            } else if let Some(next) = next {
                next.into()
            } else {
                // Wrap to the start
                if let Some(range) = db.time_range_for(timeline) {
                    range.min.into()
                } else {
                    return;
                }
            };

            if let Some(state) = self.states.get_mut(self.timeline.name()) {
                state.time = new_time;
            }
        }
    }

    /// Move time by arrow keys. Preserves play/pause state, but exits follow mode.
    fn move_time(
        &mut self,
        db: &dyn TimeControlDb,
        blueprint_ctx: Option<&impl BlueprintContext>,
        direction: MoveDirection,
        speed: MoveSpeed,
    ) {
        self.exit_follow_mode(db, blueprint_ctx);

        match self.time_type() {
            Some(TimeType::Sequence) => {
                let steps = match speed {
                    MoveSpeed::Normal => 1,
                    MoveSpeed::Fast => 10,
                };
                for _ in 0..steps {
                    match direction {
                        MoveDirection::Back => {
                            self.step_time_back_no_pause(db);
                        }
                        MoveDirection::Forward => {
                            self.step_time_fwd_no_pause(db);
                        }
                    }
                }
            }
            Some(TimeType::DurationNs | TimeType::TimestampNs) => {
                let seconds = match (direction, speed) {
                    (MoveDirection::Back, MoveSpeed::Normal) => -0.1,
                    (MoveDirection::Forward, MoveSpeed::Normal) => 0.1,
                    (MoveDirection::Back, MoveSpeed::Fast) => -1.0,
                    (MoveDirection::Forward, MoveSpeed::Fast) => 1.0,
                };
                self.move_by_seconds_temporal(db, seconds);
            }
            None => {}
        }
    }

    fn move_by_seconds_temporal(&mut self, db: &dyn TimeControlDb, seconds: f64) {
        if let Some(time) = self.time() {
            let mut new_time = time + TimeReal::from_secs(seconds);

            let range = self
                .time_selection()
                .or_else(|| db.time_range_for(self.timeline_name()).map(|r| r.into()));
            if let Some(range) = range {
                if time == range.min && new_time < range.min {
                    // jump right to the end
                    new_time = range.max;
                } else if new_time < range.min {
                    // we are right at the end, wrap to the start
                    new_time = range.min;
                } else if time == range.max && new_time > range.max {
                    // jump right to the start
                    new_time = range.min;
                } else if new_time > range.max {
                    // we are right at the start, wrap to the end
                    new_time = range.max;
                }
            }

            if let Some(state) = self.states.get_mut(self.timeline.name()) {
                state.time = new_time;
            }
        }
    }

    /// If following, switch to playing. Otherwise keep the current play state.
    fn exit_follow_mode(
        &mut self,
        db: &dyn TimeControlDb,
        blueprint_ctx: Option<&impl BlueprintContext>,
    ) {
        if self.following {
            self.set_play_state(Some(db), PlayState::Playing, blueprint_ctx);
        }
    }

    fn toggle_play_pause(
        &mut self,
        db: &dyn TimeControlDb,
        blueprint_ctx: Option<&impl BlueprintContext>,
    ) {
        if self.playing {
            self.pause(blueprint_ctx);
        } else {
            // Start from beginning if we are at the end:
            if let Some(range) = db.time_range_for(self.timeline_name())
                && let Some(state) = self.states.get_mut(self.timeline.name())
                && range.max <= state.time
            {
                state.time = range.min.into();
                self.playing = true;
                self.following = false;
                return;
            }

            self.set_play_state(Some(db), PlayState::Playing, blueprint_ctx);
        }
    }
}