From c61d27cb0f2296ce8ba8a69c9534a8da3e4c703a Mon Sep 17 00:00:00 2001 From: Samuel Hurel Date: Sat, 29 Jan 2022 10:27:28 +0100 Subject: [PATCH 1/2] rustfmt pass --- examples/export/main.rs | 38 +++-- examples/tree/main.rs | 2 +- gltf-json/src/accessor.rs | 72 ++++---- gltf-json/src/animation.rs | 62 +++---- gltf-json/src/asset.rs | 5 +- gltf-json/src/buffer.rs | 25 ++- gltf-json/src/camera.rs | 34 ++-- gltf-json/src/extensions/accessor.rs | 2 +- gltf-json/src/extensions/animation.rs | 2 +- gltf-json/src/extensions/asset.rs | 2 +- gltf-json/src/extensions/buffer.rs | 2 +- gltf-json/src/extensions/camera.rs | 2 +- gltf-json/src/extensions/image.rs | 2 +- gltf-json/src/extensions/material.rs | 67 ++++++-- gltf-json/src/extensions/mesh.rs | 8 +- gltf-json/src/extensions/root.rs | 28 +++- gltf-json/src/extensions/scene.rs | 39 +++-- gltf-json/src/extensions/skin.rs | 2 +- gltf-json/src/extensions/texture.rs | 6 +- gltf-json/src/extras.rs | 2 +- gltf-json/src/image.rs | 7 +- gltf-json/src/lib.rs | 4 +- gltf-json/src/material.rs | 20 ++- gltf-json/src/mesh.rs | 79 +++++---- gltf-json/src/root.rs | 41 +++-- gltf-json/src/scene.rs | 4 +- gltf-json/src/skin.rs | 4 +- gltf-json/src/texture.rs | 32 ++-- gltf-json/src/validation.rs | 39 +++-- gltf-json/tests/test_validation.rs | 36 ++-- rustfmt.toml | 0 src/accessor/mod.rs | 11 +- src/accessor/sparse.rs | 27 ++- src/accessor/util.rs | 90 ++++++---- src/animation/iter.rs | 16 +- src/animation/mod.rs | 36 ++-- src/animation/util/mod.rs | 55 +++--- src/animation/util/morph_target_weights.rs | 18 +- src/animation/util/rotations.rs | 18 +- src/binary.rs | 112 ++++++++----- src/buffer.rs | 27 ++- src/camera.rs | 10 +- src/image.rs | 23 +-- src/import.rs | 64 +++---- src/iter.rs | 186 +++++++++++++++------ src/khr_lights_punctual.rs | 10 +- src/khr_materials_variants.rs | 19 ++- src/lib.rs | 159 +++++++++++++----- src/material.rs | 43 ++--- src/math.rs | 98 ++++++----- src/mesh/iter.rs | 60 ++++--- src/mesh/mod.rs | 146 +++++++++------- src/mesh/util/colors.rs | 62 ++++--- src/mesh/util/indices.rs | 20 ++- src/mesh/util/joints.rs | 8 +- src/mesh/util/mod.rs | 11 +- src/mesh/util/tex_coords.rs | 8 +- src/mesh/util/weights.rs | 8 +- src/scene/iter.rs | 8 +- src/scene/mod.rs | 83 +++++---- src/skin/mod.rs | 28 +--- src/texture.rs | 15 +- tests/import_sanity_check.rs | 2 +- tests/roundtrip_binary_gltf.rs | 7 +- tests/test_wrapper.rs | 12 +- 65 files changed, 1309 insertions(+), 859 deletions(-) create mode 100644 rustfmt.toml diff --git a/examples/export/main.rs b/examples/export/main.rs index 498ca62e..ce521cee 100644 --- a/examples/export/main.rs +++ b/examples/export/main.rs @@ -60,7 +60,11 @@ fn export(output: Output) { extensions: Default::default(), extras: Default::default(), name: None, - uri: if output == Output::Standard { Some("buffer0.bin".into()) } else { None }, + uri: if output == Output::Standard { + Some("buffer0.bin".into()) + } else { + None + }, }; let buffer_view = json::buffer::View { buffer: json::Index::new(0), @@ -76,7 +80,9 @@ fn export(output: Output) { buffer_view: Some(json::Index::new(0)), byte_offset: 0, count: triangle_vertices.len() as u32, - component_type: Valid(json::accessor::GenericComponentType(json::accessor::ComponentType::F32)), + component_type: Valid(json::accessor::GenericComponentType( + json::accessor::ComponentType::F32, + )), extensions: Default::default(), extras: Default::default(), type_: Valid(json::accessor::Type::Vec3), @@ -90,7 +96,9 @@ fn export(output: Output) { buffer_view: Some(json::Index::new(0)), byte_offset: (3 * mem::size_of::()) as u32, count: triangle_vertices.len() as u32, - component_type: Valid(json::accessor::GenericComponentType(json::accessor::ComponentType::F32)), + component_type: Valid(json::accessor::GenericComponentType( + json::accessor::ComponentType::F32, + )), extensions: Default::default(), extras: Default::default(), type_: Valid(json::accessor::Type::Vec3), @@ -145,15 +153,13 @@ fn export(output: Output) { buffer_views: vec![buffer_view], meshes: vec![mesh], nodes: vec![node], - scenes: vec![ - json::Scene { - extensions: Default::default(), - extras: Default::default(), - name: None, - nodes: vec![json::Index::new(0)], - }, - ], - .. Default::default() + scenes: vec![json::Scene { + extensions: Default::default(), + extras: Default::default(), + name: None, + nodes: vec![json::Index::new(0)], + }], + ..Default::default() }; match output { @@ -166,10 +172,9 @@ fn export(output: Output) { let bin = to_padded_byte_vector(triangle_vertices); let mut writer = fs::File::create("triangle/buffer0.bin").expect("I/O error"); writer.write_all(&bin).expect("I/O error"); - }, + } Output::Binary => { - let json_string = json::serialize::to_string(&root) - .expect("Serialization error"); + let json_string = json::serialize::to_string(&root).expect("Serialization error"); let mut json_offset = json_string.len() as u32; align_to_multiple_of_four(&mut json_offset); let glb = gltf::binary::Glb { @@ -183,8 +188,7 @@ fn export(output: Output) { }; let writer = std::fs::File::create("triangle.glb").expect("I/O error"); glb.to_writer(writer).expect("glTF binary output error"); - - }, + } } } diff --git a/examples/tree/main.rs b/examples/tree/main.rs index a89bbd66..4e0040c2 100644 --- a/examples/tree/main.rs +++ b/examples/tree/main.rs @@ -1,6 +1,6 @@ -use std::{fs, io}; use std::boxed::Box; use std::error::Error as StdError; +use std::{fs, io}; fn print_tree(node: &gltf::Node, depth: i32) { for _ in 0..(depth - 1) { diff --git a/gltf-json/src/accessor.rs b/gltf-json/src/accessor.rs index f399fb41..56dedc0e 100644 --- a/gltf-json/src/accessor.rs +++ b/gltf-json/src/accessor.rs @@ -1,29 +1,24 @@ +use crate::validation::{Checked, Error, Validate}; +use crate::{buffer, extensions, Extras, Index, Path, Root}; use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; -use crate::{buffer, extensions, Extras, Index, Root, Path}; use serde::{de, ser}; +use serde_derive::{Deserialize, Serialize}; use serde_json::Value; use std::fmt; -use crate::validation::{Checked, Error, Validate}; /// The component data type. #[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)] pub enum ComponentType { /// Corresponds to `GL_BYTE`. I8 = 1, - /// Corresponds to `GL_UNSIGNED_BYTE`. U8, - /// Corresponds to `GL_SHORT`. I16, - /// Corresponds to `GL_UNSIGNED_SHORT`. U16, - /// Corresponds to `GL_UNSIGNED_INT`. U32, - /// Corresponds to `GL_FLOAT`. F32, } @@ -33,22 +28,16 @@ pub enum ComponentType { pub enum Type { /// Scalar quantity. Scalar = 1, - /// 2D vector. Vec2, - /// 3D vector. Vec3, - /// 4D vector. Vec4, - /// 2x2 matrix. Mat2, - /// 3x3 matrix. Mat3, - /// 4x4 matrix. Mat4, } @@ -82,13 +71,15 @@ pub const VALID_COMPONENT_TYPES: &'static [u32] = &[ ]; /// All valid index component types. +#[rustfmt::skip] pub const VALID_INDEX_TYPES: &'static [u32] = &[ UNSIGNED_BYTE, UNSIGNED_SHORT, - UNSIGNED_INT, + UNSIGNED_INT ]; /// All valid accessor types. +#[rustfmt::skip] pub const VALID_ACCESSOR_TYPES: &'static [&'static str] = &[ "SCALAR", "VEC2", @@ -96,7 +87,7 @@ pub const VALID_ACCESSOR_TYPES: &'static [&'static str] = &[ "VEC4", "MAT2", "MAT3", - "MAT4", + "MAT4" ]; /// Contains data structures for sparse storage. @@ -238,7 +229,7 @@ pub struct Accessor { /// Specifies whether integer data values should be normalized. #[serde(default, skip_serializing_if = "is_normalized_default")] pub normalized: bool, - + /// Sparse storage of attributes that deviate from their initialization /// value. #[serde(default)] @@ -248,7 +239,9 @@ pub struct Accessor { impl Validate for Accessor { fn validate(&self, root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { if self.sparse.is_none() && self.buffer_view.is_none() { // If sparse is missing, then bufferView must be present. Report that bufferView is @@ -256,17 +249,24 @@ impl Validate for Accessor { report(&|| path().field("bufferView"), Error::Missing); } - self.buffer_view.validate(root, || path().field("bufferView"), report); - self.byte_offset.validate(root, || path().field("byteOffset"), report); + self.buffer_view + .validate(root, || path().field("bufferView"), report); + self.byte_offset + .validate(root, || path().field("byteOffset"), report); self.count.validate(root, || path().field("count"), report); - self.component_type.validate(root, || path().field("componentType"), report); - self.extensions.validate(root, || path().field("extensions"), report); - self.extras.validate(root, || path().field("extras"), report); + self.component_type + .validate(root, || path().field("componentType"), report); + self.extensions + .validate(root, || path().field("extensions"), report); + self.extras + .validate(root, || path().field("extras"), report); self.type_.validate(root, || path().field("type"), report); self.min.validate(root, || path().field("min"), report); self.max.validate(root, || path().field("max"), report); - self.normalized.validate(root, || path().field("normalized"), report); - self.sparse.validate(root, || path().field("sparse"), report); + self.normalized + .validate(root, || path().field("normalized"), report); + self.sparse + .validate(root, || path().field("sparse"), report); } } @@ -285,7 +285,8 @@ pub struct GenericComponentType(pub ComponentType); impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -296,7 +297,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_u64(self, value: u64) -> Result - where E: de::Error + where + E: de::Error, { use self::ComponentType::*; use crate::validation::Checked::*; @@ -317,7 +319,8 @@ impl<'de> de::Deserialize<'de> for Checked { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -328,7 +331,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_u64(self, value: u64) -> Result - where E: de::Error + where + E: de::Error, { use self::ComponentType::*; use crate::validation::Checked::*; @@ -346,7 +350,8 @@ impl<'de> de::Deserialize<'de> for Checked { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -357,7 +362,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_str(self, value: &str) -> Result - where E: de::Error + where + E: de::Error, { use self::Type::*; use crate::validation::Checked::*; @@ -380,7 +386,7 @@ impl<'de> de::Deserialize<'de> for Checked { impl ser::Serialize for Type { fn serialize(&self, serializer: S) -> Result where - S: ser::Serializer + S: ser::Serializer, { serializer.serialize_str(match *self { Type::Scalar => "SCALAR", @@ -421,7 +427,7 @@ impl ComponentType { impl ser::Serialize for ComponentType { fn serialize(&self, serializer: S) -> Result where - S: ser::Serializer + S: ser::Serializer, { serializer.serialize_u32(self.as_gl_enum()) } diff --git a/gltf-json/src/animation.rs b/gltf-json/src/animation.rs index 234b4629..3ef85778 100644 --- a/gltf-json/src/animation.rs +++ b/gltf-json/src/animation.rs @@ -1,23 +1,25 @@ +use crate::validation::{Checked, Error, Validate}; +use crate::{accessor, extensions, scene, Extras, Index, Path, Root}; use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use serde::{de, ser}; +use serde_derive::{Deserialize, Serialize}; use std::fmt; -use crate::validation::{Checked, Error, Validate}; -use crate::{accessor, extensions, scene, Extras, Index, Path, Root}; /// All valid animation interpolation algorithms. +#[rustfmt::skip] pub const VALID_INTERPOLATIONS: &'static [&'static str] = &[ "LINEAR", "STEP", - "CUBICSPLINE", + "CUBICSPLINE" ]; /// All valid animation property names. +#[rustfmt::skip] pub const VALID_PROPERTIES: &'static [&'static str] = &[ "translation", "rotation", "scale", - "weights", + "weights" ]; /// Specifies an interpolation algorithm. @@ -53,13 +55,10 @@ pub enum Interpolation { pub enum Property { /// XYZ translation vector. Translation = 1, - /// XYZW rotation quaternion. Rotation, - /// XYZ scale vector. Scale, - /// Weights of morph targets. MorphTargetWeights, } @@ -70,24 +69,24 @@ pub struct Animation { /// Extension specific data. #[serde(default, skip_serializing_if = "Option::is_none")] pub extensions: Option, - + /// Optional application specific data. #[serde(default)] #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))] pub extras: Extras, - + /// An array of channels, each of which targets an animation's sampler at a /// node's property. /// /// Different channels of the same animation must not have equal targets. #[serde(skip_serializing_if = "Vec::is_empty")] pub channels: Vec, - + /// Optional user-defined name for this object. #[cfg(feature = "names")] #[cfg_attr(feature = "names", serde(skip_serializing_if = "Option::is_none"))] pub name: Option, - + /// An array of samplers that combine input and output accessors with an /// interpolation algorithm to define a keyframe graph (but not its target). #[serde(skip_serializing_if = "Vec::is_empty")] @@ -100,14 +99,14 @@ pub struct Channel { /// The index of a sampler in this animation used to compute the value for the /// target. pub sampler: Index, - + /// The index of the node and TRS property to target. pub target: Target, - + /// Extension specific data. #[serde(default, skip_serializing_if = "Option::is_none")] pub extensions: Option, - + /// Optional application specific data. #[serde(default)] #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))] @@ -120,15 +119,15 @@ pub struct Target { /// Extension specific data. #[serde(default, skip_serializing_if = "Option::is_none")] pub extensions: Option, - + /// Optional application specific data. #[serde(default)] #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))] pub extras: Extras, - + /// The index of the node to target. pub node: Index, - + /// The name of the node's property to modify or the 'weights' of the /// morph targets it instantiates. pub path: Checked, @@ -140,19 +139,19 @@ pub struct Sampler { /// Extension specific data. #[serde(default, skip_serializing_if = "Option::is_none")] pub extensions: Option, - + /// Optional application specific data. #[serde(default)] #[cfg_attr(feature = "extras", serde(skip_serializing_if = "Option::is_none"))] pub extras: Extras, - + /// The index of an accessor containing keyframe input values, e.g., time. pub input: Index, - + /// The interpolation algorithm. #[serde(default)] pub interpolation: Checked, - + /// The index of an accessor containing keyframe output values. pub output: Index, } @@ -163,7 +162,8 @@ impl Validate for Animation { P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error), { - self.samplers.validate(root, || path().field("samplers"), report); + self.samplers + .validate(root, || path().field("samplers"), report); for (index, channel) in self.channels.iter().enumerate() { if channel.sampler.value() as usize >= self.samplers.len() { let path = || path().field("channels").index(index).field("sampler"); @@ -181,7 +181,8 @@ impl Default for Interpolation { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -192,7 +193,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_str(self, value: &str) -> Result - where E: de::Error + where + E: de::Error, { use self::Interpolation::*; use crate::validation::Checked::*; @@ -211,7 +213,7 @@ impl<'de> de::Deserialize<'de> for Checked { impl ser::Serialize for Interpolation { fn serialize(&self, serializer: S) -> Result where - S: ser::Serializer + S: ser::Serializer, { serializer.serialize_str(match *self { Interpolation::Linear => "LINEAR", @@ -223,7 +225,8 @@ impl ser::Serialize for Interpolation { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -234,7 +237,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_str(self, value: &str) -> Result - where E: de::Error + where + E: de::Error, { use self::Property::*; use crate::validation::Checked::*; @@ -254,7 +258,7 @@ impl<'de> de::Deserialize<'de> for Checked { impl ser::Serialize for Property { fn serialize(&self, serializer: S) -> Result where - S: ser::Serializer + S: ser::Serializer, { serializer.serialize_str(match *self { Property::Translation => "translation", diff --git a/gltf-json/src/asset.rs b/gltf-json/src/asset.rs index d9064907..3e6baf34 100644 --- a/gltf-json/src/asset.rs +++ b/gltf-json/src/asset.rs @@ -1,6 +1,6 @@ -use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use crate::{extensions, Extras}; +use gltf_derive::Validate; +use serde_derive::{Deserialize, Serialize}; /// Metadata about the glTF asset. #[derive(Clone, Debug, Deserialize, Serialize, Validate)] @@ -43,4 +43,3 @@ impl Default for Asset { } } } - diff --git a/gltf-json/src/buffer.rs b/gltf-json/src/buffer.rs index 98d1a78f..c2626cd5 100644 --- a/gltf-json/src/buffer.rs +++ b/gltf-json/src/buffer.rs @@ -1,9 +1,9 @@ +use crate::validation::Checked; +use crate::{extensions, Extras, Index}; use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use serde::{de, ser}; +use serde_derive::{Deserialize, Serialize}; use std::fmt; -use crate::validation::Checked; -use crate::{extensions, Extras, Index}; /// Corresponds to `GL_ARRAY_BUFFER`. pub const ARRAY_BUFFER: u32 = 34_962; @@ -18,9 +18,10 @@ pub const MIN_BYTE_STRIDE: u32 = 4; pub const MAX_BYTE_STRIDE: u32 = 252; /// All valid GPU buffer targets. +#[rustfmt::skip] pub const VALID_TARGETS: &'static [u32] = &[ ARRAY_BUFFER, - ELEMENT_ARRAY_BUFFER, + ELEMENT_ARRAY_BUFFER ]; /// Specifies the target a GPU buffer should be bound to. @@ -35,7 +36,8 @@ pub enum Target { impl ser::Serialize for Target { fn serialize(&self, serializer: S) -> Result - where S: ser::Serializer + where + S: ser::Serializer, { match *self { Target::ArrayBuffer => serializer.serialize_u32(ARRAY_BUFFER), @@ -85,7 +87,11 @@ pub struct View { pub byte_length: u32, /// Offset into the parent buffer in bytes. - #[serde(default, rename = "byteOffset", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "byteOffset", + skip_serializing_if = "Option::is_none" + )] pub byte_offset: Option, /// The stride in bytes between vertex attributes or other interleavable data. @@ -116,7 +122,8 @@ pub struct View { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -127,7 +134,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_u64(self, value: u64) -> Result - where E: de::Error + where + E: de::Error, { use self::Target::*; use crate::validation::Checked::*; @@ -141,4 +149,3 @@ impl<'de> de::Deserialize<'de> for Checked { deserializer.deserialize_u64(Visitor) } } - diff --git a/gltf-json/src/camera.rs b/gltf-json/src/camera.rs index 43827990..7b973a84 100644 --- a/gltf-json/src/camera.rs +++ b/gltf-json/src/camera.rs @@ -1,14 +1,15 @@ +use crate::validation::{Checked, Error, Validate}; +use crate::{extensions, Extras, Path, Root}; use gltf_derive::Validate; use serde::{de, ser}; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; use std::fmt; -use crate::validation::{Checked, Error, Validate}; -use crate::{extensions, Extras, Root, Path}; /// All valid camera types. +#[rustfmt::skip] pub const VALID_CAMERA_TYPES: &'static [&'static str] = &[ "perspective", - "orthographic", + "orthographic" ]; /// Specifies the camera type. @@ -111,23 +112,30 @@ pub struct Perspective { impl Validate for Camera { fn validate(&self, root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { if self.orthographic.is_none() && self.perspective.is_none() { report(&path, Error::Missing); } - self.orthographic.validate(root, || path().field("orthographic"), report); - self.perspective.validate(root, || path().field("perspective"), report); + self.orthographic + .validate(root, || path().field("orthographic"), report); + self.perspective + .validate(root, || path().field("perspective"), report); self.type_.validate(root, || path().field("type"), report); - self.extensions.validate(root, || path().field("extensions"), report); - self.extras.validate(root, || path().field("extras"), report); + self.extensions + .validate(root, || path().field("extensions"), report); + self.extras + .validate(root, || path().field("extras"), report); } } impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -138,7 +146,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_str(self, value: &str) -> Result - where E: de::Error + where + E: de::Error, { use self::Type::*; use crate::validation::Checked::*; @@ -155,7 +164,8 @@ impl<'de> de::Deserialize<'de> for Checked { impl ser::Serialize for Type { fn serialize(&self, serializer: S) -> Result - where S: ser::Serializer + where + S: ser::Serializer, { match *self { Type::Perspective => serializer.serialize_str("perspective"), diff --git a/gltf-json/src/extensions/accessor.rs b/gltf-json/src/extensions/accessor.rs index 1f6fbf14..a10f996f 100644 --- a/gltf-json/src/extensions/accessor.rs +++ b/gltf-json/src/extensions/accessor.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// Contains data structures for sparse storage. pub mod sparse { diff --git a/gltf-json/src/extensions/animation.rs b/gltf-json/src/extensions/animation.rs index 54b9ea39..7809d707 100644 --- a/gltf-json/src/extensions/animation.rs +++ b/gltf-json/src/extensions/animation.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// A keyframe animation. #[derive(Clone, Debug, Default, Deserialize, Serialize)] diff --git a/gltf-json/src/extensions/asset.rs b/gltf-json/src/extensions/asset.rs index c947c9af..8c375987 100644 --- a/gltf-json/src/extensions/asset.rs +++ b/gltf-json/src/extensions/asset.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// Metadata about the glTF asset. #[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)] diff --git a/gltf-json/src/extensions/buffer.rs b/gltf-json/src/extensions/buffer.rs index a402fc60..40876ce8 100644 --- a/gltf-json/src/extensions/buffer.rs +++ b/gltf-json/src/extensions/buffer.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// A buffer points to binary data representing geometry, animations, or skins. #[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)] diff --git a/gltf-json/src/extensions/camera.rs b/gltf-json/src/extensions/camera.rs index 5b70d99f..fda9400e 100644 --- a/gltf-json/src/extensions/camera.rs +++ b/gltf-json/src/extensions/camera.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// A camera's projection. /// diff --git a/gltf-json/src/extensions/image.rs b/gltf-json/src/extensions/image.rs index b02c92c5..f29ddea2 100644 --- a/gltf-json/src/extensions/image.rs +++ b/gltf-json/src/extensions/image.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// Image data used to create a texture. #[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)] diff --git a/gltf-json/src/extensions/material.rs b/gltf-json/src/extensions/material.rs index e7c97d2e..adf67d5c 100644 --- a/gltf-json/src/extensions/material.rs +++ b/gltf-json/src/extensions/material.rs @@ -1,37 +1,68 @@ -use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; -#[cfg(any(feature = "KHR_materials_pbrSpecularGlossiness", feature = "KHR_materials_transmission", feature = "KHR_materials_ior"))] -use crate::{Extras, validation::Validate}; -#[cfg(any(feature = "KHR_materials_pbrSpecularGlossiness", feature = "KHR_materials_transmission"))] -use crate::texture; #[cfg(feature = "KHR_materials_pbrSpecularGlossiness")] use crate::material::StrengthFactor; +#[cfg(any( + feature = "KHR_materials_pbrSpecularGlossiness", + feature = "KHR_materials_transmission" +))] +use crate::texture; +#[cfg(any( + feature = "KHR_materials_pbrSpecularGlossiness", + feature = "KHR_materials_transmission", + feature = "KHR_materials_ior" +))] +use crate::{validation::Validate, Extras}; +use gltf_derive::Validate; +use serde_derive::{Deserialize, Serialize}; /// The material appearance of a primitive. #[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)] pub struct Material { #[cfg(feature = "KHR_materials_pbrSpecularGlossiness")] - #[serde(default, rename = "KHR_materials_pbrSpecularGlossiness", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_materials_pbrSpecularGlossiness", + skip_serializing_if = "Option::is_none" + )] pub pbr_specular_glossiness: Option, #[cfg(feature = "KHR_materials_unlit")] - #[serde(default, rename = "KHR_materials_unlit", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_materials_unlit", + skip_serializing_if = "Option::is_none" + )] pub unlit: Option, #[cfg(feature = "KHR_materials_transmission")] - #[serde(default, rename = "KHR_materials_transmission", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_materials_transmission", + skip_serializing_if = "Option::is_none" + )] pub transmission: Option, #[cfg(feature = "KHR_materials_volume")] - #[serde(default, rename = "KHR_materials_volume", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_materials_volume", + skip_serializing_if = "Option::is_none" + )] pub volume: Option, #[cfg(feature = "KHR_materials_specular")] - #[serde(default, rename = "KHR_materials_specular", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_materials_specular", + skip_serializing_if = "Option::is_none" + )] pub specular: Option, #[cfg(feature = "KHR_materials_ior")] - #[serde(default, rename = "KHR_materials_ior", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_materials_ior", + skip_serializing_if = "Option::is_none" + )] pub ior: Option, } @@ -155,17 +186,17 @@ impl Validate for TransmissionFactor {} pub struct Transmission { /// The base percentage of light that is transmitted through the surface. /// - /// The amount of light that is transmitted by the surface rather than diffusely re-emitted. - /// This is a percentage of all the light that penetrates a surface (i.e. isn’t specularly reflected) - /// rather than a percentage of the total light that hits a surface. + /// The amount of light that is transmitted by the surface rather than diffusely re-emitted. + /// This is a percentage of all the light that penetrates a surface (i.e. isn’t specularly reflected) + /// rather than a percentage of the total light that hits a surface. /// A value of 1.0 means that 100% of the light that penetrates the surface is transmitted through. pub transmission_factor: TransmissionFactor, /// The transmission texture. /// - /// The R channel of this texture defines the amount of light that is transmitted by the surface + /// The R channel of this texture defines the amount of light that is transmitted by the surface /// rather than diffusely re-emitted. A value of 1.0 in the red channel means that 100% of the light - /// that penetrates the surface (i.e. isn’t specularly reflected) is transmitted through. + /// that penetrates the surface (i.e. isn’t specularly reflected) is transmitted through. /// The value is linear and is multiplied by the transmissionFactor to determine the total transmission value. #[serde(skip_serializing_if = "Option::is_none")] pub transmission_texture: Option, @@ -196,7 +227,7 @@ impl Validate for IndexOfRefraction {} pub struct Ior { /// The index of refraction. /// - /// Typical values for the index of refraction range from 1 to 2. + /// Typical values for the index of refraction range from 1 to 2. /// In rare cases values greater than 2 are possible. /// For example, the ior of water is 1.33, and diamond is 2.42 pub ior: IndexOfRefraction, diff --git a/gltf-json/src/extensions/mesh.rs b/gltf-json/src/extensions/mesh.rs index 92b555a4..39b6165f 100644 --- a/gltf-json/src/extensions/mesh.rs +++ b/gltf-json/src/extensions/mesh.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// A set of primitives to be rendered. /// @@ -12,7 +12,11 @@ pub struct Mesh {} #[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)] pub struct Primitive { #[cfg(feature = "KHR_materials_variants")] - #[serde(default, rename = "KHR_materials_variants", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_materials_variants", + skip_serializing_if = "Option::is_none" + )] pub khr_materials_variants: Option, } diff --git a/gltf-json/src/extensions/root.rs b/gltf-json/src/extensions/root.rs index 819b7c0a..64449969 100644 --- a/gltf-json/src/extensions/root.rs +++ b/gltf-json/src/extensions/root.rs @@ -1,15 +1,23 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// The root object of a glTF 2.0 asset. #[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)] pub struct Root { #[cfg(feature = "KHR_lights_punctual")] - #[serde(default, rename = "KHR_lights_punctual", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_lights_punctual", + skip_serializing_if = "Option::is_none" + )] pub khr_lights_punctual: Option, #[cfg(feature = "KHR_materials_variants")] - #[serde(default, rename = "KHR_materials_variants", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_materials_variants", + skip_serializing_if = "Option::is_none" + )] pub khr_materials_variants: Option, } @@ -22,9 +30,10 @@ pub struct KhrLightsPunctual { #[cfg(feature = "KHR_lights_punctual")] impl crate::root::Get for crate::Root { - fn get(&self, id: crate::Index) - -> Option<&crate::extensions::scene::khr_lights_punctual::Light> - { + fn get( + &self, + id: crate::Index, + ) -> Option<&crate::extensions::scene::khr_lights_punctual::Light> { if let Some(extensions) = self.extensions.as_ref() { if let Some(khr_lights_punctual) = extensions.khr_lights_punctual.as_ref() { khr_lights_punctual.lights.get(id.value()) @@ -45,9 +54,10 @@ pub struct KhrMaterialsVariants { #[cfg(feature = "KHR_materials_variants")] impl crate::root::Get for crate::Root { - fn get(&self, id: crate::Index) - -> Option<&crate::extensions::scene::khr_materials_variants::Variant> - { + fn get( + &self, + id: crate::Index, + ) -> Option<&crate::extensions::scene::khr_materials_variants::Variant> { self.extensions .as_ref()? .khr_materials_variants diff --git a/gltf-json/src/extensions/scene.rs b/gltf-json/src/extensions/scene.rs index cea9cd6a..e3689ca9 100644 --- a/gltf-json/src/extensions/scene.rs +++ b/gltf-json/src/extensions/scene.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// A node in the node hierarchy. When the node contains `skin`, all /// `mesh.primitives` must contain `JOINTS_0` and `WEIGHTS_0` attributes. @@ -14,24 +14,29 @@ use serde_derive::{Serialize, Deserialize}; #[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)] pub struct Node { #[cfg(feature = "KHR_lights_punctual")] - #[serde(default, rename = "KHR_lights_punctual", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_lights_punctual", + skip_serializing_if = "Option::is_none" + )] pub khr_lights_punctual: Option, } #[cfg(feature = "KHR_lights_punctual")] pub mod khr_lights_punctual { - use crate::{Extras, Index, Root, Path}; use crate::validation::{Checked, Error, Validate}; + use crate::{Extras, Index, Path, Root}; use gltf_derive::Validate; use serde::{de, ser}; use serde_derive::{Deserialize, Serialize}; use std::fmt; /// All valid light types. + #[rustfmt::skip] pub const VALID_TYPES: &'static [&'static str] = &[ "directional", "point", - "spot", + "spot" ]; #[derive(Clone, Debug, Deserialize, Serialize, Validate)] @@ -111,7 +116,9 @@ pub mod khr_lights_punctual { impl Validate for Light { fn validate(&self, root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { if let Checked::Valid(ty) = self.type_.as_ref() { if *ty == Type::Spot && self.spot.is_none() { @@ -120,8 +127,10 @@ pub mod khr_lights_punctual { } self.type_.validate(root, || path().field("type"), report); - self.extensions.validate(root, || path().field("extensions"), report); - self.extras.validate(root, || path().field("extras"), report); + self.extensions + .validate(root, || path().field("extensions"), report); + self.extras + .validate(root, || path().field("extras"), report); } } @@ -152,7 +161,8 @@ pub mod khr_lights_punctual { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -163,7 +173,8 @@ pub mod khr_lights_punctual { } fn visit_str(self, value: &str) -> Result - where E: de::Error + where + E: de::Error, { use self::Type::*; use crate::validation::Checked::*; @@ -181,8 +192,8 @@ pub mod khr_lights_punctual { impl ser::Serialize for Type { fn serialize(&self, serializer: S) -> Result - where - S: ser::Serializer + where + S: ser::Serializer, { serializer.serialize_str(match *self { Type::Directional => "directional", @@ -195,8 +206,8 @@ pub mod khr_lights_punctual { #[cfg(feature = "KHR_materials_variants")] pub mod khr_materials_variants { - use crate::{Extras, Index, Root, Path}; use crate::validation::{Checked, Error, Validate}; + use crate::{Extras, Index, Path, Root}; use gltf_derive::Validate; use serde::{de, ser}; use serde_derive::{Deserialize, Serialize}; @@ -209,7 +220,9 @@ pub mod khr_materials_variants { impl Validate for Variant { fn validate(&self, root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { self.name.validate(root, || path().field("name"), report); } diff --git a/gltf-json/src/extensions/skin.rs b/gltf-json/src/extensions/skin.rs index d73a2215..6861a6f1 100644 --- a/gltf-json/src/extensions/skin.rs +++ b/gltf-json/src/extensions/skin.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; /// Joints and matrices defining a skin. #[derive(Clone, Debug, Default, Deserialize, Serialize, Validate)] diff --git a/gltf-json/src/extensions/texture.rs b/gltf-json/src/extensions/texture.rs index c7a3ef7a..0755cfc0 100644 --- a/gltf-json/src/extensions/texture.rs +++ b/gltf-json/src/extensions/texture.rs @@ -15,7 +15,11 @@ pub struct Texture {} /// Reference to a `Texture`. pub struct Info { #[cfg(feature = "KHR_texture_transform")] - #[serde(default, rename = "KHR_texture_transform", skip_serializing_if = "Option::is_none")] + #[serde( + default, + rename = "KHR_texture_transform", + skip_serializing_if = "Option::is_none" + )] pub texture_transform: Option, } diff --git a/gltf-json/src/extras.rs b/gltf-json/src/extras.rs index eab20b26..4d5f9e15 100644 --- a/gltf-json/src/extras.rs +++ b/gltf-json/src/extras.rs @@ -1,5 +1,5 @@ use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; +use serde_derive::{Deserialize, Serialize}; use std::fmt; #[cfg(feature = "extras")] diff --git a/gltf-json/src/image.rs b/gltf-json/src/image.rs index dfa2b73b..e56c7b00 100644 --- a/gltf-json/src/image.rs +++ b/gltf-json/src/image.rs @@ -1,12 +1,13 @@ -use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use crate::validation::Validate; use crate::{buffer, extensions, Extras, Index}; +use gltf_derive::Validate; +use serde_derive::{Deserialize, Serialize}; /// All valid MIME types. +#[rustfmt::skip] pub const VALID_MIME_TYPES: &'static [&'static str] = &[ "image/jpeg", - "image/png", + "image/png" ]; /// Image data used to create a texture. diff --git a/gltf-json/src/lib.rs b/gltf-json/src/lib.rs index e3db343c..95251508 100644 --- a/gltf-json/src/lib.rs +++ b/gltf-json/src/lib.rs @@ -101,5 +101,7 @@ pub mod deserialize { /// so that one can serialize data structures other than `Root` without /// being bound to a specific version of `serde_json`. pub mod serialize { - pub use serde_json::{to_string, to_string_pretty, to_value, to_vec, to_vec_pretty, to_writer, to_writer_pretty}; + pub use serde_json::{ + to_string, to_string_pretty, to_value, to_vec, to_vec_pretty, to_writer, to_writer_pretty, + }; } diff --git a/gltf-json/src/material.rs b/gltf-json/src/material.rs index a86f1d85..33b2f74d 100644 --- a/gltf-json/src/material.rs +++ b/gltf-json/src/material.rs @@ -1,15 +1,16 @@ +use crate::validation::{Checked, Validate}; +use crate::{extensions, texture, Extras, Index}; use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use serde::{de, ser}; +use serde_derive::{Deserialize, Serialize}; use std::fmt; -use crate::validation::{Checked, Validate}; -use crate::{extensions, texture, Extras, Index}; /// All valid alpha modes. +#[rustfmt::skip] pub const VALID_ALPHA_MODES: &'static [&'static str] = &[ "OPAQUE", "MASK", - "BLEND", + "BLEND" ]; /// The alpha rendering mode of a material. @@ -29,7 +30,8 @@ pub enum AlphaMode { impl ser::Serialize for AlphaMode { fn serialize(&self, serializer: S) -> Result - where S: ser::Serializer + where + S: ser::Serializer, { match *self { AlphaMode::Opaque => serializer.serialize_str("OPAQUE"), @@ -48,7 +50,7 @@ pub struct Material { //#[cfg_attr(feature = "alphaCutoff", serde(skip_serializing_if = "Option::is_none"))] #[serde(skip_serializing_if = "Option::is_none")] pub alpha_cutoff: Option, - + /// The alpha rendering mode of the material. /// /// The material's alpha rendering mode enumeration specifying the @@ -262,7 +264,8 @@ impl Default for AlphaMode { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -273,7 +276,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_str(self, value: &str) -> Result - where E: de::Error + where + E: de::Error, { use self::AlphaMode::*; use crate::validation::Checked::*; diff --git a/gltf-json/src/mesh.rs b/gltf-json/src/mesh.rs index bae2b82c..bead3ba3 100644 --- a/gltf-json/src/mesh.rs +++ b/gltf-json/src/mesh.rs @@ -1,11 +1,11 @@ +use crate::validation::{Checked, Error, Validate}; +use crate::{accessor, extensions, material, Extras, Index}; use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use serde::{de, ser}; +use serde_derive::{Deserialize, Serialize}; use serde_json::from_value; use std::collections::HashMap; use std::fmt; -use crate::validation::{Checked, Error, Validate}; -use crate::{accessor, extensions, material, Extras, Index}; /// Corresponds to `GL_POINTS`. pub const POINTS: u32 = 0; @@ -40,10 +40,11 @@ pub const VALID_MODES: &'static [u32] = &[ ]; /// All valid semantic names for Morph targets. +#[rustfmt::skip] pub const VALID_MORPH_TARGETS: &'static [&'static str] = &[ "POSITION", "NORMAL", - "TANGENT", + "TANGENT" ]; /// The type of primitives to render. @@ -140,22 +141,29 @@ fn is_primitive_mode_default(mode: &Checked) -> bool { impl Validate for Primitive { fn validate(&self, root: &crate::Root, path: P, report: &mut R) - where + where P: Fn() -> crate::Path, R: FnMut(&dyn Fn() -> crate::Path, crate::validation::Error), { // Generated part - self.attributes.validate(root, || path().field("attributes"), report); - self.extensions.validate(root, || path().field("extensions"), report); - self.extras.validate(root, || path().field("extras"), report); - self.indices.validate(root, || path().field("indices"), report); - self.material.validate(root, || path().field("material"), report); + self.attributes + .validate(root, || path().field("attributes"), report); + self.extensions + .validate(root, || path().field("extensions"), report); + self.extras + .validate(root, || path().field("extras"), report); + self.indices + .validate(root, || path().field("indices"), report); + self.material + .validate(root, || path().field("material"), report); self.mode.validate(root, || path().field("mode"), report); - self.targets.validate(root, || path().field("targets"), report); + self.targets + .validate(root, || path().field("targets"), report); // Custom part let position_path = &|| path().field("attributes").key("POSITION"); - if let Some(pos_accessor_index) = self.attributes.get(&Checked::Valid(Semantic::Positions)) { + if let Some(pos_accessor_index) = self.attributes.get(&Checked::Valid(Semantic::Positions)) + { // spec: POSITION accessor **must** have `min` and `max` properties defined. let pos_accessor = &root.accessors[pos_accessor_index.value()]; @@ -254,7 +262,8 @@ impl Mode { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -265,7 +274,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_u64(self, value: u64) -> Result - where E: de::Error + where + E: de::Error, { use self::Mode::*; use crate::validation::Checked::*; @@ -304,29 +314,21 @@ impl Semantic { "TANGENT" => Valid(Tangents), #[cfg(feature = "extras")] _ if s.starts_with("_") => Valid(Extras(s[1..].to_string())), - _ if s.starts_with("COLOR_") => { - match s["COLOR_".len()..].parse() { - Ok(set) => Valid(Colors(set)), - Err(_) => Invalid, - } + _ if s.starts_with("COLOR_") => match s["COLOR_".len()..].parse() { + Ok(set) => Valid(Colors(set)), + Err(_) => Invalid, }, - _ if s.starts_with("TEXCOORD_") => { - match s["TEXCOORD_".len()..].parse() { - Ok(set) => Valid(TexCoords(set)), - Err(_) => Invalid, - } + _ if s.starts_with("TEXCOORD_") => match s["TEXCOORD_".len()..].parse() { + Ok(set) => Valid(TexCoords(set)), + Err(_) => Invalid, }, - _ if s.starts_with("JOINTS_") => { - match s["JOINTS_".len()..].parse() { - Ok(set) => Valid(Joints(set)), - Err(_) => Invalid, - } + _ if s.starts_with("JOINTS_") => match s["JOINTS_".len()..].parse() { + Ok(set) => Valid(Joints(set)), + Err(_) => Invalid, }, - _ if s.starts_with("WEIGHTS_") => { - match s["WEIGHTS_".len()..].parse() { - Ok(set) => Valid(Weights(set)), - Err(_) => Invalid, - } + _ if s.starts_with("WEIGHTS_") => match s["WEIGHTS_".len()..].parse() { + Ok(set) => Valid(Weights(set)), + Err(_) => Invalid, }, _ => Invalid, } @@ -335,7 +337,8 @@ impl Semantic { impl ser::Serialize for Semantic { fn serialize(&self, serializer: S) -> Result - where S: ser::Serializer + where + S: ser::Serializer, { serializer.serialize_str(&self.to_string()) } @@ -369,7 +372,8 @@ impl ToString for Checked { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -380,7 +384,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_str(self, value: &str) -> Result - where E: de::Error + where + E: de::Error, { Ok(Semantic::checked(value)) } diff --git a/gltf-json/src/root.rs b/gltf-json/src/root.rs index 6d2bd569..da6ac83c 100644 --- a/gltf-json/src/root.rs +++ b/gltf-json/src/root.rs @@ -1,14 +1,17 @@ -use gltf_derive::Validate; use crate::buffer; use crate::extensions; -use serde_derive::{Serialize, Deserialize}; -use std::{self, fmt, io, marker}; use crate::texture; use crate::validation; +use gltf_derive::Validate; +use serde_derive::{Deserialize, Serialize}; +use std::{self, fmt, io, marker}; use crate::path::Path; +use crate::{ + Accessor, Animation, Asset, Buffer, Camera, Error, Extras, Image, Material, Mesh, Node, Scene, + Skin, Texture, Value, +}; use validation::Validate; -use crate::{Accessor, Animation, Asset, Buffer, Camera, Error, Extras, Image, Material, Mesh, Node, Scene, Skin, Texture, Value}; /// Helper trait for retrieving top-level objects by a universal identifier. pub trait Get { @@ -117,7 +120,8 @@ pub struct Root { impl Root { /// Returns a single item from the root object. pub fn get(&self, index: Index) -> Option<&T> - where Self: Get + where + Self: Get, { (self as &dyn Get).get(index) } @@ -134,7 +138,8 @@ impl Root { /// Deserialize from a stream of JSON. pub fn from_reader(reader: R) -> Result - where R: io::Read + where + R: io::Read, { serde_json::from_reader(reader) } @@ -166,14 +171,16 @@ impl Root { /// Serialize as a JSON byte writertor. pub fn to_writer(&self, writer: W) -> Result<(), Error> - where W: io::Write, + where + W: io::Write, { serde_json::to_writer(writer, self) } /// Serialize as a pretty-printed JSON byte writertor. pub fn to_writer_pretty(&self, writer: W) -> Result<(), Error> - where W: io::Write, + where + W: io::Write, { serde_json::to_writer_pretty(writer, self) } @@ -193,7 +200,8 @@ impl Index { impl serde::Serialize for Index { fn serialize(&self, serializer: S) -> Result - where S: ::serde::Serializer + where + S: ::serde::Serializer, { serializer.serialize_u64(self.value() as u64) } @@ -201,7 +209,8 @@ impl serde::Serialize for Index { impl<'de, T> serde::Deserialize<'de> for Index { fn deserialize(deserializer: D) -> Result - where D: serde::Deserializer<'de> + where + D: serde::Deserializer<'de>, { struct Visitor(marker::PhantomData); impl<'de, T> serde::de::Visitor<'de> for Visitor { @@ -212,7 +221,8 @@ impl<'de, T> serde::Deserialize<'de> for Index { } fn visit_u64(self, value: u64) -> Result - where E: serde::de::Error + where + E: serde::de::Error, { Ok(Index::new(value as u32)) } @@ -245,10 +255,13 @@ impl fmt::Display for Index { } impl Validate for Index - where Root: Get +where + Root: Get, { fn validate(&self, root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, validation::Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, validation::Error), { if root.get(*self).is_none() { report(&path, validation::Error::IndexOutOfBounds); @@ -263,7 +276,7 @@ macro_rules! impl_get { self.$field.get(index.value()) } } - } + }; } impl_get!(Accessor, accessors); diff --git a/gltf-json/src/scene.rs b/gltf-json/src/scene.rs index bbae30bc..cc24fb87 100644 --- a/gltf-json/src/scene.rs +++ b/gltf-json/src/scene.rs @@ -1,7 +1,7 @@ -use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use crate::validation::Validate; use crate::{camera, extensions, mesh, scene, skin, Extras, Index}; +use gltf_derive::Validate; +use serde_derive::{Deserialize, Serialize}; /// A node in the node hierarchy. When the node contains `skin`, all /// `mesh.primitives` must contain `JOINTS_0` and `WEIGHTS_0` attributes. diff --git a/gltf-json/src/skin.rs b/gltf-json/src/skin.rs index 01cbb9b8..39fa5408 100644 --- a/gltf-json/src/skin.rs +++ b/gltf-json/src/skin.rs @@ -1,6 +1,6 @@ -use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use crate::{accessor, extensions, scene, Extras, Index}; +use gltf_derive::Validate; +use serde_derive::{Deserialize, Serialize}; /// Joints and matrices defining a skin. #[derive(Clone, Debug, Deserialize, Serialize, Validate)] diff --git a/gltf-json/src/texture.rs b/gltf-json/src/texture.rs index 31e7f992..a8000bad 100644 --- a/gltf-json/src/texture.rs +++ b/gltf-json/src/texture.rs @@ -1,9 +1,9 @@ +use crate::validation::Checked; +use crate::{extensions, image, Extras, Index}; use gltf_derive::Validate; -use serde_derive::{Serialize, Deserialize}; use serde::{de, ser}; +use serde_derive::{Deserialize, Serialize}; use std::fmt; -use crate::validation::Checked; -use crate::{extensions, image, Extras, Index}; /// Corresponds to `GL_NEAREST`. pub const NEAREST: u32 = 9728; @@ -33,10 +33,7 @@ pub const MIRRORED_REPEAT: u32 = 33_648; pub const REPEAT: u32 = 10_497; /// All valid magnification filters. -pub const VALID_MAG_FILTERS: &'static [u32] = &[ - NEAREST, - LINEAR, -]; +pub const VALID_MAG_FILTERS: &'static [u32] = &[NEAREST, LINEAR]; /// All valid minification filters. pub const VALID_MIN_FILTERS: &'static [u32] = &[ @@ -49,10 +46,11 @@ pub const VALID_MIN_FILTERS: &'static [u32] = &[ ]; /// All valid wrapping modes. +#[rustfmt::skip] pub const VALID_WRAPPING_MODES: &'static [u32] = &[ CLAMP_TO_EDGE, MIRRORED_REPEAT, - REPEAT, + REPEAT ]; /// Magnification filter. @@ -219,7 +217,8 @@ pub struct Info { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -230,7 +229,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_u64(self, value: u64) -> Result - where E: de::Error + where + E: de::Error, { use self::MagFilter::*; use crate::validation::Checked::*; @@ -247,7 +247,8 @@ impl<'de> de::Deserialize<'de> for Checked { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -258,7 +259,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_u64(self, value: u64) -> Result - where E: de::Error + where + E: de::Error, { use self::MinFilter::*; use crate::validation::Checked::*; @@ -288,7 +290,8 @@ impl ser::Serialize for MinFilter { impl<'de> de::Deserialize<'de> for Checked { fn deserialize(deserializer: D) -> Result - where D: de::Deserializer<'de> + where + D: de::Deserializer<'de>, { struct Visitor; impl<'de> de::Visitor<'de> for Visitor { @@ -299,7 +302,8 @@ impl<'de> de::Deserialize<'de> for Checked { } fn visit_u64(self, value: u64) -> Result - where E: de::Error + where + E: de::Error, { use self::WrappingMode::*; use crate::validation::Checked::*; diff --git a/gltf-json/src/validation.rs b/gltf-json/src/validation.rs index d42905e9..6bdc4408 100644 --- a/gltf-json/src/validation.rs +++ b/gltf-json/src/validation.rs @@ -63,7 +63,8 @@ impl Checked { impl Serialize for Checked { fn serialize(&self, serializer: S) -> Result - where S: Serializer + where + S: Serializer, { match *self { Checked::Valid(ref item) => item.serialize(serializer), @@ -91,10 +92,12 @@ impl Default for Checked { impl Validate for Checked { fn validate(&self, _root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { match *self { - Checked::Valid(_) => {}, + Checked::Valid(_) => {} Checked::Invalid => report(&path, Error::Invalid), } } @@ -102,7 +105,9 @@ impl Validate for Checked { impl Validate for HashMap { fn validate(&self, root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { for (key, value) in self.iter() { key.validate(root, || path().key(&key.to_string()), report); @@ -113,7 +118,9 @@ impl Validate for HashMap impl Validate for Option { fn validate(&self, root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { if let Some(value) = self.as_ref() { value.validate(root, path, report); @@ -123,7 +130,9 @@ impl Validate for Option { impl Validate for Vec { fn validate(&self, root: &Root, path: P, report: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { for (index, value) in self.iter().enumerate() { value.validate(root, || path().index(index), report); @@ -133,7 +142,9 @@ impl Validate for Vec { impl Validate for std::boxed::Box { fn validate(&self, _: &Root, _: P, _: &mut R) - where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error) + where + P: Fn() -> Path, + R: FnMut(&dyn Fn() -> Path, Error), { // nop } @@ -143,11 +154,15 @@ impl std::error::Error for Error {} impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{}", match *self { - Error::IndexOutOfBounds => "Index out of bounds", - Error::Invalid => "Invalid value", - Error::Missing => "Missing data", - }) + write!( + f, + "{}", + match *self { + Error::IndexOutOfBounds => "Index out of bounds", + Error::Invalid => "Invalid value", + Error::Missing => "Missing data", + } + ) } } diff --git a/gltf-json/tests/test_validation.rs b/gltf-json/tests/test_validation.rs index e990f186..1e868939 100644 --- a/gltf-json/tests/test_validation.rs +++ b/gltf-json/tests/test_validation.rs @@ -1,6 +1,6 @@ use std::{fs, io}; -use gltf_json::validation::{Validate, Error}; +use gltf_json::validation::{Error, Validate}; use gltf_json::Path; fn import_json(filename: &str) -> gltf_json::Root { @@ -14,25 +14,33 @@ fn test_accessor_bounds_validate() { // file with missing min/max values let json = import_json("tests/minimal_accessor_invalid.gltf"); let mut errs = vec![]; - json.validate( - &json, - gltf_json::Path::new, - &mut |path, err| errs.push((path(), err)), + json.validate(&json, gltf_json::Path::new, &mut |path, err| { + errs.push((path(), err)) + }); + assert_eq!( + errs, + [ + ( + Path("meshes[0].primitives[0].attributes[\"POSITION\"].min".into()), + Error::Missing + ), + ( + Path("meshes[0].primitives[0].attributes[\"POSITION\"].max".into()), + Error::Invalid + ) + ] ); - assert_eq!(errs, - [(Path("meshes[0].primitives[0].attributes[\"POSITION\"].min".into()), Error::Missing), - (Path("meshes[0].primitives[0].attributes[\"POSITION\"].max".into()), Error::Invalid)]); } #[test] fn test_non_sparse_accessor_without_buffer_view_validate() { let json = import_json("tests/non_sparse_accessor_without_buffer_view.gltf"); let mut errs = vec![]; - json.validate( - &json, - gltf_json::Path::new, - &mut |path, err| errs.push((path(), err)), + json.validate(&json, gltf_json::Path::new, &mut |path, err| { + errs.push((path(), err)) + }); + assert_eq!( + errs, + [(Path("accessors[0].bufferView".into()), Error::Missing)] ); - assert_eq!(errs, - [(Path("accessors[0].bufferView".into()), Error::Missing)]); } diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 00000000..e69de29b diff --git a/src/accessor/mod.rs b/src/accessor/mod.rs index b4e52af7..96c2a6c0 100644 --- a/src/accessor/mod.rs +++ b/src/accessor/mod.rs @@ -113,7 +113,9 @@ impl<'a> Accessor<'a> { /// /// This may be `None` if the corresponding accessor is sparse. pub fn view(&self) -> Option> { - self.json.buffer_view.map(|view| self.document.views().nth(view.value()).unwrap()) + self.json + .buffer_view + .map(|view| self.document.views().nth(view.value()).unwrap()) } /// Returns the offset relative to the start of the parent buffer view in bytes. @@ -167,8 +169,9 @@ impl<'a> Accessor<'a> { /// Returns sparse storage of attributes that deviate from their initialization /// value. pub fn sparse(&self) -> Option> { - self.json.sparse.as_ref().map(|json| { - sparse::Sparse::new(self.document, json) - }) + self.json + .sparse + .as_ref() + .map(|json| sparse::Sparse::new(self.document, json)) } } diff --git a/src/accessor/sparse.rs b/src/accessor/sparse.rs index 30c35cfd..3b62f096 100644 --- a/src/accessor/sparse.rs +++ b/src/accessor/sparse.rs @@ -24,10 +24,7 @@ pub struct Indices<'a> { impl<'a> Indices<'a> { /// Constructs `sparse::Indices`. - pub(crate) fn new( - document: &'a Document, - json: &'a json::accessor::sparse::Indices, - ) -> Self { + pub(crate) fn new(document: &'a Document, json: &'a json::accessor::sparse::Indices) -> Self { Self { document: document, json: json, @@ -36,7 +33,10 @@ impl<'a> Indices<'a> { /// Returns the buffer view containing the sparse indices. pub fn view(&self) -> buffer::View<'a> { - self.document.views().nth(self.json.buffer_view.value()).unwrap() + self.document + .views() + .nth(self.json.buffer_view.value()) + .unwrap() } /// The offset relative to the start of the parent buffer view in bytes. @@ -54,7 +54,6 @@ impl<'a> Indices<'a> { } } - /// Optional application specific data. pub fn extras(&self) -> &'a json::Extras { &self.json.extras @@ -72,10 +71,7 @@ pub struct Sparse<'a> { impl<'a> Sparse<'a> { /// Constructs `Sparse`. - pub(crate) fn new( - document: &'a Document, - json: &'a json::accessor::sparse::Sparse, - ) -> Self { + pub(crate) fn new(document: &'a Document, json: &'a json::accessor::sparse::Sparse) -> Self { Self { document: document, json: json, @@ -117,10 +113,7 @@ pub struct Values<'a> { impl<'a> Values<'a> { /// Constructs `sparse::Values`. - pub(crate) fn new( - document: &'a Document, - json: &'a json::accessor::sparse::Values, - ) -> Self { + pub(crate) fn new(document: &'a Document, json: &'a json::accessor::sparse::Values) -> Self { Self { document: document, json: json, @@ -129,7 +122,10 @@ impl<'a> Values<'a> { /// Returns the buffer view containing the sparse values. pub fn view(&self) -> buffer::View<'a> { - self.document.views().nth(self.json.buffer_view.value()).unwrap() + self.document + .views() + .nth(self.json.buffer_view.value()) + .unwrap() } /// The offset relative to the start of the parent buffer view in bytes. @@ -143,7 +139,6 @@ impl<'a> Values<'a> { } } - impl IndexType { /// Returns the number of bytes this value represents. pub fn size(&self) -> usize { diff --git a/src/accessor/util.rs b/src/accessor/util.rs index 286e0039..42d9c8bd 100644 --- a/src/accessor/util.rs +++ b/src/accessor/util.rs @@ -1,6 +1,6 @@ -use std::{iter, mem}; -use byteorder::{LE, ByteOrder}; +use byteorder::{ByteOrder, LE}; use std::marker::PhantomData; +use std::{iter, mem}; use crate::{accessor, buffer}; @@ -10,8 +10,7 @@ fn buffer_view_slice<'a, 's>( ) -> Option<&'s [u8]> { let start = view.offset(); let end = start + view.length(); - get_buffer_data(view.buffer()) - .map(|slice| &slice[start..end]) + get_buffer_data(view.buffer()).map(|slice| &slice[start..end]) } /// General iterator for an accessor. @@ -107,7 +106,7 @@ pub struct SparseIter<'a, T: Item> { impl<'a, T: Item> SparseIter<'a, T> { /// Constructor. - /// + /// /// Here `base` is allowed to be `None` when the base buffer view is not explicitly specified. pub fn new( base: Option>, @@ -126,7 +125,11 @@ impl<'a, T: Item> SparseIter<'a, T> { impl<'a, T: Item> Iterator for SparseIter<'a, T> { type Item = T; fn next(&mut self) -> Option { - let next_base_value = self.base.as_mut().map(|iter| iter.next()).unwrap_or(Some(T::zero())); + let next_base_value = self + .base + .as_mut() + .map(|iter| iter.next()) + .unwrap_or(Some(T::zero())); if next_base_value.is_none() { return None; } @@ -230,8 +233,10 @@ impl Item for f32 { impl Item for [T; 2] { fn from_slice(slice: &[u8]) -> Self { assert!(slice.len() >= 2 * mem::size_of::()); - [T::from_slice(slice), - T::from_slice(&slice[mem::size_of::() ..])] + [ + T::from_slice(slice), + T::from_slice(&slice[mem::size_of::()..]), + ] } fn zero() -> Self { [T::zero(); 2] @@ -241,9 +246,11 @@ impl Item for [T; 2] { impl Item for [T; 3] { fn from_slice(slice: &[u8]) -> Self { assert!(slice.len() >= 3 * mem::size_of::()); - [T::from_slice(slice), - T::from_slice(&slice[1 * mem::size_of::() ..]), - T::from_slice(&slice[2 * mem::size_of::() ..])] + [ + T::from_slice(slice), + T::from_slice(&slice[1 * mem::size_of::()..]), + T::from_slice(&slice[2 * mem::size_of::()..]), + ] } fn zero() -> Self { [T::zero(); 3] @@ -253,10 +260,12 @@ impl Item for [T; 3] { impl Item for [T; 4] { fn from_slice(slice: &[u8]) -> Self { assert!(slice.len() >= 4 * mem::size_of::()); - [T::from_slice(slice), - T::from_slice(&slice[1 * mem::size_of::() ..]), - T::from_slice(&slice[2 * mem::size_of::() ..]), - T::from_slice(&slice[3 * mem::size_of::() ..])] + [ + T::from_slice(slice), + T::from_slice(&slice[1 * mem::size_of::()..]), + T::from_slice(&slice[2 * mem::size_of::()..]), + T::from_slice(&slice[3 * mem::size_of::()..]), + ] } fn zero() -> Self { [T::zero(); 4] @@ -276,11 +285,9 @@ impl<'a, T: Item> ItemIter<'a, T> { impl<'a, 's, T: Item> Iter<'s, T> { /// Constructor. - pub fn new( - accessor: super::Accessor<'a>, - get_buffer_data: F, - ) -> Option> - where F: Clone + Fn(buffer::Buffer<'a>) -> Option<&'s [u8]>, + pub fn new(accessor: super::Accessor<'a>, get_buffer_data: F) -> Option> + where + F: Clone + Fn(buffer::Buffer<'a>) -> Option<&'s [u8]>, { let is_sparse = accessor.sparse().is_some(); if is_sparse { @@ -296,7 +303,7 @@ impl<'a, 's, T: Item> Iter<'s, T> { let subslice = if let Some(slice) = buffer_view_slice(view, &get_buffer_data) { &slice[start..end] } else { - return None + return None; }; Some(ItemIter::new(subslice, stride)) } else { @@ -313,12 +320,18 @@ impl<'a, 's, T: Item> Iter<'s, T> { let end = start + stride * (sparse_count - 1) + index_size; &slice[start..end] } else { - return None + return None; }; match indices.index_type() { - accessor::sparse::IndexType::U8 => SparseIndicesIter::U8(ItemIter::new(subslice, stride)), - accessor::sparse::IndexType::U16 => SparseIndicesIter::U16(ItemIter::new(subslice, stride)), - accessor::sparse::IndexType::U32 => SparseIndicesIter::U32(ItemIter::new(subslice, stride)), + accessor::sparse::IndexType::U8 => { + SparseIndicesIter::U8(ItemIter::new(subslice, stride)) + } + accessor::sparse::IndexType::U16 => { + SparseIndicesIter::U16(ItemIter::new(subslice, stride)) + } + accessor::sparse::IndexType::U32 => { + SparseIndicesIter::U32(ItemIter::new(subslice, stride)) + } } }; let value_iter = { @@ -329,25 +342,36 @@ impl<'a, 's, T: Item> Iter<'s, T> { let end = start + stride * (sparse_count - 1) + mem::size_of::(); &slice[start..end] } else { - return None + return None; }; ItemIter::new(subslice, stride) }; - Some(Iter::Sparse(SparseIter::new(base_iter, index_iter, value_iter))) + Some(Iter::Sparse(SparseIter::new( + base_iter, index_iter, value_iter, + ))) } else { debug_assert_eq!(mem::size_of::(), accessor.size()); debug_assert!(mem::size_of::() > 0); if let Some(view) = accessor.view() { let stride = view.stride().unwrap_or(mem::size_of::()); - debug_assert!(stride >= mem::size_of::(), "Mismatch in stride, expected at least {} stride but found {}", mem::size_of::(), stride); + debug_assert!( + stride >= mem::size_of::(), + "Mismatch in stride, expected at least {} stride but found {}", + mem::size_of::(), + stride + ); let start = accessor.offset(); let end = start + stride * (accessor.count() - 1) + mem::size_of::(); let subslice = if let Some(slice) = buffer_view_slice(view, &get_buffer_data) { &slice[start..end] } else { - return None + return None; }; - Some(Iter::Standard(ItemIter { stride, data: subslice, _phantom: PhantomData })) + Some(Iter::Standard(ItemIter { + stride, + data: subslice, + _phantom: PhantomData, + })) } else { None } @@ -378,10 +402,10 @@ impl<'a, T: Item> Iterator for ItemIter<'a, T> { } fn nth(&mut self, nth: usize) -> Option { - if let Some(val_data) = self.data.get(nth * self.stride ..) { + if let Some(val_data) = self.data.get(nth * self.stride..) { if val_data.len() >= mem::size_of::() { let val = T::from_slice(val_data); - self.data = &val_data[self.stride.min(val_data.len()) ..]; + self.data = &val_data[self.stride.min(val_data.len())..]; Some(val) } else { None @@ -394,7 +418,7 @@ impl<'a, T: Item> Iterator for ItemIter<'a, T> { fn last(self) -> Option { if self.data.len() >= mem::size_of::() { self.data - .get((self.data.len() - 1) / self.stride * self.stride ..) + .get((self.data.len() - 1) / self.stride * self.stride..) .map(T::from_slice) } else { None diff --git a/src/animation/iter.rs b/src/animation/iter.rs index c56f908e..dd135186 100644 --- a/src/animation/iter.rs +++ b/src/animation/iter.rs @@ -25,7 +25,9 @@ pub struct Samplers<'a> { impl<'a> Iterator for Channels<'a> { type Item = Channel<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|json| Channel::new(self.anim.clone(), json)) + self.iter + .next() + .map(|json| Channel::new(self.anim.clone(), json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -38,14 +40,18 @@ impl<'a> Iterator for Channels<'a> { self.iter.last().map(|json| Channel::new(anim, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|json| Channel::new(self.anim.clone(), json)) + self.iter + .nth(n) + .map(|json| Channel::new(self.anim.clone(), json)) } } impl<'a> Iterator for Samplers<'a> { type Item = Sampler<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|json| Sampler::new(self.anim.clone(), json)) + self.iter + .next() + .map(|json| Sampler::new(self.anim.clone(), json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -58,6 +64,8 @@ impl<'a> Iterator for Samplers<'a> { self.iter.last().map(|json| Sampler::new(anim, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|json| Sampler::new(self.anim.clone(), json)) + self.iter + .nth(n) + .map(|json| Sampler::new(self.anim.clone(), json)) } } diff --git a/src/animation/mod.rs b/src/animation/mod.rs index 2c370238..7c4c0060 100644 --- a/src/animation/mod.rs +++ b/src/animation/mod.rs @@ -63,7 +63,8 @@ pub struct Target<'a> { impl<'a> Animation<'a> { /// Constructs an `Animation`. pub(crate) fn new( - document: &'a Document, index: usize, + document: &'a Document, + index: usize, json: &'a json::animation::Animation, ) -> Self { Self { @@ -113,10 +114,7 @@ impl<'a> Animation<'a> { impl<'a> Channel<'a> { /// Constructs a `Channel`. - pub(crate) fn new( - anim: Animation<'a>, - json: &'a json::animation::Channel, - ) -> Self { + pub(crate) fn new(anim: Animation<'a>, json: &'a json::animation::Channel) -> Self { Self { anim: anim, json: json, @@ -160,10 +158,7 @@ impl<'a> Channel<'a> { impl<'a> Target<'a> { /// Constructs a `Target`. - pub(crate) fn new( - anim: Animation<'a>, - json: &'a json::animation::Target, - ) -> Self { + pub(crate) fn new(anim: Animation<'a>, json: &'a json::animation::Target) -> Self { Self { anim: anim, json: json, @@ -182,7 +177,11 @@ impl<'a> Target<'a> { /// Returns the target node. pub fn node(&self) -> scene::Node<'a> { - self.anim.document.nodes().nth(self.json.node.value()).unwrap() + self.anim + .document + .nodes() + .nth(self.json.node.value()) + .unwrap() } /// Returns the node's property to modify or the 'weights' of the morph @@ -194,10 +193,7 @@ impl<'a> Target<'a> { impl<'a> Sampler<'a> { /// Constructs a `Sampler`. - pub(crate) fn new( - anim: Animation<'a>, - json: &'a json::animation::Sampler, - ) -> Self { + pub(crate) fn new(anim: Animation<'a>, json: &'a json::animation::Sampler) -> Self { Self { anim: anim, json: json, @@ -216,7 +212,11 @@ impl<'a> Sampler<'a> { /// Returns the accessor containing the keyframe input values (e.g. time). pub fn input(&self) -> accessor::Accessor<'a> { - self.anim.document.accessors().nth(self.json.input.value()).unwrap() + self.anim + .document + .accessors() + .nth(self.json.input.value()) + .unwrap() } /// Returns the keyframe interpolation algorithm. @@ -226,6 +226,10 @@ impl<'a> Sampler<'a> { /// Returns the accessor containing the keyframe output values. pub fn output(&self) -> accessor::Accessor<'a> { - self.anim.document.accessors().nth(self.json.output.value()).unwrap() + self.anim + .document + .accessors() + .nth(self.json.output.value()) + .unwrap() } } diff --git a/src/animation/util/mod.rs b/src/animation/util/mod.rs index 3c05ed91..d55d6824 100644 --- a/src/animation/util/mod.rs +++ b/src/animation/util/mod.rs @@ -137,7 +137,8 @@ impl<'a> MorphTargetWeights<'a> { } impl<'a, 's, F> Reader<'a, 's, F> -where F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, +where + F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, { /// Visits the input samples of a channel. pub fn read_inputs(&self) -> Option> { @@ -146,31 +147,41 @@ where F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, /// Visits the output samples of a channel. pub fn read_outputs(&self) -> Option> { - use accessor::{DataType, Iter}; use crate::animation::Property; + use accessor::{DataType, Iter}; let output = self.channel.sampler().output(); match self.channel.target().property() { - Property::Translation => Iter::new(output, self.get_buffer_data.clone()).map(ReadOutputs::Translations), - Property::Rotation => { - match output.data_type() { - DataType::I8 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::Rotations(Rotations::I8(x))), - DataType::U8 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::Rotations(Rotations::U8(x))), - DataType::I16 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::Rotations(Rotations::I16(x))), - DataType::U16 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::Rotations(Rotations::U16(x))), - DataType::F32 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::Rotations(Rotations::F32(x))), - _ => unreachable!() - } + Property::Translation => { + Iter::new(output, self.get_buffer_data.clone()).map(ReadOutputs::Translations) + } + Property::Rotation => match output.data_type() { + DataType::I8 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::Rotations(Rotations::I8(x))), + DataType::U8 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::Rotations(Rotations::U8(x))), + DataType::I16 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::Rotations(Rotations::I16(x))), + DataType::U16 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::Rotations(Rotations::U16(x))), + DataType::F32 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::Rotations(Rotations::F32(x))), + _ => unreachable!(), }, - Property::Scale => Iter::new(output, self.get_buffer_data.clone()).map(ReadOutputs::Scales), - Property::MorphTargetWeights => { - match output.data_type() { - DataType::I8 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::I8(x))), - DataType::U8 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::U8(x))), - DataType::I16 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::I16(x))), - DataType::U16 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::U16(x))), - DataType::F32 => Iter::new(output, self.get_buffer_data.clone()).map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::F32(x))), - _ => unreachable!() - } + Property::Scale => { + Iter::new(output, self.get_buffer_data.clone()).map(ReadOutputs::Scales) + } + Property::MorphTargetWeights => match output.data_type() { + DataType::I8 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::I8(x))), + DataType::U8 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::U8(x))), + DataType::I16 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::I16(x))), + DataType::U16 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::U16(x))), + DataType::F32 => Iter::new(output, self.get_buffer_data.clone()) + .map(|x| ReadOutputs::MorphTargetWeights(MorphTargetWeights::F32(x))), + _ => unreachable!(), }, } } diff --git a/src/animation/util/morph_target_weights.rs b/src/animation/util/morph_target_weights.rs index 7a8564d1..bc995c22 100644 --- a/src/animation/util/morph_target_weights.rs +++ b/src/animation/util/morph_target_weights.rs @@ -1,6 +1,6 @@ use super::MorphTargetWeights; -use std::marker::PhantomData; use crate::Normalize; +use std::marker::PhantomData; /// Casting iterator for `MorphTargetWeights`. #[derive(Clone, Debug)] @@ -65,8 +65,8 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn next(&mut self) -> Option { match self.0 { - MorphTargetWeights::I8(ref mut i) => i.next().map(A::cast_i8), - MorphTargetWeights::U8(ref mut i) => i.next().map(A::cast_u8), + MorphTargetWeights::I8(ref mut i) => i.next().map(A::cast_i8), + MorphTargetWeights::U8(ref mut i) => i.next().map(A::cast_u8), MorphTargetWeights::I16(ref mut i) => i.next().map(A::cast_i16), MorphTargetWeights::U16(ref mut i) => i.next().map(A::cast_u16), MorphTargetWeights::F32(ref mut i) => i.next().map(A::cast_f32), @@ -76,8 +76,8 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn nth(&mut self, x: usize) -> Option { match self.0 { - MorphTargetWeights::I8(ref mut i) => i.nth(x).map(A::cast_i8), - MorphTargetWeights::U8(ref mut i) => i.nth(x).map(A::cast_u8), + MorphTargetWeights::I8(ref mut i) => i.nth(x).map(A::cast_i8), + MorphTargetWeights::U8(ref mut i) => i.nth(x).map(A::cast_u8), MorphTargetWeights::I16(ref mut i) => i.nth(x).map(A::cast_i16), MorphTargetWeights::U16(ref mut i) => i.nth(x).map(A::cast_u16), MorphTargetWeights::F32(ref mut i) => i.nth(x).map(A::cast_f32), @@ -86,8 +86,8 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { fn last(self) -> Option { match self.0 { - MorphTargetWeights::I8(i) => i.last().map(A::cast_i8), - MorphTargetWeights::U8(i) => i.last().map(A::cast_u8), + MorphTargetWeights::I8(i) => i.last().map(A::cast_i8), + MorphTargetWeights::U8(i) => i.last().map(A::cast_u8), MorphTargetWeights::I16(i) => i.last().map(A::cast_i16), MorphTargetWeights::U16(i) => i.last().map(A::cast_u16), MorphTargetWeights::F32(i) => i.last().map(A::cast_f32), @@ -101,8 +101,8 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn size_hint(&self) -> (usize, Option) { match self.0 { - MorphTargetWeights::I8(ref i) => i.size_hint(), - MorphTargetWeights::U8(ref i) => i.size_hint(), + MorphTargetWeights::I8(ref i) => i.size_hint(), + MorphTargetWeights::U8(ref i) => i.size_hint(), MorphTargetWeights::I16(ref i) => i.size_hint(), MorphTargetWeights::U16(ref i) => i.size_hint(), MorphTargetWeights::F32(ref i) => i.size_hint(), diff --git a/src/animation/util/rotations.rs b/src/animation/util/rotations.rs index 7d72090e..e0ecfa8d 100644 --- a/src/animation/util/rotations.rs +++ b/src/animation/util/rotations.rs @@ -1,6 +1,6 @@ use super::Rotations; -use std::marker::PhantomData; use crate::Normalize; +use std::marker::PhantomData; /// Casting iterator for `Rotations`. #[derive(Clone, Debug)] @@ -65,8 +65,8 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn next(&mut self) -> Option { match self.0 { - Rotations::I8(ref mut i) => i.next().map(A::cast_i8), - Rotations::U8(ref mut i) => i.next().map(A::cast_u8), + Rotations::I8(ref mut i) => i.next().map(A::cast_i8), + Rotations::U8(ref mut i) => i.next().map(A::cast_u8), Rotations::I16(ref mut i) => i.next().map(A::cast_i16), Rotations::U16(ref mut i) => i.next().map(A::cast_u16), Rotations::F32(ref mut i) => i.next().map(A::cast_f32), @@ -76,8 +76,8 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn nth(&mut self, x: usize) -> Option { match self.0 { - Rotations::I8(ref mut i) => i.nth(x).map(A::cast_i8), - Rotations::U8(ref mut i) => i.nth(x).map(A::cast_u8), + Rotations::I8(ref mut i) => i.nth(x).map(A::cast_i8), + Rotations::U8(ref mut i) => i.nth(x).map(A::cast_u8), Rotations::I16(ref mut i) => i.nth(x).map(A::cast_i16), Rotations::U16(ref mut i) => i.nth(x).map(A::cast_u16), Rotations::F32(ref mut i) => i.nth(x).map(A::cast_f32), @@ -86,8 +86,8 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { fn last(self) -> Option { match self.0 { - Rotations::I8(i) => i.last().map(A::cast_i8), - Rotations::U8(i) => i.last().map(A::cast_u8), + Rotations::I8(i) => i.last().map(A::cast_i8), + Rotations::U8(i) => i.last().map(A::cast_u8), Rotations::I16(i) => i.last().map(A::cast_i16), Rotations::U16(i) => i.last().map(A::cast_u16), Rotations::F32(i) => i.last().map(A::cast_f32), @@ -101,8 +101,8 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn size_hint(&self) -> (usize, Option) { match self.0 { - Rotations::I8(ref i) => i.size_hint(), - Rotations::U8(ref i) => i.size_hint(), + Rotations::I8(ref i) => i.size_hint(), + Rotations::U8(ref i) => i.size_hint(), Rotations::I16(ref i) => i.size_hint(), Rotations::U16(ref i) => i.size_hint(), Rotations::F32(ref i) => i.size_hint(), diff --git a/src/binary.rs b/src/binary.rs index e62a2a4a..4c1a4397 100644 --- a/src/binary.rs +++ b/src/binary.rs @@ -1,6 +1,6 @@ use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; -use std::{fmt, io, mem}; use std::borrow::Cow; +use std::{fmt, io, mem}; /// Represents a Glb loader error. #[derive(Debug)] @@ -94,7 +94,9 @@ impl Header { } } - fn size_of() -> usize { 12 } + fn size_of() -> usize { + 12 + } } impl ChunkHeader { @@ -118,19 +120,23 @@ fn align_to_multiple_of_four(n: &mut usize) { fn split_binary_gltf<'a>(mut data: &'a [u8]) -> Result<(&'a [u8], Option<&'a [u8]>), Error> { let (json, mut data) = ChunkHeader::from_reader(&mut data) - .and_then(|json_h| if let ChunkType::Json = json_h.ty { - Ok(json_h) - } else { - Err(Error::ChunkType(json_h.ty)) + .and_then(|json_h| { + if let ChunkType::Json = json_h.ty { + Ok(json_h) + } else { + Err(Error::ChunkType(json_h.ty)) + } }) - .and_then(|json_h| if json_h.length as usize <= data.len() { - Ok(json_h) - } else { - Err(Error::ChunkLength { - ty: json_h.ty, - length: json_h.length, - length_read: data.len(), - }) + .and_then(|json_h| { + if json_h.length as usize <= data.len() { + Ok(json_h) + } else { + Err(Error::ChunkLength { + ty: json_h.ty, + length: json_h.length, + length_read: data.len(), + }) + } }) // We have verified that json_h.length is no greater than that of // data.len(). @@ -138,19 +144,23 @@ fn split_binary_gltf<'a>(mut data: &'a [u8]) -> Result<(&'a [u8], Option<&'a [u8 let bin = if data.len() > 0 { ChunkHeader::from_reader(&mut data) - .and_then(|bin_h| if let ChunkType::Bin = bin_h.ty { - Ok(bin_h) - } else { - Err(Error::ChunkType(bin_h.ty)) + .and_then(|bin_h| { + if let ChunkType::Bin = bin_h.ty { + Ok(bin_h) + } else { + Err(Error::ChunkType(bin_h.ty)) + } }) - .and_then(|bin_h| if bin_h.length as usize <= data.len() { - Ok(bin_h) - } else { - Err(Error::ChunkLength { - ty: bin_h.ty, - length: bin_h.length, - length_read: data.len(), - }) + .and_then(|bin_h| { + if bin_h.length as usize <= data.len() { + Ok(bin_h) + } else { + Err(Error::ChunkLength { + ty: bin_h.ty, + length: bin_h.length, + length_read: data.len(), + }) + } }) // We have verified that bin_h.length is no greater than that // of data.len(). @@ -165,13 +175,15 @@ fn split_binary_gltf<'a>(mut data: &'a [u8]) -> Result<(&'a [u8], Option<&'a [u8 impl<'a> Glb<'a> { /// Writes binary glTF to a writer. pub fn to_writer(&self, mut writer: W) -> Result<(), crate::Error> - where W: io::Write + where + W: io::Write, { // Write GLB header { let magic = b"glTF"; let version = 2; - let mut length = mem::size_of::
() + mem::size_of::() + self.json.len(); + let mut length = + mem::size_of::
() + mem::size_of::() + self.json.len(); align_to_multiple_of_four(&mut length); if let Some(bin) = self.bin.as_ref() { length += mem::size_of::() + bin.len(); @@ -250,9 +262,13 @@ impl<'a> Glb<'a> { .map_err(crate::Error::Binary)?; match header.version { 2 => split_binary_gltf(data) - .map(|(json, bin)| Glb { header, json: json.into(), bin: bin.map(Into::into) }) + .map(|(json, bin)| Glb { + header, + json: json.into(), + bin: bin.map(Into::into), + }) .map_err(crate::Error::Binary), - x => Err(crate::Error::Binary(Error::Version(x))) + x => Err(crate::Error::Binary(Error::Version(x))), } } @@ -280,28 +296,32 @@ impl<'a> Glb<'a> { .map_err(crate::Error::Binary) } } - x => Err(crate::Error::Binary(Error::Version(x))) + x => Err(crate::Error::Binary(Error::Version(x))), } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", match *self { - Error::Io(ref e) => return e.fmt(f), - Error::Version(_) => "unsupported version", - Error::Magic(_) => "not glTF magic", - Error::Length { .. } => "could not completely read the object", - Error::ChunkLength { ty, .. } => match ty { - ChunkType::Json => "JSON chunk length exceeds that of slice", - ChunkType::Bin => "BIN\\0 chunk length exceeds that of slice", - }, - Error::ChunkType(ty) => match ty { - ChunkType::Json => "was not expecting JSON chunk", - ChunkType::Bin => "was not expecting BIN\\0 chunk", - }, - Error::UnknownChunkType(_) => "unknown chunk type", - }) + write!( + f, + "{}", + match *self { + Error::Io(ref e) => return e.fmt(f), + Error::Version(_) => "unsupported version", + Error::Magic(_) => "not glTF magic", + Error::Length { .. } => "could not completely read the object", + Error::ChunkLength { ty, .. } => match ty { + ChunkType::Json => "JSON chunk length exceeds that of slice", + ChunkType::Bin => "BIN\\0 chunk length exceeds that of slice", + }, + Error::ChunkType(ty) => match ty { + ChunkType::Json => "was not expecting JSON chunk", + ChunkType::Bin => "was not expecting BIN\\0 chunk", + }, + Error::UnknownChunkType(_) => "unknown chunk type", + } + ) } } diff --git a/src/buffer.rs b/src/buffer.rs index 38a683ff..02012e03 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -107,11 +107,7 @@ impl<'a> Buffer<'a> { impl<'a> View<'a> { /// Constructs a `View`. - pub(crate) fn new( - document: &'a Document, - index: usize, - json: &'a json::buffer::View, - ) -> Self { + pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::buffer::View) -> Self { let parent = document.buffers().nth(json.buffer.value()).unwrap(); Self { document, @@ -128,7 +124,10 @@ impl<'a> View<'a> { /// Returns the parent `Buffer`. pub fn buffer(&self) -> Buffer<'a> { - self.document.buffers().nth(self.json.buffer.value()).unwrap() + self.document + .buffers() + .nth(self.json.buffer.value()) + .unwrap() } /// Returns the length of the buffer view in bytes. @@ -145,14 +144,14 @@ impl<'a> View<'a> { /// data. When `None`, data is assumed to be tightly packed. pub fn stride(&self) -> Option { self.json.byte_stride.and_then(|x| { - // Treat byte_stride == 0 same as not specifying stride. - // This is technically a validation error, but best way we can handle it here - if x == 0 { - None - } else { - Some(x as usize) - } - }) + // Treat byte_stride == 0 same as not specifying stride. + // This is technically a validation error, but best way we can handle it here + if x == 0 { + None + } else { + Some(x as usize) + } + }) } /// Optional user-defined name for this object. diff --git a/src/camera.rs b/src/camera.rs index 9440e801..a9ea1b28 100644 --- a/src/camera.rs +++ b/src/camera.rs @@ -46,7 +46,11 @@ pub struct Perspective<'a> { impl<'a> Camera<'a> { /// Constructs a `Camera`. - pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::camera::Camera) -> Self { + pub(crate) fn new( + document: &'a Document, + index: usize, + json: &'a json::camera::Camera, + ) -> Self { Self { document: document, index: index, @@ -72,11 +76,11 @@ impl<'a> Camera<'a> { json::camera::Type::Orthographic => { let json = self.json.orthographic.as_ref().unwrap(); Projection::Orthographic(Orthographic::new(self.document, json)) - }, + } json::camera::Type::Perspective => { let json = self.json.perspective.as_ref().unwrap(); Projection::Perspective(Perspective::new(self.document, json)) - }, + } } } diff --git a/src/image.rs b/src/image.rs index d7daa477..33224768 100644 --- a/src/image.rs +++ b/src/image.rs @@ -95,11 +95,7 @@ pub struct Data { impl<'a> Image<'a> { /// Constructs an `Image` from owned data. - pub(crate) fn new( - document: &'a Document, - index: usize, - json: &'a json::image::Image, - ) -> Self { + pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::image::Image) -> Self { Self { document: document, index: index, @@ -122,14 +118,8 @@ impl<'a> Image<'a> { /// Returns the image data source. pub fn source(&self) -> Source<'a> { if let Some(index) = self.json.buffer_view.as_ref() { - let view = self.document - .views() - .nth(index.value()) - .unwrap(); - let mime_type = self.json.mime_type - .as_ref() - .map(|x| x.0.as_str()) - .unwrap(); + let view = self.document.views().nth(index.value()).unwrap(); + let mime_type = self.json.mime_type.as_ref().map(|x| x.0.as_str()).unwrap(); Source::View { view, mime_type } } else { let uri = self.json.uri.as_ref().unwrap(); @@ -164,6 +154,11 @@ impl Data { }; let (width, height) = image.dimensions(); let pixels = image.to_bytes(); - Data { format, width, height, pixels } + Data { + format, + width, + height, + pixels, + } } } diff --git a/src/import.rs b/src/import.rs index e791ed95..15980dc2 100644 --- a/src/import.rs +++ b/src/import.rs @@ -1,11 +1,11 @@ -use base64; use crate::buffer; use crate::image; +use base64; use std::{fs, io}; +use crate::{Document, Error, Gltf, Result}; use image_crate::ImageFormat::{Jpeg, Png}; use std::path::Path; -use crate::{Document, Error, Gltf, Result}; /// Return type of `import`. type Import = (Document, Vec, Vec); @@ -61,13 +61,14 @@ impl<'a> Scheme<'a> { Scheme::File(path) if base.is_some() => read_to_end(path), Scheme::Relative if base.is_some() => read_to_end(base.unwrap().join(uri)), Scheme::Unsupported => Err(Error::UnsupportedScheme), - _ => Err(Error::ExternalReferenceInSliceImport) + _ => Err(Error::ExternalReferenceInSliceImport), } } } fn read_to_end

(path: P) -> Result> -where P: AsRef +where + P: AsRef, { use io::Read; let file = fs::File::open(path.as_ref()).map_err(Error::Io)?; @@ -94,13 +95,11 @@ pub fn import_buffer_data( buffer::Source::Bin => blob.take().ok_or(Error::MissingBlob), }?; if data.len() < buffer.length() { - return Err( - Error::BufferLength { - buffer: buffer.index(), - expected: buffer.length(), - actual: data.len(), - } - ); + return Err(Error::BufferLength { + buffer: buffer.index(), + expected: buffer.length(), + actual: data.len(), + }); } while data.len() % 4 != 0 { data.push(0); @@ -118,17 +117,13 @@ pub fn import_image_data( ) -> Result> { let mut images = Vec::new(); #[cfg(feature = "guess_mime_type")] - let guess_format = |encoded_image: &[u8]| { - match image_crate::guess_format(encoded_image) { - Ok(image_crate::ImageFormat::Png) => Some(Png), - Ok(image_crate::ImageFormat::Jpeg) => Some(Jpeg), - _ => None, - } + let guess_format = |encoded_image: &[u8]| match image_crate::guess_format(encoded_image) { + Ok(image_crate::ImageFormat::Png) => Some(Png), + Ok(image_crate::ImageFormat::Jpeg) => Some(Jpeg), + _ => None, }; #[cfg(not(feature = "guess_mime_type"))] - let guess_format = |_encoded_image: &[u8]| { - None - }; + let guess_format = |_encoded_image: &[u8]| None; for image in document.images() { match image.source() { image::Source::Uri { uri, mime_type } if base.is_some() => { @@ -143,15 +138,18 @@ pub fn import_image_data( None => return Err(Error::UnsupportedImageEncoding), }, }; - let decoded_image = image_crate::load_from_memory_with_format(&encoded_image, encoded_format)?; + let decoded_image = image_crate::load_from_memory_with_format( + &encoded_image, + encoded_format, + )?; images.push(image::Data::new(decoded_image)); continue; - }, + } Scheme::Unsupported => return Err(Error::UnsupportedScheme), - _ => {}, + _ => {} } let encoded_image = Scheme::read(base, uri)?; - let encoded_format = match mime_type { + let encoded_format = match mime_type { Some("image/png") => Png, Some("image/jpeg") => Jpeg, Some(_) => match guess_format(&encoded_image) { @@ -167,9 +165,10 @@ pub fn import_image_data( }, }, }; - let decoded_image = image_crate::load_from_memory_with_format(&encoded_image, encoded_format)?; + let decoded_image = + image_crate::load_from_memory_with_format(&encoded_image, encoded_format)?; images.push(image::Data::new(decoded_image)); - }, + } image::Source::View { view, mime_type } => { let parent_buffer_data = &buffer_data[view.buffer().index()].0; let begin = view.offset(); @@ -183,10 +182,11 @@ pub fn import_image_data( None => return Err(Error::UnsupportedImageEncoding), }, }; - let decoded_image = image_crate::load_from_memory_with_format(encoded_image, encoded_format)?; + let decoded_image = + image_crate::load_from_memory_with_format(encoded_image, encoded_format)?; images.push(image::Data::new(decoded_image)); - }, - _ => return Err(Error::ExternalReferenceInSliceImport) + } + _ => return Err(Error::ExternalReferenceInSliceImport), } } @@ -235,7 +235,8 @@ fn import_path(path: &Path) -> Result { /// [`Gltf`]: struct.Gltf.html /// [`Glb`]: struct.Glb.html pub fn import

(path: P) -> Result - where P: AsRef +where + P: AsRef, { import_path(path.as_ref()) } @@ -264,7 +265,8 @@ pub fn import_slice_impl(slice: &[u8]) -> Result { /// # } /// ``` pub fn import_slice(slice: S) -> Result - where S: AsRef<[u8]> +where + S: AsRef<[u8]>, { import_slice_impl(slice.as_ref()) } diff --git a/src/iter.rs b/src/iter.rs index 7446f92e..ffd3ef41 100644 --- a/src/iter.rs +++ b/src/iter.rs @@ -85,7 +85,8 @@ pub struct Images<'a> { #[derive(Clone, Debug)] pub struct Lights<'a> { /// Internal image iterator. - pub(crate) iter: iter::Enumerate>, + pub(crate) iter: + iter::Enumerate>, /// The internal root glTF object. pub(crate) document: &'a Document, @@ -96,7 +97,8 @@ pub struct Lights<'a> { #[derive(Clone, Debug)] pub struct Variants<'a> { /// Internal variant iterator. - pub(crate) iter: iter::Enumerate>, + pub(crate) iter: + iter::Enumerate>, /// The internal root glTF object. pub(crate) document: &'a Document, @@ -176,7 +178,9 @@ impl<'a> ExactSizeIterator for Accessors<'a> {} impl<'a> Iterator for Accessors<'a> { type Item = Accessor<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Accessor::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Accessor::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -186,10 +190,14 @@ impl<'a> Iterator for Accessors<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Accessor::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Accessor::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Accessor::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Accessor::new(self.document, index, json)) } } @@ -197,7 +205,9 @@ impl<'a> ExactSizeIterator for Animations<'a> {} impl<'a> Iterator for Animations<'a> { type Item = Animation<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Animation::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Animation::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -207,10 +217,14 @@ impl<'a> Iterator for Animations<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Animation::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Animation::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Animation::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Animation::new(self.document, index, json)) } } @@ -218,7 +232,9 @@ impl<'a> ExactSizeIterator for Buffers<'a> {} impl<'a> Iterator for Buffers<'a> { type Item = Buffer<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Buffer::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Buffer::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -228,10 +244,14 @@ impl<'a> Iterator for Buffers<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Buffer::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Buffer::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Buffer::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Buffer::new(self.document, index, json)) } } @@ -279,7 +299,9 @@ impl<'a> ExactSizeIterator for Views<'a> {} impl<'a> Iterator for Views<'a> { type Item = View<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| View::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| View::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -289,10 +311,14 @@ impl<'a> Iterator for Views<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| View::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| View::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| View::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| View::new(self.document, index, json)) } } @@ -300,7 +326,9 @@ impl<'a> ExactSizeIterator for Cameras<'a> {} impl<'a> Iterator for Cameras<'a> { type Item = Camera<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Camera::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Camera::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -310,10 +338,14 @@ impl<'a> Iterator for Cameras<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Camera::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Camera::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Camera::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Camera::new(self.document, index, json)) } } @@ -321,7 +353,9 @@ impl<'a> ExactSizeIterator for Images<'a> {} impl<'a> Iterator for Images<'a> { type Item = Image<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Image::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Image::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -331,10 +365,14 @@ impl<'a> Iterator for Images<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Image::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Image::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Image::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Image::new(self.document, index, json)) } } @@ -357,14 +395,17 @@ impl<'a> Iterator for Lights<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| crate::khr_lights_punctual::Light::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| crate::khr_lights_punctual::Light::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| crate::khr_lights_punctual::Light::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| crate::khr_lights_punctual::Light::new(self.document, index, json)) } } - #[cfg(feature = "KHR_materials_variants")] impl<'a> ExactSizeIterator for Variants<'a> {} @@ -372,9 +413,9 @@ impl<'a> ExactSizeIterator for Variants<'a> {} impl<'a> Iterator for Variants<'a> { type Item = crate::khr_materials_variants::Variant<'a>; fn next(&mut self) -> Option { - self.iter - .next() - .map(|(index, json)| crate::khr_materials_variants::Variant::new(self.document, index, json)) + self.iter.next().map(|(index, json)| { + crate::khr_materials_variants::Variant::new(self.document, index, json) + }) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -384,19 +425,24 @@ impl<'a> Iterator for Variants<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| crate::khr_materials_variants::Variant::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| crate::khr_materials_variants::Variant::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| crate::khr_materials_variants::Variant::new(self.document, index, json)) + self.iter.nth(n).map(|(index, json)| { + crate::khr_materials_variants::Variant::new(self.document, index, json) + }) } } - impl<'a> ExactSizeIterator for Materials<'a> {} impl<'a> Iterator for Materials<'a> { type Item = Material<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Material::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Material::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -406,10 +452,14 @@ impl<'a> Iterator for Materials<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Material::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Material::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Material::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Material::new(self.document, index, json)) } } @@ -417,7 +467,9 @@ impl<'a> ExactSizeIterator for Meshes<'a> {} impl<'a> Iterator for Meshes<'a> { type Item = Mesh<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Mesh::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Mesh::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -427,10 +479,14 @@ impl<'a> Iterator for Meshes<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Mesh::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Mesh::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Mesh::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Mesh::new(self.document, index, json)) } } @@ -438,7 +494,9 @@ impl<'a> ExactSizeIterator for Nodes<'a> {} impl<'a> Iterator for Nodes<'a> { type Item = Node<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Node::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Node::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -448,10 +506,14 @@ impl<'a> Iterator for Nodes<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Node::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Node::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Node::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Node::new(self.document, index, json)) } } @@ -459,7 +521,9 @@ impl<'a> ExactSizeIterator for Samplers<'a> {} impl<'a> Iterator for Samplers<'a> { type Item = Sampler<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Sampler::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Sampler::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -469,10 +533,14 @@ impl<'a> Iterator for Samplers<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Sampler::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Sampler::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Sampler::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Sampler::new(self.document, index, json)) } } @@ -480,7 +548,9 @@ impl<'a> ExactSizeIterator for Scenes<'a> {} impl<'a> Iterator for Scenes<'a> { type Item = Scene<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Scene::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Scene::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -490,10 +560,14 @@ impl<'a> Iterator for Scenes<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Scene::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Scene::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Scene::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Scene::new(self.document, index, json)) } } @@ -501,7 +575,9 @@ impl<'a> ExactSizeIterator for Skins<'a> {} impl<'a> Iterator for Skins<'a> { type Item = Skin<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Skin::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Skin::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -511,10 +587,14 @@ impl<'a> Iterator for Skins<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Skin::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Skin::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Skin::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Skin::new(self.document, index, json)) } } @@ -522,7 +602,9 @@ impl<'a> ExactSizeIterator for Textures<'a> {} impl<'a> Iterator for Textures<'a> { type Item = Texture<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Texture::new(self.document, index, json)) + self.iter + .next() + .map(|(index, json)| Texture::new(self.document, index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -532,9 +614,13 @@ impl<'a> Iterator for Textures<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|(index, json)| Texture::new(document, index, json)) + self.iter + .last() + .map(|(index, json)| Texture::new(document, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Texture::new(self.document, index, json)) + self.iter + .nth(n) + .map(|(index, json)| Texture::new(self.document, index, json)) } } diff --git a/src/khr_lights_punctual.rs b/src/khr_lights_punctual.rs index 23fed4c1..75ca22c9 100644 --- a/src/khr_lights_punctual.rs +++ b/src/khr_lights_punctual.rs @@ -1,5 +1,5 @@ -use gltf_json::Extras; use crate::Document; +use gltf_json::Extras; /// A light in the scene. pub struct Light<'a> { @@ -16,7 +16,11 @@ pub struct Light<'a> { impl<'a> Light<'a> { /// Constructs a `Light`. - pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::extensions::scene::khr_lights_punctual::Light) -> Self { + pub(crate) fn new( + document: &'a Document, + index: usize, + json: &'a json::extensions::scene::khr_lights_punctual::Light, + ) -> Self { Self { document, index, @@ -69,7 +73,7 @@ impl<'a> Light<'a> { inner_cone_angle: args.inner_cone_angle, outer_cone_angle: args.outer_cone_angle, } - }, + } } } } diff --git a/src/khr_materials_variants.rs b/src/khr_materials_variants.rs index 8efc681d..6d3b3718 100644 --- a/src/khr_materials_variants.rs +++ b/src/khr_materials_variants.rs @@ -1,5 +1,5 @@ -use gltf_json::Extras; use crate::{Document, Material}; +use gltf_json::Extras; /// A variant. pub struct Variant<'a> { @@ -16,7 +16,11 @@ pub struct Variant<'a> { impl<'a> Variant<'a> { /// Constructs a `Variant`. - pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::extensions::scene::khr_materials_variants::Variant) -> Self { + pub(crate) fn new( + document: &'a Document, + index: usize, + json: &'a json::extensions::scene::khr_materials_variants::Variant, + ) -> Self { Self { document, index, @@ -42,10 +46,7 @@ pub struct Mapping<'a> { impl<'a> Mapping<'a> { /// Constructs a `Mapping`. pub(crate) fn new(document: &'a Document, json: &'a json::extensions::mesh::Mapping) -> Self { - Self { - document, - json, - } + Self { document, json } } /// Get the variant indices that use this material. @@ -55,7 +56,9 @@ impl<'a> Mapping<'a> { /// Get the corresponding material. pub fn material(&self) -> Material<'a> { - self.document.materials().nth(self.json.material as usize) - .unwrap_or_else(|| Material::default(self.document)) + self.document + .materials() + .nth(self.json.material as usize) + .unwrap_or_else(|| Material::default(self.document)) } } diff --git a/src/lib.rs b/src/lib.rs index d73983c3..dcdeba21 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -142,11 +142,11 @@ pub mod skin; /// Textures and their samplers. pub mod texture; -#[doc(inline)] -pub use self::animation::Animation; #[doc(inline)] pub use self::accessor::Accessor; #[doc(inline)] +pub use self::animation::Animation; +#[doc(inline)] pub use self::binary::Glb; #[doc(inline)] pub use self::buffer::Buffer; @@ -270,7 +270,7 @@ impl Gltf { /// Loads glTF from a reader without performing validation checks. pub fn from_reader_without_validation(mut reader: R) -> Result where - R: io::Read + io::Seek + R: io::Read + io::Seek, { let mut magic = [0u8; 4]; reader.read_exact(&mut magic)?; @@ -359,11 +359,10 @@ impl Document { pub(crate) fn validate(&self) -> Result<()> { use json::validation::Validate; let mut errors = Vec::new(); - self.0.validate( - &self.0, - json::Path::new, - &mut |path, error| errors.push((path(), error)), - ); + self.0 + .validate(&self.0, json::Path::new, &mut |path, error| { + errors.push((path(), error)) + }); if errors.is_empty() { Ok(()) } else { @@ -542,15 +541,17 @@ impl std::fmt::Display for Error { Error::Base64(ref e) => e.fmt(f), Error::Binary(ref e) => e.fmt(f), #[cfg(feature = "import")] - Error::BufferLength { buffer, expected, actual } => { + Error::BufferLength { + buffer, + expected, + actual, + } => { write!( f, "buffer {}: expected {} bytes but received {} bytes", - buffer, - expected, - actual + buffer, expected, actual ) - }, + } Error::Deserialize(ref e) => e.fmt(f), Error::Io(ref e) => e.fmt(f), #[cfg(feature = "import")] @@ -558,7 +559,9 @@ impl std::fmt::Display for Error { #[cfg(feature = "import")] Error::MissingBlob => write!(f, "missing binary portion of binary glTF"), #[cfg(feature = "import")] - Error::ExternalReferenceInSliceImport => write!(f, "external reference in slice only import"), + Error::ExternalReferenceInSliceImport => { + write!(f, "external reference in slice only import") + } #[cfg(feature = "import")] Error::UnsupportedImageEncoding => write!(f, "unsupported image encoding"), #[cfg(feature = "import")] @@ -608,119 +611,187 @@ impl From> for Error { } impl Normalize for i8 { - fn normalize(self) -> i8 { self } + fn normalize(self) -> i8 { + self + } } impl Normalize for i8 { - fn normalize(self) -> u8 { self.max(0) as u8 * 2 } + fn normalize(self) -> u8 { + self.max(0) as u8 * 2 + } } impl Normalize for i8 { - fn normalize(self) -> i16 { self as i16 * 0x100 } + fn normalize(self) -> i16 { + self as i16 * 0x100 + } } impl Normalize for i8 { - fn normalize(self) -> u16 { self.max(0) as u16 * 0x200 } + fn normalize(self) -> u16 { + self.max(0) as u16 * 0x200 + } } impl Normalize for i8 { - fn normalize(self) -> f32 { (self as f32 * 127.0_f32.recip()).max(-1.0) } + fn normalize(self) -> f32 { + (self as f32 * 127.0_f32.recip()).max(-1.0) + } } impl Normalize for u8 { - fn normalize(self) -> i8 { (self / 2) as i8 } + fn normalize(self) -> i8 { + (self / 2) as i8 + } } impl Normalize for u8 { - fn normalize(self) -> u8 { self } + fn normalize(self) -> u8 { + self + } } impl Normalize for u8 { - fn normalize(self) -> i16 { self as i16 * 0x80 } + fn normalize(self) -> i16 { + self as i16 * 0x80 + } } impl Normalize for u8 { - fn normalize(self) -> u16 { self as u16 * 0x100 } + fn normalize(self) -> u16 { + self as u16 * 0x100 + } } impl Normalize for u8 { - fn normalize(self) -> f32 { self as f32 * 255.0_f32.recip() } + fn normalize(self) -> f32 { + self as f32 * 255.0_f32.recip() + } } impl Normalize for i16 { - fn normalize(self) -> i8 { (self / 0x100) as i8 } + fn normalize(self) -> i8 { + (self / 0x100) as i8 + } } impl Normalize for i16 { - fn normalize(self) -> u8 { (self.max(0) / 0x80) as u8 } + fn normalize(self) -> u8 { + (self.max(0) / 0x80) as u8 + } } impl Normalize for i16 { - fn normalize(self) -> i16 { self } + fn normalize(self) -> i16 { + self + } } impl Normalize for i16 { - fn normalize(self) -> u16 { self.max(0) as u16 * 2 } + fn normalize(self) -> u16 { + self.max(0) as u16 * 2 + } } impl Normalize for i16 { - fn normalize(self) -> f32 { (self as f32 * 32767.0_f32.recip()).max(-1.0) } + fn normalize(self) -> f32 { + (self as f32 * 32767.0_f32.recip()).max(-1.0) + } } impl Normalize for u16 { - fn normalize(self) -> i8 { (self / 0x200) as i8 } + fn normalize(self) -> i8 { + (self / 0x200) as i8 + } } impl Normalize for u16 { - fn normalize(self) -> u8 { (self / 0x100) as u8 } + fn normalize(self) -> u8 { + (self / 0x100) as u8 + } } impl Normalize for u16 { - fn normalize(self) -> i16 { (self / 2) as i16 } + fn normalize(self) -> i16 { + (self / 2) as i16 + } } impl Normalize for u16 { - fn normalize(self) -> u16 { self } + fn normalize(self) -> u16 { + self + } } impl Normalize for u16 { - fn normalize(self) -> f32 { self as f32 * 65535.0_f32.recip() } + fn normalize(self) -> f32 { + self as f32 * 65535.0_f32.recip() + } } impl Normalize for f32 { - fn normalize(self) -> i8 { (self * 127.0) as i8 } + fn normalize(self) -> i8 { + (self * 127.0) as i8 + } } impl Normalize for f32 { - fn normalize(self) -> u8 { (self.max(0.0) * 255.0) as u8 } + fn normalize(self) -> u8 { + (self.max(0.0) * 255.0) as u8 + } } impl Normalize for f32 { - fn normalize(self) -> i16 { (self * 32767.0) as i16 } + fn normalize(self) -> i16 { + (self * 32767.0) as i16 + } } impl Normalize for f32 { - fn normalize(self) -> u16 { (self.max(0.0) * 65535.0) as u16 } + fn normalize(self) -> u16 { + (self.max(0.0) * 65535.0) as u16 + } } impl Normalize for f32 { - fn normalize(self) -> f32 { self } + fn normalize(self) -> f32 { + self + } } -impl Normalize<[T; 2]> for [U; 2] where U: Normalize + Copy { +impl Normalize<[T; 2]> for [U; 2] +where + U: Normalize + Copy, +{ fn normalize(self) -> [T; 2] { [self[0].normalize(), self[1].normalize()] } } -impl Normalize<[T; 3]> for [U; 3] where U: Normalize + Copy { +impl Normalize<[T; 3]> for [U; 3] +where + U: Normalize + Copy, +{ fn normalize(self) -> [T; 3] { - [self[0].normalize(), self[1].normalize(), self[2].normalize()] + [ + self[0].normalize(), + self[1].normalize(), + self[2].normalize(), + ] } } -impl Normalize<[T; 4]> for [U; 4] where U: Normalize + Copy { +impl Normalize<[T; 4]> for [U; 4] +where + U: Normalize + Copy, +{ fn normalize(self) -> [T; 4] { - [self[0].normalize(), self[1].normalize(), self[2].normalize(), self[3].normalize()] + [ + self[0].normalize(), + self[1].normalize(), + self[2].normalize(), + self[3].normalize(), + ] } } diff --git a/src/material.rs b/src/material.rs index 9221acfd..1d97cfa7 100644 --- a/src/material.rs +++ b/src/material.rs @@ -99,9 +99,11 @@ impl<'a> Material<'a> { #[cfg(feature = "KHR_materials_pbrSpecularGlossiness")] #[cfg_attr(docsrs, doc(cfg(feature = "KHR_materials_pbrSpecularGlossiness")))] pub fn pbr_specular_glossiness(&self) -> Option> { - self.json.extensions + self.json + .extensions .as_ref()? - .pbr_specular_glossiness.as_ref() + .pbr_specular_glossiness + .as_ref() .map(|x| PbrSpecularGlossiness::new(self.document, x)) } @@ -109,9 +111,11 @@ impl<'a> Material<'a> { #[cfg(feature = "KHR_materials_transmission")] #[cfg_attr(docsrs, doc(cfg(feature = "KHR_materials_transmission")))] pub fn transmission(&self) -> Option> { - self.json.extensions + self.json + .extensions .as_ref()? - .transmission.as_ref() + .transmission + .as_ref() .map(|x| Transmission::new(self.document, x)) } @@ -119,19 +123,18 @@ impl<'a> Material<'a> { #[cfg(feature = "KHR_materials_ior")] #[cfg_attr(docsrs, doc(cfg(feature = "KHR_materials_ior")))] pub fn ior(&self) -> Option { - self.json.extensions - .as_ref()? - .ior.as_ref() - .map(|x| x.ior.0) + self.json.extensions.as_ref()?.ior.as_ref().map(|x| x.ior.0) } /// Parameter values that define a volume for the transmission of light through the material #[cfg(feature = "KHR_materials_volume")] #[cfg_attr(docsrs, doc(cfg(feature = "KHR_materials_volume")))] pub fn volume(&self) -> Option> { - self.json.extensions + self.json + .extensions .as_ref()? - .volume.as_ref() + .volume + .as_ref() .map(|x| Volume::new(self.document, x)) } @@ -139,9 +142,11 @@ impl<'a> Material<'a> { #[cfg(feature = "KHR_materials_specular")] #[cfg_attr(docsrs, doc(cfg(feature = "KHR_materials_specular")))] pub fn specular(&self) -> Option> { - self.json.extensions + self.json + .extensions .as_ref()? - .specular.as_ref() + .specular + .as_ref() .map(|x| Specular::new(self.document, x)) } @@ -200,15 +205,16 @@ impl<'a> Material<'a> { } /// Specifies whether the material is unlit. - /// - /// Returns `true` if the [`KHR_materials_unlit`] property was specified, in which + /// + /// Returns `true` if the [`KHR_materials_unlit`] property was specified, in which /// case the renderer should prefer to ignore all PBR values except `baseColor`. - /// + /// /// [`KHR_materials_unlit`](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit#overview) #[cfg(feature = "KHR_materials_unlit")] #[cfg_attr(docsrs, doc(cfg(feature = "KHR_materials_unlit")))] pub fn unlit(&self) -> bool { - self.json.extensions + self.json + .extensions .as_ref() .map_or(false, |extensions| extensions.unlit.is_some()) } @@ -351,7 +357,6 @@ pub struct Volume<'a> { json: &'a json::extensions::material::Volume, } - #[cfg(feature = "KHR_materials_volume")] #[cfg_attr(docsrs, doc(cfg(feature = "KHR_materials_volume")))] impl<'a> Volume<'a> { @@ -403,7 +408,6 @@ impl<'a> Volume<'a> { } } - /// Parameter values that define the strength and colour of the specular reflection of the material #[cfg(feature = "KHR_materials_specular")] #[cfg_attr(docsrs, doc(cfg(feature = "KHR_materials_specular")))] @@ -459,7 +463,6 @@ impl<'a> Specular<'a> { }) } - /// Optional application specific data. pub fn extras(&self) -> &'a json::Extras { &self.json.extras @@ -620,7 +623,7 @@ impl<'a> OcclusionTexture<'a> { pub fn texture(&self) -> texture::Texture<'a> { self.texture.clone() } - + /// Optional application specific data. pub fn extras(&self) -> &'a json::Extras { &self.json.extras diff --git a/src/math.rs b/src/math.rs index fc88216b..5c13ba4c 100644 --- a/src/math.rs +++ b/src/math.rs @@ -18,8 +18,8 @@ use std::ops; #[cfg(test)] mod test { - use approx; use super::*; + use approx; impl approx::AbsDiffEq for Vector4 { type Epsilon = f32; @@ -29,12 +29,9 @@ mod test { fn abs_diff_eq(&self, other: &Vector4, epsilon: Self::Epsilon) -> bool { f32::abs_diff_eq(&self.x, &other.x, epsilon) - && - f32::abs_diff_eq(&self.y, &other.y, epsilon) - && - f32::abs_diff_eq(&self.z, &other.z, epsilon) - && - f32::abs_diff_eq(&self.w, &other.w, epsilon) + && f32::abs_diff_eq(&self.y, &other.y, epsilon) + && f32::abs_diff_eq(&self.z, &other.z, epsilon) + && f32::abs_diff_eq(&self.w, &other.w, epsilon) } } @@ -45,12 +42,9 @@ mod test { fn relative_eq(&self, other: &Self, epsilon: f32, max_relative: f32) -> bool { f32::relative_eq(&self.x, &other.x, epsilon, max_relative) - && - f32::relative_eq(&self.y, &other.y, epsilon, max_relative) - && - f32::relative_eq(&self.z, &other.z, epsilon, max_relative) - && - f32::relative_eq(&self.w, &other.w, epsilon, max_relative) + && f32::relative_eq(&self.y, &other.y, epsilon, max_relative) + && f32::relative_eq(&self.z, &other.z, epsilon, max_relative) + && f32::relative_eq(&self.w, &other.w, epsilon, max_relative) } } @@ -61,12 +55,9 @@ mod test { fn ulps_eq(&self, other: &Self, epsilon: f32, max_ulps: u32) -> bool { f32::ulps_eq(&self.x, &other.x, epsilon, max_ulps) - && - f32::ulps_eq(&self.y, &other.y, epsilon, max_ulps) - && - f32::ulps_eq(&self.z, &other.z, epsilon, max_ulps) - && - f32::ulps_eq(&self.w, &other.w, epsilon, max_ulps) + && f32::ulps_eq(&self.y, &other.y, epsilon, max_ulps) + && f32::ulps_eq(&self.z, &other.z, epsilon, max_ulps) + && f32::ulps_eq(&self.w, &other.w, epsilon, max_ulps) } } @@ -78,12 +69,9 @@ mod test { fn abs_diff_eq(&self, other: &Matrix4, epsilon: Self::Epsilon) -> bool { Vector4::abs_diff_eq(&self.x, &other.x, epsilon) - && - Vector4::abs_diff_eq(&self.y, &other.y, epsilon) - && - Vector4::abs_diff_eq(&self.z, &other.z, epsilon) - && - Vector4::abs_diff_eq(&self.w, &other.w, epsilon) + && Vector4::abs_diff_eq(&self.y, &other.y, epsilon) + && Vector4::abs_diff_eq(&self.z, &other.z, epsilon) + && Vector4::abs_diff_eq(&self.w, &other.w, epsilon) } } @@ -94,12 +82,9 @@ mod test { fn relative_eq(&self, other: &Self, epsilon: f32, max_relative: f32) -> bool { Vector4::relative_eq(&self.x, &other.x, epsilon, max_relative) - && - Vector4::relative_eq(&self.y, &other.y, epsilon, max_relative) - && - Vector4::relative_eq(&self.z, &other.z, epsilon, max_relative) - && - Vector4::relative_eq(&self.w, &other.w, epsilon, max_relative) + && Vector4::relative_eq(&self.y, &other.y, epsilon, max_relative) + && Vector4::relative_eq(&self.z, &other.z, epsilon, max_relative) + && Vector4::relative_eq(&self.w, &other.w, epsilon, max_relative) } } @@ -110,12 +95,9 @@ mod test { fn ulps_eq(&self, other: &Self, epsilon: f32, max_ulps: u32) -> bool { Vector4::ulps_eq(&self.x, &other.x, epsilon, max_ulps) - && - Vector4::ulps_eq(&self.y, &other.y, epsilon, max_ulps) - && - Vector4::ulps_eq(&self.z, &other.z, epsilon, max_ulps) - && - Vector4::ulps_eq(&self.w, &other.w, epsilon, max_ulps) + && Vector4::ulps_eq(&self.y, &other.y, epsilon, max_ulps) + && Vector4::ulps_eq(&self.z, &other.z, epsilon, max_ulps) + && Vector4::ulps_eq(&self.w, &other.w, epsilon, max_ulps) } } } @@ -147,6 +129,11 @@ impl Vector3 { pub fn normalize(self) -> Vector3 { self * (1.0 / self.magnitude()) } + + #[cfg(test)] + pub fn from_array([x, y, z]: [f32; 3]) -> Self { + Self { x, y, z } + } } impl ops::Mul for Vector3 { @@ -181,6 +168,11 @@ impl Vector4 { pub fn as_array(&self) -> [f32; 4] { [self.x, self.y, self.z, self.w] } + + #[cfg(test)] + pub fn from_array([x, y, z, w]: [f32; 4]) -> Self { + Self { x, y, z, w } + } } impl ops::Add for Vector4 { @@ -213,6 +205,7 @@ pub struct Matrix3 { } impl Matrix3 { + #[rustfmt::skip] pub fn new( c0r0: f32, c0r1: f32, c0r2: f32, c1r0: f32, c1r1: f32, c1r2: f32, @@ -246,12 +239,13 @@ pub struct Matrix4 { } impl Matrix4 { + #[rustfmt::skip] pub fn new( c0r0: f32, c0r1: f32, c0r2: f32, c0r3: f32, c1r0: f32, c1r1: f32, c1r2: f32, c1r3: f32, c2r0: f32, c2r1: f32, c2r2: f32, c2r3: f32, c3r0: f32, c3r1: f32, c3r2: f32, c3r3: f32, - ) -> Matrix4 { + ) -> Matrix4 { Matrix4 { x: Vector4::new(c0r0, c0r1, c0r2, c0r3), y: Vector4::new(c1r0, c1r1, c1r2, c1r3), @@ -261,16 +255,17 @@ impl Matrix4 { } #[cfg(test)] - pub fn from_array(m: [[f32; 4]; 4]) -> Matrix4 { - Matrix4::new( - m[0][0], m[0][1], m[0][2], m[0][3], - m[1][0], m[1][1], m[1][2], m[1][3], - m[2][0], m[2][1], m[2][2], m[2][3], - m[3][0], m[3][1], m[3][2], m[3][3], - ) + pub fn from_array([x, y, z, w]: [[f32; 4]; 4]) -> Matrix4 { + Matrix4 { + x: Vector4::from_array(x), + y: Vector4::from_array(y), + z: Vector4::from_array(z), + w: Vector4::from_array(w), + } } /// Create a homogeneous transformation matrix from a translation vector. + #[rustfmt::skip] pub fn from_translation(v: Vector3) -> Matrix4 { Matrix4::new( 1.0, 0.0, 0.0, 0.0, @@ -281,6 +276,7 @@ impl Matrix4 { } /// Create a homogeneous transformation matrix from a set of scale values. + #[rustfmt::skip] pub fn from_nonuniform_scale(x: f32, y: f32, z: f32) -> Matrix4 { Matrix4::new( x, 0.0, 0.0, 0.0, @@ -308,12 +304,12 @@ impl Matrix4 { let sz2 = z2 * q.s; let sx2 = x2 * q.s; - Matrix4::new( - 1.0 - yy2 - zz2, xy2 + sz2, xz2 - sy2, 0.0, - xy2 - sz2, 1.0 - xx2 - zz2, yz2 + sx2, 0.0, - xz2 + sy2, yz2 - sx2, 1.0 - xx2 - yy2, 0.0, - 0.0, 0.0, 0.0, 1.0, - ) + Matrix4 { + x: Vector4::new(1.0 - yy2 - zz2, xy2 + sz2, xz2 - sy2, 0.0), + y: Vector4::new(xy2 - sz2, 1.0 - xx2 - zz2, yz2 + sx2, 0.0), + z: Vector4::new(xz2 + sy2, yz2 - sx2, 1.0 - xx2 - yy2, 0.0), + w: Vector4::new(0.0, 0.0, 0.0, 1.0), + } } pub fn as_array(&self) -> [[f32; 4]; 4] { diff --git a/src/mesh/iter.rs b/src/mesh/iter.rs index 5f91a630..dbffd5e8 100644 --- a/src/mesh/iter.rs +++ b/src/mesh/iter.rs @@ -24,15 +24,15 @@ pub struct Attributes<'a> { /// The internal attribute iterator. pub(crate) iter: collections::hash_map::Iter< - 'a, + 'a, json::validation::Checked, json::Index, - >, + >, } /// An `Iterator` that visits the primitives of a `Mesh`. #[derive(Clone, Debug)] -pub struct Primitives<'a> { +pub struct Primitives<'a> { /// The parent `Mesh` struct. pub(crate) mesh: Mesh<'a>, @@ -44,13 +44,11 @@ impl<'a> ExactSizeIterator for Attributes<'a> {} impl<'a> Iterator for Attributes<'a> { type Item = Attribute<'a>; fn next(&mut self) -> Option { - self.iter - .next() - .map(|(key, index)| { - let semantic = key.as_ref().unwrap().clone(); - let accessor = self.document.accessors().nth(index.value()).unwrap(); - (semantic, accessor) - }) + self.iter.next().map(|(key, index)| { + let semantic = key.as_ref().unwrap().clone(); + let accessor = self.document.accessors().nth(index.value()).unwrap(); + (semantic, accessor) + }) } fn size_hint(&self) -> (usize, Option) { @@ -62,7 +60,9 @@ impl<'a> ExactSizeIterator for Primitives<'a> {} impl<'a> Iterator for Primitives<'a> { type Item = Primitive<'a>; fn next(&mut self) -> Option { - self.iter.next().map(|(index, json)| Primitive::new(self.mesh.clone(), index, json)) + self.iter + .next() + .map(|(index, json)| Primitive::new(self.mesh.clone(), index, json)) } fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() @@ -72,21 +72,31 @@ impl<'a> Iterator for Primitives<'a> { } fn last(self) -> Option { let mesh = self.mesh; - self.iter.last().map(|(index, json)| Primitive::new(mesh, index, json)) + self.iter + .last() + .map(|(index, json)| Primitive::new(mesh, index, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|(index, json)| Primitive::new(self.mesh.clone(), index, json)) + self.iter + .nth(n) + .map(|(index, json)| Primitive::new(self.mesh.clone(), index, json)) } } -fn map_morph_target<'a>(document: &'a crate::Document, json: &json::mesh::MorphTarget) -> MorphTarget<'a> { - let positions = json.positions +fn map_morph_target<'a>( + document: &'a crate::Document, + json: &json::mesh::MorphTarget, +) -> MorphTarget<'a> { + let positions = json + .positions .as_ref() .map(|index| document.accessors().nth(index.value()).unwrap()); - let normals = json.normals + let normals = json + .normals .as_ref() .map(|index| document.accessors().nth(index.value()).unwrap()); - let tangents = json.tangents + let tangents = json + .tangents .as_ref() .map(|index| document.accessors().nth(index.value()).unwrap()); MorphTarget { @@ -112,10 +122,14 @@ impl<'a> Iterator for MorphTargets<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|json| map_morph_target(document, json)) + self.iter + .last() + .map(|json| map_morph_target(document, json)) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|json| map_morph_target(self.document, json)) + self.iter + .nth(n) + .map(|json| map_morph_target(self.document, json)) } } @@ -149,10 +163,14 @@ impl<'a> Iterator for Mappings<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|json| crate::khr_materials_variants::Mapping::new(document, json)) + self.iter + .last() + .map(|json| crate::khr_materials_variants::Mapping::new(document, json)) } fn nth(&mut self, n: usize) -> Option { let document = self.document; - self.iter.nth(n).map(|json| crate::khr_materials_variants::Mapping::new(document, json)) + self.iter + .nth(n) + .map(|json| crate::khr_materials_variants::Mapping::new(document, json)) } } diff --git a/src/mesh/mod.rs b/src/mesh/mod.rs index 59854e2a..db899432 100644 --- a/src/mesh/mod.rs +++ b/src/mesh/mod.rs @@ -82,7 +82,7 @@ pub struct Bounds { /// A set of primitives to be rendered. #[derive(Clone, Debug)] -pub struct Mesh<'a> { +pub struct Mesh<'a> { /// The parent `Document` struct. document: &'a Document, @@ -108,7 +108,7 @@ pub struct MorphTarget<'a> { /// Geometry to be rendered with the given material. #[derive(Clone, Debug)] -pub struct Primitive<'a> { +pub struct Primitive<'a> { /// The parent `Mesh` struct. mesh: Mesh<'a>, @@ -129,13 +129,9 @@ where pub(crate) get_buffer_data: F, } -impl<'a> Mesh<'a> { +impl<'a> Mesh<'a> { /// Constructs a `Mesh`. - pub(crate) fn new( - document: &'a Document, - index: usize, - json: &'a json::mesh::Mesh, - ) -> Self { + pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::mesh::Mesh) -> Self { Self { document: document, index: index, @@ -176,11 +172,7 @@ impl<'a> Mesh<'a> { impl<'a> Primitive<'a> { /// Constructs a `Primitive`. - pub(crate) fn new( - mesh: Mesh<'a>, - index: usize, - json: &'a json::mesh::Primitive, - ) -> Self { + pub(crate) fn new(mesh: Mesh<'a>, index: usize, json: &'a json::mesh::Primitive) -> Self { Self { mesh: mesh, index: index, @@ -191,8 +183,17 @@ impl<'a> Primitive<'a> { /// Returns the bounds of the `POSITION` vertex attribute. pub fn bounding_box(&self) -> BoundingBox { // NOTE: cannot panic if validated "minimally" - let pos_accessor_index = self.json.attributes.get(&Checked::Valid(Semantic::Positions)).unwrap(); - let pos_accessor = self.mesh.document.accessors().nth(pos_accessor_index.value()).unwrap(); + let pos_accessor_index = self + .json + .attributes + .get(&Checked::Valid(Semantic::Positions)) + .unwrap(); + let pos_accessor = self + .mesh + .document + .accessors() + .nth(pos_accessor_index.value()) + .unwrap(); let min: [f32; 3] = json::deserialize::from_value(pos_accessor.min().unwrap()).unwrap(); let max: [f32; 3] = json::deserialize::from_value(pos_accessor.max().unwrap()).unwrap(); Bounds { min, max } @@ -205,7 +206,8 @@ impl<'a> Primitive<'a> { /// Return the accessor with the given semantic. pub fn get(&self, semantic: &Semantic) -> Option> { - self.json.attributes + self.json + .attributes .get(&json::validation::Checked::Valid(semantic.clone())) .map(|index| self.mesh.document.accessors().nth(index.value()).unwrap()) } @@ -217,7 +219,8 @@ impl<'a> Primitive<'a> { /// Returns the accessor containing the primitive indices, if provided. pub fn indices(&self) -> Option> { - self.json.indices + self.json + .indices .as_ref() .map(|index| self.mesh.document.accessors().nth(index.value()).unwrap()) } @@ -233,7 +236,8 @@ impl<'a> Primitive<'a> { /// Returns the material to apply to this primitive when rendering pub fn material(&self) -> Material<'a> { - self.json.material + self.json + .material .as_ref() .map(|index| self.mesh.document.materials().nth(index.value()).unwrap()) .unwrap_or_else(|| Material::default(self.mesh.document)) @@ -280,20 +284,21 @@ impl<'a> Primitive<'a> { /// Constructs the primitive reader. #[cfg(feature = "utils")] #[cfg_attr(docsrs, doc(cfg(feature = "utils")))] - pub fn reader<'s, F>( - &'a self, - get_buffer_data: F, - ) -> Reader<'a, 's, F> + pub fn reader<'s, F>(&'a self, get_buffer_data: F) -> Reader<'a, 's, F> where F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, { - Reader { primitive: self, get_buffer_data } + Reader { + primitive: self, + get_buffer_data, + } } } #[cfg(feature = "utils")] impl<'a, 's, F> Reader<'a, 's, F> - where F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, +where + F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, { /// Visits the vertex positions of a primitive. pub fn read_positions(&self) -> Option> { @@ -318,84 +323,97 @@ impl<'a, 's, F> Reader<'a, 's, F> /// Visits the vertex colors of a primitive. pub fn read_colors(&self, set: u32) -> Option> { - use accessor::DataType::{U8, U16, F32}; - use accessor::Dimensions::{Vec3, Vec4}; use self::util::ReadColors; + use accessor::DataType::{F32, U16, U8}; + use accessor::Dimensions::{Vec3, Vec4}; self.primitive .get(&Semantic::Colors(set)) - .and_then(|accessor| { - match (accessor.data_type(), accessor.dimensions()) { - (U8, Vec3) => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadColors::RgbU8), - (U16, Vec3) => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadColors::RgbU16), - (F32, Vec3) => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadColors::RgbF32), - (U8, Vec4) => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadColors::RgbaU8), - (U16, Vec4) => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadColors::RgbaU16), - (F32, Vec4) => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadColors::RgbaF32), + .and_then( + |accessor| match (accessor.data_type(), accessor.dimensions()) { + (U8, Vec3) => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadColors::RgbU8), + (U16, Vec3) => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadColors::RgbU16), + (F32, Vec3) => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadColors::RgbF32), + (U8, Vec4) => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadColors::RgbaU8), + (U16, Vec4) => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadColors::RgbaU16), + (F32, Vec4) => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadColors::RgbaF32), _ => unreachable!(), - } - }) + }, + ) } /// Visits the vertex draw sequence of a primitive. pub fn read_indices(&self) -> Option> { - use accessor::DataType; use self::util::ReadIndices; + use accessor::DataType; self.primitive .indices() - .and_then(|accessor| { - match accessor.data_type() { - DataType::U8 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadIndices::U8), - DataType::U16 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadIndices::U16), - DataType::U32 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadIndices::U32), - _ => unreachable!(), + .and_then(|accessor| match accessor.data_type() { + DataType::U8 => { + accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadIndices::U8) } + DataType::U16 => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadIndices::U16), + DataType::U32 => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadIndices::U32), + _ => unreachable!(), }) } /// Visits the joint indices of the primitive. pub fn read_joints(&self, set: u32) -> Option> { - use accessor::DataType; use self::util::ReadJoints; + use accessor::DataType; self.primitive .get(&Semantic::Joints(set)) - .and_then(|accessor| { - match accessor.data_type() { - DataType::U8 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadJoints::U8), - DataType::U16 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadJoints::U16), - _ => unreachable!(), + .and_then(|accessor| match accessor.data_type() { + DataType::U8 => { + accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadJoints::U8) + } + DataType::U16 => { + accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadJoints::U16) } + _ => unreachable!(), }) } /// Visits the vertex texture co-ordinates of a primitive. pub fn read_tex_coords(&self, set: u32) -> Option> { - use accessor::DataType; use self::util::ReadTexCoords; + use accessor::DataType; self.primitive .get(&Semantic::TexCoords(set)) - .and_then(|accessor| { - match accessor.data_type() { - DataType::U8 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadTexCoords::U8), - DataType::U16 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadTexCoords::U16), - DataType::F32 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadTexCoords::F32), - _ => unreachable!(), - } + .and_then(|accessor| match accessor.data_type() { + DataType::U8 => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadTexCoords::U8), + DataType::U16 => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadTexCoords::U16), + DataType::F32 => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadTexCoords::F32), + _ => unreachable!(), }) } /// Visits the joint weights of the primitive. - pub fn read_weights(&self, set: u32) -> Option> { + pub fn read_weights(&self, set: u32) -> Option> { use self::accessor::DataType; use self::util::ReadWeights; self.primitive .get(&Semantic::Weights(set)) - .and_then(|accessor| { - match accessor.data_type() { - DataType::U8 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadWeights::U8), - DataType::U16 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadWeights::U16), - DataType::F32 => accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadWeights::F32), - _ => unreachable!(), + .and_then(|accessor| match accessor.data_type() { + DataType::U8 => { + accessor::Iter::new(accessor, self.get_buffer_data.clone()).map(ReadWeights::U8) } + DataType::U16 => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadWeights::U16), + DataType::F32 => accessor::Iter::new(accessor, self.get_buffer_data.clone()) + .map(ReadWeights::F32), + _ => unreachable!(), }) } diff --git a/src/mesh/util/colors.rs b/src/mesh/util/colors.rs index 50ed2820..91aebb3b 100644 --- a/src/mesh/util/colors.rs +++ b/src/mesh/util/colors.rs @@ -37,30 +37,44 @@ trait ColorChannel { } impl ColorChannel for u8 { - fn max_color() -> Self { u8::max_value() } + fn max_color() -> Self { + u8::max_value() + } } impl ColorChannel for u16 { - fn max_color() -> Self { u16::max_value() } + fn max_color() -> Self { + u16::max_value() + } } impl ColorChannel for f32 { - fn max_color() -> Self { 1.0 } + fn max_color() -> Self { + 1.0 + } } trait ColorArray { - fn into_rgb(self) -> [T; 3]; + fn into_rgb(self) -> [T; 3]; fn into_rgba(self) -> [T; 4]; } impl ColorArray for [T; 3] { - fn into_rgb(self) -> [T; 3] { self } - fn into_rgba(self) -> [T; 4] { [self[0], self[1], self[2], T::max_color()] } + fn into_rgb(self) -> [T; 3] { + self + } + fn into_rgba(self) -> [T; 4] { + [self[0], self[1], self[2], T::max_color()] + } } impl ColorArray for [T; 4] { - fn into_rgb(self) -> [T; 3] { [self[0], self[1], self[2]] } - fn into_rgba(self) -> [T; 4] { self } + fn into_rgb(self) -> [T; 3] { + [self[0], self[1], self[2]] + } + fn into_rgba(self) -> [T; 4] { + self + } } /// Trait for types which describe casting behaviour. @@ -105,10 +119,10 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn next(&mut self) -> Option { match self.0 { - ReadColors::RgbU8(ref mut i) => i.next().map(A::cast_rgb_u8), - ReadColors::RgbU16(ref mut i) => i.next().map(A::cast_rgb_u16), - ReadColors::RgbF32(ref mut i) => i.next().map(A::cast_rgb_f32), - ReadColors::RgbaU8(ref mut i) => i.next().map(A::cast_rgba_u8), + ReadColors::RgbU8(ref mut i) => i.next().map(A::cast_rgb_u8), + ReadColors::RgbU16(ref mut i) => i.next().map(A::cast_rgb_u16), + ReadColors::RgbF32(ref mut i) => i.next().map(A::cast_rgb_f32), + ReadColors::RgbaU8(ref mut i) => i.next().map(A::cast_rgba_u8), ReadColors::RgbaU16(ref mut i) => i.next().map(A::cast_rgba_u16), ReadColors::RgbaF32(ref mut i) => i.next().map(A::cast_rgba_f32), } @@ -117,10 +131,10 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn nth(&mut self, x: usize) -> Option { match self.0 { - ReadColors::RgbU8(ref mut i) => i.nth(x).map(A::cast_rgb_u8), - ReadColors::RgbU16(ref mut i) => i.nth(x).map(A::cast_rgb_u16), - ReadColors::RgbF32(ref mut i) => i.nth(x).map(A::cast_rgb_f32), - ReadColors::RgbaU8(ref mut i) => i.nth(x).map(A::cast_rgba_u8), + ReadColors::RgbU8(ref mut i) => i.nth(x).map(A::cast_rgb_u8), + ReadColors::RgbU16(ref mut i) => i.nth(x).map(A::cast_rgb_u16), + ReadColors::RgbF32(ref mut i) => i.nth(x).map(A::cast_rgb_f32), + ReadColors::RgbaU8(ref mut i) => i.nth(x).map(A::cast_rgba_u8), ReadColors::RgbaU16(ref mut i) => i.nth(x).map(A::cast_rgba_u16), ReadColors::RgbaF32(ref mut i) => i.nth(x).map(A::cast_rgba_f32), } @@ -128,10 +142,10 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { fn last(self) -> Option { match self.0 { - ReadColors::RgbU8(i) => i.last().map(A::cast_rgb_u8), - ReadColors::RgbU16(i) => i.last().map(A::cast_rgb_u16), - ReadColors::RgbF32(i) => i.last().map(A::cast_rgb_f32), - ReadColors::RgbaU8(i) => i.last().map(A::cast_rgba_u8), + ReadColors::RgbU8(i) => i.last().map(A::cast_rgb_u8), + ReadColors::RgbU16(i) => i.last().map(A::cast_rgb_u16), + ReadColors::RgbF32(i) => i.last().map(A::cast_rgb_f32), + ReadColors::RgbaU8(i) => i.last().map(A::cast_rgba_u8), ReadColors::RgbaU16(i) => i.last().map(A::cast_rgba_u16), ReadColors::RgbaF32(i) => i.last().map(A::cast_rgba_f32), } @@ -144,10 +158,10 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn size_hint(&self) -> (usize, Option) { match self.0 { - ReadColors::RgbU8(ref i) => i.size_hint(), - ReadColors::RgbU16(ref i) => i.size_hint(), - ReadColors::RgbF32(ref i) => i.size_hint(), - ReadColors::RgbaU8(ref i) => i.size_hint(), + ReadColors::RgbU8(ref i) => i.size_hint(), + ReadColors::RgbU16(ref i) => i.size_hint(), + ReadColors::RgbF32(ref i) => i.size_hint(), + ReadColors::RgbaU8(ref i) => i.size_hint(), ReadColors::RgbaU16(ref i) => i.size_hint(), ReadColors::RgbaF32(ref i) => i.size_hint(), } diff --git a/src/mesh/util/indices.rs b/src/mesh/util/indices.rs index 898abe6c..acf99572 100644 --- a/src/mesh/util/indices.rs +++ b/src/mesh/util/indices.rs @@ -43,7 +43,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn next(&mut self) -> Option { match self.0 { - ReadIndices::U8(ref mut i) => i.next().map(A::cast_u8), + ReadIndices::U8(ref mut i) => i.next().map(A::cast_u8), ReadIndices::U16(ref mut i) => i.next().map(A::cast_u16), ReadIndices::U32(ref mut i) => i.next().map(A::cast_u32), } @@ -52,7 +52,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn nth(&mut self, x: usize) -> Option { match self.0 { - ReadIndices::U8(ref mut i) => i.nth(x).map(A::cast_u8), + ReadIndices::U8(ref mut i) => i.nth(x).map(A::cast_u8), ReadIndices::U16(ref mut i) => i.nth(x).map(A::cast_u16), ReadIndices::U32(ref mut i) => i.nth(x).map(A::cast_u32), } @@ -60,7 +60,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { fn last(self) -> Option { match self.0 { - ReadIndices::U8(i) => i.last().map(A::cast_u8), + ReadIndices::U8(i) => i.last().map(A::cast_u8), ReadIndices::U16(i) => i.last().map(A::cast_u16), ReadIndices::U32(i) => i.last().map(A::cast_u32), } @@ -73,7 +73,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn size_hint(&self) -> (usize, Option) { match self.0 { - ReadIndices::U8(ref i) => i.size_hint(), + ReadIndices::U8(ref i) => i.size_hint(), ReadIndices::U16(ref i) => i.size_hint(), ReadIndices::U32(ref i) => i.size_hint(), } @@ -83,7 +83,13 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { impl Cast for U32 { type Output = u32; - fn cast_u8(x: u8) -> Self::Output { x as Self::Output } - fn cast_u16(x: u16) -> Self::Output { x as Self::Output } - fn cast_u32(x: u32) -> Self::Output { x } + fn cast_u8(x: u8) -> Self::Output { + x as Self::Output + } + fn cast_u16(x: u16) -> Self::Output { + x as Self::Output + } + fn cast_u32(x: u32) -> Self::Output { + x + } } diff --git a/src/mesh/util/joints.rs b/src/mesh/util/joints.rs index 09e20e9f..b8202272 100644 --- a/src/mesh/util/joints.rs +++ b/src/mesh/util/joints.rs @@ -40,7 +40,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn next(&mut self) -> Option { match self.0 { - ReadJoints::U8(ref mut i) => i.next().map(A::cast_u8), + ReadJoints::U8(ref mut i) => i.next().map(A::cast_u8), ReadJoints::U16(ref mut i) => i.next().map(A::cast_u16), } } @@ -48,14 +48,14 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn nth(&mut self, x: usize) -> Option { match self.0 { - ReadJoints::U8(ref mut i) => i.nth(x).map(A::cast_u8), + ReadJoints::U8(ref mut i) => i.nth(x).map(A::cast_u8), ReadJoints::U16(ref mut i) => i.nth(x).map(A::cast_u16), } } fn last(self) -> Option { match self.0 { - ReadJoints::U8(i) => i.last().map(A::cast_u8), + ReadJoints::U8(i) => i.last().map(A::cast_u8), ReadJoints::U16(i) => i.last().map(A::cast_u16), } } @@ -67,7 +67,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn size_hint(&self) -> (usize, Option) { match self.0 { - ReadJoints::U8(ref i) => i.size_hint(), + ReadJoints::U8(ref i) => i.size_hint(), ReadJoints::U16(ref i) => i.size_hint(), } } diff --git a/src/mesh/util/mod.rs b/src/mesh/util/mod.rs index 371cca38..206373f5 100644 --- a/src/mesh/util/mod.rs +++ b/src/mesh/util/mod.rs @@ -110,10 +110,10 @@ where pub(crate) reader: mesh::Reader<'a, 's, F>, } -impl<'a, 's, F> ExactSizeIterator for ReadMorphTargets<'a, 's, F> -where - F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, -{} +impl<'a, 's, F> ExactSizeIterator for ReadMorphTargets<'a, 's, F> where + F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]> +{ +} impl<'a, 's, F> Iterator for ReadMorphTargets<'a, 's, F> where @@ -126,7 +126,8 @@ where ); fn next(&mut self) -> Option { self.index += 1; - self.reader.primitive + self.reader + .primitive .morph_targets() .nth(self.index - 1) .map(|morph_target| { diff --git a/src/mesh/util/tex_coords.rs b/src/mesh/util/tex_coords.rs index 26a039aa..92f68a50 100644 --- a/src/mesh/util/tex_coords.rs +++ b/src/mesh/util/tex_coords.rs @@ -53,7 +53,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn next(&mut self) -> Option { match self.0 { - ReadTexCoords::U8(ref mut i) => i.next().map(A::cast_u8), + ReadTexCoords::U8(ref mut i) => i.next().map(A::cast_u8), ReadTexCoords::U16(ref mut i) => i.next().map(A::cast_u16), ReadTexCoords::F32(ref mut i) => i.next().map(A::cast_f32), } @@ -62,7 +62,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn nth(&mut self, x: usize) -> Option { match self.0 { - ReadTexCoords::U8(ref mut i) => i.nth(x).map(A::cast_u8), + ReadTexCoords::U8(ref mut i) => i.nth(x).map(A::cast_u8), ReadTexCoords::U16(ref mut i) => i.nth(x).map(A::cast_u16), ReadTexCoords::F32(ref mut i) => i.nth(x).map(A::cast_f32), } @@ -70,7 +70,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { fn last(self) -> Option { match self.0 { - ReadTexCoords::U8(i) => i.last().map(A::cast_u8), + ReadTexCoords::U8(i) => i.last().map(A::cast_u8), ReadTexCoords::U16(i) => i.last().map(A::cast_u16), ReadTexCoords::F32(i) => i.last().map(A::cast_f32), } @@ -83,7 +83,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn size_hint(&self) -> (usize, Option) { match self.0 { - ReadTexCoords::U8(ref i) => i.size_hint(), + ReadTexCoords::U8(ref i) => i.size_hint(), ReadTexCoords::U16(ref i) => i.size_hint(), ReadTexCoords::F32(ref i) => i.size_hint(), } diff --git a/src/mesh/util/weights.rs b/src/mesh/util/weights.rs index e3fd8279..1edf4b21 100644 --- a/src/mesh/util/weights.rs +++ b/src/mesh/util/weights.rs @@ -53,7 +53,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn next(&mut self) -> Option { match self.0 { - ReadWeights::U8(ref mut i) => i.next().map(A::cast_u8), + ReadWeights::U8(ref mut i) => i.next().map(A::cast_u8), ReadWeights::U16(ref mut i) => i.next().map(A::cast_u16), ReadWeights::F32(ref mut i) => i.next().map(A::cast_f32), } @@ -62,7 +62,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn nth(&mut self, x: usize) -> Option { match self.0 { - ReadWeights::U8(ref mut i) => i.nth(x).map(A::cast_u8), + ReadWeights::U8(ref mut i) => i.nth(x).map(A::cast_u8), ReadWeights::U16(ref mut i) => i.nth(x).map(A::cast_u16), ReadWeights::F32(ref mut i) => i.nth(x).map(A::cast_f32), } @@ -70,7 +70,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { fn last(self) -> Option { match self.0 { - ReadWeights::U8(i) => i.last().map(A::cast_u8), + ReadWeights::U8(i) => i.last().map(A::cast_u8), ReadWeights::U16(i) => i.last().map(A::cast_u16), ReadWeights::F32(i) => i.last().map(A::cast_f32), } @@ -83,7 +83,7 @@ impl<'a, A: Cast> Iterator for CastingIter<'a, A> { #[inline] fn size_hint(&self) -> (usize, Option) { match self.0 { - ReadWeights::U8(ref i) => i.size_hint(), + ReadWeights::U8(ref i) => i.size_hint(), ReadWeights::U16(ref i) => i.size_hint(), ReadWeights::F32(ref i) => i.size_hint(), } diff --git a/src/scene/iter.rs b/src/scene/iter.rs index f2dae70e..bd6431e4 100644 --- a/src/scene/iter.rs +++ b/src/scene/iter.rs @@ -52,9 +52,13 @@ impl<'a> Iterator for Children<'a> { } fn last(self) -> Option { let document = self.document; - self.iter.last().map(|index| document.nodes().nth(index.value()).unwrap()) + self.iter + .last() + .map(|index| document.nodes().nth(index.value()).unwrap()) } fn nth(&mut self, n: usize) -> Option { - self.iter.nth(n).map(|index| self.document.nodes().nth(index.value()).unwrap()) + self.iter + .nth(n) + .map(|index| self.document.nodes().nth(index.value()).unwrap()) } } diff --git a/src/scene/mod.rs b/src/scene/mod.rs index 837a3241..785e3bea 100644 --- a/src/scene/mod.rs +++ b/src/scene/mod.rs @@ -34,12 +34,16 @@ impl Transform { pub fn matrix(self) -> [[f32; 4]; 4] { match self { Transform::Matrix { matrix } => matrix, - Transform::Decomposed { translation: t, rotation: r, scale: s } => { + Transform::Decomposed { + translation: t, + rotation: r, + scale: s, + } => { let t = Matrix4::from_translation(Vector3::new(t[0], t[1], t[2])); let r = Matrix4::from_quaternion(Quaternion::new(r[3], r[0], r[1], r[2])); let s = Matrix4::from_nonuniform_scale(s[0], s[1], s[2]); (t * r * s).as_array() - }, + } } } @@ -51,6 +55,7 @@ impl Transform { match self { Transform::Matrix { matrix: m } => { let translation = [m[3][0], m[3][1], m[3][2]]; + #[rustfmt::skip] let mut i = Matrix3::new( m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], @@ -66,10 +71,12 @@ impl Transform { let r = Quaternion::from_matrix(i); let rotation = [r.v.x, r.v.y, r.v.z, r.s]; (translation, rotation, scale) - }, - Transform::Decomposed { translation, rotation, scale } => { - (translation, rotation, scale) - }, + } + Transform::Decomposed { + translation, + rotation, + scale, + } => (translation, rotation, scale), } } } @@ -106,11 +113,7 @@ pub struct Scene<'a> { impl<'a> Node<'a> { /// Constructs a `Node`. - pub(crate) fn new( - document: &'a Document, - index: usize, - json: &'a json::scene::Node, - ) -> Self { + pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::scene::Node) -> Self { Self { document: document, index: index, @@ -125,9 +128,10 @@ impl<'a> Node<'a> { /// Returns the camera referenced by this node. pub fn camera(&self) -> Option> { - self.json.camera.as_ref().map(|index| { - self.document.cameras().nth(index.value()).unwrap() - }) + self.json + .camera + .as_ref() + .map(|index| self.document.cameras().nth(index.value()).unwrap()) } /// Returns an `Iterator` that visits the node's children. @@ -161,9 +165,10 @@ impl<'a> Node<'a> { /// Returns the mesh referenced by this node. pub fn mesh(&self) -> Option> { - self.json.mesh.as_ref().map(|index| { - self.document.meshes().nth(index.value()).unwrap() - }) + self.json + .mesh + .as_ref() + .map(|index| self.document.meshes().nth(index.value()).unwrap()) } /// Optional user-defined name for this object. @@ -185,21 +190,23 @@ impl<'a> Node<'a> { } } else { Transform::Decomposed { - translation: self.json.translation - .unwrap_or_else(|| [0.0, 0.0, 0.0]), - rotation: self.json.rotation - .unwrap_or_else(json::scene::UnitQuaternion::default).0, - scale: self.json.scale - .unwrap_or_else(|| [1.0, 1.0, 1.0]), + translation: self.json.translation.unwrap_or_else(|| [0.0, 0.0, 0.0]), + rotation: self + .json + .rotation + .unwrap_or_else(json::scene::UnitQuaternion::default) + .0, + scale: self.json.scale.unwrap_or_else(|| [1.0, 1.0, 1.0]), } } } /// Returns the skin referenced by this node. pub fn skin(&self) -> Option> { - self.json.skin.as_ref().map(|index| { - self.document.skins().nth(index.value()).unwrap() - }) + self.json + .skin + .as_ref() + .map(|index| self.document.skins().nth(index.value()).unwrap()) } /// Returns the weights of the instantiated morph target. @@ -210,11 +217,7 @@ impl<'a> Node<'a> { impl<'a> Scene<'a> { /// Constructs a `Scene`. - pub(crate) fn new( - document: &'a Document, - index: usize, - json: &'a json::scene::Scene, - ) -> Self { + pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::scene::Scene) -> Self { Self { document: document, index: index, @@ -228,7 +231,7 @@ impl<'a> Scene<'a> { } /// Optional application specific data. - pub fn extras(&self) -> &'a json::Extras{ + pub fn extras(&self) -> &'a json::Extras { &self.json.extras } @@ -249,8 +252,8 @@ impl<'a> Scene<'a> { #[cfg(test)] mod tests { - use crate::scene::Transform; use crate::math::*; + use crate::scene::Transform; use std::f32::consts::PI; fn rotate(x: f32, y: f32, z: f32, r: f32) -> [f32; 4] { @@ -259,9 +262,19 @@ mod tests { } fn test_decompose(translation: [f32; 3], rotation: [f32; 4], scale: [f32; 3]) { - let matrix = Transform::Decomposed { translation, rotation, scale }.matrix(); + let matrix = Transform::Decomposed { + translation, + rotation, + scale, + } + .matrix(); let (translation, rotation, scale) = Transform::Matrix { matrix }.decomposed(); - let check = Transform::Decomposed { translation, rotation, scale }.matrix(); + let check = Transform::Decomposed { + translation, + rotation, + scale, + } + .matrix(); assert_relative_eq!( Matrix4::from_array(check), Matrix4::from_array(matrix), diff --git a/src/skin/mod.rs b/src/skin/mod.rs index 03d325cb..7710b8fa 100644 --- a/src/skin/mod.rs +++ b/src/skin/mod.rs @@ -30,11 +30,7 @@ pub struct Skin<'a> { impl<'a> Skin<'a> { /// Constructs a `Skin`. - pub(crate) fn new( - document: &'a Document, - index: usize, - json: &'a json::skin::Skin, - ) -> Self { + pub(crate) fn new(document: &'a Document, index: usize, json: &'a json::skin::Skin) -> Self { Self { document: document, index: index, @@ -57,23 +53,16 @@ impl<'a> Skin<'a> { /// When `None`, each matrix is assumed to be the 4x4 identity matrix which /// implies that the inverse-bind matrices were pre-applied. pub fn inverse_bind_matrices(&self) -> Option> { - self.json.inverse_bind_matrices + self.json + .inverse_bind_matrices .as_ref() - .map(|index| { - self.document - .accessors() - .nth(index.value()) - .unwrap() - }) + .map(|index| self.document.accessors().nth(index.value()).unwrap()) } /// Constructs a skin reader. #[cfg(feature = "utils")] #[cfg_attr(docsrs, doc(cfg(feature = "utils")))] - pub fn reader<'s, F>( - &'a self, - get_buffer_data: F, - ) -> Reader<'a, 's, F> + pub fn reader<'s, F>(&'a self, get_buffer_data: F) -> Reader<'a, 's, F> where F: Clone + Fn(Buffer<'a>) -> Option<&'s [u8]>, { @@ -102,8 +91,9 @@ impl<'a> Skin<'a> { /// Returns the node used as the skeleton root. When `None`, joints /// transforms resolve to scene root. pub fn skeleton(&self) -> Option> { - self.json.skeleton.as_ref().map(|index| { - self.document.nodes().nth(index.value()).unwrap() - }) + self.json + .skeleton + .as_ref() + .map(|index| self.document.nodes().nth(index.value()).unwrap()) } } diff --git a/src/texture.rs b/src/texture.rs index bf37ffde..d152ab63 100644 --- a/src/texture.rs +++ b/src/texture.rs @@ -132,15 +132,24 @@ impl<'a> Texture<'a> { /// Returns the sampler used by this texture. pub fn sampler(&self) -> Sampler<'a> { - self.json.sampler + self.json + .sampler .as_ref() - .map(|index| self.document.samplers().nth(index.value() as usize).unwrap()) + .map(|index| { + self.document + .samplers() + .nth(index.value() as usize) + .unwrap() + }) .unwrap_or_else(|| Sampler::default(self.document)) } /// Returns the image used by this texture. pub fn source(&self) -> image::Image<'a> { - self.document.images().nth(self.json.source.value() as usize).unwrap() + self.document + .images() + .nth(self.json.source.value() as usize) + .unwrap() } /// Optional application specific data. diff --git a/tests/import_sanity_check.rs b/tests/import_sanity_check.rs index 6257ddda..53c3f070 100644 --- a/tests/import_sanity_check.rs +++ b/tests/import_sanity_check.rs @@ -1,5 +1,5 @@ -use std::{fs, path}; use std::error::Error as StdError; +use std::{fs, path}; const SAMPLE_MODELS_DIRECTORY_PATH: &str = "glTF-Sample-Models/2.0"; diff --git a/tests/roundtrip_binary_gltf.rs b/tests/roundtrip_binary_gltf.rs index b9e18abc..ba2b9979 100644 --- a/tests/roundtrip_binary_gltf.rs +++ b/tests/roundtrip_binary_gltf.rs @@ -3,8 +3,8 @@ //! Read some binary glTF, write it to disk, and compare to the original. //! The test will succeed if the output is the same as the original. -use std::{boxed, error, fs, io, path}; use std::io::Read; +use std::{boxed, error, fs, io, path}; const SAMPLE_MODELS_DIRECTORY_PATH: &str = "glTF-Sample-Models/2.0"; @@ -19,7 +19,8 @@ fn run() -> Result<(), boxed::Box> { if let Some(file_name) = entry_path.file_name() { let mut path = entry_path.join("glTF-Binary").join(file_name); path.set_extension("glb"); - if path.exists() { // not all models have binary versions + if path.exists() { + // not all models have binary versions if let Err(err) = test(&path) { println!("{:?}: error: {:?}", path, err); all_tests_passed = false; @@ -69,7 +70,7 @@ fn test(path: &path::Path) -> Result<(), boxed::Box> { } /// Test a file with a sparse accessor with no buffer view. -/// +/// /// Return true if the test passes, and false otherwise. fn sparse_accessor_without_buffer_view_test() -> bool { let path = path::Path::new("tests/box_sparse.glb"); diff --git a/tests/test_wrapper.rs b/tests/test_wrapper.rs index f91cb608..e59108f5 100644 --- a/tests/test_wrapper.rs +++ b/tests/test_wrapper.rs @@ -1,5 +1,5 @@ -use std::{fs, io}; use std::io::Read; +use std::{fs, io}; use gltf::mesh::Bounds; @@ -14,7 +14,11 @@ fn test_accessor_bounds() { let mesh = &gltf.meshes().nth(0).unwrap(); let prim = mesh.primitives().nth(0).unwrap(); let bounds = prim.bounding_box(); - assert_eq!(bounds, Bounds { min: [-0.03, -0.04, -0.05], max: [1.0, 1.01, 0.02]}); + assert_eq!( + bounds, + Bounds { + min: [-0.03, -0.04, -0.05], + max: [1.0, 1.01, 0.02] + } + ); } - - From 38237685b16fb359dc2aa878dd243b1d87e7d1d3 Mon Sep 17 00:00:00 2001 From: Samuel Hurel Date: Sat, 29 Jan 2022 11:17:41 +0100 Subject: [PATCH 2/2] add formatting check to tests --- .appveyor.yml | 3 ++- gltf-json/src/accessor.rs | 19 +++---------------- gltf-json/src/animation.rs | 16 +++------------- gltf-json/src/buffer.rs | 6 +----- gltf-json/src/camera.rs | 6 +----- gltf-json/src/extensions/scene.rs | 7 +------ gltf-json/src/image.rs | 6 +----- gltf-json/src/material.rs | 7 +------ gltf-json/src/mesh.rs | 7 +------ gltf-json/src/texture.rs | 7 +------ 10 files changed, 15 insertions(+), 69 deletions(-) diff --git a/.appveyor.yml b/.appveyor.yml index 73eed662..1268c28e 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -12,4 +12,5 @@ before_test: - git submodule update --init --recursive test_script: - - cargo test --all --all-features --release \ No newline at end of file + - cargo test --all --all-features --release + - cargo fmt --all -- --check diff --git a/gltf-json/src/accessor.rs b/gltf-json/src/accessor.rs index 56dedc0e..6b3b18ad 100644 --- a/gltf-json/src/accessor.rs +++ b/gltf-json/src/accessor.rs @@ -71,24 +71,11 @@ pub const VALID_COMPONENT_TYPES: &'static [u32] = &[ ]; /// All valid index component types. -#[rustfmt::skip] -pub const VALID_INDEX_TYPES: &'static [u32] = &[ - UNSIGNED_BYTE, - UNSIGNED_SHORT, - UNSIGNED_INT -]; +pub const VALID_INDEX_TYPES: &'static [u32] = &[UNSIGNED_BYTE, UNSIGNED_SHORT, UNSIGNED_INT]; /// All valid accessor types. -#[rustfmt::skip] -pub const VALID_ACCESSOR_TYPES: &'static [&'static str] = &[ - "SCALAR", - "VEC2", - "VEC3", - "VEC4", - "MAT2", - "MAT3", - "MAT4" -]; +pub const VALID_ACCESSOR_TYPES: &'static [&'static str] = + &["SCALAR", "VEC2", "VEC3", "VEC4", "MAT2", "MAT3", "MAT4"]; /// Contains data structures for sparse storage. pub mod sparse { diff --git a/gltf-json/src/animation.rs b/gltf-json/src/animation.rs index 3ef85778..4016ff0e 100644 --- a/gltf-json/src/animation.rs +++ b/gltf-json/src/animation.rs @@ -6,21 +6,11 @@ use serde_derive::{Deserialize, Serialize}; use std::fmt; /// All valid animation interpolation algorithms. -#[rustfmt::skip] -pub const VALID_INTERPOLATIONS: &'static [&'static str] = &[ - "LINEAR", - "STEP", - "CUBICSPLINE" -]; +pub const VALID_INTERPOLATIONS: &'static [&'static str] = &["LINEAR", "STEP", "CUBICSPLINE"]; /// All valid animation property names. -#[rustfmt::skip] -pub const VALID_PROPERTIES: &'static [&'static str] = &[ - "translation", - "rotation", - "scale", - "weights" -]; +pub const VALID_PROPERTIES: &'static [&'static str] = + &["translation", "rotation", "scale", "weights"]; /// Specifies an interpolation algorithm. #[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize)] diff --git a/gltf-json/src/buffer.rs b/gltf-json/src/buffer.rs index c2626cd5..a5a6709b 100644 --- a/gltf-json/src/buffer.rs +++ b/gltf-json/src/buffer.rs @@ -18,11 +18,7 @@ pub const MIN_BYTE_STRIDE: u32 = 4; pub const MAX_BYTE_STRIDE: u32 = 252; /// All valid GPU buffer targets. -#[rustfmt::skip] -pub const VALID_TARGETS: &'static [u32] = &[ - ARRAY_BUFFER, - ELEMENT_ARRAY_BUFFER -]; +pub const VALID_TARGETS: &'static [u32] = &[ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER]; /// Specifies the target a GPU buffer should be bound to. #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/gltf-json/src/camera.rs b/gltf-json/src/camera.rs index 7b973a84..f2fdb28b 100644 --- a/gltf-json/src/camera.rs +++ b/gltf-json/src/camera.rs @@ -6,11 +6,7 @@ use serde_derive::{Deserialize, Serialize}; use std::fmt; /// All valid camera types. -#[rustfmt::skip] -pub const VALID_CAMERA_TYPES: &'static [&'static str] = &[ - "perspective", - "orthographic" -]; +pub const VALID_CAMERA_TYPES: &'static [&'static str] = &["perspective", "orthographic"]; /// Specifies the camera type. #[derive(Clone, Copy, Debug, Eq, PartialEq)] diff --git a/gltf-json/src/extensions/scene.rs b/gltf-json/src/extensions/scene.rs index e3689ca9..953fe0ac 100644 --- a/gltf-json/src/extensions/scene.rs +++ b/gltf-json/src/extensions/scene.rs @@ -32,12 +32,7 @@ pub mod khr_lights_punctual { use std::fmt; /// All valid light types. - #[rustfmt::skip] - pub const VALID_TYPES: &'static [&'static str] = &[ - "directional", - "point", - "spot" - ]; + pub const VALID_TYPES: &'static [&'static str] = &["directional", "point", "spot"]; #[derive(Clone, Debug, Deserialize, Serialize, Validate)] pub struct KhrLightsPunctual { diff --git a/gltf-json/src/image.rs b/gltf-json/src/image.rs index e56c7b00..9987964f 100644 --- a/gltf-json/src/image.rs +++ b/gltf-json/src/image.rs @@ -4,11 +4,7 @@ use gltf_derive::Validate; use serde_derive::{Deserialize, Serialize}; /// All valid MIME types. -#[rustfmt::skip] -pub const VALID_MIME_TYPES: &'static [&'static str] = &[ - "image/jpeg", - "image/png" -]; +pub const VALID_MIME_TYPES: &'static [&'static str] = &["image/jpeg", "image/png"]; /// Image data used to create a texture. #[derive(Clone, Debug, Deserialize, Serialize, Validate)] diff --git a/gltf-json/src/material.rs b/gltf-json/src/material.rs index 33b2f74d..130990f4 100644 --- a/gltf-json/src/material.rs +++ b/gltf-json/src/material.rs @@ -6,12 +6,7 @@ use serde_derive::{Deserialize, Serialize}; use std::fmt; /// All valid alpha modes. -#[rustfmt::skip] -pub const VALID_ALPHA_MODES: &'static [&'static str] = &[ - "OPAQUE", - "MASK", - "BLEND" -]; +pub const VALID_ALPHA_MODES: &'static [&'static str] = &["OPAQUE", "MASK", "BLEND"]; /// The alpha rendering mode of a material. #[derive(Clone, Copy, Eq, PartialEq, Debug)] diff --git a/gltf-json/src/mesh.rs b/gltf-json/src/mesh.rs index bead3ba3..54df6585 100644 --- a/gltf-json/src/mesh.rs +++ b/gltf-json/src/mesh.rs @@ -40,12 +40,7 @@ pub const VALID_MODES: &'static [u32] = &[ ]; /// All valid semantic names for Morph targets. -#[rustfmt::skip] -pub const VALID_MORPH_TARGETS: &'static [&'static str] = &[ - "POSITION", - "NORMAL", - "TANGENT" -]; +pub const VALID_MORPH_TARGETS: &'static [&'static str] = &["POSITION", "NORMAL", "TANGENT"]; /// The type of primitives to render. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)] diff --git a/gltf-json/src/texture.rs b/gltf-json/src/texture.rs index a8000bad..29a4e17b 100644 --- a/gltf-json/src/texture.rs +++ b/gltf-json/src/texture.rs @@ -46,12 +46,7 @@ pub const VALID_MIN_FILTERS: &'static [u32] = &[ ]; /// All valid wrapping modes. -#[rustfmt::skip] -pub const VALID_WRAPPING_MODES: &'static [u32] = &[ - CLAMP_TO_EDGE, - MIRRORED_REPEAT, - REPEAT -]; +pub const VALID_WRAPPING_MODES: &'static [u32] = &[CLAMP_TO_EDGE, MIRRORED_REPEAT, REPEAT]; /// Magnification filter. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]