GitCorner

Code

ossartcraftcadcraft🌐
a770fa5a5e5f
//! Data that used to be lost only when a drawing is saved as DWG and reopened (the DWG bridge
//! converts our DXF with acadrust), and the paper-space viewport the DXF writer adds for it.

use cadcraft_color::{Color, Rgb};
use cadcraft_doc::*;
use cadcraft_geom::{Vec2, Vec3};

fn through_dwg(d: &Drawing) -> Drawing {
    let dwg = cadcraft_io::write(d, "x.dwg").unwrap();
    cadcraft_io::read(&dwg, "x.dwg").unwrap()
}

fn line(d: &mut Drawing, space: &Space, common: Common) -> Handle {
    d.add(space, common, EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(10.0, 5.0, 0.0) })).unwrap()
}

fn viewport(id: u32) -> EntityKind {
    EntityKind::Viewport(Viewport {
        center: Vec3::new(50.0, 40.0, 0.0),
        width: 80.0,
        height: 60.0,
        view_center: Vec2::new(10.0, 10.0),
        view_height: 50.0,
        id,
        locked: false,
        frozen_layers: vec![],
        layer_colors: vec![],
        clip: None,
        on: true,
        twist: 0.0,
    })
}

/// The (code, value) pairs of every `kind` record in DXF text.
fn records(text: &str, kind: &str) -> Vec<Vec<(String, String)>> {
    let lines: Vec<&str> = text.lines().map(str::trim).collect();
    let mut out: Vec<Vec<(String, String)>> = Vec::new();
    let mut inside = false;
    for pair in lines.chunks(2) {
        let [code, value] = pair else { break };
        if *code == "0" {
            inside = *value == kind;
            if inside {
                out.push(Vec::new());
            }
        } else if inside && let Some(rec) = out.last_mut() {
            rec.push((code.to_string(), value.to_string()));
        }
    }
    out
}

fn group<'a>(rec: &'a [(String, String)], code: &str) -> Option<&'a str> {
    rec.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str())
}

fn viewport_ids(l: &Layout) -> Vec<u32> {
    l.entities.iter().filter_map(|e| if let EntityKind::Viewport(v) = &e.kind { Some(v.id) } else { None }).collect()
}

/// True colours (entity and layer) and entity transparency: a new drawing's DWG is written as
/// AutoCAD 2018 (R2000 DWG has neither), while the DXF the bridge reads stays R2000.
#[test]
fn dwg_keeps_true_colours_and_transparency() {
    let mut d = Drawing::new_metric();
    d.layers.push(Layer { name: "Fancy".into(), color: Color::True(Rgb(12, 200, 99)), ..Layer::default() });
    let h = line(
        &mut d,
        &Space::Model,
        Common { layer: "Fancy".into(), color: Color::True(Rgb(1, 2, 3)), transparency: Transparency::Percent(40), ..Common::default() },
    );

    let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
    assert_eq!(craft_dwg::version(&dwg).as_deref(), Some("AC1032"));
    let header = records(&cadcraft_io::write_dxf(&d), "SECTION");
    assert_eq!(header.first().and_then(|h| group(h, "1")), Some("AC1015"), "the DXF stays R2000");

    let back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
    let e = back.entity(h).unwrap();
    assert_eq!(e.common.color, Color::True(Rgb(1, 2, 3)));
    assert_eq!(e.common.transparency, Transparency::Percent(40));
    assert_eq!(back.layers.iter().find(|l| l.name == "Fancy").map(|l| l.color), Some(Color::True(Rgb(12, 200, 99))));
}

/// Entities of a layout other than the first stay in that layout.
#[test]
fn dwg_keeps_paper_space_entities_in_their_layout() {
    let mut d = Drawing::new_metric();
    let second = Space::Paper(d.layouts[1].name.clone());
    let h = d.add(&second, Common::default(), EntityKind::Circle(Circle { center: Vec3::new(1.0, 1.0, 0.0), radius: 0.5 })).unwrap();
    let back = through_dwg(&d);
    assert!(back.layouts[1].entities.contains(h), "{:?}", back.layouts.iter().map(|l| l.entities.len()).collect::<Vec<_>>());
    assert!(!back.layouts[0].entities.contains(h));
}

/// Table styles (R2000 DWG has no TABLESTYLE objects).
#[test]
fn dwg_keeps_table_styles() {
    let mut d = Drawing::new_metric();
    let sched = TableStyle { name: "Sched".into(), text_height: 2.5, margin: 1.0, title: false, header: true, ..TableStyle::default() };
    d.table_styles.push(sched.clone());
    let back = through_dwg(&d);
    assert_eq!(back.table_styles.iter().find(|s| s.name == "Sched"), Some(&sched));
}

/// DWG doesn't store viewport ids; readers number a layout's viewports in order, and id 1 is the
/// paper-space viewport (the sheet, not drawn). The writer puts that viewport ahead of a layout's
/// own viewports, so a viewport made in CADCraft (id 2) keeps its id instead of becoming the
/// sheet; our reader drops the added viewport again, so a DXF round trip is unchanged.
#[test]
fn viewport_ids_survive_dwg_and_the_paper_viewport_stays_implicit() {
    let mut d = Drawing::new_metric();
    let first = Space::Paper(d.layouts[0].name.clone());
    let h = d.add(&first, Common::default(), viewport(2)).unwrap();
    d.add(&first, Common::default(), viewport(3)).unwrap();

    let text = cadcraft_io::write_dxf(&d);
    let vps = records(&text, "VIEWPORT");
    assert_eq!(vps.len(), 3, "{text}");
    assert_eq!(group(&vps[0], "69"), Some("1"));
    assert_eq!(group(&vps[0], "1000"), Some("PAPERVIEW"));
    // Viewports are written "on": status 68 positive, and 90 with the always-set bit 32768.
    assert_eq!(group(&vps[1], "68"), Some("2"));
    assert_eq!(group(&vps[1], "90"), Some("32768"));

    let back = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
    assert_eq!(viewport_ids(&back.layouts[0]), [2, 3]);
    assert_eq!(back.layouts[0].entities.len(), 2);

    let back = through_dwg(&d);
    assert_eq!(viewport_ids(&back.layouts[0]), [2, 3]);
    assert!(back.layouts[0].entities.contains(h));

    // A layout that has its paper-space viewport (from another program) gets no second one.
    let mut d = Drawing::new_metric();
    d.add(&first, Common::default(), viewport(1)).unwrap();
    d.add(&first, Common::default(), viewport(2)).unwrap();
    let text = cadcraft_io::write_dxf(&d);
    assert!(!text.contains("PAPERVIEW"));
    assert_eq!(viewport_ids(&cadcraft_io::read_dxf(text.as_bytes()).unwrap().layouts[0]), [1, 2]);
}

/// The paper-space viewport (id 1) of a drawing from another program can come after a model
/// viewport in the layout, e.g. when the draw order (SORTENTS) put it behind. DWG numbers in
/// order, so the writer puts it first: otherwise the model viewport became the sheet on reopen.
#[test]
fn a_paper_viewport_behind_a_model_viewport_stays_id_1_through_dwg() {
    let mut d = Drawing::new_metric();
    let names: Vec<String> = d.layouts.iter().map(|l| l.name.clone()).collect();
    for name in &names {
        let space = Space::Paper(name.clone());
        let model = d.add(&space, Common::default(), viewport(2)).unwrap();
        let sheet = d.add(&space, Common::default(), viewport(1)).unwrap();
        let back = through_dwg(&d);
        let l = back.layouts.iter().find(|l| &l.name == name).unwrap();
        let id = |h: Handle| match &l.entities.get(h).map(|e| &e.kind) {
            Some(EntityKind::Viewport(v)) => Some(v.id),
            _ => None,
        };
        assert_eq!((id(model), id(sheet)), (Some(2), Some(1)), "layout {name}");
    }
}

/// The paper-space viewport a save adds is the sheet as large as it plots: a layout with a custom
/// plot scale (here 49.6 mm of paper per unit, as in #2108's file) has an A3 sheet of 8.47 × 5.99
/// units in paper space, not 420 × 297. A layout at 1:1 or scaled to fit keeps the page size.
#[test]
fn the_added_paper_viewport_follows_the_plot_scale() {
    let sheet_width = |scale: f64, fit: bool| {
        let mut d = Drawing::new_metric();
        let page = &mut d.layouts[0].page;
        (page.width_mm, page.height_mm, page.landscape, page.paper_mm) = (297.0, 420.0, true, true);
        (page.scale, page.scale_to_fit) = (scale, fit);
        let first = Space::Paper(d.layouts[0].name.clone());
        d.add(&first, Common::default(), viewport(2)).unwrap();
        let text = cadcraft_io::write_dxf(&d);
        let vps = records(&text, "VIEWPORT");
        assert_eq!(group(&vps[0], "1000"), Some("PAPERVIEW"), "{text}");
        group(&vps[0], "40").unwrap().parse::<f64>().unwrap()
    };
    assert!((sheet_width(49.6, false) - 420.0 / 49.6).abs() < 1e-9, "{}", sheet_width(49.6, false));
    assert!((sheet_width(1.0, false) - 420.0).abs() < 1e-9);
    assert!((sheet_width(49.6, true) - 420.0).abs() < 1e-9, "scaled to fit: the scale means nothing");
    assert!((sheet_width(f64::NAN, false) - 420.0).abs() < 1e-9, "an unusable scale is 1");
}

/// A layout viewport's view twist (group 51, #1316) is read and written, so DXF and DWG keep it;
/// a hostile angle reads as no twist and never panics.
#[test]
fn viewport_twist_survives_dxf_and_dwg() {
    let mut d = Drawing::new_metric();
    let name = d.layouts[0].name.clone();
    let space = Space::Paper(name.clone());
    let twist = 30f64.to_radians();
    let EntityKind::Viewport(mut vp) = viewport(2) else { unreachable!() };
    vp.twist = twist;
    let h = d.add(&space, Common::default(), EntityKind::Viewport(vp)).unwrap();
    let twist_of = |d: &Drawing| {
        let l = d.layouts.iter().find(|l| l.name == name).unwrap();
        l.entities
            .iter()
            .find_map(|e| {
                if let EntityKind::Viewport(v) = &e.kind
                    && v.id == 2
                {
                    Some(v.twist)
                } else {
                    None
                }
            })
            .unwrap()
    };

    let dxf = cadcraft_io::write(&d, "x.dxf").unwrap();
    let text = String::from_utf8_lossy(&dxf).to_string();
    let rec = records(&text, "VIEWPORT").into_iter().find(|r| group(r, "5") == Some(h.hex().as_str())).unwrap();
    assert_eq!(group(&rec, "51").and_then(|v| v.parse::<f64>().ok()).map(f64::round), Some(30.0), "{rec:?}");
    assert!((twist_of(&cadcraft_io::read(&dxf, "x.dxf").unwrap()) - twist).abs() < 1e-9);
    assert!((twist_of(&through_dwg(&d)) - twist).abs() < 1e-9);

    // An untwisted viewport writes no group 51; a hostile twist (from JSON or MCP) writes a finite
    // angle within one turn, or none.
    for (value, want) in [(0.0, None), (f64::NAN, None), (f64::INFINITY, None), (1e300, Some(()))] {
        let mut d = Drawing::new_metric();
        let EntityKind::Viewport(mut vp) = viewport(2) else { unreachable!() };
        vp.twist = value;
        let h = d.add(&space, Common::default(), EntityKind::Viewport(vp)).unwrap();
        let text = String::from_utf8_lossy(&cadcraft_io::write(&d, "x.dxf").unwrap()).to_string();
        let rec = records(&text, "VIEWPORT").into_iter().find(|r| group(r, "5") == Some(h.hex().as_str())).unwrap();
        let written = group(&rec, "51").map(|v| v.parse::<f64>().unwrap());
        assert_eq!(written.map(|_| ()), want, "{value}: {rec:?}");
        assert!(written.is_none_or(|a| a.is_finite() && (0.0..360.0).contains(&a)), "{value}: {written:?}");
    }

    // Hostile angles: not a number reads as 0, a huge one is brought into one turn.
    for (value, want) in
        [("nan", Some(0.0)), ("1e400", Some(0.0)), ("-1e-20", Some(0.0)), ("-330", Some(30f64.to_radians())), ("7200000000000000000030", None)]
    {
        let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
        let at = lines.windows(2).position(|w| w[0].trim() == "51" && Some(w[1].trim()) == group(&rec, "51")).unwrap();
        lines[at + 1] = value.to_string();
        let bad = lines.join("\n");
        let back = twist_of(&cadcraft_io::read(bad.as_bytes(), "x.dxf").unwrap());
        assert!(back.is_finite() && (0.0..std::f64::consts::TAU).contains(&back), "{value}: {back}");
        if let Some(w) = want {
            assert!((back - w).abs() < 1e-9, "{value}: {back}");
        }
    }
}