use std::fs::*;
use std::io::{BufRead, BufReader};
use crate::Vec3;
#[derive(Debug, Clone, Default)]
pub struct MtlData {
pub name: String,
pub ka: Vec3,
pub kd: Vec3,
pub ks: Vec3,
pub ns: f32,
pub ni: f32,
pub d: f32,
pub illum: u64,
pub map_kd: String,
}
impl MtlData {
pub fn from_disk_file(path: &str) -> Vec<Self> {
let file = match File::open(path) {
Ok(file) => file,
Err(_) => {
eprintln!("path {} not found for mtl lib", path);
return Vec::new();
}
};
let reader = BufReader::new(file);
let mut material_list = Vec::new();
let mut res = Self::default();
for line in reader.lines() {
let line_str = line.unwrap();
let line_str = line_str.trim();
let tokens = line_str.split_whitespace().collect::<Vec<&str>>();
if tokens.is_empty() {
continue;
}
match tokens[0] {
"newmtl" => {
material_list.push(res);
res = Self::default();
assert!(
res.name.is_empty(),
"Found duplicate name in mtl file, this is malformed."
);
res.name = tokens[1].to_string()
}
"Ka" => {
res.ka = Vec3::new(
tokens[1].parse::<f32>().unwrap(),
tokens[2].parse::<f32>().unwrap(),
tokens[3].parse::<f32>().unwrap(),
);
}
"Kd" => {
res.kd = Vec3::new(
tokens[1].parse::<f32>().unwrap(),
tokens[2].parse::<f32>().unwrap(),
tokens[3].parse::<f32>().unwrap(),
);
}
"Ks" => {
res.ks = Vec3::new(
tokens[1].parse::<f32>().unwrap(),
tokens[2].parse::<f32>().unwrap(),
tokens[3].parse::<f32>().unwrap(),
);
}
"Ns" => {
res.ns = tokens[1].parse::<f32>().unwrap();
}
"Ni" => {
res.ni = tokens[1].parse::<f32>().unwrap();
}
"d" => {
res.d = tokens[1].parse::<f32>().unwrap();
}
"illum" => {
res.illum = tokens[1].parse::<u64>().unwrap();
}
"map_Kd" => {
res.map_kd = tokens[1].to_string();
}
_ => {
continue;
}
}
}
material_list.push(res);
material_list.remove(0);
material_list
}
}