1use crate::arrow::Arrow;
2use crate::boundingbox::BoundingBox;
3use crate::cylinder::Cylinder;
4use crate::line::Line;
5use crate::mesh::Mesh;
6use crate::plane::Plane;
7use crate::point::Point;
8use crate::pointcloud::PointCloud;
9use crate::polyline::Polyline;
10use serde::{ser::Serialize as SerTrait, Deserialize, Serialize};
11use std::fmt;
12use std::fs;
13use uuid::Uuid;
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
17#[serde(tag = "type", rename = "Objects")]
18pub struct Objects {
19 pub guid: String,
20 pub name: String,
21 pub points: Vec<Point>,
22 pub lines: Vec<Line>,
23 pub planes: Vec<Plane>,
24 pub bboxes: Vec<BoundingBox>,
25 pub polylines: Vec<Polyline>,
26 pub pointclouds: Vec<PointCloud>,
27 pub meshes: Vec<Mesh>,
28 pub cylinders: Vec<Cylinder>,
29 pub arrows: Vec<Arrow>,
30}
31
32impl Default for Objects {
33 fn default() -> Self {
34 Self {
35 guid: Uuid::new_v4().to_string(),
36 name: "my_objects".to_string(),
37 points: Vec::new(),
38 lines: Vec::new(),
39 planes: Vec::new(),
40 bboxes: Vec::new(),
41 polylines: Vec::new(),
42 pointclouds: Vec::new(),
43 meshes: Vec::new(),
44 cylinders: Vec::new(),
45 arrows: Vec::new(),
46 }
47 }
48}
49
50impl Objects {
51 pub fn new() -> Self {
52 Self {
53 name: "my_objects".to_string(),
54 ..Default::default()
55 }
56 }
57
58 pub fn jsondump(&self) -> Result<String, Box<dyn std::error::Error>> {
64 let mut buf = Vec::new();
65 let formatter = serde_json::ser::PrettyFormatter::with_indent(b" ");
66 let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
67 SerTrait::serialize(self, &mut ser)?;
68 Ok(String::from_utf8(buf)?)
69 }
70
71 pub fn jsonload(json_data: &str) -> Result<Self, Box<dyn std::error::Error>> {
73 Ok(serde_json::from_str(json_data)?)
74 }
75
76 pub fn to_json(&self, filepath: &str) -> Result<(), Box<dyn std::error::Error>> {
78 let json = self.jsondump()?;
79 fs::write(filepath, json)?;
80 Ok(())
81 }
82
83 pub fn from_json(filepath: &str) -> Result<Self, Box<dyn std::error::Error>> {
85 let json = fs::read_to_string(filepath)?;
86 Self::jsonload(&json)
87 }
88}
89
90impl fmt::Display for Objects {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 write!(
93 f,
94 "Objects({}, {}, points={})",
95 self.name,
96 self.guid,
97 self.points.len()
98 )
99 }
100}
101
102#[cfg(test)]
103#[path = "objects_test.rs"]
104mod objects_test;