acadrust 0.3.4

A pure Rust library for reading and writing CAD files in DXF format (ASCII and Binary) and DWG format (Binary).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Tolerance (Feature Control Frame) entity implementation.
//!
//! The Tolerance entity represents a geometric dimensioning and tolerancing
//! (GD&T) feature control frame annotation.

use crate::entities::{Entity, EntityCommon};
use crate::types::{BoundingBox3D, Color, Handle, LineWeight, Transparency, Vector3};

// ============================================================================
// Tolerance Entity
// ============================================================================

/// Tolerance entity (Feature Control Frame).
///
/// Represents a geometric dimensioning and tolerancing (GD&T) feature
/// control frame annotation used in technical drawings.
///
/// # DXF Information
/// - Entity type: TOLERANCE
/// - Subclass marker: AcDbFcf
/// - Object type code: 0x2E (46)
///
/// # Text Format
///
/// The tolerance text uses a special format for GDT symbols:
/// - `{\Fgdt;X}` - Font switch to GDT font with symbol X
///   - `j` - Perpendicularity
///   - `n` - Angularity
///   - `s` - Symmetry
///   - `p` - Position
/// - `%%v` - Special character/separator
/// - `^J` - Line separator (newline within frame)
///
/// # Example
///
/// ```ignore
/// use acadrust::entities::Tolerance;
/// use acadrust::types::Vector3;
///
/// let mut tol = Tolerance::new();
/// tol.insertion_point = Vector3::new(10.0, 10.0, 0.0);
/// tol.text = "{\\Fgdt;p}%%v0.5%%v%%v%%v%%v".to_string();
/// tol.dimension_style_name = "Standard".to_string();
/// ```
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Tolerance {
    /// Common entity data.
    pub common: EntityCommon,

    /// Insertion point in WCS.
    /// DXF codes: 10, 20, 30
    pub insertion_point: Vector3,

    /// X-axis direction vector in WCS.
    /// DXF codes: 11, 21, 31
    pub direction: Vector3,

    /// Extrusion/normal vector.
    /// DXF codes: 210, 220, 230
    /// Default: (0, 0, 1)
    pub normal: Vector3,

    /// Tolerance text string (feature control frame content).
    /// DXF code: 1
    /// Uses special GDT font formatting.
    pub text: String,

    /// Dimension style name.
    /// DXF code: 3 (name reference)
    pub dimension_style_name: String,

    /// Dimension style handle (for DWG).
    pub dimension_style_handle: Option<Handle>,

    /// Text height (from dimension style or override).
    pub text_height: f64,

    /// Dimension gap (from dimension style).
    pub dimension_gap: f64,
}

impl Tolerance {
    /// Entity type name.
    pub const ENTITY_NAME: &'static str = "TOLERANCE";

    /// DXF subclass marker.
    pub const SUBCLASS_MARKER: &'static str = "AcDbFcf";

    /// Object type code (DWG).
    pub const OBJECT_TYPE: u16 = 0x2E; // 46

    /// Creates a new tolerance entity with default values.
    pub fn new() -> Self {
        Tolerance {
            common: EntityCommon::default(),
            insertion_point: Vector3::ZERO,
            direction: Vector3::UNIT_X,
            normal: Vector3::UNIT_Z,
            text: String::new(),
            dimension_style_name: "Standard".to_string(),
            dimension_style_handle: None,
            text_height: 0.18,
            dimension_gap: 0.09,
        }
    }

    /// Creates a tolerance with insertion point and text.
    pub fn with_text(insertion_point: Vector3, text: impl Into<String>) -> Self {
        Tolerance {
            insertion_point,
            text: text.into(),
            ..Self::new()
        }
    }

    /// Creates a tolerance with full parameters.
    pub fn new_full(
        insertion_point: Vector3,
        text: impl Into<String>,
        direction: Vector3,
        style: impl Into<String>,
    ) -> Self {
        Tolerance {
            insertion_point,
            text: text.into(),
            direction: direction.normalize(),
            dimension_style_name: style.into(),
            ..Self::new()
        }
    }

    /// Sets the direction to point toward the given location.
    pub fn point_toward(&mut self, target: Vector3) {
        let dir = target - self.insertion_point;
        if dir.length() > 1e-10 {
            self.direction = dir.normalize();
        }
    }

    /// Rotates the tolerance frame around its normal.
    pub fn rotate(&mut self, angle: f64) {
        let cos_a = angle.cos();
        let sin_a = angle.sin();
        let n = self.normal.normalize();

        // Rodrigues' rotation formula for direction vector
        let d = self.direction;
        let dot = n.x * d.x + n.y * d.y + n.z * d.z;
        let cross = Vector3::new(
            n.y * d.z - n.z * d.y,
            n.z * d.x - n.x * d.z,
            n.x * d.y - n.y * d.x,
        );

        self.direction = Vector3::new(
            d.x * cos_a + cross.x * sin_a + n.x * dot * (1.0 - cos_a),
            d.y * cos_a + cross.y * sin_a + n.y * dot * (1.0 - cos_a),
            d.z * cos_a + cross.z * sin_a + n.z * dot * (1.0 - cos_a),
        );
    }

    /// Returns the rotation angle around the normal (in radians).
    pub fn rotation_angle(&self) -> f64 {
        let n = self.normal.normalize();
        let d = self.direction.normalize();

        // Project direction onto the plane perpendicular to normal
        let dot = n.x * d.x + n.y * d.y + n.z * d.z;
        let projected = Vector3::new(d.x - n.x * dot, d.y - n.y * dot, d.z - n.z * dot);

        if projected.length() < 1e-10 {
            return 0.0;
        }

        // Calculate angle from X axis in the plane
        let x_axis = if (n.z.abs() - 1.0).abs() < 1e-10 {
            Vector3::UNIT_X
        } else {
            Vector3::new(-n.y, n.x, 0.0).normalize()
        };

        let y_axis = Vector3::new(
            n.y * x_axis.z - n.z * x_axis.y,
            n.z * x_axis.x - n.x * x_axis.z,
            n.x * x_axis.y - n.y * x_axis.x,
        );

        let px = projected.x * x_axis.x + projected.y * x_axis.y + projected.z * x_axis.z;
        let py = projected.x * y_axis.x + projected.y * y_axis.y + projected.z * y_axis.z;

        py.atan2(px)
    }

    /// Parses the tolerance text and returns the lines.
    pub fn text_lines(&self) -> Vec<&str> {
        self.text.split("^J").collect()
    }

    /// Returns the number of lines in the tolerance frame.
    pub fn line_count(&self) -> usize {
        self.text.matches("^J").count() + 1
    }

    /// Creates a simple position tolerance string.
    ///
    /// # Arguments
    /// * `tolerance` - The tolerance value (e.g., 0.5)
    /// * `datum_a` - Optional first datum reference
    /// * `datum_b` - Optional second datum reference
    /// * `datum_c` - Optional third datum reference
    pub fn position_tolerance(
        tolerance: f64,
        datum_a: Option<&str>,
        datum_b: Option<&str>,
        datum_c: Option<&str>,
    ) -> String {
        let mut text = format!("{{\\Fgdt;p}}%%v{}%%v", tolerance);

        if let Some(a) = datum_a {
            text.push_str(a);
        }
        text.push_str("%%v");

        if let Some(b) = datum_b {
            text.push_str(b);
        }
        text.push_str("%%v");

        if let Some(c) = datum_c {
            text.push_str(c);
        }
        text.push_str("%%v");

        text
    }

    /// Creates a flatness tolerance string.
    pub fn flatness_tolerance(tolerance: f64) -> String {
        format!("{{\\Fgdt;c}}%%v{}%%v%%v%%v%%v", tolerance)
    }

    /// Creates a perpendicularity tolerance string.
    pub fn perpendicularity_tolerance(tolerance: f64, datum: &str) -> String {
        format!("{{\\Fgdt;j}}%%v{}%%v{}%%v%%v%%v", tolerance, datum)
    }

    /// Creates a parallelism tolerance string.
    pub fn parallelism_tolerance(tolerance: f64, datum: &str) -> String {
        format!("{{\\Fgdt;h}}%%v{}%%v{}%%v%%v%%v", tolerance, datum)
    }

    /// Creates a concentricity tolerance string.
    pub fn concentricity_tolerance(tolerance: f64, datum: &str) -> String {
        format!("{{\\Fgdt;u}}%%v{}%%v{}%%v%%v%%v", tolerance, datum)
    }

    /// Creates a symmetry tolerance string.
    pub fn symmetry_tolerance(tolerance: f64, datum: &str) -> String {
        format!("{{\\Fgdt;i}}%%v{}%%v{}%%v%%v%%v", tolerance, datum)
    }

    /// Creates a runout tolerance string.
    pub fn runout_tolerance(tolerance: f64, datum: &str, total: bool) -> String {
        let symbol = if total { "t" } else { "r" };
        format!("{{\\Fgdt;{}}}%%v{}%%v{}%%v%%v%%v", symbol, tolerance, datum)
    }

    /// Creates a cylindricity tolerance string.
    pub fn cylindricity_tolerance(tolerance: f64) -> String {
        format!("{{\\Fgdt;e}}%%v{}%%v%%v%%v%%v", tolerance)
    }

    /// Creates a straightness tolerance string.
    pub fn straightness_tolerance(tolerance: f64) -> String {
        format!("{{\\Fgdt;a}}%%v{}%%v%%v%%v%%v", tolerance)
    }

    /// Creates a circularity/roundness tolerance string.
    pub fn circularity_tolerance(tolerance: f64) -> String {
        format!("{{\\Fgdt;g}}%%v{}%%v%%v%%v%%v", tolerance)
    }

    /// Creates a profile of a line tolerance string.
    pub fn line_profile_tolerance(tolerance: f64, datum: Option<&str>) -> String {
        let datum_str = datum.unwrap_or("");
        format!("{{\\Fgdt;k}}%%v{}%%v{}%%v%%v%%v", tolerance, datum_str)
    }

    /// Creates a profile of a surface tolerance string.
    pub fn surface_profile_tolerance(tolerance: f64, datum: Option<&str>) -> String {
        let datum_str = datum.unwrap_or("");
        format!("{{\\Fgdt;d}}%%v{}%%v{}%%v%%v%%v", tolerance, datum_str)
    }

    /// Creates a multi-line tolerance by joining lines with ^J.
    pub fn multi_line(lines: &[&str]) -> String {
        lines.join("^J")
    }
}

impl Default for Tolerance {
    fn default() -> Self {
        Self::new()
    }
}

impl Entity for Tolerance {
    fn handle(&self) -> Handle {
        self.common.handle
    }

    fn set_handle(&mut self, handle: Handle) {
        self.common.handle = handle;
    }

    fn layer(&self) -> &str {
        &self.common.layer
    }

    fn set_layer(&mut self, layer: String) {
        self.common.layer = layer;
    }

    fn color(&self) -> Color {
        self.common.color
    }

    fn set_color(&mut self, color: Color) {
        self.common.color = color;
    }

    fn line_weight(&self) -> LineWeight {
        self.common.line_weight
    }

    fn set_line_weight(&mut self, weight: LineWeight) {
        self.common.line_weight = weight;
    }

    fn transparency(&self) -> Transparency {
        self.common.transparency
    }

    fn set_transparency(&mut self, transparency: Transparency) {
        self.common.transparency = transparency;
    }

    fn is_invisible(&self) -> bool {
        self.common.invisible
    }

    fn set_invisible(&mut self, invisible: bool) {
        self.common.invisible = invisible;
    }

    fn bounding_box(&self) -> BoundingBox3D {
        // Approximate bounding box - would need font metrics for accuracy
        let half_width = self.text.len() as f64 * self.text_height * 0.6;
        let half_height = self.text_height * self.line_count() as f64;

        let min = Vector3::new(
            self.insertion_point.x - half_width * 0.1,
            self.insertion_point.y - half_height * 0.5,
            self.insertion_point.z,
        );
        let max = Vector3::new(
            self.insertion_point.x + half_width,
            self.insertion_point.y + half_height * 0.5,
            self.insertion_point.z,
        );

        BoundingBox3D::new(min, max)
    }

    fn translate(&mut self, offset: Vector3) {
        super::translate::translate_tolerance(self, offset);
    }

    fn entity_type(&self) -> &'static str {
        Self::ENTITY_NAME
    }
    
    fn apply_transform(&mut self, transform: &crate::types::Transform) {
        super::transform::transform_tolerance(self, transform);
    }
}

// ============================================================================
// GDT Symbol Constants
// ============================================================================

/// GDT (Geometric Dimensioning and Tolerancing) symbol codes.
///
/// These are used with the `{\Fgdt;X}` format in tolerance text.
pub mod gdt_symbols {
    /// Straightness symbol.
    pub const STRAIGHTNESS: char = 'a';
    /// Flatness symbol.
    pub const FLATNESS: char = 'c';
    /// Circularity/Roundness symbol.
    pub const CIRCULARITY: char = 'g';
    /// Cylindricity symbol.
    pub const CYLINDRICITY: char = 'e';
    /// Profile of a line symbol.
    pub const LINE_PROFILE: char = 'k';
    /// Profile of a surface symbol.
    pub const SURFACE_PROFILE: char = 'd';
    /// Parallelism symbol.
    pub const PARALLELISM: char = 'h';
    /// Perpendicularity symbol.
    pub const PERPENDICULARITY: char = 'j';
    /// Angularity symbol.
    pub const ANGULARITY: char = 'n';
    /// Position symbol.
    pub const POSITION: char = 'p';
    /// Concentricity symbol.
    pub const CONCENTRICITY: char = 'u';
    /// Symmetry symbol.
    pub const SYMMETRY: char = 'i';
    /// Circular runout symbol.
    pub const CIRCULAR_RUNOUT: char = 'r';
    /// Total runout symbol.
    pub const TOTAL_RUNOUT: char = 't';
    /// Diameter symbol.
    pub const DIAMETER: char = 'n';
    /// MMC (Maximum Material Condition) symbol.
    pub const MMC: char = 'm';
    /// LMC (Least Material Condition) symbol.
    pub const LMC: char = 'l';
    /// RFS (Regardless of Feature Size) symbol.
    pub const RFS: char = 's';
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tolerance_creation() {
        let tol = Tolerance::new();
        assert_eq!(tol.insertion_point, Vector3::ZERO);
        assert_eq!(tol.direction, Vector3::UNIT_X);
        assert_eq!(tol.normal, Vector3::UNIT_Z);
        assert!(tol.text.is_empty());
        assert_eq!(tol.dimension_style_name, "Standard");
    }

    #[test]
    fn test_tolerance_with_text() {
        let tol = Tolerance::with_text(Vector3::new(10.0, 20.0, 0.0), "test");
        assert_eq!(tol.insertion_point.x, 10.0);
        assert_eq!(tol.insertion_point.y, 20.0);
        assert_eq!(tol.text, "test");
    }

    #[test]
    fn test_tolerance_full() {
        let tol = Tolerance::new_full(
            Vector3::new(5.0, 5.0, 0.0),
            "tolerance text",
            Vector3::UNIT_Y,
            "DIMSTYLE1",
        );
        assert_eq!(tol.insertion_point.x, 5.0);
        assert_eq!(tol.text, "tolerance text");
        assert!((tol.direction.y - 1.0).abs() < 1e-10);
        assert_eq!(tol.dimension_style_name, "DIMSTYLE1");
    }

    #[test]
    fn test_tolerance_translate() {
        let mut tol = Tolerance::with_text(Vector3::new(0.0, 0.0, 0.0), "test");
        tol.translate(Vector3::new(5.0, 10.0, 0.0));
        assert_eq!(tol.insertion_point.x, 5.0);
        assert_eq!(tol.insertion_point.y, 10.0);
    }

    #[test]
    fn test_tolerance_entity_type() {
        let tol = Tolerance::new();
        assert_eq!(tol.entity_type(), "TOLERANCE");
    }

    #[test]
    fn test_position_tolerance() {
        let text = Tolerance::position_tolerance(0.5, Some("A"), Some("B"), None);
        assert!(text.contains("p"));
        assert!(text.contains("0.5"));
        assert!(text.contains("A"));
        assert!(text.contains("B"));
    }

    #[test]
    fn test_flatness_tolerance() {
        let text = Tolerance::flatness_tolerance(0.1);
        assert!(text.contains("c"));
        assert!(text.contains("0.1"));
    }

    #[test]
    fn test_perpendicularity_tolerance() {
        let text = Tolerance::perpendicularity_tolerance(0.05, "A");
        assert!(text.contains("j"));
        assert!(text.contains("0.05"));
        assert!(text.contains("A"));
    }

    #[test]
    fn test_multi_line() {
        let text = Tolerance::multi_line(&["line1", "line2", "line3"]);
        assert_eq!(text, "line1^Jline2^Jline3");
    }

    #[test]
    fn test_text_lines() {
        let mut tol = Tolerance::new();
        tol.text = "line1^Jline2^Jline3".to_string();
        let lines = tol.text_lines();
        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0], "line1");
        assert_eq!(lines[1], "line2");
        assert_eq!(lines[2], "line3");
    }

    #[test]
    fn test_line_count() {
        let mut tol = Tolerance::new();
        tol.text = "line1".to_string();
        assert_eq!(tol.line_count(), 1);

        tol.text = "line1^Jline2".to_string();
        assert_eq!(tol.line_count(), 2);

        tol.text = "line1^Jline2^Jline3".to_string();
        assert_eq!(tol.line_count(), 3);
    }

    #[test]
    fn test_point_toward() {
        let mut tol = Tolerance::new();
        tol.insertion_point = Vector3::new(0.0, 0.0, 0.0);
        tol.point_toward(Vector3::new(0.0, 10.0, 0.0));
        assert!((tol.direction.y - 1.0).abs() < 1e-10);
        assert!(tol.direction.x.abs() < 1e-10);
    }

    #[test]
    fn test_bounding_box() {
        let tol = Tolerance::with_text(Vector3::new(10.0, 10.0, 0.0), "test text");
        let bb = tol.bounding_box();
        assert!(bb.min.x <= 10.0);
        assert!(bb.max.x >= 10.0);
    }

    #[test]
    fn test_cylindricity_tolerance() {
        let text = Tolerance::cylindricity_tolerance(0.02);
        assert!(text.contains("e"));
        assert!(text.contains("0.02"));
    }

    #[test]
    fn test_runout_tolerance() {
        let circular = Tolerance::runout_tolerance(0.1, "A", false);
        assert!(circular.contains("r"));

        let total = Tolerance::runout_tolerance(0.1, "A", true);
        assert!(total.contains("t"));
    }
}