diff --git a/examples/anim.rs b/examples/anim.rs index 84bc998..36d2702 100644 --- a/examples/anim.rs +++ b/examples/anim.rs @@ -87,7 +87,7 @@ fn make_indices(meta: &[u16]) -> Vec<[u32; 3]> { fn main() { let mut win = three::Window::new("Three-rs mesh blending example"); - let cam = win.factory.perspective_camera(60.0, 1.0 .. 1000.0); + let cam = win.factory.perspective_camera(60.0, 1.0..1000.0); cam.look_at( [100.0, 0.0, 100.0], [0.0, 0.0, 30.0], @@ -103,17 +103,16 @@ fn main() { faces: make_indices(INDICES), shapes: V_FLY .iter() - .map(|data| { - three::Shape { - vertices: make_vertices(data), - .. three::Shape::default() - } + .map(|data| three::Shape { + vertices: make_vertices(data), + ..three::Shape::default() }) .collect(), ..three::Geometry::default() }; - let mesh = win.factory + let mesh = win + .factory .mesh_dynamic(geom, three::material::Wireframe { color: 0xFFFFFF }); win.scene.add(&mesh); @@ -129,11 +128,7 @@ fn main() { if id0 == V_FLY.len() { id0 = 0; } - id1 = if id0 + 1 < V_FLY.len() { - id0 + 1 - } else { - 0 - }; + id1 = if id0 + 1 < V_FLY.len() { id0 + 1 } else { 0 }; timer.reset(); } win.render(&cam); diff --git a/examples/aviator/main.rs b/examples/aviator/main.rs index 7dba106..0b84f47 100644 --- a/examples/aviator/main.rs +++ b/examples/aviator/main.rs @@ -25,7 +25,7 @@ fn main() { let mut win = three::Window::new("Three-rs Aviator demo"); win.scene.background = three::Background::Color(COLOR_BACKGROUND); - let cam = win.factory.perspective_camera(60.0, 1.0 .. 1000.0); + let cam = win.factory.perspective_camera(60.0, 1.0..1000.0); cam.set_position([0.0, 100.0, 200.0]); win.scene.add(&cam); @@ -37,7 +37,7 @@ fn main() { let mut dir_light = win.factory.directional_light(0xffffff, 0.9); dir_light.look_at([150.0, 350.0, 350.0], [0.0, 0.0, 0.0], None); let shadow_map = win.factory.shadow_map(2048, 2048); - dir_light.set_shadow(shadow_map, 400.0, 1.0 .. 1000.0); + dir_light.set_shadow(shadow_map, 400.0, 1.0..1000.0); win.scene.add(&dir_light); let ambient_light = win.factory.ambient_light(0xdc8874, 0.5); win.scene.add(&ambient_light); diff --git a/examples/aviator/plane.rs b/examples/aviator/plane.rs index f859f87..34dd5fb 100644 --- a/examples/aviator/plane.rs +++ b/examples/aviator/plane.rs @@ -99,11 +99,7 @@ impl AirPlane { } } - pub fn update( - &mut self, - time: f32, - target: mint::Point2<f32>, - ) { + pub fn update(&mut self, time: f32, target: mint::Point2<f32>) { let q = Quaternion::from_angle_x(Rad(0.3 * time)); self.propeller_group.set_orientation(q); self.group diff --git a/examples/aviator/sky.rs b/examples/aviator/sky.rs index 3da0ba7..5b4d3e9 100644 --- a/examples/aviator/sky.rs +++ b/examples/aviator/sky.rs @@ -7,16 +7,12 @@ use three::{self, Object}; use COLOR_WHITE; - pub struct Sky { pub group: three::Group, } impl Sky { - fn make_cloud<R: Rng>( - rng: &mut R, - factory: &mut three::Factory, - ) -> three::Group { + fn make_cloud<R: Rng>(rng: &mut R, factory: &mut three::Factory) -> three::Group { let group = factory.group(); let geo = three::Geometry::cuboid(20.0, 20.0, 20.0); let material = three::material::Lambert { @@ -24,7 +20,7 @@ impl Sky { flat: true, }; let template = factory.mesh(geo, material.clone()); - for i in 0i32 .. rng.gen_range(3, 6) { + for i in 0i32..rng.gen_range(3, 6) { let m = factory.mesh_instance(&template); let rot = cgmath::Quaternion::<f32>::new(rng.gen(), rng.gen(), rng.gen(), rng.gen()); let q = rot.normalize(); @@ -42,14 +38,11 @@ impl Sky { group } - pub fn new<R: Rng>( - rng: &mut R, - factory: &mut three::Factory, - ) -> Self { + pub fn new<R: Rng>(rng: &mut R, factory: &mut three::Factory) -> Self { let group = factory.group(); let num = 20i32; let step_angle = PI * 2.0 / num as f32; - for i in 0 .. num { + for i in 0..num { let cloud = Self::make_cloud(rng, factory); let angle = cgmath::Rad(i as f32 * step_angle); let dist = rng.gen_range(750.0, 950.0); diff --git a/examples/gltf-morph-targets.rs b/examples/gltf-morph-targets.rs index 19d1c51..c7b3b2c 100644 --- a/examples/gltf-morph-targets.rs +++ b/examples/gltf-morph-targets.rs @@ -9,7 +9,10 @@ fn main() { window.scene.add(&light); window.scene.background = three::Background::Color(0xC6F0FF); - let default = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/AnimatedMorphCube/AnimatedMorphCube.gltf"); + let default = concat!( + env!("CARGO_MANIFEST_DIR"), + "/test_data/AnimatedMorphCube/AnimatedMorphCube.gltf" + ); let path = std::env::args().nth(1).unwrap_or(default.into()); // Load the contents of the glTF files. Scenes loaded from the file are returned as @@ -28,7 +31,7 @@ fn main() { // Create a camera with which to render the scene, and control it with the built-in // orbit controller, set to orbit the model. - let camera = window.factory.perspective_camera(60.0, 0.1 .. 20.0); + let camera = window.factory.perspective_camera(60.0, 0.1..20.0); let mut controls = three::controls::Orbit::builder(&camera) .position([-3.0, 3.0, -3.0]) .up([0.0, 1.0, 0.0]) diff --git a/examples/gltf-node-animation.rs b/examples/gltf-node-animation.rs index dccb878..71b3f99 100644 --- a/examples/gltf-node-animation.rs +++ b/examples/gltf-node-animation.rs @@ -9,7 +9,10 @@ fn main() { window.scene.add(&light); window.scene.background = three::Background::Color(0xC6F0FF); - let default = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/BoxAnimated/BoxAnimated.gltf"); + let default = concat!( + env!("CARGO_MANIFEST_DIR"), + "/test_data/BoxAnimated/BoxAnimated.gltf" + ); let path = std::env::args().nth(1).unwrap_or(default.into()); // Load the contents of the glTF files. Scenes loaded from the file are returned as @@ -28,7 +31,7 @@ fn main() { // Create a camera with which to render the scene, and control it with the built-in // orbit controller, set to orbit the model. - let camera = window.factory.perspective_camera(60.0, 0.1 .. 100.0); + let camera = window.factory.perspective_camera(60.0, 0.1..100.0); let mut controls = three::controls::Orbit::builder(&camera) .position([3.0, 3.0, 3.0]) .target([0.0, 1.0, 0.0]) diff --git a/examples/gltf-pbr-shader.rs b/examples/gltf-pbr-shader.rs index cc7c526..2a357ec 100644 --- a/examples/gltf-pbr-shader.rs +++ b/examples/gltf-pbr-shader.rs @@ -1,9 +1,6 @@ extern crate three; -use three::{ - camera::Camera, - Object, -}; +use three::{camera::Camera, Object}; fn main() { let mut win = three::Window::new("Three-rs glTF example"); @@ -12,7 +9,10 @@ fn main() { win.scene.add(&light); win.scene.background = three::Background::Color(0xC6F0FF); - let default = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/Lantern/Lantern.gltf"); + let default = concat!( + env!("CARGO_MANIFEST_DIR"), + "/test_data/Lantern/Lantern.gltf" + ); let path = std::env::args().nth(1).unwrap_or(default.into()); println!("Loading {:?} (this may take a while)", path); @@ -33,7 +33,7 @@ fn main() { // If we didn't find a camera in the glTF scene, create a default one to use. let cam = cam.unwrap_or_else(|| { - let default = win.factory.perspective_camera(60.0, 0.001 .. 100.0); + let default = win.factory.perspective_camera(60.0, 0.001..100.0); win.scene.add(&default); default }); @@ -52,10 +52,7 @@ fn main() { // Determine the current position of the camera so that we can use it to initialize the // camera controller. - let init = win.scene - .sync_guard() - .resolve_world(&cam) - .transform; + let init = win.scene.sync_guard().resolve_world(&cam).transform; // Create a first person camera controller, starting at the camera's current position. let mut controls = three::controls::FirstPerson::builder(&cam) diff --git a/examples/gltf-vertex-skinning.rs b/examples/gltf-vertex-skinning.rs index fd50c87..2182a48 100644 --- a/examples/gltf-vertex-skinning.rs +++ b/examples/gltf-vertex-skinning.rs @@ -9,7 +9,10 @@ fn main() { window.scene.add(&light); window.scene.background = three::Background::Color(0xC6F0FF); - let default = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/BrainStem/BrainStem.gltf"); + let default = concat!( + env!("CARGO_MANIFEST_DIR"), + "/test_data/BrainStem/BrainStem.gltf" + ); let path = std::env::args().nth(1).unwrap_or(default.into()); // Load the contents of the glTF files. Scenes loaded from the file are returned as @@ -28,7 +31,7 @@ fn main() { // Create a camera with which to render the scene, and control it with the built-in // orbit controller, set to orbit the model. - let camera = window.factory.perspective_camera(45.0, 0.1 .. 100.0); + let camera = window.factory.perspective_camera(45.0, 0.1..100.0); let mut controls = three::controls::Orbit::builder(&camera) .position([0.0, 3.0, -1.0]) .target([0.0, 0.0, -1.0]) diff --git a/examples/group.rs b/examples/group.rs index a22fd40..86775be 100644 --- a/examples/group.rs +++ b/examples/group.rs @@ -46,13 +46,11 @@ fn create_cubes( mat_id: usize, lev_id: usize, } - let mut stack = vec![ - Stack { - parent_id: 0, - mat_id: 1, - lev_id: 1, - }, - ]; + let mut stack = vec![Stack { + parent_id: 0, + mat_id: 1, + lev_id: 1, + }]; let axis = [ Vector3::unit_z(), @@ -61,13 +59,15 @@ fn create_cubes( Vector3::unit_y(), -Vector3::unit_y(), ]; - let children: Vec<_> = axis.iter() + let children: Vec<_> = axis + .iter() .map(|&axe| { Decomposed { disp: Vector3::new(0.0, 0.0, 1.0), rot: Quaternion::from_axis_angle(axe, Rad::turn_div_4()), scale: 1.0, - }.concat(&Decomposed { + } + .concat(&Decomposed { disp: Vector3::new(0.0, 0.0, 1.0), rot: Quaternion::one(), scale: 0.4, @@ -106,6 +106,7 @@ struct LevelDesc { color: three::Color, speed: f32, // in radians per second } +#[rustfmt::skip] const LEVELS: &[LevelDesc] = &[ LevelDesc { color: 0xffff80, speed: 0.7 }, LevelDesc { color: 0x8080ff, speed: -1.0 }, @@ -120,7 +121,7 @@ fn main() { let mut win = three::Window::new("Three-rs group example"); win.scene.background = three::Background::Color(0x204060); - let cam = win.factory.perspective_camera(60.0, 1.0 .. 100.0); + let cam = win.factory.perspective_camera(60.0, 1.0..100.0); cam.look_at([-1.8, -8.0, 7.0], [0.0, 0.0, 3.5], None); let light = win.factory.point_light(0xffffff, 1.0); @@ -129,7 +130,10 @@ fn main() { let materials = LEVELS .iter() - .map(|l| three::material::Lambert { color: l.color, flat: false }) + .map(|l| three::material::Lambert { + color: l.color, + flat: false, + }) .collect::<Vec<_>>(); let levels = LEVELS .iter() diff --git a/examples/lights.rs b/examples/lights.rs index a3a9bdf..b668751 100644 --- a/examples/lights.rs +++ b/examples/lights.rs @@ -4,7 +4,7 @@ use three::Object; fn main() { let mut win = three::Window::new("Three-rs lights example"); - let cam = win.factory.perspective_camera(45.0, 1.0 .. 50.0); + let cam = win.factory.perspective_camera(45.0, 1.0..50.0); cam.look_at([-4.0, 15.0, 10.0], [0.0, 0.0, 2.0], None); let hemisphere_light = win.factory.hemisphere_light(0xffffff, 0x8080ff, 0.5); @@ -15,9 +15,10 @@ fn main() { let mut dir_light = win.factory.directional_light(0xffffff, 0.9); dir_light.look_at([15.0, 35.0, 35.0], [0.0, 0.0, 2.0], None); let shadow_map = win.factory.shadow_map(1024, 1024); - let _debug_shadow = win.renderer + let _debug_shadow = win + .renderer .debug_shadow_quad(&shadow_map, 1, [10, 10], [256, 256]); - dir_light.set_shadow(shadow_map, 40.0, 1.0 .. 200.0); + dir_light.set_shadow(shadow_map, 40.0, 1.0..200.0); let lights: [&three::object::Base; 4] = [ hemisphere_light.as_ref(), diff --git a/examples/materials.rs b/examples/materials.rs index 74e764c..ea09c3c 100644 --- a/examples/materials.rs +++ b/examples/materials.rs @@ -4,7 +4,7 @@ use three::Object; fn main() { let mut win = three::Window::new("Three-rs materials example"); - let cam = win.factory.perspective_camera(75.0, 1.0 .. 50.0); + let cam = win.factory.perspective_camera(75.0, 1.0..50.0); cam.set_position([0.0, 0.0, 10.0]); let light = win.factory.point_light(0xffffff, 0.5); @@ -17,19 +17,23 @@ fn main() { three::material::Basic { color: 0xFFFFFF, map: None, - }.into(), + } + .into(), three::material::Lambert { color: 0xFFFFFF, flat: true, - }.into(), + } + .into(), three::material::Lambert { color: 0xFFFFFF, flat: false, - }.into(), + } + .into(), three::material::Phong { color: 0xFFFFFF, glossiness: 80.0, - }.into(), + } + .into(), three::material::Pbr { base_color_factor: 0xFFFFFF, base_color_alpha: 1.0, @@ -43,7 +47,8 @@ fn main() { emissive_map: None, metallic_roughness_map: None, occlusion_map: None, - }.into(), + } + .into(), ]; let count = materials.len(); diff --git a/examples/mesh-update.rs b/examples/mesh-update.rs index b0c45e0..dfa8071 100644 --- a/examples/mesh-update.rs +++ b/examples/mesh-update.rs @@ -5,7 +5,6 @@ extern crate three; use cgmath::prelude::*; use std::f32::consts::PI; - fn make_tetrahedron_geometry() -> three::Geometry { let vertices = vec![ mint::Point3 { @@ -42,7 +41,7 @@ fn make_tetrahedron_geometry() -> three::Geometry { fn main() { let mut win = three::Window::new("Three-rs Mesh Update Example"); - let cam = win.factory.perspective_camera(60.0, 1.0 .. 10.0); + let cam = win.factory.perspective_camera(60.0, 1.0..10.0); let mut controls = three::controls::Orbit::builder(&cam) .position([0.0, 2.0, -5.0]) .target([0.0, 0.0, 0.0]) diff --git a/examples/obj.rs b/examples/obj.rs index 6027d5b..35dc741 100644 --- a/examples/obj.rs +++ b/examples/obj.rs @@ -8,7 +8,7 @@ fn main() { let obj_path = concat!(env!("CARGO_MANIFEST_DIR"), "/test_data/car.obj"); let path = args.nth(1).unwrap_or(obj_path.into()); let mut win = three::Window::new("Three-rs obj loading example"); - let cam = win.factory.perspective_camera(60.0, 1.0 .. 1000.0); + let cam = win.factory.perspective_camera(60.0, 1.0..1000.0); let mut controls = three::controls::Orbit::builder(&cam) .position([0.0, 2.0, -5.0]) .target([0.0, 0.0, 0.0]) diff --git a/examples/reload.rs b/examples/reload.rs index 2c1385f..e4b6d7b 100644 --- a/examples/reload.rs +++ b/examples/reload.rs @@ -1,8 +1,8 @@ extern crate notify; extern crate three; -use std::{env, fs, io}; use std::sync::mpsc; +use std::{env, fs, io}; use notify::Watcher; use std::path::{Path, PathBuf}; @@ -80,8 +80,7 @@ fn main() { println!("Edit sprite_vs.glsl or sprite_ps.glsl and review."); let mut win = three::Window::new("Three-rs shader reloading example"); - let cam = win.factory - .orthographic_camera([0.0, 0.0], 1.0, -1.0 .. 1.0); + let cam = win.factory.orthographic_camera([0.0, 0.0], 1.0, -1.0..1.0); let (tx, rx) = mpsc::channel(); let mut watcher = notify::watcher(tx, Duration::from_secs(1)).unwrap(); diff --git a/examples/shapes.rs b/examples/shapes.rs index bf3ff97..026783b 100644 --- a/examples/shapes.rs +++ b/examples/shapes.rs @@ -7,7 +7,7 @@ use three::Object; fn main() { let mut win = three::Window::new("Three-rs shapes example"); - let cam = win.factory.perspective_camera(75.0, 1.0 .. 50.0); + let cam = win.factory.perspective_camera(75.0, 1.0..50.0); cam.set_position([0.0, 0.0, 10.0]); let mbox = { diff --git a/examples/sprite.rs b/examples/sprite.rs index 4bf2005..663611c 100644 --- a/examples/sprite.rs +++ b/examples/sprite.rs @@ -21,15 +21,14 @@ impl Animator { self.sprite.set_texel_range(base, self.cell_size); } - fn update( - &mut self, - switch_row: Option<u16>, - ) { + fn update(&mut self, switch_row: Option<u16>) { if let Some(row) = switch_row { self.timer.reset(); self.current = [0, row]; self.update_uv(); - } else if self.timer.elapsed() >= self.duration && (self.repeat || self.current[0] < self.cell_counts[0]) { + } else if self.timer.elapsed() >= self.duration + && (self.repeat || self.current[0] < self.cell_counts[0]) + { self.timer.reset(); self.current[0] += 1; if self.current[0] < self.cell_counts[0] { @@ -44,8 +43,9 @@ impl Animator { fn main() { let mut win = three::Window::new("Three-rs sprite example"); - let cam = win.factory - .orthographic_camera([0.0, 0.0], 10.0, -10.0 .. 10.0); + let cam = win + .factory + .orthographic_camera([0.0, 0.0], 10.0, -10.0..10.0); let pikachu_path: String = format!("{}/test_data/pikachu_anim.png", env!("CARGO_MANIFEST_DIR")); let pikachu_path_str: &str = pikachu_path.as_str(); diff --git a/examples/text.rs b/examples/text.rs index 88ebae9..87f1e44 100644 --- a/examples/text.rs +++ b/examples/text.rs @@ -7,7 +7,7 @@ fn main() { let center = [0.0, 0.0]; let yextent = 1.0; - let zrange = -1.0 .. 1.0; + let zrange = -1.0..1.0; let camera = window.factory.orthographic_camera(center, yextent, zrange); let deja_vu = window.factory.load_font(format!( diff --git a/examples/tutorial.rs b/examples/tutorial.rs index d870eb2..a6769cf 100644 --- a/examples/tutorial.rs +++ b/examples/tutorial.rs @@ -19,7 +19,7 @@ fn main() { let center = [0.0, 0.0]; let yextent = 1.0; - let zrange = -1.0 .. 1.0; + let zrange = -1.0..1.0; let camera = window.factory.orthographic_camera(center, yextent, zrange); while window.update() { diff --git a/rustfmt.toml b/rustfmt.toml index ad34fa2..dccb320 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,9 +1,3 @@ -reorder_imports = true -reorder_extern_crates = true -reorder_extern_crates_in_group = true -reorder_imported_names = true -reorder_imports_in_group = true + error_on_line_overflow = false -max_width = 15000 spaces_around_ranges = true -fn_args_density = "Vertical" diff --git a/src/animation.rs b/src/animation.rs index 495f9e2..e7e7932 100644 --- a/src/animation.rs +++ b/src/animation.rs @@ -112,7 +112,6 @@ use object::{Base, Object}; use std::hash::{Hash, Hasher}; use std::sync::mpsc; - /// A target of an animation. pub type Target = Base; @@ -249,10 +248,7 @@ pub struct Action { } impl PartialEq for Action { - fn eq( - &self, - other: &Action, - ) -> bool { + fn eq(&self, other: &Action) -> bool { self.pointer == other.pointer } } @@ -260,10 +256,7 @@ impl PartialEq for Action { impl Eq for Action {} impl Hash for Action { - fn hash<H: Hasher>( - &self, - state: &mut H, - ) { + fn hash<H: Hasher>(&self, state: &mut H) { self.pointer.hash(state); } } @@ -335,10 +328,7 @@ pub struct Mixer { } impl Action { - fn send( - &mut self, - operation: Operation, - ) -> &mut Self { + fn send(&mut self, operation: Operation) -> &mut Self { let message = (self.pointer.downgrade(), operation); let _ = self.tx.send(message); self @@ -365,10 +355,7 @@ impl Action { } /// Sets the animation loop mode. - pub fn set_loop_mode( - &mut self, - loop_mode: LoopMode, - ) -> &mut Self { + pub fn set_loop_mode(&mut self, loop_mode: LoopMode) -> &mut Self { self.send(Operation::SetLoopMode(loop_mode)) } } @@ -393,10 +380,7 @@ impl Mixer { } } - fn update_actions( - &mut self, - delta_time: f32, - ) { + fn update_actions(&mut self, delta_time: f32) { for action in self.actions.iter_mut() { action.update(delta_time); } @@ -412,10 +396,7 @@ impl Mixer { /// Spawns a new animation [`Action`] to be updated by this mixer. /// /// [`Action`]: struct.Action.html - pub fn action( - &mut self, - clip: Clip, - ) -> Action { + pub fn action(&mut self, clip: Clip) -> Action { let action_data = ActionData::new(clip); let pointer = self.actions.create(action_data); let tx = self.tx.clone(); @@ -423,10 +404,7 @@ impl Mixer { } /// Updates the actions owned by the mixer. - pub fn update( - &mut self, - delta_time: f32, - ) { + pub fn update(&mut self, delta_time: f32) { self.process_messages(); self.update_actions(delta_time); } @@ -445,10 +423,7 @@ impl ActionData { } /// Updates a single animation action. - fn update( - &mut self, - delta_time: f32, - ) { + fn update(&mut self, delta_time: f32) { if self.paused || !self.enabled { return; } @@ -546,10 +521,7 @@ impl ActionData { } impl Track { - fn frame_at_time( - &self, - t: f32, - ) -> FrameRef { + fn frame_at_time(&self, t: f32) -> FrameRef { if t < self.times[0] { // The clip hasn't started yet. return FrameRef::Unstarted; diff --git a/src/audio.rs b/src/audio.rs index a8a896c..33378df 100644 --- a/src/audio.rs +++ b/src/audio.rs @@ -36,42 +36,27 @@ impl Clip { } /// Passing true enforces looping sound. Defaults to `false`. - pub fn repeat( - &mut self, - enable: bool, - ) { + pub fn repeat(&mut self, enable: bool) { self.repeat = enable; } /// Clip the sound to the desired duration. - pub fn take_duration( - &mut self, - duration: Duration, - ) { + pub fn take_duration(&mut self, duration: Duration) { self.duration = Some(duration); } /// Play sound after desired delay. - pub fn delay( - &mut self, - delay: Duration, - ) { + pub fn delay(&mut self, delay: Duration) { self.delay = Some(delay); } /// Fade in sound in desired duration. - pub fn fade_in( - &mut self, - duration: Duration, - ) { + pub fn fade_in(&mut self, duration: Duration) { self.fade_in = Some(duration); } /// Adjust the playback speed. Defaults to `1.0`. - pub fn speed( - &mut self, - ratio: f32, - ) { + pub fn speed(&mut self, ratio: f32) { self.speed = ratio; } } @@ -124,10 +109,7 @@ impl Source { } /// Add clip to the queue. - pub fn play( - &self, - clip: &Clip, - ) { + pub fn play(&self, clip: &Clip) { let msg = hub::Operation::SetAudio(Operation::Append(clip.clone())); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } @@ -155,10 +137,7 @@ impl Source { /// Adjust playback volume. /// /// Default value is `1.0`. - pub fn set_volume( - &self, - volume: f32, - ) { + pub fn set_volume(&self, volume: f32) { let msg = hub::Operation::SetAudio(Operation::SetVolume(volume)); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } @@ -172,10 +151,7 @@ pub(crate) enum SourceInternal { } impl fmt::Debug for SourceInternal { - fn fmt( - &self, - f: &mut fmt::Formatter, - ) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { SourceInternal::D2(_) => write!(f, "SourceInternal::D2"), SourceInternal::D3(_) => write!(f, "SourceInternal::D3"), @@ -205,20 +181,14 @@ impl SourceInternal { } } - pub(crate) fn set_volume( - &mut self, - volume: f32, - ) { + pub(crate) fn set_volume(&mut self, volume: f32) { match *self { SourceInternal::D2(ref mut sink) => sink.set_volume(volume), _ => unimplemented!(), } } - pub(crate) fn append( - &mut self, - clip: Clip, - ) { + pub(crate) fn append(&mut self, clip: Clip) { match *self { SourceInternal::D2(ref mut sink) => { let vec: Vec<u8> = (&*clip.data).clone(); diff --git a/src/camera.rs b/src/camera.rs index 941a283..bebb5f6 100644 --- a/src/camera.rs +++ b/src/camera.rs @@ -105,7 +105,9 @@ pub struct Camera { } impl AsRef<Base> for Camera { - fn as_ref(&self) -> &Base { &self.object } + fn as_ref(&self) -> &Base { + &self.object + } } impl Object for Camera { @@ -128,7 +130,8 @@ impl Camera { /// Sets the projection used by the camera. pub fn set_projection<P: Into<Projection>>(&self, projection: P) { - self.as_ref().send(Operation::SetProjection(projection.into())); + self.as_ref() + .send(Operation::SetProjection(projection.into())); } } @@ -143,11 +146,7 @@ impl DowncastObject for Camera { impl Projection { /// Constructs an orthographic projection. - pub fn orthographic<P>( - center: P, - extent_y: f32, - range: ops::Range<f32>, - ) -> Self + pub fn orthographic<P>(center: P, extent_y: f32, range: ops::Range<f32>) -> Self where P: Into<mint::Point2<f32>>, { @@ -160,10 +159,7 @@ impl Projection { } /// Constructs a perspective projection. - pub fn perspective<R>( - fov_y: f32, - range: R, - ) -> Self + pub fn perspective<R>(fov_y: f32, range: R) -> Self where R: Into<ZRange>, { @@ -174,10 +170,7 @@ impl Projection { } /// Computes the projection matrix representing the camera's projection. - pub fn matrix( - &self, - aspect_ratio: f32, - ) -> mint::ColumnMatrix4<f32> { + pub fn matrix(&self, aspect_ratio: f32) -> mint::ColumnMatrix4<f32> { match *self { Projection::Orthographic(ref x) => x.matrix(aspect_ratio), Projection::Perspective(ref x) => x.matrix(aspect_ratio), @@ -199,10 +192,7 @@ pub struct Orthographic { impl Orthographic { /// Computes the projection matrix representing the camera's projection. - pub fn matrix( - &self, - aspect_ratio: f32, - ) -> mint::ColumnMatrix4<f32> { + pub fn matrix(&self, aspect_ratio: f32) -> mint::ColumnMatrix4<f32> { let extent_x = aspect_ratio * self.extent_y; cgmath::ortho( self.center.x - extent_x, @@ -211,7 +201,8 @@ impl Orthographic { self.center.y + self.extent_y, self.range.start, self.range.end, - ).into() + ) + .into() } } @@ -227,17 +218,15 @@ pub struct Perspective { impl Perspective { /// Computes the projection matrix representing the camera's projection. - pub fn matrix( - &self, - aspect_ratio: f32, - ) -> mint::ColumnMatrix4<f32> { + pub fn matrix(&self, aspect_ratio: f32) -> mint::ColumnMatrix4<f32> { match self.zrange { ZRange::Finite(ref range) => cgmath::perspective( cgmath::Deg(self.fov_y), aspect_ratio, range.start, range.end, - ).into(), + ) + .into(), ZRange::Infinite(ref range) => { let f = 1.0 / (0.5 * self.fov_y.to_radians()).tan(); diff --git a/src/controls/first_person.rs b/src/controls/first_person.rs index a1b0e9a..ded745f 100644 --- a/src/controls/first_person.rs +++ b/src/controls/first_person.rs @@ -69,7 +69,7 @@ impl Builder { position: [0.0, 0.0, 0.0].into(), yaw: 0.0, pitch: 0.0, - pitch_range: Some(-PI / 2.0 .. PI / 2.0), + pitch_range: Some(-PI / 2.0..PI / 2.0), move_speed: 1.0, look_speed: 0.5, axes: Axes::default(), @@ -81,10 +81,7 @@ impl Builder { /// Set the initial yaw angle in radians. /// /// Default is 0.0. - pub fn yaw( - &mut self, - yaw: f32, - ) -> &mut Self { + pub fn yaw(&mut self, yaw: f32) -> &mut Self { self.yaw = yaw; self } @@ -92,10 +89,7 @@ impl Builder { /// Set the initial pitch angle in radians. /// /// Defaults to 0.0. - pub fn pitch( - &mut self, - pitch: f32, - ) -> &mut Self { + pub fn pitch(&mut self, pitch: f32) -> &mut Self { self.pitch = pitch; self } @@ -103,10 +97,7 @@ impl Builder { /// Set the initial pitch range in radians. /// /// Defaults to `Some(-PI / 2.0 .. PI / 2.0)`. - pub fn pitch_range( - &mut self, - range: Option<ops::Range<f32>>, - ) -> &mut Self { + pub fn pitch_range(&mut self, range: Option<ops::Range<f32>>) -> &mut Self { self.pitch_range = range; self } @@ -114,10 +105,7 @@ impl Builder { /// Set the initial position. /// /// Defaults to the world origin. - pub fn position<P>( - &mut self, - position: P, - ) -> &mut Self + pub fn position<P>(&mut self, position: P) -> &mut Self where P: Into<mint::Point3<f32>>, { @@ -128,10 +116,7 @@ impl Builder { /// Setup the movement speed in world units per second. /// /// Defaults to 1.0 world units per second. - pub fn move_speed( - &mut self, - speed: f32, - ) -> &mut Self { + pub fn move_speed(&mut self, speed: f32) -> &mut Self { self.move_speed = speed; self } @@ -139,10 +124,7 @@ impl Builder { /// Setup mouse sensitivity. /// /// Defaults to 0.5 - pub fn look_speed( - &mut self, - speed: f32, - ) -> &mut Self { + pub fn look_speed(&mut self, speed: f32) -> &mut Self { self.look_speed = speed; self } @@ -151,10 +133,7 @@ impl Builder { /// down or up. /// /// Defaults to true. - pub fn vertical_movement( - &mut self, - value: bool, - ) -> &mut Self { + pub fn vertical_movement(&mut self, value: bool) -> &mut Self { self.vertical_move = value; self } @@ -162,10 +141,7 @@ impl Builder { /// Setup whether controlled object can adjust pitch using mouse. /// /// Defaults to true. - pub fn vertical_look( - &mut self, - value: bool, - ) -> &mut Self { + pub fn vertical_look(&mut self, value: bool) -> &mut Self { self.vertical_look = value; self } @@ -173,10 +149,7 @@ impl Builder { /// Setup key axis for moving forward/backward. /// /// Defaults to `W` and `S` keys. - pub fn axis_forward( - &mut self, - axis: Option<axis::Key>, - ) -> &mut Self { + pub fn axis_forward(&mut self, axis: Option<axis::Key>) -> &mut Self { self.axes.forward = axis; self } @@ -184,10 +157,7 @@ impl Builder { /// Setup button for "strafing" left/right. /// /// Defaults to `A` and `D` keys. - pub fn axis_strafing( - &mut self, - axis: Option<axis::Key>, - ) -> &mut Self { + pub fn axis_strafing(&mut self, axis: Option<axis::Key>) -> &mut Self { self.axes.strafing = axis; self } @@ -195,10 +165,7 @@ impl Builder { /// Setup button for moving up/down. /// /// Defaults to `None`. - pub fn axis_vertical( - &mut self, - axis: Option<axis::Key>, - ) -> &mut Self { + pub fn axis_vertical(&mut self, axis: Option<axis::Key>) -> &mut Self { self.axes.vertical = axis; self } @@ -232,37 +199,25 @@ impl FirstPerson { } /// Sets the yaw angle in radians. - pub fn set_yaw( - &mut self, - yaw: f32, - ) -> &mut Self { + pub fn set_yaw(&mut self, yaw: f32) -> &mut Self { self.yaw = yaw; self } /// Sets the pitch angle in radians. - pub fn set_pitch( - &mut self, - pitch: f32, - ) -> &mut Self { + pub fn set_pitch(&mut self, pitch: f32) -> &mut Self { self.pitch = pitch; self } /// Sets the pitch range in radians. - pub fn pitch_range( - &mut self, - range: Option<ops::Range<f32>>, - ) -> &mut Self { + pub fn pitch_range(&mut self, range: Option<ops::Range<f32>>) -> &mut Self { self.pitch_range = range; self } /// Sets the object position. - pub fn set_position<P>( - &mut self, - position: P, - ) -> &mut Self + pub fn set_position<P>(&mut self, position: P) -> &mut Self where P: Into<mint::Point3<f32>>, { @@ -271,75 +226,51 @@ impl FirstPerson { } /// Sets the movement speed in world units per second. - pub fn set_move_speed( - &mut self, - speed: f32, - ) -> &mut Self { + pub fn set_move_speed(&mut self, speed: f32) -> &mut Self { self.move_speed = speed; self } /// Sets the mouse sensitivity. - pub fn set_look_speed( - &mut self, - speed: f32, - ) -> &mut Self { + pub fn set_look_speed(&mut self, speed: f32) -> &mut Self { self.look_speed = speed; self } /// Specifies whether controlled object should move along `y` axis when looking /// down or up. - pub fn set_vertical_movement( - &mut self, - value: bool, - ) -> &mut Self { + pub fn set_vertical_movement(&mut self, value: bool) -> &mut Self { self.vertical_move = value; self } /// Specifies whether controlled object can adjust pitch using mouse. - pub fn set_vertical_look( - &mut self, - value: bool, - ) -> &mut Self { + pub fn set_vertical_look(&mut self, value: bool) -> &mut Self { self.vertical_look = value; self } /// Sets the key axis for moving forward/backward. - pub fn set_axis_forward( - &mut self, - axis: Option<axis::Key>, - ) -> &mut Self { + pub fn set_axis_forward(&mut self, axis: Option<axis::Key>) -> &mut Self { self.axes.forward = axis; self } /// Sets the button for "strafing" left/right. - pub fn set_axis_strafing( - &mut self, - axis: Option<axis::Key>, - ) -> &mut Self { + pub fn set_axis_strafing(&mut self, axis: Option<axis::Key>) -> &mut Self { self.axes.strafing = axis; self } /// Sets button for moving up/down. - pub fn set_axis_vertical( - &mut self, - axis: Option<axis::Key>, - ) -> &mut Self { + pub fn set_axis_vertical(&mut self, axis: Option<axis::Key>) -> &mut Self { self.axes.vertical = axis; self } /// Updates the position, yaw, and pitch of the controlled object according to /// the last frame input. - pub fn update( - &mut self, - input: &Input, - ) { + pub fn update(&mut self, input: &Input) { let dlook = input.delta_time() * self.look_speed; let mouse = input.mouse_delta_raw(); diff --git a/src/controls/mod.rs b/src/controls/mod.rs index 223113f..4971f27 100644 --- a/src/controls/mod.rs +++ b/src/controls/mod.rs @@ -32,7 +32,7 @@ pub use self::first_person::FirstPerson; #[doc(inline)] pub use self::orbit::Orbit; -pub use input::{axis, - Button, Delta, Hit, HitCount, Key, Input, Timer, MouseButton, - AXIS_DOWN_UP, AXIS_LEFT_RIGHT, KEY_ESCAPE, KEY_SPACE, MOUSE_LEFT, MOUSE_RIGHT, +pub use input::{ + axis, Button, Delta, Hit, HitCount, Input, Key, MouseButton, Timer, AXIS_DOWN_UP, + AXIS_LEFT_RIGHT, KEY_ESCAPE, KEY_SPACE, MOUSE_LEFT, MOUSE_RIGHT, }; diff --git a/src/controls/orbit.rs b/src/controls/orbit.rs index ce1ba40..bed275e 100644 --- a/src/controls/orbit.rs +++ b/src/controls/orbit.rs @@ -49,10 +49,7 @@ impl Builder { /// Set the initial position. /// /// Defaults to the world origin. - pub fn position<P>( - &mut self, - position: P, - ) -> &mut Self + pub fn position<P>(&mut self, position: P) -> &mut Self where P: Into<mint::Point3<f32>>, { @@ -63,12 +60,9 @@ impl Builder { /// Sets the initial up direction. /// /// Defaults to the unit z axis. - pub fn up<P>( - &mut self, - up: P, - ) -> &mut Self + pub fn up<P>(&mut self, up: P) -> &mut Self where - P: Into<mint::Vector3<f32>> + P: Into<mint::Vector3<f32>>, { self.up = up.into(); self @@ -77,10 +71,7 @@ impl Builder { /// Set the target position. /// /// Defaults to the world origin. - pub fn target<P>( - &mut self, - target: P, - ) -> &mut Self + pub fn target<P>(&mut self, target: P) -> &mut Self where P: Into<mint::Point3<f32>>, { @@ -89,19 +80,13 @@ impl Builder { } /// Setup the speed of the movements. Default value is 1.0 - pub fn speed( - &mut self, - speed: f32, - ) -> &mut Self { + pub fn speed(&mut self, speed: f32) -> &mut Self { self.speed = speed; self } /// Setup control button. Default is left mouse button (`MOUSE_LEFT`). - pub fn button( - &mut self, - button: Button, - ) -> &mut Self { + pub fn button(&mut self, button: Button) -> &mut Self { self.button = button; self } @@ -137,10 +122,7 @@ impl Orbit { } /// Update current position and rotation of the controlled object according to the last frame input. - pub fn update( - &mut self, - input: &Input, - ) { + pub fn update(&mut self, input: &Input) { let mouse_delta = if input.hit(self.button) { input.mouse_delta_ndc() } else { diff --git a/src/custom.rs b/src/custom.rs index 693a4fe..040887f 100644 --- a/src/custom.rs +++ b/src/custom.rs @@ -1,5 +1,5 @@ //! Contains re-exports for custom pipeline state. -pub use gfx::Primitive; pub use gfx::preset; pub use gfx::state; +pub use gfx::Primitive; diff --git a/src/factory/load_gltf.rs b/src/factory/load_gltf.rs index 3d1bd96..fc31dcb 100644 --- a/src/factory/load_gltf.rs +++ b/src/factory/load_gltf.rs @@ -16,20 +16,15 @@ use std::collections::HashMap; use camera::{Orthographic, Perspective, Projection}; use std::path::Path; -use {Material, Texture}; +use super::Factory; use geometry::{Geometry, Shape}; use image::{DynamicImage, ImageBuffer}; use node::Transform; -use super::Factory; use template::{ - AnimationTemplate, - BoneTemplate, - CameraTemplate, - InstancedGeometry, - MeshTemplate, - ObjectTemplate, - Template, + AnimationTemplate, BoneTemplate, CameraTemplate, InstancedGeometry, MeshTemplate, + ObjectTemplate, Template, }; +use {Material, Texture}; fn load_textures( factory: &mut Factory, @@ -41,36 +36,24 @@ fn load_textures( let (width, height) = (data.width, data.height); let image = match data.format { gltf::image::Format::R8 => DynamicImage::ImageLuma8( - ImageBuffer::from_raw( - width, - height, - data.pixels, - ).expect("incorrect image dimensions") + ImageBuffer::from_raw(width, height, data.pixels) + .expect("incorrect image dimensions"), ), gltf::image::Format::R8G8 => DynamicImage::ImageLumaA8( - ImageBuffer::from_raw( - width, - height, - data.pixels, - ).expect("incorrect image dimensions") + ImageBuffer::from_raw(width, height, data.pixels) + .expect("incorrect image dimensions"), ), gltf::image::Format::R8G8B8 => DynamicImage::ImageRgb8( - ImageBuffer::from_raw( - width, - height, - data.pixels, - ).expect("incorrect image dimensions") - ), - gltf::image::Format::R8G8B8A8 => DynamicImage::ImageRgba8( - ImageBuffer::from_raw( - width, - height, - data.pixels, - ).unwrap() + ImageBuffer::from_raw(width, height, data.pixels) + .expect("incorrect image dimensions"), ), - }.to_rgba(); - use {FilterMethod, WrapMode}; + gltf::image::Format::R8G8B8A8 => { + DynamicImage::ImageRgba8(ImageBuffer::from_raw(width, height, data.pixels).unwrap()) + } + } + .to_rgba(); use gltf::texture::{MagFilter, WrappingMode}; + use {FilterMethod, WrapMode}; let params = texture.sampler(); // gfx does not support separate min / mag // filters yet, so for now we'll use `mag_filter` for both. @@ -89,19 +72,18 @@ fn load_textures( WrappingMode::Repeat => WrapMode::Tile, }; let sampler = factory.sampler(mag_filter, wrap_s, wrap_t); - let texture = factory.load_texture_from_memory(width as u16, height as u16, &image, sampler); + let texture = + factory.load_texture_from_memory(width as u16, height as u16, &image, sampler); textures.push(texture); } textures } -fn load_material<'a>( - mat: gltf::Material<'a>, - textures: &[Texture<[f32; 4]>], -) -> Material { +fn load_material<'a>(mat: gltf::Material<'a>, textures: &[Texture<[f32; 4]>]) -> Material { let pbr = mat.pbr_metallic_roughness(); let mut is_basic_material = true; - let base_color_map = pbr.base_color_texture() + let base_color_map = pbr + .base_color_texture() .map(|t| textures[t.as_ref().index()].clone()); let normal_map = mat.normal_texture().map(|t| { is_basic_material = false; @@ -124,30 +106,29 @@ fn load_material<'a>( (color::from_linear_rgb([x[0], x[1], x[2]]), x[3]) }; - if false {// is_basic_material { + if false { + // is_basic_material { material::Basic { color: base_color_factor, map: base_color_map, - }.into() + } + .into() } else { material::Pbr { base_color_factor, base_color_alpha, metallic_factor: pbr.metallic_factor(), roughness_factor: pbr.roughness_factor(), - occlusion_strength: mat.occlusion_texture().map_or(1.0, |t| { - t.strength() - }), + occlusion_strength: mat.occlusion_texture().map_or(1.0, |t| t.strength()), emissive_factor: color::from_linear_rgb(mat.emissive_factor()), - normal_scale: mat.normal_texture().map_or(1.0, |t| { - t.scale() - }), + normal_scale: mat.normal_texture().map_or(1.0, |t| t.scale()), base_color_map, normal_map, emissive_map, metallic_roughness_map, occlusion_map, - }.into() + } + .into() } } @@ -165,11 +146,8 @@ fn load_primitive<'a>( if let Some(iter) = reader.read_indices() { faces.extend(iter.into_u32().tuples().map(|(a, b, c)| [a, b, c])); } - let vertices: Vec<mint::Point3<f32>> = reader - .read_positions() - .unwrap() - .map(|x| x.into()) - .collect(); + let vertices: Vec<mint::Point3<f32>> = + reader.read_positions().unwrap().map(|x| x.into()).collect(); let normals = if let Some(iter) = reader.read_normals() { iter.map(|x| x.into()).collect() } else { @@ -209,7 +187,12 @@ fn load_primitive<'a>( shape.normals.extend(iter.map(mint::Vector3::<f32>::from)); } if let Some(iter) = tangents { - shape.tangents.extend(iter.map(|v| mint::Vector4{ x: v[0], y: v[1], z: v[2], w: 1.0 })); + shape.tangents.extend(iter.map(|v| mint::Vector4 { + x: v[0], + y: v[1], + z: v[2], + w: 1.0, + })); } shape }) @@ -254,7 +237,7 @@ fn load_skin<'a>( use std::iter::repeat; let reader = skin.reader(|buffer| Some(&buffers[buffer.index()].0)); - + let mut ibms = Vec::new(); if let Some(iter) = reader.read_inverse_bind_matrices() { for ibm in iter { @@ -267,19 +250,15 @@ fn load_skin<'a>( [0., 0., 1., 0.], [0., 0., 0., 1.], ]); - let ibm_iter = ibms. - into_iter() - .chain(repeat(mx_id)); + let ibm_iter = ibms.into_iter().chain(repeat(mx_id)); - let joint_iter = skin - .joints() - .map(|joint| joint.index()); + let joint_iter = skin.joints().map(|joint| joint.index()); for (index, (joint_index, inverse_bind_matrix)) in joint_iter.zip(ibm_iter).enumerate() { // Create a bone node corresponding to the joint. let object = objects.len(); objects.push(ObjectTemplate { parent: Some(joint_index), - .. Default::default() + ..Default::default() }); bones.push(BoneTemplate { object, @@ -293,7 +272,7 @@ fn load_skin<'a>( let object = objects.len(); objects.push(ObjectTemplate { parent: skin.skeleton().map(|node| node.index()), - .. Default::default() + ..Default::default() }); object @@ -323,9 +302,7 @@ fn load_animation<'a>( let times: Vec<f32> = reader.read_inputs().unwrap().collect(); let (binding, values) = match reader.read_outputs().unwrap() { gltf::animation::util::ReadOutputs::Translations(iter) => { - let values = iter - .map(|v| mint::Vector3::from(v)) - .collect::<Vec<_>>(); + let values = iter.map(|v| mint::Vector3::from(v)).collect::<Vec<_>>(); assert_eq!(values.len(), times.len()); (Binding::Position, Values::Vector3(values)) } @@ -371,16 +348,12 @@ fn load_animation<'a>( times, values, }, - // Target the object for the group that corresponds to the target node. groups[node.index()], )); } - AnimationTemplate { - name, - tracks, - } + AnimationTemplate { name, tracks } } /// Partially loads a single glTF node and creates template nodes from its data. @@ -447,7 +420,7 @@ fn load_node<'a>( let object = objects.len(); objects.push(ObjectTemplate { parent: Some(node.index()), - .. Default::default() + ..Default::default() }); meshes.push(MeshTemplate { object, @@ -463,7 +436,7 @@ fn load_node<'a>( let object = objects.len(); objects.push(ObjectTemplate { parent: Some(node.index()), - .. Default::default() + ..Default::default() }); cameras.push(CameraTemplate { object, @@ -474,23 +447,25 @@ fn load_node<'a>( object_index } -fn load_camera<'a>( - entry: gltf::Camera<'a>, -) -> Projection { +fn load_camera<'a>(entry: gltf::Camera<'a>) -> Projection { match entry.projection() { gltf::camera::Projection::Orthographic(values) => { let center = mint::Point2::<f32>::from([0.0, 0.0]); let extent_y = values.ymag(); - let range = values.znear() .. values.zfar(); - Projection::Orthographic(Orthographic { center, extent_y, range }) + let range = values.znear()..values.zfar(); + Projection::Orthographic(Orthographic { + center, + extent_y, + range, + }) } gltf::camera::Projection::Perspective(values) => { let fov_y = values.yfov().to_degrees(); let near = values.znear(); let zrange = match values.zfar() { - Some(far) => (near .. far).into(), - None => (near ..).into(), + Some(far) => (near..far).into(), + None => (near..).into(), }; Projection::Perspective(Perspective { fov_y, zrange }) } @@ -502,7 +477,7 @@ fn load_scene<'a>(scene: gltf::Scene<'a>, raw: &Template) -> Template { Template { name: scene.name().map(Into::into), - .. raw.clone() + ..raw.clone() } } @@ -542,15 +517,11 @@ impl super::Factory { /// [`template`]: ./template/index.html /// [`Template`]: ./template/struct.Template.html /// [`Factory::instantiate_template`]: #method.instantiate_template - pub fn load_gltf( - &mut self, - path_str: &str, - ) -> Vec<Template> { + pub fn load_gltf(&mut self, path_str: &str) -> Vec<Template> { info!("Loading glTF file {}", path_str); let path = Path::new(path_str); - let (gltf, buffers, images) = gltf::import(path) - .expect("invalid glTF 2.0"); + let (gltf, buffers, images) = gltf::import(path).expect("invalid glTF 2.0"); let textures = load_textures(self, &gltf, images); @@ -593,7 +564,14 @@ impl super::Factory { let groups: Vec<_> = gltf .nodes() .map(|node| { - load_node(node, &mut objects, &mut meshes, &mut cameras, &mesh_map, &primitives) + load_node( + node, + &mut objects, + &mut meshes, + &mut cameras, + &mesh_map, + &primitives, + ) }) .collect(); @@ -605,7 +583,10 @@ impl super::Factory { for child_index in gltf_node.children().map(|child| child.index()) { let object = &mut objects[groups[child_index]]; - assert!(object.parent.is_none(), "Object template already had a parent specified"); + assert!( + object.parent.is_none(), + "Object template already had a parent specified" + ); object.parent = Some(gltf_node.index()); } } @@ -639,8 +620,7 @@ impl super::Factory { warn!("Mutliple scenes found in {}, glTF loading does not currently work correctly for glTF files with multiple scenes", path.display()); } - gltf - .scenes() + gltf.scenes() .map(|scene| load_scene(scene, &raw_template)) .collect() } diff --git a/src/factory/mod.rs b/src/factory/mod.rs index 95ac677..738786d 100644 --- a/src/factory/mod.rs +++ b/src/factory/mod.rs @@ -1,14 +1,14 @@ #[cfg(feature = "gltf")] mod load_gltf; -use std::{cmp, fs, io, iter, ops}; use std::borrow::Cow; -use std::collections::HashSet; use std::collections::hash_map::{Entry, HashMap}; +use std::collections::HashSet; use std::io::Read; use std::path::{Path, PathBuf}; +use std::{cmp, fs, io, iter, ops}; -use cgmath::{Vector3}; +use cgmath::Vector3; use gfx; use gfx::format::I8Norm; use gfx::traits::{Factory as Factory_, FactoryExt}; @@ -23,27 +23,22 @@ use audio; use animation; use camera::{Camera, Projection, ZRange}; -use color::{BLACK, Color}; +use color::{Color, BLACK}; use geometry::Geometry; use hub::{Hub, HubPtr, LightData, SubLight, SubNode}; use light::{Ambient, Directional, Hemisphere, Point, ShadowMap}; use material::{self, Material}; use mesh::{DynamicMesh, Mesh}; use object::{self, Group, Object}; -use render::{basic_pipe, - BackendFactory, BackendResources, BasicPipelineState, DisplacementContribution, - DynamicData, GpuData, Instance, InstanceCacheKey, PipelineCreationError, ShadowFormat, Source, Vertex, - DEFAULT_VERTEX, VECS_PER_BONE, ZEROED_DISPLACEMENT_CONTRIBUTION, +use render::{ + basic_pipe, BackendFactory, BackendResources, BasicPipelineState, DisplacementContribution, + DynamicData, GpuData, Instance, InstanceCacheKey, PipelineCreationError, ShadowFormat, Source, + Vertex, DEFAULT_VERTEX, VECS_PER_BONE, ZEROED_DISPLACEMENT_CONTRIBUTION, }; use scene::{Background, Scene}; -use sprite::Sprite; use skeleton::{Bone, InverseBindMatrix, Skeleton}; -use template::{ - InstancedGeometry, - LightTemplate, - SubLightTemplate, - Template, -}; +use sprite::Sprite; +use template::{InstancedGeometry, LightTemplate, SubLightTemplate, Template}; use text::{Font, Text, TextData}; use texture::{CubeMap, CubeMapPath, FilterMethod, Sampler, Texture, WrapMode}; @@ -54,22 +49,22 @@ const QUAD: [Vertex; 4] = [ Vertex { pos: [-1.0, -1.0, 0.0, 1.0], uv: [0.0, 0.0], - .. DEFAULT_VERTEX + ..DEFAULT_VERTEX }, Vertex { pos: [1.0, -1.0, 0.0, 1.0], uv: [1.0, 0.0], - .. DEFAULT_VERTEX + ..DEFAULT_VERTEX }, Vertex { pos: [-1.0, 1.0, 0.0, 1.0], uv: [0.0, 1.0], - .. DEFAULT_VERTEX + ..DEFAULT_VERTEX }, Vertex { pos: [1.0, 1.0, 0.0, 1.0], uv: [1.0, 1.0], - .. DEFAULT_VERTEX + ..DEFAULT_VERTEX }, ]; @@ -118,30 +113,42 @@ impl Factory { let displacements = if num_shapes != 0 { let num_vertices = geometry.base.vertices.len(); let mut contents = vec![[0.0; 4]; num_shapes * 3 * num_vertices]; - for (content_chunk, shape) in contents.chunks_mut(3 * num_vertices).zip(&geometry.shapes) { + for (content_chunk, shape) in + contents.chunks_mut(3 * num_vertices).zip(&geometry.shapes) + { let mut contribution = DisplacementContribution::ZERO; if !shape.vertices.is_empty() { contribution.position = 1.0; - for (out, v) in content_chunk[0 * num_vertices .. 1 * num_vertices].iter_mut().zip(&shape.vertices) { + for (out, v) in content_chunk[0 * num_vertices..1 * num_vertices] + .iter_mut() + .zip(&shape.vertices) + { *out = [v.x, v.y, v.z, 1.0]; } } if !shape.normals.is_empty() { contribution.normal = 1.0; - for (out, v) in content_chunk[1 * num_vertices .. 2 * num_vertices].iter_mut().zip(&shape.normals) { + for (out, v) in content_chunk[1 * num_vertices..2 * num_vertices] + .iter_mut() + .zip(&shape.normals) + { *out = [v.x, v.y, v.z, 0.0]; } } if !shape.tangents.is_empty() { contribution.tangent = 1.0; - for (out, &v) in content_chunk[2 * num_vertices .. 3 * num_vertices].iter_mut().zip(&shape.tangents) { + for (out, &v) in content_chunk[2 * num_vertices..3 * num_vertices] + .iter_mut() + .zip(&shape.tangents) + { *out = v.into(); } } displacement_contributions.push(contribution); } - let texture_and_view = self.backend + let texture_and_view = self + .backend .create_texture_immutable::<[f32; 4]>( gfx::texture::Kind::D2( num_vertices as _, @@ -277,10 +284,7 @@ impl Factory { .collect(); for template in &template.meshes { - let mesh = self.create_instanced_mesh( - &template.geometry, - template.material.clone(), - ); + let mesh = self.create_instanced_mesh(&template.geometry, template.material.clone()); if let Some(skeleton_index) = template.skeleton { mesh.set_skeleton(skeletons[skeleton_index].clone()) @@ -295,16 +299,19 @@ impl Factory { } for &template in &template.lights { - let LightTemplate { object, color, intensity, sub_light } = template; + let LightTemplate { + object, + color, + intensity, + sub_light, + } = template; let light = match sub_light { - SubLightTemplate::Ambient => - self.ambient_light(color, intensity).upcast(), - SubLightTemplate::Directional => - self.directional_light(color, intensity).upcast(), - SubLightTemplate::Hemisphere { ground } => - self.hemisphere_light(color, ground, intensity).upcast(), - SubLightTemplate::Point => - self.point_light(color, intensity).upcast(), + SubLightTemplate::Ambient => self.ambient_light(color, intensity).upcast(), + SubLightTemplate::Directional => self.directional_light(color, intensity).upcast(), + SubLightTemplate::Hemisphere { ground } => { + self.hemisphere_light(color, ground, intensity).upcast() + } + SubLightTemplate::Point => self.point_light(color, intensity).upcast(), }; objects.insert(object, light.clone()); } @@ -325,7 +332,9 @@ impl Factory { // HACK: We need to add any `Skeleton` objects to their parent group *last*, so // we skip them. See note above for more details. - if skeleton_objects.contains(&index) { continue; } + if skeleton_objects.contains(&index) { + continue; + } match template.parent { Some(parent) => groups[parent].add(base), @@ -369,12 +378,11 @@ impl Factory { /// /// [`Bone`]: ../skeleton/struct.Bone.html /// [`Skeleton`]: ../skeleton/struct.Skeleton.html - pub fn bone( - &mut self, - index: usize, - inverse_bind_matrix: InverseBindMatrix, - ) -> Bone { - let data = SubNode::Bone { index, inverse_bind_matrix }; + pub fn bone(&mut self, index: usize, inverse_bind_matrix: InverseBindMatrix) -> Bone { + let data = SubNode::Bone { + index, + inverse_bind_matrix, + }; let object = self.hub.lock().unwrap().spawn(data); Bone { object } } @@ -385,11 +393,9 @@ impl Factory { /// * `inverses` is an optional array of inverse bind matrices for each bone. /// [`Skeleton`]: ../skeleton/struct.Skeleton.html /// [`Bone`]: ../skeleton/struct.Bone.html - pub fn skeleton( - &mut self, - bones: Vec<Bone>, - ) -> Skeleton { - let gpu_buffer = self.backend + pub fn skeleton(&mut self, bones: Vec<Bone>) -> Skeleton { + let gpu_buffer = self + .backend .create_buffer( bones.len() * VECS_PER_BONE, gfx::buffer::Role::Constant, @@ -397,10 +403,15 @@ impl Factory { gfx::memory::Bind::SHADER_RESOURCE, ) .expect("create GPU target buffer"); - let gpu_buffer_view = self.backend + let gpu_buffer_view = self + .backend .view_buffer_as_shader_resource(&gpu_buffer) .expect("create shader resource view for GPU target buffer"); - let data = hub::SkeletonData { bones, gpu_buffer, gpu_buffer_view }; + let data = hub::SkeletonData { + bones, + gpu_buffer, + gpu_buffer_view, + }; let object = self.hub.lock().unwrap().spawn_skeleton(data); Skeleton { object } } @@ -412,10 +423,7 @@ impl Factory { /// of projection the camera uses. If you're manually creating a camera, you should use /// [`perspective_camera`] or [`orthographic_camera`]. pub fn camera<P: Into<Projection>>(&mut self, projection: P) -> Camera { - Camera::new( - &mut *self.hub.lock().unwrap(), - projection.into(), - ) + Camera::new(&mut *self.hub.lock().unwrap(), projection.into()) } /// Create new [Orthographic] Camera. @@ -457,11 +465,7 @@ impl Factory { /// ``` /// /// [Perspective]: https://en.wikipedia.org/wiki/Perspective_(graphical) - pub fn perspective_camera<R: Into<ZRange>>( - &mut self, - fov_y: f32, - range: R, - ) -> Camera { + pub fn perspective_camera<R: Into<ZRange>>(&mut self, fov_y: f32, range: R) -> Camera { Camera::new( &mut *self.hub.lock().unwrap(), Projection::perspective(fov_y, range), @@ -479,7 +483,9 @@ impl Factory { Either::Left(iter::repeat(NORMAL_Z)) } else { Either::Right( - geometry.base.normals + geometry + .base + .normals .iter() .map(|n| [f2i(n.x), f2i(n.y), f2i(n.z), I8Norm(0)]), ) @@ -495,7 +501,9 @@ impl Factory { Either::Left(iter::repeat(TANGENT_X)) } else { Either::Right( - geometry.base.tangents + geometry + .base + .tangents .iter() .map(|t| [f2i(t.x), f2i(t.y), f2i(t.z), f2i(t.w)]), ) @@ -519,17 +527,17 @@ impl Factory { joint_indices_iter, joint_weights_iter, ) - .map(|(pos, normal, tangent, uv, joint_indices, joint_weights)| { - Vertex { - pos: [pos.x, pos.y, pos.z, 1.0], - normal, - uv, - tangent, - joint_indices, - joint_weights, - } - }) - .collect() + .map( + |(pos, normal, tangent, uv, joint_indices, joint_weights)| Vertex { + pos: [pos.x, pos.y, pos.z, 1.0], + normal, + uv, + tangent, + joint_indices, + joint_weights, + }, + ) + .collect() } /// Uploads geometry data to the GPU so that it can be reused for instanced rendering. @@ -565,28 +573,21 @@ impl Factory { /// ``` /// /// [`template`]: ./template/index.html#mesh-instancing - pub fn upload_geometry( - &mut self, - geometry: Geometry, - ) -> InstancedGeometry { + pub fn upload_geometry(&mut self, geometry: Geometry) -> InstancedGeometry { let gpu_data = self.create_gpu_data(geometry); InstancedGeometry { gpu_data } } /// Create new `Mesh` with desired `Geometry` and `Material`. - pub fn mesh<M: Into<Material>>( - &mut self, - geometry: Geometry, - material: M, - ) -> Mesh { + pub fn mesh<M: Into<Material>>(&mut self, geometry: Geometry, material: M) -> Mesh { let gpu_data = self.create_gpu_data(geometry); Mesh { - object: self.hub.lock().unwrap().spawn_visual( - material.into(), - gpu_data, - None, - ), + object: self + .hub + .lock() + .unwrap() + .spawn_visual(material.into(), gpu_data, None), } } @@ -640,11 +641,11 @@ impl Factory { }); Mesh { - object: self.hub.lock().unwrap().spawn_visual( - material, - gpu_data, - None, - ), + object: self + .hub + .lock() + .unwrap() + .spawn_visual(material, gpu_data, None), } } @@ -666,8 +667,13 @@ impl Factory { }; let (num_vertices, vertices, upload_buf) = { let data = Self::mesh_vertices(&geometry); - let dest_buf = self.backend - .create_buffer_immutable(&data, gfx::buffer::Role::Vertex, gfx::memory::Bind::TRANSFER_DST) + let dest_buf = self + .backend + .create_buffer_immutable( + &data, + gfx::buffer::Role::Vertex, + gfx::memory::Bind::TRANSFER_DST, + ) .unwrap(); let upload_buf = self.backend.create_upload_buffer(data.len()).unwrap(); // TODO: Workaround for not having a 'write-to-slice' capability. @@ -706,23 +712,21 @@ impl Factory { /// Create a `Mesh` sharing the geometry with another one. /// Rendering a sequence of meshes with the same geometry is faster. /// The material is duplicated from the template. - pub fn mesh_instance( - &mut self, - template: &Mesh, - ) -> Mesh { + pub fn mesh_instance(&mut self, template: &Mesh) -> Mesh { let instances = self.create_instance_buffer(); let mut hub = self.hub.lock().unwrap(); let (material, gpu_data) = match hub[template].sub_node { - SubNode::Visual(ref mat, ref gpu, _) => { - (mat.clone(), GpuData { + SubNode::Visual(ref mat, ref gpu, _) => ( + mat.clone(), + GpuData { instances, instance_cache_key: Some(InstanceCacheKey { material: mat.clone(), geometry: gpu.vertices.clone(), }), ..gpu.clone() - }) - } + }, + ), _ => unreachable!(), }; Mesh { @@ -757,10 +761,7 @@ impl Factory { } /// Create new sprite from `Material`. - pub fn sprite( - &mut self, - material: material::Sprite, - ) -> Sprite { + pub fn sprite(&mut self, material: material::Sprite) -> Sprite { let instances = self.create_instance_buffer(); let mut slice = gfx::Slice::new_match_vertex_buffer(&self.quad_buf); slice.instances = Some((1, 0)); @@ -782,34 +783,28 @@ impl Factory { /// Create a `Sprite` sharing the material with another one. /// Rendering a sequence of instanced sprites is much faster. - pub fn sprite_instance( - &mut self, - template: &Sprite, - ) -> Sprite { + pub fn sprite_instance(&mut self, template: &Sprite) -> Sprite { let instances = self.create_instance_buffer(); let mut hub = self.hub.lock().unwrap(); let (material, gpu_data) = match hub[template].sub_node { - SubNode::Visual(ref mat, ref gpu, _) => { - (mat.clone(), GpuData { + SubNode::Visual(ref mat, ref gpu, _) => ( + mat.clone(), + GpuData { instances, instance_cache_key: Some(InstanceCacheKey { material: mat.clone(), geometry: self.quad_buf.clone(), }), ..gpu.clone() - }) - } + }, + ), _ => unreachable!(), }; Sprite::new(hub.spawn_visual(material, gpu_data, None)) } /// Create new `AmbientLight`. - pub fn ambient_light( - &mut self, - color: Color, - intensity: f32, - ) -> Ambient { + pub fn ambient_light(&mut self, color: Color, intensity: f32) -> Ambient { Ambient::new(self.hub.lock().unwrap().spawn_light(LightData { color, intensity, @@ -819,11 +814,7 @@ impl Factory { } /// Create new `DirectionalLight`. - pub fn directional_light( - &mut self, - color: Color, - intensity: f32, - ) -> Directional { + pub fn directional_light(&mut self, color: Color, intensity: f32) -> Directional { Directional::new(self.hub.lock().unwrap().spawn_light(LightData { color, intensity, @@ -850,11 +841,7 @@ impl Factory { } /// Create new `PointLight`. - pub fn point_light( - &mut self, - color: Color, - intensity: f32, - ) -> Point { + pub fn point_light(&mut self, color: Color, intensity: f32) -> Point { Point::new(self.hub.lock().unwrap().spawn_light(LightData { color, intensity, @@ -892,12 +879,9 @@ impl Factory { } /// Create new `ShadowMap`. - pub fn shadow_map( - &mut self, - width: u16, - height: u16, - ) -> ShadowMap { - let (_, resource, target) = self.backend + pub fn shadow_map(&mut self, width: u16, height: u16) -> ShadowMap { + let (_, resource, target) = self + .backend .create_depth_stencil::<ShadowFormat>(width, height) .unwrap(); ShadowMap { resource, target } @@ -917,24 +901,22 @@ impl Factory { ) -> Result<BasicPipelineState, PipelineCreationError> { let vs = Source::user(&dir, name, "vs")?; let ps = Source::user(&dir, name, "ps")?; - let shaders = self.backend + let shaders = self + .backend .create_shader_set(vs.0.as_bytes(), ps.0.as_bytes())?; let init = basic_pipe::Init { out_color: ("Target0", color_mask, blend_state), out_depth: (depth_state, stencil_state), ..basic_pipe::new() }; - let pso = self.backend + let pso = self + .backend .create_pipeline_state(&shaders, primitive, rasterizer, init)?; Ok(pso) } /// Create new UI (on-screen) text. See [`Text`](struct.Text.html) for default settings. - pub fn ui_text<S: Into<String>>( - &mut self, - font: &Font, - text: S, - ) -> Text { + pub fn ui_text<S: Into<String>>(&mut self, font: &Font, text: S) -> Text { let sub = SubNode::UiText(TextData::new(font, text)); let object = self.hub.lock().unwrap().spawn(sub); Text::with_object(object) @@ -949,25 +931,18 @@ impl Factory { } /// Map vertices for updating their data. - pub fn map_vertices<'a>( - &'a mut self, - mesh: &'a mut DynamicMesh, - ) -> MapVertices<'a> { + pub fn map_vertices<'a>(&'a mut self, mesh: &'a mut DynamicMesh) -> MapVertices<'a> { self.hub.lock().unwrap().update_mesh(mesh); self.backend.write_mapping(&mesh.dynamic.buffer).unwrap() } /// Interpolate between the shapes of a `DynamicMesh`. - pub fn mix( - &mut self, - mesh: &DynamicMesh, - shapes: &[(usize, f32)], - ) { + pub fn mix(&mut self, mesh: &DynamicMesh, shapes: &[(usize, f32)]) { self.hub.lock().unwrap().update_mesh(mesh); let mut mapping = self.backend.write_mapping(&mesh.dynamic.buffer).unwrap(); let n = mesh.geometry.base.vertices.len(); - for i in 0 .. n { + for i in 0..n { let (mut pos, ksum) = shapes.iter().fold( (Vector3::new(0.0, 0.0, 0.0), 0.0), |(pos, ksum), &(idx, k)| { @@ -986,10 +961,7 @@ impl Factory { /// Load TrueTypeFont (.ttf) from file. /// #### Panics /// Panics if I/O operations with file fails (e.g. file not found or corrupted) - pub fn load_font<P: AsRef<Path>>( - &mut self, - file_path: P, - ) -> Font { + pub fn load_font<P: AsRef<Path>>(&mut self, file_path: P) -> Font { let file_path = file_path.as_ref(); let mut buffer = Vec::new(); let file = fs::File::open(&file_path).expect(&format!( @@ -1002,18 +974,27 @@ impl Factory { "Can't read font file:\nFile: {}", file_path.display() )); - Font::new(buffer, format!("path: {:?}", file_path), self.backend.clone()) + Font::new( + buffer, + format!("path: {:?}", file_path), + self.backend.clone(), + ) } /// Load the Karla font pub fn load_font_karla(&mut self) -> Font { let buffer: &'static [u8] = include_bytes!("../../data/fonts/Karla-Regular.ttf"); - Font::new(buffer, String::from("Embedded Karla-Regular.ttf"), self.backend.clone()) + Font::new( + buffer, + String::from("Embedded Karla-Regular.ttf"), + self.backend.clone(), + ) } fn parse_texture_format(path: &Path) -> image::ImageFormat { use image::ImageFormat as F; - let extension = path.extension() + let extension = path + .extension() .expect("no extension for an image?") .to_string_lossy() .to_lowercase(); @@ -1040,7 +1021,8 @@ impl Factory { use gfx::texture as t; //TODO: generate mipmaps let format = Factory::parse_texture_format(path); - let file = fs::File::open(path).unwrap_or_else(|e| panic!("Unable to open {}: {:?}", path.display(), e)); + let file = fs::File::open(path) + .unwrap_or_else(|e| panic!("Unable to open {}: {:?}", path.display(), e)); let img = image::load(io::BufReader::new(file), format) .unwrap_or_else(|e| panic!("Unable to decode {}: {:?}", path.display(), e)) .flipv() @@ -1070,14 +1052,18 @@ impl Factory { .iter() .map(|path| { let format = Factory::parse_texture_format(path.as_ref()); - let file = fs::File::open(path).unwrap_or_else(|e| panic!("Unable to open {}: {:?}", path.as_ref().display(), e)); + let file = fs::File::open(path).unwrap_or_else(|e| { + panic!("Unable to open {}: {:?}", path.as_ref().display(), e) + }); image::load(io::BufReader::new(file), format) - .unwrap_or_else(|e| panic!("Unable to decode {}: {:?}", path.as_ref().display(), e)) + .unwrap_or_else(|e| { + panic!("Unable to decode {}: {:?}", path.as_ref().display(), e) + }) .to_rgba() }) .collect::<Vec<_>>(); let data: [&[u8]; 6] = [ - &images[0], &images[1], &images[2], &images[3], &images[4], &images[5] + &images[0], &images[1], &images[2], &images[3], &images[4], &images[5], ]; let size = images[0].dimensions().0; let kind = t::Kind::Cube(size as t::Size); @@ -1089,11 +1075,7 @@ impl Factory { CubeMap::new(view, sampler.0) } - fn request_texture<P: AsRef<Path>>( - &mut self, - path: P, - sampler: Sampler, - ) -> Texture<[f32; 4]> { + fn request_texture<P: AsRef<Path>>(&mut self, path: P, sampler: Sampler) -> Texture<[f32; 4]> { match self.texture_cache.entry(path.as_ref().to_owned()) { Entry::Occupied(e) => e.get().clone(), Entry::Vacant(e) => { @@ -1120,22 +1102,18 @@ impl Factory { kd: Some(color), ns: Some(glossiness), .. - } if has_normals => - { - material::Phong { - color: cf2u(color), - glossiness, - }.into() + } if has_normals => material::Phong { + color: cf2u(color), + glossiness, } + .into(), obj::Material { kd: Some(color), .. - } if has_normals => - { - material::Lambert { - color: cf2u(color), - flat: false, - }.into() + } if has_normals => material::Lambert { + color: cf2u(color), + flat: false, } + .into(), obj::Material { kd: Some(color), ref map_kd, @@ -1146,14 +1124,16 @@ impl Factory { (true, &Some(ref name)) => { let sampler = self.default_sampler(); Some(self.request_texture(&concat_path(obj_dir, name), sampler)) - }, + } _ => None, }, - }.into(), + } + .into(), _ => material::Basic { color: 0xffffff, map: None, - }.into(), + } + .into(), } } @@ -1167,8 +1147,13 @@ impl Factory { ) -> Texture<[f32; 4]> { use gfx::texture as t; let kind = t::Kind::D2(width, height, t::AaMode::Single); - let (_, view) = self.backend - .create_texture_immutable_u8::<gfx::format::Srgba8>(kind, t::Mipmap::Provided, &[pixels]) + let (_, view) = self + .backend + .create_texture_immutable_u8::<gfx::format::Srgba8>( + kind, + t::Mipmap::Provided, + &[pixels], + ) .unwrap_or_else(|e| { panic!("Unable to create GPU texture from memory: {:?}", e); }); @@ -1177,10 +1162,7 @@ impl Factory { /// Load texture from file, with default `Sampler`. /// Supported file formats are: PNG, JPEG, GIF, WEBP, PPM, TIFF, TGA, BMP, ICO, HDR. - pub fn load_texture<P: AsRef<Path>>( - &mut self, - path_str: P, - ) -> Texture<[f32; 4]> { + pub fn load_texture<P: AsRef<Path>>(&mut self, path_str: P) -> Texture<[f32; 4]> { let sampler = self.default_sampler(); self.request_texture(path_str, sampler) } @@ -1197,18 +1179,12 @@ impl Factory { /// Load cubemap from files. /// Supported file formats are: PNG, JPEG, GIF, WEBP, PPM, TIFF, TGA, BMP, ICO, HDR. - pub fn load_cubemap<P: AsRef<Path>>( - &mut self, - paths: &CubeMapPath<P>, - ) -> CubeMap<[f32; 4]> { + pub fn load_cubemap<P: AsRef<Path>>(&mut self, paths: &CubeMapPath<P>) -> CubeMap<[f32; 4]> { Factory::load_cubemap_impl(paths, self.default_sampler(), &mut self.backend) } /// Load mesh from Wavefront Obj format. - pub fn load_obj( - &mut self, - path_str: &str, - ) -> (HashMap<String, object::Group>, Vec<Mesh>) { + pub fn load_obj(&mut self, path_str: &str) -> (HashMap<String, object::Group>, Vec<Mesh>) { use genmesh::{Indexer, LruIndexer, Polygon, Triangulate, Vertices}; info!("Loading {}", path_str); @@ -1230,7 +1206,8 @@ impl Factory { let (mut num_normals, mut num_uvs) = (0, 0); { // separate scope for LruIndexer - let f2i = |x: f32| I8Norm(cmp::min(cmp::max((x * 127.) as isize, -128), 127) as i8); + let f2i = + |x: f32| I8Norm(cmp::min(cmp::max((x * 127.) as isize, -128), 127) as i8); vertices.clear(); let mut lru = LruIndexer::new(10, |_, obj::IndexTuple(ipos, iuv, inor)| { let p: [f32; 3] = obj.position[ipos]; @@ -1251,7 +1228,7 @@ impl Factory { } None => [I8Norm(0), I8Norm(0), I8Norm(0x7f), I8Norm(0)], }, - .. DEFAULT_VERTEX + ..DEFAULT_VERTEX }); }); @@ -1271,18 +1248,26 @@ impl Factory { gr.name, num_normals, num_uvs ); let material = match gr.material { - Some(ref rc_mat) => self.load_obj_material(&*rc_mat, num_normals != 0, num_uvs != 0, path_parent), + Some(ref rc_mat) => self.load_obj_material( + &*rc_mat, + num_normals != 0, + num_uvs != 0, + path_parent, + ), None => material::Basic { color: 0xFFFFFF, map: None, - }.into(), + } + .into(), }; info!("\t{:?}", material); - let (vertices, mut slice) = self.backend + let (vertices, mut slice) = self + .backend .create_vertex_buffer_with_slice(&vertices, &indices[..]); slice.instances = Some((1, 0)); - let instances = self.backend + let instances = self + .backend .create_buffer( 1, gfx::buffer::Role::Vertex, @@ -1317,10 +1302,7 @@ impl Factory { #[cfg(feature = "audio")] /// Load audio from file. Supported formats are Flac, Vorbis and WAV. - pub fn load_audio<P: AsRef<Path>>( - &self, - path: P, - ) -> audio::Clip { + pub fn load_audio<P: AsRef<Path>>(&self, path: P) -> audio::Clip { let mut buffer = Vec::new(); let mut file = fs::File::open(&path).expect(&format!( "Can't open audio file:\nFile: {}", @@ -1334,10 +1316,7 @@ impl Factory { } } -fn concat_path<'a>( - base: Option<&Path>, - name: &'a str, -) -> Cow<'a, Path> { +fn concat_path<'a>(base: Option<&Path>, name: &'a str) -> Cow<'a, Path> { match base { Some(base) => Cow::Owned(base.join(name)), None => Cow::Borrowed(Path::new(name)), diff --git a/src/geometry.rs b/src/geometry.rs index fd59c6d..198cf04 100644 --- a/src/geometry.rs +++ b/src/geometry.rs @@ -1,7 +1,7 @@ //! Structures for creating and storing geometric primitives. -use genmesh::{EmitTriangles, Triangulate, Vertex as GenVertex}; use genmesh::generators::{self, IndexedPolygon, SharedVertex}; +use genmesh::{EmitTriangles, Triangulate, Vertex as GenVertex}; use mint; /// A collection of vertices, their normals, and faces that defines the @@ -104,17 +104,13 @@ impl Geometry { Geometry { base: Shape { vertices, - .. Shape::default() + ..Shape::default() }, - .. Geometry::default() + ..Geometry::default() } } - fn generate<P, G, Fpos, Fnor>( - gen: G, - fpos: Fpos, - fnor: Fnor, - ) -> Self + fn generate<P, G, Fpos, Fnor>(gen: G, fpos: Fpos, fnor: Fnor) -> Self where P: EmitTriangles<Vertex = usize>, G: IndexedPolygon<P> + SharedVertex<GenVertex>, @@ -125,14 +121,15 @@ impl Geometry { base: Shape { vertices: gen.shared_vertex_iter().map(fpos).collect(), normals: gen.shared_vertex_iter().map(fnor).collect(), - .. Shape::default() + ..Shape::default() }, // TODO: Add similar functions for tangents and texture coords - faces: gen.indexed_polygon_iter() + faces: gen + .indexed_polygon_iter() .triangulate() .map(|t| [t.x as u32, t.y as u32, t.z as u32]) .collect(), - .. Geometry::default() + ..Geometry::default() } } @@ -152,10 +149,7 @@ impl Geometry { /// } /// # fn main() { let _ = make_square(); } /// ``` - pub fn plane( - width: f32, - height: f32, - ) -> Self { + pub fn plane(width: f32, height: f32) -> Self { Self::generate( generators::Plane::new(), |GenVertex { pos, .. }| [pos.x * 0.5 * width, pos.y * 0.5 * height, 0.0].into(), @@ -179,11 +173,7 @@ impl Geometry { /// } /// # fn main() { let _ = make_cube(); } /// ``` - pub fn cuboid( - width: f32, - height: f32, - depth: f32, - ) -> Self { + pub fn cuboid(width: f32, height: f32, depth: f32) -> Self { Self::generate( generators::Cube::new(), |GenVertex { pos, .. }| { @@ -191,7 +181,8 @@ impl Geometry { pos.x * 0.5 * width, pos.y * 0.5 * height, pos.z * 0.5 * depth, - ].into() + ] + .into() }, |v| v.normal.into(), ) @@ -251,11 +242,7 @@ impl Geometry { /// } /// # fn main() { let _ = make_sphere(); } /// ``` - pub fn uv_sphere( - radius: f32, - equatorial_segments: usize, - meridional_segments: usize, - ) -> Self { + pub fn uv_sphere(radius: f32, equatorial_segments: usize, meridional_segments: usize) -> Self { Self::generate( generators::SphereUv::new(equatorial_segments, meridional_segments), |GenVertex { pos, .. }| [pos.x * radius, pos.y * radius, pos.z * radius].into(), diff --git a/src/hub.rs b/src/hub.rs index 9a1107c..3d61133 100644 --- a/src/hub.rs +++ b/src/hub.rs @@ -17,10 +17,9 @@ use froggy; use gfx; use mint; -use std::{mem, ops}; -use std::sync::{Arc, Mutex}; use std::sync::mpsc; - +use std::sync::{Arc, Mutex}; +use std::{mem, ops}; #[derive(Clone, Debug)] pub(crate) enum SubLight { @@ -68,7 +67,10 @@ pub(crate) enum SubNode { /// Lighting information for illumination and shadow casting. Light(LightData), /// A single bone. - Bone { index: usize, inverse_bind_matrix: mint::ColumnMatrix4<f32> }, + Bone { + index: usize, + inverse_bind_matrix: mint::ColumnMatrix4<f32>, + }, /// Skeleton root. Skeleton(SkeletonData), } @@ -132,10 +134,7 @@ impl Hub { Arc::new(Mutex::new(hub)) } - pub(crate) fn spawn( - &mut self, - sub: SubNode, - ) -> Base { + pub(crate) fn spawn(&mut self, sub: SubNode) -> Base { Base { node: self.nodes.create(sub.into()), tx: self.message_tx.clone(), @@ -151,17 +150,11 @@ impl Hub { self.spawn(SubNode::Visual(mat, gpu_data, skeleton)) } - pub(crate) fn spawn_light( - &mut self, - data: LightData, - ) -> Base { + pub(crate) fn spawn_light(&mut self, data: LightData) -> Base { self.spawn(SubNode::Light(data)) } - pub(crate) fn spawn_skeleton( - &mut self, - data: SkeletonData, - ) -> Base { + pub(crate) fn spawn_skeleton(&mut self, data: SkeletonData) -> Base { self.spawn(SubNode::Skeleton(data)) } @@ -185,14 +178,13 @@ impl Hub { if let SubNode::Audio(ref mut data) = self.nodes[&ptr].sub_node { Hub::process_audio(operation, data); } - }, + } Operation::SetVisible(visible) => { self.nodes[&ptr].visible = visible; } Operation::SetTransform(pos, rot, scale) => { let transform = &mut self.nodes[&ptr].transform; if let Some(pos) = pos { - transform.disp = mint::Vector3::from(pos).into(); } if let Some(rot) = rot { @@ -204,14 +196,17 @@ impl Hub { } Operation::AddChild(child_ptr) => { let sibling = match self.nodes[&ptr].sub_node { - SubNode::Group { ref mut first_child } => - mem::replace(first_child, Some(child_ptr.clone())), + SubNode::Group { + ref mut first_child, + } => mem::replace(first_child, Some(child_ptr.clone())), _ => unreachable!(), }; let child = &mut self.nodes[&child_ptr]; if child.next_sibling.is_some() { - error!("Element {:?} is added to a group while still having old parent - {}", - child.sub_node, "discarding siblings"); + error!( + "Element {:?} is added to a group while still having old parent - {}", + child.sub_node, "discarding siblings" + ); } child.next_sibling = sibling; } @@ -219,14 +214,16 @@ impl Hub { let next_sibling = self.nodes[&child_ptr].next_sibling.clone(); let target_maybe = Some(child_ptr); let mut cur_ptr = match self.nodes[&ptr].sub_node { - SubNode::Group { ref mut first_child } => { + SubNode::Group { + ref mut first_child, + } => { if *first_child == target_maybe { *first_child = next_sibling; continue; } first_child.clone() } - _ => unreachable!() + _ => unreachable!(), }; //TODO: consolidate the code with `Scene::remove()` @@ -245,61 +242,47 @@ impl Hub { cur_ptr = node.next_sibling.clone(); //TODO: avoid clone } } - Operation::SetLight(operation) => { - match self.nodes[&ptr].sub_node { - SubNode::Light(ref mut data) => { - Hub::process_light(operation, data); - } - _ => unreachable!() + Operation::SetLight(operation) => match self.nodes[&ptr].sub_node { + SubNode::Light(ref mut data) => { + Hub::process_light(operation, data); } - } - Operation::SetText(operation) => { - match self.nodes[&ptr].sub_node { - SubNode::UiText(ref mut data) => { - Hub::process_text(operation, data); - } - _ => unreachable!() + _ => unreachable!(), + }, + Operation::SetText(operation) => match self.nodes[&ptr].sub_node { + SubNode::UiText(ref mut data) => { + Hub::process_text(operation, data); } - } - Operation::SetMaterial(material) => { - match self.nodes[&ptr].sub_node { - SubNode::Visual(ref mut mat, _, _) => { - *mat = material; - } - _ => unreachable!() + _ => unreachable!(), + }, + Operation::SetMaterial(material) => match self.nodes[&ptr].sub_node { + SubNode::Visual(ref mut mat, _, _) => { + *mat = material; } - } - Operation::SetSkeleton(sleketon) => { - match self.nodes[&ptr].sub_node { - SubNode::Visual(_, _, ref mut skel) => { - *skel = Some(sleketon); - } - _ => unreachable!() + _ => unreachable!(), + }, + Operation::SetSkeleton(sleketon) => match self.nodes[&ptr].sub_node { + SubNode::Visual(_, _, ref mut skel) => { + *skel = Some(sleketon); } - } - Operation::SetShadow(map, proj) => { - match self.nodes[&ptr].sub_node { - SubNode::Light(ref mut data) => { - data.shadow = Some((map, proj)); - }, - _ => unreachable!() + _ => unreachable!(), + }, + Operation::SetShadow(map, proj) => match self.nodes[&ptr].sub_node { + SubNode::Light(ref mut data) => { + data.shadow = Some((map, proj)); } - } - Operation::SetTexelRange(base, size) => { - match self.nodes[&ptr].sub_node { - SubNode::Visual(Material::Sprite(ref mut params), _, _) => { - params.map.set_texel_range(base, size); - } - _ => unreachable!() + _ => unreachable!(), + }, + Operation::SetTexelRange(base, size) => match self.nodes[&ptr].sub_node { + SubNode::Visual(Material::Sprite(ref mut params), _, _) => { + params.map.set_texel_range(base, size); } - } + _ => unreachable!(), + }, Operation::SetWeights(weights) => { - fn set_weights( - gpu_data: &mut GpuData, - weights: &[f32], - ) { + fn set_weights(gpu_data: &mut GpuData, weights: &[f32]) { use std::iter::repeat; - for (out, input) in gpu_data.displacement_contributions + for (out, input) in gpu_data + .displacement_contributions .iter_mut() .zip(weights.iter().chain(repeat(&0.0))) { @@ -326,14 +309,12 @@ impl Hub { Operation::SetName(name) => { self.nodes[&ptr].name = Some(name); } - Operation::SetProjection(projection) => { - match self.nodes[&ptr].sub_node { - SubNode::Camera(ref mut internal_projection) => { - *internal_projection = projection; - } - _ => unreachable!() + Operation::SetProjection(projection) => match self.nodes[&ptr].sub_node { + SubNode::Camera(ref mut internal_projection) => { + *internal_projection = projection; } - } + _ => unreachable!(), + }, } } @@ -341,10 +322,7 @@ impl Hub { } #[cfg(feature = "audio")] - fn process_audio( - operation: AudioOperation, - data: &mut AudioData, - ) { + fn process_audio(operation: AudioOperation, data: &mut AudioData) { match operation { AudioOperation::Append(clip) => data.source.append(clip), AudioOperation::Pause => data.source.pause(), @@ -354,20 +332,14 @@ impl Hub { } } - fn process_light( - operation: LightOperation, - data: &mut LightData, - ) { + fn process_light(operation: LightOperation, data: &mut LightData) { match operation { LightOperation::Color(color) => data.color = color, LightOperation::Intensity(intensity) => data.intensity = intensity, } } - fn process_text( - operation: TextOperation, - data: &mut TextData, - ) { + fn process_text(operation: TextOperation, data: &mut TextData) { use gfx_glyph::Scale; match operation { TextOperation::Color(color) => { @@ -385,19 +357,16 @@ impl Hub { } } - pub(crate) fn update_mesh( - &mut self, - mesh: &DynamicMesh, - ) { + pub(crate) fn update_mesh(&mut self, mesh: &DynamicMesh) { match self[mesh].sub_node { - SubNode::Visual(_, ref mut gpu_data, _) => gpu_data.pending = Some(mesh.dynamic.clone()), + SubNode::Visual(_, ref mut gpu_data, _) => { + gpu_data.pending = Some(mesh.dynamic.clone()) + } _ => unreachable!(), } } - fn walk_impl( - &self, base: &Option<NodePointer>, only_visible: bool - ) -> TreeWalker { + fn walk_impl(&self, base: &Option<NodePointer>, only_visible: bool) -> TreeWalker { let default_stack_size = 10; let mut walker = TreeWalker { hub: self, @@ -462,10 +431,12 @@ impl<'a> TreeWalker<'a> { } match node.sub_node { - SubNode::Group { first_child: Some(ref child_ptr) } => { + SubNode::Group { + first_child: Some(ref child_ptr), + } => { ptr = child_ptr; node = &self.hub.nodes[&ptr]; - }, + } _ => break, } } @@ -481,7 +452,7 @@ impl<'a> Iterator for TreeWalker<'a> { while let Some(top) = self.stack.pop() { self.descend(&top.node.next_sibling); if !self.only_visible || top.world_visible { - return Some(top) + return Some(top); } } None diff --git a/src/input/mod.rs b/src/input/mod.rs index 86497df..0085712 100644 --- a/src/input/mod.rs +++ b/src/input/mod.rs @@ -5,8 +5,8 @@ use mint; use std::collections::HashSet; use std::time; -mod timer; pub mod axis; +mod timer; pub use self::axis::{AXIS_DOWN_UP, AXIS_LEFT_RIGHT}; @@ -74,7 +74,8 @@ impl Input { let now = time::Instant::now(); let dt = now - self.state.time_moment; self.state.time_moment = now; - self.delta.time_delta = dt.as_secs() as TimerDuration + 1e-9 * dt.subsec_nanos() as TimerDuration; + self.delta.time_delta = + dt.as_secs() as TimerDuration + 1e-9 * dt.subsec_nanos() as TimerDuration; self.delta.keys_hit.clear(); self.delta.mouse_moves.clear(); self.delta.mouse_moves_ndc.clear(); @@ -174,18 +175,11 @@ impl Input { self.state.is_focused } - pub(crate) fn window_focus( - &mut self, - state: bool, - ) { + pub(crate) fn window_focus(&mut self, state: bool) { self.state.is_focused = state; } - pub(crate) fn keyboard_input( - &mut self, - state: ElementState, - key: Key, - ) { + pub(crate) fn keyboard_input(&mut self, state: ElementState, key: Key) { match state { ElementState::Pressed => { if !self.state.keys_pressed.contains(&key) { @@ -199,11 +193,7 @@ impl Input { } } - pub(crate) fn mouse_input( - &mut self, - state: ElementState, - button: MouseButton, - ) { + pub(crate) fn mouse_input(&mut self, state: ElementState, button: MouseButton) { match state { ElementState::Pressed => { self.state.mouse_pressed.insert(button); @@ -215,11 +205,7 @@ impl Input { } } - pub(crate) fn mouse_moved( - &mut self, - pos: mint::Point2<f32>, - pos_ndc: mint::Point2<f32>, - ) { + pub(crate) fn mouse_moved(&mut self, pos: mint::Point2<f32>, pos_ndc: mint::Point2<f32>) { use cgmath::Point2; self.delta .mouse_moves @@ -231,18 +217,11 @@ impl Input { self.state.mouse_pos_ndc = pos_ndc; } - pub(crate) fn axis_moved_raw( - &mut self, - axis: u8, - value: f32, - ) { + pub(crate) fn axis_moved_raw(&mut self, axis: u8, value: f32) { self.delta.axes_raw.push((axis, value)); } - pub(crate) fn mouse_wheel_input( - &mut self, - delta: MouseScrollDelta, - ) { + pub(crate) fn mouse_wheel_input(&mut self, delta: MouseScrollDelta) { self.delta.mouse_wheel.push(match delta { MouseScrollDelta::LineDelta(_, y) => y * PIXELS_PER_LINE, MouseScrollDelta::PixelDelta(delta) => delta.y as f32, @@ -251,10 +230,7 @@ impl Input { /// Returns `true` there is any input info from [`Button`](struct.Button.html), /// [`axis::Key`](struct.Key.html) or [`axis::Raw`](struct.Raw.html). Otherwise returns `false`. - pub fn hit<H: Hit>( - &self, - hit: H, - ) -> bool { + pub fn hit<H: Hit>(&self, hit: H) -> bool { hit.hit(self) } @@ -278,10 +254,7 @@ impl Input { /// [`Window::update`]: window/struct.Window.html#method.update /// [`axis::Key`]: input/axis/struct.Key.html /// [`axis::Raw`]: input/axis/struct.Raw.html - pub fn delta<D: Delta>( - &self, - delta: D, - ) -> <D as Delta>::Output { + pub fn delta<D: Delta>(&self, delta: D) -> <D as Delta>::Output { delta.delta(self) } @@ -289,10 +262,7 @@ impl Input { /// /// [`delta`]: struct.Input.html#method.delta /// [`delta_time`]: struct.Input.html#method.delta_time - pub fn timed<D: Delta>( - &self, - delta: D, - ) -> Option<TimerDuration> { + pub fn timed<D: Delta>(&self, delta: D) -> Option<TimerDuration> { delta.timed(self) } @@ -302,10 +272,7 @@ impl Input { /// /// - Hits for [`axis::Key`](struct.Key.html) as `(u8, u8)` where first number is for `positive` /// direction and the second one is for `negative`. - pub fn hit_count<C: HitCount>( - &self, - hit_count: C, - ) -> <C as HitCount>::Output { + pub fn hit_count<C: HitCount>(&self, hit_count: C) -> <C as HitCount>::Output { hit_count.hit_count(self) } } @@ -322,17 +289,11 @@ pub enum Button { /// Trait for [`Buttons`](enum.Button.html). pub trait Hit { /// See [`Input::hit`](struct.Input.html#method.hit). - fn hit( - &self, - input: &Input, - ) -> bool; + fn hit(&self, input: &Input) -> bool; } impl Hit for Button { - fn hit( - &self, - input: &Input, - ) -> bool { + fn hit(&self, input: &Input) -> bool { match *self { Button::Key(button) => button.hit(input), Button::Mouse(button) => button.hit(input), @@ -341,28 +302,19 @@ impl Hit for Button { } impl Hit for Key { - fn hit( - &self, - input: &Input, - ) -> bool { + fn hit(&self, input: &Input) -> bool { input.state.keys_pressed.contains(self) } } impl Hit for MouseButton { - fn hit( - &self, - input: &Input, - ) -> bool { + fn hit(&self, input: &Input) -> bool { input.state.mouse_pressed.contains(self) } } impl Hit for axis::Key { - fn hit( - &self, - input: &Input, - ) -> bool { + fn hit(&self, input: &Input) -> bool { let pos_hit = input.state.keys_pressed.contains(&self.pos); let neg_hit = input.state.keys_pressed.contains(&self.neg); pos_hit || neg_hit @@ -370,16 +322,14 @@ impl Hit for axis::Key { } impl Hit for axis::Raw { - fn hit( - &self, - input: &Input, - ) -> bool { + fn hit(&self, input: &Input) -> bool { input .delta .axes_raw .iter() .filter(|&&(id, _)| id == self.id) - .count() > 0 + .count() + > 0 } } @@ -388,18 +338,12 @@ pub trait HitCount { /// Output type. type Output; /// See [`Input::hit_count`](struct.Input.html#method.hit_count). - fn hit_count( - &self, - input: &Input, - ) -> Self::Output; + fn hit_count(&self, input: &Input) -> Self::Output; } impl HitCount for Button { type Output = u8; - fn hit_count( - &self, - input: &Input, - ) -> Self::Output { + fn hit_count(&self, input: &Input) -> Self::Output { use std::u8::MAX; match *self { Button::Key(button) => input @@ -423,10 +367,7 @@ impl HitCount for Button { impl HitCount for axis::Key { type Output = (u8, u8); - fn hit_count( - &self, - input: &Input, - ) -> Self::Output { + fn hit_count(&self, input: &Input) -> Self::Output { use std::u8::MAX; let pos = input .delta @@ -452,25 +393,19 @@ pub trait Delta { type Output; /// See [`Input::delta`](struct.Input.html#method.delta). - fn delta( - &self, - input: &Input, - ) -> Self::Output; + fn delta(&self, input: &Input) -> Self::Output; /// See [`Input::timed`](struct.Input.html#method.timed). - fn timed( - &self, - input: &Input, - ) -> Option<TimerDuration>; + fn timed(&self, input: &Input) -> Option<TimerDuration>; } impl Delta for axis::Key { type Output = Option<i8>; - fn delta( - &self, - input: &Input, - ) -> Self::Output { - match (input.delta.keys_hit.contains(&self.pos), input.delta.keys_hit.contains(&self.neg)) { + fn delta(&self, input: &Input) -> Self::Output { + match ( + input.delta.keys_hit.contains(&self.pos), + input.delta.keys_hit.contains(&self.neg), + ) { (true, true) => Some(0), (true, false) => Some(1), (false, true) => Some(-1), @@ -478,26 +413,21 @@ impl Delta for axis::Key { } } - fn timed( - &self, - input: &Input, - ) -> Option<TimerDuration> { + fn timed(&self, input: &Input) -> Option<TimerDuration> { match (self.pos.hit(input), self.neg.hit(input)) { (true, true) => Some(0), (true, false) => Some(1), (false, true) => Some(-1), (false, false) => None, - }.map(|delta| delta as TimerDuration * input.delta_time()) + } + .map(|delta| delta as TimerDuration * input.delta_time()) } } impl Delta for axis::Raw { type Output = Option<f32>; - fn delta( - &self, - input: &Input, - ) -> Self::Output { + fn delta(&self, input: &Input) -> Self::Output { let moves = input .delta .axes_raw @@ -512,10 +442,7 @@ impl Delta for axis::Raw { } } - fn timed( - &self, - input: &Input, - ) -> Option<TimerDuration> { + fn timed(&self, input: &Input) -> Option<TimerDuration> { self.delta(input) .map(|v| v as TimerDuration * input.delta_time()) } diff --git a/src/input/timer.rs b/src/input/timer.rs index e8588a4..8c8e3ca 100644 --- a/src/input/timer.rs +++ b/src/input/timer.rs @@ -22,9 +22,7 @@ impl Timer { } /// Get period of time since timer creation in seconds. - pub fn elapsed( - &self, - ) -> TimerDuration { + pub fn elapsed(&self) -> TimerDuration { let dt = self.start.elapsed(); dt.as_secs() as f32 + 1e-9 * dt.subsec_nanos() as f32 } diff --git a/src/lib.rs b/src/lib.rs index f46a9a8..bb0436b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -317,7 +317,7 @@ pub use color::Color; pub use controls::{AXIS_DOWN_UP, AXIS_LEFT_RIGHT, KEY_ESCAPE, KEY_SPACE, MOUSE_LEFT, MOUSE_RIGHT}; #[doc(inline)] -pub use controls::{Button, MouseButton, Input, Timer}; +pub use controls::{Button, Input, MouseButton, Timer}; #[doc(inline)] pub use factory::Factory; @@ -339,7 +339,7 @@ pub use material::Material; pub use mesh::{DynamicMesh, Mesh}; #[doc(inline)] -pub use node::{Node, Transform, Local, World}; +pub use node::{Local, Node, Transform, World}; #[doc(inline)] pub use object::{Group, Object}; diff --git a/src/light.rs b/src/light.rs index 3a442d4..a3d3203 100644 --- a/src/light.rs +++ b/src/light.rs @@ -19,19 +19,13 @@ pub(crate) enum LightOperation { /// Marks light sources and implements their common methods. pub trait Light: Object { /// Change light color. - fn set_color( - &self, - color: Color, - ) { + fn set_color(&self, color: Color) { let msg = Operation::SetLight(LightOperation::Color(color)); let _ = self.as_ref().tx.send((self.as_ref().node.downgrade(), msg)); } /// Change light intensity. - fn set_intensity( - &self, - intensity: f32, - ) { + fn set_intensity(&self, intensity: f32) { let msg = Operation::SetLight(LightOperation::Intensity(intensity)); let _ = self.as_ref().tx.send((self.as_ref().node.downgrade(), msg)); } @@ -56,7 +50,9 @@ pub(crate) enum ShadowProjection { } impl ShadowMap { - pub(crate) fn to_target(&self) -> gfx::handle::DepthStencilView<BackendResources, ShadowFormat> { + pub(crate) fn to_target( + &self, + ) -> gfx::handle::DepthStencilView<BackendResources, ShadowFormat> { self.target.clone() } @@ -79,7 +75,9 @@ impl Ambient { } impl AsRef<Base> for Ambient { - fn as_ref(&self) -> &Base { &self.object } + fn as_ref(&self) -> &Base { + &self.object + } } impl Object for Ambient { @@ -105,18 +103,11 @@ pub struct Directional { impl Directional { pub(crate) fn new(object: Base) -> Self { - Directional { - object, - } + Directional { object } } /// Adds or updates the shadow map for this light source. - pub fn set_shadow( - &mut self, - map: ShadowMap, - extent_y: f32, - range: ops::Range<f32>, - ) { + pub fn set_shadow(&mut self, map: ShadowMap, extent_y: f32, range: ops::Range<f32>) { let sp = ShadowProjection::Orthographic(Orthographic { center: [0.0; 2].into(), extent_y, @@ -128,7 +119,9 @@ impl Directional { } impl AsRef<Base> for Directional { - fn as_ref(&self) -> &Base { &self.object } + fn as_ref(&self) -> &Base { + &self.object + } } impl Object for Directional { @@ -165,7 +158,9 @@ impl Hemisphere { } impl AsRef<Base> for Hemisphere { - fn as_ref(&self) -> &Base { &self.object } + fn as_ref(&self) -> &Base { + &self.object + } } impl Object for Hemisphere { @@ -194,7 +189,9 @@ impl Point { } impl AsRef<Base> for Point { - fn as_ref(&self) -> &Base { &self.object } + fn as_ref(&self) -> &Base { + &self.object + } } impl Object for Point { diff --git a/src/macros.rs b/src/macros.rs index bd4a947..d4dd627 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -46,13 +46,13 @@ macro_rules! three_object { impl $crate::Object for $name { type Data = (); - fn resolve_data(&self, _: & $crate::scene::SyncGuard) -> Self::Data {} + fn resolve_data(&self, _: &$crate::scene::SyncGuard) -> Self::Data {} } }; ($name:ident) => { - three_object!($name ::object); - } + three_object!($name::object); + }; } macro_rules! derive_DowncastObject { @@ -60,10 +60,10 @@ macro_rules! derive_DowncastObject { impl ::object::DowncastObject for $type { fn downcast(object: ::object::ObjectType) -> Option<Self> { match object { - $pattern (inner) => Some(inner), + $pattern(inner) => Some(inner), _ => None, } } } - } + }; } diff --git a/src/mesh.rs b/src/mesh.rs index 6eea58d..9e60441 100644 --- a/src/mesh.rs +++ b/src/mesh.rs @@ -95,10 +95,7 @@ pub struct DynamicMesh { three_object!(DynamicMesh::object); impl PartialEq for DynamicMesh { - fn eq( - &self, - other: &DynamicMesh, - ) -> bool { + fn eq(&self, other: &DynamicMesh) -> bool { self.object == other.object } } @@ -106,28 +103,19 @@ impl PartialEq for DynamicMesh { impl Eq for DynamicMesh {} impl Hash for DynamicMesh { - fn hash<H: Hasher>( - &self, - state: &mut H, - ) { + fn hash<H: Hasher>(&self, state: &mut H) { self.object.hash(state); } } impl Mesh { /// Set mesh material. - pub fn set_material<M: Into<Material>>( - &self, - material: M, - ) { + pub fn set_material<M: Into<Material>>(&self, material: M) { self.as_ref().send(Operation::SetMaterial(material.into())); } /// Bind a skeleton to the mesh. - pub fn set_skeleton( - &self, - skeleton: Skeleton, - ) { + pub fn set_skeleton(&self, skeleton: Skeleton) { self.as_ref().send(Operation::SetSkeleton(skeleton)); } } @@ -139,10 +127,7 @@ impl DynamicMesh { } /// Set mesh material. - pub fn set_material<M: Into<Material>>( - &mut self, - material: M, - ) { + pub fn set_material<M: Into<Material>>(&mut self, material: M) { self.as_ref().send(Operation::SetMaterial(material.into())); } } diff --git a/src/node.rs b/src/node.rs index cddca53..90b2e72 100644 --- a/src/node.rs +++ b/src/node.rs @@ -9,7 +9,8 @@ use std::marker::PhantomData; /// Pointer to a Node pub(crate) type NodePointer = froggy::Pointer<NodeInternal>; -pub(crate) type TransformInternal = cgmath::Decomposed<cgmath::Vector3<f32>, cgmath::Quaternion<f32>>; +pub(crate) type TransformInternal = + cgmath::Decomposed<cgmath::Vector3<f32>, cgmath::Quaternion<f32>>; // Fat node of the scene graph. // diff --git a/src/object.rs b/src/object.rs index 0b56315..b840d9a 100644 --- a/src/object.rs +++ b/src/object.rs @@ -69,81 +69,64 @@ pub trait Object: AsRef<Base> { } /// Invisible objects are not rendered by cameras. - fn set_visible( - &self, - visible: bool, - ) { + fn set_visible(&self, visible: bool) { self.as_ref().send(Operation::SetVisible(visible)); } /// Sets the name of the object. - fn set_name<S: Into<String>>( - &self, - name: S, - ) { + fn set_name<S: Into<String>>(&self, name: S) { self.as_ref().send(Operation::SetName(name.into())); } /// Set both position, orientation and scale. - fn set_transform<P, Q>( - &self, - pos: P, - rot: Q, - scale: f32, - ) where + fn set_transform<P, Q>(&self, pos: P, rot: Q, scale: f32) + where Self: Sized, P: Into<mint::Point3<f32>>, Q: Into<mint::Quaternion<f32>>, { - self.as_ref().send(Operation::SetTransform(Some(pos.into()), Some(rot.into()), Some(scale))); + self.as_ref().send(Operation::SetTransform( + Some(pos.into()), + Some(rot.into()), + Some(scale), + )); } /// Set position. - fn set_position<P>( - &self, - pos: P, - ) where + fn set_position<P>(&self, pos: P) + where Self: Sized, P: Into<mint::Point3<f32>>, { - self.as_ref().send(Operation::SetTransform(Some(pos.into()), None, None)); + self.as_ref() + .send(Operation::SetTransform(Some(pos.into()), None, None)); } /// Set orientation. - fn set_orientation<Q>( - &self, - rot: Q, - ) where + fn set_orientation<Q>(&self, rot: Q) + where Self: Sized, Q: Into<mint::Quaternion<f32>>, { - self.as_ref().send(Operation::SetTransform(None, Some(rot.into()), None)); + self.as_ref() + .send(Operation::SetTransform(None, Some(rot.into()), None)); } /// Set scale. - fn set_scale( - &self, - scale: f32, - ) { - self.as_ref().send(Operation::SetTransform(None, None, Some(scale))); + fn set_scale(&self, scale: f32) { + self.as_ref() + .send(Operation::SetTransform(None, None, Some(scale))); } /// Set weights. //Note: needed for animations - fn set_weights( - &self, - weights: Vec<f32>, - ) { + fn set_weights(&self, weights: Vec<f32>) { self.as_ref().send(Operation::SetWeights(weights)); } /// Rotates object in the specific direction of `target`. - fn look_at<E, T>( - &self, - eye: E, - target: T, - up: Option<mint::Vector3<f32>>, - ) where + fn look_at<E, T>(&self, eye: E, target: T, up: Option<mint::Vector3<f32>>) + where Self: Sized, E: Into<mint::Point3<f32>>, T: Into<mint::Point3<f32>>, @@ -159,15 +142,13 @@ pub trait Object: AsRef<Base> { }; let q = Quaternion::look_at(dir, up).invert(); - self.as_ref().send(Operation::SetTransform(Some(p[0]), Some(q.into()), None)); + self.as_ref() + .send(Operation::SetTransform(Some(p[0]), Some(q.into()), None)); } } impl PartialEq for Base { - fn eq( - &self, - other: &Base, - ) -> bool { + fn eq(&self, other: &Base) -> bool { self.node == other.node } } @@ -175,28 +156,19 @@ impl PartialEq for Base { impl Eq for Base {} impl Hash for Base { - fn hash<H: Hasher>( - &self, - state: &mut H, - ) { + fn hash<H: Hasher>(&self, state: &mut H) { self.node.hash(state); } } impl fmt::Debug for Base { - fn fmt( - &self, - f: &mut fmt::Formatter, - ) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.node.fmt(f) } } impl Base { - pub(crate) fn send( - &self, - operation: Operation, - ) { + pub(crate) fn send(&self, operation: Operation) { let _ = self.tx.send((self.node.downgrade(), operation)); } } @@ -335,7 +307,9 @@ pub struct Group { } impl AsRef<Base> for Group { - fn as_ref(&self) -> &Base { &self.object } + fn as_ref(&self) -> &Base { + &self.object + } } impl Object for Group { @@ -372,19 +346,13 @@ impl Group { } /// Add new [`Object`](trait.Object.html) to the group. - pub fn add<T: Object>( - &self, - child: &T, - ) { + pub fn add<T: Object>(&self, child: &T) { let node = child.as_ref().node.clone(); self.as_ref().send(Operation::AddChild(node)); } /// Removes a child [`Object`](trait.Object.html) from the group. - pub fn remove<T: Object>( - &self, - child: &T, - ) { + pub fn remove<T: Object>(&self, child: &T) { let node = child.as_ref().node.clone(); self.as_ref().send(Operation::RemoveChild(node)); } diff --git a/src/render/mod.rs b/src/render/mod.rs index 1512903..056de53 100644 --- a/src/render/mod.rs +++ b/src/render/mod.rs @@ -15,13 +15,13 @@ use gfx_window_glutin; use glutin; use mint; -pub mod source; mod pso_data; +pub mod source; use color; -use std::{io, str}; use std::collections::HashMap; +use std::{io, str}; pub use self::back::CommandBuffer as BackendCommandBuffer; pub use self::back::Factory as BackendFactory; @@ -31,13 +31,13 @@ pub use self::source::Source; use self::pso_data::{PbrFlags, PsoData}; use camera::Camera; use factory::Factory; +use glutin::{ContextCurrentState, ContextWrapper, NotCurrent, PossiblyCurrent, Window}; use hub::{SubLight, SubNode}; use light::{ShadowMap, ShadowProjection}; use material::Material; use scene::{Background, Scene}; use text::Font; use texture::Texture; -use glutin::{ContextCurrentState, NotCurrent, Window, ContextWrapper, PossiblyCurrent}; /// The format of the back buffer color requested from the windowing system. pub type ColorFormat = gfx::format::Rgba8; @@ -250,12 +250,7 @@ pub(crate) struct InstanceCacheKey { impl Instance { #[inline] - fn basic( - mx_world: mint::RowMatrix4<f32>, - color: u32, - uv_range: [f32; 4], - param: f32, - ) -> Self { + fn basic(mx_world: mint::RowMatrix4<f32>, color: u32, uv_range: [f32; 4], param: f32) -> Self { Instance { world0: mx_world.x.into(), world1: mx_world.y.into(), @@ -285,7 +280,12 @@ impl Instance { impl DisplacementContribution { /// Zero displacement contribution. - pub const ZERO: Self = DisplacementContribution { position: 0.0, normal: 0.0, tangent: 0.0, weight: 0.0 }; + pub const ZERO: Self = DisplacementContribution { + position: 0.0, + normal: 0.0, + tangent: 0.0, + weight: 0.0, + }; } //TODO: private fields? @@ -295,8 +295,7 @@ pub(crate) struct GpuData { pub vertices: h::Buffer<back::Resources, Vertex>, pub instances: h::Buffer<back::Resources, Instance>, pub displacements: Option<( - h::Texture<back::Resources, - gfx::format::R32_G32_B32_A32>, + h::Texture<back::Resources, gfx::format::R32_G32_B32_A32>, h::ShaderResourceView<back::Resources, [f32; 4]>, )>, pub pending: Option<DynamicData>, @@ -369,17 +368,11 @@ pub struct PipelineStates<R: gfx::Resources> { impl PipelineStates<back::Resources> { /// Creates the set of pipeline states needed by the `three` renderer. - pub fn new( - src: &source::Set, - factory: &mut Factory, - ) -> Result<Self, PipelineCreationError> { + pub fn new(src: &source::Set, factory: &mut Factory) -> Result<Self, PipelineCreationError> { Self::init(src, &mut factory.backend) } - pub(crate) fn pso_by_material<'a>( - &'a self, - material: &'a Material, - ) -> &'a BasicPipelineState { + pub(crate) fn pso_by_material<'a>(&'a self, material: &'a Material) -> &'a BasicPipelineState { match *material { Material::Basic(_) => &self.mesh_basic_fill, Material::CustomBasic(ref b) => &b.pipeline, @@ -457,7 +450,11 @@ impl<R: gfx::Resources> PipelineStates<R> { gfx::Primitive::TriangleStrip, rast_fill, basic_pipe::Init { - out_color: ("Target0", gfx::state::ColorMask::all(), gfx::preset::blend::ALPHA), + out_color: ( + "Target0", + gfx::state::ColorMask::all(), + gfx::preset::blend::ALPHA, + ), ..basic_pipe::new() }, )?; @@ -545,20 +542,23 @@ impl Renderer { ) -> (Self, glutin::WindowedContext<PossiblyCurrent>, Factory) { use gfx::texture as t; - let (windowedContext, device, mut gl_factory, out_color, out_depth) = gfx_window_glutin::init(builder, context, event_loop).unwrap(); + let (windowedContext, device, mut gl_factory, out_color, out_depth) = + gfx_window_glutin::init(builder, context, event_loop).unwrap(); let window = windowedContext.window(); let (_, srv_white) = gl_factory .create_texture_immutable::<gfx::format::Rgba8>( t::Kind::D2(1, 1, t::AaMode::Single), t::Mipmap::Provided, - &[&[[0xFF; 4]]] - ).unwrap(); + &[&[[0xFF; 4]]], + ) + .unwrap(); let (_, srv_shadow) = gl_factory .create_texture_immutable::<(gfx::format::R32, gfx::format::Float)>( t::Kind::D2(1, 1, t::AaMode::Single), t::Mipmap::Provided, &[&[0x3F800000]], - ).unwrap(); + ) + .unwrap(); let sampler = gl_factory.create_sampler_linear(); let sampler_shadow = gl_factory.create_sampler(t::SamplerInfo { comparison: Some(gfx::state::Comparison::Less), @@ -644,10 +644,7 @@ impl Renderer { } /// Reloads the shaders. - pub fn reload( - &mut self, - pipeline_states: PipelineStates<back::Resources>, - ) { + pub fn reload(&mut self, pipeline_states: PipelineStates<back::Resources>) { self.pso = pipeline_states; } @@ -683,10 +680,7 @@ impl Renderer { /// Map screen pixel coordinates to Normalized Display Coordinates. /// The lower left corner corresponds to (-1,-1), and the upper right corner /// corresponds to (1,1). - pub fn map_to_ndc<P: Into<mint::Point2<f32>>>( - &self, - point: P, - ) -> mint::Point2<f32> { + pub fn map_to_ndc<P: Into<mint::Point2<f32>>>(&self, point: P) -> mint::Point2<f32> { let point = point.into(); mint::Point2 { x: 2.0 * point.x / self.size.to_physical(self.dpi).width as f32 - 1.0, @@ -695,11 +689,7 @@ impl Renderer { } /// See [`Window::render`](struct.Window.html#method.render). - pub fn render( - &mut self, - scene: &Scene, - camera: &Camera, - ) { + pub fn render(&mut self, scene: &Scene, camera: &Camera) { { use gfx::Device; self.device.cleanup(); @@ -727,11 +717,16 @@ impl Renderer { gpu_buffer: skeleton.gpu_buffer.clone(), }); } - SubNode::Bone { index, inverse_bind_matrix } => { + SubNode::Bone { + index, + inverse_bind_matrix, + } => { let skel = skeletons.last_mut().unwrap(); - let mx_base = Matrix4::from(skel.inverse_world_transform.concat(&w.world_transform)); + let mx_base = + Matrix4::from(skel.inverse_world_transform.concat(&w.world_transform)); let mx = (mx_base * Matrix4::from(inverse_bind_matrix)).transpose(); - let buf = &mut skel.cpu_buffer[index * VECS_PER_BONE .. (index + 1) * VECS_PER_BONE]; + let buf = &mut skel.cpu_buffer + [index * VECS_PER_BONE..(index + 1) * VECS_PER_BONE]; buf[0] = mx.x.into(); buf[1] = mx.y.into(); buf[2] = mx.z.into(); @@ -742,11 +737,7 @@ impl Renderer { for skel in skeletons { self.encoder - .update_buffer( - &skel.gpu_buffer, - &skel.cpu_buffer, - 0, - ) + .update_buffer(&skel.gpu_buffer, &skel.cpu_buffer, 0) .expect("upload to GPU target buffer"); } } @@ -908,7 +899,7 @@ impl Renderer { let mx_view = Matrix4::from(mx_camera_transform.inverse_transform().unwrap()); let projection = match hub[&camera].sub_node { SubNode::Camera(ref projection) => projection.clone(), - _ => panic!("Camera had incorrect sub node") + _ => panic!("Camera had incorrect sub node"), }; let mx_proj = Matrix4::from(projection.matrix(self.aspect_ratio())); self.encoder.update_constant_buffer( @@ -967,30 +958,27 @@ impl Renderer { None => [0.0; 4], }; if let Some(ref key) = gpu_data.instance_cache_key { - let data = self.instance_cache - .entry(key.clone()) - .or_insert_with(|| InstanceData { + let data = self.instance_cache.entry(key.clone()).or_insert_with(|| { + InstanceData { slice: gpu_data.slice.clone(), vertices: gpu_data.vertices.clone(), material: material.clone(), list: Vec::new(), - }); - data.list.push(Instance::basic(mx_world.into(), color, uv_range, param0)); + } + }); + data.list + .push(Instance::basic(mx_world.into(), color, uv_range, param0)); // Create a new instance and defer the draw call. continue; } Instance::basic(mx_world.into(), color, uv_range, param0) } - PsoData::Pbr { .. } => { - Instance::pbr(mx_world.into()) - } + PsoData::Pbr { .. } => Instance::pbr(mx_world.into()), }; let joint_buffer_view = if let Some(ref ptr) = *skeleton { match hub[ptr].sub_node { - SubNode::Skeleton(ref skeleton_data) => { - skeleton_data.gpu_buffer_view.clone() - } - _ => unreachable!() + SubNode::Skeleton(ref skeleton_data) => skeleton_data.gpu_buffer_view.clone(), + _ => unreachable!(), } } else { self.default_joint_buffer_view.clone() @@ -1028,7 +1016,8 @@ impl Renderer { // render instanced meshes for data in self.instance_cache.values() { if data.list.len() > self.inst_buf.len() { - self.inst_buf = self.factory + self.inst_buf = self + .factory .create_buffer( data.list.len(), gfx::buffer::Role::Vertex, @@ -1057,7 +1046,10 @@ impl Renderer { &shadow0, &shadow1, &ZEROED_DISPLACEMENT_CONTRIBUTION, - (self.default_displacement_buffer_view.clone(), self.map_default.to_param().1), + ( + self.default_displacement_buffer_view.clone(), + self.map_default.to_param().1, + ), self.default_joint_buffer_view.clone(), false, ); @@ -1180,7 +1172,10 @@ impl Renderer { shadow0: &h::ShaderResourceView<back::Resources, f32>, shadow1: &h::ShaderResourceView<back::Resources, f32>, displacement_contributions: &[DisplacementContribution], - displacements: (h::ShaderResourceView<back::Resources, [f32; 4]>, h::Sampler<back::Resources>), + displacements: ( + h::ShaderResourceView<back::Resources, [f32; 4]>, + h::Sampler<back::Resources>, + ), joint_transform_buffer_view: h::ShaderResourceView<back::Resources, [f32; 4]>, displace: bool, ) { @@ -1195,12 +1190,17 @@ impl Renderer { PsoData::Pbr { maps, mut params } => { if displace { let data = if displacement_contributions.len() > MAX_TARGETS { - error!("Too many mesh targets ({})!", displacement_contributions.len()); - &displacement_contributions[.. MAX_TARGETS] + error!( + "Too many mesh targets ({})!", + displacement_contributions.len() + ); + &displacement_contributions[..MAX_TARGETS] } else { displacement_contributions }; - encoder.update_buffer(&displacement_contributions_buf, data, 0).unwrap(); + encoder + .update_buffer(&displacement_contributions_buf, data, 0) + .unwrap(); params.pbr_flags |= PbrFlags::DISPLACEMENT_BUFFER.bits(); } encoder.update_constant_buffer(&pbr_buf, ¶ms); diff --git a/src/render/pso_data.rs b/src/render/pso_data.rs index df5e968..4b09772 100644 --- a/src/render/pso_data.rs +++ b/src/render/pso_data.rs @@ -40,15 +40,13 @@ pub(crate) struct PbrMapParams { } impl PbrMaps { - pub(crate) fn into_params( - self, - map_default: &Texture<[f32; 4]>, - ) -> PbrMapParams { + pub(crate) fn into_params(self, map_default: &Texture<[f32; 4]>) -> PbrMapParams { PbrMapParams { base_color: self.base_color.as_ref().unwrap_or(map_default).to_param(), normal: self.normal.as_ref().unwrap_or(map_default).to_param(), emissive: self.emissive.as_ref().unwrap_or(map_default).to_param(), - metallic_roughness: self.metallic_roughness + metallic_roughness: self + .metallic_roughness .as_ref() .unwrap_or(map_default) .to_param(), diff --git a/src/render/source.rs b/src/render/source.rs index 9c3b711..c080e0c 100644 --- a/src/render/source.rs +++ b/src/render/source.rs @@ -3,9 +3,9 @@ use data; use util; -use std::{io, ops, str}; use std::borrow::Borrow; use std::path::Path; +use std::{io, ops, str}; /// Source code for a single GLSL shader. #[derive(Clone, Debug, PartialEq, Eq, Hash)] @@ -19,25 +19,22 @@ impl ops::Deref for Source { } impl Source { - fn preprocess<P: AsRef<Path>>( - root: P, - code: &str, - ) -> io::Result<String> { + fn preprocess<P: AsRef<Path>>(root: P, code: &str) -> io::Result<String> { let root = root.as_ref(); let mut new_code = String::new(); for line in code.lines() { if line.starts_with("#include") { if let Some(arg) = line.split_whitespace().skip(1).next() { if arg.starts_with('<') { - if let Some(pos) = arg[1 ..].find('>') { - let name = &arg[1 .. (pos + 1)]; + if let Some(pos) = arg[1..].find('>') { + let name = &arg[1..(pos + 1)]; let path = format!("data/shaders/{}.glsl", name); let content = &data::FILES.get(&path).unwrap(); new_code += str::from_utf8(content.borrow()).unwrap(); } } else if arg.starts_with('"') { - if let Some(pos) = arg[1 ..].find('"') { - let relative_path = &arg[1 .. (pos + 1)]; + if let Some(pos) = arg[1..].find('"') { + let relative_path = &arg[1..(pos + 1)]; let path = root.join(relative_path); let content = util::read_file_to_string(&path)?; let include = Self::preprocess(root, &content)?; @@ -54,10 +51,7 @@ impl Source { } /// Load the named shader from the default set of shaders. - pub fn default( - name: &str, - suffix: &str, - ) -> io::Result<Self> { + pub fn default(name: &str, suffix: &str) -> io::Result<Self> { let path = format!("data/shaders/{}_{}.glsl", name, suffix); let unprocessed = data::FILES.get(&path).unwrap(); let processed = Self::preprocess("", str::from_utf8(unprocessed.borrow()).unwrap())?; @@ -65,11 +59,7 @@ impl Source { } /// Load the named shader from the given directory path. - pub fn user<P: AsRef<Path>>( - root: P, - name: &str, - suffix: &str, - ) -> io::Result<Self> { + pub fn user<P: AsRef<Path>>(root: P, name: &str, suffix: &str) -> io::Result<Self> { let base_name = format!("{}_{}.glsl", name, suffix); let path = root.as_ref().join(&base_name); let unprocessed = util::read_file_to_string(Path::new(&path))?; diff --git a/src/scene.rs b/src/scene.rs index 078f867..974abce 100644 --- a/src/scene.rs +++ b/src/scene.rs @@ -1,16 +1,15 @@ //! `Scene` and `SyncGuard` structures. -use node; use color::Color; use hub::{Hub, HubPtr, SubNode}; +use node; use object::{Base, DowncastObject, Group, Object}; use texture::{CubeMap, Texture}; -use std::mem; use std::marker::PhantomData; +use std::mem; use std::sync::MutexGuard; - /// Background type. #[derive(Clone, Debug, PartialEq)] pub enum Background { @@ -35,10 +34,8 @@ pub struct Scene { impl Scene { /// Add new [`Base`](struct.Base.html) to the scene. - pub fn add<P>( - &mut self, - child_base: P, - ) where + pub fn add<P>(&mut self, child_base: P) + where P: AsRef<Base>, { let mut hub = self.hub.lock().unwrap(); @@ -46,18 +43,18 @@ impl Scene { let child = &mut hub[child_base]; if child.next_sibling.is_some() { - error!("Element {:?} is added to a scene while still having old parent - {}", - child.sub_node, "discarding siblings"); + error!( + "Element {:?} is added to a scene while still having old parent - {}", + child.sub_node, "discarding siblings" + ); } child.next_sibling = mem::replace(&mut self.first_child, Some(node_ptr)); } /// Remove a previously added [`Base`](struct.Base.html) from the scene. - pub fn remove<P>( - &mut self, - child_base: P, - ) where + pub fn remove<P>(&mut self, child_base: P) + where P: AsRef<Base>, { let target_maybe = Some(child_base.as_ref().node.clone()); @@ -83,7 +80,6 @@ impl Scene { } } - /// `SyncGuard` is used to obtain information about scene nodes in the most effective way. /// /// # Examples @@ -156,10 +152,7 @@ impl<'a> SyncGuard<'a> { /// Panics if `scene` doesn't have this `object::Base`. /// /// [`Node`]: ../node/struct.Node.html - pub fn resolve<T: 'a + Object>( - &self, - object: &T, - ) -> node::Node<node::Local> { + pub fn resolve<T: 'a + Object>(&self, object: &T) -> node::Node<node::Local> { self.hub[object].to_node() } @@ -170,12 +163,10 @@ impl<'a> SyncGuard<'a> { /// Panics if the scene doesn't have this `object::Base`. /// /// [`Node`]: ../node/struct.Node.html - pub fn resolve_world<T: 'a + Object>( - &self, - object: &T, - ) -> node::Node<node::World> { + pub fn resolve_world<T: 'a + Object>(&self, object: &T) -> node::Node<node::World> { let internal = &self.hub[object] as *const _; - let wn = self.hub + let wn = self + .hub .walk_all(&self.scene.first_child) .find(|wn| wn.node as *const _ == internal) .expect("Unable to find objects for world resolve!"); @@ -223,10 +214,7 @@ impl<'a> SyncGuard<'a> { /// [`Directional`]: ../light/struct.Directional.html /// [`Hemisphere`]: ../light/struct.Hemisphere.html /// [`HemisphereLightData`]: ../light/struct.HemisphereLightData.html - pub fn resolve_data<T: 'a + Object>( - &self, - object: &T, - ) -> T::Data { + pub fn resolve_data<T: 'a + Object>(&self, object: &T) -> T::Data { object.resolve_data(self) } @@ -240,8 +228,7 @@ impl<'a> SyncGuard<'a> { pub fn walk_hierarchy(&'a self, root: &Group) -> impl Iterator<Item = Base> + 'a { let root = root.as_ref().node.clone(); let guard = &*self; - self - .hub + self.hub .walk_all(&Some(root)) .map(move |walked| guard.hub.upgrade_ptr(walked.node_ptr.clone())) } @@ -271,8 +258,7 @@ impl<'a> SyncGuard<'a> { ) -> impl Iterator<Item = Base> + 'a { let root = root.as_ref().node.clone(); let guard = &*self; - self - .hub + self.hub .walk_all(&Some(root)) .filter(move |walked| { walked @@ -308,8 +294,7 @@ impl<'a> SyncGuard<'a> { ) -> impl Iterator<Item = T> + 'a { let root = root.as_ref().node.clone(); let guard = &*self; - self - .hub + self.hub .walk_all(&Some(root)) .map(move |walked| guard.hub.upgrade_ptr(walked.node_ptr.clone())) .filter_map(move |base| guard.downcast(&base)) @@ -343,8 +328,7 @@ impl<'a> SyncGuard<'a> { name: &'a str, ) -> impl Iterator<Item = T> + 'a { let guard = &*self; - self - .find_children_by_name(root, name) + self.find_children_by_name(root, name) .filter_map(move |base| guard.downcast(&base)) } diff --git a/src/sprite.rs b/src/sprite.rs index 898f580..a251c2d 100644 --- a/src/sprite.rs +++ b/src/sprite.rs @@ -16,11 +16,8 @@ impl Sprite { } /// Set area of the texture to render. It can be used in sequential animations. - pub fn set_texel_range<P, S>( - &mut self, - base: P, - size: S, - ) where + pub fn set_texel_range<P, S>(&mut self, base: P, size: S) + where P: Into<mint::Point2<i16>>, S: Into<mint::Vector2<u16>>, { diff --git a/src/template.rs b/src/template.rs index e71027b..b9334e6 100644 --- a/src/template.rs +++ b/src/template.rs @@ -153,7 +153,9 @@ impl Template { /// ``` /// /// [`Factory::group`]: ../struct.Factory.html#method.group - pub fn new() -> Template { Default::default() } + pub fn new() -> Template { + Default::default() + } } /// Common data used by all object types. @@ -356,7 +358,6 @@ impl LightTemplate { pub fn ambient(object: usize, color: Color, intensity: f32) -> LightTemplate { LightTemplate { object, - color, intensity, sub_light: SubLightTemplate::Ambient, @@ -384,7 +385,6 @@ impl LightTemplate { pub fn directional(object: usize, color: Color, intensity: f32) -> LightTemplate { LightTemplate { object, - color, intensity, sub_light: SubLightTemplate::Directional, @@ -412,7 +412,6 @@ impl LightTemplate { pub fn point(object: usize, color: Color, intensity: f32) -> LightTemplate { LightTemplate { object, - color, intensity, sub_light: SubLightTemplate::Point, @@ -446,10 +445,11 @@ impl LightTemplate { ) -> LightTemplate { LightTemplate { object, - color: sky_color, intensity, - sub_light: SubLightTemplate::Hemisphere { ground: ground_color }, + sub_light: SubLightTemplate::Hemisphere { + ground: ground_color, + }, } } } diff --git a/src/text.rs b/src/text.rs index e039d37..9bc0f2d 100644 --- a/src/text.rs +++ b/src/text.rs @@ -2,8 +2,8 @@ use std::cell::RefCell; use std::fmt; use std::rc::Rc; -use gfx::Encoder; use gfx::handle::{DepthStencilView, RenderTargetView}; +use gfx::Encoder; use gfx_glyph as g; use mint; use object; @@ -104,10 +104,7 @@ impl Font { } } - pub(crate) fn queue( - &self, - section: &g::OwnedVariedSection, - ) { + pub(crate) fn queue(&self, section: &g::OwnedVariedSection) { let mut brush = self.brush.borrow_mut(); brush.queue(section); } @@ -126,10 +123,7 @@ impl Font { } impl fmt::Debug for Font { - fn fmt( - &self, - f: &mut fmt::Formatter, - ) -> fmt::Result { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Font {{ {} }}", self.id) } } @@ -141,19 +135,14 @@ pub(crate) struct TextData { } impl TextData { - pub(crate) fn new<S: Into<String>>( - font: &Font, - text: S, - ) -> Self { + pub(crate) fn new<S: Into<String>>(font: &Font, text: S) -> Self { TextData { section: g::OwnedVariedSection { - text: vec![ - g::OwnedSectionText { - color: [1.0, 1.0, 1.0, 1.0], - text: text.into(), - ..g::OwnedSectionText::default() - }, - ], + text: vec![g::OwnedSectionText { + color: [1.0, 1.0, 1.0, 1.0], + text: text.into(), + ..g::OwnedSectionText::default() + }], ..Default::default() }, font: font.clone(), @@ -177,19 +166,13 @@ impl Text { } /// Change text. - pub fn set_text<S: Into<String>>( - &mut self, - text: S, - ) { + pub fn set_text<S: Into<String>>(&mut self, text: S) { let msg = HubOperation::SetText(Operation::Text(text.into())); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } /// Change font. - pub fn set_font( - &mut self, - font: &Font, - ) { + pub fn set_font(&mut self, font: &Font) { let msg = HubOperation::SetText(Operation::Font(font.clone())); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } @@ -197,30 +180,21 @@ impl Text { /// Change text position. /// Coordinates in pixels from top-left. /// Defaults to (0, 0). - pub fn set_pos<P: Into<mint::Point2<f32>>>( - &mut self, - point: P, - ) { + pub fn set_pos<P: Into<mint::Point2<f32>>>(&mut self, point: P) { let msg = HubOperation::SetText(Operation::Pos(point.into())); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } /// Change maximum bounds size, in pixels from top-left. /// Defaults to unbound. - pub fn set_size<V: Into<mint::Vector2<f32>>>( - &mut self, - dimensions: V, - ) { + pub fn set_size<V: Into<mint::Vector2<f32>>>(&mut self, dimensions: V) { let msg = HubOperation::SetText(Operation::Size(dimensions.into())); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } /// Change text color. /// Defaults to white (`0xFFFFFF`). - pub fn set_color( - &mut self, - color: Color, - ) { + pub fn set_color(&mut self, color: Color) { let msg = HubOperation::SetText(Operation::Color(color)); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } @@ -228,30 +202,21 @@ impl Text { /// Change text opacity. /// From `0.0` to `1.0`. /// Defaults to `1.0`. - pub fn set_opacity( - &mut self, - opacity: f32, - ) { + pub fn set_opacity(&mut self, opacity: f32) { let msg = HubOperation::SetText(Operation::Opacity(opacity)); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } /// Change font size (scale). /// Defaults to 16. - pub fn set_font_size( - &mut self, - size: f32, - ) { + pub fn set_font_size(&mut self, size: f32) { let msg = HubOperation::SetText(Operation::Scale(size)); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } /// Change text layout. /// Defaults to `Layout::SingleLine(Align::Left)`. - pub fn set_layout( - &mut self, - layout: Layout, - ) { + pub fn set_layout(&mut self, layout: Layout) { let msg = HubOperation::SetText(Operation::Layout(layout)); let _ = self.object.tx.send((self.object.node.downgrade(), msg)); } diff --git a/src/texture.rs b/src/texture.rs index c136ec6..338d16d 100644 --- a/src/texture.rs +++ b/src/texture.rs @@ -19,8 +19,10 @@ pub struct Texture<T> { view: h::ShaderResourceView<BackendResources, T>, sampler: h::Sampler<BackendResources>, total_size: [u32; 2], - #[derivative(Hash(hash_with = "util::hash_f32_slice"))] tex0: [f32; 2], - #[derivative(Hash(hash_with = "util::hash_f32_slice"))] tex1: [f32; 2], + #[derivative(Hash(hash_with = "util::hash_f32_slice"))] + tex0: [f32; 2], + #[derivative(Hash(hash_with = "util::hash_f32_slice"))] + tex1: [f32; 2], } impl<T> Texture<T> { @@ -48,11 +50,7 @@ impl<T> Texture<T> { } /// See [`Sprite::set_texel_range`](struct.Sprite.html#method.set_texel_range). - pub fn set_texel_range( - &mut self, - base: mint::Point2<i16>, - size: mint::Vector2<u16>, - ) { + pub fn set_texel_range(&mut self, base: mint::Point2<i16>, size: mint::Vector2<u16>) { self.tex0 = [ base.x as f32, self.total_size[1] as f32 - base.y as f32 - size.y as f32, diff --git a/src/util.rs b/src/util.rs index d65834a..1047746 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,7 +1,7 @@ //! Internal utility functions. -use std::{fs, io, path}; use std::hash::{Hash, Hasher}; +use std::{fs, io, path}; /// Reads the entire contents of a file into a `String`. pub fn read_file_to_string<P: AsRef<path::Path>>(path: P) -> io::Result<String> { @@ -14,18 +14,12 @@ pub fn read_file_to_string<P: AsRef<path::Path>>(path: P) -> io::Result<String> } /// Hash f32 value using its bit interpretation. -pub fn hash_f32<H: Hasher>( - value: &f32, - state: &mut H, -) { +pub fn hash_f32<H: Hasher>(value: &f32, state: &mut H) { value.to_bits().hash(state); } /// Hash slice of floats using its bit interpretation. -pub fn hash_f32_slice<H: Hasher>( - value: &[f32], - state: &mut H, -) { +pub fn hash_f32_slice<H: Hasher>(value: &[f32], state: &mut H) { for element in value { element.to_bits().hash(state); } diff --git a/src/window.rs b/src/window.rs index 4cfe785..dc56b80 100644 --- a/src/window.rs +++ b/src/window.rs @@ -6,11 +6,11 @@ use render; use camera::Camera; use factory::Factory; +use glutin::{GlProfile, GlRequest, PossiblyCurrent}; use input::Input; use render::Renderer; use scene::Scene; use std::path::PathBuf; -use glutin::{GlRequest, GlProfile, PossiblyCurrent}; /// `Window` is the core entity of every `three-rs` application. /// @@ -50,48 +50,32 @@ impl Builder { /// Set the size of the viewport (the resolution) in logical pixels. /// That is the dpi setting affects the amount of pixels used but the window will /// take up the same amount of space regardless of dpi. Defaults to 1024x768. - pub fn dimensions( - &mut self, - width: f64, - height: f64, - ) -> &mut Self { + pub fn dimensions(&mut self, width: f64, height: f64) -> &mut Self { self.dimensions = glutin::dpi::LogicalSize::new(width, height); self } /// Whether enable fullscreen mode or not. Defauls to `false`. - pub fn fullscreen( - &mut self, - option: bool, - ) -> &mut Self { + pub fn fullscreen(&mut self, option: bool) -> &mut Self { self.fullscreen = option; self } /// Sets the multisampling level to request. A value of `0` indicates that multisampling must /// not be enabled. Must be the power of 2. Defaults to `0`. - pub fn multisampling( - &mut self, - option: u16, - ) -> &mut Self { + pub fn multisampling(&mut self, option: u16) -> &mut Self { self.multisampling = option; self } /// Specifies the user shader directory. - pub fn shader_directory<P: Into<PathBuf>>( - &mut self, - option: P, - ) -> &mut Self { + pub fn shader_directory<P: Into<PathBuf>>(&mut self, option: P) -> &mut Self { self.shader_directory = Some(option.into()); self } /// Whether to enable vertical synchronization or not. Defaults to `true`. - pub fn vsync( - &mut self, - option: bool, - ) -> &mut Self { + pub fn vsync(&mut self, option: bool) -> &mut Self { self.vsync = option; self } @@ -150,7 +134,8 @@ impl Builder { try_override!(basic, gouraud, pbr, phong, quad, shadow, skybox, sprite,); } - let (renderer, windowedContext, mut factory) = Renderer::new(builder, context, &event_loop, &source_set); + let (renderer, windowedContext, mut factory) = + Renderer::new(builder, context, &event_loop, &source_set); let dpi = windowedContext.window().get_hidpi_factor(); let scene = factory.scene(); Window { @@ -207,17 +192,23 @@ impl Window { WindowEvent::Focused(state) => input.window_focus(state), WindowEvent::CloseRequested | WindowEvent::Destroyed => running = false, WindowEvent::KeyboardInput { - input: glutin::KeyboardInput { - state, - virtual_keycode: Some(keycode), - .. - }, + input: + glutin::KeyboardInput { + state, + virtual_keycode: Some(keycode), + .. + }, .. } => input.keyboard_input(state, keycode), - WindowEvent::MouseInput { state, button, .. } => input.mouse_input(state, button), + WindowEvent::MouseInput { state, button, .. } => { + input.mouse_input(state, button) + } WindowEvent::CursorMoved { position, .. } => { let pos = position.to_physical(dpi); - input.mouse_moved([pos.x as f32, pos.y as f32].into(), renderer.map_to_ndc([pos.x as f32, pos.y as f32])); + input.mouse_moved( + [pos.x as f32, pos.y as f32].into(), + renderer.map_to_ndc([pos.x as f32, pos.y as f32]), + ); } WindowEvent::MouseWheel { delta, .. } => input.mouse_wheel_input(delta), _ => {} @@ -236,16 +227,14 @@ impl Window { } /// Render the current scene with specific [`Camera`](struct.Camera.html). - pub fn render( - &mut self, - camera: &Camera, - ) { + pub fn render(&mut self, camera: &Camera) { self.renderer.render(&self.scene, camera); } /// Get current window size in pixels. pub fn size(&self) -> mint::Vector2<f32> { - let size = self.windowedContext + let size = self + .windowedContext .window() .get_inner_size() .expect("Can't get window size")