veloren_voxygen/scene/terrain/
sprite.rs

1use std::ops::Range;
2
3use super::SPRITE_LOD_LEVELS;
4use common::{
5    assets,
6    terrain::{
7        Block, SpriteKind,
8        sprite::{self, RelativeNeighborPosition},
9    },
10};
11use hashbrown::HashMap;
12use serde::Deserialize;
13use vek::*;
14
15#[derive(Deserialize, Debug)]
16/// Configuration data for an individual sprite model.
17#[serde(deny_unknown_fields)]
18pub(super) struct SpriteModelConfig {
19    /// Data for the .vox model associated with this sprite.
20    pub model: String,
21    /// Sprite model center (as an offset from 0 in the .vox file).
22    pub offset: (f32, f32, f32),
23    /// LOD axes (how LOD gets applied along each axis, when we switch
24    /// to an LOD model).
25    pub lod_axes: (f32, f32, f32),
26}
27
28macro_rules! impl_sprite_attribute_filter {
29    (
30        $($attr:ident $field_name:ident = |$filter_arg:ident: $filter_ty:ty, $value_arg:ident| $filter:block),+ $(,)?
31    ) => {
32        // TODO: depending on what types of filters we end up with an enum may end up being more suitable.
33        #[derive(Debug, Clone, Deserialize, Default, PartialEq, Eq, Hash)]
34        #[serde(default, deny_unknown_fields)]
35        pub struct SpriteAttributeFilters {
36            $(
37                pub $field_name: Option<$filter_ty>,
38            )+
39        }
40
41        impl SpriteAttributeFilters {
42            fn matches_filter(&self, block: &Block) -> bool {
43                $(
44                    self.$field_name.as_ref().map_or(true, |$filter_arg| {
45                        block
46                            .get_attr::<sprite::$attr>()
47                            .map_or(false, |$value_arg| $filter)
48                    })
49                )&&+
50            }
51
52            #[cfg(test)]
53            fn is_valid_for_category(&self, category: sprite::Category) -> Result<(), &'static str> {
54                $(if self.$field_name.is_some() && !category.has_attr::<sprite::$attr>() {
55                    return Err(::std::any::type_name::<sprite::$attr>());
56                })*
57                Ok(())
58            }
59
60            fn no_filters(&self) -> bool {
61                true $(&& self.$field_name.is_none())+
62            }
63        }
64    };
65}
66
67impl_sprite_attribute_filter!(
68    Growth growth_stage = |filter: Range<u8>, growth| { filter.contains(&growth.0) },
69    LightEnabled light_enabled = |filter: bool, light_enabled| { *filter == light_enabled.0 },
70    Damage damage = |filter: Range<u8>, damage| { filter.contains(&damage.0) },
71    AdjacentType adjacent_type = |filter: RelativeNeighborPosition, adjacent_type| { (*filter as u8) == adjacent_type.0 },
72    SnowCovered snow_covered = |filter: bool, snow_covered| { *filter == snow_covered.0 },
73);
74
75/// Configuration data for a group of sprites (currently associated with a
76/// particular SpriteKind).
77#[derive(Deserialize, Debug)]
78#[serde(deny_unknown_fields)]
79struct SpriteConfig {
80    /// Filter for selecting what config to use based on sprite attributes.
81    #[serde(default)]
82    filter: SpriteAttributeFilters,
83    /// All possible model variations for this sprite.
84    // NOTE: Could make constant per sprite type, but eliminating this indirection and
85    // allocation is probably not that important considering how sprites are used.
86    #[serde(default)]
87    variations: Vec<SpriteModelConfig>,
88    /// The extent to which the sprite sways in the wind.
89    ///
90    /// 0.0 is normal.
91    #[serde(default)]
92    wind_sway: f32,
93}
94
95#[serde_with::serde_as]
96#[derive(Deserialize)]
97struct SpriteSpecRaw(
98    #[serde_as(as = "serde_with::MapPreventDuplicates<_, _>")]
99    HashMap<SpriteKind, Vec<SpriteConfig>>,
100);
101
102/// Configuration data for all sprite models.
103///
104/// NOTE: Model is an asset path to the appropriate sprite .vox model.
105#[derive(Deserialize)]
106#[serde(try_from = "SpriteSpecRaw")]
107pub struct SpriteSpec(HashMap<SpriteKind, Vec<SpriteConfig>>);
108
109/// Conversion of [`SpriteSpec`] from a hashmap failed because some sprite kinds
110/// were missing.
111struct SpritesMissing(Vec<SpriteKind>);
112
113impl core::fmt::Display for SpritesMissing {
114    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115        writeln!(
116            f,
117            "Missing entries in the sprite manifest for these sprites: {:?}",
118            &self.0,
119        )
120    }
121}
122
123impl TryFrom<SpriteSpecRaw> for SpriteSpec {
124    type Error = SpritesMissing;
125
126    fn try_from(SpriteSpecRaw(map): SpriteSpecRaw) -> Result<Self, Self::Error> {
127        let sprites_missing = SpriteKind::all()
128            .iter()
129            .copied()
130            .filter(|kind| !map.contains_key(kind))
131            .collect::<Vec<_>>();
132
133        if sprites_missing.is_empty() {
134            Ok(Self(map))
135        } else {
136            Err(SpritesMissing(sprites_missing))
137        }
138    }
139}
140
141impl assets::Asset for SpriteSpec {
142    type Loader = assets::RonLoader;
143
144    const EXTENSION: &'static str = "ron";
145}
146
147impl SpriteSpec {
148    pub fn map_to_data(
149        &self,
150        mut map_variation: impl FnMut(&SpriteModelConfig) -> [SpriteModelData; super::SPRITE_LOD_LEVELS],
151    ) -> HashMap<SpriteKind, FilteredSpriteData> {
152        let mut to_sprite_data = |config: &SpriteConfig| SpriteData {
153            variations: config.variations.iter().map(&mut map_variation).collect(),
154            wind_sway: config.wind_sway,
155        };
156
157        // Note, the returned datastructure can potentially be optimized further from a
158        // HashMap, a phf could be used or if we can rely on the sprite kind
159        // discriminants in each sprite category being packed fairly densely, we
160        // could just have an offset per sprite catagory used to
161        // convert a sprite kind into a flat index.
162        self.0
163            .iter()
164            .map(|(kind, config)| {
165                let filtered_data = match config.as_slice() {
166                    [config] if config.filter.no_filters() => {
167                        FilteredSpriteData::Unfiltered(to_sprite_data(config))
168                    },
169                    // Note, we have a test that checks if this is completely empty. That should be
170                    // represented by an entry with no variantions instead of having an empty
171                    // top-level list.
172                    filtered_configs => {
173                        let list = filtered_configs
174                            .iter()
175                            .map(|config| (config.filter.clone(), to_sprite_data(config)))
176                            .collect::<Box<[_]>>();
177                        FilteredSpriteData::Filtered(list)
178                    },
179                };
180                (*kind, filtered_data)
181            })
182            .collect()
183    }
184}
185
186pub(in crate::scene) struct SpriteModelData {
187    // Sprite vert page ranges that need to be drawn
188    pub vert_pages: core::ops::Range<u32>,
189    // Scale
190    pub scale: Vec3<f32>,
191    // Offset
192    pub offset: Vec3<f32>,
193}
194
195pub(in crate::scene) struct SpriteData {
196    pub variations: Box<[[SpriteModelData; SPRITE_LOD_LEVELS]]>,
197    /// See [`SpriteConfig::wind_sway`].
198    pub wind_sway: f32,
199}
200
201pub(in crate::scene) enum FilteredSpriteData {
202    // Special case when there is only one entry with the an empty filter since this is most
203    // cases, and it will reduce indirection.
204    Unfiltered(SpriteData),
205    Filtered(Box<[(SpriteAttributeFilters, SpriteData)]>),
206}
207
208impl FilteredSpriteData {
209    /// Gets sprite data for the filter that matches the provided block.
210    ///
211    /// This only returns `None` if no filters matches the provided block (i.e.
212    /// the set of filters does not cover all values). A "missing"
213    /// placeholder model can be displayed in this case in this case.
214    pub fn for_block(&self, block: &Block) -> Option<&SpriteData> {
215        match self {
216            Self::Unfiltered(data) => Some(data),
217            Self::Filtered(multiple) => multiple
218                .iter()
219                .find_map(|(filter, data)| filter.matches_filter(block).then_some(data)),
220        }
221    }
222}
223
224#[cfg(test)]
225mod test {
226    use super::SpriteSpec;
227    use common_assets::AssetExt;
228
229    #[test]
230    fn test_sprite_spec_valid() {
231        let spec = SpriteSpec::load_expect("voxygen.voxel.sprite_manifest").read();
232
233        // Test that filters are relevant for the particular sprite kind.
234        for (sprite, filter) in spec.0.iter().flat_map(|(&sprite, configs)| {
235            configs.iter().map(move |config| (sprite, &config.filter))
236        }) {
237            if let Err(invalid_attribute) = filter.is_valid_for_category(sprite.category()) {
238                panic!(
239                    "Sprite category '{:?}' does not have attribute '{}' (in sprite config for \
240                     {:?})",
241                    sprite.category(),
242                    invalid_attribute,
243                    sprite,
244                );
245            }
246        }
247
248        // Test that there is at least one entry per sprite. An empty variations list in
249        // an entry is used to represent a sprite that doesn't have a model.
250        let mut empty_config = Vec::new();
251        for (kind, configs) in &spec.0 {
252            if configs.is_empty() {
253                empty_config.push(kind)
254            }
255        }
256        assert!(
257            empty_config.is_empty(),
258            "Sprite config(s) with no entries, if these sprite(s) are intended to have no models \
259             use an explicit entry with an empty `variations` list instead: {empty_config:?}",
260        );
261    }
262}