shine_gltf/
accessor.rs

1use crate::validation::Checked;
2use crate::{buffer, extensions, Index};
3use serde::{de, ser};
4use serde_derive::{Deserialize, Serialize};
5use serde_json::Value;
6use shine_gltf_macro::Validate;
7use std::fmt;
8
9/// The component data type.
10#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
11pub enum ComponentType {
12    /// Corresponds to `GL_BYTE`.
13    I8 = 1,
14
15    /// Corresponds to `GL_UNSIGNED_BYTE`.
16    U8,
17
18    /// Corresponds to `GL_SHORT`.
19    I16,
20
21    /// Corresponds to `GL_UNSIGNED_SHORT`.
22    U16,
23
24    /// Corresponds to `GL_UNSIGNED_INT`.
25    U32,
26
27    /// Corresponds to `GL_FLOAT`.
28    F32,
29}
30
31/// Specifies whether an attribute, vector, or matrix.
32#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)]
33pub enum Type {
34    /// Scalar quantity.
35    Scalar = 1,
36
37    /// 2D vector.
38    Vec2,
39
40    /// 3D vector.
41    Vec3,
42
43    /// 4D vector.
44    Vec4,
45
46    /// 2x2 matrix.
47    Mat2,
48
49    /// 3x3 matrix.
50    Mat3,
51
52    /// 4x4 matrix.
53    Mat4,
54}
55
56/// Corresponds to `GL_BYTE`.
57pub const BYTE: u32 = 5120;
58
59/// Corresponds to `GL_UNSIGNED_BYTE`.
60pub const UNSIGNED_BYTE: u32 = 5121;
61
62/// Corresponds to `GL_SHORT`.
63pub const SHORT: u32 = 5122;
64
65/// Corresponds to `GL_UNSIGNED_SHORT`.
66pub const UNSIGNED_SHORT: u32 = 5123;
67
68/// Corresponds to `GL_UNSIGNED_INT`.
69pub const UNSIGNED_INT: u32 = 5125;
70
71/// Corresponds to `GL_FLOAT`.
72pub const FLOAT: u32 = 5126;
73
74/// All valid generic vertex attribute component types.
75pub const VALID_COMPONENT_TYPES: &[u32] = &[BYTE, UNSIGNED_BYTE, SHORT, UNSIGNED_SHORT, UNSIGNED_INT, FLOAT];
76
77/// All valid index component types.
78pub const VALID_INDEX_TYPES: &[u32] = &[UNSIGNED_BYTE, UNSIGNED_SHORT, UNSIGNED_INT];
79
80/// All valid accessor types.
81pub const VALID_ACCESSOR_TYPES: &[&str] = &["SCALAR", "VEC2", "VEC3", "VEC4", "MAT2", "MAT3", "MAT4"];
82
83/// Contains data structures for sparse storage.
84pub mod sparse {
85    use super::*;
86    use crate::extensions;
87
88    /// Indices of those attributes that deviate from their initialization value.
89    #[derive(Clone, Debug, Deserialize, Serialize, Validate)]
90    pub struct Indices {
91        /// The parent buffer view containing the sparse indices.
92        ///
93        /// The referenced buffer view must not have `ARRAY_BUFFER` nor
94        /// `ELEMENT_ARRAY_BUFFER` as its target.
95        #[serde(rename = "bufferView")]
96        pub buffer_view: Index<buffer::View>,
97
98        /// The offset relative to the start of the parent `BufferView` in bytes.
99        #[serde(default, rename = "byteOffset")]
100        pub byte_offset: u32,
101
102        /// The data type of each index.
103        #[serde(rename = "componentType")]
104        pub component_type: Checked<IndexComponentType>,
105
106        /// Extension specific data.
107        #[serde(default, skip_serializing_if = "Option::is_none")]
108        pub extensions: Option<extensions::accessor::sparse::Indices>,
109    }
110
111    /// Sparse storage of attributes that deviate from their initialization value.
112    #[derive(Clone, Debug, Deserialize, Serialize, Validate)]
113    pub struct Sparse {
114        /// The number of attributes encoded in this sparse accessor.
115        pub count: u32,
116
117        /// Index array of size `count` that points to those accessor attributes
118        /// that deviate from their initialization value.
119        ///
120        /// Indices must strictly increase.
121        pub indices: Indices,
122
123        /// Array of size `count * number_of_components` storing the displaced
124        /// accessor attributes pointed by `indices`.
125        ///
126        /// Substituted values must have the same `component_type` and number of
127        /// components as the base `Accessor`.
128        pub values: Values,
129
130        /// Extension specific data.
131        #[serde(default, skip_serializing_if = "Option::is_none")]
132        pub extensions: Option<extensions::accessor::sparse::Sparse>,
133    }
134
135    /// Array of size `count * number_of_components` storing the displaced
136    /// accessor attributes pointed by `accessor::sparse::Indices`.
137    #[derive(Clone, Debug, Deserialize, Serialize, Validate)]
138    pub struct Values {
139        /// The parent buffer view containing the sparse indices.
140        ///
141        /// The referenced buffer view must not have `ARRAY_BUFFER` nor
142        /// `ELEMENT_ARRAY_BUFFER` as its target.
143        #[serde(rename = "bufferView")]
144        pub buffer_view: Index<buffer::View>,
145
146        /// The offset relative to the start of the parent buffer view in bytes.
147        #[serde(default, rename = "byteOffset")]
148        pub byte_offset: u32,
149
150        /// Extension specific data.
151        #[serde(default, skip_serializing_if = "Option::is_none")]
152        pub extensions: Option<extensions::accessor::sparse::Values>,
153    }
154}
155
156/// A typed view into a buffer view.
157#[derive(Clone, Debug, Deserialize, Serialize, Validate)]
158pub struct Accessor {
159    /// The parent buffer view this accessor reads from.
160    #[serde(rename = "bufferView")]
161    pub buffer_view: Index<buffer::View>,
162
163    /// The offset relative to the start of the parent `BufferView` in bytes.
164    #[serde(default, rename = "byteOffset")]
165    pub byte_offset: u32,
166
167    /// The number of components within the buffer view - not to be confused
168    /// with the number of bytes in the buffer view.
169    pub count: u32,
170
171    /// The data type of components in the attribute.
172    #[serde(rename = "componentType")]
173    pub component_type: Checked<GenericComponentType>,
174
175    /// Specifies if the attribute is a scalar, vector, or matrix.
176    #[serde(rename = "type")]
177    pub type_: Checked<Type>,
178
179    /// Minimum value of each component in this attribute.
180    #[serde(default)]
181    #[serde(skip_serializing_if = "Option::is_none")]
182    pub min: Option<Value>,
183
184    /// Maximum value of each component in this attribute.
185    #[serde(default)]
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub max: Option<Value>,
188
189    /// Specifies whether integer data values should be normalized.
190    #[serde(default, skip_serializing_if = "is_normalized_default")]
191    pub normalized: bool,
192
193    /// Sparse storage of attributes that deviate from their initialization
194    /// value.
195    #[serde(default)]
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub sparse: Option<sparse::Sparse>,
198
199    /// Extension specific data.
200    #[serde(default, skip_serializing_if = "Option::is_none")]
201    pub extensions: Option<extensions::accessor::Accessor>,
202}
203
204impl Accessor {
205    pub fn with_view(buffer_view: Index<buffer::View>, type_: Type, component_type: ComponentType, normalized: bool) -> Accessor {
206        let component_type: Checked<GenericComponentType> = component_type.into();
207        assert!(
208            component_type.is_valid(),
209            "invalid component type for accessor: {:?}",
210            component_type
211        );
212
213        Accessor {
214            buffer_view,
215            type_: Checked::Valid(type_),
216            component_type,
217            normalized,
218            byte_offset: 0,
219            count: 0,
220            min: None,
221            max: None,
222            sparse: None,
223            extensions: None,
224        }
225    }
226}
227
228// Help serde avoid serializing this glTF 2.0 default value.
229#[allow(clippy::trivially_copy_pass_by_ref)]
230fn is_normalized_default(b: &bool) -> bool {
231    !*b
232}
233
234/// The data type of an index.
235#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
236pub struct IndexComponentType(pub ComponentType);
237
238/// The data type of a generic vertex attribute.
239#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
240pub struct GenericComponentType(pub ComponentType);
241
242impl From<ComponentType> for Checked<GenericComponentType> {
243    fn from(type_: ComponentType) -> Checked<GenericComponentType> {
244        use crate::validation::Checked::*;
245        match type_ {
246            t @ ComponentType::I8
247            | t @ ComponentType::U8
248            | t @ ComponentType::I16
249            | t @ ComponentType::U16
250            | t @ ComponentType::U32
251            | t @ ComponentType::F32 => Valid(GenericComponentType(t)),
252            //_ => Invalid,
253        }
254    }
255}
256
257impl<'de> de::Deserialize<'de> for Checked<GenericComponentType> {
258    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
259    where
260        D: de::Deserializer<'de>,
261    {
262        struct Visitor;
263        impl<'de> de::Visitor<'de> for Visitor {
264            type Value = Checked<GenericComponentType>;
265
266            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267                write!(f, "any of: {:?}", VALID_COMPONENT_TYPES)
268            }
269
270            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
271            where
272                E: de::Error,
273            {
274                use self::ComponentType::*;
275                use crate::validation::Checked::*;
276                Ok(match value as u32 {
277                    BYTE => Valid(GenericComponentType(I8)),
278                    UNSIGNED_BYTE => Valid(GenericComponentType(U8)),
279                    SHORT => Valid(GenericComponentType(I16)),
280                    UNSIGNED_SHORT => Valid(GenericComponentType(U16)),
281                    UNSIGNED_INT => Valid(GenericComponentType(U32)),
282                    FLOAT => Valid(GenericComponentType(F32)),
283                    _ => Invalid,
284                })
285            }
286        }
287        deserializer.deserialize_u64(Visitor)
288    }
289}
290
291impl From<ComponentType> for Checked<IndexComponentType> {
292    fn from(type_: ComponentType) -> Checked<IndexComponentType> {
293        use crate::validation::Checked::*;
294        match type_ {
295            t @ ComponentType::U8 | t @ ComponentType::U16 | t @ ComponentType::U32 => Valid(IndexComponentType(t)),
296            _ => Invalid,
297        }
298    }
299}
300
301impl<'de> de::Deserialize<'de> for Checked<IndexComponentType> {
302    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
303    where
304        D: de::Deserializer<'de>,
305    {
306        struct Visitor;
307        impl<'de> de::Visitor<'de> for Visitor {
308            type Value = Checked<IndexComponentType>;
309
310            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311                write!(f, "any of: {:?}", VALID_INDEX_TYPES)
312            }
313
314            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
315            where
316                E: de::Error,
317            {
318                use self::ComponentType::*;
319                use crate::validation::Checked::*;
320                Ok(match value as u32 {
321                    UNSIGNED_BYTE => Valid(IndexComponentType(U8)),
322                    UNSIGNED_SHORT => Valid(IndexComponentType(U16)),
323                    UNSIGNED_INT => Valid(IndexComponentType(U32)),
324                    _ => Invalid,
325                })
326            }
327        }
328        deserializer.deserialize_u64(Visitor)
329    }
330}
331
332impl<'de> de::Deserialize<'de> for Checked<Type> {
333    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
334    where
335        D: de::Deserializer<'de>,
336    {
337        struct Visitor;
338        impl<'de> de::Visitor<'de> for Visitor {
339            type Value = Checked<Type>;
340
341            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342                write!(f, "any of: {:?}", VALID_ACCESSOR_TYPES)
343            }
344
345            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
346            where
347                E: de::Error,
348            {
349                use self::Type::*;
350                use crate::validation::Checked::*;
351                Ok(match value {
352                    "SCALAR" => Valid(Scalar),
353                    "VEC2" => Valid(Vec2),
354                    "VEC3" => Valid(Vec3),
355                    "VEC4" => Valid(Vec4),
356                    "MAT2" => Valid(Mat2),
357                    "MAT3" => Valid(Mat3),
358                    "MAT4" => Valid(Mat4),
359                    _ => Invalid,
360                })
361            }
362        }
363        deserializer.deserialize_str(Visitor)
364    }
365}
366
367impl ser::Serialize for Type {
368    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
369    where
370        S: ser::Serializer,
371    {
372        serializer.serialize_str(match *self {
373            Type::Scalar => "SCALAR",
374            Type::Vec2 => "VEC2",
375            Type::Vec3 => "VEC3",
376            Type::Vec4 => "VEC4",
377            Type::Mat2 => "MAT2",
378            Type::Mat3 => "MAT3",
379            Type::Mat4 => "MAT4",
380        })
381    }
382}
383
384impl ComponentType {
385    /// Returns the number of bytes this value represents.
386    pub fn size(self) -> usize {
387        use self::ComponentType::*;
388        match self {
389            I8 | U8 => 1,
390            I16 | U16 => 2,
391            F32 | U32 => 4,
392        }
393    }
394
395    /// Returns the corresponding `GLenum`.
396    pub fn as_gl_enum(self) -> u32 {
397        match self {
398            ComponentType::I8 => BYTE,
399            ComponentType::U8 => UNSIGNED_BYTE,
400            ComponentType::I16 => SHORT,
401            ComponentType::U16 => UNSIGNED_SHORT,
402            ComponentType::U32 => UNSIGNED_INT,
403            ComponentType::F32 => FLOAT,
404        }
405    }
406}
407
408impl ser::Serialize for ComponentType {
409    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
410    where
411        S: ser::Serializer,
412    {
413        serializer.serialize_u32(self.as_gl_enum())
414    }
415}
416
417impl Type {
418    /// Returns the equivalent number of scalar quantities this type represents.
419    pub fn multiplicity(self) -> usize {
420        use self::Type::*;
421        match self {
422            Scalar => 1,
423            Vec2 => 2,
424            Vec3 => 3,
425            Vec4 | Mat2 => 4,
426            Mat3 => 9,
427            Mat4 => 16,
428        }
429    }
430}