Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

### Unreleased

- **DXF writer looks extension dictionaries up in linear time** - Each table
record that names no extension dictionary had its owner looked up by walking
every object of the document, so writing a DXF was quadratic in block records
times objects (a 32 MB DWG with 16 027 block records took 11.3 s to write).
The writer now gathers the dictionaries' owners once per write
(`CadDocument::owned_dictionaries`); `extension_dictionary_handle` is
unchanged.
- **Extended dimensions keep AcDbDimension base groups** - The
ARC_DIMENSION and LARGE_RADIAL_DIMENSION reader had no arms for the
AcDbDimension insertion point (12), horizontal direction (51) and
Expand Down
62 changes: 52 additions & 10 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4551,6 +4551,57 @@ impl CadDocument {
}

pub fn extension_dictionary_handle(&self, owner: Handle) -> Option<Handle> {
self.extension_dictionary_handle_or(owner, || {
self.objects
.iter()
.find_map(|(handle, object)| match object {
ObjectType::Dictionary(dictionary)
if dictionary.owner == owner && !handle.is_null() =>
{
Some(*handle)
}
_ => None,
})
})
}

/// [`Self::extension_dictionary_handle`] with its last step, the walk over
/// every object for a dictionary `owner` owns, answered from `owned`
/// ([`Self::owned_dictionaries`]). For a caller that asks for many owners
/// while the document does not change: the DXF writer asks for every
/// table record, and walking every object each time made writing
/// quadratic in records times objects.
pub(crate) fn extension_dictionary_handle_in(
&self,
owner: Handle,
owned: &HashMap<Handle, Handle>,
) -> Option<Handle> {
self.extension_dictionary_handle_or(owner, || owned.get(&owner).copied())
}

/// Each owner of a dictionary and that dictionary, the first one in the
/// order of `objects` for an owner of several: what the walk in
/// [`Self::extension_dictionary_handle`] finds for each owner, gathered in
/// one walk.
pub(crate) fn owned_dictionaries(&self) -> HashMap<Handle, Handle> {
let mut owned = HashMap::new();
for (handle, object) in &self.objects {
if let ObjectType::Dictionary(dictionary) = object {
if !handle.is_null() {
owned.entry(dictionary.owner).or_insert(*handle);
}
}
}
owned
}

/// The steps of [`Self::extension_dictionary_handle`] before its walk over
/// every object, which `walk` takes.
fn extension_dictionary_handle_or(
&self,
owner: Handle,
walk: impl FnOnce() -> Option<Handle>,
) -> Option<Handle> {
// A record without a handle owns nothing; the search below would
// otherwise return the root dictionary, whose owner is NULL too.
if owner.is_null() {
Expand Down Expand Up @@ -4585,16 +4636,7 @@ impl CadDocument {
if matches!(self.objects.get(&owner), Some(ObjectType::Dictionary(_))) {
return None;
}
self.objects
.iter()
.find_map(|(handle, object)| match object {
ObjectType::Dictionary(dictionary)
if dictionary.owner == owner && !handle.is_null() =>
{
Some(*handle)
}
_ => None,
})
walk()
}

/// Resolve a named XRecord in `owner`'s extension dictionary.
Expand Down
1 change: 1 addition & 0 deletions src/io/dxf/writer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ impl<'a> DxfWriter<'a> {
let mut section_writer = SectionWriter::new(writer, handle_start, handle_seed);
section_writer.set_version(output_version);
section_writer.build_valid_handles(document);
section_writer.gather_owned_dictionaries(document);
if let Some(counts) = class_counts {
section_writer.set_class_instance_counts(counts);
}
Expand Down
25 changes: 23 additions & 2 deletions src/io/dxf/writer/section_writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@ pub struct SectionWriter<'a, W: DxfStreamWriter> {
/// Records written per DXF name (upper case), used for the CLASSES
/// instance counts. `None` keeps each class's stored count.
class_instance_counts: Option<HashMap<String, i32>>,
/// Each dictionary's owner in the document being written
/// (`CadDocument::owned_dictionaries`), gathered once: every table record
/// is asked for its extension dictionary. `None` walks the document's
/// objects for each record.
owned_dictionaries: Option<HashMap<Handle, Handle>>,
}

impl<'a, W: DxfStreamWriter> SectionWriter<'a, W> {
Expand All @@ -128,6 +133,22 @@ impl<'a, W: DxfStreamWriter> SectionWriter<'a, W> {
loft_reference_appid: None,
source_dwg_context: None,
class_instance_counts: None,
owned_dictionaries: None,
}
}

/// Gather the dictionaries' owners of `document` once, for the extension
/// dictionaries of its table records. The document must not change while
/// this writer writes it.
pub(crate) fn gather_owned_dictionaries(&mut self, document: &CadDocument) {
self.owned_dictionaries = Some(document.owned_dictionaries());
}

/// `owner`'s extension dictionary, from the gathered owners when there are.
fn extension_dictionary(&self, document: &CadDocument, owner: Handle) -> Option<Handle> {
match &self.owned_dictionaries {
Some(owned) => document.extension_dictionary_handle_in(owner, owned),
None => document.extension_dictionary_handle(owner),
}
}

Expand Down Expand Up @@ -2085,7 +2106,7 @@ impl<'a, W: DxfStreamWriter> SectionWriter<'a, W> {
self.writer.write_string(0, "TABLE")?;
self.writer.write_string(2, name)?;
self.writer.write_handle(5, table_handle)?;
if let Some(handle) = document.extension_dictionary_handle(table_handle) {
if let Some(handle) = self.extension_dictionary(document, table_handle) {
self.writer.write_string(102, "{ACAD_XDICTIONARY")?;
self.writer.write_handle(360, handle)?;
self.writer.write_string(102, "}")?;
Expand All @@ -2107,7 +2128,7 @@ impl<'a, W: DxfStreamWriter> SectionWriter<'a, W> {
handle: Handle,
document: &CadDocument,
) -> Result<()> {
if let Some(xdictionary) = document.extension_dictionary_handle(handle) {
if let Some(xdictionary) = self.extension_dictionary(document, handle) {
if !xdictionary.is_null()
&& (self.valid_handles.is_empty() || self.valid_handles.contains(&xdictionary))
{
Expand Down
79 changes: 79 additions & 0 deletions tests/dxf_write_scaling.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//! Writing a DXF takes time in proportion to the drawing: four times the blocks and objects take well under sixteen
//! times as long. A table record that names no extension dictionary has its owner looked up in every object of the
//! document (`CadDocument::extension_dictionary_handle`), and the writer asks for every block record, so a drawing of
//! many blocks (every dimension has one) and many objects is quadratic to write.

use std::time::{Duration, Instant};

use acadrust::entities::{EntityType, Line};
use acadrust::objects::{Dictionary, ObjectType};
use acadrust::tables::BlockRecord;
use acadrust::types::{DxfVersion, Vector3};
use acadrust::{CadDocument, DxfWriter};

/// A drawing of `n` blocks of one line each, and `n` lines in model space, each with an extension dictionary.
fn drawing(n: usize) -> CadDocument {
let mut doc = CadDocument::with_version(DxfVersion::AC1032);
for b in 0..n {
let mut record = BlockRecord::new(format!("B{b}"));
record.handle = doc.allocate_handle();
record.block_entity_handle = doc.allocate_handle();
record.block_end_handle = doc.allocate_handle();
let owner = record.handle;
doc.block_records.add(record).unwrap();
let mut line = Line::from_points(Vector3::new(0.0, 0.0, 0.0), Vector3::new(1.0, 0.0, 0.0));
line.common.owner_handle = owner;
doc.add_entity(EntityType::Line(line)).unwrap();
}
for i in 0..n {
let x = i as f64;
let line = doc
.add_entity(EntityType::Line(Line::from_points(
Vector3::new(x, 0.0, 0.0),
Vector3::new(x, 1.0, 0.0),
)))
.unwrap();
let mut dictionary = Dictionary::new();
dictionary.handle = doc.allocate_handle();
dictionary.owner = line;
dictionary.hard_owner = true;
let handle = dictionary.handle;
doc.objects.insert(handle, ObjectType::Dictionary(dictionary));
doc.get_entity_mut(line).unwrap().common_mut().xdictionary_handle = Some(handle);
}
doc
}

fn fastest_write(doc: &CadDocument) -> (Duration, Vec<u8>) {
let mut best: Option<(Duration, Vec<u8>)> = None;
for _ in 0..3 {
let t = Instant::now();
let bytes = DxfWriter::new(doc).write_to_vec().unwrap();
let e = t.elapsed();
if best.as_ref().is_none_or(|(b, _)| e < *b) {
best = Some((e, bytes));
}
}
best.unwrap()
}

#[test]
fn writing_many_blocks_and_objects_to_dxf_scales_linearly() {
const N: usize = 3_000;
let (small, large) = (drawing(N), drawing(N * 4));
let (a, _) = fastest_write(&small);
let (b, bytes) = fastest_write(&large);
let text = String::from_utf8_lossy(&bytes);
assert_eq!(
text.matches("{ACAD_XDICTIONARY").count(),
N * 4,
"every model space line keeps its extension dictionary"
);
// Linear is 4x, quadratic 16x; below a few milliseconds the ratio is noise.
let ratio = b.as_secs_f64() / a.as_secs_f64().max(0.005);
eprintln!("{N} blocks {a:?}, {} blocks {b:?}, ratio {ratio:.1}", N * 4);
assert!(
ratio < 9.0,
"4x the blocks and objects took {ratio:.1}x as long to write ({a:?} → {b:?})"
);
}