ray_tracing_utility/serialization/texture/
bitmap_file.rs

1use crate::image;
2use crate::serialization::IdConstructor;
3use ray_tracing_core::texture;
4use serde::{Deserialize, Serialize};
5use std::error::Error;
6use std::path::Path;
7
8#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
9pub struct BitmapFile {
10    pub id: IdConstructor,
11    pub filename: String,
12}
13
14impl BitmapFile {
15    pub fn file_to_texture(filename: &String) -> Result<texture::BitmapTexture, Box<dyn Error>> {
16        let (nx, ny, pixel_data) = match image::load_image(&filename) {
17            Ok((nx, ny, pixel_data)) => (nx, ny, pixel_data),
18            Err(e) => {
19                eprintln!("error reading file: {}", filename);
20                return Err(e);
21            }
22        };
23        Ok(texture::BitmapTexture::new(nx, ny, pixel_data))
24    }
25
26    pub fn to_texture(
27        &self,
28        index: usize,
29        root_path: &Option<String>,
30    ) -> Result<texture::BitmapTexture, Box<dyn Error>> {
31        let filename = match root_path {
32            Some(root_path) => {
33                let path = Path::new(&self.filename);
34                if !path.is_absolute() {
35                    String::from(Path::new(&root_path).join(path).to_str().unwrap())
36                } else {
37                    self.filename.clone()
38                }
39            }
40            None => self.filename.clone(),
41        };
42        let (nx, ny, pixel_data) = match image::load_image(&filename) {
43            Ok((nx, ny, pixel_data)) => (nx, ny, pixel_data),
44            Err(e) => {
45                eprintln!("error reading file: {}", filename);
46                return Err(e);
47            }
48        };
49        Ok(texture::BitmapTexture::new_id(
50            self.id.get_id(index),
51            nx,
52            ny,
53            pixel_data,
54        ))
55    }
56}
57
58#[cfg(test)]
59mod bitmap_file_test {
60    use super::*;
61
62    #[test]
63    fn bitmap_file_to_texture() {
64        let bt = BitmapFile {
65            id: IdConstructor::Single(2),
66            filename: "../resource/texture/physical-free-world-map-b1.jpg".to_string(),
67        };
68        let t = match bt.to_texture(0, &None) {
69            Ok(t) => t,
70            Err(e) => panic!("read file error {}", e),
71        };
72        assert_eq!(t.nx, 1000);
73        assert_eq!(t.ny, 500);
74        assert_eq!(t.data.len(), t.nx * t.ny * 4);
75    }
76}