From 076118edaa43716cb9b81d57cf13e23a2305dc16 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 18 Mar 2020 13:03:12 +0100 Subject: [PATCH] library: core: camera: add deserialization --- src/core/camera.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/src/core/camera.rs b/src/core/camera.rs index 264bc80..69a1011 100644 --- a/src/core/camera.rs +++ b/src/core/camera.rs @@ -1,5 +1,6 @@ use super::film::Film; use crate::{Point, Vector}; +use serde::{Deserialize, Deserializer}; /// Represent an abstract camera to observe the scene. #[derive(Debug, PartialEq)] @@ -19,7 +20,7 @@ impl Camera { dist_to_image: f32, x: u32, y: u32, - ) -> Camera { + ) -> Self { let right = forward.cross(&up); let center = origin + forward.normalize() * dist_to_image; let screen_size = 2. * f32::tan(fov / 2.) * dist_to_image; @@ -36,6 +37,41 @@ impl Camera { } } +#[derive(Debug, Deserialize)] +struct SerializedCamera { + origin: Point, + forward: Vector, + up: Vector, + fov: f32, + distance_to_image: f32, + x: u32, + y: u32, +} + +impl From for Camera { + fn from(cam: SerializedCamera) -> Self { + Camera::new( + cam.origin, + cam.forward, + cam.up, + std::f32::consts::PI * cam.fov / 180., + cam.distance_to_image, + cam.x, + cam.y, + ) + } +} + +impl<'de> Deserialize<'de> for Camera { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let cam: SerializedCamera = Deserialize::deserialize(deserializer)?; + Ok(cam.into()) + } +} + #[cfg(test)] mod test { use super::*; @@ -66,4 +102,32 @@ mod test { } ) } + + #[test] + fn deserialization_works() { + let yaml = r#" + origin: [-1.0, 0.0, 0.0] + forward: [ 1.0, 0.0, 0.0] + up: [0.0, 1.0, 0.0] + fov: 90.0 + distance_to_image: 1.0 + x: 1080 + y: 1080 + "#; + let cam: Camera = serde_yaml::from_str(yaml).unwrap(); + assert_eq!( + cam, + Camera { + origin: Point::new(-1., 0., 0.), + film: Film::new( + 1080, + 1080, + 2., + Point::origin(), + Vector::new(0., 1., 0.), + Vector::new(0., 0., 1.), + ) + } + ) + } }