Source

PCBmodE / utils / footprint.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
#!/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 json
from lxml import etree as et

# pcbmode modules
import svg 
import utils
import place
from Point import Point




def create_footprint(cfg,
                     footprint_name, 
                     refdef, 
                     part_rotate=0, 
                     part_rotation_point=Point(), 
                     part_scale_factor=1,
                     silkscreen_outline_place=True, 
                     silkscreen_refdef_place=True,
                     assembly_place=True, 
                     silkscreen_refdef_location=None,
                     silkscreen_refdef_rotate=0):



    def place_pads(refdef):
        """ 
        Places pads on the board, and adds a soldermask area automatically,
        unless explicitely prevented in the pin definition. Also places drills
        if any are specified.
        """

        # count number of drills per diameter 
        drill_count = {}

        # xpath search expression
        xpath_expr = "//g[@inkscape:label='%s']//g[@inkscape:label='%s']"

        pad_drills_group = et.SubElement(footprint_svg_layers['drills']['layer'], 'g', 
                                         id='pad_drills', refdef=refdef)

        # the group where cutouts are going to be placed
        cutouts_group = et.SubElement(footprint_svg_layers['dimensions']['outline']['layer'], 'g', 
                                         id='cutouts_%s' % refdef, refdef=refdef)

        pad_numbers_style = utils.dict_to_style(cfg['layout_style']['board'].get('pad_numbers'))
        pad_numbers_font_size = cfg['layout_style']['board']['pad_numbers'].get('font-size') or '0.15px'
        # remove 'px'
        pad_numbers_font_size = float(pad_numbers_font_size[:-2])
        pad_numbers_group = et.SubElement(footprint_svg_layers[cfg['board']['physical']['stackup'][0]]['copper']['pads']['layer'], 
                                          'g', id='pin_numbers_%s' % refdef,
                                          style=pad_numbers_style,
                                          refdef=refdef)

        # create groups
        pad_soldermask_group = {}
        pad_group = {}

        # the size of soldermask is the pad size multiplied by this scale factor
        try:
            # from board configuration
            soldermask_scale_factor = cfg['board']['soldermask'].get('pad_scale_factor') or 1.1
        except:
            # or hard coded default
            soldermask_scale_factor = 1.1

        # the size of soldermask is the pad size plus this buffer; only used for
        # rectangular shapes
        try:
            # from board configuration
            soldermask_buffer = cfg['board']['soldermask'].get('pad_buffer') or 0.1
        except:
            # or hard coded default
            soldermask_buffer = 0.1


        # place pins/pads
        for pin in part.get('pins'):
     
            # get the pad name
            pad_name = part['pins'][pin]['layout'].get('pad')

            # get location of pad and convert to type Point   
            location = utils.to_Point(part['pins'][pin]['layout'].get('location') or [0, 0])
            
            # get the rotation of the pad and add the rotation of the part
            pin_rotate = -(part['pins'][pin]['layout'].get('rotate') or 0)
            pin_rotate -= part_rotate
            
            pad_scale_factor = part['pins'][pin]['layout'].get('scale_factor') or 1
                 
            # rotate the placement point of pad when the part is rotated     
            location.rotate(part_rotate, Point())

            shapes = {}
            for pcb_layer in utils.get_surface_layers(cfg):
                shapes[pcb_layer] = part['pads'][pad_name]['shapes'].get(pcb_layer) or []

            for pcb_layer in utils.get_surface_layers(cfg):
                for shape in shapes[pcb_layer]:

                    # the following is a bit of an inefficient hack to solve the issue
                    # with phantom groups appearing both on the top and bottom layers
                    # and mess up extraction of properties when the SVG is modified in
                    # Inkscape
                    if pad_soldermask_group.get(pcb_layer) is None:
                        pad_soldermask_group[pcb_layer] = et.SubElement(footprint_svg_layers[pcb_layer]['soldermask']['layer'], 
                                                                        'g', id='%s_pad_soldermask_%s' % (pcb_layer, refdef),
                                                                        style=utils.dict_to_style(cfg['layout_style']['soldermask']['fill']),
                                                                        refdef=refdef)

                    if pad_group.get(pcb_layer) is None:
                        pad_group[pcb_layer] = et.SubElement(footprint_svg_layers[pcb_layer]['copper']['pads']['layer'], 
                                                             'g', id='%s_pads_%s' % (pcb_layer, refdef),
                                                             style=utils.dict_to_style(cfg['layout_style']['copper']['pads'][pcb_layer]),
                                                             refdef=refdef)


                    shape_type = shape['type']
                    shape_offset = utils.to_Point(shape.get('offset') or [0, 0])
                    shape_scale_factor = shape.get('scale_factor') or 1
                    shape_rotate = shape.get('rotate') or 0
                    gerber_lp = shape.get('gerber_lp')
                    shape_soldermask_buffer = shape.get('soldermask_buffer') or soldermask_buffer
                    shape_style = None

                    translate = (str(round((location.x + shape_offset.x)*part_scale_factor, sig_dig)) + ' ' +
                                 str(round((-location.y - shape_offset.y)*part_scale_factor, sig_dig)))
                    transform = 'translate(' + translate + ')'

                    # if the pad shape is defined as a 'rect' convert it into
                    # a path
                    if shape_type.lower() in ['rect', 'rectangle']:
                        shape_path = svg.rect_to_path(shape)
     
                    elif shape_type.lower() == 'path':
                        shape_path = shape.get('value')
     
                    elif shape_type.lower() == 'circle':
                        diameter = shape.get('diameter')
                        shape_path = svg.circle_diameter_to_path(diameter)

                    elif shape_type.lower() == 'ring':
                        shape_path = svg.ring_diameters_to_path(shape.get('diameter_outer'),
                                                                shape.get('diameter_inner'))
                        gerber_lp = 'dc'
                        shape_style = 'fill-rule:evenodd;'
     
                    else:
                        print "ERROR: unrecognised shape type %s" % shape_type
     
                    # convert path to relative commands
                    shape_path = svg.absolute_to_relative_path(shape_path)

                    # combined scale factor for copper
                    combined_scale_factor = (pad_scale_factor * 
                                             part_scale_factor * 
                                             shape_scale_factor)

                    w, h, shape_path = svg.transform_path(shape_path, 
                                                          True, 
                                                          combined_scale_factor, 
                                                          pin_rotate - shape_rotate, 
                                                          part_rotation_point)
     
                    # place shape
                    shape_element = et.SubElement(pad_group[pcb_layer], 
                                                  'path',
                                                  id="%s_%s" % (refdef, pin),
                                                  transform=transform,
                                                  d=shape_path,
                                                  pin=pin,
                                                  refdef=refdef)
                    if gerber_lp is not None:
                        shape_element.set('gerber_lp', gerber_lp)

                    if shape_style is not None:
                        shape_element.set('style', shape_style)

                    # first check if the pad has a distance setting, then check for global
                    # setting, and if not, default to 0.5
                    # TODO: set the default setting in the board config, not hard coded
                    distances = shape.get('distances')
                    if distances is not None:
                        try:
                            pour_buffer = distances['buffer_from_pour_to'].get('pad')
                        except:
                            pour_buffer = 0.5
                    else:                        
                        try:
                            pour_buffer = cfg['board']['distances']['buffer_from_pour_to'].get('pad') or 0.5
                        except:
                            pour_buffer = 0.5


                    # place mask unless no mask is needed
                    if pour_buffer not in ['none', 'None', None, 'no']:
                        mask_element = et.SubElement(footprint_masks[pcb_layer], 'path', 
                                                     #id="%s" % pcb_layer,
                                                     transform=transform,
                                                     type="mask_shape",
                                                     style=cfg['pcbmode']['mask_style'] % str(pour_buffer * 2),
                                                     d=shape_path)
                        if gerber_lp is not None:
                            mask_element.set('gerber_lp', gerber_lp)


                    # get soldermask data
                    soldermask = shape.get('soldermask')
                    if soldermask not in ['none', 'no', 'None', 'No']:
                        if soldermask is None:
                            soldermask_path = shape_path
                            soldermask_offset = Point()
                            soldermask_rotate = 0
                            if shape_type in ['rect', 'rectangle']:
                                shape_soldermask_scale_factor = 1
                                shape_radii = shape.get('radii')
                                shape_width = shape.get('width')
                                shape_height = shape.get('height')
                                if shape_radii is not None:
                                    shape_radii_silkscreen = {}
                                    for corner in shape_radii:
                                        if shape_radii[corner] != 0:
                                            shape_radii_silkscreen[corner] = shape_radii[corner] + shape_soldermask_buffer/2
                                else:
                                    shape_radii_silkscreen = None

                                soldermask_path = svg.width_and_height_to_path(shape_width + shape_soldermask_buffer, 
                                                                               shape_height + shape_soldermask_buffer,
                                                                               shape_radii_silkscreen)
                              

                                soldermask_rotate = -pin_rotate
                            else:
                                shape_soldermask_scale_factor = soldermask_scale_factor
                                
                        else:
                            soldermask_offset = utils.to_Point(soldermask.get('offset') or [0, 0])
                            soldermask_rotate = float(soldermask.get('rotate') or 0)
                            soldermask_type = soldermask.get('type') or 'shape'
                            shape_soldermask_scale_factor = float(soldermask.get('scale_factor') or soldermask_scale_factor)

                            if soldermask_type in ['shape', 'same_as_shape']:

                                # for a ring, this increases the size of the outer ring and decreases
                                # the size of the inner ring
                                if shape_type == 'ring':
                                    outer_diameter = shape.get('diameter_outer')*shape_soldermask_scale_factor
                                    inner_diameter = shape.get('diameter_inner')-(outer_diameter-shape.get('diameter_outer'))
                                    soldermask_path = svg.ring_diameters_to_path(outer_diameter,
                                                                                 inner_diameter)
                                    shape_soldermask_scale_factor = 1
                                else:
                                    soldermask_path = shape_path
                            
                            elif soldermask_type in ['rect', 'rectangle']:
                                width = float(soldermask['width'])
                                height = float(soldermask['height'])
                                shape_soldermask_buffer = soldermask.get('buffer') or soldermask_buffer
                                soldermask_path = svg.width_and_height_to_path(width+shape_soldermask_buffer, 
                                                                               height+shape_soldermask_buffer)
                                shape_soldermask_scale_factor = 1
                            
                            elif soldermask_type == 'path':
                                soldermask_path = svg.absolute_to_relative_path(soldermask.get('value'))
                            
                            else:
                                print "ERROR: unregognised soldermask shape type"
     
                        
                        soldermask_translate = (str(round((location.x + shape_offset.x + 
                                                           soldermask_offset.x)*part_scale_factor, sig_dig)) + ' ' +
                                                str(round((-location.y - shape_offset.y - 
                                                            soldermask_offset.y)*part_scale_factor, sig_dig)))
                        soldermask_transform = 'translate(' + soldermask_translate + ')'
     
                        # combined scale factor for soldermask
                        soldermask_combined_scale_factor = (part_scale_factor *
                                                            pad_scale_factor *
                                                            shape_soldermask_scale_factor)



                        w, h, shape_soldermask_path = svg.transform_path(soldermask_path, 
                                                                         False, 
                                                                         soldermask_combined_scale_factor, 
                                                                         -soldermask_rotate,
                                                                         part_rotation_point)
     
     
                        # add soldermask to shape
                        soldermask_pad = et.SubElement(pad_soldermask_group[pcb_layer], 
                                                       'path',
                                                       transform=soldermask_transform,
                                                       d=shape_soldermask_path,
                                                       refdef=refdef)
                        if gerber_lp is not None:
                            soldermask_pad.set('gerber_lp', gerber_lp)

                        if shape_style is not None:
                            soldermask_pad.set('style', shape_style)


            # process drills
            pad_drills = part['pads'][pad_name].get('drills')
            if pad_drills is not None:
                for drill in pad_drills:
                    place.place_drill(cfg, drill, pad_drills_group, 
                                      location, part_scale_factor)

                    diameter = str(drill.get('diameter'))
                    count = drill_count.get(diameter)
                    if count is None:
                        drill_count[str(diameter)] = 1
                    else:
                        drill_count[str(diameter)] = count + 1


            # should the pad number be shown? Default to 'yes'
            show_number = part['pins'][pin]['layout'].get('show_pin_number') or 'yes'
            pin_name = part['pins'][pin]['layout'].get('name')

            if show_number.lower() == 'yes':
                text_to_show = pin
                if pin_name is not None:
                    text_to_show += " %s" % pin_name
                t = et.SubElement(pad_numbers_group, 'text',
                                  x=str(location.x),
                                  # TODO: get rid of this hack
                                  y=str(-location.y + pad_numbers_font_size/3),
                                  refdef=refdef)
                t.text = text_to_show

            # process cutouts
            cutouts = part['pads'][pad_name].get('cutouts') 
            if cutouts is not None:
                for cutout in cutouts:
                    shape_type = cutout.get('type')
                    if shape_type in ['rect', 'rectangle']:
                        offset = utils.to_Point(shape.get('offset') or [0, 0])
                        cutout_path = svg.rect_to_path(cutout)
                        cutout_element = et.SubElement(cutouts_group, 'path',
                                                       transform=transform,
                                                       d=cutout_path,
                                                       refdef=refdef)

        return drill_count





     
    def place_assembly_outline(refdef):
        """
        Adds the assembly outline to the board
        """ 

        assembly_outline_group = {}
        for pcb_layer in utils.get_surface_layers(cfg):
            # default style to outline
            assembly_outline_group[pcb_layer] = et.SubElement(footprint_svg_layers[pcb_layer]['assembly']['layer'], 
                                                              'g', id='assembly_outline',
                                                              style=utils.dict_to_style(cfg['layout_style']['assembly']['outline']),
                                                              refdef=refdef)

        shapes = {}
        for pcb_layer in utils.get_surface_layers(cfg):
            try:
                shapes[pcb_layer] = part['layout']['assembly']['outline'].get(pcb_layer)
            except:
                shapes[pcb_layer] = None

        for pcb_layer in utils.get_surface_layers(cfg):
            if shapes[pcb_layer] is not None:
                assembly_outline = footprint_svg_layers[pcb_layer]['assembly']['layer']
                for shape in shapes[pcb_layer]:
                    shape_type = shape['type']
                    shape_style = shape.get('style')
                    shape_scale = shape.get('scale_factor') or 1
                    shape_location = utils.to_Point(shape.get('location') or [0, 0])
                    shape_offset = shape.get('offset') or [0, 0]

                    translate = 'translate(%s %s)' % (round(shape_location.x, sig_dig),
                                                      round(-shape_location.y, sig_dig))
         
                    transform = translate

                    if shape_type in ['rect', 'rectangle']:
                        offset = shape['offset']
                        width = float(shape['width'])
                        height = float(shape['height'])
                        offset = Point(shape['offset'][0], shape['offset'][1])

                        transform += ' rotate('+str(part_rotate)+')'
           
                        element = et.SubElement(assembly_outline_group[pcb_layer], 'rect',
                                                x=str(offset.x - width/2),
                                                y=str(-offset.y - height/2),
                                                width=str(width),
                                                height=str(height),
                                                transform=transform,
                                                refdef=refdef)

                    if shape_type in ['circ', 'circle']:
                        offset = utils.to_Point(shape.get('offset') or [0, 0])
                        radius = float(shape['diameter']) / 2
                        transform += ' rotate('+str(part_rotate)+')'
           
                        element = et.SubElement(assembly_outline_group[pcb_layer], 'circle',
                                                cx=str(offset.x),
                                                cy=str(-offset.y),
                                                r=str(radius),
                                                transform=transform,
                                                refdef=refdef)

                    if shape_type in ['text']:
                        text = shape.get('value')
                        if text not in [None, '']:
                            place.place_text(shape, assembly_outline, 'assembly')
                        path = None

                    elif shape_type in ['path']:
                        path = shape.get('value')

                        # convert path to relative commands
                        path = svg.absolute_to_relative_path(path)
             
                        # get a path having an origin at the center of the shape
                        # defined by the path
                        w, h, path = svg.transform_path(
                                path, 
                                True, 
                                shape_scale * part_scale_factor, 
                                -part_rotate, 
                                Point())
             
                        element = et.SubElement(assembly_outline_group[pcb_layer], 'path',
                                                   transform=transform,
                                                   d=path,
                                                   refdef=refdef)

                    if shape_style is not None:
                        element.set('style', shape_style)              
         
     

     
    def place_silkscreen_outline(refdef):


        silkscreen_outline_group = {}
        for pcb_layer in utils.get_surface_layers(cfg):
            # default style to outline
            silkscreen_outline_group[pcb_layer] = et.SubElement(footprint_svg_layers[pcb_layer]['silkscreen']['layer'], 
                                                                'g', id='silkscreen_outline',
                                                                refdef=refdef)

        shapes = {}
        for pcb_layer in utils.get_surface_layers(cfg):
            try:
                shapes[pcb_layer] = part['layout']['silkscreen']['outline'].get(pcb_layer)
            except:
                shapes[pcb_layer] = None

        for pcb_layer in utils.get_surface_layers(cfg):
            if shapes[pcb_layer] is not None:
                silkscreen_outline = footprint_svg_layers[pcb_layer]['silkscreen']['layer']
                for shape in shapes[pcb_layer]:
                    shape_type = shape['type']
         
                    # get rotation of shape and add the part's rotation
                    shape_rotate = shape.get('rotation') or 0
                    shape_rotate += part_rotate
                    shape_location = utils.to_Point(shape.get('location') or [0, 0])
                    shape_scale = shape.get('scale_factor') or 1
                    shape_offset = utils.to_Point(shape.get('offset') or [0, 0])
                    shape_style = shape.get('style') or None

                    shape_offset.rotate(shape_rotate, Point())
                    t_point = Point(shape_location.x+shape_offset.x, 
                                    -shape_location.y-shape_offset.y)

                    translate = 'translate(%s %s)' % (round(t_point.x, sig_dig),
                                                      round(t_point.y, sig_dig))
         
                    transform = translate
         
                    # if the pad shape is defined as a 'rect' convert it into
                    # a path
                    if shape_type in ['rect', 'rectangle']:
                        offset = shape.get('offset') or [0, 0]
                        path = svg.rect_to_path(shape)

                    if shape_type in ['circ', 'circle']:
                        offset = shape.get('offset') or [0, 0]
                        path = svg.circle_diameter_to_path(float(shape.get('diameter')))

                    if shape_type in ['text']:
                        text = shape.get('value')
                        if text not in [None, '']:
                            place.place_text(cfg, shape, silkscreen_outline, 'silkscreen')
                        path = None

                    elif shape_type in ['path']:
                        path = shape.get('value')

                    if path is not None:

                        # convert path to relative commands
                        path = svg.absolute_to_relative_path(path)
             
                        # get a path having an origin at the center of the shape
                        # defined by the path
                        w, h, path = svg.transform_path(
                                path, 
                                True, 
                                shape_scale * part_scale_factor, 
                                -part_rotate, 
                                Point())
             
                        ss_element = et.SubElement(silkscreen_outline_group[pcb_layer], 'path',
                                                   transform=transform,
                                                   d=path,
                                                   refdef=refdef)

                        if shape_style == 'outline':
                            shape_style = utils.dict_to_style(cfg['layout_style']['silkscreen'].get('outline'))
                        elif shape_style == 'fill':
                            shape_style = utils.dict_to_style(cfg['layout_style']['silkscreen'].get('fill'))
                        else:
                            # default to outline
                            shape_style = utils.dict_to_style(cfg['layout_style']['silkscreen'].get('outline'))

                        if shape_style is not None:
                            ss_element.set('style', shape_style)
                    
        return



     
    def place_assembly_refdef(refdef=None):
        """
        Places the reference designators for the assembly drawing
        TODO: instead of location coordinates, be able to accept "center"
        and place at the center of the assembly outline automatically
        """

        refdefs = {}
        for pcb_layer in utils.get_surface_layers(cfg):
            refdefs[pcb_layer] = part['layout']['assembly']['refdef'].get(pcb_layer)

        font_name = cfg['board']['meta'].get('assembly_font') or cfg['board']['meta']['font']
        
        # open font SVG
        try: 
            font = et.ElementTree(file=os.path.join(cfg['base_dir'], cfg['pcbmode']['locations']['fonts'], font_name + '.svg'))
        except IOError as e:
            print "I/O error({0}): {1}".format(e.errno, e.strerror)

        # scale of text
        # TODO: add as a global parameter somewhere
        font_scale = 0.0009

        # get dimensions of font
        # TODO: check how this is spec'd variable-width fonts
        glyph_width = float(font.find("//n:font", namespaces={'n': cfg['namespace']['svg']}).get('horiz-adv-x'))
        glyph_height = float(font.find("//n:font-face", namespaces={'n': cfg['namespace']['svg']}).get('units-per-em'))
        glyph_ascent = float(font.find("//n:font-face", namespaces={'n': cfg['namespace']['svg']}).get('ascent'))
        glyph_decent = float(font.find("//n:font-face", namespaces={'n': cfg['namespace']['svg']}).get('descent'))

        for pcb_layer in utils.get_surface_layers(cfg):
            if refdefs[pcb_layer] is not None and len(refdefs[pcb_layer]) != 0:
                location = utils.to_Point(part['layout']['assembly']['refdef'][pcb_layer].get('location') or [0, 0])
                assembly_refdef_group = et.SubElement(footprint_svg_layers[pcb_layer]['assembly']['layer'], 
                                                      'g', id='assembly_refdef',
                                                      style=utils.dict_to_style(cfg['layout_style']['assembly']['fill']),
                                                      refdef=refdef)
                for i, letter in enumerate(refdef[:]):
                    glyph_path = font.find("//n:glyph[@unicode='"+letter+"']", namespaces={'n': cfg['namespace']['svg']}).get('d')
                    fd = svg.mirror_path_over_axis(glyph_path, 'x', glyph_width)
                    rotate = 'rotate('+str(180+part_rotate)+')'
         
                    fd_r = svg.absolute_to_relative_path(fd)
                    
                    # the division by '3' here is a hack that works for now, for a specific font!
                    # TODO: figure out a consistent way to alighn text vertically
                    translate = 'translate(%s %s)' % (round(-i*glyph_width*font_scale-location.x, sig_dig),
                                                      round(location.y-glyph_ascent/3*font_scale, sig_dig))
                    scale = 'scale('+str(font_scale)+')'
                    transform = rotate + ' ' + translate + ' ' + scale
         
                    lt = et.SubElement(assembly_refdef_group, 
                                       'path', type='refdef', 
                                       letter=letter,
                                       transform=transform,
                                       d=fd_r,
                                       refdef=refdef)

        return






    def place_silkscreen_refdef(refdef=None, location=None, rotate=0):
        """
        Places the reference designators for silkscreen
        """

        refdefs = {}
        for pcb_layer in utils.get_surface_layers(cfg):
            refdefs[pcb_layer] = part['layout']['silkscreen']['refdef'].get(pcb_layer)

        # TODO: instead of location coordinates, be able to accept 
        # "top_left"/"center"/ etc. and place the refdefs there automatically

        font_name = cfg['board']['meta'].get('silkscreen_font') or cfg['board']['meta']['font']

        # open font SVG
        try: 
            font = et.ElementTree(file=os.path.join(cfg['base_dir'], cfg['pcbmode']['locations']['fonts'], font_name + '.svg')) 
        except IOError as e:
            print "I/O error({0}): {1}".format(e.errno, e.strerror)

        # scale of text
        # TODO: add as a global parameter somewhere; maybe calculate based on
        # desired height specification in mm from size of font glyphs?
        font_scale = 0.0009

        # get dimensions of font
        # TODO: check how this is spec'd variable-width fonts
        glyph_width = float(font.find("//n:font", namespaces={'n': cfg['namespace']['svg']}).get('horiz-adv-x'))
        glyph_height = float(font.find("//n:font-face", namespaces={'n': cfg['namespace']['svg']}).get('units-per-em'))
        glyph_ascent = float(font.find("//n:font-face", namespaces={'n': cfg['namespace']['svg']}).get('ascent'))
        glyph_decent = float(font.find("//n:font-face", namespaces={'n': cfg['namespace']['svg']}).get('descent'))

        for pcb_layer in utils.get_surface_layers(cfg):
            if refdefs[pcb_layer] is not None and len(refdefs[pcb_layer]) != 0:
                # placement location can be overridden when the part is instantiated
                if location is None:
                    location = utils.to_Point(part['layout']['silkscreen']['refdef'][pcb_layer].get('location') or [0, 0])
                silkscreen_refdef_group = et.SubElement(footprint_svg_layers[pcb_layer]['silkscreen']['layer'], 
                                                       'g', id='silkscreen_refdef',
                                                        style=utils.dict_to_style(cfg['layout_style']['silkscreen']['fill']),
                                                        refdef=refdef)
                for i, letter in enumerate(refdef[:]):
                    glyph_path = font.find("//n:glyph[@unicode='"+letter+"']", namespaces={'n': cfg['namespace']['svg']}).get('d')
         
                    # check to see if there's a gerber 'level polarity' ('LP') directive
                    gerber_lp = font.find("//n:glyph[@unicode='"+letter+"']", namespaces={'n': cfg['namespace']['svg']}).get('gerber_lp') or None
         
                    # mirror the path over x-axis
                    # TODO: check if this is required for all SVG fonts...
                    fd = svg.mirror_path_over_axis(glyph_path, 'x', glyph_width)
         
                    # convert to a relative path 
                    fd_r = svg.absolute_to_relative_path(fd)
         
                    total_rotate = 180 - part_rotate - rotate
         
                    # rotate and scale path
                    fd_width, fd_height, fd_r_norm = svg.transform_path(fd_r,
                                                                        False,
                                                                        font_scale,
                                                                        total_rotate,
                                                                        Point())
                    
                    # the division by '3' here is a possible hack that works for now, for a specific font!
                    # TODO: figure out a consistent way to alighn text vertically, and how to properly do it
                    place = Point(i*glyph_width*font_scale+location.x, -location.y+glyph_ascent/3*font_scale)
                    place.rotate(-part_rotate-rotate, Point())
                    translate = 'translate(%s %s)' % (round(place.x, sig_dig),
                                                      round(place.y, sig_dig))
                    
                    transform = translate
         
                    lt = et.SubElement(
                             silkscreen_refdef_group, 
                             'path', 
                             type='refdef',
                             letter=letter,
                             transform=transform,
                             d=fd_r_norm,
                             refdef=refdef)
                    if gerber_lp is not None:
                        lt.set('gerber_lp', gerber_lp)

                
        return




    footprint_path = os.path.join(cfg['base_dir'], 
                                  cfg['pcbmode']['locations']['build'], 
                                  'footprints')


    filename_in = os.path.join(cfg['base_dir'], 
                               cfg['pcbmode']['locations']['parts'], 
                               footprint_name + '.json')
    filename_out = os.path.join(footprint_path, "%s_%s.svg" % (footprint_name, refdef))


    part = utils.get_json_data_from_file(filename_in)

    fp_width = float(part['meta']['svg_width'])
    fp_height = float(part['meta']['svg_height'])

    # create an SVG XML element 
    footprint = et.Element('svg', 
                           width=str(fp_width),
                           height=str(fp_height),
                           version='1.1', 
                           xmlns='http://www.w3.org/2000/svg')
     
    doc = et.ElementTree(footprint)

    # add a definitions tag, where masking definitions are placed
    footprint_defs = et.SubElement(footprint, 'defs', id="footprint_defs")
    footprint_masks = {}
    for pcb_layer in utils.get_surface_layers(cfg):
        footprint_masks[pcb_layer] = et.SubElement(footprint_defs, 
                                                   'mask', 
                                                   id="mask_%s" % pcb_layer)

    # this transform will centre the footprint
    sig_dig = cfg['pcbmode']['significant_digits']
    transform = 'translate(%s %s)' % (round(fp_width/2, sig_dig),
                                      round(fp_height/2, sig_dig))

    # create SVG layer structure for foorprint
    footprint_svg_layers = svg.create_svg_layers(cfg, 
                                                 footprint,
                                                 transform,
                                                 refdef)


    # place the footprint's pads    
    drill_count = place_pads(refdef)

    # place assembly
    if assembly_place is True:
        place_assembly_outline(refdef)
        if 'refdef' in part['layout']['assembly']:
            place_assembly_refdef(refdef)


    # place silkscreen 
    if silkscreen_outline_place is True:
        place_silkscreen_outline(refdef)

    if 'refdef' in part['layout']['silkscreen']:
        if silkscreen_refdef_place is True:
            place_silkscreen_refdef(refdef, 
                                    silkscreen_refdef_location, 
                                    silkscreen_refdef_rotate)


    f = open(filename_out, 'wb')
    f.write(et.tostring(doc, pretty_print = True))
    f.close()


    return doc, fp_width, fp_height, drill_count





def footprint_to_bottom(cfg, footprint):
    """
    Returns a footprint that's mirrored over the Y-axis for bottom layer placement
    """


    def remove_colours(style):
        """
        Removed the colours from 'fill' and 'stroke' from SVG style string
        """
        for attrib in ['fill', 'stroke']:
            regex = r"(\s?%s\s?:#[^;]*;)" % attrib
            style = re.sub(regex, '', style)

        return style


    regex = r"(?P<before>.*?)rotate\s?\(\s?(?P<r>-?[0-9]*\s?)\)(?P<after>.*)"

    svg_layers = [['copper', 'pads'], ['copper', 'routing'], ['soldermask'], ['silkscreen'], ['assembly']]

    for pcb_layer in utils.get_surface_layers(cfg):

        layer = footprint.find(".//g[@inkscape:label='%s']" % pcb_layer, namespaces=cfg['namespace'])

        groups = layer.xpath(".//g[@style]")

        for group in groups:
            style = remove_colours(group.get('style'))
            group.set('style', style)

        for svg_layer in svg_layers:

            # mirror paths
            paths = layer.xpath(".//path[@d]")
            for i, path in enumerate(paths):
                mirrored_path = svg.mirror_path_over_axis(path.get('d'), 'y', 0) 
                path.set('d', mirrored_path)
                transform = path.get('transform')
                capture = re.match(regex, path.get('transform'))
                if capture is not None:
                    path.set('transform', "%srotate(%g)%s" % (capture.group('before'), 
                                                              -float(capture.group('r')),
                                                              capture.group('after')))
            # mirror translates (position)
            transforms = layer.xpath(".//*[@transform]")
            for transform in transforms:
               mirrored_transform = svg.mirror_transform(transform.get('transform'))
               transform.set('transform', mirrored_transform)
            # mirror text coordinates
            texts = layer.xpath(".//text")
            for text in texts:
               text.set('x', str(-float(text.get('x'))))
            # mirror rectangles
            rectangles = layer.xpath(".//rect")
            for rect in rectangles:
                transform = rect.get('transform')
                capture = re.match(regex, transform)
                if capture is not None:
                    rect.set('transform', "%srotate(%g)%s" % (capture.group('before'), 
                                                              180 - float(capture.group('r')),
                                                              capture.group('after')))



    # mirror drills
    drills = footprint.xpath(".//path[@id='%s']" % 'pad_drill')
    for drill in drills:
        mirrored_transform = svg.mirror_transform(drill.get('transform'))
        drill.set('transform', mirrored_transform)          

    # mirror masks
    masks_top = footprint.find("//mask[@id='%s']" % 'mask_top', namespaces=cfg['namespace'])
    masks_bottom = footprint.find("//mask[@id='%s']" % 'mask_bottom', namespaces=cfg['namespace'])
    if masks_top is not None:
        mask_paths = masks_top.xpath(".//path")
        for mask_path in mask_paths:
            mirrored_path = svg.mirror_path_over_axis(mask_path.get('d'), 'y', 0) 
            mask_path.set('d', mirrored_path)
        masks_top.set('id', 'mask_bottom')
    if masks_bottom is not None:
        mask_paths = masks_bottom.xpath(".//path")
        for mask_path in mask_paths:
            mirrored_path = svg.mirror_path_over_axis(mask_path.get('d'), 'y', 0) 
            mask_path.set('d', mirrored_path)
        masks_bottom.set('id', 'mask_top')

    # mirror top/bottom layers and replace ids
    # TODO: clean up this non-elegant code

    pcb_layers = utils.get_surface_layers(cfg)

    layer_top = footprint.find(".//g[@inkscape:label='%s']" % pcb_layers[0], namespaces=cfg['namespace'])
    ids_to_change = layer_top.xpath('.//*[starts-with(@id,"%s")]' % pcb_layers[0])
    for idtc in ids_to_change:
        new_id = re.sub(pcb_layers[0], pcb_layers[1], idtc.get('id'))
        idtc.set('id', new_id)
 
    layer_bot = footprint.find(".//g[@inkscape:label='%s']" % pcb_layers[1], namespaces=cfg['namespace'])
    ids_to_change = layer_bot.xpath('.//*[starts-with(@id,"%s")]' % pcb_layers[1])
    for idtc in ids_to_change:
        new_id = re.sub(pcb_layers[1], pcb_layers[0], idtc.get('id'))
        idtc.set('id', new_id)

    layer_top.set('{'+cfg['namespace']['inkscape']+'}label', pcb_layers[1])
    layer_bot.set('{'+cfg['namespace']['inkscape']+'}label', pcb_layers[0])


    return footprint