1. boldport
  2. Untitled project
  3. PCBmodE

Source

PCBmodE / utils / gerber.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
#!/usr/bin/python

#   Copyright 2013 Boldport Limited
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

import os
import re
import datetime
from lxml import etree as et

# pcbmode modules
import svg
import utils
from Point import Point



def gerberise(cfg, manufacturer='default'):
    """
    Generate Gerbers for one or more layers
    """


    def gerberise_Point(coord, offset=Point(), digits=6, decimals=6):
        """
        Convert a float to the ridiculous Gerber format 
        """
     
        # add offset to coordinate
        coord += offset
     
        # split to integer and decimal content; the reformatting is required 
        # for floats coming in represented in scientific notation
        xi, xd = str("%f"%coord.x).split(".")
        yi, yd = str("%f"%-coord.y).split(".")
     
        # pad decimals to required number of digits for Gerber (yuck!)
        xd = xd.ljust(decimals, '0')
        yd = yd.ljust(decimals, '0')
     
        return "X%s%sY%s%s" % (xi, xd[:decimals], yi, yd[:decimals])




    def gerberise_layers(svg_in, pcb_layer, layers, gerber_file, apertures, steps=20):
        """
        Convert the SVG board to gerber layers; all the layers specified in the 'layers'
        list are combined into a single Gerber file. This allows, for example, to add the
        outline to every Gerber, as some manufacturers prefer for alighnment purposes. The
        'steps' determine the linearisation steps for Bezier curves; the higher the number,
        the better the resolution.
        """
     
        def pgparam(f, parameter, comment):
            """
            prints a gerber parameter with a preceeding comment
            """
            f.write('G04 ' + comment + ' *\n')
            f.write('%' + parameter + '*%\n')
     
            return
     
     
     
        def place_shape_in_gerber(path, style, polarity):
     
            polarity_sequence = ''
            order = ''
     
            # get level polarity directive from path
            gerber_lp = path.get('gerber_lp')
            path_type = path.get('type')
     
            if gerber_lp is None:
                gerber_lp = 'd'
     
            if path_type == 'mask_shape':
                gerber_lp = "%s" % ('c' * len(coords))
            else:
                # when stroking, all paths need to be dark, except for masks
                if style == 'stroke':
                    gerber_lp = "d%s" % ('d' * len(gerber_lp))
     
            # check for polarity and order information
            if gerber_lp is not None:
                if gerber_lp.find(';') != -1:
                    # for paths that have a particular polarity order
                    polarity_sequence, order = gerber_lp.split(';')
                    order = order.split(',')
                    # add -1 on all values
                    for i in range(0, len(order)):
                        order[i] = int(order[i]) - 1
                else:
                    polarity_sequence = gerber_lp
     
         
            if style == 'fill':
                gerber.write("G36*\n")
            elif style == 'stroke':
                gerber.write("D%d*\n" % apertures[str(stroke_width)]) # choose aperture
            else:
                print "ERROR: Gerber placement style unrecognised"
     
            # define the order or iteration
            if order == '':
                i_order = range(0, len(coords))
            else:
                i_order = order
     
            for i in i_order:
     
                # get the level polarity from list; default to 'D'
                if i < len(polarity_sequence):
                    new_polarity = polarity_sequence[i].upper()
                else:
                    new_polarity = 'D'
     
                if new_polarity != polarity:
                    polarity = new_polarity
                    if stroke_width == 0:
                        gerber.write("G37*\n")
                        
                    pgparam(gerber, "LP%s" % polarity, "level polarity (LP): dark (D), clear (C)")
     
                    to_write = "G01%sD02*\n" % (gerberise_Point(coords[0][0], transform))
                    gerber.write(to_write)
     
                    if stroke_width == 0:
                        gerber.write("G36*\n")
     
                to_write = "G01%sD02*\n" % (gerberise_Point(coords[i][0], transform))
                gerber.write(to_write)
     
                for coord in coords[i][1:]:
                    to_write = "G01%sD01*\n" % (gerberise_Point(coord, transform))
                    gerber.write(to_write)
            
            if (style == 'fill'):
                gerber.write("G37*\n")
            else:
                pass
     
            return polarity
     
     
     
     
        def print_gerber_header(gerber, layers):
            """
            Prints the header information and commands onto the Gerber file;
            the header includes everything up to the actual placement of shapes
            """
     
            # print out gerber preamble
            gerber.write("G04 *\n")
            gerber.write("G04 Hello! This Gerber file was generated using PCBmodE version %s on %s GMT; *\n" % (cfg['pcbmode']['version'], datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")))
            gerber.write("G04 please visit http://boldport.blogspot.co.uk for latest information. *\n")
            gerber.write("G04 *\n")
            temp = ''
            for layer in layers[:-1]:
                temp += layer + ', '
            temp += layers[-1]
            gerber.write("G04 Layers included in this file: %s *\n" % temp)
            gerber.write("G04 *\n")
         
            pgparam(gerber, "FSLAX26Y26", "leading zeros omitted (L); absolute data (A); 2 integer digits and 3 fractional digits")
            pgparam(gerber, "MOMM", "mode (MO): millimeters (MM)")
         
            # this aperture is used for fills
            pgparam(gerber, "ADD10R,%.3fX%.3f" % (0.001, 0.001), "silkscreen fill aperture definition") 
         
            # the aperture list, based on the different stroke-widths defined in
            # input SVG
            for aperture in apertures:
                pgparam(gerber, "ADD%dC,%.2fX" % (apertures[aperture], 
                                                  float(aperture)), "aperture definition")
     
            return
     
     
     
        def get_mask_paths(svg_layer):
            """
            Locates and extracts all the mask paths
            """
     
            mask_paths = []
     
            # check if layer has a mask
            mask = svg_layer.find(".//svg:g[@mask]", namespaces={'inkscape':cfg['namespace']['inkscape'],'svg':cfg['namespace']['svg']})
     
            if mask is not None:
     
                # this captures the paths that are going to be masked by the masking
                # paths that are captured next
                paths_to_be_masked = mask.xpath(".//*")
                for path in paths_to_be_masked:
                    mask_paths.append(path)
     
                mask_field = mask.get('mask')            
                # TODO: there's probably a more robust way to do this...
                mask_id = mask_field[mask_field.index('#')+1:-1]
                mask_id = mask_id.strip()
                # get the masking group based on the url
                mask_def = svg_in.find("//svg:mask[@id='%s']" % mask_id, namespaces={'inkscape':cfg['namespace']['inkscape'],'svg':cfg['namespace']['svg']})
                mask_groups = mask_def.xpath(".//svg:g", namespaces={'inkscape':cfg['namespace']['inkscape'],'svg':cfg['namespace']['svg']})
                
                # extract all the paths, except for the 'cover' which defines the overall
                # area of the masking, which is effectively the size of the board
                for mask_group in mask_groups:
                    mask_paths += mask_group.xpath(".//*[not(@id='%s')]" % 'mask_cover', namespaces={'inkscape':cfg['namespace']['inkscape'],'svg':cfg['namespace']['svg']})
     
            return mask_paths
     
     
     
        # open gerber file
        #gerber = open(os.path.join(pcbmode_cfg['build_path'], 'production', "%s" % filename), 'w')
        gerber = open(gerber_file, 'w')
     
        print_gerber_header(gerber, layers)
     
        paths = []
     
        # get the default line witdth from the style sheet
        ss_line_width = float(cfg['layout_style']['silkscreen']['outline'].get('stroke-width') or 0.15)
     
        transform = Point()
        tmp = Point()
        
        # the layers that go into a single file
        for layer in layers:
     
            polarity = 'D'
     
            # set polarity in Gerber file
            pgparam(gerber, "LP%s" % polarity, "level polarity (LP): dark (D), clear (C)")
     
            if pcb_layer is not None: # SVG layers independant of PCB layers (e.g., 'documentation')
                xpath_regex = "//svg:g[@inkscape:label='%s']//svg:g[@inkscape:label='%s']"
                svg_layer = svg_in.find(xpath_regex % (pcb_layer, layer), namespaces={'inkscape':cfg['namespace']['inkscape'],'svg':cfg['namespace']['svg']})
            else:
                xpath_regex = "//svg:g[@inkscape:label='%s']"
                svg_layer = svg_in.find(xpath_regex % (layer), namespaces={'inkscape':cfg['namespace']['inkscape'],'svg':cfg['namespace']['svg']})
     
            # get all paths except copper pours, which are handled elsewhere
            layer_paths = svg_layer.xpath(".//svg:path[@d and not(@id='%s')]" % ('copper_pour'), namespaces={'inkscape':cfg['namespace']['inkscape'],'svg':cfg['namespace']['svg']})
     
            # get all mask paths
            mask_paths = get_mask_paths(svg_layer)
     
            # add paths; the order matters since the pours, then masks must be drawn
            # before anything else
            paths = mask_paths + layer_paths
     
            for path in paths:
            
                t = path.get('transform') or ''
                d = path.get('d')
         
                regex = r".*?translate\s?\(\s?(?P<x>-?[0-9]*\.?[0-9]+)\s?[\s,]\s?(?P<y>-?[0-9]*\.?[0-9]+\s?)\s?\).*"
         
                tr = re.match(regex, t)
                if tr:
                    transform.assign(tr.group('x'), tr.group('y'))
                else:
                    transform.assign(0, 0)
                ancestors = path.xpath("ancestor::*[@transform]")
                for ancestor in ancestors:
                    t = ancestor.get('transform')
                    tr = re.match(regex, t)
                    if tr:
                        tmp.assign(tr.group('x'), tr.group('y'))
                        transform += tmp
     
                # convert path to a list of coordinates
                coords = svg.relative_svg_path_to_absolute_coord_list(d, steps)
     
                styles = []
         
                # get the style from ancestors if a specific style isn't defined
                ancestors_with_style = path.xpath("ancestor::*[@style]") or []
     
                for ancestor in ancestors_with_style:
                    styles.append(ancestor.get('style'))
     
                path_style = path.get('style') or None
                if path_style is not None:
                    styles.append(path_style)
     
                stroke = 'none'
                stroke_width = 0
                fill = 'none'
     
                for style in styles:
                    regex = r".*?%s:\s?(?P<s>[^;]*)(?:;|$)"
                    stroke_def = re.match(regex % 'stroke', style)
                    if stroke_def is not None:
                        stroke = stroke_def.group('s')
     
                    stroke_width_def = re.match(regex % 'stroke-width', style)    
                    if stroke_width_def is not None:
                        stroke_width = float(stroke_width_def.group('s'))
     
                    fill = re.match(regex % 'fill', style)
                    if fill is not None:
                        fill = fill.group('s')
     
                if stroke == 'none':
                     stroke_width = 0                 
     
                if fill != 'none':
                    polarity = place_shape_in_gerber(path, 'fill', polarity) 
                if stroke_width != 0:
                    polarity = place_shape_in_gerber(path, 'stroke', polarity)
     
     
        gerber.write("G04 end of program*\n")
        gerber.write("M02*\n")
        gerber.close()





    # directory for storing the Gerbers within the build path
    production_path = os.path.join(cfg['base_dir'], 
                                   cfg['pcbmode']['locations']['build'], 
                                   'production')
    utils.create_dir(production_path)

    input_file = os.path.join(cfg['base_dir'], 
                              cfg['pcbmode']['locations']['build'], 
                              cfg['board_name'] + '.svg')
    svg_in = et.ElementTree(file=input_file)

    # get all styles into dict
    tags_with_style = svg_in.xpath(".//*[@style]")
    stroke_regex = r".*?stroke-width:\s?(?P<s>[^;]*).*?"
    apertures = {}
    aperture_number = 20
    for tag in tags_with_style:
        stroke_style = re.match(stroke_regex, tag.get('style'))
        if stroke_style is not None:
            if apertures.get(stroke_style.group('s')) is None:
                apertures[stroke_style.group('s')] = aperture_number
                aperture_number += 1

    pcbmode_version = cfg['pcbmode']['version']
    board_name = cfg['board_name']
    board_revision = cfg['board']['meta'].get('board_revision') or 'A'


    filenames = []

    base_dir = os.path.join(cfg['base_dir'], 
                            cfg['pcbmode']['locations']['build'], 
                            'production')
    base_name = "%s_rev_%s" % (board_name, board_revision)


    filename_info = cfg['pcbmode']['manufacturers'][manufacturer]['filenames']['gerbers']

    # outline gerber
    add = '_%s.%s' % ('outline', 
                      filename_info['other']['outline'].get('ext'))
    filename = os.path.join(base_dir, base_name + add)
    print base_name + add,
    filenames.append(filename)
    gerberise_layers(svg_in, None, ['outline'], 
                     filename, apertures, 30)

    # documentation gerber
    add = '_%s.%s' % ('documentation', 
                      filename_info['other']['documentation'].get('ext'))
    filename = os.path.join(base_dir, base_name + add) 
    print base_name + add,
    filenames.append(filename)
    gerberise_layers(svg_in, None, ['documentation','measurements'],
                     filename, apertures)
 
    
    for pcb_layer in utils.get_surface_layers(cfg):
   
        add = '_%s_%s.%s' % (pcb_layer, 'copper', 
                          filename_info[pcb_layer]['copper'].get('ext'))
        filename = os.path.join(base_dir, base_name + add)
        print base_name + add,
        filenames.append(filename)
        gerberise_layers(svg_in, pcb_layer, ['copper'],
                         filename, apertures)

        add = '_%s_%s.%s' % (pcb_layer, 'soldermask', 
                          filename_info[pcb_layer]['soldermask'].get('ext'))
        filename = os.path.join(base_dir, base_name + add) 
        print base_name + add,
        filenames.append(filename)
        gerberise_layers(svg_in, pcb_layer, ['soldermask'],
                         filename, apertures)

        add = '_%s_%s.%s' % (pcb_layer, 'silkscreen', 
                          filename_info[pcb_layer]['silkscreen'].get('ext'))
        filename = os.path.join(base_dir, base_name + add) 
        print base_name + add,
        filenames.append(filename)
        gerberise_layers(svg_in, pcb_layer, ['silkscreen'], 
                         filename, apertures)


    return filenames