Просмотр исходного кода

cleanup code and run cargo fmt

narodnik 5 лет назад
Родитель
Сommit
1afc4269de

+ 1 - 1
Cargo.toml

@@ -64,7 +64,7 @@ async-native-tls = "0.3.3"
 anyhow = "1.0"
 bytemuck = { version = "1.4", features = [ "derive" ] }
 image = "0.23"
-winit = "0.22"
+winit = "0.23"
 shaderc = "0.7"
 cgmath = "0.17"
 env_logger = "0.7"

+ 30 - 17
lisp/core.rs

@@ -368,9 +368,7 @@ fn mul_scalar(a: MalArgs) -> MalRet {
             Ok(Str(std::string::ToString::to_string(&s0)[2..].to_string()))
         }
         (ZKScalar(a0), Str(a1)) => {
-            let (mut s0, s1) = (a0,
-                bls12_381::Scalar::from_string(&a1),
-            );
+            let (mut s0, s1) = (a0, bls12_381::Scalar::from_string(&a1));
             s0.mul_assign(s1);
             Ok(Str(std::string::ToString::to_string(&s0)[2..].to_string()))
         }
@@ -379,8 +377,7 @@ fn mul_scalar(a: MalArgs) -> MalRet {
             s0.mul_assign(s1);
             Ok(Str(std::string::ToString::to_string(&s0)[2..].to_string()))
         }
-        _ => error( 
-            &format!("scalar mul expect (zkscalar, zkscalar) \n {:?}", a).to_string())
+        _ => error(&format!("scalar mul expect (zkscalar, zkscalar) \n {:?}", a).to_string()),
     }
 }
 
@@ -421,8 +418,7 @@ fn div_scalar(a: MalArgs) -> MalRet {
                 error("DivisionByZero")
             }
         }
-        _ => error( 
-            &format!("scalar div expect (zkscalar, zkscalar) \n {:?}", a).to_string())
+        _ => error(&format!("scalar div expect (zkscalar, zkscalar) \n {:?}", a).to_string()),
     }
 }
 
@@ -529,18 +525,21 @@ fn scalar_invert(a: MalArgs) -> MalRet {
             if let Vector(ref values, _) = a[0].apply(vec![]).unwrap() {
                 if let ZKScalar(a0) = values[0] {
                     if a0.is_zero() {
-                        error(
-                            &format!("scalar invert divizion by zero \n {:?}", a0).to_string())
+                        error(&format!("scalar invert divizion by zero \n {:?}", a0).to_string())
                     } else {
-                        Ok(ZKScalar(a0.invert().unwrap()))        
+                        Ok(ZKScalar(a0.invert().unwrap()))
                     }
                 } else {
                     error(
-                        &format!("scalar invert expect (zkscalar or string) found \n {:?}", a).to_string())
+                        &format!("scalar invert expect (zkscalar or string) found \n {:?}", a)
+                            .to_string(),
+                    )
                 }
             } else {
                 error(
-                    &format!("scalar invert expect (zkscalar or string) found \n {:?}", a).to_string())
+                    &format!("scalar invert expect (zkscalar or string) found \n {:?}", a)
+                        .to_string(),
+                )
             }
         }
         ZKScalar(a0) => {
@@ -562,14 +561,24 @@ fn scalar_is_zero(a: MalArgs) -> MalRet {
         Func(_, _) => {
             if let Vector(ref values, _) = a[0].apply(vec![]).unwrap() {
                 if let ZKScalar(a0) = values[0] {
-                    Ok(Bool(a0.is_zero()))        
+                    Ok(Bool(a0.is_zero()))
                 } else {
                     error(
-                        &format!("scalar is zero expect (zkscalar or string) found \n {:?}", a).to_string())
+                        &format!(
+                            "scalar is zero expect (zkscalar or string) found \n {:?}",
+                            a
+                        )
+                        .to_string(),
+                    )
                 }
             } else {
                 error(
-                    &format!("scalar is zero expect (zkscalar or string) found \n {:?}", a).to_string())
+                    &format!(
+                        "scalar is zero expect (zkscalar or string) found \n {:?}",
+                        a
+                    )
+                    .to_string(),
+                )
             }
         }
         ZKScalar(a0) => {
@@ -581,7 +590,11 @@ fn scalar_is_zero(a: MalArgs) -> MalRet {
             Ok(Bool(s0.is_zero()))
         }
         _ => error(
-            &format!("scalar is zero expect (zkscalar or string) found \n {:?}", a).to_string(),
+            &format!(
+                "scalar is zero expect (zkscalar or string) found \n {:?}",
+                a
+            )
+            .to_string(),
         ),
     }
 }
@@ -615,7 +628,7 @@ fn add_scalar(a: MalArgs) -> MalRet {
         }
         (ZKScalar(a0), ZKScalar(a1)) => {
             let (mut z0, z1) = (a0.clone(), a1.clone());
-            z0.add_assign(z1);        
+            z0.add_assign(z1);
             Ok(ZKScalar(z0))
         }
         (Str(a0), Str(a1)) => {

+ 1 - 1
lisp/env.rs

@@ -1,6 +1,6 @@
 use std::cell::RefCell;
-use std::rc::Rc;
 use std::collections::HashMap;
+use std::rc::Rc;
 // use fnv::FnvHashMap;
 
 use crate::types::MalErr::ErrString;

+ 16 - 38
lisp/lisp.rs

@@ -11,13 +11,13 @@ use bls12_381::Bls12;
 // use fnv::FnvHashMap;
 use itertools::Itertools;
 use rand::rngs::OsRng;
-use std::{collections::HashMap, cell::RefCell};
 use std::rc::Rc;
 use std::time::Instant;
 use std::{
     borrow::{Borrow, BorrowMut},
     fs,
 };
+use std::{cell::RefCell, collections::HashMap};
 use types::EnforceAllocation;
 
 #[macro_use]
@@ -31,7 +31,9 @@ extern crate regex;
 #[macro_use]
 mod types;
 use crate::types::MalErr::{ErrMalVal, ErrString};
-use crate::types::MalVal::{Bool, Enforce, Func, Hash, List, MalFunc, Nil, Str, Sym, Vector, Alloc};
+use crate::types::MalVal::{
+    Alloc, Bool, Enforce, Func, Hash, List, MalFunc, Nil, Str, Sym, Vector,
+};
 use crate::types::VerifyKeyParams;
 use crate::types::{error, format_error, MalArgs, MalErr, MalRet, MalVal};
 mod env;
@@ -108,7 +110,7 @@ fn macroexpand(mut ast: MalVal, env: &Env) -> (bool, MalRet) {
             Err(e) => return (false, Err(e)),
             Ok(a) => a,
         };
-        // println!("macroexpand 2: {:?}", ast); 
+        // println!("macroexpand 2: {:?}", ast);
         was_expanded = true;
     }
     (was_expanded, Ok(ast))
@@ -297,7 +299,7 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                                 Ok(Nil)
                             }
                             _ => error("invalid args for dotimes"),
-                        }                        
+                        }
                     }
                     Sym(ref a0sym) if a0sym == "if" => {
                         let cond = eval(l[1].clone(), env.clone())?;
@@ -352,23 +354,15 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         let result = eval(value.clone(), env.clone())?;
                         let allocs = get_allocations(&env, "AllocationsConst");
                         allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
-                        // let mut new_hm: HashMap<String, MalVal> = HashMap::default();                        
+                        // let mut new_hm: HashMap<String, MalVal> = HashMap::default();
                         // for (k, v) in allocs.borrow_mut().iter() {
                         //     new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
                         // }
-                        // new_hm.insert(a1.pr_str(false), result.clone());      
+                        // new_hm.insert(a1.pr_str(false), result.clone());
                         if let Some(e) = &env.outer {
-                            env_set(
-                                &e,
-                                Sym("AllocationsConst".to_string()),
-                                Alloc(allocs),
-                            )?;
+                            env_set(&e, Sym("AllocationsConst".to_string()), Alloc(allocs))?;
                         } else {
-                            env_set(
-                                &env,
-                                Sym("AllocationsConst".to_string()),
-                                Alloc(allocs),
-                            )?;
+                            env_set(&env, Sym("AllocationsConst".to_string()), Alloc(allocs))?;
                         }
                         // println!("Alloc Const: {:?}", start.elapsed());
                         Ok(result.clone())
@@ -386,17 +380,9 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         // }
                         // new_hm.insert(a1.pr_str(false), result.clone());
                         if let Some(e) = &env.outer {
-                            env_set(
-                                &e,
-                                Sym("AllocationsInput".to_string()),
-                                Alloc(allocs),
-                            )?;
+                            env_set(&e, Sym("AllocationsInput".to_string()), Alloc(allocs))?;
                         } else {
-                            env_set(
-                                &env,
-                                Sym("AllocationsInput".to_string()),
-                                Alloc(allocs),
-                            )?;
+                            env_set(&env, Sym("AllocationsInput".to_string()), Alloc(allocs))?;
                         }
                         // println!("Alloc Input: {:?}", start.elapsed());
                         Ok(result.clone())
@@ -407,27 +393,19 @@ fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
                         let mut value = eval(l[2].clone(), env.clone())?;
                         if let Func(_, _) = value {
                             value = value.apply(vec![]).unwrap();
-                        } 
+                        }
                         let result = eval(value.clone(), env.clone())?;
                         let allocs = get_allocations(&env, "Allocations");
                         allocs.borrow_mut().insert(a1.pr_str(false), result.clone());
                         // let mut new_hm: HashMap<String, MalVal> = HashMap::default();
                         // for (k, v) in allocs.borrow_mut().iter() {
                         //     new_hm.insert(k.to_string(), eval(v.clone(), env.clone())?);
-                        // }                                        
+                        // }
                         // new_hm.insert(a1.pr_str(false), result.clone());
                         if let Some(e) = &env.outer {
-                            env_set(
-                                &e,
-                                Sym("Allocations".to_string()),
-                                Alloc(allocs),
-                            )?;
+                            env_set(&e, Sym("Allocations".to_string()), Alloc(allocs))?;
                         } else {
-                            env_set(
-                                &env,
-                                Sym("Allocations".to_string()),
-                                Alloc(allocs),
-                            )?;
+                            env_set(&env, Sym("Allocations".to_string()), Alloc(allocs))?;
                         }
                         // println!("Alloc: {:?}", start.elapsed());
                         Ok(result.clone())

+ 10 - 4
lisp/types.rs

@@ -1,8 +1,8 @@
 use bellman::{gadgets::Assignment, groth16, Circuit, ConstraintSystem, SynthesisError};
 use sapvi::bls_extensions::BlsStringConversion;
-use std::{cell::RefCell, collections::HashMap};
 use std::ops::{Add, AddAssign, MulAssign, SubAssign};
 use std::rc::Rc;
+use std::{cell::RefCell, collections::HashMap};
 // use fnv::FnvHashMap;
 use itertools::Itertools;
 
@@ -142,7 +142,9 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                                 let val = bls12_381::Scalar::from_string(&s.to_string());
                                 left = left + (val, val_b);
                             }
-                            _ => { println!("not a valid param {:?}", value) }
+                            _ => {
+                                println!("not a valid param {:?}", value)
+                            }
                         }
                     }
                 }
@@ -169,7 +171,9 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                                 let val = bls12_381::Scalar::from_string(&s.to_string());
                                 right = right + (val, val_b);
                             }
-                            _ => { println!("not a valid param {:?}", value) }
+                            _ => {
+                                println!("not a valid param {:?}", value)
+                            }
                         }
                     }
                 }
@@ -197,7 +201,9 @@ impl Circuit<bls12_381::Scalar> for LispCircuit {
                                 let val = bls12_381::Scalar::from_string(&s.to_string());
                                 output = output + (val, val_b);
                             }
-                            _ => { println!("not a valid param {:?}", value) }
+                            _ => {
+                                println!("not a valid param {:?}", value)
+                            }
                         }
                     }
                 }

+ 126 - 272
src/bin/dfg.rs

@@ -1,5 +1,5 @@
-use std::iter;
 use rand::Rng;
+use std::iter;
 
 use cgmath::prelude::*;
 use wgpu::util::DeviceExt;
@@ -9,7 +9,7 @@ use winit::{
     window::Window,
 };
 
-use sapvi::gfx::{model, texture};
+use sapvi::gfx::{camera, model, texture};
 
 use model::{DrawLight, DrawModel, Vertex};
 
@@ -27,34 +27,8 @@ fn get_time() -> f32 {
 
 const FONT_BYTES: &[u8] = include_bytes!("../../res/font/PressStart2P-Regular.ttf");
 
-#[rustfmt::skip]
-pub const OPENGL_TO_WGPU_MATRIX: cgmath::Matrix4<f32> = cgmath::Matrix4::new(
-    1.0, 0.0, 0.0, 0.0,
-    0.0, 1.0, 0.0, 0.0,
-    0.0, 0.0, 0.5, 0.0,
-    0.0, 0.0, 0.5, 1.0,
-);
-
 const NUM_INSTANCES_PER_ROW: u32 = 10;
 
-struct Camera {
-    eye: cgmath::Point3<f32>,
-    target: cgmath::Point3<f32>,
-    up: cgmath::Vector3<f32>,
-    aspect: f32,
-    fovy: f32,
-    znear: f32,
-    zfar: f32,
-}
-
-impl Camera {
-    fn build_view_projection_matrix(&self) -> cgmath::Matrix4<f32> {
-        let view = cgmath::Matrix4::look_at(self.eye, self.target, self.up);
-        let proj = cgmath::perspective(cgmath::Deg(self.fovy), self.aspect, self.znear, self.zfar);
-        proj * view
-    }
-}
-
 #[repr(C)]
 #[derive(Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
 struct Uniforms {
@@ -70,113 +44,9 @@ impl Uniforms {
         }
     }
 
-    fn update_view_proj(&mut self, camera: &Camera) {
-        // We don't specifically need homogeneous coordinates since we're just using
-        // a vec3 in the shader. We're using Point3 for the camera.eye, and this is
-        // the easiest way to convert to Vector4. We're using Vector4 because of
-        // the uniforms 16 byte spacing requirement
-        self.view_position = camera.eye.to_homogeneous().into();
-        // self.view_proj = OPENGL_TO_WGPU_MATRIX * camera.build_view_projection_matrix();
-        self.view_proj = camera.build_view_projection_matrix().into();
-    }
-}
-
-struct CameraController {
-    speed: f32,
-    is_up_pressed: bool,
-    is_down_pressed: bool,
-    is_forward_pressed: bool,
-    is_backward_pressed: bool,
-    is_left_pressed: bool,
-    is_right_pressed: bool,
-}
-
-impl CameraController {
-    fn new(speed: f32) -> Self {
-        Self {
-            speed,
-            is_up_pressed: false,
-            is_down_pressed: false,
-            is_forward_pressed: false,
-            is_backward_pressed: false,
-            is_left_pressed: false,
-            is_right_pressed: false,
-        }
-    }
-
-    fn process_events(&mut self, event: &WindowEvent) -> bool {
-        match event {
-            WindowEvent::KeyboardInput {
-                input:
-                    KeyboardInput {
-                        state,
-                        virtual_keycode: Some(keycode),
-                        ..
-                    },
-                ..
-            } => {
-                let is_pressed = *state == ElementState::Pressed;
-                match keycode {
-                    VirtualKeyCode::Space => {
-                        self.is_up_pressed = is_pressed;
-                        true
-                    }
-                    VirtualKeyCode::LShift => {
-                        self.is_down_pressed = is_pressed;
-                        true
-                    }
-                    VirtualKeyCode::W | VirtualKeyCode::Up => {
-                        self.is_forward_pressed = is_pressed;
-                        true
-                    }
-                    VirtualKeyCode::A | VirtualKeyCode::Left => {
-                        self.is_left_pressed = is_pressed;
-                        true
-                    }
-                    VirtualKeyCode::S | VirtualKeyCode::Down => {
-                        self.is_backward_pressed = is_pressed;
-                        true
-                    }
-                    VirtualKeyCode::D | VirtualKeyCode::Right => {
-                        self.is_right_pressed = is_pressed;
-                        true
-                    }
-                    _ => false,
-                }
-            }
-            _ => false,
-        }
-    }
-
-    fn update_camera(&self, camera: &mut Camera) {
-        let forward = camera.target - camera.eye;
-        let forward_norm = forward.normalize();
-        let forward_mag = forward.magnitude();
-
-        // Prevents glitching when camera gets too close to the
-        // center of the scene.
-        if self.is_forward_pressed && forward_mag > self.speed {
-            camera.eye += forward_norm * self.speed;
-        }
-        if self.is_backward_pressed {
-            camera.eye -= forward_norm * self.speed;
-        }
-
-        let right = forward_norm.cross(camera.up);
-
-        // Redo radius calc in case the up/ down is pressed.
-        let forward = camera.target - camera.eye;
-        let forward_mag = forward.magnitude();
-
-        if self.is_right_pressed {
-            // Rescale the distance between the target and eye so
-            // that it doesn't change. The eye therefore still
-            // lies on the circle made by the target and eye.
-            camera.eye = camera.target - (forward + right * self.speed).normalize() * forward_mag;
-        }
-        if self.is_left_pressed {
-            camera.eye = camera.target - (forward - right * self.speed).normalize() * forward_mag;
-        }
+    fn update_view_proj(&mut self, camera: &camera::Camera, projection: &camera::Projection) {
+        self.view_position = camera.position.to_homogeneous().into();
+        self.view_proj = (projection.calc_matrix() * camera.calc_matrix()).into()
     }
 }
 
@@ -325,8 +195,11 @@ struct State {
     swap_chain: wgpu::SwapChain,
     render_pipeline: wgpu::RenderPipeline,
     obj_model: model::Model,
-    camera: Camera,
-    camera_controller: CameraController,
+
+    camera: camera::Camera,                      // UPDATED!
+    projection: camera::Projection,              // NEW!
+    camera_controller: camera::CameraController, // UPDATED!
+
     uniforms: Uniforms,
     uniform_buffer: wgpu::Buffer,
     uniform_bind_group: wgpu::BindGroup,
@@ -355,6 +228,7 @@ struct State {
     staging_belt: wgpu::util::StagingBelt,
 
     is_space_pressed: bool,
+    mouse_pressed: bool,
 }
 
 fn create_render_pipeline(
@@ -475,20 +349,13 @@ impl State {
                 label: Some("texture_bind_group_layout"),
             });
 
-        let camera = Camera {
-            eye: (0.0, 5.0, -10.0).into(),
-            target: (0.0, 0.0, 0.0).into(),
-            up: cgmath::Vector3::unit_y(),
-            aspect: sc_desc.width as f32 / sc_desc.height as f32,
-            fovy: 45.0,
-            znear: 0.1,
-            zfar: 100.0,
-        };
-
-        let camera_controller = CameraController::new(0.2);
+        let camera = camera::Camera::new((0.0, 5.0, 10.0), cgmath::Deg(-90.0), cgmath::Deg(-20.0));
+        let projection =
+            camera::Projection::new(sc_desc.width, sc_desc.height, cgmath::Deg(45.0), 0.1, 100.0);
+        let camera_controller = camera::CameraController::new(4.0, 0.4);
 
         let mut uniforms = Uniforms::new();
-        uniforms.update_view_proj(&camera);
+        uniforms.update_view_proj(&camera, &projection);
 
         let uniform_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
             label: Some("Uniform Buffer"),
@@ -503,31 +370,14 @@ impl State {
                     let x = SPACE_BETWEEN * (x as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0);
                     let z = SPACE_BETWEEN * (z as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0);
 
-                    let time = get_time() * 100.0;
-                    println!("{} {} {}", x, z, time);
-                    let y = ((x + time).sin() + (z + time).sin()) * 20.0;
+                    let y = 0.0;
 
                     let position = cgmath::Vector3 { x, y, z };
 
-                    let rotation = 
-                        cgmath::Quaternion::from_axis_angle(
-                            cgmath::Vector3::unit_z(),
-                            cgmath::Deg(180.0 + 0.0),
-                        );
-
-                            /*
-                    let rotation = if position.is_zero() {
-                        cgmath::Quaternion::from_axis_angle(
-                            cgmath::Vector3::unit_z(),
-                            cgmath::Deg(180.0 + 0.0),
-                        )
-                    } else {
-                        cgmath::Quaternion::from_axis_angle(
-                            position.clone().normalize(),
-                            cgmath::Deg(180.0 + 45.0),
-                        )
-                    };
-                    */
+                    let rotation = cgmath::Quaternion::from_axis_angle(
+                        cgmath::Vector3::unit_z(),
+                        cgmath::Deg(180.0 + 0.0),
+                    );
 
                     Instance { position, rotation }
                 })
@@ -701,8 +551,7 @@ impl State {
 
         let cartoon_bytes = include_bytes!("../../res/img/absolutely-proprietary2.png");
         let cartoon_texture =
-            texture::Texture::from_bytes(&device, &queue, cartoon_bytes, "stallman2")
-                .unwrap();
+            texture::Texture::from_bytes(&device, &queue, cartoon_bytes, "stallman2").unwrap();
 
         let cartoon_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
             layout: &texture_bind_group_layout,
@@ -719,9 +568,6 @@ impl State {
             label: Some("cartoon_bind_group"),
         });
 
-        let vs_module = device.create_shader_module(&wgpu::include_spirv!("../../res/shader/ui_shader.vert.spv"));
-        let fs_module = device.create_shader_module(&wgpu::include_spirv!("../../res/shader/ui_shader.frag.spv"));
-
         let render_pipeline_layout =
             device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                 label: Some("Render Pipeline Layout"),
@@ -729,47 +575,15 @@ impl State {
                 push_constant_ranges: &[],
             });
 
-        let ui_render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
-            label: Some("Render Pipeline"),
-            layout: Some(&render_pipeline_layout),
-            vertex: wgpu::VertexState {
-                module: &vs_module,
-                entry_point: "main",
-                buffers: &[model::ModelVertex::desc()],
-            },
-            fragment: Some(wgpu::FragmentState {
-                module: &fs_module,
-                entry_point: "main",
-                targets: &[wgpu::ColorTargetState {
-                    format: sc_desc.format,
-                    alpha_blend: wgpu::BlendState::REPLACE,
-                    color_blend: wgpu::BlendState::REPLACE,
-                    write_mask: wgpu::ColorWrite::ALL,
-                }],
-            }),
-            primitive: wgpu::PrimitiveState {
-                topology: wgpu::PrimitiveTopology::TriangleList,
-                strip_index_format: None,
-                front_face: wgpu::FrontFace::Ccw,
-                cull_mode: wgpu::CullMode::Back,
-                // Setting this to anything other than Fill requires Features::NON_FILL_POLYGON_MODE
-                polygon_mode: wgpu::PolygonMode::Fill,
-            },
-        depth_stencil: Some(wgpu::DepthStencilState {
-            format: texture::Texture::DEPTH_FORMAT,
-            depth_write_enabled: true,
-            depth_compare: wgpu::CompareFunction::Less,
-            stencil: wgpu::StencilState::default(),
-            bias: wgpu::DepthBiasState::default(),
-            // Setting this to true requires Features::DEPTH_CLAMPING
-            clamp_depth: false,
-        }),
-            multisample: wgpu::MultisampleState {
-                count: 1,
-                mask: !0,
-                alpha_to_coverage_enabled: false,
-            },
-        });
+        let ui_render_pipeline = create_render_pipeline(
+            &device,
+            &render_pipeline_layout,
+            sc_desc.format,
+            Some(texture::Texture::DEPTH_FORMAT),
+            &[model::ModelVertex::desc()],
+            wgpu::include_spirv!("../../res/shader/ui_shader.vert.spv"),
+            wgpu::include_spirv!("../../res/shader/ui_shader.frag.spv"),
+        );
 
         let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
             label: Some("Vertex Buffer"),
@@ -796,8 +610,11 @@ impl State {
             swap_chain,
             render_pipeline,
             obj_model,
+
             camera,
+            projection,
             camera_controller,
+
             uniform_buffer,
             uniform_bind_group,
             uniforms,
@@ -823,11 +640,12 @@ impl State {
             staging_belt,
 
             is_space_pressed: true,
+            mouse_pressed: false,
         }
     }
 
     fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
-        self.camera.aspect = self.sc_desc.width as f32 / self.sc_desc.height as f32;
+        self.projection.resize(new_size.width, new_size.height);
         self.size = new_size;
         self.sc_desc.width = new_size.width;
         self.sc_desc.height = new_size.height;
@@ -836,17 +654,42 @@ impl State {
             texture::Texture::create_depth_texture(&self.device, &self.sc_desc, "depth_texture");
     }
 
-    fn input(&mut self, event: &WindowEvent) -> bool {
-        self.camera_controller.process_events(event)
+    fn input(&mut self, event: &DeviceEvent) -> bool {
+        match event {
+            DeviceEvent::Key(KeyboardInput {
+                virtual_keycode: Some(key),
+                state,
+                ..
+            }) => self.camera_controller.process_keyboard(*key, *state),
+            DeviceEvent::MouseWheel { delta, .. } => {
+                self.camera_controller.process_scroll(delta);
+                true
+            }
+            DeviceEvent::Button {
+                button: 1, // Left Mouse Button
+                state,
+            } => {
+                self.mouse_pressed = *state == ElementState::Pressed;
+                true
+            }
+            DeviceEvent::MouseMotion { delta } => {
+                if self.mouse_pressed {
+                    self.camera_controller.process_mouse(delta.0, delta.1);
+                }
+                true
+            }
+            _ => false,
+        }
     }
 
-    fn update(&mut self) {
+    fn update(&mut self, dt: std::time::Duration) {
         if rand::thread_rng().gen_range(0, 5) == 0 {
             self.is_space_pressed = !self.is_space_pressed;
         }
 
-        self.camera_controller.update_camera(&mut self.camera);
-        self.uniforms.update_view_proj(&self.camera);
+        self.camera_controller.update_camera(&mut self.camera, dt);
+        self.uniforms
+            .update_view_proj(&self.camera, &self.projection);
         self.queue.write_buffer(
             &self.uniform_buffer,
             0,
@@ -862,15 +705,14 @@ impl State {
                     let z = SPACE_BETWEEN * (z as f32 - NUM_INSTANCES_PER_ROW as f32 / 2.0);
 
                     //println!("{} {} {}", x, z, time);
-                    let y = ((x/3.0 + time).sin() + (z/3.0 + time).cos()) * 1.5;
+                    let y = ((x / 3.0 + time).sin() + (z / 3.0 + time).cos()) * 1.5;
 
                     let position = cgmath::Vector3 { x, y, z };
 
-                    let rotation = 
-                        cgmath::Quaternion::from_axis_angle(
-                            cgmath::Vector3::unit_z(),
-                            cgmath::Deg(180.0 + 0.0),
-                        );
+                    let rotation = cgmath::Quaternion::from_axis_angle(
+                        cgmath::Vector3::unit_z(),
+                        cgmath::Deg(180.0 + 0.0),
+                    );
 
                     Instance { position, rotation }
                 })
@@ -878,8 +720,11 @@ impl State {
             .collect::<Vec<_>>();
 
         let instance_data = instances.iter().map(Instance::to_raw).collect::<Vec<_>>();
-        self.queue.write_buffer(&self.instance_buffer, 0, 
-            bytemuck::cast_slice(&instance_data));
+        self.queue.write_buffer(
+            &self.instance_buffer,
+            0,
+            bytemuck::cast_slice(&instance_data),
+        );
 
         // Update the light
         let old_position: cgmath::Vector3<_> = self.light.position.into();
@@ -964,18 +809,18 @@ impl State {
         };
         draw_text(&play_text, &mut self.glyph_brush);
 
-                self.glyph_brush
-                    .draw_queued(
-                        &self.device,
-                        &mut self.staging_belt,
-                        &mut encoder,
-                        &frame.view,
-                        self.sc_desc.width,
-                        self.sc_desc.height,
-                    )
-                    .unwrap();
+        self.glyph_brush
+            .draw_queued(
+                &self.device,
+                &mut self.staging_belt,
+                &mut encoder,
+                &frame.view,
+                self.sc_desc.width,
+                self.sc_desc.height,
+            )
+            .unwrap();
 
-                self.staging_belt.finish();
+        self.staging_belt.finish();
 
         self.queue.submit(iter::once(encoder.finish()));
 
@@ -990,20 +835,21 @@ fn draw_text(text: &Text, glyph_brush: &mut wgpu_glyph::GlyphBrush<()>) {
         wgpu_glyph::HorizontalAlign::Left
     });
 
-    let section =
-        wgpu_glyph::Section {
-            screen_position: text.position.into(),
-            bounds: text.bounds.into(),
-            layout,
-            ..Default::default()
-        }
-        .add_text(wgpu_glyph::Text::new(&text.text).with_color(text.color).with_scale(
-            if text.focused {
+    let section = wgpu_glyph::Section {
+        screen_position: text.position.into(),
+        bounds: text.bounds.into(),
+        layout,
+        ..Default::default()
+    }
+    .add_text(
+        wgpu_glyph::Text::new(&text.text)
+            .with_color(text.color)
+            .with_scale(if text.focused {
                 text.size + 8.0
             } else {
                 text.size
-            },
-        ));
+            }),
+    );
 
     glyph_brush.queue(section);
 }
@@ -1018,39 +864,47 @@ fn main() {
         .unwrap();
     use futures::executor::block_on;
     let mut state = block_on(State::new(&window));
+    let mut last_render_time = std::time::Instant::now();
     event_loop.run(move |event, _, control_flow| {
         *control_flow = ControlFlow::Poll;
         match event {
             Event::MainEventsCleared => window.request_redraw(),
+            Event::DeviceEvent {
+                ref event,
+                .. // We're not using device_id currently
+            } => {
+                state.input(event);
+            }
             Event::WindowEvent {
                 ref event,
                 window_id,
             } if window_id == window.id() => {
-                if !state.input(event) {
-                    match event {
-                        WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
-                        WindowEvent::KeyboardInput { input, .. } => match input {
-                            KeyboardInput {
-                                state: ElementState::Pressed,
-                                virtual_keycode: Some(VirtualKeyCode::Escape),
-                                ..
-                            } => {
-                                *control_flow = ControlFlow::Exit;
-                            }
-                            _ => {}
-                        },
-                        WindowEvent::Resized(physical_size) => {
-                            state.resize(*physical_size);
-                        }
-                        WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
-                            state.resize(**new_inner_size);
+                match event {
+                    WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
+                    WindowEvent::KeyboardInput { input, .. } => match input {
+                        KeyboardInput {
+                            state: ElementState::Pressed,
+                            virtual_keycode: Some(VirtualKeyCode::Escape),
+                            ..
+                        } => {
+                            *control_flow = ControlFlow::Exit;
                         }
                         _ => {}
+                    },
+                    WindowEvent::Resized(physical_size) => {
+                        state.resize(*physical_size);
+                    }
+                    WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
+                        state.resize(**new_inner_size);
                     }
+                    _ => {}
                 }
             }
             Event::RedrawRequested(_) => {
-                state.update();
+                let now = std::time::Instant::now();
+                let dt = now - last_render_time;
+                last_render_time = now;
+                state.update(dt);
                 match state.render() {
                     Ok(_) => {}
                     // Recreate the swap_chain if lost

+ 1 - 1
src/gfx/mod.rs

@@ -1,3 +1,3 @@
+pub mod camera;
 pub mod model;
 pub mod texture;
-

+ 1 - 1
src/gfx/texture.rs

@@ -83,7 +83,7 @@ impl Texture {
         label: Option<&str>,
     ) -> Result<Self> {
         let dimensions = img.dimensions();
-        let rgba = img.to_rgba();
+        let rgba = img.to_rgba8();
 
         let size = wgpu::Extent3d {
             width: dimensions.0,

+ 0 - 1
src/gui/mod.rs

@@ -1,2 +1 @@
 pub mod texture;
-

+ 0 - 1
src/gui/texture.rs

@@ -75,4 +75,3 @@ impl Texture {
         })
     }
 }
-

+ 4 - 4
src/net/acceptor.rs

@@ -38,18 +38,18 @@ impl Acceptor {
 
         Ok(())
     }
-    
+
     /// Stop accepting inbound socket connections.
     pub async fn stop(&self) {
         // Send stop signal
         self.task.stop().await;
     }
-    
+
     /// Start receiving network messages.
     pub async fn subscribe(self: Arc<Self>) -> Subscription<NetResult<ChannelPtr>> {
         self.channel_subscriber.clone().subscribe().await
     }
-    
+
     /// Start listening on a local socket address.
     fn setup(accept_addr: SocketAddr) -> NetResult<Async<TcpListener>> {
         let listener = match Async::<TcpListener>::bind(accept_addr) {
@@ -100,7 +100,7 @@ impl Acceptor {
             }
         }
     }
-    
+
     /// Single attempt to accept an incoming connection. Stops after one attempt.
     async fn tick_accept(&self, listener: &Async<TcpListener>) -> NetResult<ChannelPtr> {
         let (stream, peer_addr) = match listener.accept().await {

+ 12 - 13
src/net/channel.rs

@@ -31,10 +31,7 @@ pub struct Channel {
 
 impl Channel {
     /// Create a new channel.
-    pub async fn new(
-        stream: Async<TcpStream>,
-        address: SocketAddr,
-    ) -> Arc<Self> {
+    pub async fn new(stream: Async<TcpStream>, address: SocketAddr) -> Arc<Self> {
         let (reader, writer) = stream.split();
         let reader = Mutex::new(reader);
         let writer = Mutex::new(writer);
@@ -52,7 +49,7 @@ impl Channel {
             stopped: AtomicBool::new(false),
         })
     }
-    
+
     /// Start the channel.
     pub fn start(self: Arc<Self>, executor: Arc<Executor<'_>>) {
         debug!(target: "net", "Channel::start() [START, address={}]", self.address());
@@ -66,7 +63,7 @@ impl Channel {
         );
         debug!(target: "net", "Channel::start() [END, address={}]", self.address());
     }
-    
+
     /// Stop the channel.
     pub async fn stop(&self) {
         debug!(target: "net", "Channel::stop() [START, address={}]", self.address());
@@ -74,7 +71,9 @@ impl Channel {
         self.stopped.store(false, Ordering::Relaxed);
         self.stop_subscriber.notify(NetError::ChannelStopped).await;
         self.receive_task.stop().await;
-        self.message_subsystem.trigger_error(NetError::ChannelStopped).await;
+        self.message_subsystem
+            .trigger_error(NetError::ChannelStopped)
+            .await;
         debug!(target: "net", "Channel::stop() [END, address={}]", self.address());
     }
 
@@ -93,8 +92,8 @@ impl Channel {
         );
         sub
     }
-    
-    /// Send a message across a channel. 
+
+    /// Send a message across a channel.
     pub async fn send<M: messages::Message>(&self, message: M) -> NetResult<()> {
         debug!(target: "net",
             "Channel::send() [START, command={:?}, address={}]",
@@ -121,7 +120,7 @@ impl Channel {
         );
         result
     }
-    
+
     /// Implements send message functionality.
     async fn send_message<M: messages::Message>(&self, message: M) -> error::Result<()> {
         let mut payload = Vec::new();
@@ -150,12 +149,12 @@ impl Channel {
         );
         sub
     }
-    
+
     /// Return the local socket address.
     pub fn address(&self) -> SocketAddr {
         self.address
     }
-    
+
     /// End of file error. Triggered when unexpected end of file occurs.
     fn is_eof_error(err: &error::Error) -> bool {
         match err {
@@ -185,7 +184,7 @@ impl Channel {
             .add_dispatch::<messages::AddrsMessage>()
             .await;
     }
-    
+
     pub fn get_message_subsystem(&self) -> &MessageSubsystem {
         &self.message_subsystem
     }

+ 1 - 1
src/net/connector.rs

@@ -16,7 +16,7 @@ impl Connector {
     pub fn new(settings: SettingsPtr) -> Self {
         Self { settings }
     }
-    
+
     /// Establish an outbound connection.
     pub async fn connect(&self, hostaddr: SocketAddr) -> NetResult<ChannelPtr> {
         futures::select! {

+ 8 - 4
src/net/hosts.rs

@@ -1,8 +1,8 @@
 use async_std::sync::Mutex;
 use rand::seq::SliceRandom;
+use std::collections::HashSet;
 use std::net::SocketAddr;
 use std::sync::Arc;
-use std::collections::HashSet;
 
 /// Pointer to hosts class.
 pub type HostsPtr = Arc<Hosts>;
@@ -19,11 +19,15 @@ impl Hosts {
             addrs: Mutex::new(Vec::new()),
         })
     }
-    
+
     /// Checks if a host address is in the host list.
     async fn contains(&self, addrs: &Vec<SocketAddr>) -> bool {
         let a_set: HashSet<_> = addrs.iter().copied().collect();
-        self.addrs.lock().await.iter().any(|item| a_set.contains(item))
+        self.addrs
+            .lock()
+            .await
+            .iter()
+            .any(|item| a_set.contains(item))
     }
 
     /// Add a new host to the host list.
@@ -32,7 +36,7 @@ impl Hosts {
             self.addrs.lock().await.extend(addrs)
         }
     }
-    
+
     /// Return a single host address.
     pub async fn load_single(&self) -> Option<SocketAddr> {
         self.addrs

+ 6 - 7
src/net/message_subscriber.rs

@@ -18,7 +18,7 @@ pub type MessageSubscriptionID = u64;
 type MessageResult<M> = NetResult<Arc<M>>;
 
 /// Handles message subscriptions through a subscription ID and a receiver channel.
-/// Inherits from Message Dispatcher. 
+/// Inherits from Message Dispatcher.
 pub struct MessageSubscription<M: Message> {
     id: MessageSubscriptionID,
     recv_queue: async_channel::Receiver<MessageResult<M>>,
@@ -43,7 +43,7 @@ impl<M: Message> MessageSubscription<M> {
 }
 
 #[async_trait]
-/// Generic interface for message dispatcher. 
+/// Generic interface for message dispatcher.
 trait MessageDispatcherInterface: Send + Sync {
     async fn trigger(&self, payload: Vec<u8>);
 
@@ -88,7 +88,7 @@ impl<M: Message> MessageDispatcher<M> {
     async fn unsubscribe(&self, sub_id: MessageSubscriptionID) {
         self.subs.lock().await.remove(&sub_id);
     }
-    
+
     /// Send a message to all subscriber channels. Automatically clear inactive channels.
     async fn trigger_all(&self, message: MessageResult<M>) {
         debug!(
@@ -119,7 +119,7 @@ impl<M: Message> MessageDispatcher<M> {
             self.subs.lock().await.len()
         );
     }
-    
+
     /// Remove inactive channels.
     async fn collect_garbage(&self, ids: Vec<MessageSubscriptionID>) {
         let mut subs = self.subs.lock().await;
@@ -147,7 +147,7 @@ impl<M: Message> MessageDispatcherInterface for MessageDispatcher<M> {
             }
         }
     }
-    
+
     /// Sends a message to all subscriber channels. Clears any inactive channels.
     async fn trigger_error(&self, err: NetError) {
         self.trigger_all(Err(err)).await;
@@ -161,7 +161,7 @@ impl<M: Message> MessageDispatcherInterface for MessageDispatcher<M> {
 
 /// Generic publish/subscribe class that can dispatch any kind of message
 /// to a subscribed list of dispatchers. Dispatchers subscribe to a single message format of any
-/// type. This is a generalized version of the pub/sub model in system::Subscriber. 
+/// type. This is a generalized version of the pub/sub model in system::Subscriber.
 pub struct MessageSubsystem {
     dispatchers: Mutex<HashMap<&'static str, Arc<dyn MessageDispatcherInterface>>>,
 }
@@ -304,4 +304,3 @@ mod tests {
         smol::block_on(_do_message_subscriber_test());
     }
 }
-

+ 1 - 1
src/net/messages.rs

@@ -23,7 +23,7 @@ pub struct PongMessage {
     pub nonce: u32,
 }
 
-/// Requests address of outbound connection. 
+/// Requests address of outbound connection.
 pub struct GetAddrsMessage {}
 
 /// Sends address information to inbound connection. Response to GetAddrs message.

+ 1 - 1
src/net/mod.rs

@@ -2,8 +2,8 @@ pub mod acceptor;
 pub mod channel;
 pub mod connector;
 pub mod error;
-pub mod message_subscriber;
 pub mod hosts;
+pub mod message_subscriber;
 pub mod messages;
 pub mod p2p;
 pub mod protocols;

+ 1 - 1
src/net/p2p.rs

@@ -6,9 +6,9 @@ use std::net::SocketAddr;
 use std::sync::Arc;
 
 use crate::net::error::{NetError, NetResult};
+use crate::net::messages::Message;
 use crate::net::sessions::{InboundSession, OutboundSession, SeedSession};
 use crate::net::{Channel, ChannelPtr, Hosts, HostsPtr, Settings, SettingsPtr};
-use crate::net::messages::Message;
 use crate::system::{Subscriber, SubscriberPtr, Subscription};
 
 /// List of channels that are awaiting connection.

+ 0 - 1
src/net/settings.rs

@@ -35,4 +35,3 @@ impl Default for Settings {
         }
     }
 }
-

+ 7 - 3
src/old/mimc.rs

@@ -109,7 +109,7 @@ impl<'a, Scalar: PrimeField> Circuit<Scalar> for MiMCDemo<'a, Scalar> {
                 e.add_assign(&self.constants[i]);
                 e.square()
             });
-            
+
             // println!("tmp_value {:?} {:?}", self.constants[i], tmp_value);
 
             let tmp = cs.alloc(
@@ -222,8 +222,12 @@ fn main() {
         // Generate a random preimage and compute the image
         // let xl = Scalar::random(&mut OsRng);
         // let xr = Scalar::random(&mut OsRng);
-        let xl = bls12_381::Scalar::from_string("15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e");
-        let xr = bls12_381::Scalar::from_string("015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891");
+        let xl = bls12_381::Scalar::from_string(
+            "15a36d1f0f390d8852a35a8c1908dd87a361ee3fd48fdf77b9819dc82d90607e",
+        );
+        let xr = bls12_381::Scalar::from_string(
+            "015d8c7f5b43fe33f7891142c001d9251f3abeeb98fad3e87b0dc53c4ebf1891",
+        );
         let image = mimc(xl, xr, &constants);
 
         proof_vec.truncate(0);