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
//! Internal state of mist.
#[cfg(feature = "ser")]
use super::dump::StateDump;
use super::Comparison as Comp;
use super::MistInstant;
use super::Run;
use super::{DiffType, TimeType};
#[cfg(feature = "ser")]
use serde::{Deserialize, Serialize};
use std::{cell::RefCell, rc::Rc};
/// The state of the loaded run.
///
/// This holds everything needed for timekeeping, updating the state of the run (e.g. paused/running),
/// keeping comparisons, and storing times.
pub struct RunState {
run: Rc<RefCell<Run>>,
timer: MistInstant,
timer_state: TimerState,
run_status: SplitStatus,
comparison: Comp,
run_times: Vec<TimeType>,
run_diffs: Vec<DiffType>,
run_golds: Vec<bool>,
status_sum: i128,
/// what the time was when we paused
before_pause: u128,
/// sum of times in the split spent unpaused, updated when pausing
before_pause_split: u128,
/// last instant when we started the timer (after offset), unpaused, or split
split: u128,
/// last instant when we started the timer (after offset) or unpaused
start: u128,
/// global time without pauses: when running, updated to (cur - start + before_pause)
time: u128,
current_split: usize,
needs_save: bool,
}
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
enum TimerState {
Running,
NotRunning,
Paused,
Offset,
Finished,
}
/// A request to the [`RunState`] to change its state.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
#[repr(C)]
pub enum StateChangeRequest {
/// No request.
None,
/// Pause the timer.
Pause,
/// Start the timer, advance a split, or stop the timer.
Split,
/// Undo a split, returning to the previous one.
Unsplit,
/// Skip a split, leaving it with no time.
Skip,
/// Set the timer back to the beginning.
Reset,
/// Change to the next comparison.
NextComparison,
/// Change to the previous comparison.
PrevComparison,
}
/// A single change in state.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum StateChange {
/// No change.
None,
/// Start the timer in an offset.
EnterOffset, /*{amt: u128}*/
/// Start timing forwards after an offset.
ExitOffset,
/// Start a split.
EnterSplit {
/// Index of split that was entered.
idx: usize, /*name: String, pb: u128, gold: u128 */
},
/// Finish a split.
ExitSplit {
/// Index of split that was finished.
idx: usize,
/*name: String,*/ status: SplitStatus,
/// Amount of time spent on split.
time: u128,
/// Difference from comparison.
diff: i128,
},
Pause,
Unpause {
status: SplitStatus,
},
/// Exited the last split, so the run is over.
Finish,
Reset {
offset: Option<u128>,
},
ComparisonChanged {
comp: Comp,
},
}
/// Update returned from the [`RunState`].
///
/// One of these is returned every frame when [`update`](RunState::update) is called.
/// Since there could be multiple requests in one frame, and each request can cause
/// multiple state changes (e.g. [`ExitSplit`](StateChange::ExitSplit) and [`EnterSplit`](StateChange::EnterSplit)),
/// a [`Vec`] is used to store the state changes.
#[derive(Clone, Debug)]
pub struct RunUpdate {
/// All changes in state that occurred during a call to [`update`](RunState::update).
pub change: Vec<StateChange>,
/// Amount of time that has passed in the current split.
pub split_time: u128,
/// Amount of time that has passed in the run as a whole.
pub time: u128,
/// Whether the run is in an offset or not.
pub offset: bool,
/// Whether run is ahead, behind, etc.
pub status: SplitStatus,
}
/// Status of an active run.
///
/// Usually corresponds to colors in the renderer.
#[cfg_attr(feature = "ser", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum SplitStatus {
/// Timer is not running or no comparison.
None,
/// Runner is faster than comparison.
Ahead,
/// Runner is behind comparison but could save time.
Gaining,
/// Runner completed a split at their fastest time.
Gold,
/// Runner is slower than comparison.
Behind,
/// Runner is ahead of comparison, but is too slow to maintain previous pace.
Losing,
}
impl RunState {
/// Create a new RunState.
pub fn new(run: Rc<RefCell<Run>>) -> Self {
let len = run.borrow().pb_times().len();
Self {
run,
timer: MistInstant::now(),
timer_state: TimerState::NotRunning,
comparison: Comp::PersonalBest,
run_status: SplitStatus::None,
run_times: vec![TimeType::None; len],
run_diffs: vec![DiffType::Time(0); len],
run_golds: vec![false; len],
status_sum: 0,
before_pause: 0,
before_pause_split: 0,
split: 0,
start: 0,
time: 0,
current_split: 0,
needs_save: false,
}
}
#[cfg(feature = "ser")]
/// Fill in the RunState from a [`StateDump`].
///
/// Fills out all relevant fields of the RunState, and sets the timer state to
/// paused. No other processing is necessary, on unpause everything should pick up properly.
pub fn read_dump(&mut self, dump: &StateDump) {
self.run.replace(dump.run.clone());
self.run_status = dump.status;
self.comparison = dump.comparison;
self.run_times = dump.run_times.clone();
self.run_diffs = dump.run_diffs.clone();
self.run_golds = dump.run_golds.clone();
self.before_pause = dump.before_pause;
self.before_pause_split = dump.before_pause_split;
self.time = dump.time;
self.current_split = dump.current_split;
self.needs_save = dump.needs_save;
self.timer_state = TimerState::Paused;
}
/// Update the RunState.
///
/// Because multiple inputs can occur in the same frame, multiple state changes can be requested.
/// This handles all of them at once, and returns a [`RunUpdate`]. Also handles updating timing,
/// setting times to a [`Run`] once they are solidified, running offsets, etc. Prevents
/// illegal state changes from occurring by ignoring the request and returning [`StateChange::None`] in
/// the [`RunUpdate`]
pub fn update(&mut self, rq: &[StateChangeRequest]) -> RunUpdate {
let elapsed = self.timer.elapsed().as_millis();
if self.timer_state == TimerState::Running || self.timer_state == TimerState::Offset {
self.time = (elapsed - self.start) + self.before_pause;
}
let mut change = rq.iter().fold(Vec::new(), |mut vec, request| {
vec.append(&mut self.handle_scrq(request, elapsed));
vec
});
if self.timer_state == TimerState::Offset && self.run.borrow().offset().val() <= self.time {
self.timer_state = TimerState::Running;
self.start = elapsed;
self.split = elapsed;
self.time = 0;
change.push(StateChange::ExitOffset);
change.push(StateChange::EnterSplit { idx: 0 });
}
self.calc_status(elapsed);
RunUpdate {
change,
split_time: (elapsed - self.split) + self.before_pause_split,
time: self.time,
offset: self.timer_state == TimerState::Offset,
status: self.run_status,
}
}
/// Whether the [`Run`] has been changed and needs to be saved.
pub fn needs_save(&self) -> bool {
self.needs_save
}
/// Whether the timer is currently running.
pub fn is_running(&self) -> bool {
self.timer_state == TimerState::Running
}
fn calc_status(&mut self, elapsed: u128) {
if !self.is_running() || self.comparison == Comp::None {
self.run_status = SplitStatus::None;
return;
}
let run = self.run.borrow();
if self.run_times.len() <= 1 {
if run.pb().is_none() || self.time < run.pb().val() {
self.run_status = SplitStatus::Ahead;
} else {
self.run_status = SplitStatus::Behind;
}
} else if run.pb_times()[self.current_split].is_none() {
self.run_status = SplitStatus::Ahead;
} else {
let time = ((elapsed - self.split) + self.before_pause_split) as i128;
let current_diff = if self.comparison == Comp::PersonalBest {
time - run.pb_times()[self.current_split].val() as i128
} else if self.comparison == Comp::Golds {
time - run.gold_times()[self.current_split].val() as i128
} else if self.comparison == Comp::Average {
let sum = self.run.borrow().sum_times()[self.current_split];
time - (sum.1 / {
if sum.0 == 0 {
1
} else {
sum.0
}
}) as i128
} else {
0
};
let sum = self.status_sum + current_diff;
self.run_status = calc_status(sum, self.status_sum);
}
}
fn handle_scrq(&mut self, rq: &StateChangeRequest, elapsed: u128) -> Vec<StateChange> {
use StateChangeRequest::*;
match rq {
Pause
if self.timer_state == TimerState::Running
|| self.timer_state == TimerState::Offset =>
{
self.timer_state = TimerState::Paused;
self.before_pause = self.time;
self.before_pause_split += elapsed - self.split;
return vec![StateChange::Pause];
}
Pause if self.timer_state == TimerState::Paused => {
self.timer_state = TimerState::Running;
self.start = elapsed;
self.split = elapsed;
return vec![StateChange::Unpause {
status: self.run_status,
}];
}
Split if self.timer_state == TimerState::Running => {
let time = (elapsed - self.split) + self.before_pause_split;
self.split = elapsed;
self.before_pause_split = 0;
if self.run.borrow().splits().is_empty() {
let diff = time as i128 - self.run.borrow().pb().val() as i128;
return self.end_run(diff);
}
self.run_times[self.current_split] = TimeType::Time(time);
let run_diff = if self.comparison == Comp::PersonalBest {
time as i128 - self.run.borrow().pb_times()[self.current_split].val() as i128
} else if self.comparison == Comp::Golds {
time as i128 - self.run.borrow().gold_times()[self.current_split].val() as i128
} else if self.comparison == Comp::Average {
let sum = self.run.borrow().sum_times()[self.current_split];
time as i128
- (sum.1 / {
if sum.0 == 0 {
1
} else {
sum.0
}
}) as i128
} else {
0
};
self.run_diffs[self.current_split] = DiffType::Time(run_diff);
self.status_sum += run_diff;
let mut sum = self.run.borrow().sum_times()[self.current_split];
if sum.1.is_time() {
sum.0 += 1;
}
sum.1 += time;
self.run.borrow_mut().set_sum_time(self.current_split, sum);
self.needs_save = true;
if self.run.borrow().gold_times()[self.current_split].is_none()
|| time < self.run.borrow().gold_times()[self.current_split].val()
{
self.run_golds[self.current_split] = true;
self.run_status = SplitStatus::Gold;
}
if self.current_split == self.run.borrow().pb_times().len() - 1 {
return self.end_run(self.status_sum);
} else {
self.current_split += 1;
return vec![
StateChange::ExitSplit {
idx: self.current_split - 1,
status: self.run_status,
time: self.run_times[self.current_split - 1].val(),
diff: self.status_sum,
},
StateChange::EnterSplit {
idx: self.current_split,
},
];
}
}
Split if self.timer_state == TimerState::NotRunning => {
self.start = elapsed;
self.split = elapsed;
self.time = 0;
if self.run.borrow().offset().is_time() {
self.timer_state = TimerState::Offset;
return vec![StateChange::EnterOffset];
} else {
self.timer_state = TimerState::Running;
return vec![StateChange::EnterSplit { idx: 0 }];
}
}
Unsplit if self.timer_state == TimerState::Running && self.current_split != 0 => {
self.current_split -= 1;
self.before_pause_split = 0;
self.split -= self.run_times[self.current_split].raw();
self.run_diffs[self.current_split] = DiffType::Time(0);
self.run_times[self.current_split] = TimeType::None;
self.run_golds[self.current_split] = false;
return vec![StateChange::EnterSplit {
idx: self.current_split,
}];
}
Reset => {
for idx in self
.run_golds
.iter()
.enumerate()
.filter_map(|(idx, &gold)| if gold { Some(idx) } else { Option::None })
{
self.run
.borrow_mut()
.set_gold_time(idx, self.run_times[idx]);
}
self.before_pause = 0;
self.before_pause_split = 0;
self.split = 0;
self.start = 0;
let len = self.run.borrow().pb_times().len();
self.run_diffs = vec![DiffType::Time(0); len];
self.run_times = vec![TimeType::None; len];
self.run_golds = vec![false; len];
self.current_split = 0;
self.timer_state = TimerState::NotRunning;
self.status_sum = 0;
return vec![StateChange::Reset {
offset: self.run.borrow().offset().to_option(),
}];
}
Skip if self.timer_state == TimerState::Running => {
let time = (elapsed - self.split) + self.before_pause_split;
self.run_times[self.current_split] = TimeType::Skipped(time);
self.run_diffs[self.current_split] =
DiffType::Skipped(if self.comparison == Comp::PersonalBest {
time as i128
- self.run.borrow().pb_times()[self.current_split].val() as i128
} else if self.comparison == Comp::Golds {
time as i128
- self.run.borrow().gold_times()[self.current_split].val() as i128
} else if self.comparison == Comp::Average {
let sum = self.run.borrow().sum_times()[self.current_split];
time as i128
- (sum.1 / {
if sum.0 == 0 {
1
} else {
sum.0
}
}) as i128
} else {
0
});
self.split = elapsed;
self.before_pause_split = 0;
if self.current_split == self.run.borrow().pb_times().len() - 1 {
self.timer_state = TimerState::Finished;
return vec![
StateChange::ExitSplit {
idx: self.current_split,
status: self.run_status,
time: 0,
diff: 0,
},
StateChange::Finish,
];
} else {
self.current_split += 1;
return vec![
StateChange::ExitSplit {
idx: self.current_split - 1,
status: self.run_status,
time: 0,
diff: 0,
},
StateChange::EnterSplit {
idx: self.current_split,
},
];
}
}
&n @ (NextComparison | PrevComparison) => {
if n == NextComparison {
self.comparison.next();
} else {
self.comparison.prev();
}
self.run_diffs = self
.run_times
.iter()
.zip(match self.comparison {
Comp::PersonalBest => self.run.borrow().pb_times_u128(),
Comp::Golds => self.run.borrow().gold_times_u128(),
Comp::Average => self
.run
.borrow()
.sum_times()
.iter()
.map(|&(n, t)| t / (if n == 0 { 1 } else { n }))
.collect(),
Comp::None => vec![0; self.run_times.len()],
})
.map(|(&taken, cmp)| match taken {
TimeType::Time(t) => DiffType::Time(t as i128 - cmp as i128),
TimeType::Skipped(t) => DiffType::Skipped(t as i128 - cmp as i128),
TimeType::None => DiffType::Time(0),
})
.collect();
self.status_sum = self.run_diffs.iter().map(|d| d.raw()).sum::<i128>();
return vec![StateChange::ComparisonChanged {
comp: self.comparison,
}];
}
_ => {}
}
vec![StateChange::None]
}
fn end_run(&mut self, diff: i128) -> Vec<StateChange> {
let mut run = self.run.borrow_mut();
for idx in self
.run_golds
.iter()
.enumerate()
.filter_map(|(idx, &gold)| if gold { Some(idx) } else { None })
{
run.set_gold_time(idx, self.run_times[idx]);
}
self.timer_state = TimerState::Finished;
if run.pb().is_none() || self.time < run.pb().val() {
self.needs_save = true;
run.set_pb_times(&self.run_times);
run.set_pb(TimeType::Time(self.time));
}
let time = if self.run_times.is_empty() {
self.time
} else {
self.run_times[self.current_split].val()
};
vec![
StateChange::ExitSplit {
idx: self.current_split,
status: self.run_status,
time,
diff,
},
StateChange::Finish,
]
}
#[cfg(feature = "ser")]
/// Generate a [`StateDump`].
///
/// Uses the current state of the timer to create a `StateDump` containing all
/// information available in the RunState. The fields unique to the renderer must be
/// filled by the application.
pub fn create_state_dump(&self) -> StateDump {
StateDump {
run: self.run.borrow().clone(),
status: self.run_status,
comparison: self.comparison,
run_times: self.run_times.clone(),
run_diffs: self.run_diffs.clone(),
run_golds: self.run_golds.clone(),
before_pause: self.before_pause,
before_pause_split: self.before_pause_split,
time: self.time,
current_split: self.current_split,
needs_save: self.needs_save,
}
}
}
/// Calculate the run's current status.
///
/// Calculates whether the runner is ahead, behind, gaining, or losing time based
/// on the current amount of time that has passed and the amount of time that had
/// passed in the comparison run.
pub fn calc_status(sum: i128, last_sum: i128) -> SplitStatus {
if sum <= 0 {
if sum <= last_sum {
SplitStatus::Ahead
} else {
SplitStatus::Losing
}
} else if sum < last_sum {
SplitStatus::Gaining
} else {
SplitStatus::Behind
}
}