Skip to main content

yog_body/
lib.rs

1//! Bodies for Yog mods (see `docs/design/yog-body.md`).
2//!
3//! - [`format`]: `.ymodel` skeletons and `.yanim` clips, as written;
4//! - [`model`], [`anim`], [`rig`]: those made ready, posed and layered;
5//! - [`wire`]: the frame a host sends about an entity (with the data it
6//!   keeps, synced from the server) and the [`Ops`] a mod answers with —
7//!   pose vanilla parts, turn the body, draw meshes, disguise, hide, capture;
8//! - [`morph`]: one captured body turning into another;
9//! - [`camera`], [`movement`]: the local player's view and travel step.
10//!
11//! The models and clips a mod ships are registered here by the generated
12//! code (`yog build` compiles `.ymodel`/`.yanim`); [`model`](fn@model) and
13//! [`clip`] find them.
14
15pub mod anim;
16pub mod camera;
17pub mod format;
18pub mod math;
19pub mod model;
20pub mod morph;
21pub mod movement;
22pub mod rig;
23pub mod wire;
24
25use std::collections::HashMap;
26use std::sync::{Arc, LazyLock, RwLock};
27
28pub use anim::{BonePose, Clip, Pose};
29pub use camera::{CameraFrame, CameraOut};
30pub use math::{Mat4, Vec3};
31pub use model::{Model, Quad};
32pub use movement::TravelFrame;
33pub use rig::Rig;
34pub use wire::{Anchor, BoneOp, Capture, Frame, Mesh, Mode, Ops};
35
36#[derive(Default)]
37struct Store {
38    models: HashMap<String, Arc<Model>>,
39    /// `(anim id, clip name)` → clip.
40    clips: HashMap<(String, String), Arc<Clip>>,
41}
42
43static STORE: LazyLock<RwLock<Store>> = LazyLock::new(Default::default);
44
45/// Registers model `id` (`ns:name`) from its compiled `.ymodel`.
46pub fn register_model(id: &str, data: &[u8]) -> Result<(), String> {
47    let file: format::ModelFile = yog_data::read_bytes(data).map_err(|e| format!("model {id}: {e:?}"))?;
48    let model = Model::new(&file).map_err(|e| format!("model {id}: {e}"))?;
49    STORE.write().unwrap_or_else(|e| e.into_inner()).models.insert(id.to_owned(), Arc::new(model));
50    Ok(())
51}
52
53/// Registers the clips of `id` (`ns:name`) from its compiled `.yanim`.
54pub fn register_anims(id: &str, data: &[u8]) -> Result<(), String> {
55    let file: format::AnimFile = yog_data::read_bytes(data).map_err(|e| format!("animations {id}: {e:?}"))?;
56    let clips = anim::Clips::new(&file).map_err(|e| format!("animations {id}: {e}"))?;
57    let mut store = STORE.write().unwrap_or_else(|e| e.into_inner());
58    for c in clips.0 {
59        store.clips.insert((id.to_owned(), c.name.clone()), Arc::new(c));
60    }
61    Ok(())
62}
63
64/// Model `id`, if registered.
65pub fn model(id: &str) -> Option<Arc<Model>> {
66    STORE.read().unwrap_or_else(|e| e.into_inner()).models.get(id).cloned()
67}
68
69/// Clip `name` of animations `id`, if registered.
70pub fn clip(id: &str, name: &str) -> Option<Arc<Clip>> {
71    STORE.read().unwrap_or_else(|e| e.into_inner()).clips.get(&(id.to_owned(), name.to_owned())).cloned()
72}