session_rust/
point.rs

1use crate::Color;
2use serde::{ser::Serialize as SerTrait, Deserialize, Serialize};
3use std::fmt;
4use uuid::Uuid;
5
6/// A 3D point with visual properties and JSON serialization support.
7#[derive(Debug, Clone, Serialize, Deserialize)]
8#[serde(tag = "type", rename = "Point")]
9pub struct Point {
10    pub guid: String,      // Unique identifier
11    pub name: String,      // Name of the point
12    pub x: f32,            // X coordinate
13    pub y: f32,            // Y coordinate
14    pub z: f32,            // Z coordinate
15    pub width: f32,        // Width of the point
16    pub pointcolor: Color, // Color of the point
17}
18
19impl Default for Point {
20    fn default() -> Self {
21        Self {
22            x: 0.0,
23            y: 0.0,
24            z: 0.0,
25            guid: Uuid::new_v4().to_string(),
26            name: "my_point".to_string(),
27            pointcolor: Color::white(),
28            width: 1.0,
29        }
30    }
31}
32
33impl Point {
34    /// Creates a new Point with specified coordinates.
35    pub fn new(x: f32, y: f32, z: f32) -> Self {
36        Self {
37            x,
38            y,
39            z,
40            ..Default::default()
41        }
42    }
43
44    ///////////////////////////////////////////////////////////////////////////////////////////
45    // JSON
46    ///////////////////////////////////////////////////////////////////////////////////////////
47
48    /// Serializes the Point to a JSON string.
49    pub fn to_json_data(&self) -> Result<String, Box<dyn std::error::Error>> {
50        let mut buf = Vec::new();
51        let formatter = serde_json::ser::PrettyFormatter::with_indent(b"    ");
52        let mut ser = serde_json::Serializer::with_formatter(&mut buf, formatter);
53        SerTrait::serialize(self, &mut ser)?;
54        Ok(String::from_utf8(buf)?)
55    }
56
57    /// Deserializes a Point from a JSON string.
58    pub fn from_json_data(json_data: &str) -> Result<Self, Box<dyn std::error::Error>> {
59        Ok(serde_json::from_str(json_data)?)
60    }
61
62    /// Serializes the Point to a JSON file.
63    pub fn to_json(&self, filepath: &str) -> Result<(), Box<dyn std::error::Error>> {
64        let json = self.to_json_data()?;
65        std::fs::write(filepath, json)?;
66        Ok(())
67    }
68
69    /// Deserializes a Point from a JSON file.
70    pub fn from_json(filepath: &str) -> Result<Self, Box<dyn std::error::Error>> {
71        let json = std::fs::read_to_string(filepath)?;
72        Self::from_json_data(&json)
73    }
74}
75
76impl fmt::Display for Point {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        write!(
79            f,
80            "Point({}, {}, {}, {}, {}, {}, {})",
81            self.x, self.y, self.z, self.guid, self.name, self.pointcolor, self.width
82        )
83    }
84}