File: dimension_linear.py

package info (click to toggle)
ezdxf 1.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 104,528 kB
  • sloc: python: 182,341; makefile: 116; lisp: 20; ansic: 4
file content (883 lines) | stat: -rw-r--r-- 25,461 bytes parent folder | download
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
# Copyright (c) 2018-2022, Manfred Moitzi
# License: MIT License
from typing import cast
import math
import pathlib
import random
import logging

import ezdxf
from ezdxf.tools.standards import setup_dimstyle
from ezdxf.math import Vec3, UCS
from ezdxf.entities import DimStyle
from ezdxf.enums import MTextLineAlignment

# ------------------------------------------------------------------------------
# This example shows how to use angular dimension.
#
# tutorial: https://ezdxf.mozman.at/docs/tutorials/linear_dimension.html
# ------------------------------------------------------------------------------

logging.basicConfig(level="WARNING")
DXFVERSION = "R2013"
CWD = pathlib.Path("~/Desktop/Outbox").expanduser()
if not CWD.exists():
    CWD = pathlib.Path(".")


# Default text attributes:
TEXT_ATTRIBS = {
    "height": 0.25,
    "style": ezdxf.options.default_dimension_text_style,
}
DIM_TEXT_STYLE = ezdxf.options.default_dimension_text_style

# Discarding the dimension rendering is possible for BricsCAD,
# but it is incompatible to AutoCAD -> error
BRICSCAD = False


def set_text_style(doc, textstyle=DIM_TEXT_STYLE, name="EZDXF"):
    if doc.dxfversion == "AC1009":
        return
    dimstyle = cast(DimStyle, doc.dimstyles.get(name))
    dimstyle.dxf.dimtxsty = textstyle


def linear_tutorial(dxfversion="R12"):
    doc = ezdxf.new(dxfversion, setup=True)
    msp = doc.modelspace()
    msp.add_line((0, 0), (3, 0))
    msp.add_line((0, 7), (10, 0))

    # horizontal DIMENSION
    # Default DimStyle EZDXF:
    #   1 drawing unit == 1m;
    #   scale 1: 100;
    #   length_factor=100 -> measurement in cm
    #
    # base: defines the dimension line, ezdxf accepts any point on the
    # dimension line
    # p1: defines the start point of the first extension line, which also
    # defines the first point to measure
    # p2: defines the start point of the second extension line, which also
    # defines the second point to measure

    dim = msp.add_linear_dim(
        base=(3, 2),
        p1=(0, 0),
        p2=(3, 0),
        dimstyle="EZDXF",
        override={"dimtxsty": "OpenSans"},
    )
    # Necessary second step, to create the BLOCK entity with the DIMENSION
    # geometry.
    # Ezdxf supports DXF R2000 attributes for DXF R12 rendering, but they have
    # to be applied by the DIMSTYLE override feature, this additional attributes
    # are not stored in the XDATA section of the DIMENSION entity, they are just
    # used to render the DIMENSION entity.
    # The return value `dim` is not a DIMENSION entity, instead a
    # DimStyleOverride object is returned, the DIMENSION entity is stored as
    # dim.dimension, see also ezdxf.override.DimStyleOverride class.
    dim.render()

    # rotated DIMENSION without `override` uses ezdxf.options.default_dimension_text_style
    # (OpenSansCondensed-Light)
    # angle: defines the angle of the dimension line in relation to the x-axis
    # of the WCS or UCS, measurement is the
    # distance between first and second measurement point in direction of `angle`
    dim2 = msp.add_linear_dim(
        base=(10, 2),
        p1=(7, 0),
        p2=(10, 0),
        angle=-30,
        dimstyle="EZDXF",
        override={
            "dimdle": 0,
            "dimdec": 2,
            "dimtfill": 2,  # custom text fill
            "dimtfillclr": 4,  # cyan
        },
    )
    # Some properties have setter methods for convenience, this is also the
    # reason for not calling dim2.render() automatically.
    dim2.set_arrows(blk=ezdxf.ARROWS.closed_filled, size=0.25)
    dim2.set_text_align(halign="right")
    dim2.render()

    doc.set_modelspace_vport(height=5, center=(5, 0))
    doc.saveas(CWD / f"dim_linear_{dxfversion}_tutorial.dxf")


def example_background_fill(dxfversion=DXFVERSION):
    """This example shows the background fill feature, ezdxf uses MTEXT for this
    feature and has no effect in DXF R12.

    """
    doc = ezdxf.new(dxfversion, setup=True)
    msp = doc.modelspace()
    msp.add_line((0, 2.2), (10, 2.2))

    dim = msp.add_linear_dim(
        base=(0, 2),
        p1=(0, 0),
        p2=(3, 0),
        dimstyle="EZDXF",
        override={
            "dimtfill": 1,  # background color
        },
    )
    dim.set_text("bgcolor")
    dim.render()

    dim = msp.add_linear_dim(
        base=(0, 2),
        p1=(5, 0),
        p2=(8, 0),
        dimstyle="EZDXF",
        override={
            "dimtfill": 2,  # custom text fill
            "dimtfillclr": 4,  # cyan
        },
    )
    dim.set_text("cyan")
    dim.render()
    doc.saveas(CWD / f"background_fill_example_{dxfversion}.dxf")


def example_text_override(dxfversion=DXFVERSION):
    """This example shows how to override the measurement text."""
    doc = ezdxf.new(dxfversion, setup=True)
    msp = doc.modelspace()

    # custom text
    dim = msp.add_linear_dim(
        base=(0, 2),
        p1=(0, 0),
        p2=(3, 0),
    )
    dim.set_text("=<>= <>")  # the first "<>" will be replaced by the measurement text
    dim.render()

    # suppress text
    dim = msp.add_linear_dim(
        base=(5, 2),
        p1=(5, 0),
        p2=(8, 0),
    )
    dim.set_text(" ")
    dim.render()

    # regular measurement text
    dim = msp.add_linear_dim(
        base=(10, 2),
        p1=(10, 0),
        p2=(13, 0),
    )
    dim.set_text("")
    dim.render()

    # regular measurement text
    dim = msp.add_linear_dim(
        base=(15, 2),
        p1=(15, 0),
        p2=(18, 0),
    )
    dim.set_text("<>")
    dim.render()

    doc.saveas(CWD / f"text_override_example_{dxfversion}.dxf")


def example_for_all_text_placings_R12():
    doc = ezdxf.new("R12", setup=True)
    example_for_all_text_placings(doc, "dim_linear_text_placing_R12.dxf")


def example_for_all_text_placings_ucs_R12():
    ucs = UCS(origin=(10, 10, 0), ux=(3, 1, 0), uz=(0, 0, 1))
    doc = ezdxf.new("R12", setup=True)
    example_for_all_text_placings(
        doc, "dim_linear_text_placing_ucs_R12.dxf", ucs
    )


def example_for_all_text_placings_in_space_R12():
    ucs = UCS(ux=(1, 1, 0), uy=(0, 0, 1))
    doc = ezdxf.new("R12", setup=True)
    example_for_all_text_placings(
        doc, "dim_linear_text_placing_in_space_R12.dxf", ucs
    )


def example_for_all_text_placings_R2007():
    doc = ezdxf.new("R2007", setup=True)
    set_text_style(doc)
    example_for_all_text_placings(doc, "dim_linear_text_placing_R2007.dxf")


def example_for_all_text_placings_ucs_R2007():
    ucs = UCS(origin=(10, 10, 0), ux=(3, 1, 0), uz=(0, 0, 1))
    doc = ezdxf.new("R2007", setup=True)
    set_text_style(doc)
    example_for_all_text_placings(
        doc, "dim_linear_text_placing_ucs_R2007.dxf", ucs
    )


def example_for_all_text_placings_in_space_R2007():
    ucs = (
        UCS(origin=(20, 20, 0))
        .rotate_local_x(math.radians(45))
        .rotate_local_z(math.radians(45))
    )
    doc = ezdxf.new("R2007", setup=True)
    set_text_style(doc)
    example_for_all_text_placings(
        doc, "dim_linear_text_placing_in_space_R2007.dxf", ucs
    )


def example_for_all_text_placings(doc, filename, ucs=None):
    """This example shows many combinations of dimension text placing by
    `halign`, `valign` and user defined location override.

    Args:
        doc: DXF drawing
        filename: file name for saving
        ucs: user defined coordinate system

    """

    def add_text(lines, insert):
        insert += (0.2, 0)
        attribs = dict(TEXT_ATTRIBS)
        line_space = 0.4
        delta = Vec3(0, line_space, 0)
        for line in lines:
            text = msp.add_text(line, dxfattribs=attribs).set_placement(insert)
            if ucs:
                text.transform(ucs.matrix)
            insert -= delta

    msp = doc.modelspace()
    setup_dimstyle(
        doc,
        name="TICK",
        fmt="EZ_M_100_H25_CM",
        style=DIM_TEXT_STYLE,
    )
    setup_dimstyle(
        doc,
        name="ARCHTICK",
        fmt="EZ_M_100_H25_CM",
        blk=ezdxf.ARROWS.architectural_tick,
        style=DIM_TEXT_STYLE,
    )
    setup_dimstyle(
        doc,
        name="CLOSEDBLANK",
        fmt="EZ_M_100_H25_CM",
        blk=ezdxf.ARROWS.closed_blank,
        style=DIM_TEXT_STYLE,
    )

    def text(dimstyle, x, y, halign, valign, oblique=0):
        """Default dimension text placing

        Args:
            dimstyle: dimstyle to use
            x: start point x
            y: start point y
            halign: horizontal text alignment - "left", "right", "center",
                "above1", "above2", requires DXF R2000+
            valign: vertical text alignment "above", "center", "below"
            oblique: angle of oblique extension line, 0 = orthogonal to
                dimension line

        """
        dimattr = {}
        if oblique:
            dimattr["oblique_angle"] = oblique

        base = (x, y + 2)
        # wide
        dim = msp.add_linear_dim(
            base=base,
            p1=(x, y),
            p2=(x + 5, y),
            dimstyle=dimstyle,
            dxfattribs=dimattr,
        )
        dim.set_text_align(halign=halign, valign=valign)
        dim.render(ucs=ucs, discard=BRICSCAD)

        add_text(
            [f"halign={halign}", f"valign={valign}", f"oblique={oblique}"],
            insert=Vec3(x, y),
        )

        # narrow
        dim = msp.add_linear_dim(
            base=base,
            p1=(x + 7, y),
            p2=(x + 7.3, y),
            dimstyle=dimstyle,
            dxfattribs=dimattr,
        )
        dim.set_text_align(halign=halign, valign=valign)
        dim.render(ucs=ucs, discard=BRICSCAD)

        # arrows inside, text outside

        dim = msp.add_linear_dim(
            base=base,
            p1=(x + 10, y),
            p2=(x + 10.9999, y),
            dimstyle=dimstyle,
            override={"dimdec": 2},
            dxfattribs=dimattr,
        )
        dim.set_text_align(halign=halign, valign=valign)
        dim.render(ucs=ucs, discard=BRICSCAD)

        # narrow and force text inside
        dim = msp.add_linear_dim(
            base=base,
            p1=(x + 14, y),
            p2=(x + 14.3, y),
            dimstyle=dimstyle,
            override={"dimtix": 1},
            dxfattribs=dimattr,
        )
        dim.set_text_align(halign=halign, valign=valign)
        dim.render(ucs=ucs, discard=BRICSCAD)

    def user_text_free(dimstyle, x=0, y=0, leader=False):
        """User defined dimension text placing.

        Args:
            dimstyle: dimstyle to use
            x: start point x
            y: start point y
            leader: use leader line if True

        """
        override = {
            "dimdle": 0.0,
            "dimexe": 0.5,  # length of extension line above dimension line
            "dimexo": 0.5,  # extension line offset
            "dimtfill": 2,  # custom text fill
            "dimtfillclr": 4,  # cyan
        }

        base = (x, y + 2)
        dim = msp.add_linear_dim(
            base=base,
            p1=(x, y),
            p2=(x + 3, y),
            dimstyle=dimstyle,
            override=override,
        )
        location = Vec3(x + 3, y + 3, 0)
        dim.set_location(location, leader=leader)
        dim.render(ucs=ucs, discard=BRICSCAD)
        add_text(
            [f"usr absolute={location}", f"leader={leader}"], insert=Vec3(x, y)
        )

        x += 4
        dim = msp.add_linear_dim(
            base=base,
            p1=(x, y),
            p2=(x + 3, y),
            dimstyle=dimstyle,
            override=override,
        )
        relative = Vec3(-1, +1)  # relative to dimline center
        dim.set_location(relative, leader=leader, relative=True)
        dim.render(ucs=ucs, discard=BRICSCAD)
        add_text(
            [f"usr relative={relative}", f"leader={leader}"], insert=Vec3(x, y)
        )

        x += 4
        dim = msp.add_linear_dim(
            base=base,
            p1=(x, y),
            p2=(x + 3, y),
            dimstyle=dimstyle,
            override=override,
        )
        dh = -0.7
        dv = 1.5
        dim.shift_text(dh, dv)
        dim.render(ucs=ucs, discard=BRICSCAD)
        add_text(
            [
                f"shift text=({dh}, {dv})",
            ],
            insert=Vec3(x, y),
        )

        override["dimtix"] = 1  # force text inside
        x += 4
        dim = msp.add_linear_dim(
            base=base,
            p1=(x, y),
            p2=(x + 0.3, y),
            dimstyle=dimstyle,
            override=override,
        )
        dh = 0
        dv = 1
        dim.shift_text(dh, dv)
        dim.render(ucs=ucs, discard=BRICSCAD)
        add_text(
            [
                f"shift text=({dh}, {dv})",
            ],
            insert=Vec3(x, y),
        )

    dimstyles = ["TICK", "ARCHTICK", "CLOSEDBLANK"]
    xoffset = 17
    yoffset = 5
    for col, dimstyle in enumerate(dimstyles):
        row = 0
        for halign in ("center", "left", "right"):
            text(
                dimstyle,
                x=col * xoffset,
                y=row * yoffset,
                halign=halign,
                valign="above",
            )
            row += 1
            text(
                dimstyle,
                x=col * xoffset,
                y=row * yoffset,
                halign=halign,
                valign="center",
            )
            row += 1
            text(
                dimstyle,
                x=col * xoffset,
                y=row * yoffset,
                halign=halign,
                valign="below",
            )
            row += 1

        text(
            dimstyle,
            x=col * xoffset,
            y=row * yoffset,
            halign="above1",
            valign="above",
        )
        row += 1

        text(
            dimstyle,
            x=col * xoffset,
            y=row * yoffset,
            halign="above2",
            valign="above",
        )
        row += 1

        user_text_free(dimstyle, x=col * xoffset, y=row * yoffset)
        row += 1

        user_text_free(dimstyle, x=col * xoffset, y=row * yoffset, leader=True)
        row += 1

        text(
            dimstyle,
            x=col * xoffset,
            y=row * yoffset,
            halign="center",
            valign="above",
            oblique=70,
        )
        row += 1

        text(
            dimstyle,
            x=col * xoffset,
            y=row * yoffset,
            halign="above1",
            valign="above",
            oblique=80,
        )
        row += 1

    doc.saveas(CWD / filename)


def example_multi_point_linear_dimension():
    """Example for using the ezdxf "multi-point linear dimension" feature, which
    generates dimension entities for multiple points at ones and tries to move
    dimension text to a readable location.

    This feature works best with DXF R2007+.

    """
    doc = ezdxf.new("R2007", setup=True)
    msp = doc.modelspace()
    points = [(0, 0), (5, 1), (5.2, 1), (5.4, 0), (7, 0), (10, 3)]
    msp.add_lwpolyline(points)

    # create quick a new DIMSTYLE as alternative to overriding DIMSTYLE attributes
    dimstyle = cast(
        DimStyle, doc.dimstyles.duplicate_entry("EZDXF", "WITHTFILL")
    )
    dimstyle.dxf.dimtfill = 1

    msp.add_multi_point_linear_dim(
        base=(0, 5), points=points, dimstyle="WITHTFILL"
    )
    doc.saveas(CWD / f"multi_point_linear_dim_R2007.dxf")


def random_point(start, end):
    dist = end - start
    return Vec3(start + random.random() * dist, start + random.random() * dist)


def example_random_multi_point_linear_dimension(
    count=10, length=20, discard=BRICSCAD
):
    """Example for using the ezdxf "multipoint linear dimension" feature, which
    generates dimension entities for multiple points at ones and tries to move
    dimension text to a readable location.

    This feature works best with DXF R2007+.

    """
    doc = ezdxf.new("R2007", setup=True)
    msp = doc.modelspace()

    # create a random polyline.
    points = [random_point(0, length) for _ in range(count)]
    msp.add_lwpolyline(points, dxfattribs={"color": 1})

    # create quick a new DIMSTYLE as alternative to overriding DIMSTYLE attributes
    dimstyle = cast(
        DimStyle, doc.dimstyles.duplicate_entry("EZDXF", "WITHTFILL")
    )

    dimstyle.dxf.dimtfill = 1
    dimstyle.dxf.dimdec = 2

    dimstyle = cast(
        DimStyle, doc.dimstyles.duplicate_entry("WITHTFILL", "WITHTXT")
    )
    dimstyle.dxf.dimblk = ezdxf.ARROWS.closed
    dimstyle.dxf.dimtxsty = "STANDARD"
    dimstyle.dxf.dimrnd = 0.5
    dimstyle.set_text_align(valign="center")

    msp.add_multi_point_linear_dim(
        base=(0, length + 2),
        points=points,
        dimstyle="WITHTFILL",
        discard=discard,
    )
    msp.add_multi_point_linear_dim(
        base=(-2, 0),
        points=points,
        angle=90,
        dimstyle="WITHTFILL",
        discard=discard,
    )
    msp.add_multi_point_linear_dim(
        base=(10, -10),
        points=points,
        angle=45,
        dimstyle="WITHTXT",
        discard=discard,
    )
    doc.saveas(CWD / f"multi_random_point_linear_dim_R2007.dxf")


def linear_all_arrow_style(
    version=DXFVERSION, dimltype=None, dimltex1=None, dimltex2=None, filename=""
):
    """Show all AutoCAD standard arrows on a linear dimension.

    Args:
        version: DXF version
        dimltype: dimension linetype
        dimltex1: linetype for first extension line
        dimltex2: linetype for second extension line
        filename: filename for saving

    """
    doc = ezdxf.new(version, setup=True)
    msp = doc.modelspace()
    ezdxf_dimstyle = cast(DimStyle, doc.dimstyles.get("EZDXF"))
    ezdxf_dimstyle.copy_to_header(doc)

    for index, name in enumerate(sorted(ezdxf.ARROWS.__all_arrows__)):
        y = index * 4
        attributes = {
            "dimtxsty": "LiberationMono",
            "dimdle": 0.5,
        }
        if dimltype:
            attributes["dimltype"] = dimltype
        if dimltex1:
            attributes["dimltex1"] = dimltex1
        if dimltex2:
            attributes["dimltex2"] = dimltex2

        dim = msp.add_linear_dim(
            base=(3, y + 2),
            p1=(0, y),
            p2=(3, y),
            dimstyle="EZDXF",
            override=attributes,
        )
        dim.set_arrows(blk=name, size=0.25)
        dim.render()

    if not filename:
        filename = "all_arrow_styles_dim_{}.dxf".format(version)

    doc.saveas(CWD / filename)


def linear_tutorial_using_tolerances(version=DXFVERSION):
    """Shows usage of tolerances for the dimension text.

    ezdxf uses MTEXT features for tolerance rendering and therefore requires
    DXF R2000+, but if you are using a friendly CAD application like BricsCAD,
    you can let the CAD application do the rendering job, be aware this files
    are not AutoCAD compatible.

    Args:
        version: DXF version

    """
    doc = ezdxf.new(version, setup=True)
    msp = doc.modelspace()

    # DO NOT RENDER BY EZDXF for DXF R12
    discard = version == "R12"

    tol_style = cast(
        DimStyle, doc.dimstyles.duplicate_entry("EZDXF", "TOLERANCE")
    )
    # not all features are supported by DXF R12:
    # zero suppression (DIMTZIN), align (DIMTOLJ) and dec (DIMTDEC) require
    # DXF R2000+
    tol_style.set_tolerance(
        0.1, hfactor=0.5, align=MTextLineAlignment.TOP, dec=2
    )
    msp.add_linear_dim(
        base=(0, 3), p1=(0, 0), p2=(10, 0), dimstyle="tolerance"
    ).render(discard=discard)

    dim = msp.add_linear_dim(
        base=(0, 3), p1=(15, 0), p2=(15.5, 0), dimstyle="tolerance"
    )
    # set tolerance attributes by dim style override
    dim.set_tolerance(
        0.1, 0.15, hfactor=0.4, align=MTextLineAlignment.MIDDLE, dec=2
    )
    dim.render(discard=discard)

    doc.saveas(CWD / f"dimensions_with_tolerance_{version}.dxf")


def linear_tutorial_using_limits(version=DXFVERSION):
    """Shows usage of limits for the dimension text, limits are the lower and
    upper limit for the measured distance, the measurement itself is not shown.

    Ezdxf uses MTEXT features for limits rendering and therefore requires DXF
    R2000+, but if you are using a friendly CAD application like BricsCAD, you
    can let the CAD application do the rendering job, be aware this files
    are not AutoCAD compatible.

    Args:
        version: DXF version

    """
    doc = ezdxf.new(version, setup=True)
    msp = doc.modelspace()
    # DO NOT RENDER BY EZDXF for DXF R12
    discard = version == "R12"

    tol_style = cast(DimStyle, doc.dimstyles.duplicate_entry("EZDXF", "LIMITS"))

    # not all features are supported by DXF R12:
    # zero suppression (DIMTZIN), align (DIMTOLJ) and dec (DIMTDEC) require DXF R2000+
    tol_style.set_limits(upper=0.1, lower=0.1, hfactor=0.5, dec=2)

    msp.add_linear_dim(
        base=(0, 3), p1=(0, 0), p2=(10, 0), dimstyle="limits"
    ).render(discard=discard)
    msp.add_linear_dim(
        base=(0, 3), p1=(15, 0), p2=(15.5, 0), dimstyle="limits"
    ).render(discard=discard)
    doc.saveas(CWD / f"dimensions_with_limits_{version}.dxf")


def linear_tutorial_using_tvp():
    """For the vertical text alignment "center", exists an additional DXF
    feature, to move the dimension text vertical up and down (DIMTVP).
    Vertical distance dimension line to text center = text_height * vshift (DIMTVP)

    """
    doc = ezdxf.new("R2000", setup=True)
    msp = doc.modelspace()
    style = cast(DimStyle, doc.dimstyles.duplicate_entry("EZDXF", "TVP"))
    # shift text upwards
    style.set_text_align(valign="center", vshift=2.0)
    msp.add_linear_dim(
        base=(0, 3), p1=(0, 0), p2=(10, 0), dimstyle="TVP"
    ).render()
    msp.add_linear_dim(
        base=(0, 3), p1=(15, 0), p2=(15.5, 0), dimstyle="TVP"
    ).render()

    style = cast(DimStyle, doc.dimstyles.duplicate_entry("EZDXF", "TVP2"))
    # shift text downwards
    style.set_text_align(valign="center", vshift=-2.0)
    msp.add_linear_dim(
        base=(0, 7), p1=(0, 5), p2=(10, 5), dimstyle="TVP2"
    ).render()
    msp.add_linear_dim(
        base=(0, 7), p1=(15, 5), p2=(15.5, 5), dimstyle="TVP2"
    ).render()

    doc.saveas(CWD / "dimensions_with_dimtvp.dxf")


def linear_tutorial_ext_lines():
    doc = ezdxf.new("R12", setup=True)
    msp = doc.modelspace()

    msp.add_line((0, 0), (3, 0))

    attributes = {
        "dimexo": 0.5,
        "dimexe": 0.5,
        "dimdle": 0.5,
        "dimblk": ezdxf.ARROWS.none,
        "dimclrt": 3,
    }
    msp.add_linear_dim(
        base=(3, 2), p1=(0, 0), p2=(3, 0), dimstyle="EZDXF", override=attributes
    ).render()

    attributes = {
        "dimtad": 4,
        "dimclrd": 2,
        "dimclrt": 4,
    }
    msp.add_linear_dim(
        base=(10, 2),
        p1=(7, 0),
        p2=(10, 0),
        angle=-30,
        dimstyle="EZDXF",
        override=attributes,
    ).render()
    msp.add_linear_dim(
        base=(3, 5),
        p1=(0, 10),
        p2=(3, 10),
        dimstyle="EZDXF",
        override=attributes,
    ).render()
    doc.saveas(CWD / "dim_linear_R12_ext_lines.dxf")


def linear_EZ_M(fmt):
    doc = ezdxf.new("R12", setup=("linetypes", "styles"))
    msp = doc.modelspace()
    ezdxf.setup_dimstyle(doc, fmt)

    msp.add_line((0, 0), (1, 0))
    msp.add_linear_dim(base=(0, 1), p1=(0, 0), p2=(1, 0), dimstyle=fmt).render()
    doc.saveas(CWD / f"dim_linear_R12_{fmt}.dxf")


def linear_EZ_CM(fmt):
    doc = ezdxf.new("R12", setup=("linetypes", "styles"))
    msp = doc.modelspace()
    ezdxf.setup_dimstyle(doc, fmt)

    msp.add_line((0, 0), (100, 0))
    msp.add_linear_dim(
        base=(0, 100), p1=(0, 0), p2=(100, 0), dimstyle=fmt
    ).render()
    doc.saveas(CWD / f"dim_linear_R12_{fmt}.dxf")


def linear_EZ_MM(fmt):
    doc = ezdxf.new("R12", setup=("linetypes", "styles"))
    msp = doc.modelspace()
    ezdxf.setup_dimstyle(doc, fmt)

    msp.add_line((0, 0), (1000, 0))
    msp.add_linear_dim(
        base=(0, 1000), p1=(0, 0), p2=(1000, 0), dimstyle=fmt
    ).render()
    doc.saveas(CWD / f"dim_linear_R12_{fmt}.dxf")


ALL = False

if __name__ == "__main__":
    example_text_override("R2007")

    if ALL:
        linear_tutorial("R2007")
        linear_tutorial_using_tvp()
        linear_tutorial_using_limits("R2000")
        linear_tutorial_using_limits("R12")
        linear_tutorial_using_tolerances("R2000")
        linear_tutorial_using_tolerances("R12")

        linear_tutorial("R2007")
        linear_tutorial("R12")
        example_background_fill("R2007")
        example_text_override("R2007")

        example_for_all_text_placings_R12()
        example_for_all_text_placings_R2007()

        example_multi_point_linear_dimension()
        example_random_multi_point_linear_dimension(count=10, length=20)

        linear_all_arrow_style("R12")
        linear_all_arrow_style(
            "R12",
            dimltex1="DOT2",
            dimltex2="DOT2",
            filename="dotted_extension_lines_R12.dxf",
        )
        linear_all_arrow_style("R2000")
        linear_all_arrow_style(
            "R2007",
            dimltex1="DOT2",
            dimltex2="DOT2",
            filename="dotted_extension_lines_R2007.dxf",
        )

        linear_tutorial_ext_lines()

        linear_EZ_M("EZ_M_100_H25_CM")
        linear_EZ_M("EZ_M_1_H25_CM")

        linear_EZ_CM("EZ_CM_100_H25_CM")
        linear_EZ_CM("EZ_CM_1_H25_CM")

        linear_EZ_MM("EZ_MM_100_H25_MM")
        linear_EZ_MM("EZ_MM_1_H25_MM")