#!/usr/bin/python # -*- coding: utf-8 -*- # # FillArea.py # # Copyright 2017 JS Reynaud # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. from __future__ import print_function from pcbnew import * from builtins import abs import sys import tempfile import shutil import os import random import math import pprint import wx from inspect import currentframe, getframeinfo import time def wxPrint(msg): wx.LogMessage(msg) def KicadMajorVersion(): """Return KiCad major version as int (string compare breaks for 10+).""" try: return int(str(Version()).lstrip("(").split(".")[0]) except (ValueError, IndexError): return 99 def ViaWidth(via): """Via copper width; KiCad 10+ padstacks need a layer argument.""" try: return via.GetWidth(F_Cu) except TypeError: return via.GetWidth() def Unfracture(poly): """Split outlines back into outline + holes (fractured polygons join holes by slits).""" try: poly.Unfracture() except TypeError: poly.Unfracture(SHAPE_POLY_SET.PM_FAST) # KiCad 8 and older def PadCollidesShape(pad, shape): """Test pad copper polygon vs. shape; KiCad 10+ needs a layer argument.""" try: layers = list(pad.GetLayerSet().CuStack()) if not layers: return False for layer in layers: if pad.GetEffectivePolygon(layer).Collide(shape): return True return False except TypeError: # KiCad 9 and older return pad.GetEffectivePolygon().Collide(shape) # if sys.version[0] == "2": # maui None else: xrange = range """ # This script fills all areas of a specific net with Vias (Via Stitching) # # # Usage in pcbnew's python console: # First you neet to copy this file (named FillArea.py) in your kicad_plugins # directory (~/.kicad_plugins/ on Linux) # Launch pcbnew and open python console (last entry of Tools menu) # Then enter the following line (one by one, Hit enter after each) import FillArea FillArea.FillArea().Run() # Other example: # You can add modifications to parameters by adding functions calls: FillArea.FillArea().SetDebug().SetNetname("GND").SetStepMM(1.27).SetSizeMM(0.6).SetDrillMM(0.3).SetClearanceMM(0.2).Run() # with # SetDebug: Activate debug mode (print evolution of the board in ascii art) # SetViaThroughAreas: Ignores areas on other layers # SetNetname: Change the netname to consider for the filling # (default is /GND or fallback to GND) # SetStepMM: Change step between Via (in mm) # SetSizeMM: Change Via copper size (in mm) # SetDrillMM: Change Via drill hole size (in mm) # SetClearanceMM: Change clearance for Via (in mm) # You can also use it in command line. In this case, the first parameter is # the pcb file path. Default options are applied. """ class ViaObject: """ ViaObject holds all information of a single Via """ def __init__(self, x, y, pos_x, pos_y): self.X = x self.Y = y self.PosX = pos_x self.PosY = pos_y class FillArea: """ Automaticaly add via on area where there are no track/existing via, pads and keepout areas """ REASON_OK = 0 REASON_NO_SIGNAL = 1 REASON_OTHER_SIGNAL = 2 REASON_KEEPOUT = 3 REASON_TRACK = 4 REASON_PAD = 5 REASON_DRAWING = 6 REASON_STEP = 7 REASON_NO_FILL = 8 REASON_BOARD_EDGE = 9 REASON_REFERENCE = 10 # Letters drawn into the "skipped via" markers SKIP_LABELS = { REASON_OTHER_SIGNAL: "Z", REASON_KEEPOUT: "K", REASON_TRACK: "T", REASON_PAD: "P", REASON_DRAWING: "D", REASON_NO_FILL: "F", REASON_BOARD_EDGE: "E", REASON_REFERENCE: "R", } GRID_TYPE_BOARD_BOUNDS = "Board Bounds" GRID_TYPE_ABSOLUTE = "Absolute (0, 0)" GRID_TYPE_GRID_ORIGIN = "Grid Origin" FILL_TYPE_RECTANGULAR = "Rectangular" FILL_TYPE_STAR = "Star" FILL_TYPE_CONCENTRIC = "Concentric" FILL_TYPE_OUTLINE = "Outline" FILL_TYPE_OUTLINE_NO_HOLES = "Outline (No Holes)" GROUP_MODE_PER_NET = "Per net" GROUP_MODE_PER_PATTERN = "Per net and pattern" GROUP_MODE_PER_RUN = "New group per run" def __init__(self, filename=None): self.filename = None self.clearance = 0 # Net name to use self.SetPCB(GetBoard()) # Set the filename self.SetFile(filename) # Step between via self.SetStepMM(2.54) # Size of the via (diameter of copper) self.SetSizeMM(0.46) # Size of the drill (diameter) self.SetDrillMM(0.20) # Isolation between via and other elements # ie: radius from the border of the via self.SetClearanceMM(0.2) self.only_selected_area = False self.delete_vias = False self.via_through_areas = False self.same_net_tracks = False self.refill_zones = False self.mark_skipped = False self.skip_reference = False self.ref_shapes = [] self.pad_gap_cache = {} self.area_fill_cache = {} self.snap = 0 self.grid_origin = VECTOR2I(0, 0) self.skipped = {} # (x, y) -> reason, drawn by DrawSkippedMarkers() self.unfilled_zones = [] if self.pcb is not None: for lnet in ["GND", "/GND"]: if self.pcb.FindNet(lnet) is not None: self.SetNetname(lnet) break self.netname = None self.debug = False self.random = False self.grid_type = self.GRID_TYPE_BOARD_BOUNDS self.fill_type = self.FILL_TYPE_RECTANGULAR self.group_mode = self.GROUP_MODE_PER_NET if self.netname is None: self.SetNetname("GND") self.tmp_dir = None self.parent_area = None self.pcb_group = None self.target_net = None def SetFile(self, filename): self.filename = filename if self.filename: self.SetPCB(LoadBoard(self.filename)) def SetDebug(self): wxPrint("Set debug") self.debug = True return self def SetRandom(self, r): random.seed() self.random = r return self def SetViaThroughAreas(self, r): self.via_through_areas = r return self def SetSameNetTracks(self, r): self.same_net_tracks = r return self def SetSkipReference(self, r): self.skip_reference = r return self def SetMarkSkipped(self, r): self.mark_skipped = r return self def AddSkipped(self, p, reason): if self.mark_skipped and reason in self.SKIP_LABELS: self.skipped.setdefault((int(p.x), int(p.y)), reason) def DrawSkippedMarkers(self, group_name): """Draw a circle with the reason letter on User.Drawings for every skipped via position.""" if not self.mark_skipped or not self.skipped: return 0 # A position rejected for one zone may still have got a via from another zone (other layer) placed = [via.GetPosition() for via in self.pcb_group.GetItems() if via.GetClass() == "PCB_VIA"] if self.pcb_group else [] group = PCB_GROUP(None) group.SetName(group_name + " skipped") self.pcb.Add(group) radius = int(self.size / 2) count = 0 for (x, y), reason in sorted(self.skipped.items()): p = VECTOR2I(x, y) if any((p - v).EuclideanNorm() < radius for v in placed): continue circle = PCB_SHAPE(self.pcb) circle.SetShape(SHAPE_T_CIRCLE) circle.SetLayer(Dwgs_User) circle.SetWidth(FromMM(0.05)) circle.SetCenter(p) circle.SetEnd(VECTOR2I(x + radius, y)) self.pcb.Add(circle) group.AddItem(circle) text = PCB_TEXT(self.pcb) text.SetLayer(Dwgs_User) text.SetText(self.SKIP_LABELS[reason]) h = max(int(radius * 1.2), FromMM(0.2)) text.SetTextSize(VECTOR2I(h, h)) text.SetTextThickness(max(h // 8, FromMM(0.02))) text.SetHorizJustify(GR_TEXT_H_ALIGN_CENTER) text.SetVertJustify(GR_TEXT_V_ALIGN_CENTER) text.SetPosition(p) self.pcb.Add(text) group.AddItem(text) count += 1 wxPrint("{} skipped via positions marked on User.Drawings (group '{}'): " "P=pad T=track Z=other zone K=keepout D=copper drawing F=no poured copper E=board edge R=reference".format(count, group.GetName())) return count def SetRefillZones(self, r): self.refill_zones = r return self def GetZoneFill(self, zone): """Filled copper of the zone, one SHAPE_POLY_SET per copper layer. Only the via centre has to lie on poured copper: the fill edge already keeps the zone clearance, so the via copper may reach slightly past it; clearance to the surrounding objects is checked separately (CheckViaPosition / pads / tracks). Returns None when the zone is not filled (fill check is then skipped). """ polys = [] for layer in zone.GetLayerSet().CuStack(): try: fill = zone.GetFilledPolysList(layer) except Exception: fill = None if fill is None or fill.OutlineCount() == 0: continue polys.append(SHAPE_POLY_SET(fill)) if polys: return polys self.unfilled_zones.append("{} ({})".format(zone.GetNetname(), zone.GetLayerName())) return None @staticmethod def IsOnZoneFill(zone_fill, p): return zone_fill is None or any(poly.Contains(p) for poly in zone_fill) def ReportUnfilledZones(self): if self.unfilled_zones: wxPrint("WARNING: zone(s) not filled, vias were not checked against the poured copper: {}.\n" "Fill all zones (B) before running the plugin.".format(", ".join(self.unfilled_zones))) def SetGridType(self, grid_type): self.grid_type = grid_type return self def SetSnapMM(self, s): """Snap every via to a fine grid (grid origin of the board + n * s); 0 = off.""" self.snap = int(FromMM(s)) if s and s > 0 else 0 return self def SnapCandidates(self, p): """The 4 snap grid points around p, nearest first (just p when snap is off).""" if not self.snap: return [p] o = self.grid_origin fx = int(math.floor((p.x - o.x) / float(self.snap))) fy = int(math.floor((p.y - o.y) / float(self.snap))) pts = [VECTOR2I(o.x + (fx + i) * self.snap, o.y + (fy + j) * self.snap) for i in (0, 1) for j in (0, 1)] pts.sort(key=lambda q: (q - p).EuclideanNorm()) return pts def GetGridOrig(self, lboard): if self.snap: # Snap grid follows the editor grid, which starts at the board grid origin return self.pcb.GetDesignSettings().GetGridOrigin() if self.grid_type == self.GRID_TYPE_ABSOLUTE: return VECTOR2I(0, 0) elif self.grid_type == self.GRID_TYPE_GRID_ORIGIN: return self.pcb.GetDesignSettings().GetGridOrigin() else: return lboard.GetPosition() def SetFillType(self, fill_type): self.fill_type = fill_type return self def SetGroupMode(self, group_mode): self.group_mode = group_mode return self def GetGroupName(self): """Name of the group the new vias go to (depends on group_mode).""" base = "ViaStitching {}".format(self.netname) if self.group_mode == self.GROUP_MODE_PER_NET: return base base = "{} {}".format(base, self.fill_type) if self.group_mode == self.GROUP_MODE_PER_PATTERN: return base # New group per run: first free " #N" names = set(g.GetName() for g in self.pcb.Groups()) n = 1 while "{} #{}".format(base, n) in names: n += 1 return "{} #{}".format(base, n) def SetPCB(self, pcb): self.pcb = pcb if self.pcb is not None: self.pcb.BuildListOfNets() return self def SetNetname(self, netname): self.netname = netname # .upper() # wx.LogMessage(self.netname) return self def SetStepMM(self, s): self.step = float(FromMM(s)) return self def SetSizeMM(self, s): self.size = float(FromMM(s)) return self def SetDrillMM(self, s): self.drill = float(FromMM(s)) return self def OnlyOnSelectedArea(self): self.only_selected_area = True return self def DeleteVias(self): self.delete_vias = True return self def SetClearanceMM(self, s): self.clearance = float(FromMM(s)) return self def GetReasonSymbol(self, reason): if isinstance(reason, ViaObject): return "X" if reason == self.REASON_NO_SIGNAL: return " " if reason == self.REASON_OTHER_SIGNAL: return "O" if reason == self.REASON_KEEPOUT: return "K" if reason == self.REASON_TRACK: return "T" if reason == self.REASON_PAD: return "P" if reason == self.REASON_DRAWING: return "D" if reason == self.REASON_STEP: return "-" return str(reason) def PrintRect(self, rectangle): """debuging tool Print board in ascii art """ print("_" * (len(rectangle) + 2)) for y in range(len(rectangle[0])): print("|", end="") for x in range(len(rectangle)): print("%s" % self.GetReasonSymbol(rectangle[x][y]), end="") print("|") print("_" * (len(rectangle) + 2)) print( """ OK = 'X' NO_SIGNAL = ' ' OTHER_SIGNAL = 'O' KEEPOUT = 'K' TRACK = 'T' PAD = 'P' DRAWING = 'D' STEP = '-' """ ) def AddVia(self, position, x, y): if self.parent_area: m = PCB_VIA(self.parent_area) m.SetPosition(position) if self.target_net is None: self.target_net = self.pcb.FindNet(self.netname) m.SetNet(self.target_net) m.SetViaType(VIATYPE_THROUGH) m.SetDrill(int(self.drill)) m.SetWidth(int(self.size)) m.SetIsFree(True) # again possible to mark via as own since no timestamp_t binding kicad v5.1.4 # m.SetParentGroup(self.parent_group) # wx.LogMessage('adding vias') self.pcb.Add(m) self.pcb_group.AddItem(m) return m else: wxPrint("\nUnable to find a valid parent area (zone)") def RefillBoardAreas(self): for i in range(self.pcb.GetAreaCount()): area = self.pcb.GetArea(i) # No more making a real refill since it's crashing KiCad if KicadMajorVersion() < 7: None else: area.SetNeedRefill(True) # area.UnFill() # filler = ZONE_FILLER(self.pcb) # filler.Fill(self.pcb.Zones()) def AreaFillCached(self, area): """Poured copper of a zone, one SHAPE_POLY_SET per copper layer (cached per run). None when the zone is not filled.""" key = area.m_Uuid.AsString() if key not in self.area_fill_cache: polys = [] for layer in area.GetLayerSet().CuStack(): try: fill = area.GetFilledPolysList(layer) except Exception: fill = None if fill is not None and fill.OutlineCount() > 0: polys.append(SHAPE_POLY_SET(fill)) self.area_fill_cache[key] = polys if (polys or area.IsFilled()) else None return self.area_fill_cache[key] def CheckViaInAllAreas(self, via, all_areas): """ Checks a via (round, through all layers) against keepouts and zones of other nets. - Rule area forbidding vias: the via must not touch its outline. - Copper zone of another net (unless "Ignore other areas"): the via copper plus clearance must not touch its poured copper, otherwise the via would punch a hole into it. An unfilled zone is checked against its outline instead, where a target net zone with higher priority on the same layer wins. Rule areas without via restriction and zones of the target net are ignored. """ p = VECTOR2I(int(via.PosX), int(via.PosY)) radius = int(self.size / 2) for area in all_areas: if area.GetIsRuleArea(): if area.GetDoNotAllowVias() and area.Outline().Collide(p, radius): return self.REASON_KEEPOUT continue if area.GetNetname() == self.netname or self.via_through_areas: continue clr = int(max(self.clearance, area.GetLocalClearance() or 0)) + radius fill = self.AreaFillCached(area) if fill is not None: if any(poly.Collide(p, clr) for poly in fill): return self.REASON_OTHER_SIGNAL continue # Not filled: use the drawn outline if not area.Outline().Collide(p, clr): continue area_layers = set(area.GetLayerSet().CuStack()) covered = any( other.GetNetname() == self.netname and not other.GetIsRuleArea() and other.GetAssignedPriority() > area.GetAssignedPriority() and area_layers.issubset(set(other.GetLayerSet().CuStack())) and other.Outline().Contains(p) for other in all_areas ) if not covered: return self.REASON_OTHER_SIGNAL return self.REASON_OK def ClearViaInStepSize(self, rectangle, x, y, distance): """ Stepsize==0 O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O Standard O O O O O O O O O O O O O O O O O O O O Star O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O O """ for x_pos in range(x - distance, x + distance + 1): if (x_pos >= 0) and (x_pos < len(rectangle)): # Star or Standard shape distance_y = distance - abs(x - x_pos) if self.fill_type == self.FILL_TYPE_STAR else distance for y_pos in range(y - distance_y, y + distance_y + 1): if (y_pos >= 0) and (y_pos < len(rectangle[0])): if (x_pos == x) and (y_pos == y): continue rectangle[x_pos][y_pos] = self.REASON_STEP """ Check if vias would not overlap and if in same outline then apply at minimum 60% of self.step """ def CheckViaDistance(self, p, via, outline): p2 = VECTOR2I(via.GetPosition()) dist = self.clearance + self.size / 2 + ViaWidth(via) / 2 # If via in same outline, then apply bigger space if outline.Collide(p2): dist = int(max(dist, self.step * 0.6)) return (p - p2).EuclideanNorm() >= dist """ Add via along outline (SHAPE_LINE_CHAIN), starting at offset (fraction between 0.0 and 1.0) Avoid placing vias to close to via present in all_vias """ def GetBoardEdge(self): """Board outline shrunk so that a via centre inside it keeps the edge clearance.""" board_edge = SHAPE_POLY_SET() try: # KiCad 10+: aInferOutlineIfNecessary is a required argument self.pcb.GetBoardPolygonOutlines(board_edge, True) except TypeError: # KiCad 9 and older self.pcb.GetBoardPolygonOutlines(board_edge) b_clearance = max(self.pcb.GetDesignSettings().m_CopperEdgeClearance, self.clearance) + self.size / 2 board_edge.Deflate(int(b_clearance), CORNER_STRATEGY_ROUND_ALL_CORNERS, FromMM(0.01)) return board_edge def PrepareObstacles(self, include_net_vias=False): """Collect everything a via must keep clear of. Existing vias of the target net are included only on request (outline/concentric check their spacing by CheckViaDistance).""" self.obs_board_edge = self.GetBoardEdge() self.obs_areas = [self.pcb.GetArea(i) for i in xrange(self.pcb.GetAreaCount())] # Each obstacle: (inflated bounding box for a quick reject, item, kind) reach = int(self.size / 2 + self.clearance) + FromMM(1) # generous margin for the bbox prefilter self.obstacles = [] def add(item, kind): bbox = item.GetBoundingBox() bbox.Inflate(reach + int(item.GetOwnClearance(UNDEFINED_LAYER, "") if kind != "drawing" else 0)) self.obstacles.append((bbox, item, kind)) for pad in self.pcb.GetPads(): add(pad, "pad") for track in self.pcb.GetTracks(): if track.GetNetname() == self.netname: if track.GetClass() == "PCB_VIA": if include_net_vias: add(track, "track") continue if self.same_net_tracks: continue add(track, "track") try: drawings = list(self.pcb.Drawings()) except Exception: drawings = list(self.pcb.DrawingsList()) for draw in drawings: if IsCopperLayer(draw.GetLayer()): add(draw, "drawing") # Visible footprint references: a via must not cut through the reference text self.ref_shapes = [] if self.skip_reference: for fp in self.pcb.GetFootprints(): ref = fp.Reference() if ref.IsVisible() and ref.GetText(): self.ref_shapes.append(self.TextBoxPoly(ref)) @staticmethod def TextBoxPoly(text): """Text box of a (possibly rotated) text as a polygon.""" box = text.GetTextBox(None) c = text.GetDrawPos() a = text.GetDrawRotation().AsRadians() cos_a, sin_a = math.cos(a), math.sin(a) poly = SHAPE_POLY_SET() poly.NewOutline() for x, y in ((box.GetLeft(), box.GetTop()), (box.GetRight(), box.GetTop()), (box.GetRight(), box.GetBottom()), (box.GetLeft(), box.GetBottom())): dx, dy = x - c.x, y - c.y poly.Append(int(c.x + dx * cos_a + dy * sin_a), int(c.y - dx * sin_a + dy * cos_a)) return poly def IsSameNetPad(self, pad): """Pads of the target net need no clearance to the via, only no overlap and hole-to-hole spacing.""" return pad.GetNetname() == self.netname def SameNetPadGap(self, pad): """Copper gap a via must keep to a pad of the target net: the thermal relief gap when the pad is connected to a target zone by a thermal relief, otherwise 0.""" key = pad.m_Uuid.AsString() if key in self.pad_gap_cache: return self.pad_gap_cache[key] conn = pad.GetLocalZoneConnection() fp = pad.GetParentFootprint() if conn == ZONE_CONNECTION_INHERITED and fp is not None: conn = fp.GetLocalZoneConnection() try: pad_gap = pad.GetLocalThermalGapOverride() except Exception: pad_gap = None gap = 0 pad_layers = list(pad.GetLayerSet().CuStack()) for zone in self.pcb.Zones(): if zone.GetNetname() != self.netname or zone.GetIsRuleArea(): continue if not any(zone.IsOnLayer(layer) for layer in pad_layers): continue c = conn if conn != ZONE_CONNECTION_INHERITED else zone.GetPadConnection() if c == ZONE_CONNECTION_THERMAL or (c == ZONE_CONNECTION_THT_THERMAL and pad.GetAttribute() == PAD_ATTRIB_PTH): gap = max(gap, pad_gap if pad_gap else zone.GetThermalReliefGap()) self.pad_gap_cache[key] = gap return gap def SameNetPadBlocksVia(self, pad, p): """Pad of the target net: no clearance needed, only keep the via out of the pad (no via-in-pad / solder wicking) and out of its thermal relief gap, and keep the minimum hole-to-hole distance.""" radius = int(self.size / 2) + int(self.SameNetPadGap(pad)) for layer in pad.GetLayerSet().CuStack(): if pad.GetEffectiveShape(layer).Collide(p, radius): return True if pad.HasHole(): hole_gap = int(self.drill / 2) + int(self.pcb.GetDesignSettings().m_HoleToHoleMin) if pad.GetEffectiveHoleShape().Collide(p, hole_gap): return True return False def CheckViaPosition(self, p, zone_clearance=0): """Return REASON_OK if a via at p keeps clearance to all obstacles.""" if not self.obs_board_edge.Collide(p): return self.REASON_BOARD_EDGE reason = self.CheckViaInAllAreas(ViaObject(x=0, y=0, pos_x=p.x, pos_y=p.y), self.obs_areas) if reason != self.REASON_OK: return reason base = max(self.clearance, zone_clearance) radius = int(self.size / 2) for poly in self.ref_shapes: if poly.Collide(p, radius): return self.REASON_REFERENCE for bbox, item, kind in self.obstacles: if not bbox.Contains(p): continue if kind == "pad" and self.IsSameNetPad(item): if self.SameNetPadBlocksVia(item, p): return self.REASON_PAD elif kind == "pad": clr = int(max(base, item.GetOwnClearance(UNDEFINED_LAYER, ""))) + radius for layer in item.GetLayerSet().CuStack(): if item.GetEffectiveShape(layer).Collide(p, clr): return self.REASON_PAD if item.HasHole() and item.GetEffectiveHoleShape().Collide(p, clr): return self.REASON_PAD elif kind == "track": clr = int(max(base, item.GetOwnClearance(UNDEFINED_LAYER, ""))) + radius if item.GetEffectiveShape().Collide(p, clr): return self.REASON_TRACK else: # copper text or graphic shape clr = int(base) + radius try: hit = item.GetEffectiveShape(item.GetLayer()).Collide(p, clr) except Exception: bbox_d = item.GetBoundingBox() bbox_d.Inflate(clr) hit = bbox_d.Contains(p) if hit: return self.REASON_DRAWING return self.REASON_OK def OutlineCandidates(self, outline, offset=0): """Via positions along a closed outline. Straight horizontal / vertical parts get their vias on the via grid (grid origin + n * pitch, same grid as the rectangular fill), so stitching along straight edges lines up. Slanted parts and arcs are walked at a regular pitch along the length. """ step = int(max(self.step, self.size + self.clearance)) origin = self.grid_origin tol = FromMM(0.005) points = [] carry = step * offset # distance to the next via on slanted parts for i in range(outline.SegmentCount()): seg = outline.CSegment(i) a, b = seg.A, seg.B dx, dy = b.x - a.x, b.y - a.y length = math.hypot(dx, dy) if length == 0: continue horizontal = abs(dy) <= tol vertical = abs(dx) <= tol if horizontal or vertical: start, delta, o = (a.x, dx, origin.x) if horizontal else (a.y, dy, origin.y) lo, hi = min(start, start + delta), max(start, start + delta) ts = [] k = int(math.ceil((lo - o) / float(step))) while o + k * step <= hi: ts.append((o + k * step - start) / float(delta)) k += 1 ts.sort() for t in ts: points.append(VECTOR2I(int(round(a.x + t * dx)), int(round(a.y + t * dy)))) carry = max(step - (1 - ts[-1]) * length, 0) if ts else max(carry - length, 0) else: d = carry while d <= length: points.append(VECTOR2I(int(round(a.x + dx * d / length)), int(round(a.y + dy * d / length)))) d += step carry = d - length return points def AddViasAlongOutline(self, outline, outline_parent, all_vias, offset=0, zone_clearance=0, zone_fill=None): via_placed = 0 for candidate in self.OutlineCandidates(outline, offset): # With snap on, try the nearest snap grid points and take the first one that fits first_reason = None p = None for q in self.SnapCandidates(candidate): if not all(self.CheckViaDistance(q, via, outline_parent) for via in all_vias): continue # regular spacing to other vias, not worth a marker reason = self.CheckViaPosition(q, zone_clearance) if reason == self.REASON_OK and not self.IsOnZoneFill(zone_fill, q): reason = self.REASON_NO_FILL if reason == self.REASON_OK: p = q break if first_reason is None: first_reason = (q, reason) if p is None: if first_reason is not None: self.AddSkipped(first_reason[0], first_reason[1]) else: via = self.AddVia(p, 0, 0) all_vias.append(via) via_placed += 1 return via_placed def GetZoneOutlinePoly(self, zone): """Copy of the drawn zone outline (used when the zone is not filled).""" # For KiCad >= 7, zone.Outline() may return an empty SHAPE_POLY_SET for inner-layer # zones. We therefore try to build the polygon from points directly. zone_poly = SHAPE_POLY_SET() if KicadMajorVersion() < 7: for layer_id in zone.GetLayerSet().CuStack(): z = zone.RawPolysList(layer_id) if z.OutlineCount() > 0: zone_poly.Append(z) break else: src = zone.Outline() if src is not None and src.OutlineCount() > 0: # Manually copy each outline to avoid SWIG aliasing issues for oi in range(src.OutlineCount()): chain = src.Outline(oi) zone_poly.NewOutline() for pi in range(chain.PointCount()): pt = chain.CPoint(pi) zone_poly.Append(pt.x, pt.y) for hi in range(src.HoleCount(oi)): hchain = src.Hole(oi, hi) zone_poly.NewHole(oi) for pi in range(hchain.PointCount()): pt = hchain.CPoint(pi) zone_poly.Append(pt.x, pt.y, oi, zone_poly.HoleCount(oi) - 1) return zone_poly def ConcentricFillVias(self): wxPrint("Calculate placement areas") zones = [zone for zone in self.pcb.Zones() if zone.GetNetname() == self.netname] wxPrint("Found {} zones with netname '{}'".format(len(zones), self.netname)) if not zones: wxPrint("ERROR: No zones found with netname '{}'. Available zones:".format(self.netname)) for i, zone in enumerate(self.pcb.Zones()): wxPrint(" Zone {}: netname='{}', layer={}".format(i, zone.GetNetname(), zone.GetLayerName())) return self.parent_area = zones[0] # Snapshot of vias that existed BEFORE this run. # Each zone resets to this baseline so that vias placed on OTHER zones # do not block via placement on the current zone's perimeter. existing_vias = [track for track in self.pcb.GetTracks() if (track.GetClass() == "PCB_VIA" and track.GetNetname() == self.netname)] # Global list also grows so we avoid absolute overlaps between zones. all_new_vias = [] self.PrepareObstacles() self.grid_origin = self.GetGridOrig(self.pcb.ComputeBoundingBox(False)) wxPrint("Generating via placement") off = 0 via_placed = 0 processed_any = False # Process each GND zone independently to avoid cross-layer polygon merge artefacts. # Each zone's outline is shrunk slightly and vias are placed along its boundary. for zone in zones: if self.only_selected_area and not zone.IsSelected(): continue zone_clearance = zone.GetLocalClearance() or 0 zone_fill = self.GetZoneFill(zone) # Vias follow the outer edge of the poured copper (one polygon per copper layer): # the fill edge already keeps the clearances to the board edge and to anything # touching the zone border. Clearance cut-outs inside the fill (around pads, # tracks...) are ignored here - those are handled by CheckViaPosition. Holes drawn # in the zone outline (cut-outs) are kept for the "Outline" / "Concentric" types. # Without a fill fall back to the drawn zone outline. outline_poly = self.GetZoneOutlinePoly(zone) if zone_fill: sources = [] for fill in zone_fill: filled = SHAPE_POLY_SET(fill) Unfracture(filled) poly = SHAPE_POLY_SET() for oi in range(filled.OutlineCount()): poly.AddOutline(filled.Outline(oi)) if self.fill_type != self.FILL_TYPE_OUTLINE_NO_HOLES: for oi in range(outline_poly.OutlineCount()): for hi in range(outline_poly.HoleCount(oi)): cutout = SHAPE_POLY_SET() cutout.AddOutline(outline_poly.Hole(oi, hi)) poly.BooleanSubtract(cutout) Unfracture(poly) sources.append(poly) # The fill edge already keeps the clearances: the via copper may be flush with it inflate_amount = -int(0.5 * self.size + FromMM(0.001)) else: sources = [outline_poly] # Drawn zone outline: keep the via clearance from it inflate_amount = -int(self.clearance + 0.5 * self.size) for zone_poly in sources: if zone_poly.OutlineCount() == 0: if self.debug: wxPrint(" -> Skipped (empty outline)") continue processed_any = True # Shrink so the via fits inside the copper (or keeps clearance to the zone outline). # Use ALLOW_ACUTE_CORNERS (no chamfering) to preserve complex polygon topology. zone_poly.Inflate(inflate_amount, CORNER_STRATEGY_ALLOW_ACUTE_CORNERS, FromMM(0.01)) Unfracture(zone_poly) # Inflate may return holes joined to the outline by slits if zone_poly.OutlineCount() == 0: if self.debug: wxPrint(" -> Skipped (empty after inflate)") continue # Zone too small after shrink # For this zone, only use pre-existing vias + already-placed-this-run vias # for spacing checks – NOT vias placed on other zones' perimeters. zone_vias = existing_vias + all_new_vias # Place vias along outlines and holes of this zone current_poly = zone_poly while current_poly.OutlineCount() > 0: for i in range(0, current_poly.OutlineCount()): outline = current_poly.Outline(i) n = self.AddViasAlongOutline(outline, outline, zone_vias, off, zone_clearance, zone_fill) via_placed += n if self.fill_type != self.FILL_TYPE_OUTLINE_NO_HOLES: for k in range(0, current_poly.HoleCount(i)): hole = current_poly.Hole(i, k) n = self.AddViasAlongOutline(hole, outline, zone_vias, off, zone_clearance, zone_fill) via_placed += n # Concentric: shrink inward for next ring; Outline: single pass if self.fill_type == self.FILL_TYPE_CONCENTRIC: current_poly.Inflate(int(-max(self.step, self.size + self.clearance)), CORNER_STRATEGY_CHAMFER_ALL_CORNERS, FromMM(0.01)) Unfracture(current_poly) off = 0.5 if off == 0 else 0 else: current_poly = SHAPE_POLY_SET() # exit while loop # Record vias placed for this zone to prevent global overlaps all_new_vias = zone_vias[len(existing_vias):] if not processed_any: wxPrint("No areas to fill") return self.RefillBoardAreas() self.ReportUnfilledZones() self.DrawSkippedMarkers(self.pcb_group.GetName()) msg = "Done. {:d} vias placed. You have to refill all your pcb's areas/zones !!!".format(via_placed) wxPrint(msg) return via_placed """ Main function which does the via placement or deletion """ def CheckSelectedZone(self): """With "Only under selected Zone" a zone of the target net must be selected. Tell the user why nothing would happen instead of silently placing 0 vias.""" selected = [zone for zone in self.pcb.Zones() if zone.IsSelected() and not zone.GetIsRuleArea()] if any(zone.GetNetname() == self.netname for zone in selected): return True msg = "\"Only under selected Zone\" is checked, but no zone of net {} is selected.\n\n".format(self.netname) if selected: msg += "Selected zone(s) belong to other nets: {}.\n\n".format( ", ".join(sorted(set("{} ({})".format(zone.GetNetname() or "", zone.GetLayerName()) for zone in selected)))) msg += "Select a {} zone (click its outline) and run the plugin again, or uncheck the option.".format(self.netname) try: wx.MessageBox(msg, "Via Stitching", wx.OK | wx.ICON_WARNING) except Exception: print("WARNING: " + msg.replace("\n\n", " ")) # no GUI (command line use) return False def Run(self): """ Launch the process """ if self.delete_vias: # Do not perform a real delete since exposed function in python are not safe for deletion prefix = "ViaStitching {}".format(self.netname) groups = sorted(g.GetName() for g in self.pcb.Groups() if g.GetName() == prefix or g.GetName().startswith(prefix + " ")) listing = "\n".join(" " + name for name in groups) if groups else " (none found)" wx.MessageBox( "To delete vias:\n - select one of the generated vias to select its group\n - hit delete key\n - That's all !\n\nVia groups for net {}:\n{}".format(self.netname, listing), "Information" ) """ if self.pcb_group is not None: all_vias = [track for track in self.pcb.GetTracks() if (track.GetClass() == "PCB_VIA" and track.GetNetname() == self.netname)] for via in all_vias: if via.GetParentGroup() is not None and via.GetParentGroup().GetName() == VIA_GROUP_NAME: via.DeleteStructure() """ return # no need to run the rest of logic if self.only_selected_area and not self.CheckSelectedZone(): return if self.refill_zones: wxPrint("Refilling all zones...") ZONE_FILLER(self.pcb).Fill(self.pcb.Zones()) self.area_fill_cache = {} VIA_GROUP_NAME = self.GetGroupName() if self.debug: print("Enumerate groups") for i in self.pcb.Groups(): if i.GetName() == VIA_GROUP_NAME: if self.debug: print("Group {} Found !".format(VIA_GROUP_NAME)) self.pcb_group = i if self.pcb_group is None: self.pcb_group = PCB_GROUP(None) self.pcb_group.SetName(VIA_GROUP_NAME) self.pcb.Add(self.pcb_group) if self.fill_type == self.FILL_TYPE_CONCENTRIC or self.fill_type == self.FILL_TYPE_OUTLINE or self.fill_type == self.FILL_TYPE_OUTLINE_NO_HOLES: self.ConcentricFillVias() if self.filename: self.pcb.Save(self.filename) return if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) target_tracks = self.pcb.GetTracks() if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) lboard = self.pcb.ComputeBoundingBox(False) if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) origin = self.GetGridOrig(lboard) if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) # Create an initial rectangle: all is set to "REASON_NO_SIGNAL" # get a margin to avoid out of range l_clearance = self.clearance + self.size if l_clearance < self.step: l_clearance = self.step if self.snap: # Pitch a multiple of the snap grid => all grid points lie on the snap grid l_clearance = int(math.ceil(l_clearance / float(self.snap))) * self.snap # Calculate grid extents relative to origin (support negative offsets) board_min_x = lboard.GetPosition().x board_min_y = lboard.GetPosition().y board_max_x = board_min_x + lboard.GetWidth() board_max_y = board_min_y + lboard.GetHeight() x_min = int(floor((board_min_x - origin.x - l_clearance) / l_clearance)) x_max = int(ceil((board_max_x - origin.x + l_clearance) / l_clearance)) y_min = int(floor((board_min_y - origin.y - l_clearance) / l_clearance)) y_max = int(ceil((board_max_y - origin.y + l_clearance) / l_clearance)) x_limit = x_max - x_min + 1 y_limit = y_max - y_min + 1 if self.debug: print( "l_clearance : {}; step : {}; size: {}; clearance: {}; x/y_limit ({} {}),board size : {} {}".format( l_clearance, self.step, self.size, self.clearance, x_limit, y_limit, lboard.GetWidth(), lboard.GetHeight() ) ) rectangle = [[self.REASON_NO_SIGNAL] * y_limit for i in xrange(x_limit)] if self.debug: print("\nInitial rectangle:") self.PrintRect(rectangle) all_pads = self.pcb.GetPads() all_tracks = self.pcb.GetTracks() if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) try: all_drawings = filter(lambda x: x.GetClass() == "PTEXT" and self.pcb.GetLayerID(x.GetLayerName()) in (F_Cu, B_Cu), self.pcb.DrawingsList()) except: all_drawings = filter(lambda x: x.GetClass() == "PTEXT" and self.pcb.GetLayerID(x.GetLayerName()) in (F_Cu, B_Cu), self.pcb.Drawings()) # wxPrint("exception on missing BOARD.DrawingsList") all_areas = [self.pcb.GetArea(i) for i in xrange(self.pcb.GetAreaCount())] # target_areas = filter(lambda x: (x.GetNetname().upper() == self.netname), all_areas) # KeepOuts are filtered because they have no name # KeepOuts are filtered because they have no name target_areas = filter(lambda x: (x.GetNetname() == self.netname), all_areas) board_edge = self.GetBoardEdge() via_list = [] # Create a list of existing vias => faster than scanning through the whole rectangle no_fill_cells = [] # inside a target area outline, but not on its poured copper max_target_area_clearance = 0 # Enum all target areas (Search possible positions for vias on the target net) for area in target_areas: if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) wxPrint("Processing Target Area: %s, LayerName: %s..." % (area.GetNetname(), area.GetLayerName())) if self.parent_area is None: self.parent_area = area is_selected_area = area.IsSelected() area_clearance = area.GetLocalClearance() if max_target_area_clearance < area_clearance: max_target_area_clearance = area_clearance if (not self.only_selected_area) or (self.only_selected_area and is_selected_area): # All areas or only the selected area area_fill = self.GetZoneFill(area) # Check every possible point in the virtual coordinate system if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) for x in xrange(len(rectangle)): if x % 10 == 0: if self.debug: print("%s: Line %u (x=%s;%s)" % (time.time(), currentframe().f_lineno, x, len(rectangle))) for y in xrange(len(rectangle[0])): # No other "target area" found yet => go on with processing if rectangle[x][y] == self.REASON_NO_SIGNAL: current_x = origin.x + ((x + (x_min)) * l_clearance) # Center of the via current_y = origin.y + ((y + (y_min)) * l_clearance) test_result = True # Start with true, if a check fails, it is set to false # Offset is half the size of the via plus the clearance of the via or the area offset = 0 # Use an exact zone match point_to_test = VECTOR2I(int(current_x), int(current_y)) hit_test_area = False if KicadMajorVersion() < 7: # below 7.0.0 hit_test_area = area.HitTestFilledArea(area.GetLayer(), VECTOR2I(point_to_test), int(offset)) # Collides with a filled area else: # 7.0.0 and above for i in range(0, area.Outline().OutlineCount()): area_outline = area.Outline().Outline(i) hit_test_area = hit_test_area or area_outline.PointInside(point_to_test) # Collides with an edge/corner hit_test_edge = area.HitTestForEdge(point_to_test, int(max(area_clearance, offset))) # test_result only remains true if the via is inside an area and not on an edge test_result = hit_test_area and not hit_test_edge test_result = test_result and board_edge.Collide(point_to_test) # check if inside board outline if test_result and not self.IsOnZoneFill(area_fill, point_to_test): # on poured copper test_result = False no_fill_cells.append((x, y, point_to_test)) if test_result: # Create a via object with information about the via and place it in the rectangle via_obj = ViaObject(x=x, y=y, pos_x=current_x, pos_y=current_y) rectangle[x][y] = via_obj via_list.append(via_obj) if self.debug: print("\nPost target areas:") self.PrintRect(rectangle) # Check every candidate against pads, tracks, existing vias, copper drawings, keepouts # and the board edge with the exact copper shapes (round via, real track/pad outline). wxPrint("Checking clearances of {} candidate positions...".format(len(via_list))) self.PrepareObstacles(include_net_vias=True) for via in via_list: reason = self.CheckViaPosition(VECTOR2I(int(via.PosX), int(via.PosY)), max_target_area_clearance) if reason != self.REASON_OK: rectangle[via.X][via.Y] = reason if self.debug: print("\nPost obstacles:") self.PrintRect(rectangle) # Candidate positions rejected by an obstacle (cells outside any target area are not marked) candidates = set() for via in via_list: candidates.add((via.X, via.Y)) if not isinstance(rectangle[via.X][via.Y], ViaObject): self.AddSkipped(VECTOR2I(int(via.PosX), int(via.PosY)), rectangle[via.X][via.Y]) for x, y, p in no_fill_cells: if (x, y) not in candidates: self.AddSkipped(p, self.REASON_NO_FILL) clear_distance = 0 if self.step != 0.0 and self.fill_type == self.FILL_TYPE_STAR: # How much "via steps" should be removed around a via (round up) clear_distance = int((self.step + l_clearance) / l_clearance) via_placed = 0 for x in xrange(len(rectangle)): for y in xrange(len(rectangle[0])): if isinstance(rectangle[x][y], ViaObject): if clear_distance: self.ClearViaInStepSize(rectangle, x, y, clear_distance) via = rectangle[x][y] ran_x = 0 ran_y = 0 if self.random: max_offset = max(self.step - (self.clearance + self.size), 0) / 2.0 ran_x = (random.random() * max_offset) - (max_offset / 2.0) ran_y = (random.random() * max_offset) - (max_offset / 2.0) if self.snap: # Round towards zero so the offset stays within max_offset ran_x = int(ran_x / self.snap) * self.snap ran_y = int(ran_y / self.snap) * self.snap if self.CheckViaPosition(VECTOR2I(int(via.PosX + ran_x), int(via.PosY + ran_y)), max_target_area_clearance) != self.REASON_OK: ran_x = ran_y = 0 # the shifted position violates a clearance => keep the checked one self.AddVia(VECTOR2I(int(via.PosX + ran_x), int(via.PosY + ran_y)), via.X, via.Y) via_placed += 1 if self.debug: print("\nFinal result:") self.PrintRect(rectangle) if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) self.RefillBoardAreas() self.ReportUnfilledZones() self.DrawSkippedMarkers(self.pcb_group.GetName()) if self.filename: self.pcb.Save(self.filename) msg = "Done. {:d} vias placed. You have to refill all your pcb's areas/zones !!!".format(via_placed) wxPrint(msg) if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: %s " % sys.argv[0]) else: import sys FillArea(sys.argv[1]).SetDebug().Run()