Skip to main content

gltf_json/
accessor.rs

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