use crate::gldf::GldfProduct;
use crate::ral;
use l3d_rs::l3d::L3dFile;
use l3d_rs::mtl;
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SyncOutcome {
Updated { file_id: String, mtl_path: String },
Synthesized { file_id: String, mtl_path: String },
NoModelGeometry,
NoRalAvailable,
UnknownRal { ral: i32 },
NoModelGeometryBytes,
NoSuchVariant,
}
#[derive(Debug)]
pub enum SyncError {
L3dParseFailed(std::io::Error),
MtlParseFailed(mtl::MtlParseError),
L3dWriteFailed(std::io::Error),
}
impl std::fmt::Display for SyncError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::L3dParseFailed(e) => write!(f, "L3D archive is not a valid ZIP: {}", e),
Self::MtlParseFailed(e) => write!(f, "embedded MTL failed to parse: {}", e),
Self::L3dWriteFailed(e) => write!(f, "failed to repack L3D archive: {}", e),
}
}
}
impl std::error::Error for SyncError {}
pub fn sync_l3d_mtl_for_housing_color(
embedded_files: &mut HashMap<String, Vec<u8>>,
product: &GldfProduct,
variant_idx: usize,
) -> Result<SyncOutcome, SyncError> {
let variant = match product
.product_definitions
.variants
.as_ref()
.and_then(|vs| vs.variant.get(variant_idx))
{
Some(v) => v,
None => return Ok(SyncOutcome::NoSuchVariant),
};
let ral = match variant
.descriptive_attributes
.as_ref()
.and_then(|a| a.marketing.as_ref())
.and_then(|m| m.housing_colors.as_ref())
.and_then(|hc| hc.housing_color.first())
.and_then(|h| h.ral)
{
Some(r) => r,
None => return Ok(SyncOutcome::NoRalAvailable),
};
let entry = match ral::by_number(ral) {
Some(e) => e,
None => return Ok(SyncOutcome::UnknownRal { ral }),
};
let rgb = entry.rgb_f32();
let geometry_id = match variant
.geometry
.as_ref()
.and_then(|g| g.model_geometry_reference.as_ref())
.map(|m| m.geometry_id.clone())
{
Some(id) => id,
None => return Ok(SyncOutcome::NoModelGeometry),
};
let file_id = match product
.general_definitions
.geometries
.as_ref()
.and_then(|gs| gs.model_geometry.iter().find(|g| g.id == geometry_id))
.and_then(|g| g.geometry_file_reference.first())
.map(|fr| fr.file_id.clone())
{
Some(id) => id,
None => return Ok(SyncOutcome::NoModelGeometryBytes),
};
let l3d_bytes = match embedded_files.get(&file_id) {
Some(b) => b.clone(),
None => return Ok(SyncOutcome::NoModelGeometryBytes),
};
let mut l3d_file = parse_l3d(&l3d_bytes)?;
let mtl_paths: Vec<String> = l3d_file.mtl_paths().into_iter().map(String::from).collect();
let outcome = if mtl_paths.is_empty() {
let default_mat = mtl::Material::flat_color("housing", rgb);
let synthesized = l3d_file
.ensure_mtl(default_mat)
.map_err(SyncError::L3dWriteFailed)?;
debug_assert!(synthesized, "ensure_mtl should report synthesis");
let mtl_path = l3d_file
.mtl_paths()
.first()
.map(|s| s.to_string())
.unwrap_or_else(|| "default.mtl".to_string());
SyncOutcome::Synthesized {
file_id: file_id.clone(),
mtl_path,
}
} else {
let primary_path = mtl_paths[0].clone();
for path in &mtl_paths {
let mut mtl = l3d_file
.mtl(path)
.expect("mtl_paths returned a path that asset() can't find")
.map_err(SyncError::MtlParseFailed)?;
for m in mtl.materials.iter_mut() {
m.kd = Some(rgb);
}
l3d_file.replace_mtl(path, &mtl);
}
SyncOutcome::Updated {
file_id: file_id.clone(),
mtl_path: primary_path,
}
};
let new_bytes = l3d_file.to_buffer().map_err(SyncError::L3dWriteFailed)?;
embedded_files.insert(file_id, new_bytes);
Ok(outcome)
}
fn parse_l3d(bytes: &[u8]) -> Result<L3dFile, SyncError> {
let cursor = std::io::Cursor::new(bytes);
let mut zip = zip::ZipArchive::new(cursor).map_err(|e| {
SyncError::L3dParseFailed(std::io::Error::new(std::io::ErrorKind::InvalidData, e))
})?;
let mut file = L3dFile::default();
use std::io::Read;
for i in 0..zip.len() {
let mut entry = zip.by_index(i).map_err(|e| {
SyncError::L3dParseFailed(std::io::Error::new(std::io::ErrorKind::InvalidData, e))
})?;
if !entry.is_file() {
continue;
}
let mut buf = Vec::new();
entry
.read_to_end(&mut buf)
.map_err(SyncError::L3dParseFailed)?;
let name = entry.name().to_string();
if name == "structure.xml" {
file.structure = String::from_utf8_lossy(&buf).into_owned();
} else {
let size = buf.len() as u64;
file.assets.push(l3d_rs::l3d::BufFile {
name,
content: buf,
size,
});
}
}
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gldf::general_definitions::geometries::{GeometryFileReference, ModelGeometry};
use crate::gldf::general_definitions::Files;
use crate::gldf::product_definitions::DescriptiveAttributes;
use crate::gldf::product_definitions::{
Geometry, HousingColor, HousingColors, Marketing, ModelGeometryReference,
ProductDefinitions, Variant, Variants,
};
fn make_minimal_l3d_no_mtl() -> Vec<u8> {
let file = L3dFile {
structure: "<Structure/>".to_string(),
assets: vec![l3d_rs::l3d::BufFile {
name: "geom/luminaire.obj".to_string(),
content: b"v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec(),
size: 32,
}],
};
file.to_buffer().unwrap()
}
fn make_minimal_l3d_with_mtl() -> Vec<u8> {
let file = L3dFile {
structure: "<Structure/>".to_string(),
assets: vec![
l3d_rs::l3d::BufFile {
name: "geom/luminaire.obj".to_string(),
content: b"mtllib luminaire.mtl\nusemtl housing\nv 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n".to_vec(),
size: 0,
},
l3d_rs::l3d::BufFile {
name: "geom/luminaire.mtl".to_string(),
content: b"newmtl housing\nKa 0.1 0.1 0.1\nKd 0.5 0.5 0.5\nKs 0.2 0.2 0.2\nNs 100\nd 1\nillum 2\n".to_vec(),
size: 0,
},
],
};
file.to_buffer().unwrap()
}
fn make_product(housing_ral: Option<i32>) -> GldfProduct {
use crate::gldf::general_definitions::files::File as GldfFile;
use crate::gldf::general_definitions::Geometries;
use crate::gldf::LocaleFoo;
let mut p = GldfProduct::default();
p.general_definitions.files = Files {
file: vec![GldfFile {
id: "l3d-1".to_string(),
content_type: "geo/l3d".to_string(),
type_attr: "localFileName".to_string(),
language: String::new(),
file_name: "luminaire.l3d".to_string(),
}],
};
p.general_definitions.geometries = Some(Geometries {
simple_geometry: vec![],
model_geometry: vec![ModelGeometry {
id: "geom-1".to_string(),
geometry_file_reference: vec![GeometryFileReference {
file_id: "l3d-1".to_string(),
level_of_detail: None,
}],
}],
});
p.product_definitions = ProductDefinitions {
variants: Some(Variants {
variant: vec![Variant {
id: "v1".to_string(),
geometry: Some(Geometry {
emitter_reference: vec![],
simple_geometry_reference: None,
model_geometry_reference: Some(ModelGeometryReference {
geometry_id: "geom-1".to_string(),
..Default::default()
}),
}),
descriptive_attributes: Some(DescriptiveAttributes {
marketing: Some(Marketing {
housing_colors: Some(HousingColors {
housing_color: vec![HousingColor {
ral: housing_ral,
locale: LocaleFoo::default(),
}],
}),
..Default::default()
}),
..Default::default()
}),
..Default::default()
}],
}),
..Default::default()
};
p
}
#[test]
fn updates_existing_mtl_with_ral_rgb() {
let product = make_product(Some(3020)); let mut embedded = HashMap::new();
embedded.insert("l3d-1".to_string(), make_minimal_l3d_with_mtl());
let outcome = sync_l3d_mtl_for_housing_color(&mut embedded, &product, 0).unwrap();
match outcome {
SyncOutcome::Updated { file_id, .. } => assert_eq!(file_id, "l3d-1"),
other => panic!("expected Updated, got {:?}", other),
}
let new_bytes = embedded.get("l3d-1").unwrap().clone();
let file = parse_l3d(&new_bytes).unwrap();
let mtl = file.mtl("geom/luminaire.mtl").unwrap().unwrap();
let housing = mtl.find("housing").unwrap();
let kd = housing.kd.unwrap();
let expected = ral::by_number(3020).unwrap().rgb_f32();
for i in 0..3 {
assert!(
(kd[i] - expected[i]).abs() < 1e-3,
"channel {} mismatch: kd={:?}, expected={:?}",
i,
kd,
expected
);
}
}
#[test]
fn synthesizes_mtl_when_none_present() {
let product = make_product(Some(9007)); let mut embedded = HashMap::new();
embedded.insert("l3d-1".to_string(), make_minimal_l3d_no_mtl());
let outcome = sync_l3d_mtl_for_housing_color(&mut embedded, &product, 0).unwrap();
match outcome {
SyncOutcome::Synthesized { file_id, mtl_path } => {
assert_eq!(file_id, "l3d-1");
assert_eq!(mtl_path, "geom/default.mtl");
}
other => panic!("expected Synthesized, got {:?}", other),
}
let new_bytes = embedded.get("l3d-1").unwrap().clone();
let file = parse_l3d(&new_bytes).unwrap();
assert!(file.mtl_paths().contains(&"geom/default.mtl"));
let mtl = file.mtl("geom/default.mtl").unwrap().unwrap();
let housing = mtl.find("housing").unwrap();
let expected = ral::by_number(9007).unwrap().rgb_f32();
let kd = housing.kd.unwrap();
for i in 0..3 {
assert!((kd[i] - expected[i]).abs() < 1e-3);
}
}
#[test]
fn no_housing_color_ral_is_silent_noop() {
let product = make_product(None);
let mut embedded = HashMap::new();
let original = make_minimal_l3d_with_mtl();
embedded.insert("l3d-1".to_string(), original.clone());
let outcome = sync_l3d_mtl_for_housing_color(&mut embedded, &product, 0).unwrap();
assert!(matches!(outcome, SyncOutcome::NoRalAvailable));
assert_eq!(embedded.get("l3d-1").unwrap(), &original);
}
#[test]
fn unknown_ral_is_silent_noop() {
let product = make_product(Some(1234)); let mut embedded = HashMap::new();
let original = make_minimal_l3d_with_mtl();
embedded.insert("l3d-1".to_string(), original.clone());
let outcome = sync_l3d_mtl_for_housing_color(&mut embedded, &product, 0).unwrap();
assert!(matches!(outcome, SyncOutcome::UnknownRal { ral: 1234 }));
assert_eq!(embedded.get("l3d-1").unwrap(), &original);
}
#[test]
fn variant_without_model_geometry_is_silent_noop() {
let mut product = make_product(Some(3020));
if let Some(vs) = product.product_definitions.variants.as_mut() {
if let Some(v) = vs.variant.get_mut(0) {
if let Some(g) = v.geometry.as_mut() {
g.model_geometry_reference = None;
}
}
}
let mut embedded = HashMap::new();
let original = make_minimal_l3d_with_mtl();
embedded.insert("l3d-1".to_string(), original.clone());
let outcome = sync_l3d_mtl_for_housing_color(&mut embedded, &product, 0).unwrap();
assert!(matches!(outcome, SyncOutcome::NoModelGeometry));
assert_eq!(embedded.get("l3d-1").unwrap(), &original);
}
}