cadkit-dgn 0.5.3

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

use super::*;

fn text_entity(code: u16, normal: Vec3, three: bool) -> Entity {
    let (halign, valign, _, _) = crate::map::justification(code);
    let mut e = Entity::new(EntityKind::Text {
        position: Point3::new(10., 20., if three { 30. } else { 0. }),
        end_point: None,
        height: 2.,
        rotation: 0.7,
        width_factor: 0.8,
        oblique: 0.,
        value: "Measured text".into(),
        style: None,
        halign,
        valign,
        normal,
    });
    e.props.insert("dgn.text_length".into(), Value::Float(12.5));
    e.props
        .insert("dgn.justification".into(), Value::Int(i64::from(code)));
    e
}

#[test]
fn all_documented_text_anchors_preserve_position_measurement_and_rotation() {
    for (three, normal) in [
        (false, Vec3::Z),
        (true, Vec3::Z),
        (true, Vec3::new(1., 2., 3.).normalized().unwrap()),
    ] {
        for code in 0..=14 {
            let source = text_entity(code, normal, three);
            let bytes = write_v8(
                &document(three, vec![source.clone()]),
                &seed(three),
                &WriteOptions::default(),
            )
            .unwrap();
            let parsed = crate::read(&bytes, &ReadOptions::default()).unwrap();
            let actual = &parsed.models[0].entities[0];
            let EntityKind::Text {
                position: expected,
                rotation: expected_angle,
                halign: expected_h,
                valign: expected_v,
                ..
            } = source.kind
            else {
                panic!("text");
            };
            let EntityKind::Text {
                position,
                rotation,
                halign,
                valign,
                ..
            } = actual.kind
            else {
                panic!("text");
            };
            assert!((position.x - expected.x).abs() < 1e-9);
            assert!((position.y - expected.y).abs() < 1e-9);
            assert!((position.z - expected.z).abs() < 1e-9);
            assert!((rotation - expected_angle).abs() < 1e-9);
            assert_eq!((halign, valign), (expected_h, expected_v));
            assert_eq!(actual.props["dgn.text_length"], Value::Float(12.5));
            assert_eq!(
                actual.props["dgn.justification"],
                Value::Int(i64::from(code))
            );
        }
    }
}

#[test]
fn text_measurement_is_validated_and_stale_justification_is_not_reused() {
    let mut e = text_entity(6, Vec3::Z, false);
    e.props.remove("dgn.text_length");
    assert!(
        write_v8(
            &document(false, vec![e.clone()]),
            &seed(false),
            &WriteOptions::default()
        )
        .is_err()
    );
    for bad in [f64::NAN, f64::INFINITY, -1., 0.] {
        e.props.insert("dgn.text_length".into(), Value::Float(bad));
        assert!(
            write_v8(
                &document(false, vec![e.clone()]),
                &seed(false),
                &WriteOptions::default()
            )
            .is_err()
        );
    }
    e.props.insert("dgn.text_length".into(), Value::Float(12.5));
    e.props.insert("dgn.justification".into(), Value::Int(2));
    let bytes = write_v8(
        &document(false, vec![e]),
        &seed(false),
        &WriteOptions::default(),
    )
    .unwrap();
    let parsed = crate::read(&bytes, &ReadOptions::default()).unwrap();
    assert_eq!(
        parsed.models[0].entities[0].props["dgn.justification"],
        Value::Int(6)
    );
}

#[test]
fn text_ranges_use_relative_spans_and_absolute_model_and_cell_bounds() {
    for three in [false, true] {
        let mut text = text_entity(2, Vec3::Z, three);
        if let EntityKind::Text { rotation, .. } = &mut text.kind {
            *rotation = 0.;
        }
        // The synthetic seed deliberately has global_origin = (5, 0, 0) UOR.
        let low = [10005, 20000, if three { 30000 } else { 0 }];
        let high = [22505, 22000, if three { 30000 } else { 0 }];
        let span = [12500, 2000, 0];
        for cell in [false, true] {
            let entity = if cell {
                Entity::new(EntityKind::Group {
                    group_kind: GroupKind::Cell,
                    name: Some("Synthetic text cell".into()),
                    origin: None,
                    children: vec![text.clone()],
                })
            } else {
                text.clone()
            };
            let bytes = write_v8(
                &document(three, vec![entity]),
                &seed(three),
                &WriteOptions::default(),
            )
            .unwrap();
            let native = v8::read(&bytes, &ReadOptions::default()).unwrap();
            let model = &native.models[0];
            let records: Vec<_> = model
                .graphic_pages
                .iter()
                .flat_map(|p| &p.elements)
                .collect();
            let text_record = records.iter().find(|r| r.type_code() == 17).unwrap();
            for axis in 0..3 {
                assert_eq!(
                    le::i64_at(&text_record.bytes, 0x38 + axis * 8),
                    Some(low[axis])
                );
                assert_eq!(
                    le::i64_at(&text_record.bytes, 0x50 + axis * 8),
                    Some(span[axis])
                );
            }
            assert_eq!(absolute_range(&text_record.bytes).unwrap(), [low, high]);
            let expected_extent: Vec<_> = low.into_iter().chain(high).collect();
            assert_eq!(
                model.header.as_ref().unwrap().extents.as_slice(),
                expected_extent
            );
            if cell {
                let cell_record = records.iter().find(|r| r.type_code() == 2).unwrap();
                assert_eq!(absolute_range(&cell_record.bytes).unwrap(), [low, high]);
            }
        }
    }
}

#[test]
fn rotated_and_tilted_text_range_encloses_its_measured_rectangle() {
    for normal in [Vec3::Z, Vec3::new(1., 2., 3.).normalized().unwrap()] {
        for rotation in [0., 0.7, -1.2, std::f64::consts::FRAC_PI_2] {
            for code in 0..=14 {
                let mut source = text_entity(code, normal, true);
                if let EntityKind::Text {
                    rotation: angle, ..
                } = &mut source.kind
                {
                    *angle = rotation;
                }
                let bytes = write_v8(
                    &document(true, vec![source]),
                    &seed(true),
                    &WriteOptions::default(),
                )
                .unwrap();
                let native = v8::read(&bytes, &ReadOptions::default()).unwrap();
                let model = &native.models[0];
                let record = model.graphic_pages[0]
                    .elements
                    .iter()
                    .find(|r| r.type_code() == 17)
                    .unwrap();
                let decoded = crate::native::decode_v8::decode(
                    record,
                    encoding_rs::WINDOWS_1252,
                    &ReadOptions::default().limits,
                );
                let crate::native::element::ElementData::Text(text) = decoded.data else {
                    panic!("text");
                };
                let m = text.rotation.matrix();
                let x = Vec3::new(m[0], m[3], m[6]);
                let y = Vec3::new(m[1], m[4], m[7]);
                let [ox, oy, oz] = text.origin;
                let dx = x.scaled(text.measured_length.unwrap());
                let dy = y.scaled(text.height);
                let corners = [
                    text.origin,
                    [ox + dx.x, oy + dx.y, oz + dx.z],
                    [ox + dy.x, oy + dy.y, oz + dy.z],
                    [ox + dx.x + dy.x, oy + dx.y + dy.y, oz + dx.z + dy.z],
                ];
                let [low, high] = absolute_range(&record.bytes).unwrap();
                for axis in 0..3 {
                    let min = corners
                        .iter()
                        .map(|p| p[axis])
                        .fold(f64::INFINITY, f64::min);
                    let max = corners
                        .iter()
                        .map(|p| p[axis])
                        .fold(f64::NEG_INFINITY, f64::max);
                    assert!(low[axis] as f64 <= min + 1e-8);
                    assert!(high[axis] as f64 >= max - 1e-8);
                    assert!(min - low[axis] as f64 <= 1.000001);
                    assert!(high[axis] as f64 - max <= 1.000001);
                }
                let expected: Vec<_> = low.into_iter().chain(high).collect();
                assert_eq!(model.header.as_ref().unwrap().extents.as_slice(), expected);
            }
        }
    }
}

/// A centred text whose record stores no length (`0x80` zero) but whose range starts at its
/// origin reads its length from the range (`dgn.text_length_source` = "range"); written back,
/// the record stores that length, and anchor, origin and length read back unchanged.
#[test]
fn range_derived_text_length_keeps_the_anchor_through_a_round_trip() {
    for three in [false, true] {
        let mut source = text_entity(7, Vec3::Z, three);
        if let EntityKind::Text { rotation, .. } = &mut source.kind {
            *rotation = 0.;
        }
        let written = write_v8(
            &document(three, vec![source]),
            &seed(three),
            &WriteOptions::default(),
        )
        .unwrap();
        // Clear the stored length and narrow the range to 9 drawing units (1000 UOR each).
        let native = v8::read(&written, &ReadOptions::default()).unwrap();
        let records: Vec<Vec<u8>> = native.models[0].graphic_pages[0]
            .elements
            .iter()
            .map(|r| {
                let mut b = r.bytes.clone();
                if r.type_code() == 17 {
                    assert_eq!(le::i64_at(&b, 0x50), Some(12_500));
                    f64_at(&mut b, 0x80, 0.0).unwrap();
                    b[0x50..0x58].copy_from_slice(&9_000i64.to_le_bytes());
                }
                b
            })
            .collect();
        let mut file = ::cfb::CompoundFile::open(Cursor::new(written)).unwrap();
        file.create_stream("Dgn-Md/#000000/Dgn^G/$1")
            .unwrap()
            .write_all(&page(&records, 3, 1).unwrap())
            .unwrap();
        file.flush().unwrap();
        let unmeasured = file.into_inner().into_inner();

        let doc = crate::read(&unmeasured, &ReadOptions::default()).unwrap();
        let text = &doc.models[0].entities[0];
        assert_eq!(text.props["dgn.text_length"], Value::Float(9.0));
        assert_eq!(
            text.props["dgn.text_length_source"],
            Value::Text("range".into())
        );
        assert!(!text.props.contains_key("dgn.text_length_estimated"));
        let origin = match &text.props["dgn.origin"] {
            Value::List(v) => v.clone(),
            other => panic!("{other:?}"),
        };
        let (Value::Float(ox), Value::Float(oy)) = (&origin[0], &origin[1]) else {
            panic!("origin")
        };
        let EntityKind::Text {
            position, height, ..
        } = text.kind
        else {
            panic!("text")
        };
        // Centre-middle: half the length along x, half the height along y.
        assert!((position.x - (ox + 4.5)).abs() < 1e-9);
        assert!((position.y - (oy + height / 2.)).abs() < 1e-9);

        let back = write_v8(
            &doc,
            &unmeasured,
            &WriteOptions::default().with_clear_seed_model(true),
        )
        .unwrap();
        let native = v8::read(&back, &ReadOptions::default()).unwrap();
        let record = native.models[0].graphic_pages[0]
            .elements
            .iter()
            .find(|r| r.type_code() == 17)
            .unwrap();
        assert_eq!(le::f64_at(&record.bytes, 0x80), Some(9_000.));
        let reread = crate::read(&back, &ReadOptions::default()).unwrap();
        let again = &reread.models[0].entities[0];
        let EntityKind::Text {
            position: again_position,
            ..
        } = again.kind
        else {
            panic!("text")
        };
        for (a, b) in [
            (again_position.x, position.x),
            (again_position.y, position.y),
            (again_position.z, position.z),
        ] {
            assert!((a - b).abs() < 1e-9);
        }
        assert_eq!(again.props["dgn.origin"], Value::List(origin));
        assert_eq!(again.props["dgn.text_length"], Value::Float(9.0));
        // The written record stores the length: it is no longer range-derived.
        assert!(!again.props.contains_key("dgn.text_length_source"));
        assert!(!again.props.contains_key("dgn.text_length_estimated"));
    }
}

fn seed_with_fonts(fonts: &[(u32, &str)]) -> Vec<u8> {
    let mut records = vec![];
    for (index, (number, name)) in fonts.iter().enumerate() {
        let name: Vec<_> = name.encode_utf16().flat_map(u16::to_le_bytes).collect();
        let mut b = prefix(95, 0x2e + name.len(), index as u64 + 100, 2, 0.).unwrap();
        u32_at(&mut b, 0x28, *number).unwrap();
        put(&mut b, 0x2c, &(name.len() as u16).to_le_bytes()).unwrap();
        put(&mut b, 0x2e, &name).unwrap();
        records.push(finish(b, &[]).unwrap());
    }
    let mut file = ::cfb::CompoundFile::open(Cursor::new(seed(false))).unwrap();
    file.create_storage_all("Dgn^Nm").unwrap();
    file.create_stream("Dgn^Nm/$1")
        .unwrap()
        .write_all(&page(&records, 3, 1).unwrap())
        .unwrap();
    file.flush().unwrap();
    file.into_inner().into_inner()
}

#[test]
fn font_numbers_and_styles_must_refer_to_the_selected_seed() {
    let blank = seed_with_fonts(&[(23, "Synthetic font"), (41, "Other font")]);
    let mut source = text_entity(2, Vec3::Z, false);
    let write = |entity: &Entity, seed: &[u8]| {
        write_v8(
            &document(false, vec![entity.clone()]),
            seed,
            &WriteOptions::default(),
        )
    };
    source
        .props
        .insert("dgn.font_number".into(), Value::Int(23));
    assert!(write(&source, &blank).is_ok());
    if let EntityKind::Text { style, .. } = &mut source.kind {
        *style = Some("Synthetic font".into());
    }
    assert!(write(&source, &blank).is_ok());
    source
        .props
        .insert("dgn.font_number".into(), Value::Int(41));
    assert!(write(&source, &blank).is_err());
    source.props.remove("dgn.font_number");
    let bytes = write(&source, &blank).unwrap();
    let parsed = crate::read(&bytes, &ReadOptions::default()).unwrap();
    assert_eq!(
        parsed.models[0].entities[0].props["dgn.font_number"],
        Value::Int(23)
    );
    if let EntityKind::Text { style, .. } = &mut source.kind {
        *style = None;
    }
    for invalid in [
        Value::Int(-1),
        Value::Int(999),
        Value::Float(23.),
        Value::Text("23".into()),
    ] {
        source.props.insert("dgn.font_number".into(), invalid);
        assert!(write(&source, &blank).is_err());
    }
    source.props.insert("dgn.font_number".into(), Value::Int(0));
    assert!(write(&source, &blank).is_ok());
    let table_free = seed(false);
    let bytes = write(&source, &table_free).unwrap();
    let parsed = crate::read(&bytes, &ReadOptions::default()).unwrap();
    assert!(write(&parsed.models[0].entities[0], &table_free).is_ok());
    source
        .props
        .insert("dgn.font_number".into(), Value::Int(23));
    assert!(write(&source, &table_free).is_err());
}

#[test]
fn external_font_referenced_by_seed_graphics_is_retained_without_a_named_table() {
    let original = write_v8(
        &document(false, vec![text_entity(2, Vec3::Z, false)]),
        &seed(false),
        &WriteOptions::default(),
    )
    .unwrap();
    let native = v8::read(&original, &ReadOptions::default()).unwrap();
    let mut records: Vec<_> = native.models[0].graphic_pages[0]
        .elements
        .iter()
        .map(|r| r.bytes.clone())
        .collect();
    u32_at(&mut records[0], 0x68, 127).unwrap();
    let mut file = ::cfb::CompoundFile::open(Cursor::new(original)).unwrap();
    file.create_stream("Dgn-Md/#000000/Dgn^G/$1")
        .unwrap()
        .write_all(&page(&records, 3, 1).unwrap())
        .unwrap();
    file.flush().unwrap();
    let referenced = file.into_inner().into_inner();
    let source = crate::read(&referenced, &ReadOptions::default()).unwrap();
    assert_eq!(
        source.models[0].entities[0].props["dgn.font_number"],
        Value::Int(127)
    );
    let bytes = write_v8(
        &source,
        &referenced,
        &WriteOptions {
            clear_seed_model: true,
            ..Default::default()
        },
    )
    .unwrap();
    let parsed = crate::read(&bytes, &ReadOptions::default()).unwrap();
    assert_eq!(
        parsed.models[0].entities[0].props["dgn.font_number"],
        Value::Int(127)
    );
    assert!(write_v8(&source, &seed(false), &WriteOptions::default()).is_err());
}

#[test]
fn a_font_name_with_two_numbers_is_ambiguous_until_a_number_picks_one() {
    let seed = seed_with_fonts(&[(23, "Twin"), (41, "Twin"), (50, "Case"), (51, "case")]);
    let parsed = V8Seed::from_bytes(&seed).unwrap();
    assert_eq!(
        parsed.font_entries().collect::<Vec<_>>(),
        [("Twin", 23), ("Twin", 41), ("Case", 50), ("case", 51)]
    );
    // Each name once in `fonts`, every entry in `font_entries`.
    assert_eq!(parsed.fonts().count(), 3);
    let message = |r: Result<u32>| match r {
        Err(Error::Unsupported(m)) => m,
        other => panic!("{other:?}"),
    };
    let ambiguous = "DGN font name is ambiguous in the seed font table";
    let absent = "DGN font is absent from the seed font table";
    assert_eq!(message(parsed.font_number("Twin")), ambiguous);
    // The exact name wins over the loose match; without one, the loose match decides.
    assert_eq!(parsed.font_number("Case").unwrap(), 50);
    assert_eq!(parsed.font_number("case").unwrap(), 51);
    assert_eq!(message(parsed.font_number(" CASE ")), ambiguous);
    assert_eq!(message(parsed.font_number("Other")), absent);

    let mut source = text_entity(2, Vec3::Z, false);
    let write = |entity: &Entity| {
        write_v8(
            &document(false, vec![entity.clone()]),
            &seed,
            &WriteOptions::default(),
        )
    };
    if let EntityKind::Text { style, .. } = &mut source.kind {
        *style = Some("Twin".into());
    }
    // The writer once took the last entry of a repeated name silently.
    assert!(matches!(write(&source), Err(Error::Unsupported(m)) if m.contains("ambiguous")));
    for number in [23, 41] {
        source
            .props
            .insert("dgn.font_number".into(), Value::Int(number));
        let bytes = write(&source).unwrap();
        let parsed = crate::read(&bytes, &ReadOptions::default()).unwrap();
        assert_eq!(
            parsed.models[0].entities[0].props["dgn.font_number"],
            Value::Int(number)
        );
    }
    source
        .props
        .insert("dgn.font_number".into(), Value::Int(50));
    assert!(write(&source).is_err(), "number and style disagree");
    // A document prepared for the seed drops the ambiguous style and keeps the number.
    source
        .props
        .insert("dgn.font_number".into(), Value::Int(23));
    let prepared = parsed
        .prepare_document(
            &document(false, vec![source.clone()]),
            &SeedPrepareOptions::default(),
        )
        .unwrap();
    let EntityKind::Text { style, .. } = &prepared.models[0].entities[0].kind else {
        panic!("text")
    };
    assert_eq!(style, &None);
    assert!(write_v8_with_seed(&prepared, &parsed, &WriteOptions::default()).is_ok());
}