summaryrefslogtreecommitdiff
path: root/gerbonara/cad/kicad/pcb.py
blob: 06023a5c58d91f99fa812ee93000889578602743 (plain)
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
"""
Library for handling KiCad's PCB files (`*.kicad_mod`).
"""

import math
from pathlib import Path
from dataclasses import field, KW_ONLY, fields
from itertools import chain
import re
import fnmatch
import functools

from .sexp import *
from .base_types import *
from .primitives import *
from .footprints import Footprint, Pad
from . import graphical_primitives as gr
import rtree.index

from .. import primitives as cad_pr

from ... import graphic_primitives as gp
from ... import graphic_objects as go
from ... import apertures as ap
from ...layers import LayerStack
from ...newstroke import Newstroke
from ...utils import MM, rotate_point


def match_filter(f, value):
    if isinstance(f, str) and re.fullmatch(f, value):
        return True
    return value in f

def gn_side_to_kicad(side, layer='Cu'):
    if side == 'top':
        return f'F.{layer}'
    elif side == 'bottom':
        return f'B.{layer}'
    elif side.startswith('inner'):
        return f'In{int(side[5:])}.{layer}'
    else:
        raise ValueError(f'Cannot parse gerbonara side name "{side}"')

def gn_layer_to_kicad(layer, flip=False):
    side = 'B' if flip else 'F'
    if layer == 'silk':
        return f'{side}.SilkS'
    elif layer == 'mask':
        return f'{side}.Mask'
    elif layer == 'paste':
        return f'{side}.Paste'
    elif layer == 'copper':
        return f'{side}.Cu'
    else:
        raise ValueError('Cannot translate gerbonara layer name "{layer}" to KiCad')


@sexp_type('general')
class GeneralSection:
    thickness: Named(float) = 1.60


@sexp_type('layers')
class LayerSettings:
    index: int = 0
    canonical_name: str = None
    layer_type: AtomChoice(Atom.jumper, Atom.mixed, Atom.power, Atom.signal, Atom.user) = Atom.signal
    custom_name: str = None


@sexp_type('layer')
class LayerStackupSettings:
    dielectric: Flag() = False
    name: str = None
    index: int = None
    layer_type: Named(str, name='type') = ''
    color: Color = None
    thickness: Named(float) = None
    material: Named(str) = None
    epsilon_r: Named(float) = None
    loss_tangent: Named(float) = None


@sexp_type('stackup')
class StackupSettings:
    layers: List(LayerStackupSettings) = field(default_factory=list)
    copper_finish: Named(str) = None
    dielectric_constraints: Named(YesNoAtom()) = None
    edge_connector: Named(AtomChoice(Atom.yes, Atom.bevelled)) = None
    castellated_pads: Named(YesNoAtom()) = None
    edge_plating: Named(YesNoAtom()) = None


TFBool = YesNoAtom(yes=Atom.true, no=Atom.false)

@sexp_type('pcbplotparams')
class ExportSettings:
    layerselection: Named(Atom) = None
    plot_on_all_layers_selection: Named(Atom) = None
    disableapertmacros: Named(TFBool) = False
    usegerberextensions: Named(TFBool) = True
    usegerberattributes: Named(TFBool) = True
    usegerberadvancedattributes: Named(TFBool) = True
    creategerberjobfile: Named(TFBool) = True
    dashed_line_dash_ratio: Named(float) = 12.0
    dashed_line_gap_ratio: Named(float) = 3.0
    svguseinch: Named(TFBool) = False
    svgprecision: Named(float) = 4
    excludeedgelayer: Named(TFBool) = False
    plotframeref: Named(TFBool) = False
    viasonmask: Named(TFBool) = False
    mode: Named(int) = 1
    useauxorigin: Named(TFBool) = False
    hpglpennumber: Named(int) = 1
    hpglpenspeed: Named(int) = 20
    hpglpendiameter: Named(float) = 15.0
    pdf_front_fp_property_popups: Named(TFBool) = True
    pdf_back_fp_property_popups: Named(TFBool) = True
    dxfpolygonmode: Named(TFBool) = True
    dxfimperialunits: Named(TFBool) = False
    dxfusepcbnewfont: Named(TFBool) = True
    psnegative: Named(TFBool) = False
    psa4output: Named(TFBool) = False
    plotreference: Named(TFBool) = True
    plotvalue: Named(TFBool) = True
    plotinvisibletext: Named(TFBool) = False
    sketchpadsonfab: Named(TFBool) = False
    subtractmaskfromsilk: Named(TFBool) = False
    outputformat: Named(int) = 1
    mirror: Named(TFBool) = False
    drillshape: Named(int) = 0
    scaleselection: Named(int) = 1
    outputdirectory: Named(str) = "gerber"


@sexp_type('setup')
class BoardSetup:
    stackup: OmitDefault(StackupSettings) = field(default_factory=StackupSettings)
    pad_to_mask_clearance: Named(float) = None
    solder_mask_min_width: Named(float) = None
    pad_to_past_clearance: Named(float) = None
    pad_to_paste_clearance_ratio: Named(float) = None
    aux_axis_origin: Rename(XYCoord) = None
    grid_origin: Rename(XYCoord) = None
    export_settings: ExportSettings = field(default_factory=ExportSettings)


@sexp_type('net')
class Net:
    index: int = 0
    name: str = ''


@sexp_type('segment')
class TrackSegment:
    start: Rename(XYCoord) = field(default_factory=XYCoord)
    end: Rename(XYCoord) = field(default_factory=XYCoord)
    width: Named(float) = 0.5
    layer: Named(str) = 'F.Cu'
    locked: Flag() = False
    net: Named(int) = 0
    tstamp: Timestamp = field(default_factory=Timestamp)

    @classmethod
    def from_footprint_line(kls, line, flip=False):
        # FIXME flip
        return kls(line.start, line.end, line.width or line.stroke.width, line.layer, line.locked, tstamp=line.tstamp)

    def __post_init__(self):
        self.start = XYCoord(self.start)
        self.end = XYCoord(self.end)

    @property
    def layer_mask(self):
        return layer_mask([self.layer])

    def render(self, variables=None, cache=None):
        if not self.width:
            return

        aperture = ap.CircleAperture(self.width, unit=MM)
        yield go.Line(self.start.x, self.start.y, self.end.x, self.end.y, aperture=aperture, unit=MM)

    def rotate(self, angle, cx=None, cy=None):
        if cx is None or cy is None:
            cx, cy = self.start.x, self.start.y

        self.start.x, self.start.y = rotate_point(self.start.x, self.start.y, angle, cx, cy)
        self.end.x, self.end.y = rotate_point(self.end.x, self.end.y, angle, cx, cy)

    def offset(self, x=0, y=0):
        self.start = self.start.with_offset(x, y)
        self.end = self.end.with_offset(x, y)


@sexp_type('arc')
class TrackArc:
    start: Rename(XYCoord) = field(default_factory=XYCoord)
    mid: Rename(XYCoord) = field(default_factory=XYCoord)
    end: Rename(XYCoord) = field(default_factory=XYCoord)
    width: Named(float) = 0.5
    layer: Named(str) = 'F.Cu'
    locked: Flag() = False
    net: Named(int) = 0
    tstamp: Timestamp = field(default_factory=Timestamp)
    _: SEXP_END = None
    center: XYCoord = None

    def __post_init__(self):
        self.start = XYCoord(self.start)
        self.end = XYCoord(self.end)
        self.mid = XYCoord(self.mid) if self.mid else center_arc_to_kicad_mid(XYCoord(self.center), self.start, self.end)
        self.center = None

    @property
    def layer_mask(self):
        return layer_mask([self.layer])

    def render(self, variables=None, cache=None):
        if not self.width:
            return

        aperture = ap.CircleAperture(self.width, unit=MM)
        cx, cy = self.mid.x, self.mid.y
        x1, y1 = self.start.x, self.start.y
        x2, y2 = self.end.x, self.end.y
        yield go.Arc(x1, y1, x2, y2, cx-x1, cy-y1, aperture=aperture, clockwise=True, unit=MM)

    def rotate(self, angle, cx=None, cy=None):
        self.start.x, self.start.y = rotate_point(self.start.x, self.start.y, angle, cx, cy)
        self.mid.x, self.mid.y = rotate_point(self.mid.x, self.mid.y, angle, cx, cy)
        self.end.x, self.end.y = rotate_point(self.end.x, self.end.y, angle, cx, cy)

    def offset(self, x=0, y=0):
        self.start = self.start.with_offset(x, y)
        self.mid = self.mid.with_offset(x, y)
        self.end = self.end.with_offset(x, y)


@sexp_type('via')
class Via:
    via_type: AtomChoice(Atom.blind, Atom.micro) = None
    locked: Flag() = False
    at: Rename(XYCoord) = field(default_factory=XYCoord)
    size: Named(float) = 0.8
    drill: Named(float) = 0.4
    layers: Named(Array(str)) = field(default_factory=lambda: ['F.Cu', 'B.Cu'])
    remove_unused_layers: Flag() = False
    keep_end_layers: Flag() = False
    free: Wrap(Flag()) = False
    net: Named(int) = 0
    tstamp: Timestamp = field(default_factory=Timestamp)

    @classmethod
    def from_pad(kls, pad):
        if pad.type != Atom.thru_hole or pad.shape != Atom.circle:
            raise ValueError('Can only convert circular through-hole pads to vias.')

        if pad.drill and (pad.drill.oval or pad.drill.offset):
            raise ValueError('Can only convert pads with centered, circular drills to vias.')

        x, y, rot, _flip = pad.abs_pos
        return kls(locked=pad.locked,
                   at=XYCoord(x, y),
                   size=max(pad.size.x, pad.size.y),
                   drill=pad.drill.diameter if pad.drill else 0,
                   layers=[l for l in pad.layers if l.endswith('.Cu')],
                   free=True,
                   net=pad.net.number if pad.net else 0,
                   tstamp=pad.tstamp)

    @property
    def abs_pos(self):
        return self.at.x, self.at.y, 0, False

    @property
    def layer_mask(self):
        return layer_mask(self.layers)

    @property
    def width(self):
        return self.size

    def __post_init__(self):
        self.at = XYCoord(self.at)

    def render_drill(self):
        aperture = ap.ExcellonTool(self.drill, plated=True, unit=MM)
        yield go.Flash(self.at.x, self.at.y, aperture=aperture, unit=MM) 

    def render(self, variables=None, cache=None):
        aperture = ap.CircleAperture(self.size, unit=MM)
        yield go.Flash(self.at.x, self.at.y, aperture, unit=MM)

    def rotate(self, angle, cx=None, cy=None):
        if cx is None or cy is None:
            return

        self.at.x, self.at.y = rotate_point(self.at.x, self.at.y, angle, cx, cy)

    def offset(self, x=0, y=0):
        self.at = self.at.with_offset(x, y)


SUPPORTED_FILE_FORMAT_VERSIONS = [20210108, 20211014, 20221018, 20230517]
@sexp_type('kicad_pcb')
class Board:
    _version: Named(int, name='version') = 20230517
    generator: Named(Atom) = Atom.gerbonara
    general: GeneralSection = None
    page: PageSettings = None
    layers: Named(Array(Untagged(LayerSettings))) = field(default_factory=list)
    setup: BoardSetup = field(default_factory=BoardSetup)
    properties: List(Property) = field(default_factory=list)
    nets: List(Net) = field(default_factory=list)
    footprints: List(Footprint) = field(default_factory=list)
    # Graphical elements
    texts: List(gr.Text) = field(default_factory=list)
    text_boxes: List(gr.TextBox) = field(default_factory=list)
    lines: List(gr.Line) = field(default_factory=list)
    rectangles: List(gr.Rectangle) = field(default_factory=list)
    circles: List(gr.Circle) = field(default_factory=list)
    arcs: List(gr.Arc) = field(default_factory=list)
    polygons: List(gr.Polygon) = field(default_factory=list)
    curves: List(gr.Curve) = field(default_factory=list)
    dimensions: List(gr.Dimension) = field(default_factory=list)
    images: List(gr.Image) = field(default_factory=list)
    # Tracks
    track_segments: List(TrackSegment) = field(default_factory=list)
    track_arcs: List(TrackArc) = field(default_factory=list)
    vias: List(Via) = field(default_factory=list)
    # Other stuff
    zones: List(Zone) = field(default_factory=list)
    groups: List(Group) = field(default_factory=list)

    _ : SEXP_END = None
    original_filename: str = None
    _bounding_box: tuple = None
    _trace_index: rtree.index.Index = None
    _trace_index_map: dict = None


    @classmethod
    def empty_board(kls, inner_layers=0, **kwargs):
        if 'setup' not in kwargs:
            kwargs['setup'] = None
        b = Board(**kwargs)
        b.init_default_layers(inner_layers)
        b.__after_parse__(None)
        return b

    def init_default_layers(self, inner_layers=0):
        inner = [(i, f'In{i}.Cu', 'signal', None) for i in range(1, inner_layers+1)]
        self.layers = [LayerSettings(idx, name, Atom(ltype)) for idx, name, ltype, cname in [
            (0, 'F.Cu', 'signal', None),
            *inner,
            (31, 'B.Cu', 'signal', None),
            (32, 'B.Adhes', 'user', 'B.Adhesive'),
            (33, 'F.Adhes', 'user', 'F.Adhesive'),
            (34, 'B.Paste', 'user', None),
            (35, 'F.Paste', 'user', None),
            (36, 'B.SilkS', 'user', 'B.Silkscreen'),
            (37, 'F.SilkS', 'user', 'F.Silkscreen'),
            (38, 'B.Mask', 'user', None),
            (39, 'F.Mask', 'user', None),
            (40, 'Dwgs.User', 'user', 'User.Drawings'),
            (41, 'Cmts.User', 'user', 'User.Comments'),
            (42, 'Eco1.User', 'user', 'User.Eco1'),
            (43, 'Eco2.User', 'user', 'User.Eco2'),
            (44, 'Edge.Cuts', 'user', None),
            (45, 'Margin', 'user', None),
            (46, 'B.CrtYd', 'user', 'B.Courtyard'),
            (47, 'F.CrtYd', 'user', 'F.Courtyard'),
            (48, 'B.Fab', 'user', None),
            (49, 'F.Fab', 'user', None),
            (50, 'User.1', 'user', None),
            (51, 'User.2', 'user', None),
            (52, 'User.3', 'user', None),
            (53, 'User.4', 'user', None),
            (54, 'User.5', 'user', None),
            (55, 'User.6', 'user', None),
            (56, 'User.7', 'user', None),
            (57, 'User.8', 'user', None),
            (58, 'User.9', 'user', None)]]

    def rebuild_trace_index(self):
        idx = self._trace_index = rtree.index.Index()
        id_map = self._trace_index_map = {}
        for obj in chain(self.track_segments, self.track_arcs):
            for field in ('start', 'end'):
                obj_id = id(obj)
                coord = getattr(obj, field)
                id_map[obj_id] = obj, field, obj.width, obj.layer_mask
                idx.insert(obj_id, (coord.x, coord.y, coord.x, coord.y))

        for fp in self.footprints:
            for pad in fp.pads:
                obj_id = id(pad)
                id_map[obj_id] = pad, 'at', 0, pad.layer_mask
                idx.insert(obj_id, (pad.at.x, pad.at.y, pad.at.x, pad.at.y))

        for via in self.vias:
            obj_id = id(via)
            id_map[obj_id] = via, 'at', via.size, via.layer_mask
            idx.insert(obj_id, (via.at.x, via.at.y, via.at.x, via.at.y))
    
    @staticmethod
    def _require_trace_index(fun):
        @functools.wraps(fun)
        def wrapper(self, *args, **kwargs):
            if self._trace_index is None:
                self.rebuild_trace_index()

            return fun(self, *args, **kwargs)
        return wrapper

    @_require_trace_index
    def query_trace_index_nearest(self, point, layers='*.Cu', n=1):
        layers = layer_mask(layers)

        x, y = point
        for obj_id in self._trace_index.nearest((x, y, x, y), n):
            entry = obj, attr, size, mask = self._trace_index_map[obj_id]
            if layers & mask:
                yield entry

    @_require_trace_index
    def query_trace_index_tolerance(self, point, layers='*.Cu', tol=10e-6):
        layers = layer_mask(layers)

        x, y = point
        for obj_id in self._trace_index.intersection((x-tol, y-tol, x+tol, y+tol)):
            entry = obj, attr, size, mask = self._trace_index_map[obj_id]
            attr = getattr(obj, attr)
            if layers & mask and math.dist((attr.x, attr.y), (x, y)) <= tol:
                yield entry

    def find_connected_traces(self, obj, layers='*.Cu', tol=10e-6):
        search_frontier = []
        visited = set()
        def enqueue(obj):
            visited.add(id(obj))

            if isinstance(obj, (TrackSegment, TrackArc)):
                search_frontier.append((obj.start, obj.width, obj.layer_mask))
                search_frontier.append((obj.end, obj.width, obj.layer_mask))

            elif isinstance(obj, Via):
                search_frontier.append((obj.at, obj.size, obj.layer_mask))

            elif isinstance(obj, Pad):
                search_frontier.append((obj.at, max(obj.size.x, obj.size.y), obj.layer_mask))

            elif isinstance(obj, (Footprint)):
                for pad in obj.pads:
                    search_frontier.append((pad.at, max(pad.size.x, pad.size.y), pad.layer_mask))

            else:
                raise TypeError(f'Finding connected traces for {type(obj)} objects is not (yet) supported.')

        enqueue(obj)

        filter_layers = layer_mask(layers)
        while search_frontier:
            coord, size, layers = search_frontier.pop()
            x, y = coord.x, coord.y

            # First, find all bounding box intersections
            found = []
            for cand, attr, cand_size, cand_mask in self.query_trace_index_tolerance((x, y), layers&filter_layers, size):
                cand_coord = getattr(cand, attr)
                dist = math.dist((x, y), (cand_coord.x, cand_coord.y))
                if dist <= size/2 + cand_size/2 and layers&cand_mask:
                    found.append((dist, cand))

            if not found:
                continue

            # Second, filter to match only objects that are within tolerance of closest
            min_dist = min(e[0] for e in found)
            for dist, cand in found:
                if dist < min_dist+tol and id(cand) not in visited:
                    enqueue(cand)
                    yield cand

    def track_skeleton(self, start, tol=10e-6):
        search_frontier = []
        visited = set()
        def enqueue(obj):
            visited.add(id(obj))

            if isinstance(obj, (TrackSegment, TrackArc)):
                search_frontier.append((obj.start, obj.width, obj.layer_mask))
                search_frontier.append((obj.end, obj.width, obj.layer_mask))

            elif isinstance(obj, Via):
                search_frontier.append((obj.at, obj.size, obj.layer_mask))

            elif isinstance(obj, Pad):
                search_frontier.append((obj.at, max(obj.size.x, obj.size.y), obj.layer_mask))

            else:
                raise TypeError(f'Track skeleton starting at {type(obj)} objects is not (yet) supported.')

        enqueue(start)

        while search_frontier:
            coord, size, layers = search_frontier.pop()
            x, y = coord.x, coord.y

            # First, find all bounding box intersections
            found = []
            for cand, attr, cand_size, cand_mask in self.query_trace_index_tolerance((x, y), layers, size):
                cand_coord = getattr(cand, attr)
                dist = math.dist((x, y), (cand_coord.x, cand_coord.y))
                if dist <= size/2 + cand_size/2 and layers&cand_mask:
                    found.append((dist, cand))

            if not found:
                continue

            # Second, filter to match only objects that are within tolerance of closest
            min_dist = min(e[0] for e in found)
            for dist, cand in found:
                if dist < min_dist+tol and id(cand) not in visited:
                    enqueue(cand)
                    yield cand


    def __after_parse__(self, parent):
        self.properties = {prop.key: prop.value for prop in self.properties}

        for fp in self.footprints:
            fp.board = self

        self.nets = {net.index: net.name for net in self.nets}

    def __before_sexp__(self):
        self.properties = [Property(key, value) for key, value in self.properties.items()]
        self.nets = [Net(index, name) for index, name in self.nets.items()]

    def remove(self, obj):
        match obj:
            case gr.Text():
                self.texts.remove(obj)
            case gr.TextBox():
                self.text_boxes.remove(obj)
            case gr.Line():
                self.lines.remove(obj)
            case gr.Rectangle():
                self.rectangles.remove(obj)
            case gr.Circle():
                self.circles.remove(obj)
            case gr.Arc():
                self.arcs.remove(obj)
            case gr.Polygon():
                self.polygons.remove(obj)
            case gr.Curve():
                self.curves.remove(obj)
            case gr.Dimension():
                self.dimensions.remove(obj)
            case gr.Image():
                self.images.remove(obj)
            case TrackSegment():
                self.track_segments.remove(obj)
            case TrackArc():
                self.track_arcs.remove(obj)
            case Via():
                self.vias.remove(obj)
            case Zone():
                self.zones.remove(obj)
            case Group():
                self.groups.remove(obj)
            case Footprint():
                self.footprints.remove(obj)
            case _:
                raise TypeError('Can only remove KiCad objects, cannot map generic gerbonara.cad objects for removal')

    def remove_many(self, iterable):
        iterable = {id(obj) for obj in iterable}
        for field in fields(self):
            if field.default_factory is list and field.name not in ('nets', 'properties'):
                setattr(self, field.name, [obj for obj in getattr(self, field.name) if id(obj) not in iterable])

    def add(self, obj):
        match obj:
            case gr.Text():
                self.texts.append(obj)
            case gr.TextBox():
                self.text_boxes.append(obj)
            case gr.Line():
                self.lines.append(obj)
            case gr.Rectangle():
                self.rectangles.append(obj)
            case gr.Circle():
                self.circles.append(obj)
            case gr.Arc():
                self.arcs.append(obj)
            case gr.Polygon():
                self.polygons.append(obj)
            case gr.Curve():
                self.curves.append(obj)
            case gr.Dimension():
                self.dimensions.append(obj)
            case gr.Image():
                self.images.append(obj)
            case TrackSegment():
                self.track_segments.append(obj)
            case TrackArc():
                self.track_arcs.append(obj)
            case Via():
                self.vias.append(obj)
            case Zone():
                self.zones.append(obj)
            case Group():
                self.groups.append(obj)
            case Footprint():
                self.footprints.append(obj)
            case _:
                for elem in self.map_gn_cad(obj):
                    self.add(elem)

    def map_gn_cad(self, obj, locked=False, net_name=None):
        match obj:
            case cad_pr.Trace():
                for elem in obj.to_graphic_objects():
                    elem.convert_to(MM)
                    match elem:
                        case go.Arc(x1, y1, x2, y2, xc, yc, cw, ap):
                            yield TrackArc(
                                start=XYCoord(x1, y1),
                                mid=XYCoord(x1+xc, y1+yc),
                                end=XYCoord(x2, y2),
                                width=ap.equivalent_width(MM),
                                layer=gn_side_to_kicad(obj.side),
                                locked=locked, 
                                net=self.net_id(net_name))

                        case go.Line(x1, y1, x2, y2, ap):
                            yield TrackSegment(
                                start=XYCoord(x1, y1),
                                end=XYCoord(x2, y2),
                                width=ap.equivalent_width(MM),
                                layer=gn_side_to_kicad(obj.side),
                                locked=locked,
                                net=self.net_id(net_name))

            case cad_pr.Via(pad_stack=cad_pr.ThroughViaStack(hole, dia, unit=st_unit)):
                x, y, _a, _f = obj.abs_pos
                x, y = MM(x, st_unit), MM(y, obj.unit)
                yield Via(
                    locked=locked,
                    at=XYCoord(x, y),
                    size=MM(dia, st_unit),
                    drill=MM(hole, st_unit),
                    layers='*.Cu',
                    net=self.net_id(net_name))

            case cad_pr.Text(_x, _y, text, font_size, stroke_width, h_align, v_align, layer, dark):
                x, y, a, flip = obj.abs_pos
                x, y = MM(x, st_unit), MM(y, st_unit)
                size = MM(size, unit)
                yield gr.Text(
                    text, 
                    AtPos(x, y, -math.degrees(a)),
                    layer=gr.TextLayer(gn_layer_to_kicad(layer, flip), not dark),
                    effects=TextEffect(font=FontSpec(
                            size=XYCoord(size, size),
                            thickness=stroke_width),
                        justify=Justify(h=Atom(h_align) if h_align != 'center' else None,
                                        v=Atom(v_align) if v_align != 'middle' else None,
                                        mirror=flip)))

    def unfill_zones(self):
        for zone in self.zones:
            zone.unfill()

    def find_pads(self, net=None):
        for fp in self.footprints:
            for pad in fp.pads:
                if net and not match_filter(net, pad.net.name):
                    continue
                yield pad

    def find_footprints(self, value=None, reference=None, name=None, net=None, sheetname=None, sheetfile=None):
        for fp in self.footprints:
            if name and not match_filter(name, fp.name):
                continue
            if value and not match_filter(value, fp.properties.get('value', '')):
                continue
            if reference and not match_filter(reference, fp.properties.get('reference', '')):
                continue
            if net and not any(match_filter(net, pad.net.name) for pad in fp.pads):
                continue
            if sheetname and not match_filter(sheetname, fp.sheetname):
                continue
            if sheetfile and not match_filter(sheetfile, fp.sheetfile):
                continue
            yield fp

    def find_traces(self, net=None, include_vias=True):
        net_id = self.net_id(net, create=False)
        match = lambda obj: obj.net == net_id
        for obj in chain(self.track_segments, self.track_arcs, self.vias):
            if obj.net == net_id:
                yield obj

    @property
    def version(self):
        return self._version

    @version.setter
    def version(self, value):
        if value not in SUPPORTED_FILE_FORMAT_VERSIONS:
            raise FormatError(f'File format version {value} is not supported. Supported versions are {", ".join(map(str, SUPPORTED_FILE_FORMAT_VERSIONS))}.')

    def write(self, filename=None):
        with open(filename or self.original_filename, 'w') as f:
            f.write(self.serialize())

    def serialize(self):
        return build_sexp(sexp(type(self), self)[0])

    @classmethod
    def open(kls, pcb_file, *args, **kwargs):
        return kls.load(Path(pcb_file).read_text(), *args, **kwargs, original_filename=pcb_file)

    @classmethod
    def load(kls, data, *args, **kwargs):
        return kls.parse(data, *args, **kwargs)

    @property
    def single_sided(self):
        raise NotImplementedError()

    def net_id(self, name, create=True):
        if name is None:
            return None

        for i, n in self.nets.items():
            if n == name:
                return i

        if create:
            index = max(self.nets.keys()) + 1
            self.nets[index] = name
            return index

        else:
            raise IndexError(f'No such net: "{name}"')

# FIXME vvv
    def graphic_objects(self, text=False, images=False):
        return chain(
                (self.texts if text else []),
                (self.text_boxes if text else []),
                self.lines,
                self.rectangles,
                self.circles,
                self.arcs,
                self.polygons,
                self.curves,
                (self.dimensions if text else []),
                (self.images if images else []))


    def tracks(self, vias=True):
        return chain(self.track_segments, self.track_arcs, (self.vias if vias else []))


    def objects(self, vias=True, text=False, images=False):
        return chain(self.graphic_objects(text=text, images=images), self.tracks(vias=vias), self.footprints, self.zones, self.groups)


    def render(self, layer_stack, layer_map, x=0, y=0, rotation=0, text=False, flip=False, variables={}, cache=None):
        for obj in self.objects(images=False, vias=False, text=text):
            if not (layer := layer_map.get(obj.layer)):
                continue

            for fe in obj.render(variables=variables):
                fe.rotate(rotation)
                fe.offset(x, y, MM)
                layer_stack[layer].objects.append(fe)

        for obj in self.vias:
            for glob in obj.layers or []:
                for layer in fnmatch.filter(layer_map, glob):
                    for fe in obj.render(cache=cache):
                        fe.rotate(rotation)
                        fe.offset(x, y, MM)
                        fe.aperture = fe.aperture.rotated(rotation)
                        layer_stack[layer_map[layer]].objects.append(fe)

            for fe in obj.render_drill():
                fe.rotate(rotation)
                fe.offset(x, y, MM)
                layer_stack.drill_pth.append(fe)

    def bounding_box(self, unit=MM):
        if not self._bounding_box:
            stack = LayerStack()
            layer_map = {kc_id: gn_id for kc_id, gn_id in LAYER_MAP_K2G.items() if gn_id in stack}
            self.render(stack, layer_map, x=0, y=0, rotation=0, flip=False, text=False, variables={})
            self._bounding_box = stack.bounding_box(unit)
        return self._bounding_box

 
@dataclass
class BoardInstance(cad_pr.Positioned):
    sexp: Board = None
    variables: dict = field(default_factory=lambda: {})

    def render(self, layer_stack, cache=None):
        x, y, rotation, flip = self.abs_pos
        x, y = MM(x, self.unit), MM(y, self.unit)

        variables = dict(self.variables)

        layer_map = {kc_id: gn_id for kc_id, gn_id in LAYER_MAP_K2G.items() if gn_id in layer_stack}

        self.sexp.render(layer_stack, layer_map,
                         x=x, y=y, rotation=rotation,
                         flip=flip,
                         variables=variables, cache=cache)
    
    def bounding_box(self, unit=MM):
        return offset_bounds(self.sexp.bounding_box(unit), unit(self.x, self.unit), unit(self.y, self.unit))


if __name__ == '__main__':
    import sys
    from ...layers import LayerStack
    fp = Board.open(sys.argv[1])
    stack = LayerStack()
    BoardInstance(0, 0, fp, unit=MM).render(stack)
    print(stack.to_pretty_svg())
    stack.save_to_directory('/tmp/testdir')