Skip to main content

yog_body/
model.rs

1//! A `.ymodel` made ready to draw: its bones in order, each cube baked into
2//! the quads vanilla's `ModelPart.Cube` makes (same corners, same box-UV,
3//! same mirroring) — so a model drawn here looks as one drawn by the game.
4
5use crate::format::{CubeDef, ModelFile};
6use crate::math::{Mat4, Vec3, rad};
7
8/// One four-cornered face: corners, their UVs (0–1), its normal.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Quad {
11    pub pos: [Vec3; 4],
12    pub uv: [[f32; 2]; 4],
13    pub normal: Vec3,
14}
15
16impl Quad {
17    /// This quad moved by `m`.
18    pub fn transformed(&self, m: &Mat4) -> Quad {
19        Quad {
20            pos: self.pos.map(|p| m.transform_point(p)),
21            uv: self.uv,
22            normal: m.transform_normal(self.normal),
23        }
24    }
25
26    /// The middle of its corners.
27    pub fn center(&self) -> Vec3 {
28        (self.pos[0] + self.pos[1] + self.pos[2] + self.pos[3]) * 0.25
29    }
30}
31
32/// A bone, ready.
33#[derive(Debug, Clone)]
34pub struct Bone {
35    pub name: String,
36    /// Index of its parent in [`Model::bones`] (always before it).
37    pub parent: Option<usize>,
38    /// Pixels.
39    pub pivot: Vec3,
40    /// Radians.
41    pub rotation: Vec3,
42    /// Its cubes' faces, in its own space (pixels).
43    pub quads: Vec<Quad>,
44    pub locators: Vec<(String, Vec3)>,
45}
46
47/// A model, ready.
48#[derive(Debug, Clone)]
49pub struct Model {
50    /// The texture as the host loads it (`ns:textures/….png`).
51    pub texture: String,
52    pub bones: Vec<Bone>,
53}
54
55impl Model {
56    /// Builds `file`. Errors name what's wrong (an unknown or later
57    /// parent, a repeated name).
58    pub fn new(file: &ModelFile) -> Result<Model, String> {
59        let texture = texture_resource(&file.texture);
60        let [tw, th] = file.texture_size.map(|n| n.max(1) as f32);
61        let mut bones: Vec<Bone> = Vec::with_capacity(file.bones.len());
62        for b in &file.bones {
63            if bones.iter().any(|o| o.name == b.name) {
64                return Err(format!("bone `{}` comes twice", b.name));
65            }
66            let parent = match &b.parent {
67                None => None,
68                Some(p) => Some(
69                    bones
70                        .iter()
71                        .position(|o| &o.name == p)
72                        .ok_or_else(|| format!("bone `{}`: its parent `{p}` must come before it", b.name))?,
73                ),
74            };
75            bones.push(Bone {
76                name: b.name.clone(),
77                parent,
78                pivot: Vec3::from_array(b.pivot),
79                rotation: rad(Vec3::from_array(b.rotation)),
80                quads: b.cubes.iter().flat_map(|c| cube(c, tw, th)).collect(),
81                locators: b.locators.0.iter().map(|(n, p)| (n.clone(), Vec3::from_array(*p))).collect(),
82            });
83        }
84        Ok(Model { texture, bones })
85    }
86
87    pub fn bone(&self, name: &str) -> Option<usize> {
88        self.bones.iter().position(|b| b.name == name)
89    }
90}
91
92/// The texture as the host loads it: `<ns>:textures/<path>.png`.
93pub fn texture_resource(id: &str) -> String {
94    let (ns, path) = yog_ids::split(id);
95    yog_ids::join(ns, &yog_ids::texture_file(path))
96}
97
98/// `ModelPart.Cube`'s six faces.
99pub fn cube(c: &CubeDef, tex_w: f32, tex_h: f32) -> [Quad; 6] {
100    let [x, y, z] = c.origin;
101    let [w, h, d] = c.size;
102    let [u, v] = c.uv;
103    let g = c.inflate;
104    let (mut x0, y0, z0) = (x - g, y - g, z - g);
105    let (mut x1, y1, z1) = (x + w + g, y + h + g, z + d + g);
106    if c.mirror {
107        std::mem::swap(&mut x0, &mut x1);
108    }
109    let p = |x, y, z| Vec3::new(x, y, z);
110    let (v7, v0, v1, v2) = (p(x0, y0, z0), p(x1, y0, z0), p(x1, y1, z0), p(x0, y1, z0));
111    let (v3, v4, v5, v6) = (p(x0, y0, z1), p(x1, y0, z1), p(x1, y1, z1), p(x0, y1, z1));
112    let (u0, u1, u2, u3, u4, u5) = (u, u + d, u + d + w, u + d + w + w, u + d + w + d, u + d + w + d + w);
113    let (t0, t1, t2) = (v, v + d, v + d + h);
114    let face = |corners: [Vec3; 4], ua: f32, va: f32, ub: f32, vb: f32, normal: Vec3| {
115        let mut pos = corners;
116        let mut uv = [[ub / tex_w, va / tex_h], [ua / tex_w, va / tex_h], [ua / tex_w, vb / tex_h], [ub / tex_w, vb / tex_h]];
117        let mut n = normal;
118        if c.mirror {
119            pos.reverse();
120            uv.reverse();
121            n.x = -n.x;
122        }
123        Quad { pos, uv, normal: n }
124    };
125    [
126        face([v4, v3, v7, v0], u1, t0, u2, t1, Vec3::new(0.0, -1.0, 0.0)),
127        face([v1, v2, v6, v5], u2, t1, u3, t0, Vec3::new(0.0, 1.0, 0.0)),
128        face([v7, v3, v6, v2], u0, t1, u1, t2, Vec3::new(-1.0, 0.0, 0.0)),
129        face([v0, v7, v2, v1], u1, t1, u2, t2, Vec3::new(0.0, 0.0, -1.0)),
130        face([v4, v0, v1, v5], u2, t1, u4, t2, Vec3::new(1.0, 0.0, 0.0)),
131        face([v3, v4, v5, v6], u4, t1, u5, t2, Vec3::new(0.0, 0.0, 1.0)),
132    ]
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    fn wing() -> CubeDef {
140        CubeDef { origin: [-10.0, 0.0, 0.0], size: [10.0, 20.0, 2.0], uv: [22.0, 0.0], inflate: 1.0, mirror: false }
141    }
142
143    #[test]
144    fn a_cube_is_vanillas() {
145        let q = cube(&wing(), 64.0, 32.0);
146        // DOWN: v4, v3, v7, v0 with UVs from (d, 0) to (d + w, d).
147        assert_eq!(q[0].pos[0], Vec3::new(1.0, -1.0, 3.0));
148        assert_eq!(q[0].uv[0], [34.0 / 64.0, 0.0]);
149        assert_eq!(q[0].uv[1], [24.0 / 64.0, 0.0]);
150        assert_eq!(q[3].normal, Vec3::new(0.0, 0.0, -1.0));
151    }
152
153    #[test]
154    fn a_mirrored_cube_turns_its_faces() {
155        let mut c = wing();
156        c.mirror = true;
157        let q = cube(&c, 64.0, 32.0);
158        assert_eq!(q[2].normal, Vec3::new(1.0, 0.0, 0.0));
159        assert_eq!(q[0].pos[3], Vec3::new(-11.0, -1.0, 3.0));
160    }
161
162    #[test]
163    fn a_texture_is_loaded_from_its_resource() {
164        assert_eq!(texture_resource("minecraft:entity/elytra"), "minecraft:textures/entity/elytra.png");
165    }
166}