Skip to content

Instantly share code, notes, and snippets.

@bvssvni
Last active August 29, 2015 14:02
Show Gist options
  • Save bvssvni/4df4c978120591ec1b33 to your computer and use it in GitHub Desktop.
Save bvssvni/4df4c978120591ec1b33 to your computer and use it in GitHub Desktop.
/// Updates the cursor that tracks an event.
///
/// Returns `None` if the action did not terminate.
/// or `Some(dt)` that tells how much time was consumed by the action.
pub fn update(
&mut self,
dt: f64,
f: |action: &'a A, state: S| -> Option<S>
) -> Option<f64> {
match *self {
State(action, ref mut state) => {
// Call the function that updates the state.
match f(action, *state) {
Some(new_state) => {*state = new_state; Some(0.0)},
None => None,
}
},
WaitCursor(dt, ref mut t) => {
// Update the time and return 'false' if we completed.
*t = dt.min(dt + *t);
if *t < dt { None } else { Some(dt) }
},
SequenceCursor(
seq,
i,
ref mut inc_dt,
ref mut waited_dt,
ref mut cursor
) => {
// Update a sequence of events.
let next_update = *waited_dt + dt;
let mut cur = cursor;
let mut j = i;
while j < seq.len() && *inc_dt < next_update {
// If the sub event terminates,
// decrement the delta time for next events.
match cur.update(next_update - *inc_dt, f) {
None => { *waited_dt = next_update; break },
Some(consumed_dt) => *inc_dt += consumed_dt,
};
// Create a new cursor for next event.
// Use the same pointer to avoid allocation.
j += 1;
**cur = seq.get(j).to_cursor();
}
// If finished, the sequence, return the time that was consumed by the sequence.
if j < seq.len() { None } else { Some(*inc_dt) }
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment