/
panelize.py
2252 lines (1950 loc) · 92.2 KB
/
panelize.py
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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from copy import deepcopy
import itertools
from pcbnewTransition import pcbnew, isV6
from kikit import sexpr
from kikit.common import normalize
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Set, Tuple, Union
from pcbnewTransition.pcbnew import (LoadBoard, ToMM, VECTOR2I, BOX2I, EDA_ANGLE)
from enum import Enum
from shapely.geometry import (Polygon, MultiPolygon, Point, LineString, box,
GeometryCollection, MultiLineString)
from shapely.prepared import prep
import shapely
import shapely.affinity
from itertools import product, chain
import numpy as np
import os
import json
import re
import fnmatch
from collections import OrderedDict
from kikit import substrate
from kikit import units
from kikit.kicadUtil import getPageDimensionsFromAst
from kikit.substrate import Substrate, linestringToKicad, extractRings
from kikit.defs import PAPER_DIMENSIONS, STROKE_T, Layer, EDA_TEXT_HJUSTIFY_T, EDA_TEXT_VJUSTIFY_T, PAPER_SIZES
from kikit.common import *
from kikit.sexpr import isElement, parseSexprF, SExpr, Atom, findNode, parseSexprListF
from kikit.annotations import AnnotationReader, TabAnnotation
from kikit.drc import DrcExclusion, readBoardDrcExclusions, serializeExclusion
from kikit.units import mm, deg
class PanelError(RuntimeError):
pass
class TooLargeError(PanelError):
pass
def identity(x):
return x
class GridPlacerBase:
def position(self, i: int, j: int, boardSize: Optional[BOX2I]) -> VECTOR2I:
"""
Given row and col coords of a board, return physical physical position
of the board. All function calls (except for 0, 0) also receive board
size.
The position of the board is relative to the top-left board, coordinates
(0, 0) should yield placement (0, 0).
"""
raise NotImplementedError("GridPlacerBase.position has to be overridden")
def rotation(self, i: int, j: int) -> int:
"""
Given row and col coords of a board, return the orientation of the board
"""
return 0
class BasicGridPosition(GridPlacerBase):
"""
Specify board position in the grid.
"""
def __init__(self, horSpace: int, verSpace: int,
hbonewidth: int=0, vbonewidth: int=0,
hboneskip: int=0, vboneskip: int=0,
hbonefirst: int=0, vbonefirst: int=0) -> None:
self.horSpace = horSpace
self.verSpace = verSpace
self.hbonewidth = hbonewidth
self.vbonewidth = vbonewidth
self.hboneskip = hboneskip
self.vboneskip = vboneskip
self.hbonefirst = hbonefirst
self.vbonefirst = vbonefirst
def position(self, i: int, j: int, boardSize: Optional[BOX2I]) -> VECTOR2I:
if boardSize is None:
assert i == 0 and j == 0
boardSize = BOX2I(VECTOR2I(0, 0), VECTOR2I(0, 0))
hbonecount = 0 if self.hbonewidth == 0 \
else max((i + self.hbonefirst) // (self.hboneskip + 1), 0)
vbonecount = 0 if self.vbonewidth == 0 \
else max((j + self.vbonefirst) // (self.vboneskip + 1), 0)
xPos = j * (boardSize.GetWidth() + self.horSpace) + \
vbonecount * (self.vbonewidth + self.horSpace)
yPos = i * (boardSize.GetHeight() + self.verSpace) + \
hbonecount * (self.hbonewidth + self.verSpace)
return toKiCADPoint((xPos, yPos))
def rotation(self, i: int, j: int) -> KiAngle:
return EDA_ANGLE(0, pcbnew.DEGREES_T)
class OddEvenRowsPosition(BasicGridPosition):
"""
Rotate boards by 180° for every row
"""
def rotation(self, i: int, j: int) -> KiAngle:
if i % 2 == 0:
return EDA_ANGLE(0, pcbnew.DEGREES_T)
return EDA_ANGLE(180, pcbnew.DEGREES_T)
class OddEvenColumnPosition(BasicGridPosition):
"""
Rotate boards by 180° for every column
"""
def rotation(self, i: int, j: int) -> KiAngle:
if j % 2 == 0:
return EDA_ANGLE(0, pcbnew.DEGREES_T)
return EDA_ANGLE(180, pcbnew.DEGREES_T)
class OddEvenRowsColumnsPosition(BasicGridPosition):
"""
Rotate boards by 180 for every row and column
"""
def rotation(self, i: int, j: int) -> KiAngle:
if (i % 2) == (j % 2):
return 0
return EDA_ANGLE(180, pcbnew.DEGREES_T)
class Origin(Enum):
Center = 0
TopLeft = 1
TopRight = 2
BottomLeft = 3
BottomRight = 4
class NetClass():
"""
Internal representation of a netclass. Work-around for KiCAD 6.0.6 missing
support for netclasses in API
"""
def __init__(self, netClassDef: Any) -> None:
self.data = netClassDef
self.nets: Set[str] = set()
@property
def name(self) -> str:
return self.data["name"]
@property
def originalNets(self) -> List[str]:
return self.data.get("nets", [])
def addNet(self, netname: str) -> None:
self.nets.add(netname)
def serialize(self) -> Any:
data = deepcopy(self.data)
if isV6():
data["nets"] = list(self.nets)
return data
def getOriginCoord(origin, bBox):
"""Returns real coordinates (VECTOR2I) of the origin for given bounding box"""
if origin == Origin.Center:
return VECTOR2I(bBox.GetX() + bBox.GetWidth() // 2,
bBox.GetY() + bBox.GetHeight() // 2)
if origin == Origin.TopLeft:
return VECTOR2I(bBox.GetX(), bBox.GetY())
if origin == Origin.TopRight:
return VECTOR2I(bBox.GetX() + bBox.GetWidth(), bBox.GetY())
if origin == Origin.BottomLeft:
return VECTOR2I(bBox.GetX(), bBox.GetY() + bBox.GetHeight())
if origin == Origin.BottomRight:
return VECTOR2I(bBox.GetX() + bBox.GetWidth(), bBox.GetY() + bBox.GetHeight())
def appendItem(board: pcbnew.BOARD, item: pcbnew.BOARD_ITEM,
yieldMapping: Optional[Callable[[str, str], None]]=None) -> None:
"""
Make a coppy of the item and append it to the board. Allows to append items
from one board to another.
It can also yield mapping between old item identifier and a new one via the
yieldMapping callback. This callback is invoked with an old ID and the new
ID. Mapping is applicable only in v6.
"""
try:
newItem = item.Duplicate()
except TypeError: # Footprint has overridden the method, cannot be called directly
newItem = pcbnew.Cast_to_BOARD_ITEM(item).Duplicate().Cast()
board.Add(newItem)
if not yieldMapping:
return
if isinstance(item, pcbnew.FOOTPRINT):
newFootprint = pcbnew.Cast_to_FOOTPRINT(newItem)
for getter in [lambda x: x.Pads(), lambda x: x.GraphicalItems(), lambda x: x.Zones()]:
oldList = getter(item)
newList = getter(newFootprint)
assert len(oldList) == len(newList)
for o, n in zip(oldList, newList):
assert o.GetPosition() == n.GetPosition()
yieldMapping(o.m_Uuid.AsString(), n.m_Uuid.AsString())
yieldMapping(item.m_Uuid.AsString(), newItem.m_Uuid.AsString())
def collectNetNames(board):
return [str(x) for x in board.GetNetInfo().NetsByName() if len(str(x)) > 0]
def remapNets(collection, mapping):
for item in collection:
item.SetNetCode(mapping[item.GetNetname()].GetNetCode())
ToPolygonGeometry = Union[Polygon, BOX2I, Substrate]
def toPolygon(entity: Union[List[ToPolygonGeometry], ToPolygonGeometry]) -> Polygon:
if isinstance(entity, list):
return list([toPolygon(e) for e in entity])
if isinstance(entity, Polygon) or isinstance(entity, MultiPolygon):
return entity
if isinstance(entity, BOX2I):
return Polygon([
(entity.GetX(), entity.GetY()),
(entity.GetX() + entity.GetWidth(), entity.GetY()),
(entity.GetX() + entity.GetWidth(), entity.GetY() + entity.GetHeight()),
(entity.GetX(), entity.GetY() + entity.GetHeight())])
if isinstance(entity, Substrate):
return Substrate.substrates
raise NotImplementedError("Cannot convert {} to Polygon".format(type(entity)))
def rectString(rect):
return "({}, {}) w: {}, h: {}".format(
ToMM(rect.GetX()), ToMM(rect.GetY()),
ToMM(rect.GetWidth()), ToMM(rect.GetHeight()))
def expandRect(rect: BOX2I, offsetX: KiLength, offsetY: Optional[KiLength]=None):
"""
Given a BOX2I returns a new rectangle, which is larger in all directions
by offset. If only offsetX is passed, it used for both X and Y offset
"""
if offsetY is None:
offsetY = offsetX
offsetX = int(offsetX)
offsetY = int(offsetY)
return BOX2I(
VECTOR2I(rect.GetX() - offsetX, rect.GetY() - offsetY),
VECTOR2I(rect.GetWidth() + 2 * offsetX, rect.GetHeight() + 2 * offsetY))
def rectToRing(rect):
return [
(rect.GetX(), rect.GetY()),
(rect.GetX() + rect.GetWidth(), rect.GetY()),
(rect.GetX() + rect.GetWidth(), rect.GetY() + rect.GetHeight()),
(rect.GetX(), rect.GetY() + rect.GetHeight())
]
def roundPoint(point, precision=-4):
if isinstance(point, Point):
return Point(round(point.x, precision), round(point.y, precision))
return Point(round(point[0], precision), round(point[1], precision))
def doTransformation(point: KiPoint, rotation: KiAngle, origin: KiPoint, translation: KiPoint) -> VECTOR2I:
"""
Abuses KiCAD to perform a tranformation of a point
"""
segment = pcbnew.PCB_SHAPE()
segment.SetShape(STROKE_T.S_SEGMENT)
segment.SetStart(toKiCADPoint(point))
segment.SetEnd(VECTOR2I(0, 0))
segment.Rotate(toKiCADPoint(origin), -1 * rotation)
segment.Move(toKiCADPoint(translation))
# We build a fresh VECTOR2I - otherwise there is a shared reference
return VECTOR2I(segment.GetStartX(), segment.GetStartY())
def undoTransformation(point, rotation, origin, translation):
"""
We apply a transformation "Rotate around origin and then translate" when
placing a board. Given a point and original transformation parameters,
return the original point position.
"""
# Abuse PcbNew to do so
segment = pcbnew.PCB_SHAPE()
segment.SetShape(STROKE_T.S_SEGMENT)
segment.SetStart(VECTOR2I(int(point[0]), int(point[1])))
segment.SetEnd(VECTOR2I(0, 0))
segment.Move(VECTOR2I(-translation[0], -translation[1]))
segment.Rotate(origin, -1 * rotation)
# We build a fresh VECTOR2I - otherwise there is a shared reference
return VECTOR2I(segment.GetStartX(), segment.GetStartY())
def removeCutsFromFootprint(footprint):
"""
Find all graphical items in the footprint, remove them and return them as a
list
"""
edges = []
for edge in footprint.GraphicalItems():
if edge.GetLayer() != Layer.Edge_Cuts:
continue
edges.append(edge)
for e in edges:
footprint.Remove(e)
return edges
def renameNets(board, renamer):
"""
Given a board and renaming function (taking original name, returning new
name) renames the nets
"""
originalNetNames = collectNetNames(board)
netinfo = board.GetNetInfo()
newNetMapping = { "": netinfo.GetNetItem("") }
newNames = set()
for name in originalNetNames:
newName = renamer(name)
newNet = pcbnew.NETINFO_ITEM(board, newName)
newNetMapping[name] = newNet
board.Add(newNet)
newNames.add(newName)
remapNets(board.GetPads(), newNetMapping)
remapNets(board.GetTracks(), newNetMapping)
remapNets(board.Zones(), newNetMapping)
for name in originalNetNames:
if name != "" and name not in newNames:
board.RemoveNative(netinfo.GetNetItem(name))
def renameRefs(board, renamer):
"""
Given a board and renaming function (taking original name, returning new
name) renames the references
"""
for footprint in board.GetFootprints():
ref = footprint.Reference().GetText()
footprint.Reference().SetText(renamer(ref))
def isBoardEdge(edge):
"""
Decide whether the drawing is a board edge or not.
The rule is: all drawings on Edge.Cuts layer are edges.
"""
return isinstance(edge, pcbnew.PCB_SHAPE) and edge.GetLayerName() == "Edge.Cuts"
def increaseZonePriorities(board, amount=1):
for zone in board.Zones():
zone.SetAssignedPriority(zone.GetAssignedPriority() + amount)
def tabSpacing(width, count):
"""
Given a width of board edge and tab count, return an iterable with tab
offsets.
"""
return [width * i / (count + 1) for i in range(1, count + 1)]
def prolongCut(cut, prolongation):
"""
Given a cut (Shapely LineString) it tangentially prolongs it by prolongation
"""
c = list([np.array(x) for x in cut.coords])
c[0] += normalize(c[0] - c[1]) * prolongation
c[-1] += normalize(c[-1] - c[-2]) * prolongation
return LineString(c)
def polygonToZone(polygon, board):
"""
Given a polygon and target board, creates a KiCAD zone. The zone has to be
added to the board.
"""
zone = pcbnew.ZONE(board)
boundary = polygon.exterior
zone.Outline().AddOutline(linestringToKicad(boundary))
for hole in polygon.interiors:
boundary = hole.exterior
zone.Outline().AddHole(linestringToKicad(boundary))
return zone
def buildTabs(substrate: Substrate,
partitionLines: Union[GeometryCollection, LineString],
tabAnnotations: Iterable[TabAnnotation], fillet: KiLength = 0) -> \
Tuple[List[Polygon], List[LineString]]:
"""
Given substrate, partitionLines of the substrate and an iterable of tab
annotations, build tabs. Note that if the tab does not hit the partition
line, it is not included in the design.
Return a pair of lists: tabs and cuts.
"""
tabs, cuts = [], []
for annotation in tabAnnotations:
t, c = substrate.tab(annotation.origin, annotation.direction,
annotation.width, partitionLines, annotation.maxLength, fillet)
if t is not None:
tabs.append(t)
cuts.append(c)
return tabs, cuts
def normalizePartitionLineOrientation(line):
"""
Given a LineString or MultiLineString, normalize orientation of the
partition line. For open linestrings, the orientation does not matter. For
closed linerings, it has to be counter-clock-wise.
"""
if isinstance(line, MultiLineString):
return MultiLineString([normalizePartitionLineOrientation(x) for x in line.geoms])
if isinstance(line, GeometryCollection):
return GeometryCollection([normalizePartitionLineOrientation(l) for l in line.geoms])
if not isLinestringCyclic(line):
return line
r = LinearRing(line.coords)
if not r.is_ccw:
return line
return LineString(list(r.coords)[::-1])
def maxTabCount(edgeLen, width, minDistance):
"""
Given a length of edge, tab width and their minimal distance, return maximal
number of tabs.
"""
if edgeLen < width:
return 0
c = 1 + (edgeLen - minDistance) // (minDistance + width)
return max(0, int(c))
def skipBackbones(backbones: List[LineString], skip: int, first: int,
key: Callable[[LineString], int]) -> List[LineString]:
"""
Given a list of backbones, get only every (skip + 1) other one. Treats
all backbones on a given coordinate as one.
"""
candidates = list(set(map(key, backbones)))
candidates.sort()
active = set(itertools.islice(candidates, first - 1, None, skip + 1))
return [x for x in backbones if key(x) in active]
def bakeTextVars(board: pcbnew.BOARD) -> None:
"""
Given a board, expand text variables in all text items on the board.
"""
for drawing in board.GetDrawings():
if not isinstance(drawing, pcbnew.PCB_TEXT):
continue
drawing.SetText(drawing.GetShownText())
class Panel:
"""
Basic interface for panel building. Instance of this class represents a
single panel. You can append boards, add substrate pieces, make cuts or add
holes to the panel. Once you finish, you have to save the panel to a file.
Since KiCAD 6, the board is coupled with a project files (DRC rules), so
we have to specify a filename when creating a panel. Corresponding project
file will be created.
"""
def __init__(self, panelFilename):
"""
Initializes empty panel. Note that due to the restriction of KiCAD 6,
when boards are always associated with a project, you have to pass a
name of the resulting file.
"""
self.filename = panelFilename
self.board = pcbnew.NewBoard(panelFilename)
self.sourcePaths = set() # A set of all board files that were appended to the panel
self.substrates = [] # Substrates of the individual boards; e.g. for masking
self.boardSubstrate = Substrate([]) # Keep substrate in internal representation,
# Draw it just before saving
self.backboneLines = []
self.hVCuts = set() # Keep V-cuts as numbers and append them just before saving
self.vVCuts = set() # to make them truly span the whole panel
self.vCutLayer = Layer.Cmts_User
self.vCutClearance = 0
self.copperLayerCount = None
self.renderedMousebiteCounter = 0
self.zonesToRefill = pcbnew.ZONES()
self.pageSize: Union[None, str, Tuple[int, int]] = None
self.annotationReader: AnnotationReader = AnnotationReader.getDefault()
self.drcExclusions: List[DrcExclusion] = []
# At the moment (KiCAD 6.0.6) has broken support for net classes.
# Therefore we have to handle them separately
self.newNetClasses: Dict[str, Any] = {}
self.netCLassPatterns: List[Dict[str, str]] = []
self.customDRCRules: List[SExpr] = []
# KiCAD allows to keep text variables for project. We keep a set of
# dictionary of variables for each appended board.
self.projectVars: List[Dict[str, str]] = []
# We want to prolong dimensions of the panel by the size of fillet or
# chamfer, thus, we have to remember them
self.filletSize: Optional[KiLength] = None
self.chamferWidth: Optional[KiLength] = None
self.chamferHeight: Optional[KiLength] = None
def save(self, reconstructArcs: bool=False, refillAllZones: bool=False):
"""
Saves the panel to a file and makes the requested changes to the prl and
pro files.
"""
panelEdges = self.boardSubstrate.serialize(reconstructArcs)
boardsEdges = self._getRefillEdges(reconstructArcs)
vcuts = self._renderVCutH() + self._renderVCutV()
keepouts = []
for cut, clearanceArea in vcuts:
self.board.Add(cut)
if clearanceArea is not None:
keepouts.append(self.addKeepout(clearanceArea))
# Rendering happens in two phases:
# - first, we render original board edges and save the board (to
# propagate all the design rules from project files)
# - then we load the board, fill polygons and render panel edges.
for edge in boardsEdges:
self.board.Add(edge)
# We mark zone to refill via name prefix - this is the only way we can
# remember it between saves
originalZoneNames = {}
for i, zone in enumerate(self.zonesToRefill):
newName = f"KIKIT_zone_{i}"
originalZoneNames[newName] = zone.GetZoneName()
zone.SetZoneName(newName)
self.board.Save(self.filename)
self.makeLayersVisible() # as they are not in KiCAD 6
self.transferProjectSettings()
self.writeCustomDrcRules()
# Remove cuts
for cut, _ in vcuts:
self.board.Remove(cut)
# Remove V-cuts keepouts
for keepout in keepouts:
self.board.Remove(keepout)
# Remove edges
for edge in panelEdges:
self.board.Remove(edge)
# Handle zone refilling in a separate board
fillBoard = pcbnew.LoadBoard(self.filename)
fillerTool = pcbnew.ZONE_FILLER(fillBoard)
if refillAllZones:
fillerTool.Fill(fillBoard.Zones())
for edge in collectEdges(fillBoard, Layer.Edge_Cuts):
fillBoard.Remove(edge)
for edge in panelEdges:
fillBoard.Add(edge)
if self.vCutLayer == Layer.Edge_Cuts:
vcuts = self._renderVCutH() + self._renderVCutV()
for cut, _ in vcuts:
fillBoard.Add(cut)
zonesToRefill = pcbnew.ZONES()
for zone in fillBoard.Zones():
zName = zone.GetZoneName()
if zName.startswith("KIKIT_zone_"):
zonesToRefill.append(zone)
zone.SetZoneName(originalZoneNames[zName])
fillerTool.Fill(zonesToRefill)
fillBoard.Save(self.filename)
self._adjustPageSize()
def _getRefillEdges(self, reconstructArcs: bool):
"""
Builds a list of edges that represent boards outlines and panel
surrounding as independent pieces of substrate
"""
boardsEdges = list(chain(*[sub.serialize(reconstructArcs) for sub in self.substrates]))
surrounding = self.boardSubstrate.substrates.simplify(fromMm(0.01)).difference(
shapely.ops.unary_union(list(
sub.substrates.buffer(fromMm(0.2)) for sub in self.substrates)).simplify(fromMm(0.01)))
surroundingSubstrate = Substrate([])
surroundingSubstrate.union(surrounding)
boardsEdges += surroundingSubstrate.serialize()
return boardsEdges
def _uniquePrefix(self):
return "Board_{}-".format(len(self.substrates))
def getProFilepath(self, path=None):
if path == None:
p = self.filename
else:
p = path
return os.path.splitext(p)[0]+'.kicad_pro'
def getPrlFilepath(self, path=None):
if path == None:
p = self.filename
else:
p = path
return os.path.splitext(p)[0]+'.kicad_prl'
def getDruFilepath(self, path=None):
if path == None:
p = self.filename
else:
p = path
return os.path.splitext(p)[0]+'.kicad_dru'
def makeLayersVisible(self):
"""
Modify corresponding *.prl files so all the layers are visible by
default
"""
try:
with open(self.getPrlFilepath(), encoding="utf-8") as f:
# We use ordered dict, so we preserve the ordering of the keys and
# thus, formatting
prl = json.load(f, object_pairs_hook=OrderedDict)
prl["board"]["visible_layers"] = "fffffff_ffffffff"
with open(self.getPrlFilepath(), "w", encoding="utf-8") as f:
json.dump(prl, f, indent=2)
except IOError:
# The PRL file is not always created, ignore it
pass
def writeCustomDrcRules(self):
with open(self.getDruFilepath(), "w", encoding="utf-8") as f:
f.write("(version 1)\n\n")
for r in self.customDRCRules:
f.write(str(r))
def transferProjectSettings(self):
"""
Examine DRC rules of the source boards, merge them into a single set of
rules and store them in *.kicad_pro file. Also stores board DRC
exclusions.
Also, transfers the list of net classes from the internal representation
into the project file.
"""
if len(self.sourcePaths) > 1:
raise RuntimeError("Merging of DRC rules of multiple boards is currently unsupported")
if len(self.sourcePaths) == 0:
return # Nothing to merge
sPath = list(self.sourcePaths)[0]
try:
with open(self.getProFilepath(sPath), encoding="utf-8") as f:
sourcePro = json.load(f)
except (IOError, FileNotFoundError):
# This means there is no original project file. Probably comes from
# v5, thus there is nothing to transfer
return
try:
with open(self.getProFilepath(), encoding="utf-8") as f:
currentPro = json.load(f, object_pairs_hook=OrderedDict)
currentPro["board"]["design_settings"] = sourcePro["board"]["design_settings"]
currentPro["board"]["design_settings"]["drc_exclusions"] = [
serializeExclusion(e) for e in self.drcExclusions]
currentPro["text_variables"] = sourcePro.get("text_variables", {})
currentPro["net_settings"]["classes"] = sourcePro["net_settings"]["classes"]
currentPro["net_settings"]["classes"] += [x.serialize() for x in self.newNetClasses.values()]
currentPro["net_settings"]["netclass_patterns"] = self.netCLassPatterns
with open(self.getProFilepath(), "w", encoding="utf-8") as f:
json.dump(currentPro, f, indent=2)
except (KeyError, FileNotFoundError):
# This means the source board has no DRC setting. Probably a board
# without attached project
pass
def _assignNetToClasses(self, nets: Iterable[str], patterns: List[Tuple[str, str]])\
-> Dict[str, Set[str]]:
def safeCompile(p):
try:
return re.compile(p)
except Exception:
return None
regexes = [
(netclass, safeCompile(pattern)) for netclass, pattern in patterns
]
assignment: Dict[str, Set[str]] = {
netclass: set() for netclass, _ in patterns
}
for net in nets:
for netclass, pattern in patterns:
if fnmatch.fnmatch(net, pattern):
assignment[netclass].add(net)
for netclass, regex in regexes:
if regex is not None and regex.match(net):
assignment[netclass].add(net)
return assignment
def _inheritNetClasses(self, board, netRenamer):
"""
KiCADhas broken API for net classes. Therefore, we have to load and save
the net classes manually in the project file.
KiCAD 6 uses the approach of explicitly listing all nets, KiCAD 7 uses
patterns instead. The code below tries to cover both cases in a
non-conflicting way.
"""
proFilename = os.path.splitext(board.GetFileName())[0]+'.kicad_pro'
try:
with open(proFilename, encoding="utf-8") as f:
project = json.load(f)
except FileNotFoundError:
# If the source board doesn't contain project, there's nothing to
# inherit.
return
boardNetsNames = collectNetNames(board)
netClassPatterns = [
(p["netclass"], p["pattern"])
for p in project["net_settings"].get("netclass_patterns", [])
]
netAssignment = self._assignNetToClasses(boardNetsNames, netClassPatterns)
seenNets = set()
for c in project["net_settings"]["classes"]:
origName = c["name"]
c["name"] = netRenamer(c["name"])
nc = NetClass(c)
for net in chain(nc.originalNets, netAssignment.get(origName, [])):
seenNets.add(net)
nc.addNet(netRenamer(net))
self.newNetClasses[nc.name] = nc
defaultNetClass = self.newNetClasses[netRenamer("Default")]
for name in boardNetsNames:
if name in seenNets:
continue
defaultNetClass.addNet(netRenamer(name))
for net in defaultNetClass.nets:
self.netCLassPatterns.append({
"netclass": defaultNetClass.name,
"pattern": net
})
for netclass, pattern in netClassPatterns:
self.netCLassPatterns.append({
"netclass": netRenamer(netclass),
"pattern": netRenamer(pattern)
})
def _inheriCustomDrcRules(self, board, netRenamer):
"""
KiCADhas has no API for custom DRC rules, so we read the source files
instead.
The inheritance works as follows:
- we rename each rule via net renamer
- if the rule contains condition, we identify boolean operations equals
and not equals for net names and net classes and rename the nets
"""
proFilename = os.path.splitext(board.GetFileName())[0]+'.kicad_dru'
try:
with open(proFilename, encoding="utf-8") as f:
rules = parseSexprListF(f)
except FileNotFoundError:
# If the source board doesn't contain DRU files, there's nothing to
# inherit.
return
conditionRegex = re.compile(r"((A|B)\.Net(Class|Name)\s*?(==|!=)\s*?)'(.*?)'")
for rule in rules:
if isElement("version")(rule):
continue
elif isElement("rule")(rule):
# Rename rule
rule.items[1].value = netRenamer(rule.items[1].value)
for clause in rule.items[2:]:
if isElement("condition")(clause):
# Rename net classes and names in the condition
clause.items[1].value = conditionRegex.sub(
lambda m: f"{m.group(1)}'{netRenamer(m.group(5))}'", clause.items[1].value)
self.customDRCRules.append(rule)
else:
raise RuntimeError(f"Unkwnown custom DRC rule {rule}")
def _adjustPageSize(self) -> None:
"""
Open the just saved panel file and syntactically change the page size.
At the moment, there is no API do so, therefore this extra step is
required.
"""
if self.pageSize is None:
return
with open(self.filename, "r", encoding="utf-8") as f:
tree = parseSexprF(f, limit=10) # Introduce limit to speed up parsing
# Find paper property
paperExpr = None
for subExpr in tree:
if not isinstance(subExpr, SExpr):
continue
if len(subExpr) > 0 and isinstance(subExpr[0], Atom) and subExpr[0].value == "paper":
paperExpr = subExpr
break
assert paperExpr is not None
if isinstance(self.pageSize, str):
paperProps = self.pageSize.split("-")
paperExpr.items = [
Atom("paper"),
Atom(paperProps[0], " ", quoted=True)
]
if len(paperProps) > 1:
paperExpr.items.append(Atom("portrait", " "))
else:
pageSize = [float(x) / units.mm for x in self.pageSize]
paperExpr.items = [
Atom("paper"),
Atom("User", " ", quoted=True),
Atom(str(pageSize[0]), " "),
Atom(str(pageSize[1]), " "),
]
with open(self.filename, "w", encoding="utf-8") as f:
f.write(str(tree))
def inheritDesignSettings(self, board):
"""
Inherit design settings from the given board specified by a filename or
a board
"""
if not isinstance(board, pcbnew.BOARD):
board = pcbnew.LoadBoard(board)
self.setDesignSettings(board.GetDesignSettings())
def setDesignSettings(self, designSettings):
"""
Set design settings
"""
d = self.board.GetDesignSettings()
d.CloneFrom(designSettings)
def inheritProperties(self, board):
"""
Inherit text properties from a board specified by a filename or a board
"""
if not isinstance(board, pcbnew.BOARD):
board = pcbnew.LoadBoard(board)
self.board.SetProperties(board.GetProperties())
def inheritPageSize(self, board: Union[pcbnew.BOARD, str]) -> None:
"""
Inherit page size from a board specified by a filename or a board
"""
if not isinstance(board, pcbnew.BOARD):
board = pcbnew.LoadBoard(board)
self.board.SetPageSettings(board.GetPageSettings())
self.pageSize = None
# What follows is a hack as KiCAD has no API for page access. Therefore,
# we have to read out the page size from the source board and save it so
# we can recover it.
with open(board.GetFileName(), "r", encoding="utf-8") as f:
tree = parseSexprF(f, limit=10) # Introduce limit to speed up parsing
self._inheritedPageDimensions = getPageDimensionsFromAst(tree)
def setPageSize(self, size: Union[str, Tuple[int, int]] ) -> None:
"""
Set page size - either a string name (e.g., A4) or size in KiCAD units
"""
if isinstance(size, str):
if size not in PAPER_SIZES:
raise RuntimeError(f"Unknown paper size: {size}")
self.pageSize = size
def getPageDimensions(self) -> Tuple[KiLength, KiLength]:
"""
Get page size in KiCAD units for the current panel
"""
if self.pageSize is None:
return self._inheritedPageDimensions
if isinstance(self.pageSize, tuple):
return self.pageSize
if isinstance(self.pageSize, str):
if self.pageSize.endswith("-portrait"):
# Portrait
pageSize = PAPER_DIMENSIONS[self.pageSize.split("-")[0]]
return pageSize[1], pageSize[0]
else:
return PAPER_DIMENSIONS[self.pageSize]
raise RuntimeError("Unknown page dimension - this is probably a bug and you should report it.")
def setProperties(self, properties):
"""
Set text properties cached in the board
"""
self.board.SetProperties(properties)
def inheritTitleBlock(self, board):
"""
Inherit title block from a board specified by a filename or a board
"""
if not isinstance(board, pcbnew.BOARD):
board = pcbnew.LoadBoard(board)
self.setTitleBlock(board.GetTitleBlock())
def setTitleBlock(self, titleBlock):
"""
Set panel title block
"""
self.board.SetTitleBlock(titleBlock)
def appendBoard(self, filename: Union[str, Path], destination: VECTOR2I,
sourceArea: Optional[BOX2I] = None,
origin: Origin = Origin.Center,
rotationAngle: KiAngle = fromDegrees(0),
shrink: bool = False, tolerance: KiLength = 0,
bufferOutline: KiLength = fromMm(0.001),
netRenamer: Optional[Callable[[int, str], str]] = None,
refRenamer: Optional[Callable[[int, str], str]] = None,
inheritDrc: bool = True, interpretAnnotations: bool=True,
bakeText: bool = False):
"""
Appends a board to the panel.
The sourceArea (BOX2I) of the board specified by filename is extracted
and placed at destination (VECTOR2I). The source area (BOX2I) can be
auto detected if it is not provided. Only board items which fit entirely
into the source area are selected. You can also specify rotation. Both
translation and rotation origin are specified by origin. Origin
specifies which point of the sourceArea is used for translation and
rotation (origin it is placed to destination). It is possible to specify
coarse source area and automatically shrink it if shrink is True.
Tolerance enlarges (even shrinked) source area - useful for inclusion of
filled zones which can reach out of the board edges or footprints that
extend outside the board outline, like connectors.
You can also specify functions which will rename the net and ref names.
By default, nets are renamed to "Board_{n}-{orig}", refs are unchanged.
The renamers are given board seq number and original name.
You can also decide whether you would like to inherit design rules from
this boards or not.
Similarly, you can substitute variables in the text via bakeText.
Returns bounding box (BOX2I) of the extracted area placed at the
destination and the extracted substrate of the board.
"""
# Since we want to follow KiCAD's new API, we require angles to be given
# as EDA_ANGLE. However, there might be old scripts that will pass a
# number.
if not isinstance(rotationAngle, EDA_ANGLE):
raise RuntimeError("Board rotation has to be passed as EDA_ANGLE, not a number")
board = LoadBoard(str(filename))
if inheritDrc:
self.sourcePaths.add(filename)
if bakeText:
bakeTextVars(board)
thickness = board.GetDesignSettings().GetBoardThickness()
if len(self.substrates) == 0:
self.board.GetDesignSettings().SetBoardThickness(thickness)
else:
panelThickness = self.board.GetDesignSettings().GetBoardThickness()
if panelThickness != thickness:
raise PanelError(f"Cannot append board {filename} as its " \
f"thickness ({toMm(thickness)} mm) differs from " \
f"thickness of the panel ({toMm(panelThickness)}) mm")
self.inheritCopperLayers(board)
if not sourceArea:
sourceArea = findBoardBoundingBox(board)
elif shrink:
sourceArea = findBoardBoundingBox(board, sourceArea)
enlargedSourceArea = expandRect(sourceArea, tolerance)
originPoint = getOriginCoord(origin, sourceArea)
translation = VECTOR2I(destination[0] - originPoint[0],
destination[1] - originPoint[1])
if netRenamer is None:
netRenamer = lambda x, y: self._uniquePrefix() + y
bId = len(self.substrates)
netRenamerFn = lambda x: netRenamer(bId, x)
self._inheritNetClasses(board, netRenamerFn)
self._inheriCustomDrcRules(board, netRenamerFn)
renameNets(board, netRenamerFn)
if refRenamer is not None:
renameRefs(board, lambda x: refRenamer(len(self.substrates), x))
drawings = collectItems(board.GetDrawings(), enlargedSourceArea)
footprints = collectFootprints(board.GetFootprints(), enlargedSourceArea)
tracks = collectItems(board.GetTracks(), enlargedSourceArea)
zones = collectItems(board.Zones(), enlargedSourceArea)
itemMapping: Dict[str, str] = {} # string KIID to string KIID
def yieldMapping(old: str, new: str) -> None:
nonlocal itemMapping
itemMapping[old] = new
edges = []