Merge review/1845: PR #1845 DGNIMPORT with fixes

# Conflicts:
#	src/app/commands/dgn_import.rs
This commit is contained in:
Hakan Seven committed 2026-10-16 23:51:54 +03:00
commit fba1dfcd88
36 files changed
+2237 -501

No files matched your search

+4 -1
View File
@@ -6678,7 +6678,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6666,7 +6666,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6663,7 +6663,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6664,7 +6664,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6666,7 +6666,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6665,7 +6665,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6666,7 +6666,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6663,7 +6663,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6666,7 +6666,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6654,7 +6654,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6650,7 +6650,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6665,7 +6665,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6654,7 +6654,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6665,7 +6665,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6666,7 +6666,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6664,7 +6664,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6665,7 +6665,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6666,7 +6666,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6667,7 +6667,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6587,7 +6587,10 @@ dgn-import =
.references = Dış DGN referansları
.bind = Blok / xref yap
.attach = DGN altlığı bağla
.references-note = DGN dosyalarının referans ekleri okunmaz; dışarıda bırakılır.
.existing = Çevrilmiş çizim zaten varsa
.prompt-overwrite = Sor
.overwrite = Sormadan üzerine yaz
.keep-existing = Üzerine yazma
.mapping = Özellik eşleme
.mapping-standard = Standart eşleme kurulumu.
.mapping-note = Önizleme seçili kurulumun bu dosyaya etkisini gösterir.
+4 -1
View File
@@ -6649,7 +6649,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+4 -1
View File
@@ -6661,7 +6661,10 @@ dgn-import =
.references = External DGN references
.bind = Bind as block / xref
.attach = Attach as DGN underlay
.references-note = Reference attachments of DGN files are not read; they are left out.
.existing = When the translated drawing exists
.prompt-overwrite = Prompt to overwrite
.overwrite = Overwrite without prompting
.keep-existing = Do not overwrite
.mapping = Property mapping
.mapping-standard = Standard mapping setup.
.mapping-note = The preview shows the selected setup's effect on this file.
+317 -84
View File
@@ -9,7 +9,9 @@ use std::sync::Arc;
use super::*;
use crate::io::model_import::ModelFormat;
use crate::modules::insert::dgn_import::{self, DgnImportCommand, DgnImportRequest};
use crate::modules::insert::dgn_import::{
self, DgnImportCommand, DgnImportRequest, ExistingReference, ReferenceMode,
};
use crate::ui::window::import_dialogs::{
unsupported_reason, DgnImportState, ImportDialogMsg, ImportFileState, Support, FORMATS,
};
@@ -54,7 +56,7 @@ fn exists(path: &str) -> bool {
/// Whether the file is a DGN model DGNIMPORT reads.
fn is_dgn(path: &str) -> bool {
crate::scene::model::underlay_vector::item_names(codec::entities::UnderlayType::Dgn, path)
crate::scene::model::underlay_vector::dgn_import_models(path)
.and_then(|models| models.into_iter().next())
.is_some_and(|model| crate::scene::model::underlay_vector::dgn_import(path, &model).is_some())
}
@@ -178,28 +180,38 @@ impl OpenCADStudio {
/// The DGN Import window for a file; an error when it is no DGN model.
pub(in crate::app) fn open_dgn_import_dialog(&mut self, path: &str) -> Result<(), String> {
use crate::scene::model::underlay_vector::{dgn_import, item_names};
let models = item_names(codec::entities::UnderlayType::Dgn, path).unwrap_or_default();
use crate::scene::model::underlay_vector::{dgn_import, dgn_import_models};
let models = dgn_import_models(path).unwrap_or_default();
let Some(import) = models.first().and_then(|m| dgn_import(path, m)) else {
return Err(crate::t!("Invalid or unsupported DGN file.").into_owned());
};
// The options chosen last stay when the file is changed.
// The options chosen last (DGNIMPORTMODE and the kept import
// settings when the window opens) stay when the file is changed.
let previous = self.import_dialogs.dgn.take();
let saved = dgn_import::settings();
let keep = |f: fn(&DgnImportState) -> bool, default: bool| {
previous.as_ref().map_or(default, f)
};
self.import_dialogs.dgn = Some(DgnImportState {
path: path.to_string(),
version: if import.v7 { "V7" } else { "V8" },
// Sheet models are not imported.
models: crate::ui::window::pdf_dialogs::item_thumbs(
codec::entities::UnderlayType::Dgn,
path,
),
)
.into_iter()
.filter(|m| models.contains(&m.label))
.collect(),
model: 0,
current_drawing: keep(|s| s.current_drawing, false),
prefix_duplicates: keep(|s| s.prefix_duplicates, false),
current_drawing: keep(|s| s.current_drawing, saved.mode != 0),
prefix_duplicates: keep(|s| s.prefix_duplicates, saved.mode == 2),
sub_units: keep(|s| s.sub_units, false),
explode_text_nodes: keep(|s| s.explode_text_nodes, false),
explode_text_nodes: keep(|s| s.explode_text_nodes, saved.explode_text_nodes),
references: previous.as_ref().map_or(saved.references, |s| s.references),
existing_reference: previous
.as_ref()
.map_or(saved.existing_reference, |s| s.existing_reference),
units: import.unit_names.clone(),
mapping_tab: previous.as_ref().map_or(0, |s| s.mapping_tab),
mapping: [0, 1, 2, 3].map(|tab| dgn_import::mapping_rows(&import, tab)),
@@ -478,6 +490,16 @@ impl OpenCADStudio {
s.explode_text_nodes = on;
}
}
ImportDialogMsg::DgnReferences(mode) => {
if let Some(s) = self.import_dialogs.dgn.as_mut() {
s.references = mode;
}
}
ImportDialogMsg::DgnExisting(choice) => {
if let Some(s) = self.import_dialogs.dgn.as_mut() {
s.existing_reference = choice;
}
}
ImportDialogMsg::DgnMappingTab(tab) => {
if let Some(s) = self.import_dialogs.dgn.as_mut() {
s.mapping_tab = tab.min(3);
@@ -498,7 +520,22 @@ impl OpenCADStudio {
explode_text_nodes: s.explode_text_nodes,
current_drawing: s.current_drawing,
prefix_duplicates: s.prefix_duplicates,
references: s.references,
existing_reference: s.existing_reference,
};
// The window's choices become DGNIMPORTMODE and the kept
// settings the command line imports with.
dgn_import::set_settings(dgn_import::DgnImportSettings {
mode: match (s.current_drawing, s.prefix_duplicates) {
(false, _) => 0,
(true, false) => 1,
(true, true) => 2,
},
explode_text_nodes: s.explode_text_nodes,
references: s.references,
existing_reference: s.existing_reference,
});
self.save_config();
self.close_active_modal();
return self.run_dgn_import(i, request);
}
@@ -506,7 +543,8 @@ impl OpenCADStudio {
Task::none()
}
/// The import: into a new drawing (or the current one), one undo step.
/// The import: into a new drawing (or the current one), one undo step;
/// then the model's reference attachments as the request says.
pub(in crate::app) fn run_dgn_import(&mut self, i: usize, request: DgnImportRequest) -> Task<Message> {
let Some(import) =
crate::scene::model::underlay_vector::dgn_import(&request.path, &request.model)
@@ -525,84 +563,34 @@ impl OpenCADStudio {
self.active_tab
};
self.push_undo_snapshot(i, "DGNIMPORT");
let stem = std::path::Path::new(&request.path.replace('\\', "/"))
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let scene = &mut self.tabs[i].scene;
// In the current drawing, names it already has keep the existing
// definitions, or are imported under the file's name as prefix.
let prefix = (request.current_drawing && request.prefix_duplicates)
.then(|| format!("{stem}$0$"));
let rename = |taken: bool, name: &str| match &prefix {
Some(p) if taken && name != "0" => format!("{p}{name}"),
_ => name.to_string(),
let naming = if !request.current_drawing {
Naming::Number
} else if request.prefix_duplicates {
let stem = std::path::Path::new(&request.path.replace('\\', "/"))
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let prefix = format!("{stem} - {}$0$", request.model);
Naming::Prefix(dgn_import::symbol_name(&prefix))
} else {
Naming::Keep
};
let mut layers: HashMap<String, String> = HashMap::new();
for (name, color) in &converted.layers {
let target = rename(scene.document.layers.contains(name), name);
if !scene.document.layers.contains(&target) {
let mut layer = codec::tables::Layer::new(target.as_str());
layer.handle = scene.document.allocate_handle();
layer.color = *color;
let _ = scene.document.layers.add(layer);
let layers = place_converted(&mut self.tabs[i].scene, converted, &naming);
if request.references != ReferenceMode::Ignore {
let k = if request.sub_units { import.sub_per_master } else { 1.0 };
// A reference is placed on the model's default level.
let layer = import
.levels
.get(&64)
.map(|l| dgn_import::symbol_name(&l.0))
.unwrap_or_else(|| "0".to_string());
let layer = layers.get(&layer).cloned().unwrap_or(layer);
for reference in &import.references {
self.attach_dgn_reference(i, &request, reference, k, &layer);
}
layers.insert(name.clone(), target);
}
let mut styles: HashMap<String, String> = HashMap::new();
for (name, font) in &converted.styles {
let target = rename(scene.document.text_styles.contains(name), name);
if !scene.document.text_styles.contains(&target) {
let mut style = codec::tables::TextStyle::new(target.as_str());
style.handle = scene.document.allocate_handle();
style.font_file = font.clone();
let _ = scene.document.text_styles.add(style);
}
styles.insert(name.clone(), target);
}
let mut blocks: HashMap<String, String> = HashMap::new();
for (name, _) in &converted.blocks {
let taken = scene.document.block_records.get(name).is_some();
blocks.insert(name.clone(), rename(taken, name));
}
let fix = |mut entity: codec::EntityType| {
let common = entity.common_mut();
if let Some(layer) = layers.get(&common.layer) {
common.layer = layer.clone();
}
match &mut entity {
codec::EntityType::Text(t) => {
if let Some(s) = styles.get(&t.style) {
t.style = s.clone();
}
}
codec::EntityType::MText(t) => {
if let Some(s) = styles.get(&t.style) {
t.style = s.clone();
}
}
codec::EntityType::Insert(insert) => {
if let Some(b) = blocks.get(&insert.block_name) {
insert.block_name = b.clone();
}
}
_ => {}
}
entity
};
for (name, entities) in converted.blocks {
let target = &blocks[&name];
if scene.document.block_records.get(target).is_some() {
continue;
}
let entities = entities.into_iter().map(&fix).collect();
let _ = scene.define_block_from_owned_entities(entities, target, glam::DVec3::ZERO);
}
for entity in converted.entities {
scene.add_entity(fix(entity));
}
if !request.current_drawing {
scene.fit_all();
self.tabs[i].scene.fit_all();
}
self.tabs[i].dirty = true;
self.command_line.push_output("Regenerating model.");
@@ -610,4 +598,249 @@ impl OpenCADStudio {
self.refresh_properties();
task
}
/// One reference attachment: its file translated to "<file>-<model>.dwg"
/// beside it and attached as the external reference "<file> - <model>",
/// or the file attached as a DGN underlay, at the attachment's place.
fn attach_dgn_reference(
&mut self,
i: usize,
request: &DgnImportRequest,
reference: &crate::scene::model::underlay_vector::DgnReference,
units: f64,
layer: &str,
) {
use crate::scene::model::underlay_vector::{dgn_import, dgn_import_models};
let host_dir = std::path::Path::new(&request.path)
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_default();
// A relative name is beside the host file; failing that, the file
// of that name in the host's folder.
let named = std::path::Path::new(&reference.file.replace('\\', "/")).to_path_buf();
let joined = host_dir.join(&named);
let file = if joined.is_file() {
joined
} else {
host_dir.join(named.file_name().unwrap_or_default())
};
let path = file.to_string_lossy().into_owned();
if crate::scene::model::pdf_raster::source_bytes(&path).is_none() {
return;
}
let Some(model) = (if reference.model.is_empty() {
dgn_import_models(&path).and_then(|m| m.into_iter().next())
} else {
Some(reference.model.clone())
}) else {
return;
};
// Sub units scale the placement and the size alike.
let origin = glam::DVec3::from_array(reference.origin) * units;
let scale = reference.scale * units;
if request.references == ReferenceMode::Underlay {
let mut placed = crate::modules::insert::pdf_attach::underlays_for_pages(
codec::entities::UnderlayType::Dgn,
std::slice::from_ref(&model),
origin,
scale,
reference.rotation,
);
let scene = &mut self.tabs[i].scene;
for (page, mut entity) in placed.drain(..) {
let definition = crate::modules::insert::pdf_attach::ensure_underlay_definition(
&mut scene.document,
codec::entities::UnderlayType::Dgn,
&path,
&page,
);
if let codec::EntityType::Underlay(underlay) = &mut entity {
underlay.definition_handle = definition;
}
entity.common_mut().layer = layer.to_string();
scene.add_entity(entity);
}
return;
}
let stem = file
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
// The model name comes from the file: made a plain file name so the
// drawing is written in the reference's folder.
let model_name = dgn_import::symbol_name(&model);
let target = file.with_file_name(format!("{stem}-{model_name}.dwg"));
// ponytail: "Prompt to overwrite" asks nothing and keeps the existing
// drawing, like "Do not overwrite"; add a confirmation if wanted.
let write = !target.is_file() || request.existing_reference == ExistingReference::Overwrite;
if write {
let Some(source) = dgn_import(&path, &model) else {
return;
};
let mut scene = crate::scene::Scene::new();
let converted = dgn_import::convert(&source, false, request.explode_text_nodes);
place_converted(&mut scene, converted, &Naming::Number);
if let Err(error) = crate::io::save(&scene.document, &target) {
self.command_line.push_error(&error);
return;
}
}
let xref = crate::modules::insert::xattach::XrefAttachRequest {
path: target.to_string_lossy().into_owned(),
overlay: false,
path_type: crate::io::xref_model::Pathtype::Relative,
};
let name = dgn_import::symbol_name(&format!("{stem} - {model}"));
let full = crate::modules::insert::xattach::resolve_xref_store_path(&xref.path, None);
self.command_line
.push_output(&format!("Attach Xref \"{name}\": {full}"));
let host = self.tabs[i].current_path.clone();
let block = crate::modules::insert::xattach::prepare_named_xref_definition(
&mut self.tabs[i].scene,
&xref,
host.as_deref(),
&name,
);
if host.is_none() {
self.tabs[i].xref_relative_on_save.insert(block.clone());
}
self.command_line
.push_output(&format!("\"{name}\" loaded: {full}"));
let mut insert = codec::entities::Insert::new(
block,
codec::types::Vector3::new(origin.x, origin.y, origin.z),
)
.with_scale(scale, scale, scale)
.with_rotation(reference.rotation);
insert.common.layer = layer.to_string();
insert.common.linetype = "Continuous".to_string();
self.tabs[i]
.scene
.add_entity(codec::EntityType::Insert(insert));
self.refresh_xref_manager();
}
}
/// How imported names meet the names a drawing already has: a new drawing
/// numbers a clashing layer "<name>_1" and a clashing block or text style
/// "<name>1" (layer 0 and the Standard style are shared); the current
/// drawing either keeps its own definitions or prefixes every imported name
/// (layers 0 and Defpoints excepted).
enum Naming {
Number,
Keep,
Prefix(String),
}
impl Naming {
fn name(&self, kind: char, name: &str, taken: &dyn Fn(&str) -> bool) -> String {
match self {
Naming::Keep => name.to_string(),
Naming::Prefix(p) => {
let shared = kind == 'l'
&& (name == "0" || name.eq_ignore_ascii_case("Defpoints"));
if shared {
name.to_string()
} else {
format!("{p}{name}")
}
}
Naming::Number => {
let shared = (kind == 'l' && name == "0")
|| (kind == 's' && name.eq_ignore_ascii_case("Standard"));
if shared || !taken(name) {
return name.to_string();
}
let sep = if kind == 'l' { "_" } else { "" };
(1..)
.map(|n| format!("{name}{sep}{n}"))
.find(|n| !taken(n))
.unwrap_or_default()
}
}
}
}
/// Adds converted objects to a drawing under the naming rule; returns the
/// layer names as placed.
fn place_converted(
scene: &mut crate::scene::Scene,
converted: dgn_import::Converted,
naming: &Naming,
) -> HashMap<String, String> {
let mut layers: HashMap<String, String> = HashMap::new();
for (name, color) in &converted.layers {
let doc = &scene.document;
let taken = |n: &str| doc.layers.iter().any(|l| l.name.eq_ignore_ascii_case(n));
let target = naming.name('l', name, &taken);
if !scene.document.layers.iter().any(|l| l.name.eq_ignore_ascii_case(&target)) {
let mut layer = codec::tables::Layer::new(target.as_str());
layer.handle = scene.document.allocate_handle();
layer.color = *color;
let _ = scene.document.layers.add(layer);
}
layers.insert(name.clone(), target);
}
let mut styles: HashMap<String, String> = HashMap::new();
for (name, font) in &converted.styles {
let doc = &scene.document;
let taken = |n: &str| doc.text_styles.iter().any(|s| s.name.eq_ignore_ascii_case(n));
let target = naming.name('s', name, &taken);
if !scene.document.text_styles.iter().any(|s| s.name.eq_ignore_ascii_case(&target)) {
let mut style = codec::tables::TextStyle::new(target.as_str());
style.handle = scene.document.allocate_handle();
style.font_file = font.clone();
let _ = scene.document.text_styles.add(style);
}
styles.insert(name.clone(), target);
}
let mut blocks: HashMap<String, String> = HashMap::new();
let mut claimed: Vec<String> = Vec::new();
for (name, _) in &converted.blocks {
let doc = &scene.document;
let taken = |n: &str| {
doc.block_records.iter().any(|b| b.name.eq_ignore_ascii_case(n))
|| claimed.iter().any(|c| c.eq_ignore_ascii_case(n))
};
let target = naming.name('b', name, &taken);
claimed.push(target.clone());
blocks.insert(name.clone(), target);
}
let fix = |mut entity: codec::EntityType| {
let common = entity.common_mut();
if let Some(layer) = layers.get(&common.layer) {
common.layer = layer.clone();
}
match &mut entity {
codec::EntityType::Text(t) => {
if let Some(s) = styles.get(&t.style) {
t.style = s.clone();
}
}
codec::EntityType::MText(t) => {
if let Some(s) = styles.get(&t.style) {
t.style = s.clone();
}
}
codec::EntityType::Insert(insert) => {
if let Some(b) = blocks.get(&insert.block_name) {
insert.block_name = b.clone();
}
}
_ => {}
}
entity
};
for (name, entities) in converted.blocks {
let target = &blocks[&name];
if scene.document.block_records.get(target).is_some() {
continue;
}
let entities = entities.into_iter().map(&fix).collect();
let _ = scene.define_block_from_owned_entities(entities, target, glam::DVec3::ZERO);
}
for entity in converted.entities {
scene.add_entity(fix(entity));
}
layers
}
+1
View File
@@ -860,6 +860,7 @@ inventory::submit!(crate::command::CommandRegistration {
"SELECTIONCYCLING",
"UCSDETECT",
"SURFACEASSOCIATIVITY",
"DGNIMPORTMODE",
"LAYOUTCREATEVIEWPORT",
"TXT2MTXTCOMBINEMTEXT",
"TXT2MTXTTEXTORDER",
+36
View File
@@ -1223,6 +1223,7 @@ impl OpenCADStudio {
| "SELECTIONCYCLING"
| "UCSDETECT"
| "SURFACEASSOCIATIVITY"
| "DGNIMPORTMODE"
| "UCSORTHO"
| "UCSVIEW"
| "LAYOUTCREATEVIEWPORT"
@@ -1622,6 +1623,41 @@ impl OpenCADStudio {
}
return Some(self.finish_dispatch(cmd));
}
if name == "DGNIMPORTMODE" {
// Where DGNIMPORT puts the model: 0 a new drawing, 1 the
// current one keeping its definitions, 2 the current one
// with prefixed names.
use crate::modules::insert::dgn_import::{set_settings, settings};
let mut s = settings();
let current = s.mode;
match value
.as_deref()
.map(|v| v.trim().parse::<u8>().ok().filter(|v| *v <= 2))
{
Some(Some(mode)) => {
if current != mode {
s.mode = mode;
set_settings(s);
self.save_config();
}
}
Some(None) => {
self.command_line
.push_error("Requires an integer between 0 and 2.");
self.command_line.push_output(&format!(
"Enter new value for DGNIMPORTMODE <{current}>:"
));
self.pending_setvar = Some(name.clone());
}
None => {
self.command_line.push_output(&format!(
"Enter new value for DGNIMPORTMODE <{current}>:"
));
self.pending_setvar = Some(name.clone());
}
}
return Some(self.finish_dispatch(cmd));
}
if name == "SURFACEASSOCIATIVITY" {
use crate::scene::model::sweep_model;
let current = i16::from(sweep_model::surface_associativity());
+13
View File
@@ -2277,6 +2277,7 @@ impl OpenCADStudio {
// The DGN Import window, one field per call: "path=<file>" (as
// Change… picks it), "model=<n>", "target=new|current",
// "conflict=prefix|ignore", "units=master|sub", "explode=on|off",
// "references=translate|ignore|underlay", "existing=prompt|overwrite|keep",
// "mapping=layer|linetype|lineweight|color", "ok" or "cancel".
"dgn_import_dialog" => {
use crate::ui::window::import_dialogs::ImportDialogMsg as I;
@@ -2314,6 +2315,18 @@ impl OpenCADStudio {
_ => return Err(bad()),
}),
"explode" => I::DgnExplode(on(value)?),
"references" => I::DgnReferences(match value {
"translate" => crate::modules::insert::dgn_import::ReferenceMode::Translate,
"ignore" => crate::modules::insert::dgn_import::ReferenceMode::Ignore,
"underlay" => crate::modules::insert::dgn_import::ReferenceMode::Underlay,
_ => return Err(bad()),
}),
"existing" => I::DgnExisting(match value {
"prompt" => crate::modules::insert::dgn_import::ExistingReference::Prompt,
"overwrite" => crate::modules::insert::dgn_import::ExistingReference::Overwrite,
"keep" => crate::modules::insert::dgn_import::ExistingReference::Keep,
_ => return Err(bad()),
}),
"mapping" => I::DgnMappingTab(match value {
"layer" => 0,
"linetype" => 1,
+3
View File
@@ -519,6 +519,8 @@ pub struct UserSettings {
/// PDFSHXTEXT's recognition settings (fonts, threshold, PDFSHXLAYER,
/// PDFSHXBESTFONT, PDFSHXTEXTSETTINGS).
pub pdf_shx_text: crate::modules::insert::pdf_shx_text::ShxTextSettings,
/// DGNIMPORTMODE and the DGN Import window's last choices.
pub dgn_import: crate::modules::insert::dgn_import::DgnImportSettings,
/// Nested-copy symbol handling: false inserts, true binds.
pub ncopy_bind: bool,
/// Last Options page; unknown saved names fall back without rejecting the config.
@@ -999,6 +1001,7 @@ impl Default for UserSettings {
ucs_view: true,
layout_create_viewport: true,
pdf_shx_text: Default::default(),
dgn_import: Default::default(),
ncopy_bind: false,
cursor_type: CursorType::Crosshair,
crosshair_color: None,
+2
View File
@@ -864,6 +864,7 @@ impl OpenCADStudio {
ucs_view: crate::modules::view::view_cmd::ucs_view(),
layout_create_viewport: crate::scene::layout_create_viewport(),
pdf_shx_text: crate::modules::insert::pdf_shx_text::settings(),
dgn_import: crate::modules::insert::dgn_import::settings(),
ncopy_bind: self.ncopy_bind,
cursor_type: self.cursor_type,
crosshair_color: self.crosshair_color,
@@ -1013,6 +1014,7 @@ impl OpenCADStudio {
crate::modules::view::view_cmd::set_ucs_view(s.ucs_view);
crate::scene::set_layout_create_viewport(s.layout_create_viewport);
crate::modules::insert::pdf_shx_text::set_settings(s.pdf_shx_text.clone());
crate::modules::insert::dgn_import::set_settings(s.dgn_import);
self.ncopy_bind = s.ncopy_bind;
self.cursor_type = s.cursor_type;
self.crosshair_color = s.crosshair_color;
+4 -1
View File
@@ -3494,7 +3494,10 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static
"External DGN references" => Some(("dgn-import", "references")),
"Bind as block / xref" => Some(("dgn-import", "bind")),
"Attach as DGN underlay" => Some(("dgn-import", "attach")),
"Reference attachments of DGN files are not read; they are left out." => Some(("dgn-import", "references-note")),
"When the translated drawing exists" => Some(("dgn-import", "existing")),
"Prompt to overwrite" => Some(("dgn-import", "prompt-overwrite")),
"Overwrite without prompting" => Some(("dgn-import", "overwrite")),
"Do not overwrite" => Some(("dgn-import", "keep-existing")),
"Property mapping" => Some(("dgn-import", "mapping")),
"Standard mapping setup." => Some(("dgn-import", "mapping-standard")),
"The preview shows the selected setup's effect on this file." => Some(("dgn-import", "mapping-note")),
File diff suppressed because it is too large. Load diff
+11 -1
View File
@@ -651,7 +651,17 @@ pub fn prepare_xref_definition(
request: &XrefAttachRequest,
host_file: Option<&std::path::Path>,
) -> String {
let stem = path_to_block_name(&request.path);
prepare_named_xref_definition(scene, request, host_file, &path_to_block_name(&request.path))
}
/// [`prepare_xref_definition`] under a chosen name instead of the file's.
pub fn prepare_named_xref_definition(
scene: &mut Scene,
request: &XrefAttachRequest,
host_file: Option<&std::path::Path>,
stem: &str,
) -> String {
let stem = stem.to_string();
if let Some(existing) = existing_reference(scene, &stem) {
return existing;
}
+253 -47
View File
@@ -6,8 +6,8 @@
use std::collections::HashMap;
use super::model::{
arc_cubics, bspline_points, dgn_color_table, paths_bounds, scaled_elements, DgnCollector,
DgnElement, DgnGeom, DgnImport, Path, PathBuilder, Segment, Sheet, SubPath, Text,
arc_cubics, bspline_points, dgn_color_table, paths_bounds, scaled_elements, By, DgnCollector,
DgnColor, DgnElement, DgnGeom, DgnImport, Path, PathBuilder, Segment, Sheet, SubPath, Text,
DGN_DEFAULT_COLORS,
};
@@ -49,6 +49,42 @@ pub fn is_v7(bytes: &[u8]) -> bool {
bytes.len() > 1256 && (bytes[1] & 0x7f) == 9 && (bytes[0] & 0x3f) == 8
}
/// A 3D design file: the header element's 3D flag. Its points have a z,
/// and planar elements carry their plane as a quaternion.
fn is_3d(bytes: &[u8]) -> bool {
bytes[0] & 0x40 != 0
}
/// The rows of the rotation a 3D element's quaternion (w, x, y, z as
/// signed 1.31 fractions) stands for: the element's own x, y and z axes.
fn quaternion_axes(e: &[u8], at: usize) -> Option<[[f64; 3]; 3]> {
let q = |k: usize| int32(e, at + 4 * k).map(|v| v as f64 / 2_147_483_648.0);
let (w, x, y, z) = (q(0)?, q(1)?, q(2)?, q(3)?);
// The rotation matrix's columns are the axes.
let m = [
[x * x - y * y - z * z + w * w, 2.0 * (z * w + x * y), 2.0 * (x * z - y * w)],
[2.0 * (x * y - z * w), -x * x + y * y - z * z + w * w, 2.0 * (x * w + y * z)],
[2.0 * (x * z + y * w), 2.0 * (y * z - x * w), -x * x - y * y + z * z + w * w],
];
Some([0, 1, 2].map(|c| [m[0][c], m[1][c], m[2][c]]))
}
/// A cell name in Radix-50: two words of three characters each.
fn radix50(e: &[u8], at: usize) -> String {
const SET: &[u8] = b" ABCDEFGHIJKLMNOPQRSTUVWXYZ$.?0123456789";
let mut name = String::new();
for k in 0..2 {
let Some(mut word) = uint16(e, at + 2 * k).map(usize::from) else { break };
let mut chars = [0u8; 3];
for c in chars.iter_mut().rev() {
*c = SET.get(word % 40).copied().unwrap_or(b' ');
word /= 40;
}
name.extend(chars.iter().map(|c| char::from(*c)));
}
name.trim().to_string()
}
struct Units {
uor_per_sub: f64,
sub_per_master: f64,
@@ -136,11 +172,18 @@ struct Instance {
origin: [f64; 2],
}
/// How deep cells inside cells are read.
const MAX_CELL_DEPTH: usize = 16;
/// Reads a run of elements into raw geometry: plain elements, complex
/// chains and shapes (joined), B-splines, text and shared cell instances.
fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
/// chains and shapes (joined), B-splines, text, cells and shared cell
/// instances. In a 3D file (`d3`) points have a z and planar elements their
/// plane; the drawn geometry is their plan.
fn read_run(run: &[&[u8]], colors: &[[u8; 3]], d3: bool, depth: usize) -> Raw {
let mut raw = Raw::default();
let mut spline: Option<(usize, usize, [u8; 3], f64)> = None;
// An open B-spline curve: order, pole count, colour, closed, and the
// header as the element it imports as.
let mut spline: Option<(usize, usize, [u8; 3], bool, DgnElement)> = None;
let mut knots: Vec<f64> = Vec::new();
// A complex shape or chain collects its components into one path.
let mut complex: Option<(
@@ -203,31 +246,82 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
}
};
let mut collect = DgnCollector::default();
for e in run {
let mut index = 0;
while index < run.len() {
let e = run[index];
index += 1;
let kind = e[1] & 0x7f;
if e[1] & 0x80 != 0 || e.len() < 36 {
continue;
}
// An element that is no component ends the complex elements still
// open.
if e[0] & 0x80 == 0 {
collect.close();
}
let symbology = uint16(e, 34).unwrap_or(0);
let color = colors[(symbology >> 8) as usize];
let element = |geom: DgnGeom| DgnElement {
level: level(e) as u32,
color: Some(color),
weight: Some(((symbology >> 3) & 31) as u32),
style: Some((symbology & 7) as u32),
color: By::Own(DgnColor {
index: (symbology >> 8) as u32,
table: color,
rgb: color,
}),
weight: By::Own(((symbology >> 3) & 31) as u32),
style: By::Own((symbology & 7) as u32),
geom,
filled: fill_index(e).is_some(),
};
// One pixel wide, as V8 models draw: the element weight is a
// lineweight, not shown while lineweights are off.
let stroke = Some((color, -1.0));
let fill = fill_index(e).map(|i| colors[i as usize]);
let int_pt =
|i: usize| -> Option<[f64; 2]> { Some([int32(e, i)? as f64, int32(e, i + 4)? as f64]) };
// A point as the file holds it: two whole UORs, or three in 3D.
let pt3 = |i: usize| -> Option<[f64; 3]> {
Some([
int32(e, i)? as f64,
int32(e, i + 4)? as f64,
if d3 { int32(e, i + 8)? as f64 } else { 0.0 },
])
};
let plan = |p: [f64; 3]| [p[0], p[1]];
let step = if d3 { 12 } else { 8 };
match kind {
// A text node: its count of text components.
// A cell: its components follow as complex elements, as many as
// its total length (36, the words after its first 38 bytes)
// covers; they are already placed, so the cell keeps them as
// they are. Nesting past `MAX_CELL_DEPTH` is left out.
2 => {
let total = 38 + uint16(e, 36).unwrap_or(0) as usize * 2;
let mut left = total.saturating_sub(e.len());
let start = index;
while left > 0 && index < run.len() && run[index][0] & 0x80 != 0 {
left = left.saturating_sub(run[index].len());
index += 1;
}
if depth >= MAX_CELL_DEPTH {
continue;
}
let inner = read_run(&run[start..index], colors, d3, depth + 1);
raw.paths.extend(inner.paths);
raw.texts.extend(inner.texts);
raw.instances.extend(inner.instances);
collect.push(element(DgnGeom::CellGroup {
name: radix50(e, 38),
parts: inner.elements,
}));
}
// A text node: its count of text components, justification
// (45), line spacing (46) and origin (62, or 74 in 3D).
7 => collect.open(
uint16(e, 38).unwrap_or(0) as usize,
element(DgnGeom::TextNode(Vec::new())),
element(DgnGeom::TextNode {
lines: Vec::new(),
origin: pt3(if d3 { 74 } else { 62 }),
just: e.get(45).copied().unwrap_or(0),
line_spacing: int32(e, 46).map(|v| v as f64),
}),
),
12 | 14 => {
let n = uint16(e, 38).unwrap_or(0) as usize;
@@ -243,8 +337,9 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
}
}
3 => {
if let (Some(a), Some(b)) = (int_pt(36), int_pt(44)) {
collect.push(element(DgnGeom::Line(a, b)));
if let (Some(a3), Some(b3)) = (pt3(36), pt3(36 + step)) {
let (a, b) = (plan(a3), plan(b3));
collect.push(element(DgnGeom::Line(a3, b3)));
push(
&mut raw,
&mut complex,
@@ -261,9 +356,10 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
}
4 | 6 | 11 => {
let n = uint16(e, 36).unwrap_or(0) as usize;
let pts: Vec<[f64; 2]> = (0..n).filter_map(|k| int_pt(38 + k * 8)).collect();
let pts3: Vec<[f64; 3]> = (0..n).filter_map(|k| pt3(38 + k * step)).collect();
let pts: Vec<[f64; 2]> = pts3.iter().map(|p| plan(*p)).collect();
if pts.len() >= 2 {
collect.push(element(DgnGeom::Points(pts.clone())));
collect.push(element(DgnGeom::Points(pts3)));
push(
&mut raw,
&mut complex,
@@ -271,6 +367,69 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
);
}
}
// 3D ellipses and arcs: the axes from the quaternion (52 or
// 60), the centre as three doubles after it.
15 | 16 if d3 => {
let at = if kind == 15 { 36 } else { 44 };
let q = at + 16;
let (Some(a), Some(b), Some(axes), Some(cx), Some(cy), Some(cz)) = (
vax_double(e, at),
vax_double(e, at + 8),
quaternion_axes(e, q),
vax_double(e, q + 16),
vax_double(e, q + 24),
vax_double(e, q + 32),
) else {
continue;
};
let (start, sweep) = if kind == 15 {
(0.0, 360.0)
} else {
let (Some(st), Some(sw)) = (int32(e, 36), int32(e, 40)) else { continue };
let sw = sw as u32;
let mut sweep = if sw & 0x8000_0000 != 0 {
-((sw & 0x7fff_ffff) as f64)
} else {
sw as f64
} / 360000.0;
if sweep == 0.0 {
sweep = 360.0;
}
(st as f64 / 360000.0, sweep)
};
let [x, y, _] = axes;
collect.push(element(DgnGeom::Arc {
center: [cx, cy, cz],
u: x.map(|c| c * a),
v: y.map(|c| c * b),
start: start.to_radians(),
sweep: sweep.to_radians(),
}));
let pieces = arc_cubics(
[cx, cy],
a,
b,
x[1].atan2(x[0]),
start.to_radians(),
sweep.to_radians(),
);
let closed = sweep.abs() >= 360.0;
push(
&mut raw,
&mut complex,
Path {
subpaths: vec![SubPath {
segments: pieces
.into_iter()
.map(|[a, b, c, d]| Segment::Cubic(a, b, c, d))
.collect(),
closed,
}],
stroke,
fill: if closed { fill } else { None },
},
);
}
15 | 16 => {
let arc = if kind == 15 {
(|| {
@@ -312,9 +471,9 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
let turn = (r as f64 / 360000.0).to_radians();
let (c, s) = (turn.cos(), turn.sin());
collect.push(element(DgnGeom::Arc {
center: [ox, oy],
u: [a * c, a * s],
v: [-b * s, b * c],
center: [ox, oy, 0.0],
u: [a * c, a * s, 0.0],
v: [-b * s, b * c, 0.0],
start: start.to_radians(),
sweep: sweep.to_radians(),
}));
@@ -344,16 +503,30 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
);
}
17 => {
let (Some(width), Some(height), Some(rotation), Some(origin)) =
(int32(e, 38), int32(e, 42), int32(e, 46), int_pt(50))
// 2D: rotation (46), origin (50), count (58), characters
// (60); 3D: quaternion (46), origin (62), count (74),
// characters (76).
let rotation = if d3 {
quaternion_axes(e, 46).map(|[x, _, _]| (x[1].atan2(x[0]).to_degrees() * 360000.0).round() as i32)
} else {
int32(e, 46)
};
let (origin_at, count_at) = if d3 { (62, 74) } else { (50, 58) };
let (Some(width), Some(height), Some(rotation), Some(origin3)) =
(int32(e, 38), int32(e, 42), rotation, pt3(origin_at))
else {
continue;
};
let n = e.get(58).copied().unwrap_or(0) as usize;
let Some(chars) = e.get(60..60 + n) else {
let origin = plan(origin3);
let n = e.get(count_at).copied().unwrap_or(0) as usize;
let Some(chars) = e.get(count_at + 2..count_at + 2 + n) else {
continue;
};
let (height, width) = (height as f64 * 6.0 / 1000.0, width as f64 * 6.0 / 1000.0);
// Sizes in whole UORs (the multipliers are 1000/6 of one).
let (height, width) = (
(height as f64 * 6.0 / 1000.0).round(),
(width as f64 * 6.0 / 1000.0).round(),
);
let text = Text {
text: String::from_utf8_lossy(chars)
.trim_end_matches('\0')
@@ -365,26 +538,36 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
color,
font: "txt".to_string(),
};
// A V7 font is drawn monospaced: the text is as long as its
// characters times their width.
collect.push(element(DgnGeom::Text {
text: text.text.clone(),
origin,
origin: origin3,
height,
width_factor: text.width_factor,
length: text.text.chars().count() as f64 * width,
rotation: text.rotation,
just: e[37],
font: Some(e[36] as u32),
style: None,
}));
raw.texts.push(text);
}
27 => {
// B-spline curve header: order, pole count.
let order = ((e.get(40).copied().unwrap_or(0) & 0x0f) + 2) as usize;
// B-spline curve header: order and closure (40), pole count
// (42), knot count (44); the curve imports with the header's
// level and symbology.
let flags = e.get(40).copied().unwrap_or(0);
let order = ((flags & 0x0f) + 2) as usize;
let poles = uint16(e, 42).unwrap_or(0) as usize;
spline = Some((order, poles, color, -1.0));
knots.clear();
let header = element(DgnGeom::Chain(Vec::new()));
spline = Some((order, poles, color, flags & 0x80 != 0, header));
knots = vec![f64::NAN; uint16(e, 44).unwrap_or(0) as usize];
}
26 => {
// Interior knots as fractions of the parameter range.
let n = spline.map(|s| s.1.saturating_sub(s.0)).unwrap_or(0);
// Knots as fractions of the parameter range; a closed
// curve's list also holds its ends.
let n = knots.len();
knots = (0..n)
.filter_map(|k| int32(e, 36 + k * 4))
.map(|v| v as u32 as f64 / 2_147_483_648.0)
@@ -392,11 +575,17 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
}
21 => {
let n = uint16(e, 36).unwrap_or(0) as usize;
let poles: Vec<[f64; 2]> = (0..n).filter_map(|k| int_pt(38 + k * 8)).collect();
if let Some((order, count, color, width)) = spline.take() {
let poles3: Vec<[f64; 3]> = (0..n).filter_map(|k| pt3(38 + k * step)).collect();
let poles: Vec<[f64; 2]> = poles3.iter().map(|p| plan(*p)).collect();
if let Some((order, count, color, closed, header)) = spline.take() {
if poles.len() == count && count >= order {
let interior = if knots.len() == count - order {
knots.clone()
let stored: Vec<f64> = knots
.iter()
.copied()
.filter(|k| *k > 1e-9 && *k < 1.0 - 1e-6)
.collect();
let interior = if stored.len() == count - order {
stored
} else {
(1..=count - order)
.map(|k| k as f64 / (count - order + 1) as f64)
@@ -407,13 +596,18 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
full.extend(vec![1.0; order]);
let pts = bspline_points(order, &poles, &full, 24 * count);
collect.push(DgnElement {
color: Some(color),
..element(DgnGeom::Points(pts.clone()))
geom: DgnGeom::Spline {
degree: order - 1,
knots: full,
poles: poles3.clone(),
closed,
},
..header
});
push(
&mut raw,
&mut complex,
polyline(&pts, false, Some((color, width)), None),
polyline(&pts, false, Some((color, -1.0)), None),
);
}
}
@@ -430,21 +624,32 @@ fn read_run(run: &[&[u8]], colors: &[[u8; 3]]) -> Raw {
.to_string()
})
.unwrap_or_default();
// A 3D instance holds a 3×3 matrix (its plan part and the z
// scale are used) and a z.
let (r1, zz) = if d3 { (100, 140) } else { (92, 0) };
let (Some(m0), Some(m1), Some(m2), Some(m3), Some(ox), Some(oy)) = (
vax_double(e, 76),
vax_double(e, 84),
vax_double(e, 92),
vax_double(e, 100),
vax_double(e, r1),
vax_double(e, r1 + 8),
le_i32(e, 148),
le_i32(e, 152),
) else {
continue;
};
let (oz, z_scale) = if d3 {
(
le_i32(e, 156).unwrap_or(0) as f64,
vax_double(e, zz).filter(|z| *z != 0.0).unwrap_or(1.0),
)
} else {
(0.0, 1.0)
};
collect.push(element(DgnGeom::Cell {
name: name.clone(),
m: [m0, m1, m2, m3],
origin: [ox as f64, oy as f64],
z_scale: 1.0,
origin: [ox as f64, oy as f64, oz],
z_scale,
}));
raw.instances.push(Instance {
name,
@@ -647,14 +852,14 @@ pub fn model(bytes: &[u8], hidden: &[String]) -> Option<Sheet> {
while j < all.len() && all[j][0] & 0x80 != 0 {
j += 1;
}
defs.insert(name, read_run(&all[i + 1..j], &colors));
defs.insert(name, read_run(&all[i + 1..j], &colors, is_3d(bytes), 0));
i = j;
continue;
}
top.push(e);
i += 1;
}
let raw = read_run(&top, &colors);
let raw = read_run(&top, &colors, is_3d(bytes), 0);
let per_unit = u.uor_per_sub * u.sub_per_master;
let m: Affine = [
1.0 / per_unit,
@@ -721,7 +926,7 @@ pub fn import(bytes: &[u8]) -> Option<DgnImport> {
while j < all.len() && all[j][0] & 0x80 != 0 {
j += 1;
}
let def = read_run(&all[i + 1..j], &colors).elements;
let def = read_run(&all[i + 1..j], &colors, is_3d(bytes), 0).elements;
cells.push((name, scaled_elements(&def, s, [0.0, 0.0])));
i = j;
continue;
@@ -729,7 +934,7 @@ pub fn import(bytes: &[u8]) -> Option<DgnImport> {
top.push(e);
i += 1;
}
let raw = read_run(&top, &colors);
let raw = read_run(&top, &colors, is_3d(bytes), 0);
let levels = (0..64u32)
.map(|l| {
let name = names.get(&(l as u8)).cloned().unwrap_or_else(|| l.to_string());
@@ -743,5 +948,6 @@ pub fn import(bytes: &[u8]) -> Option<DgnImport> {
sub_per_master: u.sub_per_master,
unit_names: (unit_name(bytes, 1120), unit_name(bytes, 1122)),
v7: true,
..Default::default()
})
}
+408 -33
View File
@@ -8,8 +8,9 @@ use std::collections::HashMap;
use std::io::Read;
use super::model::{
arc_cubics, dgn_color_table, paths_bounds, scaled_elements, DgnCollector, DgnElement, DgnGeom,
DgnImport, Path, PathBuilder, Segment, Sheet, SubPath, Text, DGN_DEFAULT_COLORS,
arc_cubics, bspline_points, dgn_color_table, paths_bounds, scaled_elements, By, DgnCollector,
DgnColor, DgnElement, DgnGeom, DgnImport, DgnReference, Path, PathBuilder, Segment, Sheet,
SubPath, Text, DGN_DEFAULT_COLORS,
};
// ── Compound file ───────────────────────────────────────────────────────────
@@ -208,16 +209,22 @@ impl<'a> Cfb<'a> {
}
}
/// Far above any real element stream; stops a crafted one from inflating
/// until memory runs out.
const STREAM_LIMIT: u64 = 512 << 20;
/// A DGN stream: raw, or zlib data after a 16-byte header.
fn inflate(data: &[u8]) -> Vec<u8> {
// Far above any real element stream; stops a crafted one from
// inflating until memory runs out.
const STREAM_LIMIT: u64 = 512 << 20;
inflate_at_most(data, STREAM_LIMIT)
}
/// [`inflate`] stopping after `limit` bytes.
fn inflate_at_most(data: &[u8], limit: u64) -> Vec<u8> {
for skip in [16usize, 0] {
if let Some(z) = data.get(skip..) {
let mut out = Vec::new();
if flate2::read::ZlibDecoder::new(z)
.take(STREAM_LIMIT)
.take(limit)
.read_to_end(&mut out)
.is_ok()
&& !out.is_empty()
@@ -277,6 +284,34 @@ fn f64_at(e: &[u8], at: usize) -> Option<f64> {
Some(f64::from_le_bytes(e.get(at..at + 8)?.try_into().ok()?))
}
/// The text style a text element uses: the id in its text style linkage
/// (the four bytes after `04 20 e6 04 00 00`).
fn text_style_id(e: &[u8]) -> Option<u32> {
let at = e.windows(6).position(|w| w == [0x04, 0x20, 0xe6, 0x04, 0x00, 0x00])? + 6;
u32_at(e, at)
}
/// The text style table (the table entries after a header of table 3):
/// each style's id and name.
fn text_style_table(nm: &[&[u8]]) -> Vec<(u32, String)> {
let mut out = Vec::new();
let mut table = 0;
for e in nm {
match kind(e) {
96 => table = u32_at(e, 12).unwrap_or(0),
95 if table == 3 => {
if let (Some(id), Some(name)) = (u32_at(e, 32), marked_string(e, 32)) {
if !out.iter().any(|(i, _)| *i == id) {
out.push((id, name));
}
}
}
_ => {}
}
}
out
}
/// A string stored after the "ff fe 01 00" marker, when the element has one.
fn marked_string(e: &[u8], from: usize) -> Option<String> {
let i = e
@@ -384,6 +419,99 @@ impl Styles {
.copied()
.unwrap_or([255, 255, 255])
}
/// The colour word as an element's colour: the level's (0xFFFFFFFF),
/// the enclosing cell's (0xFFFFFFFE), or a table index (low byte) with
/// the table entry and the colour drawn.
fn color_word(&self, e: &[u8]) -> By<DgnColor> {
match u32_at(e, 52) {
None | Some(u32::MAX) => By::Level,
Some(0xFFFF_FFFE) => By::Cell,
Some(word) => {
let index = word & 0xff;
By::Own(DgnColor {
index,
table: self
.colors
.get(index as usize)
.copied()
.unwrap_or([255, 255, 255]),
rgb: self.color(e),
})
}
}
}
}
/// A B-spline curve from its order and poles, with uniform knots. A closed
/// curve (its last pole repeating the first) is periodic: its distinct
/// poles wrap around with knots (i + 1) / (count + 1), and the curve is
/// clamped at both ends of its domain by knot insertion.
fn bspline_geom(order: usize, poles: Vec<[f64; 3]>, closed: bool) -> DgnGeom {
let degree = order - 1;
let distinct = poles.len() - usize::from(closed && poles.first() == poles.last());
if !closed || distinct < order {
let interior = poles.len() - order;
let mut knots = vec![0.0; order];
knots.extend((1..=interior).map(|k| k as f64 / (interior + 1) as f64));
knots.extend(vec![1.0; order]);
return DgnGeom::Spline {
degree,
knots,
poles,
closed,
};
}
let mut ctrl: Vec<[f64; 3]> = (0..distinct + degree).map(|i| poles[i % distinct]).collect();
let count = ctrl.len() + order;
let mut knots: Vec<f64> = (0..count).map(|i| (i + 1) as f64 / (count + 1) as f64).collect();
let (lo, hi) = (knots[degree], knots[ctrl.len()]);
let same = |a: f64, b: f64| (a - b).abs() < 1e-12;
// Knot insertion (Boehm) of t until it is a degree-fold knot.
let mut insert = |t: f64| loop {
let mult = knots.iter().filter(|k| same(**k, t)).count();
if mult >= degree {
return;
}
let Some(k) = knots.iter().rposition(|x| *x <= t + 1e-12) else {
return;
};
let mut next = Vec::with_capacity(ctrl.len() + 1);
for i in 0..=ctrl.len() {
if i + degree <= k {
next.push(ctrl[i]);
} else if i + mult > k {
next.push(ctrl[i - 1]);
} else {
let a = (t - knots[i]) / (knots[i + degree] - knots[i]);
next.push(std::array::from_fn(|c| (1.0 - a) * ctrl[i - 1][c] + a * ctrl[i][c]));
}
}
ctrl = next;
knots.insert(k + 1, t);
};
insert(lo);
insert(hi);
// The domain clamped: an order-fold knot at each end, the poles that
// span it.
let first = knots.iter().position(|k| same(*k, lo)).unwrap_or(1).max(1);
let last = knots.iter().rposition(|k| same(*k, hi)).unwrap_or(knots.len() - 1);
let mut clamped = vec![lo];
clamped.extend_from_slice(&knots[first..=last]);
clamped.push(hi);
let poles: Vec<[f64; 3]> = ctrl
.iter()
.skip(first - 1)
.take(clamped.len() - order)
.copied()
.collect();
let knots = clamped;
DgnGeom::Spline {
degree,
knots,
poles,
closed: true,
}
}
/// Plan geometry in UORs, and the shared cells it places.
@@ -554,19 +682,36 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
[q[0], q[1]]
};
let mut collect = DgnCollector::default();
// An open B-spline curve: order, pole count, closure and its header.
let mut spline: Option<(usize, usize, bool, DgnElement)> = None;
for (index, e) in run.iter().enumerate() {
// An element that is no component ends the complex elements still
// open.
if !is_component(e) {
collect.close();
}
if e.len() < 104 || styles.hidden.contains(&u32_at(e, 12).unwrap_or(0)) {
continue;
}
let color = styles.color(e);
// Colour and weight words: 0xFFFFFFFF takes the level's; line style
// 0x7FFFFFFF (or 0xFFFFFFFF).
// Colour and weight words: 0xFFFFFFFF takes the level's, 0xFFFFFFFE
// the enclosing cell's; line style 0x7FFFFFFF (or 0xFFFFFFFF) the
// level's, 0x7FFFFFFE the cell's.
let element = |geom: DgnGeom| DgnElement {
level: u32_at(e, 12).unwrap_or(0),
color: (u32_at(e, 52) != Some(u32::MAX)).then_some(color),
weight: u32_at(e, 48).filter(|w| *w != u32::MAX).map(|w| w & 31),
style: u32_at(e, 44).filter(|s| *s != u32::MAX && *s != 0x7FFF_FFFF),
color: styles.color_word(e),
weight: match u32_at(e, 48) {
None | Some(u32::MAX) => By::Level,
Some(0xFFFF_FFFE) => By::Cell,
Some(w) => By::Own(w & 31),
},
style: match u32_at(e, 44) {
None | Some(u32::MAX) | Some(0x7FFF_FFFF) => By::Level,
Some(0xFFFF_FFFE) | Some(0x7FFF_FFFE) => By::Cell,
Some(s) => By::Own(s),
},
geom,
filled: matches!(kind(e), 6 | 14) && e.windows(4).any(|w| w == [0x07, 0x10, 0x41, 0x00]),
};
let stroke = Some((color, -1.0));
let d3 = is_3d(e);
@@ -578,6 +723,9 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
if d3 { f64_at(e, at + 16)? } else { 0.0 },
])
};
// A point or vector placed in the model (3D kept for the import).
let at3 = |p: [f64; 3]| xf_point(xf, p);
let dir3 = |v: [f64; 3]| xf_vector(xf, v);
match kind(e) {
// A text node: grouped when its count is followed by that many
// text components.
@@ -587,7 +735,34 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
parts.iter().all(|p| p.len() >= 104 && kind(p) == 17 && is_component(p))
});
if texts {
collect.open(n, element(DgnGeom::TextNode(Vec::new())));
// 2D: justification 118, origin 152 (the node's
// justification point).
let origin = (!d3).then(|| p3(152)).flatten().map(at3);
collect.open(
n,
element(DgnGeom::TextNode {
lines: Vec::new(),
origin,
just: if d3 { 0 } else { e.get(118).copied().unwrap_or(0) },
line_spacing: None,
}),
);
}
}
// A cell (not shared): its components follow, flagged as such.
2 => {
let n = u32_at(e, 104).unwrap_or(0) as usize;
let parts = run
.get(index + 1..index + 1 + n)
.is_some_and(|parts| parts.iter().all(|p| is_component(p)));
if parts && n > 0 {
collect.open(
n,
element(DgnGeom::CellGroup {
name: marked_string(e, 104).unwrap_or_default(),
parts: Vec::new(),
}),
);
}
}
12 | 14 => {
@@ -602,7 +777,7 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
}
3 => {
if let (Some(a), Some(b)) = (p3(104), p3(if d3 { 128 } else { 120 })) {
collect.push(element(DgnGeom::Line(plan(a), plan(b))));
collect.push(element(DgnGeom::Line(at3(a), at3(b))));
push(
&mut raw,
&mut complex,
@@ -620,12 +795,10 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
4 | 6 | 11 => {
let n = u32_at(e, 104).unwrap_or(0) as usize;
let stride = if d3 { 24 } else { 16 };
let pts: Vec<[f64; 2]> = (0..n)
.filter_map(|k| p3(112 + k * stride))
.map(plan)
.collect();
let pts3: Vec<[f64; 3]> = (0..n).filter_map(|k| p3(112 + k * stride)).collect();
let pts: Vec<[f64; 2]> = pts3.iter().map(|p| plan(*p)).collect();
if pts.len() >= 2 {
collect.push(element(DgnGeom::Points(pts.clone())));
collect.push(element(DgnGeom::Points(pts3.iter().map(|p| at3(*p)).collect())));
let mut pb = PathBuilder::default();
pb.move_to(pts[0]);
for p in &pts[1..] {
@@ -702,11 +875,11 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
};
let closed = sweep.abs() >= std::f64::consts::TAU - 1e-9;
{
let (pu, pv) = (axis(u), axis(v));
let (du, dv) = (dir3(u), dir3(v));
collect.push(element(DgnGeom::Arc {
center: plan(c),
u: [a * pu[0], a * pu[1]],
v: [b * pv[0], b * pv[1]],
center: at3(c),
u: du.map(|x| a * x),
v: dv.map(|x| b * x),
start,
sweep,
}));
@@ -726,7 +899,8 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
}
17 => {
// 3D: width 112, height 120, quaternion 144, origin 176, the
// characters after the string marker. 2D: angle 144, origin
// characters after the string marker, as many as the byte
// count at 110 holds. 2D: angle 144, origin
// 152, a byte count (with its 4-byte marker) at 110 and the
// characters from 174.
let placed = if d3 {
@@ -736,7 +910,18 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
f64_at(e, 120)?,
quat_axes(e, 144)?,
p3(176)?,
marked_string(e, 200)?,
// The byte count at 110 (with the 4-byte marker)
// ends the characters.
{
let count =
u16::from_le_bytes(e.get(110..112)?.try_into().ok()?) as usize;
let mark = e
.get(200..)?
.windows(4)
.position(|w| w == [0xff, 0xfe, 0x01, 0x00])?
+ 200;
marked_string(&e[..(mark + count.max(4)).min(e.len())], mark)?
},
))
})()
} else {
@@ -758,6 +943,16 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
let Some((width, height, (u, v), origin, text)) = placed else {
continue;
};
// 2D: the justification (108) and the length of the text box
// along the baseline (128).
let (just, length) = if d3 {
(2, 0.0)
} else {
(
e.get(108).copied().unwrap_or(2),
f64_at(e, 128).filter(|l| l.is_finite()).unwrap_or(0.0),
)
};
// The text's axes as the plan shows them: its baseline sets the
// angle, and each axis's plan length scales its size.
let (pu, pv) = (axis(u), axis(v));
@@ -769,11 +964,14 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
let width_factor = if height > 0.0 { width / height } else { 1.0 };
collect.push(element(DgnGeom::Text {
text: text.clone(),
origin: plan(origin),
origin: at3(origin),
height,
width_factor,
length: length * su,
rotation: pu[1].atan2(pu[0]),
just,
font: None,
style: text_style_id(e),
}));
raw.texts.push(Text {
text,
@@ -804,7 +1002,7 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
collect.push(element(DgnGeom::Cell {
name: name.clone(),
m: [m[0], m[1], m[3], m[4]],
origin: [o[0], o[1]],
origin: o,
z_scale: m[8],
}));
raw.instances.push(Instance {
@@ -812,6 +1010,58 @@ fn read_run(run: &[&[u8]], styles: &Styles, xf: &Xf) -> Raw {
xf: xf_compose(xf, &local),
});
}
27 => {
// B-spline curve header: order and closure in the word at
// 108, pole count 112; its poles follow (type 21).
let Some(&[lo, hi]) = e.get(108..110) else {
continue;
};
let flags = u16::from_le_bytes([lo, hi]);
// A curve before it that never got its poles still takes
// its place in an open cell.
let unread = spline.replace((
((flags & 0x0f) + 2) as usize,
u32_at(e, 112).unwrap_or(0) as usize,
flags & 0x0180 != 0,
element(DgnGeom::Chain(Vec::new())),
));
if unread.is_some() {
collect.skip();
}
}
21 => {
let n = u32_at(e, 104).unwrap_or(0) as usize;
let stride = if d3 { 24 } else { 16 };
let poles: Vec<[f64; 3]> = (0..n).filter_map(|k| p3(112 + k * stride)).collect();
if let Some((order, count, closed, header)) = spline.take() {
if poles.len() == count && count >= order && order >= 2 {
let poles: Vec<[f64; 3]> = poles.iter().map(|p| at3(*p)).collect();
let geom = bspline_geom(order, poles, closed);
if let DgnGeom::Spline { degree, knots, poles, .. } = &geom {
let plan_poles: Vec<[f64; 2]> =
poles.iter().map(|p| [p[0], p[1]]).collect();
let pts = bspline_points(degree + 1, &plan_poles, knots, 24 * count);
let mut pb = PathBuilder::default();
pb.move_to(pts[0]);
for p in &pts[1..] {
pb.line_to(*p);
}
push(
&mut raw,
&mut complex,
Path {
subpaths: pb.finish(),
stroke,
fill: None,
},
);
}
collect.push(DgnElement { geom, ..header });
} else {
collect.skip();
}
}
}
_ => {}
}
}
@@ -925,6 +1175,11 @@ fn units(header: &[u8]) -> (f64, f64) {
(master, sub)
}
/// How many bytes the streams of one file may inflate to in all.
fn inflate_budget(cfb: &Cfb) -> usize {
cfb.b.len().saturating_mul(64).max(256 << 20)
}
/// Models of the file: (name, graphic stream, header stream).
fn models(cfb: &Cfb) -> Vec<(String, Vec<u8>, Vec<u8>)> {
let streams = cfb.streams();
@@ -939,7 +1194,7 @@ fn models(cfb: &Cfb) -> Vec<(String, Vec<u8>, Vec<u8>)> {
// scales with the file (×64 covers any real compression ratio, so
// legitimate files never trip it) with a 256 MiB floor for small ones;
// models past the budget are dropped, the earlier ones still load.
let total_limit = cfb.b.len().saturating_mul(64).max(256 << 20);
let total_limit = inflate_budget(cfb);
let mut total = 0usize;
let mut out = Vec::new();
for dir in dirs {
@@ -983,12 +1238,14 @@ fn level_table(nm: &[&[u8]]) -> Vec<(u32, String, u32)> {
out
}
/// The level table with the file's own names.
/// The level table with the file's own names: the first one (the file's;
/// a later level table holds a reference attachment's levels).
fn level_table_raw(nm: &[&[u8]]) -> Vec<(u32, String, u32)> {
let mut out = Vec::new();
let mut in_levels = false;
for e in nm {
match kind(e) {
96 if u32_at(e, 12) == Some(1) && !out.is_empty() => break,
96 => in_levels = u32_at(e, 12) == Some(1),
95 if in_levels && e.len() >= 80 => {
let (Some(id), Some(color)) = (u32_at(e, 32), u32_at(e, 72)) else {
@@ -1153,16 +1410,114 @@ fn unit_name(metres: f64) -> String {
.unwrap_or_default()
}
/// A design model (not a sheet): the model type byte of its header (4105)
/// is 2 for a sheet.
fn is_design(header: &[u8]) -> bool {
header.get(4105) != Some(&2)
}
/// The models DGNIMPORT offers: the design models (sheets are not
/// imported).
pub fn design_model_names(bytes: &[u8]) -> Option<Vec<String>> {
let cfb = Cfb::open(bytes)?;
let names: Vec<String> = models(&cfb)
.into_iter()
.filter(|m| is_design(&m.2))
.map(|m| m.0)
.collect();
(!names.is_empty()).then_some(names)
}
/// The control stream (Dgn^C) of model `k` in the order `models` lists
/// them, inflated within what is left of the file's budget (`used` bytes
/// are taken by the models already read).
fn control_stream(cfb: &Cfb, k: usize, used: usize) -> Vec<u8> {
let streams = cfb.streams();
let mut dirs: Vec<&str> = streams
.iter()
.filter_map(|(p, _)| p.strip_suffix("/Dgn^G/$1"))
.collect();
dirs.sort();
let Some(dir) = dirs.get(k) else {
return Vec::new();
};
let left = inflate_budget(cfb).saturating_sub(used) as u64;
if left == 0 {
return Vec::new();
}
streams
.iter()
.find(|(p, _)| *p == format!("{dir}/Dgn^C/$1"))
.map(|(_, e)| inflate_at_most(&cfb.stream(e), left.min(STREAM_LIMIT)))
.unwrap_or_default()
}
/// Every string of an element stored after the "ff fe 01 00" marker, with
/// the subtype of the string linkage before it (2 file name, 3 full path,
/// 4 logical name).
fn linked_strings(e: &[u8]) -> Vec<(u32, String)> {
let mut out = Vec::new();
let mut from = 0;
while let Some(i) = e
.get(from..)
.and_then(|rest| rest.windows(4).position(|w| w == [0xff, 0xfe, 0x01, 0x00]))
{
let at = from + i;
let end = e[at + 4..]
.iter()
.position(|&c| c == 0 || c < 0x20)
.map(|n| at + 4 + n)
.unwrap_or(e.len());
let subtype = at.checked_sub(8).and_then(|p| u32_at(e, p)).unwrap_or(0);
out.push((subtype, String::from_utf8_lossy(&e[at + 4..end]).to_string()));
from = end.max(at + 4);
}
out
}
/// The reference attachments (type 100) of a model's control stream: the
/// file (full path, else file name), origin 192, rotation rows from 216,
/// scale 288, in UORs of the model.
fn references(control: &[u8]) -> Vec<DgnReference> {
elements(control)
.into_iter()
.filter(|e| kind(e) == 100 && e.len() >= 296)
.filter_map(|e| {
let strings = linked_strings(e);
let file = strings
.iter()
.find(|s| s.0 == 3)
.or_else(|| strings.iter().find(|s| s.0 == 2))?
.1
.clone();
Some(DgnReference {
file,
model: strings
.iter()
.find(|s| s.0 == 1)
.map(|s| s.1.clone())
.unwrap_or_default(),
origin: [f64_at(e, 192)?, f64_at(e, 200)?, f64_at(e, 208)?],
scale: f64_at(e, 288).filter(|s| *s > 0.0).unwrap_or(1.0),
rotation: f64_at(e, 240)?.atan2(f64_at(e, 216)?),
})
})
.collect()
}
/// The named model element by element (DGNIMPORT): in master units with
/// the global origin at 0,0, shared cell definitions in master units, and
/// every level by id with its own name and colour.
pub fn import(bytes: &[u8], name: &str) -> Option<DgnImport> {
let cfb = Cfb::open(bytes)?;
let all = models(&cfb);
let (_, graphics, header) = all
let designs: Vec<usize> = (0..all.len()).filter(|k| is_design(&all[*k].2)).collect();
let k = designs
.iter()
.find(|m| m.0.eq_ignore_ascii_case(name))
.or_else(|| all.first())?;
.copied()
.find(|k| all[*k].0.eq_ignore_ascii_case(name))
.or_else(|| designs.first().copied())?;
let (_, graphics, header) = &all[k];
let non_model = non_model(&cfb);
let nm = elements(&non_model);
let colors = nm
@@ -1184,6 +1539,7 @@ pub fn import(bytes: &[u8], name: &str) -> Option<DgnImport> {
(*id, (name.clone(), rgb))
})
.collect();
let level_order = table.iter().map(|l| l.0).collect();
let (per_unit, sub_uor) = units(header);
let s = 1.0 / per_unit;
let mut cells = Vec::new();
@@ -1195,8 +1551,12 @@ pub fn import(bytes: &[u8], name: &str) -> Option<DgnImport> {
while j < nm.len() && is_component(nm[j]) {
j += 1;
}
let def = read_run(&nm[i + 1..j], &styles, &IDENTITY).elements;
cells.push((cell, scaled_elements(&def, s, [0.0, 0.0])));
// The cell that draws points belongs to the writing program,
// not to the drawing: it is left out.
if !cell.eq_ignore_ascii_case("POINT_DISPLAY") {
let def = read_run(&nm[i + 1..j], &styles, &IDENTITY).elements;
cells.push((cell, scaled_elements(&def, s, [0.0, 0.0])));
}
i = j;
} else {
i += 1;
@@ -1210,13 +1570,28 @@ pub fn import(bytes: &[u8], name: &str) -> Option<DgnImport> {
(Some(n), Some(d)) if n > 0.0 && d > 0.0 => unit_name(d / n),
_ => String::new(),
};
let used = all.iter().map(|m| m.1.len() + m.2.len()).sum();
let references = references(&control_stream(&cfb, k, used))
.into_iter()
.map(|r| DgnReference {
origin: [
(r.origin[0] - origin[0]) * s,
(r.origin[1] - origin[1]) * s,
r.origin[2] * s,
],
..r
})
.collect();
Some(DgnImport {
elements: scaled_elements(&raw.elements, s, [-origin[0] * s, -origin[1] * s]),
cells,
levels,
level_order,
sub_per_master: per_unit / sub_uor,
unit_names: (metres(4180), metres(4196)),
v7: false,
references,
text_styles: text_style_table(&nm),
})
}
+15 -1
View File
@@ -20,7 +20,10 @@ use std::sync::{Arc, Mutex, OnceLock};
use codec::entities::UnderlayType;
pub use model::{scaled_elements, DgnElement, DgnGeom, DgnImport, Path, Segment, Sheet, SubPath};
pub use model::{
scaled_elements, By, DgnColor, DgnElement, DgnGeom, DgnImport, DgnReference, Path, Segment,
Sheet, SubPath, P3,
};
use super::pdf_raster::{source_bytes, PdfPage};
@@ -35,6 +38,17 @@ pub fn dgn_import(path: &str, item: &str) -> Option<DgnImport> {
}
}
/// The models DGNIMPORT offers: a V7 file's one model, a V8 file's design
/// models (sheet models are not imported).
pub fn dgn_import_models(path: &str) -> Option<Vec<String>> {
let bytes = source_bytes(path)?;
if dgn7::is_v7(&bytes) {
dgn7::model_names(&bytes)
} else {
dgn8::design_model_names(&bytes)
}
}
/// Sheet names (DWF) or model names (DGN) of a file.
pub fn item_names(kind: UnderlayType, path: &str) -> Option<Vec<String>> {
let bytes = source_bytes(path)?;
+172 -39
View File
@@ -532,55 +532,112 @@ pub fn dgn_color_table(e: &[u8], first: usize) -> Option<Vec<[u8; 3]>> {
Some(out)
}
/// A symbology attribute of a DGN element: the level's, the enclosing
/// cell's (V8 "by cell"), or its own.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum By<T> {
Level,
Cell,
Own(T),
}
impl<T> By<T> {
pub fn own(self) -> Option<T> {
match self {
By::Own(v) => Some(v),
_ => None,
}
}
}
/// An element's own colour: its index in the file's colour table, that
/// table entry's RGB and the RGB it is drawn in (a true colour can differ
/// from the table entry it names).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DgnColor {
pub index: u32,
pub table: [u8; 3],
pub rgb: [u8; 3],
}
/// A DGN element as drawing geometry (what DGNIMPORT converts): its level,
/// symbology and shape, in the units of the run that read it.
#[derive(Clone, Debug, PartialEq)]
pub struct DgnElement {
/// Level number (V7) or id (V8).
pub level: u32,
/// Colour; `None` takes the level's.
pub color: Option<[u8; 3]>,
/// Weight 0-31; `None` takes the level's.
pub weight: Option<u32>,
/// Line style; `None` takes the level's.
pub style: Option<u32>,
pub color: By<DgnColor>,
/// Weight 0-31.
pub weight: By<u32>,
/// Line style.
pub style: By<u32>,
pub geom: DgnGeom,
/// The element is a filled shape (it has a fill linkage).
pub filled: bool,
}
/// A point of a DGN element (z 0 in a 2D file).
pub type P3 = [f64; 3];
#[derive(Clone, Debug, PartialEq)]
pub enum DgnGeom {
Line([f64; 2], [f64; 2]),
/// A line string, curve or B-spline (sampled), or a shape (its points
/// end where they start).
Points(Vec<[f64; 2]>),
Line(P3, P3),
/// A line string, curve or shape (its points end where they start).
Points(Vec<P3>),
/// An elliptical arc: the point at parameter t is
/// `center + cos t · u + sin t · v`, from `start` over `sweep` (radians).
Arc {
center: [f64; 2],
u: [f64; 2],
v: [f64; 2],
center: P3,
u: P3,
v: P3,
start: f64,
sweep: f64,
},
/// A B-spline curve: degree, full knot vector and poles.
Spline {
degree: usize,
knots: Vec<f64>,
poles: Vec<P3>,
closed: bool,
},
/// A complex chain or shape: its components in order.
Chain(Vec<DgnGeom>),
Text {
text: String,
origin: [f64; 2],
/// The text's lower left (baseline start).
origin: P3,
height: f64,
width_factor: f64,
/// Length of the text along its baseline (its justification box).
length: f64,
rotation: f64,
/// DGN justification code (2 left bottom).
just: u8,
/// Font number (V7); `None` when the file's font is not read.
font: Option<u32>,
/// Text style id (V8), an entry of [`DgnImport::text_styles`].
style: Option<u32>,
},
/// A text node: its lines, its origin (the justification point, when
/// read), its justification and (V7) the space between its lines.
TextNode {
lines: Vec<DgnGeom>,
origin: Option<P3>,
just: u8,
line_spacing: Option<f64>,
},
/// A cell that is not shared: its name (empty when anonymous) and its
/// components, each with its own level and symbology.
CellGroup {
name: String,
parts: Vec<DgnElement>,
},
/// A text node: its lines.
TextNode(Vec<DgnGeom>),
/// A shared cell instance: x' = m[0]·x + m[1]·y + origin.x,
/// y' = m[2]·x + m[3]·y + origin.y.
Cell {
name: String,
m: [f64; 4],
origin: [f64; 2],
origin: P3,
/// Scale along z (1 in a 2D file).
z_scale: f64,
},
@@ -589,8 +646,8 @@ pub enum DgnGeom {
impl DgnGeom {
/// The geometry through x' = s·x + t (lengths scaled by `s`).
pub fn scaled(&self, s: f64, t: [f64; 2]) -> DgnGeom {
let p = |q: [f64; 2]| [q[0] * s + t[0], q[1] * s + t[1]];
let v = |q: [f64; 2]| [q[0] * s, q[1] * s];
let p = |q: P3| [q[0] * s + t[0], q[1] * s + t[1], q[2] * s];
let v = |q: P3| [q[0] * s, q[1] * s, q[2] * s];
match self {
DgnGeom::Line(a, b) => DgnGeom::Line(p(*a), p(*b)),
DgnGeom::Points(pts) => DgnGeom::Points(pts.iter().map(|q| p(*q)).collect()),
@@ -607,24 +664,53 @@ impl DgnGeom {
start: *start,
sweep: *sweep,
},
DgnGeom::Spline {
degree,
knots,
poles,
closed,
} => DgnGeom::Spline {
degree: *degree,
knots: knots.clone(),
poles: poles.iter().map(|q| p(*q)).collect(),
closed: *closed,
},
DgnGeom::Chain(parts) => DgnGeom::Chain(parts.iter().map(|g| g.scaled(s, t)).collect()),
DgnGeom::TextNode(parts) => {
DgnGeom::TextNode(parts.iter().map(|g| g.scaled(s, t)).collect())
}
DgnGeom::CellGroup { name, parts } => DgnGeom::CellGroup {
name: name.clone(),
parts: scaled_elements(parts, s, t),
},
DgnGeom::TextNode {
lines,
origin,
just,
line_spacing,
} => DgnGeom::TextNode {
lines: lines.iter().map(|g| g.scaled(s, t)).collect(),
origin: origin.map(p),
just: *just,
line_spacing: line_spacing.map(|l| l * s),
},
DgnGeom::Text {
text,
origin,
height,
width_factor,
length,
rotation,
just,
font,
style,
} => DgnGeom::Text {
text: text.clone(),
origin: p(*origin),
height: height * s,
width_factor: *width_factor,
length: length * s,
rotation: *rotation,
just: *just,
font: *font,
style: *style,
},
DgnGeom::Cell {
name,
@@ -642,42 +728,69 @@ impl DgnGeom {
}
/// Collects elements in file order, gathering the components of a complex
/// chain, shape or text node into their header's element.
/// chain, shape, text node or cell into their header's element.
#[derive(Default)]
pub struct DgnCollector {
pub elements: Vec<DgnElement>,
/// The open complex element and how many components it still takes.
open: Option<(usize, DgnElement)>,
/// The open complex elements, innermost last, each with how many
/// components it still takes. A complex element inside another is one
/// component of it once it is complete.
open: Vec<(usize, DgnElement)>,
}
impl DgnCollector {
/// A complex chain or shape (or a text node) header with `count`
/// A complex chain or shape, a text node or a cell header with `count`
/// components.
pub fn open(&mut self, count: usize, header: DgnElement) {
self.close();
if count > 0 {
self.open = Some((count, header));
self.open.push((count, header));
} else {
self.skip();
}
}
pub fn push(&mut self, element: DgnElement) {
if let Some((left, header)) = self.open.as_mut() {
if let DgnGeom::Chain(parts) | DgnGeom::TextNode(parts) = &mut header.geom {
parts.push(element.geom);
pub fn push(&mut self, mut element: DgnElement) {
loop {
let Some((left, header)) = self.open.last_mut() else {
self.elements.push(element);
return;
};
match &mut header.geom {
DgnGeom::Chain(parts) | DgnGeom::TextNode { lines: parts, .. } => {
parts.push(element.geom)
}
DgnGeom::CellGroup { parts, .. } => parts.push(element),
_ => {}
}
*left -= 1;
if *left == 0 {
self.close();
if *left > 0 {
return;
}
return;
let Some((_, done)) = self.open.pop() else {
return;
};
element = done;
}
self.elements.push(element);
}
/// Ends a complex element cut short with the components it has.
/// A component that converts to nothing (a curve that could not be
/// read) still takes its place in the open complex element.
pub fn skip(&mut self) {
if let Some((left, _)) = self.open.last_mut() {
*left -= 1;
if *left == 0 {
if let Some((_, done)) = self.open.pop() {
self.push(done);
}
}
}
}
/// Ends the complex elements cut short with the components they have
/// (an element that is no component ends them all).
pub fn close(&mut self) {
if let Some((_, header)) = self.open.take() {
self.elements.push(header);
while let Some((_, header)) = self.open.pop() {
self.push(header);
}
}
}
@@ -690,11 +803,31 @@ pub struct DgnImport {
pub elements: Vec<DgnElement>,
pub cells: Vec<(String, Vec<DgnElement>)>,
pub levels: std::collections::HashMap<u32, (String, Option<[u8; 3]>)>,
/// Level ids in the file's level table order; a V8 file's levels all
/// become layers, used or not.
pub level_order: Vec<u32>,
pub sub_per_master: f64,
/// Master and sub unit names, when the file has them.
pub unit_names: (String, String),
/// A V7 file (its elements carry their own line style and weight).
pub v7: bool,
/// The model's reference attachments.
pub references: Vec<DgnReference>,
/// The text style table (V8): each style's id and name.
pub text_styles: Vec<(u32, String)>,
}
/// A reference attachment of a DGN model: the file and model it shows and
/// how it is placed (in master units of the attaching model).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DgnReference {
/// The file as the attachment names it.
pub file: String,
pub model: String,
pub origin: P3,
/// Scale of the reference's master units into the model's.
pub scale: f64,
pub rotation: f64,
}
/// The elements through x' = s·x + t.
+40 -8
View File
@@ -34,6 +34,8 @@ pub enum ImportDialogMsg {
DgnPrefix(bool),
DgnSub(bool),
DgnExplode(bool),
DgnReferences(crate::modules::insert::dgn_import::ReferenceMode),
DgnExisting(crate::modules::insert::dgn_import::ExistingReference),
DgnMappingTab(usize),
DgnOk,
// 3D Studio Import
@@ -151,6 +153,8 @@ pub struct DgnImportState {
pub prefix_duplicates: bool,
pub sub_units: bool,
pub explode_text_nodes: bool,
pub references: crate::modules::insert::dgn_import::ReferenceMode,
pub existing_reference: crate::modules::insert::dgn_import::ExistingReference,
/// Master and sub unit names.
pub units: (String, String),
pub mapping_tab: usize,
@@ -790,21 +794,49 @@ pub fn view_dgn_import<'a>(
]
.spacing(8),
);
// The DGN readers do not read reference attachments, so their handling
// is shown but cannot be chosen.
use crate::modules::insert::dgn_import::{ExistingReference as E, ReferenceMode as R};
let translate = state.references == R::Translate;
let references = card(
t!("External DGN references").into_owned(),
column![
segmented(vec![
(t!("Bind as block / xref").into_owned(), false, None),
(t!("Ignore").into_owned(), true, None),
(t!("Attach as DGN underlay").into_owned(), false, None),
(
t!("Bind as block / xref").into_owned(),
translate,
Some(msg(ImportDialogMsg::DgnReferences(R::Translate)))
),
(
t!("Ignore").into_owned(),
state.references == R::Ignore,
Some(msg(ImportDialogMsg::DgnReferences(R::Ignore)))
),
(
t!("Attach as DGN underlay").into_owned(),
state.references == R::Underlay,
Some(msg(ImportDialogMsg::DgnReferences(R::Underlay)))
),
]),
text(t!("Reference attachments of DGN files are not read; they are left out."))
.size(11)
text(t!("When the translated drawing exists"))
.size(10)
.style(muted_style),
segmented(
[
(t!("Prompt to overwrite"), E::Prompt),
(t!("Overwrite without prompting"), E::Overwrite),
(t!("Do not overwrite"), E::Keep),
]
.into_iter()
.map(|(label, value)| {
(
label.into_owned(),
translate && state.existing_reference == value,
translate.then(|| msg(ImportDialogMsg::DgnExisting(value))),
)
})
.collect()
),
]
.spacing(8),
.spacing(6),
);
let tabs = [t!("Layer"), t!("Linetype"), t!("Lineweight"), t!("Color")];
let mut table = column![row![