use std::collections::HashMap;
use crate::animation::animation_action::{AnimationAction, LoopMode};
use crate::animation::animation_clip::{AnimationBlendMode, AnimationClip};
use crate::animation::binding_target::TargetResolver;
use crate::animation::property_binding::parse_track_name;
use crate::animation::property_mixer::PropertyMixer;
use crate::math::interpolant::InterpolantData;
use crate::math::interpolants::{linear_interpolant, LinearInterpolant};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RootId(usize);
impl RootId {
pub const MIXER_ROOT: RootId = RootId(0);
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ActionHandle(pub(crate) usize);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) struct ControlHandle(pub usize);
#[derive(Default)]
pub struct BindingPool {
slots: Vec<Option<PropertyMixer>>,
cache_index: Vec<Option<usize>>,
key: Vec<Option<(RootId, String)>>,
order: Vec<usize>,
n_active: usize,
by_root_and_name: HashMap<(RootId, String), usize>,
}
impl BindingPool {
pub fn get(&self, handle: usize) -> Option<&PropertyMixer> {
self.slots.get(handle).and_then(|s| s.as_ref())
}
pub(crate) fn get_mut(&mut self, handle: usize) -> Option<&mut PropertyMixer> {
self.slots.get_mut(handle).and_then(|s| s.as_mut())
}
fn add_inactive_binding(&mut self, handle: usize, root: RootId, track_name: &str) {
self.by_root_and_name
.insert((root, track_name.to_string()), handle);
self.key[handle] = Some((root, track_name.to_string()));
self.cache_index[handle] = Some(self.order.len());
self.order.push(handle);
}
fn remove_inactive_binding(&mut self, handle: usize) {
let Some(cache_index) = self.cache_index[handle] else {
return;
};
let last = *self
.order
.last()
.expect("three-rs: non-empty binding order");
self.cache_index[last] = Some(cache_index);
self.order[cache_index] = last;
self.order.pop();
self.cache_index[handle] = None;
if let Some((root, track_name)) = self.key[handle].take() {
self.by_root_and_name.remove(&(root, track_name));
}
}
fn lend_binding(&mut self, handle: usize) {
let prev_index = self.cache_index[handle].expect("three-rs: lending a cached binding");
let last_active_index = self.n_active;
self.n_active += 1;
let first_inactive = self.order[last_active_index];
self.cache_index[handle] = Some(last_active_index);
self.order[last_active_index] = handle;
self.cache_index[first_inactive] = Some(prev_index);
self.order[prev_index] = first_inactive;
}
fn take_back_binding(&mut self, handle: usize) {
let prev_index = self.cache_index[handle].expect("three-rs: taking back a cached binding");
self.n_active -= 1;
let first_inactive_index = self.n_active;
let last_active = self.order[first_inactive_index];
self.cache_index[handle] = Some(first_inactive_index);
self.order[first_inactive_index] = handle;
self.cache_index[last_active] = Some(prev_index);
self.order[prev_index] = last_active;
}
}
#[derive(Default)]
pub(crate) struct ControlPool {
slots: Vec<LinearInterpolant>,
cache_index: Vec<usize>,
order: Vec<usize>,
n_active: usize,
}
impl ControlPool {
pub fn lend_control_interpolant(&mut self) -> ControlHandle {
let last_active_index = self.n_active;
self.n_active += 1;
if last_active_index == self.order.len() {
let slot = self.slots.len();
self.slots.push(linear_interpolant(
vec![0.0, 0.0],
vec![0.0, 0.0],
1,
Some(vec![0.0]),
));
self.cache_index.push(last_active_index);
self.order.push(slot);
}
ControlHandle(self.order[last_active_index])
}
pub fn take_back_control_interpolant(&mut self, handle: ControlHandle) {
let prev_index = self.cache_index[handle.0];
self.n_active -= 1;
let first_inactive_index = self.n_active;
let last_active = self.order[first_inactive_index];
self.cache_index[handle.0] = first_inactive_index;
self.order[first_inactive_index] = handle.0;
self.cache_index[last_active] = prev_index;
self.order[prev_index] = last_active;
}
pub fn data_mut(&mut self, handle: ControlHandle) -> &mut InterpolantData {
&mut self.slots[handle.0].data
}
pub fn evaluate(&mut self, handle: ControlHandle, t: f64) -> f64 {
self.slots[handle.0].evaluate(t)[0]
}
pub fn stats(&self) -> (usize, usize) {
(self.order.len(), self.n_active)
}
}
#[derive(Default)]
struct ActionsForClip {
known_actions: Vec<ActionHandle>,
action_by_root: HashMap<RootId, ActionHandle>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MixerEvent {
Loop {
action: ActionHandle,
loop_delta: f64,
},
Finished {
action: ActionHandle,
direction: f64,
},
}
impl MixerEvent {
pub fn action(&self) -> ActionHandle {
match *self {
Self::Loop { action, .. } | Self::Finished { action, .. } => action,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MixerStats {
pub actions: (usize, usize),
pub bindings: (usize, usize),
pub control_interpolants: (usize, usize),
}
pub struct AnimationMixer {
roots: Vec<Box<dyn TargetResolver>>,
actions: Vec<Option<AnimationAction>>,
action_order: Vec<usize>,
n_active_actions: usize,
actions_by_clip: HashMap<String, ActionsForClip>,
bindings: BindingPool,
control: ControlPool,
accu_index: usize,
pub time: f64,
pub time_scale: f64,
events: Vec<MixerEvent>,
}
impl AnimationMixer {
pub fn new(root: Box<dyn TargetResolver>) -> Self {
Self {
roots: vec![root],
actions: Vec::new(),
action_order: Vec::new(),
n_active_actions: 0,
actions_by_clip: HashMap::new(),
bindings: BindingPool::default(),
control: ControlPool::default(),
accu_index: 0,
time: 0.0,
time_scale: 1.0,
events: Vec::new(),
}
}
pub fn add_root(&mut self, root: Box<dyn TargetResolver>) -> RootId {
self.roots.push(root);
RootId(self.roots.len() - 1)
}
pub fn get_root(&self) -> RootId {
RootId(0)
}
pub fn root(&self, root: RootId) -> &dyn TargetResolver {
&*self.roots[root.0]
}
pub fn stats(&self) -> MixerStats {
MixerStats {
actions: (self.action_order.len(), self.n_active_actions),
bindings: (self.bindings.order.len(), self.bindings.n_active),
control_interpolants: self.control.stats(),
}
}
pub fn bindings(&self) -> &BindingPool {
&self.bindings
}
pub fn action(&self, handle: ActionHandle) -> &AnimationAction {
self.actions[handle.0]
.as_ref()
.expect("three-rs: handle of a live action")
}
pub fn action_mut(&mut self, handle: ActionHandle) -> &mut AnimationAction {
self.actions[handle.0]
.as_mut()
.expect("three-rs: handle of a live action")
}
fn action_root(&self, handle: ActionHandle) -> RootId {
self.action(handle).local_root().unwrap_or(RootId(0))
}
fn bind_action(&mut self, handle: ActionHandle) {
let root = self.action_root(handle);
let tracks = self.action(handle).get_clip().tracks.clone();
for (i, track) in tracks.iter().enumerate() {
let track_name = track.name.clone();
if let Some(&existing) = self
.bindings
.by_root_and_name
.get(&(root, track_name.clone()))
{
if let Some(binding) = self.bindings.get_mut(existing) {
binding.reference_count += 1;
}
self.action_mut(handle).property_bindings[i] = Some(existing);
continue;
}
if let Some(own) = self.action(handle).property_bindings[i] {
if self.bindings.cache_index[own].is_none() {
if let Some(binding) = self.bindings.get_mut(own) {
binding.reference_count += 1;
}
self.bindings.add_inactive_binding(own, root, &track_name);
}
continue;
}
let Ok(parsed) = parse_track_name(&track_name) else {
continue;
};
let Some(target) = self.roots[root.0].resolve(&parsed) else {
continue;
};
let binding = PropertyMixer::new(target, track.value_type(), track.get_value_size());
let slot = self.bindings.slots.len();
self.bindings.slots.push(Some(binding));
self.bindings.cache_index.push(None);
self.bindings.key.push(None);
self.bindings
.get_mut(slot)
.expect("three-rs: the binding was just pushed at this slot")
.reference_count += 1;
self.bindings.add_inactive_binding(slot, root, &track_name);
self.action_mut(handle).property_bindings[i] = Some(slot);
}
}
fn activate_action(&mut self, handle: ActionHandle) {
if self.is_active_action(handle) {
return;
}
if self.action(handle).cache_index.is_none() {
let root = self.action_root(handle);
let clip_uuid = self.action(handle).get_clip().uuid.clone();
self.bind_action(handle);
self.add_inactive_action(handle, &clip_uuid, root);
}
let bindings = self.action(handle).property_bindings.clone();
for binding_handle in bindings.into_iter().flatten() {
let use_count = match self.bindings.get_mut(binding_handle) {
Some(binding) => {
let previous = binding.use_count;
binding.use_count += 1;
previous
}
None => continue,
};
if use_count == 0 {
self.bindings.lend_binding(binding_handle);
self.bindings
.get_mut(binding_handle)
.expect("three-rs: the binding resolved on the line above")
.save_original_state();
}
}
self.lend_action(handle);
}
fn deactivate_action(&mut self, handle: ActionHandle) {
if !self.is_active_action(handle) {
return;
}
let bindings = self.action(handle).property_bindings.clone();
for binding_handle in bindings.into_iter().flatten() {
let use_count = match self.bindings.get_mut(binding_handle) {
Some(binding) => {
binding.use_count -= 1;
binding.use_count
}
None => continue,
};
if use_count == 0 {
self.bindings
.get_mut(binding_handle)
.expect("three-rs: the binding resolved on the line above")
.restore_original_state();
self.bindings.take_back_binding(binding_handle);
}
}
self.take_back_action(handle);
}
fn is_active_action(&self, handle: ActionHandle) -> bool {
match self.actions[handle.0].as_ref().and_then(|a| a.cache_index) {
Some(index) => index < self.n_active_actions,
None => false,
}
}
fn add_inactive_action(&mut self, handle: ActionHandle, clip_uuid: &str, root: RootId) {
let actions_for_clip = self
.actions_by_clip
.entry(clip_uuid.to_string())
.or_default();
let by_clip_cache_index = actions_for_clip.known_actions.len();
actions_for_clip.known_actions.push(handle);
actions_for_clip.action_by_root.insert(root, handle);
let cache_index = self.action_order.len();
self.action_order.push(handle.0);
let action = self.action_mut(handle);
action.by_clip_cache_index = Some(by_clip_cache_index);
action.cache_index = Some(cache_index);
}
fn remove_inactive_action(&mut self, handle: ActionHandle) {
let Some(cache_index) = self.action(handle).cache_index else {
return;
};
let last = *self
.action_order
.last()
.expect("three-rs: non-empty action order");
self.actions[last]
.as_mut()
.expect("three-rs: the action order only holds live actions")
.cache_index = Some(cache_index);
self.action_order[cache_index] = last;
self.action_order.pop();
self.action_mut(handle).cache_index = None;
let clip_uuid = self.action(handle).get_clip().uuid.clone();
let by_clip_cache_index = self.action(handle).by_clip_cache_index;
let root = self.action_root(handle);
let mut clip_now_empty = false;
if let (Some(actions_for_clip), Some(by_clip_cache_index)) = (
self.actions_by_clip.get_mut(&clip_uuid),
by_clip_cache_index,
) {
let known = &mut actions_for_clip.known_actions;
let last_known = *known.last().expect("three-rs: non-empty knownActions");
known[by_clip_cache_index] = last_known;
known.pop();
if last_known != handle {
self.actions[last_known.0]
.as_mut()
.expect("three-rs: knownActions only holds live actions")
.by_clip_cache_index = Some(by_clip_cache_index);
}
actions_for_clip.action_by_root.remove(&root);
clip_now_empty = actions_for_clip.known_actions.is_empty();
}
self.action_mut(handle).by_clip_cache_index = None;
if clip_now_empty {
self.actions_by_clip.remove(&clip_uuid);
}
self.remove_inactive_bindings_for_action(handle);
}
fn remove_inactive_bindings_for_action(&mut self, handle: ActionHandle) {
let bindings = self.action(handle).property_bindings.clone();
for binding_handle in bindings.into_iter().flatten() {
let reference_count = match self.bindings.get_mut(binding_handle) {
Some(binding) => {
binding.reference_count -= 1;
binding.reference_count
}
None => continue,
};
if reference_count == 0 {
self.bindings.remove_inactive_binding(binding_handle);
}
}
}
fn lend_action(&mut self, handle: ActionHandle) {
let prev_index = self
.action(handle)
.cache_index
.expect("three-rs: cached action");
let last_active_index = self.n_active_actions;
self.n_active_actions += 1;
let first_inactive = self.action_order[last_active_index];
self.action_mut(handle).cache_index = Some(last_active_index);
self.action_order[last_active_index] = handle.0;
self.actions[first_inactive]
.as_mut()
.expect("three-rs: the action order only holds live actions")
.cache_index = Some(prev_index);
self.action_order[prev_index] = first_inactive;
}
fn take_back_action(&mut self, handle: ActionHandle) {
let prev_index = self
.action(handle)
.cache_index
.expect("three-rs: cached action");
self.n_active_actions -= 1;
let first_inactive_index = self.n_active_actions;
let last_active = self.action_order[first_inactive_index];
self.action_mut(handle).cache_index = Some(first_inactive_index);
self.action_order[first_inactive_index] = handle.0;
self.actions[last_active]
.as_mut()
.expect("three-rs: the action order only holds live actions")
.cache_index = Some(prev_index);
self.action_order[prev_index] = last_active;
}
pub fn clip_action(
&mut self,
clip: &AnimationClip,
optional_root: Option<RootId>,
blend_mode: Option<AnimationBlendMode>,
) -> ActionHandle {
let root = optional_root.unwrap_or(RootId(0));
let clip_uuid = clip.uuid.clone();
let blend_mode = blend_mode.unwrap_or(clip.blend_mode);
if let Some(actions_for_clip) = self.actions_by_clip.get(&clip_uuid) {
if let Some(&existing) = actions_for_clip.action_by_root.get(&root) {
if self.action(existing).blend_mode == blend_mode {
return existing;
}
}
}
let action = AnimationAction::new(clip.clone(), optional_root, Some(blend_mode));
let handle = ActionHandle(self.actions.len());
self.actions.push(Some(action));
self.bind_action(handle);
self.add_inactive_action(handle, &clip_uuid, root);
handle
}
pub fn existing_action(
&self,
clip: &AnimationClip,
optional_root: Option<RootId>,
) -> Option<ActionHandle> {
self.existing_action_by_uuid(&clip.uuid, optional_root)
}
pub fn existing_action_by_uuid(
&self,
clip_uuid: &str,
optional_root: Option<RootId>,
) -> Option<ActionHandle> {
let root = optional_root.unwrap_or(RootId(0));
self.actions_by_clip
.get(clip_uuid)
.and_then(|actions_for_clip| actions_for_clip.action_by_root.get(&root).copied())
}
pub fn stop_all_action(&mut self) -> &mut Self {
for i in (0..self.n_active_actions).rev() {
let handle = ActionHandle(self.action_order[i]);
self.stop(handle);
}
self
}
pub fn update(&mut self, delta_time: f64) -> &mut Self {
self.events.clear();
let delta_time = delta_time * self.time_scale;
self.time += delta_time;
let time = self.time;
let time_direction = if delta_time > 0.0 {
1.0
} else if delta_time < 0.0 {
-1.0
} else {
0.0 };
self.accu_index ^= 1;
let accu_index = self.accu_index;
for i in 0..self.n_active_actions {
let slot = self.action_order[i];
let mut action = self.actions[slot].take().expect("three-rs: live action");
action.update_(
ActionHandle(slot),
time,
delta_time,
time_direction,
accu_index,
&mut self.bindings,
&mut self.control,
&mut self.events,
);
self.actions[slot] = Some(action);
}
for i in 0..self.bindings.n_active {
let slot = self.bindings.order[i];
if let Some(binding) = self.bindings.get_mut(slot) {
binding.apply(accu_index);
}
}
self
}
pub fn take_events(&mut self) -> Vec<MixerEvent> {
std::mem::take(&mut self.events)
}
pub fn set_time(&mut self, time: f64) -> &mut Self {
self.time = 0.0; for action in self.actions.iter_mut().flatten() {
action.time = 0.0; }
self.update(time)
}
pub fn uncache_clip(&mut self, clip: &AnimationClip) {
let Some(actions_for_clip) = self.actions_by_clip.remove(&clip.uuid) else {
return;
};
for handle in actions_for_clip.known_actions {
self.deactivate_action(handle);
let Some(cache_index) = self.action(handle).cache_index else {
continue;
};
let last = *self
.action_order
.last()
.expect("three-rs: non-empty action order");
self.action_mut(handle).cache_index = None;
self.action_mut(handle).by_clip_cache_index = None;
if last != handle.0 {
self.actions[last]
.as_mut()
.expect("three-rs: the action order only holds live actions")
.cache_index = Some(cache_index);
}
self.action_order[cache_index] = last;
self.action_order.pop();
self.remove_inactive_bindings_for_action(handle);
}
}
pub fn uncache_root(&mut self, root: RootId) {
let actions: Vec<ActionHandle> = self
.actions_by_clip
.values()
.filter_map(|for_clip| for_clip.action_by_root.get(&root).copied())
.collect();
for handle in actions {
self.deactivate_action(handle);
self.remove_inactive_action(handle);
}
let bindings: Vec<usize> = self
.bindings
.by_root_and_name
.iter()
.filter(|((r, _), _)| *r == root)
.map(|(_, &handle)| handle)
.collect();
for binding_handle in bindings {
if let Some(binding) = self.bindings.get_mut(binding_handle) {
binding.restore_original_state();
}
self.bindings.remove_inactive_binding(binding_handle);
}
}
pub fn uncache_action(&mut self, clip: &AnimationClip, optional_root: Option<RootId>) {
if let Some(handle) = self.existing_action(clip, optional_root) {
self.deactivate_action(handle);
self.remove_inactive_action(handle);
}
}
pub fn play(&mut self, handle: ActionHandle) -> ActionHandle {
self.activate_action(handle);
handle
}
pub fn stop(&mut self, handle: ActionHandle) -> ActionHandle {
self.deactivate_action(handle);
self.reset(handle)
}
pub fn reset(&mut self, handle: ActionHandle) -> ActionHandle {
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.reset_(control);
handle
}
pub fn is_running(&self, handle: ActionHandle) -> bool {
self.action(handle).is_running_locally() && self.is_active_action(handle)
}
pub fn is_scheduled(&self, handle: ActionHandle) -> bool {
self.is_active_action(handle)
}
pub fn start_at(&mut self, handle: ActionHandle, time: f64) -> ActionHandle {
self.action_mut(handle).start_at_(time);
handle
}
pub fn set_loop(
&mut self,
handle: ActionHandle,
mode: LoopMode,
repetitions: f64,
) -> ActionHandle {
self.action_mut(handle).set_loop_(mode, repetitions);
handle
}
pub fn set_effective_weight(&mut self, handle: ActionHandle, weight: f64) -> ActionHandle {
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.set_effective_weight_(weight, control);
handle
}
pub fn get_effective_weight(&self, handle: ActionHandle) -> f64 {
self.action(handle).get_effective_weight()
}
pub fn set_effective_time_scale(
&mut self,
handle: ActionHandle,
time_scale: f64,
) -> ActionHandle {
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.set_effective_time_scale_(time_scale, control);
handle
}
pub fn get_effective_time_scale(&self, handle: ActionHandle) -> f64 {
self.action(handle).get_effective_time_scale()
}
pub fn set_duration(&mut self, handle: ActionHandle, duration: f64) -> ActionHandle {
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.set_duration_(duration, control);
handle
}
pub fn sync_with(&mut self, handle: ActionHandle, other: ActionHandle) -> ActionHandle {
let other_time = self.action(other).time;
let other_time_scale = self.action(other).time_scale;
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.sync_with_(other_time, other_time_scale, control);
handle
}
pub fn halt(&mut self, handle: ActionHandle, duration: f64) -> ActionHandle {
let now = self.time;
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.halt_(duration, now, control);
handle
}
pub fn warp(
&mut self,
handle: ActionHandle,
start_time_scale: f64,
end_time_scale: f64,
duration: f64,
) -> ActionHandle {
let now = self.time;
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.warp_(start_time_scale, end_time_scale, duration, now, control);
handle
}
pub fn stop_warping(&mut self, handle: ActionHandle) -> ActionHandle {
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.stop_warping_(control);
handle
}
pub fn stop_fading(&mut self, handle: ActionHandle) -> ActionHandle {
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.stop_fading_(control);
handle
}
pub fn fade_in(&mut self, handle: ActionHandle, duration: f64) -> ActionHandle {
let now = self.time;
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.fade_in_(duration, now, control);
handle
}
pub fn fade_out(&mut self, handle: ActionHandle, duration: f64) -> ActionHandle {
let now = self.time;
let control = &mut self.control;
self.actions[handle.0]
.as_mut()
.expect("three-rs: live action")
.fade_out_(duration, now, control);
handle
}
pub fn cross_fade_from(
&mut self,
handle: ActionHandle,
fade_out_action: ActionHandle,
duration: f64,
warp: bool,
) -> ActionHandle {
self.fade_out(fade_out_action, duration);
self.fade_in(handle, duration);
if warp {
let fade_in_duration = self.action(handle).get_clip().duration;
let fade_out_duration = self.action(fade_out_action).get_clip().duration;
let start_end_ratio = fade_out_duration / fade_in_duration;
let end_start_ratio = fade_in_duration / fade_out_duration;
let out_time_scale = self.action(fade_out_action).time_scale;
let in_time_scale = self.action(handle).time_scale;
self.action_mut(fade_out_action).restore_time_scale = Some(out_time_scale);
self.action_mut(handle).restore_time_scale = Some(in_time_scale);
self.warp(fade_out_action, 1.0, start_end_ratio, duration);
self.warp(handle, end_start_ratio, 1.0, duration);
}
handle
}
pub fn cross_fade_to(
&mut self,
handle: ActionHandle,
fade_in_action: ActionHandle,
duration: f64,
warp: bool,
) -> ActionHandle {
self.cross_fade_from(fade_in_action, handle, duration, warp)
}
pub fn get_clip(&self, handle: ActionHandle) -> &AnimationClip {
self.action(handle).get_clip()
}
pub fn get_action_root(&self, handle: ActionHandle) -> RootId {
self.action_root(handle)
}
}