libpolymesh/common/serialization/data/
mesh.rs

1use super::super::super::{
2    transform::{
3        PolyVector,
4        PolyColor
5    },
6    TransPolyMeshPtr
7};
8use serde::{Deserialize, Serialize};
9use serde_json::Result;
10use std::fs;
11
12/// Definition of a mesh, and its geometry
13#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
14pub struct MeshDef {
15
16    /// Color of the mesh
17    pub color: PolyColor,
18
19    /// Triangle geometry
20    pub triangles: Option<Vec<[PolyVector;3]>>
21
22}
23
24impl MeshDef {
25
26    /// Read a MeshDef from a file
27    pub fn from_file(file_path: &str) -> Result<MeshDef> {
28        // Read the file
29        let file_contents = fs::read_to_string(file_path).unwrap();
30        let mesh_def: MeshDef = serde_json::from_str(&file_contents.to_string()).unwrap();
31
32        Ok(mesh_def)
33    }
34
35    /// Check if this mesh can be culled by another mesh
36    pub fn culled_by(&self, other: &MeshDef) -> bool {
37
38        if self.triangles.is_some() && other.triangles.is_some() {
39            return self.triangles.as_ref() == other.triangles.as_ref();
40        }
41
42        return false;
43
44    }
45
46    /// Copy this mesh to be absolutely transformed by its parent (used in rendering mostly)
47    pub fn transformed_by(&self, parent: &TransPolyMeshPtr) -> Self {
48
49        // Handle triangles
50        let mut triangles = None;
51        if self.triangles.is_some() {
52
53            // Build new triangle list
54            let mut tmp_triangles: Vec<[PolyVector;3]> = Vec::new();
55
56            for triangle in self.triangles.as_ref().unwrap() {
57                
58                // Build new point list
59                let mut vecs = [PolyVector { x:0.0, y:0.0, z:0.0 }; 3];
60
61                // Add transformed points
62                for i in 0..3 {
63                    if parent.translation.is_some() {
64                        vecs[i] = triangle[i] + *parent.translation.as_ref().unwrap();
65                    } else {
66                        vecs[i] = triangle[i];
67                    }
68                }
69
70                tmp_triangles.push(vecs);
71            }
72
73            triangles = Some(tmp_triangles);
74        }
75
76        Self {
77            triangles, 
78            color: self.color,
79            // emission: self.emission,
80            // albedo: self.albedo
81        }
82
83    }
84
85}