Rulingpen

The drawing model

For developers using the library. DWG and DXF files of every version are read into one set of plain Rust types, defined in the rulingpen-core crate. The same types serialise to the JSON Lines that rp dump prints, so anything you can see in a dump you can reach in code under the same name.

Reading a file, end to end

This program reads a DWG or DXF, prints what the reader noticed, lists every line in model space with its length, prints the extents, and plots model space to an A3 PDF. It was compiled against the 0.1.0 crates and run on the sample bracket; its output follows.

use rulingpen_core::{EntityKind, ReadOptions};
use rulingpen_out::{PdfOptions, PdfPage};
use rulingpen_render::{RenderOptions, RenderTarget};
use rulingpen_text::FontStore;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let path = std::env::args().nth(1).ok_or("usage: sdk-example <file.dwg|file.dxf>")?;
    let bytes = std::fs::read(&path)?;

    // One call per format; both return the same drawing model.
    let opts = ReadOptions::default();
    let loaded = if rulingpen_dwg::sniff(&bytes) {
        rulingpen_dwg::read_dwg(&bytes, &opts)?
    } else {
        rulingpen_dxf::read_dxf(&bytes, &opts)?
    };
    let drawing = &loaded.drawing;
    println!("{} ({:?}), {} layers", drawing.version_magic, drawing.version, drawing.layers.len());

    // What the reader noticed: recoverable problems are reported, not thrown.
    for d in &loaded.diagnostics {
        println!("{:?} {}: {}", d.severity, d.code, d.message);
    }

    // Model space, every line with its layer and length.
    if let Some(model) = drawing.model_space() {
        for e in &model.entities {
            if let EntityKind::Line(l) = &e.kind {
                let (dx, dy) = (l.end.x - l.start.x, l.end.y - l.start.y);
                println!("LINE {:X} on {}: {:.2}", e.common.handle.0, e.common.layer, dx.hypot(dy));
            }
        }
    }

    // Extents computed from the geometry, not taken from the header.
    let ext = rulingpen_geom::drawing_extents(drawing);
    if !ext.is_empty() {
        println!("extents {:?} to {:?}", ext.min, ext.max);
    }

    // Plot model space to an A3 PDF.
    let fonts = FontStore::with_builtin();
    let list = rulingpen_render::render(drawing, &fonts, &RenderOptions {
        target: RenderTarget::ModelExtents,
        ..RenderOptions::default()
    });
    let page = PdfPage { list: &list, width_mm: 420.0, height_mm: 297.0, fit: true };
    std::fs::write("plot.pdf", rulingpen_out::to_pdf(&[page], &PdfOptions::default())?)?;
    Ok(())
}
$ sdk-example rp-001-mounting-bracket.dxf
AC1015 (R2000), 10 layers
LINE 67 on CENTER: 44.00
LINE 68 on CENTER: 44.00
LINE 6A on CENTER: 57.00
...
LINE 96 on TITLE: 15.00
extents Point3 { x: -45.0, y: -75.0, z: 0.0 } to Point3 { x: 305.0, y: 125.0, z: 0.0 }

The PDF it writes passes qpdf --check.

The crates

CrateWhat it doesMain entry points
rulingpen-coreThe drawing model, options, diagnostics, errorsDrawing, Entity, ReadOptions, Loaded
rulingpen-dwgDWG reading, AutoCAD 1.x to 2018sniff, probe, read_dwg, thumbnail
rulingpen-dxfDXF reading and writing, ASCII and binarysniff, read_dxf, write_dxf
rulingpen-geomWorld coordinates, curves, boxes, extentsdrawing_extents, entity_bbox, flatten, ocs_to_wcs
rulingpen-textSHX and TrueType fonts, TEXT and MTEXT layoutFontStore, layout_text, layout_mtext
rulingpen-annotDimension measurement and geometrydimension_measurement, dimension_geometry
rulingpen-renderA drawing to a display list for a view or layoutrender, RenderOptions, RenderTarget
rulingpen-outDisplay lists to PDF, SVG, PNGto_pdf, to_svg, to_png, to_rgba

write_dxf exists but its round trip has no judged number yet, and write_dwg returns an Unsupported error. See limitations.

Drawing

Drawing is the whole file:

FieldHolds
version, version_magicAcVersion (Pre13, R13 ... R2018, ordered so they compare with <) and the exact code read, such as "AC1015"
codepage$DWGCODEPAGE, such as "ANSI_1252". Strings are decoded to UTF-8 on read
headerEvery header variable by name without the $: header.get("EXTMIN"), header.real("LTSCALE", 1.0)
layers, linetypes, text_styles, dim_styles, views, ucss, vports, app_idsThe symbol tables
blocksEvery block, including *Model_Space and each layout's *Paper_Space block, each with its entities
objectsNon-graphical objects: dictionaries, layouts, plot settings, groups, image definitions, XRecords and others
thumbnail, summary, app_infoThe preview image saved in the file, its summary information, and which program wrote it
handle_seedThe next free handle

Helpers: model_space(), block(name), layer(name), linetype(name), text_style(name), dim_style(name), object(handle), layouts() (in tab order) and all_entities() (every entity with the block that owns it).

Entities

An Entity is common (the properties every entity has) plus kind (what it is):

  • common: handle, owner, layer, linetype, color (ByLayer, ByBlock, Aci(n) or Rgb(r, g, b)), lineweight (hundredths of a millimetre, or ByLayer, ByBlock, Default), linetype_scale, invisible, paper_space, transparency, xdata and the rest of what DXF calls the common group codes.
  • kind: one variant per entity type: Line, Point, Circle, Arc, Ellipse, LwPolyline, Polyline, Spline, Text, Attrib, AttDef, MText, Insert, Hatch, Dimension, Leader, MLeader, Solid, Trace, Face3d, Viewport, Image, Wipeout, XLine, Ray, MLine, Tolerance, Shape, Acis (3DSOLID, REGION, BODY), Table, Mesh, Underlay, Proxy, and Other.

kind.dxf_name() gives the DXF type name ("LWPOLYLINE").

The rules every type follows

  • Angles are radians, everywhere, including arcs, text rotation and dimension angles. DXF stores most angles in degrees; the readers convert.
  • Coordinates are as the file stores them. Entities that DXF defines in their own object coordinate system (circles, arcs, text, light polylines, inserts, hatches, solids, 2D polylines) keep those coordinates and their extrusion vector. rulingpen_geom::ocs_to_wcs and ocs_matrix give world coordinates.
  • References are names for tables, handles for everything else. An entity's layer is the layer's name; names compare without regard to case (drawing.layer("outline") finds OUTLINE). DWG readers resolve handles to names for you.
  • Nothing is dropped. A record the reader cannot type becomes EntityKind::Other or ObjectKind::Other, a RawRecord holding its DXF name and every group code, and for DWG the raw object bytes. Unknown header variables stay in header. A writer can put them back.

Diagnostics and errors

A reader returns Loaded { drawing, diagnostics }. Problems it recovered from (a bad CRC, an object it could not decode, a missing table record) are Diagnostics with a severity (Info, Warning, or Error when data was lost or guessed), a stable kebab-case code such as crc-mismatch, a message, and the handle or byte offset when known.

A file that cannot be read at all is an Err of rulingpen_core::Error: NotRecognized, UnsupportedVersion, Corrupt { offset, message }, Limit (a safety limit was hit) or Unsupported.

Hostile files

ReadOptions bounds what a reader will do: max_objects (default 20,000,000) and max_section_bytes (default 2 GiB for any one decompressed section). Readers never panic on bad input; they return an error or a diagnostic. strict: true stops at the first structural error instead of recovering what can be read.

Rendering

rulingpen_render::render(&drawing, &fonts, &options) turns a drawing into a DisplayList: strokes, fills, text and images in drawing units, with the layer of each item, ready for any output. RenderTarget picks what to draw: ModelExtents, ModelSavedView, ModelWindow(box) or Layout(name). Other options: background, monochrome, lineweights, a plot style table (.ctb bytes), and use_cached_blocks (on by default: dimensions and tables are drawn from the blocks AutoCAD stored, as AutoCAD does).

rulingpen_out writes a display list as PDF (to_pdf, one or more pages in millimetres), SVG (to_svg) or PNG (to_png, or to_rgba for raw pixels).

FontStore::with_builtin() holds the open stand-in fonts that ship with Rulingpen. To use your own fonts, fonts.add_dir(path) adds every .shx, .ttf, .ttc and .otf file under a folder; text then uses them where the drawing names them. (rp itself uses only the built-in fonts.)