Skip to main content

unbanished_game/behaviour/animation/
shared.rs

1//! `Graphics::AnimationManager` (Runtime): the shared instances of instanced clips. Each clip a
2//! character plays with its flag set is followed through one of shared clocks (3, 4 or 8 for the
3//! citizens' and animals'), so the characters on one walk or work in step.
4//!
5//! - `GetInstanceId`: the first request for a group's clip makes its instances, the `k`-th starting
6//!   `k × duration / count` into the clip (and updated twice at no time); each request counts one
7//!   more user and gets the instance whose clock is earliest.
8//! - `Update`: every instance advances, before the characters; its pose's root is the identity
9//!   turned and its movement.
10//! - `FreeInstanceId`: the last user gone, the clip's instances go.
11//!
12//! The original keeps one manager for the process; the port one per thread, reset with each town
13//! ([`shared::reset`]).
14//!
15//! Original: Runtime `0x1800fe260`, Runtime `0x1800fead0`, Runtime `0x1800fe200`.
16
17use super::Playback;
18use std::cell::RefCell;
19use unbanished_formats::skeleton::Transform;
20use unbanished_formats::types::{AnimationClip, AnimationGroup};
21
22struct Entry {
23    group: String,
24    clip: usize,
25    users: i32,
26    data: AnimationClip,
27    instances: Vec<(Playback, Vec<Transform>)>,
28}
29
30thread_local! {
31    static ENTRIES: RefCell<Vec<Option<Entry>>> = const { RefCell::new(Vec::new()) };
32}
33
34/// A new town: no shared instances.
35pub fn reset() {
36    ENTRIES.with(|e| e.borrow_mut().clear());
37}
38
39/// One town's shared instances, kept aside while another town on the same thread runs (a
40/// lockstep test runs several towns in one process; on separate computers each has its own).
41#[derive(Default)]
42pub struct Table(Vec<Option<Entry>>);
43
44/// Puts `table` in place of this thread's instances, and the thread's in `table`.
45pub fn swap(table: &mut Table) {
46    ENTRIES.with(|e| std::mem::swap(&mut *e.borrow_mut(), &mut table.0));
47}
48
49// Each instance's clock and speed come from its own AnimationState (FUN_18005cd90); the pose is
50// sampled again here and replaced by the next Update before any character reads it.
51/// One shared entry as a save holds it: the group and clip, the number of users, and each
52/// instance's clock and speed.
53pub struct Saved<'g> {
54    /// The animation group.
55    pub group: &'g AnimationGroup,
56    /// The clip.
57    pub clip: usize,
58    /// The users the original counted (characters that left without freeing stay counted).
59    pub users: i32,
60    /// Each instance's clock and speed.
61    pub instances: Vec<(i64, f32)>,
62}
63
64/// The shared instances of a saved game, slot by slot (`None` for a free slot), so that every
65/// saved instance id names the same entry and instance again.
66///
67/// Original: `AnimationManager::Serialize`, Runtime `0x1800fea20` (reading).
68pub fn restore(slots: Vec<Option<Saved>>) {
69    let entries = slots
70        .into_iter()
71        .map(|slot| {
72            let s = slot?;
73            let data = s.group.clips.get(s.clip)?.clone();
74            let instances = s
75                .instances
76                .into_iter()
77                .map(|(elapsed, speed)| {
78                    let mut p = Playback::new(s.clip, elapsed);
79                    p.speed = speed;
80                    let pose = p.pose(&data);
81                    (p, pose)
82                })
83                .collect();
84            Some(Entry {
85                group: key(s.group),
86                clip: s.clip,
87                users: s.users,
88                data,
89                instances,
90            })
91        })
92        .collect();
93    ENTRIES.with(|e| *e.borrow_mut() = entries);
94}
95
96/// The shared instances slot by slot (`None` for a free slot): each entry's group (its resource,
97/// the key requests match), clip, users and its instances' clocks.
98pub fn snapshot() -> Vec<Option<(String, usize, i32, Vec<Playback>)>> {
99    ENTRIES.with(|e| {
100        e.borrow()
101            .iter()
102            .map(|x| {
103                x.as_ref().map(|x| {
104                    (
105                        x.group.clone(),
106                        x.clip,
107                        x.users,
108                        x.instances.iter().map(|(p, _)| p.clone()).collect(),
109                    )
110                })
111            })
112            .collect()
113    })
114}
115
116/// The group's key: its resource, as the original's one object per resource; a group with no name
117/// (a test's) by its address.
118fn key(group: &AnimationGroup) -> String {
119    if group.name.is_empty() {
120        format!("@{:p}", group)
121    } else {
122        group.name.clone()
123    }
124}
125
126/// `GetInstanceId`: `entry << 8 | instance`.
127pub fn instance_id(group: &AnimationGroup, clip: usize) -> i32 {
128    let key = key(group);
129    ENTRIES.with(|e| {
130        let mut entries = e.borrow_mut();
131        let found = entries
132            .iter()
133            .position(|x| x.as_ref().is_some_and(|x| x.group == key && x.clip == clip));
134        let index = match found {
135            Some(i) => i,
136            None => {
137                let data = group.clips[clip].clone();
138                let count = data.instance_count.max(1) as usize;
139                let step = super::seconds(data.duration_ticks) * (1.0 / count as f32);
140                let mut at = 0.0f32;
141                let mut instances = Vec::with_capacity(count);
142                for _ in 0..count {
143                    let mut p = Playback::new(clip, super::ticks(at));
144                    for _ in 0..2 {
145                        p.update(&data, 0);
146                    }
147                    let pose = p.pose(&data);
148                    instances.push((p, pose));
149                    at += step;
150                }
151                let entry = Entry {
152                    group: key.clone(),
153                    clip,
154                    users: 0,
155                    data,
156                    instances,
157                };
158                match entries.iter().position(Option::is_none) {
159                    Some(free) => {
160                        entries[free] = Some(entry);
161                        free
162                    }
163                    None => {
164                        entries.push(Some(entry));
165                        entries.len() - 1
166                    }
167                }
168            }
169        };
170        let entry = entries[index].as_mut().unwrap();
171        entry.users += 1;
172        let mut best = (f32::MAX, 0usize);
173        for (k, (p, _)) in entry.instances.iter().enumerate() {
174            let t = super::seconds(p.elapsed);
175            if t < best.0 {
176                best = (t, k);
177            }
178        }
179        ((index as i32) << 8) | best.1 as i32
180    })
181}
182
183/// `FreeInstanceId`.
184pub fn free(id: i32) {
185    ENTRIES.with(|e| {
186        let mut entries = e.borrow_mut();
187        let i = (id >> 8 & 0xff) as usize;
188        if let Some(Some(entry)) = entries.get_mut(i) {
189            entry.users -= 1;
190            if entry.users == 0 {
191                entries[i] = None;
192            }
193        }
194    });
195}
196
197/// `Update`: every instance by `dt`.
198pub fn update(dt: i64) {
199    ENTRIES.with(|e| {
200        for entry in e.borrow_mut().iter_mut().flatten() {
201            for (p, pose) in &mut entry.instances {
202                p.update(&entry.data, dt);
203                *pose = p.pose(&entry.data);
204            }
205        }
206    });
207}
208
209/// The poses of one slot's instances (none for a free slot).
210pub fn poses(slot: usize) -> Vec<Vec<Transform>> {
211    ENTRIES.with(|e| match e.borrow().get(slot) {
212        Some(Some(entry)) => entry.instances.iter().map(|(_, p)| p.clone()).collect(),
213        _ => Vec::new(),
214    })
215}
216
217/// `GetPose`.
218pub fn pose(id: i32) -> Option<Vec<Transform>> {
219    ENTRIES.with(|e| {
220        let entries = e.borrow();
221        let entry = entries.get((id >> 8 & 0xff) as usize)?.as_ref()?;
222        entry
223            .instances
224            .get((id & 0xff) as usize)
225            .map(|(_, pose)| pose.clone())
226    })
227}