Modify design rules from python

I was recently asked on the kicad.info forum how to create a new netclass. It was already possible to modify existing ones, but the constructor for new ones hadn’t been exposed to the python interface. I’ve submitted the change to the kicad folks and it’s in the nightly builds.

Even with the constructor exposed, the sequence of steps to get to it isn’t obvious.

import pcbnew
board = pcbnew.GetBoard()
ds = board.GetDesignSettings() 
# ugly. exposes a public member not via an accessor method
nc = ds.m_NetClasses
foo = pcbnew.NETCLASSPTR("foo")
nc.Add(foo)

The nc variable (NETCLASSPTR) has lots of useful get’er set’er functions, like SetClearance, SetTrackWidth. These are easy to find in the python window. Just type “foo.” and you should get a popup of available functions. You can also run the function “dir(foo)”

Pan, Zoom, Refresh from python in pcbnew

So you’ve written a cool new layout modification utility in python. It sure would be nice to see the results on the screen. This is an issue I faced with my placement replicator script. It does what I want except that the user has to click the refresh button to see the results.

Now there’s a way to trigger zoom, pan, and refresh from python. As of this writing (March 20, 2017), you need to use one of the nightlies or build yourself.

To refresh the screen:

pcbnew.Refresh()

To pan and zoom, you need to supply x,y, width, height:

x = pcbnew.FromMM(10)
y = pcbnew.FromMM(10)
width  = pcbnew.FromMM(20)
height = pcbnew.FromMM(20)
pcbnew.WindowZoom(x, y, width, height)

Contributing to Kicad is painless

I initially searched and searched in pcbnew’s C code for python APIs like these. Eventually, I came to realize that they didn’t exist yet in pcbnew. So finally, I have my very first code contribution to an open source project.

I’ve been paid to write software for many years but it’s all been in-house stuff. My professional environment was pretty loosey-goosey, with very few formal constraints. 1 Over the years, I’ve read lots of stories about how open source projects can be a pain to deal with. Lots of coding standards, lots of requirements,… lots of hoops to jump through.2

This was not my experience with proposing these code changes to Kicad. I read the developer wiki, and attempted with follow the directions. I mailed the patch file to the developer email list, along with an introduction of who I am and what I’m trying to accomplish.

It was committed the same day.

Wayne, the kicad project lead, was very welcoming and encouraging. Although there were a couple things I missed, he went ahead and did the tweaks and pushed the change. Next time, I’ll know.

Most important to me, I’m excited to do more.

 

 


  1. This was mostly fine. On the one hand, a lot of bugs slipped through that shouldn’t have, but on the other, it meant that a lot of what we did was very much co-development/co-design with the users.

  2. sometimes protection of empires, but probably also a lot critical code. I’d hope that mysql, Apache, linux kernel, g++,… are strict. Hopefully, they’ve also found ways to be welcoming. I don’t know. I guess it’s often the negative news that we remember.

Adding your own command buttons to the pcbnew GUI

UPDATE April 14, 2017: You no longer need to use the hardcoded numbers like 6038 mentioned below. You can use pcbnew.ID_H_TOOLBAR.

 

Kicad has three rows of command buttons with predefined functionality. This post is about how to add your own button.

The sample code can be found here.

Perliminaries

Before getting into the code, there are a couple things that are weird about kicad/wxPython’s behavior1

Getting proper aui pointers

The first thing is that if you simply open the python scripting window in pcbnew, find the top level window, and look for the command bars, you’ll likely get a pointer of type wxControl. That type doesn’t have the APIs needed to look at, amend, and change the command buttons. The real type of these is wx.aui.AuiToolBar but unless the pointer is cast correctly, you’re out of luck.

After a bunch of poking around, running in the debugger, trying to recompile (unsuccessfully) wxPython with debug symbols turned on, I stumbled upon the easy answer. You have to do this before you run any of the wx scripting apis.

import wx
import wx.aui # this is the key one

After running these, you’ll get the correct pointer types. 2

Getting a proper WxApp pointer

The second funny thing isn’t really needed to add a button, but it’s super helpful in looking at the structure of the GUI yourself. In this post, I’m not just trying to help you add a button in a specific place, but rather to help you learn more about how pcbnew is put together. With this understanding you’ll hopefully be able to do even more.

When you first open the python interpreter in pcbnew, if you ask for the wxApp pointer, you’ll get a pointer of type wxEvtHandler. While this is correct, it’s incomplete and also unhelpful if you need a wxApp pointer. If you do this, wx.GetApp() will return a usable wxApp pointer3

import wx
wx.App()

Note that if you do this more than once in a given session, it’ll crash pcbnew.4

So why do we care? Well, if you have a proper wxApp pointer you can do this (remember, only one call to wx.App() per session):

import wx
wx.App()
import wx.aui
import wx.lib.inspection
wx.lib.inspection.InspectionTool().Show()

Which will give you a Widget Inspection Tool window like the one below. It enables you to click on different parts of the pcbnew GUI and see what’s what. Note that it doesn’t give me information about the individual buttons. It’s a helpful learning/debug aid nonetheless.

So let’s add a button

There are a couple things you need to add a button

  • The toolbar you want to add the button to (top, left, or right)
  • A callback function to be called when the button is clicked
  • A picture/bitmap to use as your button’s icon.

Getting the toolbar to add to

To lookup the toolbar window, you start by finding the main pcbnew window and then asking it for one of its children by id number. How do you know the number? The current, bad, answer is to either use the window inspector I mentioned earlier in this post or for me to tell you.5 Here are the numbers:

(this has been fixed. you can now use pcbnew.ID_H_TOOLBAR, pcbnew.ID_AUX_TOOLBAR and so on.)

  • 6038 is the value that H_TOOLBAR from kicad/include/id.h happens to get. It’s the one on the top with buttons like “new board”, “open existing board”
  • 6041 is AUX_TOOLBAR. That’s the second row of stuff in the pcbnew gui. It contains things like track width, via size, grid
  • 6039 is V_TOOLBAR, the right commands window. zoom to selection, highlight net.
  • 6040 is OPT_TOOLBAR, the left commands window. disable drc, hide grid, display polar
import pcbnew
import wx
import wx.aui

def findPcbnewWindow():
    windows = wx.GetTopLevelWindows()
    pcbnew = [w for w in windows if w.GetTitle() == "Pcbnew"]
    if len(pcbnew) != 1:
        raise Exception("Cannot find pcbnew window from title matching!")
    return pcbnew[0]

pcbwin = findPcbnewWindow()
top_tb = pcbwin.FindWindowById(6038)

Callback function

This one’s easy. It’s just a function that takes the event as an argument. If you print from this function, the output will appear in the terminal used to invoke pcbnew, not the python window. The event will be of type wx.CommandEvent which is useful to know if you want to have one callback for a variety of buttons.

def MyButtonsCallback(event):
    # when called as a callback, the output of this print
    # will appear in your xterm or wherever you invoked pcbnew.
    print("got a click on my new button {}".format(str(event)))

icon image

If you were to look in the kicad source code for bitmaps_png/CMakeLists.txt you’d find this:

# Plan for three sizes of bitmaps:
# SMALL – for menus – 16 x 16
# MID – for toolbars – 26 x 26
# BIG – for program icons – 48 x 48

The rest of that file handles automagic conversion from svg files into a format that can be consumed by the kicad code. Things are easier for us. You just need a 26×26 image file. In this example, I use png format, but you can use any format listed here on the wxPython page

# assuming you're creating your button from a script, one logical place to keep
# the image is in the same directory. Here's a snippet for how to get the
# path of the script.
import inspect
import os
filename = inspect.getframeinfo(inspect.currentframe()).filename
path = os.path.dirname(os.path.abspath(filename))

# here we actually load the icon file
bm = wx.Bitmap(path + '/hello.png', wx.BITMAP_TYPE_PNG)

Putting it all together

Now we have top_tb holding the toolbar window we want to add to, bm holding a bitmap pointer, and MyButtonsCallback to do the work. Now we just need to add a new tool button, bind it to the callback and tell the system to make it real.

itemid = wx.NewId()
top_tb.AddTool(itemid, "mybutton", bm, "this is my button", wx.ITEM_NORMAL)
top_tb.Bind(wx.EVT_TOOL, MyButtonsCallback, id=itemid)
top_tb.Realize()

And that’s it. Hope you enjoyed the post. Please comment. Again, the sample code can be found here.


  1. Things are only weird if you don’t know the explanation. In this case, I can guess at the reasons, but I don’t know for sure.

  2. if you already have the pointer with the wrong type, subsequent searches for windows will yield the same unhelpful type. My theory on why this is so is a matter of caching (why it persists) and swig symbol tables. Before you do import wx.aui, these types are not yet known to python and swig, so they return a type that is known. wxControl

  3. probably incorrect, but usable for what I’m about to talk about.

  4. again, this is a bad solution, but it’s only needed for debugging and learning about pcbnew’s structure.

  5. The better answer is for the kicad enum that holds these number to be exposed in python. Easy to add, but it’s not there now.

How to add mounting holes

Most of the time, the modules in your design will be introduced via netlist import from eeschema. An important exception to this is mounting holes. Your design may need some holes to enable you to screw the resulting board onto some sort of case/enclosure. In the GUI, you’d do this via the “Add footprints” command. This works, but what if you want to ensure that the resulting holes end up in specific locations? Script it!

Compared to other scripting tasks in pcbnew, figuring out how to add footprints to a design was a pain. In the end, it’s pretty easy1

My designs are pretty simple2, amounting to rectangular boards. My “enclosures” tend to be a piece of wood to which I mount a board with some drywall screws. Because of this simplicity, it doesn’t really matter where my mounting holes are. Still, I would like for them to at least be in a regular pattern. So I put together a script to put one in each corner of the board’s boundary.

First off, while pcbnew’s add footprint command can access kicad’s footprint libraries on GITHUB, this is not something I’ve achieved yet.3 For the code in this post to work, you’ll need to clone at least one of kicad’s footprint repos. For example, something like this:

git clone https://github.com/KiCad/Connectors.pretty.git

Don’t forget where you put it. In the case of the script, I have a variable footprint_lib. You’ll want to change this variable4. While we’re at it, let’s add some other boilerplate.

footprint_lib = '/bubba/electronicsDS/kicad/development/footprints/Connectors.pretty'

board = pcbnew.GetBoard()

# the internal coorinate space of pcbnew is 10E-6 mm. (a millionth of a mm)
# the coordinate 121550000 corresponds to 121.550000 

SCALE = 1000000.0

Since I want to put my mounting holes in the four corners of the board, I have to compute the four corners:

rect = None
for d in board.GetDrawings():
  if (d.GetLayerName() != "Edge.Cuts"):
    continue
  if (rect == None):
    rect = d.GetBoundingBox()
  else:
    rect.Merge(d.GetBoundingBox())

While the module class has a GetBoundingBox function, that box includes stuff like reference designators. So I have a function to compute the bounding box of metals, solder masks and such.

def GetModBBox(mod):
  modbox = None
  for pad in mod.Pads():
    if (modbox == None):
      modbox = pad.GetBoundingBox()
    else:
      modbox.Merge(pad.GetBoundingBox())
  for gi in mod.GraphicalItems():
    if (modbox == None):
      modbox = gi.GetBoundingBox()
    else:
      modbox.Merge(gi.GetBoundingBox())
 
  return modbox

Since I want to put a mounting hole in each corner, I generate a list of points from a bounding rectangle. Much better than cut/pasting a bunch of module code.

def GetRectCorners(rect):
  return [pcbnew.wxPoint(rect.Centre().x-rect.GetWidth()/2, rect.Centre().y-rect.GetHeight()/2),
          pcbnew.wxPoint(rect.Centre().x-rect.GetWidth()/2, rect.Centre().y+rect.GetHeight()/2),
          pcbnew.wxPoint(rect.Centre().x+rect.GetWidth()/2, rect.Centre().y+rect.GetHeight()/2),
          pcbnew.wxPoint(rect.Centre().x+rect.GetWidth()/2, rect.Centre().y-rect.GetHeight()/2)]

How to actually add a footprint.

Now we finally get to the “hard” part, adding the footprint. The ability to add a footprint is exposed in an API in the PCB_IO plugin. I don’t yet understand the role that plugin’s play in the context of pcbnew; most plugins are python scripts. PCB_IO is one written in C++.

It comes down to two easy lines. One to construct an instance of the PCB_IO plugin, and the second to instantiate the footprint. As I mentioned earlier in this post footprint_lib contains a path to a directory where you’ve put your kicad_mod files.

io = pcbnew.PCB_IO()
mod = io.FootprintLoad(footprint_lib, "1pin")

Everything after is easy.

board = pcbnew.GetBoard()
board.Add(mod)

I want to put four of these in the four corners of the boundary bounding box defined by rect above. First I shrink rect by the size of the footprint module. 5. I have to do a little bit of math to size the box. SetWidth/SetHeight are relative to the bottom left corner, something I’ve had to get used to. I wanted it to be relative to the center.

mod = io.FootprintLoad(footprint_lib, "1pin")

modbox = GetModBBox(mod);
rect.SetWidth(rect.GetWidth() - modbox.GetWidth())
rect.SetHeight(rect.GetHeight() - modbox.GetHeight())
rect.SetX(rect.GetX() + modbox.GetWidth()/2)
rect.SetY(rect.GetY() + modbox.GetHeight()/2)

And now I finally create and place the holes:

for point in GetRectCorners(rect):
  mod = io.FootprintLoad(footprint_lib, "1pin")
  modbox = GetModBBox(mod)
 
  point.x = point.x - modbox.Centre().x + mod.GetPosition().x
  point.y = point.y - modbox.Centre().y + mod.GetPosition().y
  mod.SetPosition(point)
  point.y - modbox.Centre().y))
 
  board.Add(mod)

Again, the script can be found on my github.

 

 

 


  1. Makes me think of times in my career when I spent a couple full days debugging a problem that was fixed with a single character. I’m sure most C/C++ programmers have experienced this with “=” vs “==” in an if statement. In this case, it’s not a matter of bugs, but that I don’t know the code that well.I should probably try to interact some with the kicad developers.

  2. I’m a software guy. I entered college intending to major EE, but my aptitude for programming eclipsed circuit stuff. Still, I pine for the ability to design circuits.

  3. I didn’t actually try, but I did keep and eye out for relevant code while tracking down the APIs needed to add a module

  4. “bubba”, in the path below, is one of my drives. I think of it as a name that only big guys have. As disks go and as technology has progressed, it really not that big anymore.

  5. EDA_RECT is nice enough to have an API called inflate. Sadly, it takes wxCoord as arguments. I haven’t found a way to create one or these via the existing python APIs.

adding GUI elements in pcbnew

In my last post, I talked about how you can run pcbnew headless. In many cases you actually want more GUI. For example, in my code sample for replicating module placement across multiple sheet instances, I have the pivot instances hard coded in the script. Why not do it in a GUI?

Adding GUI elements to pcbnew is what this post is about.1. The code I’m talking about can be found here.

The pcbnew GUI is written using wxWidgets/wxPython. If you’re not familiar with wxPython, here is my favorite tutorial so far. All of its python APIs work fine for me in pcbnew so far. I’ve found there are two important things to keep in mind:

  • You don’t need to do the normal app = MyApp(0); app.MainLoop() 2
  • If you do print from callback (for debugging) the text will not be in the python window. Instead, you can find it in the terminal where you invoked kicad. Keep this in mind if you usually invoke from the kicad project manager or from you OS task launcher.

At the end of this post, we’ll have a new, not particularly attractive, window in pcbnew like this:

As usual, you’ll need some imports:

import wx 
import pcbnew

To create a new window, you’ll want to create a new class derived from wx.Frame3. The initializer/constructor will create the new GUI elements and you’ll want some methods to use as event callbacks. To determine the placement of the new widgets, I’m using BoxSizer, but there are a bunch of other options.

Here are some of the high level points for when your reading the code below:

  • All widgets automagically get a unique negative id. You can pick your own numbers if you’d like. You’ll need the id when binding callbacks, given a widget pointer, just call GetId().
  • wx.StaticText is a simple text label.
  • wx.Button is a button. duh
  • wx.ComboBox gives you a scrollable list selection. I use it to pick a net or module.
  • wx.BoxSizer is just for layout. Line things up vertically or horizontally
  • To tell wx about your callback functions, use the bind method

Given that, the code below should be easy to follow, even if you’ve never done anything with wxWidgets/wxPython

class SimpleGui(wx.Frame):
    def __init__(self, parent, board):
        wx.Frame.__init__(self, parent, title="this is the title")
        self.panel = wx.Panel(self) 
        label = wx.StaticText(self.panel, label = "Hello World")
        button = wx.Button(self.panel, label="Button label", id=1)
        
        nets = board.GetNetsByName()
        self.netnames = []
        for netname, net in nets.items():
            if (str(netname) == ""):
                continue
            self.netnames.append(str(netname))
        
        netcb = wx.ComboBox(self.panel, choices=self.netnames)
        netcb.SetSelection(0)

        netsbox = wx.BoxSizer(wx.HORIZONTAL)
        netsbox.Add(wx.StaticText(self.panel, label="Nets:"))
        netsbox.Add(netcb, proportion=1)
        
        modules = board.GetModules()
        self.modulenames = []
        for mod in modules:
            self.modulenames.append("{}({})".format(mod.GetReference(), mod.GetValue()))
        modcb = wx.ComboBox(self.panel, choices=self.modulenames)
        modcb.SetSelection(0)

        modsbox = wx.BoxSizer(wx.HORIZONTAL)
        modsbox.Add(wx.StaticText(self.panel, label="Modules:"))
        modsbox.Add(modcb, proportion=1)
        
        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(label,   proportion=0)
        box.Add(button,  proportion=0)
        box.Add(netsbox, proportion=0)
        box.Add(modsbox, proportion=0)
        
        self.panel.SetSizer(box)
        self.Bind(wx.EVT_BUTTON, self.OnPress, id=1)
        self.Bind(wx.EVT_COMBOBOX, self.OnSelectNet, id=netcb.GetId())
        self.Bind(wx.EVT_COMBOBOX, self.OnSelectMod, id=modcb.GetId())
        
    def OnPress(self, event):
        print("in OnPress")

    def OnSelectNet(self, event):
        item = event.GetSelection()
        print("Net {} was selected".format(self.netnames[item]))

    def OnSelectMod(self, event):
        item = event.GetSelection()
        print("Module {} was selected".format(self.modulenames[item]))

Now that we have the derived GUI class, it’s a simple matter of instantiating it.

def InitSimpleGui(board):
  sg = SimpleGui(None, board)
  sg.Show(True)
  return sg


sg = InitSimpleGui(pcbnew.GetBoard())

And that’s it. If you find this useful and if you end up creating something for pcbnew, I’d love to hear about it.


  1. I haven’t updated the replicate script yet, but I plan on it.

  2. You actually can run them, but you’ll get some undesirable behavior. In particular, the mouse icon will be stuck in “busy” mode, and the normal interactive commands won’t work

  3. There are other options, like dialogs

pcbnew scripting doesn’t require the GUI

If you just want to process something in the pcbnew data model, you don’t have to bring up the GUI. You can just start a python job directly from the commandline. 1

Why would you do this?

In my previous life working for a large semiconductor company, we had many, many quality checks and progress trackers. Now that experience was in VLSI, but surely there are parallels in the PCB world.

Management needs a way to track the progress of the project. Engineering needs a way to enforce layout standards. An obvious example of this is design rule checking. How many opens, shorts and spacing violations are there currently? There are many other things that one could check. Maybe you have rules about the clock network. Maybe you want to check that the power grid is strong enough to handle the current its being asked to carry. Maybe the sub-design you’re working on has some restrictions on it to ensure it’ll fit into the larger design.

At the beginning of a project, we had many millions of such violations. For a while the number wouldn’t change since we were still deciding on the bigger picture stuff. Eventually, we’d change gears and want to move towards tapeout.

Of course, these quality checks don’t run in a GUI 2. You want something that can be run from the command line every night in some automated fashion.

Coming back to Kicad, there’s already such a check in the scripts directory: ddr3_length_match.py.3

From the script’s header:

Report any length problems pertaining to a SDRAM DDR3 T topology using 4 memory chips: a T into 2 Ts routing strategy from the CPU.

Once you have kicad installed, pcbnew’s python library is available to any python script. 4

python
>>> import pcbnew
>>> print pcbnew.__file__
/usr/lib/python2.7/dist-packages/pcbnew.py
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.7', <a bunch of others deleted>]

What if you compiled kicad yourself?

python
>>> import sys
>>> sys.path.insert(0, "<path to your build>/kicad/install/lib/python2.7/dist-packages")
>>> import pcbnew
>>> print pcbnew.__file__
<path to your build>/kicad/install/lib/python2.7/dist-packages/pcbnew.pyc

In the case of ddr3_length_match, it simply keeps its eye on a file5. Once a second, it looks at the time stamp of the file. If it’s been updated, the script will load it and run the required checks.

Here’s the relevant code for loading the file:

pcb = pcbnew.LoadBoard(filename)
pcb.BuildListOfNets() # required so 'pcb' contains valid netclass data

There are some other interesting APIs used in there as well. For example, to see if two pads are connected only with wires and vias:

try:
  tracks = pcb.TracksInNetBetweenPoints(start_pad.GetPosition(), end_pad.GetPosition(), netcode)
except IOError as ioe:
  return False
return True

Either way, the biggest point I’m trying to make is that when working on a design, there may be some stuff you want to keep an eye on. Timing critical nets, noise safeguards, power rail loading…

Write a script that loads your design and does the checks. Maybe it continually monitors your saves, maybe you have a checkin trigger 6, nightly, or maybe you just run it by hand.


  1. Another popular method is to parse the kicad files directly, bypassing kicad. While that works, part of the point of this blog is to reduce the need for that.

  2. well, maybe they could, but not for tracking purposes

  3. this script was written by and brought to my attention by Dick Hollenbeck. He was also instrumental in making pcbnew’s python interface as useful as it is. He added a bunch of the APIs without which scripting is kinda limited

  4. my experience is limited to linux. I imagine things will be similar for Mac users. Windows always seems to be a mystery.

  5. The file name is an argument to the script

  6. in SVN or GIT, for example

Zones, boundaries, and silkscreen

UPDATE April 14, 2017 two things have changed:

  • LAYER_ID_COUNT has been renamed to PCB_LAYER_ID_COUNT
  • Zones have been changed to use the same data structure as other stuff in kicad. As a result, some of the APIs have changed
    • instead of AppendCorner, you’ll need just Append
    • The Hatch method is on the Area, not the outline. I have not updated the text below, but the code in the github will work on the latest Kicad codebase soon.

 

In previous posts, I’ve talked about the main layout components. Tracks, modules, pads. In this one, I’m focusing on lines. The board boundary, zones, and silkscreens.

At the end of this post, I’ll have a script (you can find the full script here) that redraws the board boundary to shrink wrap around all of the existing components. It’ll also generate a zone on the clk net (of course, it’s more common to use power/gnd). The zone will have the same outline as the board.

Most of the code is pretty straightforward, but I do recommend looking closely at the notes about zones at the end of this post. There are a couple things that are not immediately obvious. 1

As a reminder, I have a uml diagram in my github area of useful, pcbnew python APIs (click for a bigger view)

Some preliminaries

First, it’s helpful to have a layername->layernumber lookup table. Later on, I’ll need to know the layers for backside copper (B.Cu) and the board boundary (Edge.Cuts)

layertable = {}

numlayers = pcbnew.PCB_LAYER_ID_COUNT
for i in range(numlayers):
 layertable[board.GetLayerName(i)] = i

Next, I’ll want to compute the bounding box by starting with an empty box and adding to it. So I’ll create a bbox class. 2. Also, I have variations on min and max. Mine are different in that the value None is supported the way I want. The standard ones treat None as -inf.

def mymin(a,b):
 if (a == None):
 return b
 if (b == None):
 return a
 if (a<b):
 return a
 return b

def mymax(a,b):
 if (a == None):
 return b
 if (b == None):
 return a
 if (a>b):
 return a
 return b


class BBox:
 def __init__(self, xl=None, yl=None, xh=None, yh=None):
 self.xl = xl
 self.xh = xh
 self.yl = yl
 self.yh = yh

 def __str__(self):
 return "({},{} {},{})".format(self.xl, self.yl, self.xh, self.yh)
 
 def addPoint(self, pt):
 self.xl = mymin(self.xl, pt.x)
 self.xh = mymax(self.xh, pt.x)
 self.yl = mymin(self.yl, pt.y)
 self.yh = mymax(self.yh, pt.y)

 def addPointBloatXY(self, pt, x, y):
 self.xl = mymin(self.xl, pt.x-x)
 self.xh = mymax(self.xh, pt.x+x)
 self.yl = mymin(self.yl, pt.y-y)
 self.yh = mymax(self.yh, pt.y+y)

Computing the BBox

Start with a null bbox:

boardbbox = BBox();

Adding tracks

alltracks = board.GetTracks() 
for track in alltracks:
  boardbbox.addPoint(track.GetStart())
  boardbbox.addPoint(track.GetEnd())

Adding Pads

allpads = board.GetPads()
for pad in allpads:
  if (pad.GetShape() == pcbnew.PAD_SHAPE_RECT): 
    if ((pad.GetOrientationDegrees()==270) | (pad.GetOrientationDegrees()==90)):
      boardbbox.addPointBloatXY(pad.GetPosition(), pad.GetSize().y/2, pad.GetSize().x/2)
    else:
      boardbbox.addPointBloatXY(pad.GetPosition(), pad.GetSize().x/2, pad.GetSize().y/2)

  elif (pad.GetShape() == pcbnew.PAD_SHAPE_CIRCLE):
    boardbbox.addPointBloatXY(pad.GetPosition(), pad.GetSize().x/2, pad.GetSize().y/2)
 
  elif (pad.GetShape() == pcbnew.PAD_SHAPE_OVAL):
    boardbbox.addPointBloatXY(pad.GetPosition(), pad.GetSize().x/2, pad.GetSize().y/2)
 
  else:
    print("unknown pad shape {}({})".format(pad.GetShape(), padshapes[pad.GetShape()]))

Adding Module silkscreens and such

for mod in board.GetModules():
  for gi in mod.GraphicalItems():
    bbox = gi.GetBoundingBox()
    boardbbox.addPointBloatXY(bbox.Centre(), bbox.GetWidth()/2, bbox.GetHeight()/2)

Generating the new data

Now we have a bounding box of everything, let’s remove the old boundary before creating a new one.

for d in board.GetDrawings():
  board.Remove(d)

A new boundary

There’s be a better way to do this. I could modify the bbox class to produce a list of line segment, but I’m lazy.

edgecut = layertable['Edge.Cuts']

seg1 = pcbnew.DRAWSEGMENT(board)
board.Add(seg1)
seg1.SetStart(pcbnew.wxPoint(boardbbox.xl, boardbbox.yl))
seg1.SetEnd( pcbnew.wxPoint(boardbbox.xl, boardbbox.yh))
seg1.SetLayer(edgecut)

seg1 = pcbnew.DRAWSEGMENT(board)
board.Add(seg1)
seg1.SetStart(pcbnew.wxPoint(boardbbox.xl, boardbbox.yh))
seg1.SetEnd( pcbnew.wxPoint(boardbbox.xh, boardbbox.yh))
seg1.SetLayer(edgecut)

seg1 = pcbnew.DRAWSEGMENT(board)
board.Add(seg1)
seg1.SetStart(pcbnew.wxPoint(boardbbox.xh, boardbbox.yh))
seg1.SetEnd( pcbnew.wxPoint(boardbbox.xh, boardbbox.yl))
seg1.SetLayer(edgecut)

seg1 = pcbnew.DRAWSEGMENT(board)
board.Add(seg1)
seg1.SetStart(pcbnew.wxPoint(boardbbox.xh, boardbbox.yl))
seg1.SetEnd( pcbnew.wxPoint(boardbbox.xl, boardbbox.yl))
seg1.SetLayer(edgecut)

A new zone

Zones are a little tricky in the kicad model. There are several classes involved. To begin, here’s an interesting comment from PolyLine.h:

// A polyline contains one or more contours, where each contour
// is defined by a list of corners and side-styles
// There may be multiple contours in a polyline.
// The last contour may be open or closed, any others must be closed.
// All of the corners and side-styles are concatenated into 2 arrays,
// separated by setting the end_contour flag of the last corner of
// each contour.
//
// When used for copper (or technical layers) areas, the first contour is the outer edge
// of the area, subsequent ones are "holes" in the copper.

I want to create my zone on the clk net on the backside, so I need a pointer to the net and the layer (using the layer table generated in preliminaries

nets = board.GetNetsByName()
clknet = nets.find("/clk").value()[1]
backlayer = layertable['B.Cu']

Now let’s create the zone. It’s a little different from creating the board boundary. If you’ve used the zone creation GUI command, the order of events should make sense.

newarea = board.InsertArea(clknet.GetNet(), 0, backlayer, boardbbox.xl, boardbbox.yl, pcbnew.CPolyLine.DIAGONAL_EDGE)

newoutline = newarea.Outline()
newoutline.AppendCorner(boardbbox.xl, boardbbox.yh);
newoutline.AppendCorner(boardbbox.xh, boardbbox.yh);
newoutline.AppendCorner(boardbbox.xh, boardbbox.yl);

This next line shouldn’t really be necessary but without it, saving to file will yield a file that won’t load.3

newoutline.CloseLastContour()

I don’t know why this is necessary. When calling InsertArea above, DIAGONAL_EDGE was passed. If you save/restore the file, the zone will come back hatched. Before then, the zone boundary will just be a line. Omit this if you are using pcbnew.CPolyLine.NO_HATCH

newoutline.Hatch()

Please leave a comment with questions or if you’d like me cover some other topic.


  1. I had to read the C++ code to figure it out

  2. wxBox probably already has something for this, but I’m not familiar enough with it. So I’m writing one

  3. The parenthesis won’t line up; there won’t be enough closing parens. I’d argue that AppendCorner should automatically do it.

Compiling Kicad on Ubuntu

In my last post, I mentioned that compiling Kicad is something most would not be willing to do.

Most of the scripting in this blog will not work in version 4.0.5 which the most recent as of this writing. I recommend to install either the nightly or build yourself. If you just want the latest verion of Kicad, then you can find nightly builds in the Kicad Downloads Area

Well, this post is about the steps needed to run your own compiled version on Ubuntu 1. These steps worked for me on a freshly installed VirtualBox Ubuntu install.

The scripting support in the latest source based kicad has progressed a bit beyond the released Kicad. There are one or two APIs that have appeared and the scripting window has some IDE’ish features added 2. I do want to make some C++ changes, so I have the need to compile. I was also helpful to step through execution to understand some of the APIs

VirtualBox Ubuntu install

These are my notes from installing Ubuntu VirtualBox.

  • create virtual machine
  • linux – ubuntu 64
  • 4 GB ram
  • virtual disk image
  • file location and size to 32GB

 

virtualbox settings->storage->controller IDE->empty = set to ubuntu-16.04.1-desktop-amd64.iso

start machine

install ubuntu
english
no install updates
erase and install
write the changes to disks – continue
set time zone
set keyboard

put in login details

install

it will want to reboot. do that now.
it will say to remove the install medium. VirtualBox seems to do that automagically

At this point you’ll have a clean install of ubuntu.

Take a snapshot so you’ll have it later.

in VirtualBox manager in the upper right. click snapshots
click on the blue camera and take a snapshot

start the machine again
go the the devices menu at the top-> shared clipboard -> bidirectional
devices menu -> insert guest additions
click run on the popup
give your password

start an xterm

Build Kicad

Based on a list here: https://gist.github.com/ceremcem/4024c0a4a8649e858855 with some additions:

sudo apt-get -y install libwxgtk3.0-0v5 libglew-dev libcairo2-dev libbz2-dev doxygen libssl-dev libboost-dev libboost-thread-dev libboost-context-dev libboost-filesystem-dev libboost-iostreams-dev libboost-locale-dev libboost-program-options-dev swig python-wxgtk3.0* git cmake libwxgtk3.0 libglm-dev libcurl3 libcurl3-dev python-dev

mkdir kicad
cd kicad
mkdir build
mkdir install

git clone -b master https://git.launchpad.net/kicad
cd build
cmake -DCMAKE_BUILD_TYPE=Debug -DwxWidgets_USE_DEBUG=ON -DKICAD_SCRIPTING_WXPYTHON=ON -DKICAD_SCRIPTING=ON -DKICAD_SCRIPTING_MODULES=ON -DCMAKE_INSTALL_PREFIX=`realpath ../install` ../kicad

make
make install

 

If you install into something other than /usr/lib; if you use prefix as is shown above, you’ll need to do this:

export LD_LIBRARY_PATH=`realpath ../install/lib/`

This is for Ubuntu 16.04.1. If these directions stop working, please leave a comment below.


  1. I have basically stopped using the Windows platform. Adobe Lightroom and Autodesk Fusion are the only reasons I bother with it at all. Sorry.

  2. it’s very possible that the IDE stuff is a freebie due to using a more recent Python component.

Real Scripting. The most important feature a tool can have.

One of the dreams of Free and Open Source Software (FOSS) is that if a program doesn’t do what you want, you can add it. This is frequently said, but I don’t think it’s as true as we’d like it to be or at least not as true as it could be. Kicad is open source and used by many. It’s also missing a lot of features, but what would it take for someone to contribute?

First, it’s written in C++ which is intimidating to many. I’d guess that for many (most?) folks who want to design a PCB, C++ means Kicad is effectively closed source.

Second, even if one is comfortable with C++, many (most?) compiled projects are not so easy to replicate. Just building and running the unmodified code is an obstacle.

So most potential contributors don’t even make it out of the gate. Scripting capabilities lower the bar. Few will compile code, many might consider trying a simple hello world script.

There are lots of examples of tools with scripting out there. Adobe products, for example, have scripting. Photoshop has a macro feature that enables user to automate many tasks. Lightroom goes further. 1. Even artsy people who are completely terrified by the idea of programming can use these.

A better example is the Firefox and later Chrome browsers. To write an addon/extension doesn’t require one to know C++ or even compile anything. Javascript is all that’s needed. In the case of Chrome, the debugger is always right there. 2. These browsers are successful largely (entirely?) because of the wealth of extensions available.

Yet another example is Blender. Everything is exposed to the scripting language. Everything. Menus, bindings, direct node/edge/face manipulation. There’s nothing you do from C++ that isn’t available in the scripting language.

Kicad’s pcbnew has had python support for some time now; I wrote a message on kicad-users about it almost four years ago. Things have progressed a little, but not much. You no longer have to recompile pcbnew to use it, which is a big step.

The purpose of this blog is to help things along. I hope to better document the existing scripting features to help new potential user make real changes to pcbnew 3

At this point in the post, if you just want to get into scripting, continue to my next posts. The rest of this one is just commentary on why I think this is an important topic.

Who am I. Who is this guy?

Up til two years ago 4, I worked for a well know semiconductor manufacturer. You’ve heard of the company and it’s almost guaranteed that you’ve owned one or more of their products. I worked there for a bit over 20 years in the CAD/EDA 5 department. For 14 of those years, I worked on and supported the VLSI 6 layout editing tools used to design the most well know of their products.

The earliest of the editors didn’t have scripting. They weren’t even written in C++ which was a young/new language at the time. 7. When I took from being a tool developer to a year and a half of active floor support, I made an important niche for myself by writing simple editing macros. In meetings, when someone reported a simple/repetitive task that’s too difficult on the tools, a frequent answer was, “let’s get Miles to write a macro”. It was a nice position to be in. Some of those macros were hard to write, but most were pretty trivial… Trivial if you knew how to do it.

Eventually that generation of tools wasn’t good enough and a new one was written. 8 The new one was written in C++ with a comprehensive TCL interface 9. You can do anything through the TCL interface. The only reason to move to C++ is runtime performance. 10

The result of this scripting capability is that great new features came from some unlikely places. This company has an army of polygon pushers with no training in software. Many of these came up with some great stuff that tool developers later supported. I’ve venture to say that today, the majority of the tools’ capabilities originated this way.

There’s a small handful of kicad developers 11. There are lots of kicad users.

How many of them would try to dig through the C++ code?

How many of them would pull up the scripting window and enter a couple python commands?

That’s the power I’d like to harness.


  1. I personally, think their “scripting” is a joke. They only enable you to invoke existing functionality. You can’t really create your own new functions. I would love to add a levels feature to Lightroom. I’ve had another idea for dealing with white balance. Alas,… can’t do it.

  2. right click->inspect

  3. I would love to see the same thing happen with eeschema

  4. in other words, I don’t work there now and I don’t represent them in any way

  5. Computer Aided Design is what most people think of it, but Electronic Design Automation is the term used by industry

  6. although I worked on chip design tools, which are not the same as PCB design tools, I think these lessons still apply

  7. Mainsail was the language that was used. I liked using it.

  8. This was all internal. Only a handful of companies do this kind of stuff and no one does nearly the amount of hand design. It made sense to develop these tools in-house and that continues to this day.

  9. Like with MAINSAIL, people hate on TCL. I think it’s a fine language that can do most things I want. A notable exception is closures/lambdas, but C++ doesn’t really have those either. C++ lambdas are very limited.

  10. There was one guy switched his code to C++ for the sole reason of preventing his users from messing with it. He claimed that too often, users would modify it poorly/incorrectly and then complain to him.  It was a cop out.

  11. I don’t 100% know that this is true; I’m new to the kicad world, but I’ll bet you a dollar.