PCBmodE / utils / board.py

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



def create_board(cfg):
    """
    Creates the board in SVG format
    """

    def add_layer_index(layers_to_process):
        """
        Adds a layer index to each layer for reference
        """

        def walk_dict_to_find_values_by_key(d, k, exclude=[]):
            """
            Recursively traverses a dictionary to find all values of a given key, 
            returned as a list of *unique* items. Do not add items in the 'exclude'
            list
            """
   
            values = []

            if d is not None:
                for sd in d:
                    try: 
                        values += walk_dict_to_find_values_by_key(d[sd], k)
                    except:
                        value = d[sd].get(k)
                        if value is not None:
                            if (value not in values) and (value not in exclude):
                                values.append(value)
            return values



        def add_index(layer, location, colours, name):
            """
            Adds the reference to the layer
            """

            transform = 'translate(' + str(round(location.x, sig_dig)) + ' ' + str(round(-location.y, sig_dig)) + ')'
            c_ref = et.SubElement(layer, 'g', transform=transform)

            font = cfg['board']['layer_index'].get('font') 
            font_scale = cfg['board']['layer_index'].get('scale')
            font_style = utils.dict_to_style(cfg['layout_style']['documentation'].get('default'))

            x_len = 4.0
            y_len = 2.0

            for i, colour in enumerate(colours):
                x_len_sub = x_len/(len(colours))
                transform = 'translate(' + str(round(i*x_len_sub, sig_dig)) + ' ' + str(0) + ')' 
                style = utils.dict_to_style(cfg['layout_style']['documentation'].get('layer_reference_box'))
                style += 'fill:' + colour + ';'
                path = "m %s,0 0,-%s -%s,0 0,%s z" % (str(x_len_sub), y_len, str(x_len_sub), y_len)
                c_box = et.SubElement(c_ref, 'path', d=path, transform=transform, style=style)
                
            # TODO: a bit of a hack follows; better to calculate the height compensation
            # from font size
            paths, name_width, name_height = glyphs.get_glyphs(cfg,
                                                        name, 
                                                        font, 
                                                        Point(location.x+x_len+0.5, -location.y-1), 
                                                        font_scale)
            
            for path in paths:
                placeloc = utils.to_Point(path['location'])                 
                translate = 'translate(' + str(round(placeloc.x, sig_dig)) + ' ' + str(round(placeloc.y, sig_dig)) + ')'
                transform = translate
                dm = et.SubElement(layer, 'path', 
                                   transform=transform, 
                                   d=path['d'], 
                                   style=font_style,
                                   letter=path['symbol'],
                                   gerber_lp=path['gerber_lp'])



        location = utils.to_Point(cfg['board']['layer_index'].get('location') or [0, 0])
        colours = []
        y_jump = 3

        xpath_expr = "//g[@inkscape:label='%s']//g[@inkscape:label='%s']"

        # TODO: modularise; can't be bothered to do it right now ;)
        for stackup_layer_name in utils.get_surface_layers(cfg):
            colour = cfg['layout_style']['copper']['default'][stackup_layer_name].get('fill')
            colours.append(colour)
            colour = cfg['layout_style']['copper']['default'][stackup_layer_name].get('stroke')
            if (colour not in colours) and (colour != 'none'):
                colours.append(colour)
            colour = cfg['layout_style']['copper']['routing'][stackup_layer_name].get('fill')            
            if (colour not in colours) and (colour != 'none'):
                colours.append(colour)
            colour = cfg['layout_style']['copper']['routing'][stackup_layer_name].get('stroke')            
            if (colour not in colours) and (colour != 'none'):
                colours.append(colour)
            xpath_found = board.xpath(xpath_expr % (stackup_layer_name, 'copper'), 
                                      namespaces={'inkscape':cfg['namespace']['inkscape']}) 
            add_index(xpath_found[0], location, colours, stackup_layer_name+' copper')
            colours = []

            location.y -= y_jump
            colour = cfg['layout_style']['soldermask']['default'][stackup_layer_name].get('fill')
            colours.append(colour)
            colour = cfg['layout_style']['soldermask']['default'][stackup_layer_name].get('stroke')
            if (colour not in colours) and (colour != 'none'):
                colours.append(colour)
            xpath_found = board.xpath(xpath_expr % (stackup_layer_name, 'soldermask'), 
                                      namespaces={'inkscape':cfg['namespace']['inkscape']})
            add_index(xpath_found[0], location, colours, stackup_layer_name+' soldermask')
            colours = []

            location.y -= y_jump
            colour = cfg['layout_style']['silkscreen']['default'][stackup_layer_name].get('fill')
            colours.append(colour)
            colour = cfg['layout_style']['silkscreen']['default'][stackup_layer_name].get('stroke')
            if (colour not in colours) and (colour != 'none'):
                colours.append(colour)
            xpath_found = board.xpath(xpath_expr % (stackup_layer_name, 'silkscreen'), 
                                      namespaces={'inkscape':cfg['namespace']['inkscape']})
            add_index(xpath_found[0], location, colours, stackup_layer_name+' silkscreen')
            colours = []

            location.y -= y_jump
            colour = cfg['layout_style']['assembly']['default'][stackup_layer_name].get('fill')
            colours.append(colour)
            colour = cfg['layout_style']['assembly']['default'][stackup_layer_name].get('stroke')
            if (colour not in colours) and (colour != 'none'):
                colours.append(colour)
            xpath_found = board.xpath(xpath_expr % (stackup_layer_name, 'assembly'), 
                                      namespaces={'inkscape':cfg['namespace']['inkscape']})
            add_index(xpath_found[0], location, colours, stackup_layer_name+' assembly')          
            colours = []

            location.y -= y_jump * 1.5





    def add_drill_index(layer):
        """
        Adds an index of drills, includiing size and number
        """

        location = utils.to_Point(cfg['board']['drill_index'].get('location') or [0, 0])
        scale = cfg['board']['drill_index'].get('scale') or 1
        font = cfg['board']['drill_index'].get('font')
        font_scale = cfg['board']['drill_index'].get('scale')
        font_style = utils.dict_to_style(cfg['layout_style']['documentation'].get('default'))

        buff = 2.0

        drill_total = 0
        for amount in drill_count.values():
            drill_total += amount

        if drill_total == 0:
            text_to_print = 'No drills'
        else:
            text_to_print = '%s drills:' % drill_total

        paths, title_width, title_height = glyphs.get_glyphs(cfg,
                                                             text_to_print, 
                                                             font, 
                                                             Point(location.x, -location.y), 
                                                             font_scale)


        drills_index = et.SubElement(layer, 'g', id='drill_index')

        for path in paths:
            placeloc = utils.to_Point(path['location'])                 
            translate = 'translate(' + str(round(placeloc.x, sig_dig)) + ' ' + str(round(placeloc.y, sig_dig)) + ')'
            transform = translate
            dm = et.SubElement(drills_index, 'path', 
                    transform=transform, 
                    d=path['d'], 
                    style=font_style,
                    letter=path['symbol'],
                    gerber_lp=path['gerber_lp'])


        diameter_text_style = cfg['layout_style']['drills'].get('index')
        diameter_text_style['font-size'] = "0.5px" 
        diameter_text_style = utils.dict_to_style(diameter_text_style)

        count_text_style = cfg['layout_style']['drills'].get('index')
        count_text_style['font-size'] = "2.0px" 
        count_text_style = utils.dict_to_style(count_text_style)

        # get a bit of distance from text
        location.x += title_width + 3

        for diameter in drill_count:
            transform = 'translate(' + str(round(location.x, sig_dig)) + ' ' + str(round(-location.y, sig_dig)) + ')'
            path = svg.drill_diameter_to_path(float(diameter))
            d_index = et.SubElement(drills_index, 'path', d=path, transform=transform)

            # show drill count 
            t = et.SubElement(drills_index, 'text',
                x=str(location.x),
                y=str(-location.y),
                style=count_text_style)
            t.text = str(drill_count[diameter])

            # show diameter
            t = et.SubElement(drills_index, 'text',
                x=str(location.x),
                y=str(-location.y+1),
                style=diameter_text_style)
            t.text = diameter + ' mm'

            # advance in a mildy intelligent manner
            # TODO: for large amounts of drills, this alignment will break; good for now
            advance = max(float(diameter), 5.0)
            location.x += advance



    def add_measurements(layer):
        """
        Adds measurment indicators / arrows to dimensions layer
        """

        def make_arrow(width, arrow_gap):

            # the length of bar that is perpendicular to the point of the arrow
            base_length = 2.0

            # the height of the arrow's head
            arrow_height = 2.0

            # the length of the arrow's base
            arrow_base = 1.8
     
            # path for a horizontal arrow with a centre gap of width 'arrow_gap' 
            path = "m %s,%s %s,%s m %s,%s %s,%s m %s,%s %s,%s m %s,%s %s,%s m %s,%s m %s,%s %s,%s m %s,%s %s,%s m %s,%s %s,%s m %s,%s %s,%s" % (-arrow_gap/2,0, -width/2+arrow_gap/2,0, 0,base_length/2, 0,-base_length, arrow_height,(base_length-arrow_base)/2, -arrow_height,arrow_base/2, arrow_height,arrow_base/2, -arrow_height,-arrow_base/2, width/2,0, arrow_gap/2,0, width/2-arrow_gap/2,0, 0,base_length/2, 0,-base_length, -arrow_height,(base_length-arrow_base)/2, arrow_height,arrow_base/2, -arrow_height,arrow_base/2, arrow_height,-arrow_base/2,) 
            
            return path


        # distance between the edge of the board and the edge of the arrow
        measurement_gap = 2.0

        # amount to rotate height arrows
        height_rotate = 270

        font = cfg['board']['board_outline']['measurements'].get('font')
        font_scale = cfg['board']['board_outline']['measurements'].get('scale')
        font_style = utils.dict_to_style(cfg['layout_style']['documentation'].get('default')) 

        arrow_style = utils.dict_to_style(cfg['layout_style']['dimensions'].get('measurements') or None)

        # place width arrows

        width_paths, measure_width, measure_height = glyphs.get_glyphs(cfg,
                                                                       "%.2f mm" % board_width, 
                                                                       font, 
                                                                       Point(), 
                                                                       font_scale)

        transform = 'translate(' + str(0) + ' ' + str(round(-board_height/2-measurement_gap, sig_dig)) + ')'
        width_arrows = et.SubElement(layer, 'g', transform=transform)
        width_text = et.SubElement(width_arrows, 'g')

        for path in width_paths:
            placeloc = utils.to_Point(path['location'])
            d = path.get('d')
            translate = 'translate(' + str(round(placeloc.x-measure_width/2, sig_dig)) + ' ' + str(round(placeloc.y, sig_dig)) + ')'
            transform = translate
            letter = et.SubElement(width_text, 'path', 
                                   transform=transform, 
                                   d=d, 
                                   style=font_style,
                                   letter=path['symbol'],
                                   gerber_lp=path['gerber_lp'])


        width_arrow_path = make_arrow(board_width, measure_width+3.0) 
        arrow = et.SubElement(width_arrows, 'path', d=width_arrow_path, style=arrow_style)

        # place height arrows

        height_paths, measure_width, measure_height = glyphs.get_glyphs(cfg,
                                                                        "%.2f mm" % board_height, 
                                                                        font, 
                                                                        Point(), 
                                                                        font_scale, 1, height_rotate)



        transform = 'translate(' + str(round(-board_width/2-measurement_gap, sig_dig)) + ' ' + str(0) + ')'
        height_arrows = et.SubElement(layer, 'g', transform=transform)
        height_text = et.SubElement(height_arrows, 'g')

        for path in height_paths:
            placeloc = utils.to_Point(path['location'])
            placeloc.x = -placeloc.x + measure_width/2
            placeloc.y -= measure_height/2
            placeloc.rotate(height_rotate, Point())
            d = path.get('d')             
            translate = 'translate(' + str(round(placeloc.x, sig_dig)) + ' ' + str(round(placeloc.y,sig_dig)) + ')'
            transform = translate
            letter = et.SubElement(height_text, 'path', 
                                   transform=transform, 
                                   d=d, 
                                   style=font_style,
                                   letter=path['symbol'],
                                   gerber_lp=path['gerber_lp'])


               
        height_arrow_path = make_arrow(board_height, measure_width+3.0)
        # rotate the height arrows
        w, h, height_arrow_path = svg.transform_path(height_arrow_path, False, 1, 90)
        arrow = et.SubElement(height_arrows, 'path', d=height_arrow_path, style=arrow_style)    






    def import_footprint(footprint, transform, refdef=None):
        """
        Adds a footprint to the board
        """

        svg_layers = ['drills']
        for svg_layer in svg_layers:
            footprint_pcb_layer = footprint.find(".//g[@inkscape:label='%s']" % svg_layer, namespaces=cfg['namespace'])
            board_pcb_layer = board.find(".//g[@inkscape:label='%s']" % svg_layer, namespaces=cfg['namespace'])
            et.strip_attributes(footprint_pcb_layer, '{'+cfg['namespace']['inkscape']+'}label')
            et.strip_attributes(footprint_pcb_layer, '{'+cfg['namespace']['inkscape']+'}groupmode')
            # set transform
            footprint_pcb_layer.set('transform', transform)
            board_pcb_layer.append(footprint_pcb_layer)

        # import layer content
        for pcb_layer in utils.get_surface_layers(cfg):

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

            # get the board's layer
            board_pcb_layer = board.find(".//g[@inkscape:label='%s']" % pcb_layer, namespaces=cfg['namespace'])
 
            svg_layers = [['copper','pads'], ['copper', 'routing'], 
                          ['soldermask'], ['silkscreen'], ['assembly']]
            for svg_layer in svg_layers:
                footprint_layer = footprint_pcb_layer
                board_layer = board_pcb_layer
                for layer in svg_layer:
                    footprint_layer = footprint_layer.find(".//g[@inkscape:label='%s']" % layer, namespaces=cfg['namespace'])
                    board_layer = board_layer.find(".//g[@inkscape:label='%s']" % layer, namespaces=cfg['namespace'])
                et.strip_attributes(footprint_layer, '{'+cfg['namespace']['inkscape']+'}label')
                et.strip_attributes(footprint_layer, '{'+cfg['namespace']['inkscape']+'}groupmode')

                if len(footprint_layer) > 0: # don't import if empty
                    # set transform
                    footprint_layer.set('transform', transform)
                    board_layer.append(footprint_layer)

        # import masks
        for pcb_layer in utils.get_surface_layers(cfg):
            # skip if there are no pours defined
            if utils.there_are_pours_in_this_layer(cfg, pcb_layer) is True:
                masks = footprint.find(".//defs//mask[@id='mask_%s']" % pcb_layer, namespaces=cfg['namespace'])
                if masks is not None:
                    masks_group = et.SubElement(board_masks[pcb_layer], 'g', transform=transform)
                    for feature in masks:
                        masks_group.append(feature)

        # import cutouts
        cutouts = footprint.find(".//g[@id='%s_%s']" % ('cutouts', refdef), namespaces=cfg['namespace'])
        if cutouts is not None:
            if len(cutouts) != 0:
                board_layer = board.find(".//g[@inkscape:label='%s']" % 'outline', namespaces=cfg['namespace'])
                cutout_group =  et.SubElement(board_layer, 'g', 
                                              id='cutout_%s' % refdef, 
                                              refdef=refdef,
                                              transform=transform)
                for cutout in cutouts:
                    cutout_group.append(cutout)
                                                   

        return





    def place_component(component):

        # get component parameters
        location = utils.to_Point(component.get('location') or [0, 0])
        rotation = component.get('rotation') or 0
        rotation_point = utils.to_Point(component.get('rotation_point') or [0, 0])
        scale = component.get('scale') or 1

        silkscreen_outline_place = True
        silkscreen_refdef_place = True
        assembly_place = True

        # check for silkscreen refdef location override 
        silkscreen_refdef_location = component.get('silkscreen_refdef_location')
        if silkscreen_refdef_location is not None:
            silkscreen_refdef_location = utils.to_Point(silkscreen_refdef_location)

        # check for silkscreen refdef rotation override 
        silkscreen_refdef_rotate = component.get('silkscreen_refdef_rotate') or 0

        # determine if to place silkscreen outline and/or refdef
        if component.get('place_silkscreen') in ['no']:
            silkscreen_outline_place = False
            silkscreen_refdef_place = False
        else:
            if component.get('place_silkscreen_outline') in ['no']:
                silkscreen_outline_place = False
            if component.get('place_silkscreen_refdef') in ['no']:
                silkscreen_refdef_place = False

        if component.get('place_assembly') in ['no']:
            assembly_place = False

        
        # get the name of the footprint
        footprint_name = component.get('footprint')

        print component_refdef + '(' + footprint_name + ')',

        # save footprint file
        # strictly, this is not necessary because these files are not going
        # to be used. However, it's good for debug.
        footprint_path = os.path.join(cfg['base_dir'], 
                                      cfg['pcbmode']['locations']['build'], 
                                      'footprints')
        utils.create_dir(footprint_path)

       
        # create a footprint
        footprint_instance, fp_width, fp_height, fp_drill_count = footprint.create_footprint(
                                                              cfg,
                                                              footprint_name,
                                                              component_refdef,
                                                              rotation,
                                                              rotation_point,
                                                              scale,
                                                              silkscreen_outline_place,
                                                              silkscreen_refdef_place,
                                                              assembly_place,
                                                              silkscreen_refdef_location,
                                                              silkscreen_refdef_rotate
                                                              )


        # mirror footprint for bottom layer?
        if pcb_layer.lower() == 'bottom':
            footprint_instance = footprint.footprint_to_bottom(cfg, footprint_instance)

        # rotate location if there's a rotation point defined, and is not [0, 0]
        if rotation_point != Point():
            tmp = rotation_point
            tmp.rotate(rotation, Point())
            location -= tmp
    
        translate = str(round(location.x, sig_dig))+' '+str(round(-location.y, sig_dig))
        transform = 'translate('+translate+')'

        import_footprint(footprint_instance, transform, component_refdef)

        return fp_drill_count




    drill_count = {}

    # get the board's shape / outline
    board_shape_gerber_lp = None
    shape = cfg['board']['board_outline']['shape']
    board_shape_type = shape.get('type')

    if board_shape_type in ['rect', 'rectangle']:
        offset = utils.to_Point(shape.get('offset') or [0, 0])
        board_shape_path = svg.rect_to_path(shape)

    elif board_shape_type == 'path':
        board_shape_path = shape.get('value')
        board_shape_gerber_lp = shape.get('gerber_lp')
        if board_shape_path is None:
            print "ERROR: couldn't find a path under key 'value' for board outline"

    else:
        print "ERROR: unrecognised board shape type: %s. Possible options are 'rect' or 'path'" % board_shape_type

    # convert path to relative
    board_shape_path_relative = svg.absolute_to_relative_path(board_shape_path)

    # this will return a path having an origin at the center of the shape
    # defined by the path
    board_width, board_height, board_outline = svg.transform_path(board_shape_path_relative, True)

    display_width = board_width
    display_height = board_height

    #transform = 'translate(' + str(round((board_width)/2, SD)) + ' ' + str(round((board_height)/2, SD)) + ')'
    sig_dig = cfg['pcbmode']['significant_digits']
    transform = 'translate(%s %s)' % (round(board_width/2, sig_dig),
                                      round(board_height/2, sig_dig))


    # extra buffer for display frame
    display_frame_buffer = cfg['pcbmode'].get('display_frame_buffer') or 1.0

    board = et.Element('svg',
        width=str(display_width) + cfg['board']['meta']['unit_length_si'],
        height=str(display_height) + cfg['board']['meta']['unit_length_si'],
        viewBox=str(-display_frame_buffer/2) + ' ' + str(-display_frame_buffer/2) + ' ' + str(board_width+display_frame_buffer) + ' ' + str(board_height + display_frame_buffer),
        version='1.1',
        nsmap=cfg['namespace'],
        fill='black')

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


    welcome_message = """
Hello! This SVG file was generated using PCBmodE version %s on %s GMT; 
please visit http://boldport.blogspot.co.uk for latest information.
""" % (cfg['pcbmode']['version'], datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) 
    board.append(et.Comment(welcome_message))

    #==========================================================================
    # instantiate top layers
    # the order of the instantiation matters. The first instantiated layer will 
    # appear to be the bottom one in Inkscape
    #==========================================================================
 
    doc = et.ElementTree(board)

    board_svg_layers = svg.create_svg_layers(cfg, board, transform)

    # TODO: add support for internal layers

    # add outline to dimensions layer
    outline_element = et.SubElement(board_svg_layers['dimensions']['outline']['layer'], 
                                    'path',
                                    id="board_outline",
                                    d=board_outline)
    if board_shape_gerber_lp is not None:
        outline_element.set("gerber_lp", board_shape_gerber_lp)
    

    # add origin marker to outline layer
    origin = et.SubElement(board_svg_layers['dimensions']['measurements']['layer'], 'path',
                           id="origin_marker",
                           d="m -0.5,0 1,0 m -0.5,0.5 0,-1")

    mirror_footprint = False

    xpath_expr = "//g[@inkscape:label='%s']//g[@inkscape:label='%s']"

    # get components by PCB layer
    pcb_components = {}
    for pcb_layer in utils.get_surface_layers(cfg):
        pcb_components[pcb_layer] = cfg['board']['placement']['components'][pcb_layer]


    print "-- processing parts:",

    for pcb_layer in utils.get_surface_layers(cfg):
        for component_refdef in pcb_components[pcb_layer]:
            component = pcb_components[pcb_layer][component_refdef]
            fp_drill_count = place_component(component)
            # add the count to the total
            drill_count = utils.add_dict_values(drill_count,
                                                fp_drill_count)

    print


    drills = cfg['board'].get('drills')
    if drills is not None and drills != {}:
        print "-- processing drills:",
        for pcb_layer in utils.get_surface_layers(cfg):
            for drill_refdef in drills[pcb_layer]:
                component_refdef = drill_refdef
                fp_drill_count = place_component(drills[pcb_layer][drill_refdef])
                # add the count to the total
                drill_count = utils.add_dict_values(drill_count,
                                                    fp_drill_count)

    print


    print "-- adding routing"
    filename = os.path.join(cfg['base_dir'],
                            cfg['board']['files'].get('routing_json') or cfg['board_name'] + '_routing.json')
    routing = utils.get_json_data_from_file(filename)

    # add routing to copper layers
    if routing is not None:

        routes = routing.get('routes')
        vias = routing.get('vias') 
        path_effects = routes.get('path_effects')

        xpath_expr = "//g[@inkscape:label='%s']//g[@inkscape:label='%s']"

        extra_attributes = ['inkscape:connector-curvature', 'inkscape:original-d', 'inkscape:path-effect']

        for pcb_layer in utils.get_surface_layers(cfg):

            there_are_pours = utils.there_are_pours_in_this_layer(cfg, pcb_layer)

            routing_mask_group = et.SubElement(board_masks[pcb_layer], 'g',
                                               id="routing_masks")
            sheet = board_svg_layers[pcb_layer]['copper']['routing']['layer']
            for route in routes[pcb_layer]:
                path = routes[pcb_layer][route].get('d')
                gerber_lp = routes[pcb_layer][route].get('gerber_lp')
                path_style = routes[pcb_layer][route].get('style') or 'stroke:none;'
                path_type = routes[pcb_layer][route].get('type')
                pcbmode_params = routes[pcb_layer][route].get('pcbmode')

                # add shape to copper plane 
                path_element = et.SubElement(sheet, 'path', d=path)
                if path_style is not None:
                    path_element.set('style', path_style)
                if gerber_lp is not None:
                    path_element.set('gerber_lp', gerber_lp)

                # add extra attributes if they exist
                for extra_attrib in extra_attributes:
                    ea = routes[pcb_layer][route].get(extra_attrib)
                    if ea is not None:
                        path_element.set('{'+cfg['namespace']['inkscape']+'}%s' % extra_attrib[extra_attrib.index(':')+1:], ea)

                if path_type is not None:
                    path_element.set('type', path_type)

                if pcbmode_params is not None:
                    path_element.set('pcbmode', pcbmode_params)                

                pour_buffer = 0.5
                try:
                    pour_buffer = cfg['board']['distances']['buffer_from_pour_to'].get('route') or 0.5
                except:
                    pass

                mask_style_template = "fill:%s;stroke:#000;stroke-linejoin:round;stroke-width:%s;"

                regex = r".*?%s:\s?(?P<s>[^;]*)(?:;|$)"
                stroke_def = re.match(regex % 'stroke', path_style)
                if stroke_def is not None:
                    stroke = stroke_def.group('s')

                stroke_width_def = re.match(regex % 'stroke-width', path_style)    
                if stroke_width_def is not None:
                    stroke_width = float(stroke_width_def.group('s'))
                else:
                    stroke_width = 0

                if stroke_width > 0:
                    fill = 'none'
                else:
                    fill = re.match(regex % 'fill', path_style)
                    if fill is not None:
                        fill = fill.group('s')

                # place mask
                if path_type not in ['pour_bridge'] and there_are_pours:
                    mask_element = et.SubElement(routing_mask_group, 'path',
                                                 #id="%s" % pcb_layer,
                                                 type="mask_shape",
                                                 style=mask_style_template % (fill, stroke_width + pour_buffer * 2),
                                                 d=path)
     
                    # set 'gerber_lp' attribute is it's not empty
                    if gerber_lp is not None:
                        path_element.set('gerber_lp', gerber_lp)
                        mask_element.set('gerber_lp', gerber_lp)
     
                    # Due to the limitation of the Gerber format, and the method chosen
                    # for applying masks onto pours, it is not possible to have copper
                    # pour material inside of paths that have more than a single segment.
                    # In order to make the apperance in the SVG and Gerbers consistent, 
                    # each path segment is added with a 'fill'. In the future, when the
                    # *actual* shape is calculated, it may be possible to avoid this
                    # hack. On the other hand, one can argue that having pours inside of
                    # shapes doesn't make sense anyway, because it alters its apperance, 
                    # and such shapes are stylistic anyway. OK, back to code now...
                    if gerber_lp is not None:
                        if len(gerber_lp) > 1:
                            path_segments = path.split('m')
                            for path_segment in path_segments[1:]:
                                mask_element = et.SubElement(routing_mask_group, 'path',
                                                             #id="%s" % pcb_layer,
                                                             type="mask_shape",
                                                             style="fill:#000;stroke:none;",
                                                             d='m '+path_segment)

        for via in vias.values():
            
            via_type = via.get('via_type')
            # check if via is specified, or 'default' is specified:
            via_part_name = via_type[len(cfg['via_prefix']):]
            via_part_name = via_part_name.strip(' ') # remove leading spaces if there any

            # save footprint file
            # strictly, this is not necessary because these files are not going
            # to be used. However, it's good for debug.
            footprint_path = os.path.join(cfg['base_dir'], cfg['pcbmode']['locations']['build'], 'footprints')
          
            # check if footprint directory exists; if not, create
            try:
                # try to create directory first; this prevents TOCTTOU-type race condition
                os.makedirs(footprint_path)
            except OSError:
                # if the dir exists, pass
                if os.path.isdir(footprint_path):
                    pass
                else:
                    raise
           
            filename_in = os.path.join(cfg['base_dir'], 
                                       cfg['pcbmode']['locations']['parts'], 
                                       via_part_name + '.json')
            filename_out = os.path.join(footprint_path, 
                                        via_part_name + '.svg')

            # create via footprint
            via_footprint, fp_width, fp_height, fp_drills = footprint.create_footprint(cfg,
                                                                                       via_part_name,
                                                                                       via_type, 
                                                                                       0, 
                                                                                       Point, 
                                                                                       1)

            drill_count = utils.add_dict_values(drill_count, fp_drills)

            location = utils.to_Point(via.get('location') or [0, 0])
            translate = str(round(location.x, sig_dig))+' '+str(round(-location.y, sig_dig))
            transform = 'translate('+translate+')'
            import_footprint(via_footprint, transform)



        # add path-effect paths to <defs>
        if path_effects is not None:
            for path_effect in path_effects.values():
                effect_element = et.SubElement(board_defs, '{'+cfg['namespace']['inkscape']+'}path-effect')
                for name, value in path_effect.items():
                    effect_element.set(name, value)



    # add additional shapes
    xpath_expr = "//g[@inkscape:label='%s']//g[@inkscape:label='%s']"

    print "-- adding additional shapes to board"

    mirror = False

    existing_glyphs = {}

    # create layers for top and bottom PCB layers
    for stackup_layer_name in utils.get_surface_layers(cfg):
     
        if stackup_layer_name == 'bottom':
            mirror = True
        else:
            mirror = False

        shapes = cfg['board']['additional_shapes']

        if shapes.get('copper') is not None:
            copper_shapes = shapes['copper'].get(stackup_layer_name) or []
        else:
            copper_shapes = []

        if shapes.get('soldermask') is not None:
            soldermask_shapes = shapes['soldermask'].get(stackup_layer_name) or []
        else:
            soldermask_shapes = []

        if shapes.get('silkscreen') is not None:
            silkscreen_shapes = shapes['silkscreen'].get(stackup_layer_name) or []
        else:
            silkscreen_shapes = []
     
        
        sheet = board_svg_layers[stackup_layer_name]['soldermask']['layer']
        for shape in soldermask_shapes:
            shape_type = shape.get('type')

            # for 'rect' first convert to path
            if shape_type in ['rect', 'rectangle']:
               shape['value'] = svg.rect_to_path(shape)
               shape['type'] = 'path'
               shape_type = 'path'

            # for 'circle' first convert to path
            if shape_type in ['circ', 'circle', 'round']:
               shape['value'] = svg.circle_diameter_to_path(shape['diameter'])
               shape['type'] = 'path'
               shape_type = 'path'

            if shape_type.lower() == 'path':
                place.place_path_shape(cfg, shape, sheet, 'soldermask', mirror)
            elif shape_type.lower() == 'text':
                place.place_text(cfg, shape, sheet, 'soldermask', mirror)
            else:
                print "ERROR: while processing 'addition_shapes', a shape type was not recognised"    


        sheet = board_svg_layers[stackup_layer_name]['silkscreen']['layer']
        for shape in silkscreen_shapes:
            shape_type = shape.get('type')

            # for 'rect' first convert to path
            if shape_type in ['rect', 'rectangle']:
               shape['value'] = svg.rect_to_path(shape)
               shape['type'] = 'path'
               shape_type = 'path'

            # for 'circle' first convert to path
            if shape_type in ['circ', 'circle', 'round']:
               shape['value'] = svg.circle_diameter_to_path(shape['diameter'])
               shape['type'] = 'path'
               shape_type = 'path'

            if shape_type.lower() == 'path':
                place.place_path_shape(cfg, shape, sheet, 'silkscreen', mirror)
            elif shape_type.lower() == 'text':
                place.place_text(cfg, shape, sheet, 'silkscreen', mirror)
            else:
                print "ERROR: while processing 'addition_shapes', a shape type was not recognised"
     

        sheet = board_svg_layers[stackup_layer_name]['copper']['layer']
        for shape in copper_shapes:
            shape_type = shape.get('type')

            # for 'rect' first convert to path
            if shape_type in ['rect', 'rectangle']:
               shape['value'] = svg.rect_to_path(shape)
               shape['type'] = 'path'
               shape_type = 'path'

            # for 'circle' first convert to path
            if shape_type in ['circ', 'circle', 'round']:
               shape['value'] = svg.circle_diameter_to_path(shape['diameter'])
               shape['type'] = 'path'
               shape_type = 'path'

            if shape_type.lower() == 'path':
                place.place_path_shape(cfg, shape, sheet, 'copper', mirror)
            elif shape_type.lower() == 'text':
                place.place_text(cfg, shape, sheet, 'copper', mirror)
            else:
                print "ERROR: while processing 'addition_shapes', a shape type was not recognised"




    # add copper pours; this adds the pour shapes to a 'mask' group
    try:
        pours = cfg['board']['additional_shapes'].get('pours') or {}
    except:
        pass

    gerber_lp = None

    for pcb_layer in utils.get_surface_layers(cfg):
        pours_layer = board_svg_layers[pcb_layer]['copper']['pours']['layer']
        pour_mask_group = et.SubElement(board_masks[pcb_layer], 'g',
                                        id="pour_masks")

        mask_group = et.SubElement(pours_layer, 'g',
                                   mask='url(#mask_%s)' % pcb_layer)

        for pour in pours.get(pcb_layer) or []:
            pour_type = pour.get('type')

            if pour_type.lower() in ['board_outline', 'outline', 'layer']:

                pour_path = et.SubElement(mask_group, 'path',
                                          id="copper_pour",
                                          style="fill-rule:evenodd;",
                                          d=board_outline)

                if board_shape_gerber_lp is not None:
                    pour_path.set('gerber_lp', board_shape_gerber_lp)

            elif pour_type.lower() in ['rect', 'rectangle']:
                location = utils.to_Point(pour.get('location'))
                pour_path = svg.width_and_height_to_path(pour.get('width'), 
                                                         pour.get('height'), 
                                                         pour.get('radii'))
                transform = 'translate(%f %f)' % (location.x, -location.y)
                pour_path = et.SubElement(mask_group, 'path',
                                          id="copper_pour",
                                          transform=transform,
                                          d=pour_path)

            elif pour_type.lower() == 'path':
                location = utils.to_Point(pour.get('location'))
                pour_path = svg.absolute_to_relative_path(pour.get('value'))
                transform = 'translate(%f %f)' % (location.x, -location.y)
                gerber_lp = pour.get('gerber_lp')
                pour_path = et.SubElement(mask_group, 'path',
                                          id="copper_pour",
                                          transform=transform,
                                          d=pour_path)        

                if gerber_lp is not None:
                    pour_path.set('gerber_lp', gerber_lp)

                    

            else:
                print "ERROR: copper pour type %s is unrecognised" % pour_type


        pour_buffer = 0.5
        try:
            pour_buffer = cfg['board']['distances']['buffer_from_pour_to'].get('board_outline') or 0.5
        except:
            pass


        if utils.there_are_pours_in_this_layer(cfg, pcb_layer) is True:
            # add a mask buffer between pour and board outline; this will cut out
            # any paths that go beyond the board's outline
            pour_mask = et.SubElement(pour_mask_group, 'path',
                                     #id="%s" % pcb_layer,
                                     type="mask_shape",
                                     style="fill:none;stroke:#000;stroke-linejoin:round;stroke-width:%s;" % str(pour_buffer*2),
                                     d=board_outline)
     
            if board_shape_gerber_lp is not None:
                pour_mask.set("gerber_lp", board_shape_gerber_lp)



    # add documentation
    documentation = cfg['board'].get('documentation') or None
    style = utils.dict_to_style(cfg['layout_style']['documentation'].get('default'))

    if documentation is not None:

        for text_block in documentation:
            block = documentation[text_block]
            block_font = block.get('font')
            block_font_scale = block.get('scale')
            block_title_font_scale = block.get('title_scale') or doc_font_scale
     
            location = utils.to_Point(block.get('location') or [0, 0])
            title = block.get('title') or None
            lines = block.get('text_lines') or []
     
            line_number = 1
     
            if title is not None:
                paths, title_width, title_height = glyphs.get_glyphs(cfg,
                                                                     title, 
                                                                     block_font, 
                                                                     location, 
                                                                     block_title_font_scale, 
                                                                     line_number)
                for path in paths:
                    placeloc = utils.to_Point(path['location'])
                    translate = 'translate(' + str(round(placeloc.x, sig_dig)) + ' ' + str(round(-placeloc.y, sig_dig)) + ')'
                    transform = translate
                    dm = et.SubElement(board_svg_layers['documentation']['layer'], 'path', 
                            transform=transform, 
                            d=path['d'], 
                            style=style,
                            letter=path['symbol'],
                            gerber_lp=path['gerber_lp'])
     
                line_number += 1
                
            for line in lines:
                key = line.keys()
                value = line[key[0]]
 
                message = key[0] + ' ' + value 

                paths, message_width, message_height = glyphs.get_glyphs(cfg,
                                                                         message, 
                                                                         block_font, 
                                                                         location, 
                                                                         block_font_scale, 
                                                                         line_number)
                
                for path in paths:
                    placeloc = utils.to_Point(path['location'])
                    translate = 'translate(' + str(round(placeloc.x, sig_dig)) + ' ' + str(round(-placeloc.y, sig_dig)) + ')'
                    transform = translate
                                    
                    dm = et.SubElement(board_svg_layers['documentation']['layer'], 'path', 
                                       transform=transform, 
                                       d=path['d'], 
                                       style=style,
                                       letter=path['symbol'],
                                       gerber_lp=path['gerber_lp'])
     
                line_number += 1


    # add layer index for the specified layers
    if cfg['board'].get('no_layer_index') is False:
        if cfg['board'].get('layer_index') is not None:
            add_layer_index(['copper', 'soldermask', 'silkscreen'])

    # add drill index
    if cfg['board'].get('drill_index') is not None:
        add_drill_index(board_svg_layers['drills']['layer'])

    add_measurements(board_svg_layers['dimensions']['measurements']['layer'])    


    # NOTE: the 'cover' MUST be the last element in the mask definition;
    # that's why it is added here. If it it not the last, every mask element
    # after it won't show
    for pcb_layer in utils.get_surface_layers(cfg):
        if utils.there_are_pours_in_this_layer(cfg, pcb_layer) is True:
            mask_cover = et.SubElement(board_masks[pcb_layer], 'rect',
                                       id="mask_cover", # use this id for NOT gerberising the cover
                                       x="%s" % str(-board_width/2), 
                                       y="%s" % str(-board_height/2),
                                       width="%s" % board_width,
                                       height="%s" % board_height,
                                       style="fill:#fff;")


    output_file = os.path.join(cfg['base_dir'], cfg['pcbmode']['locations']['build'], cfg['board_name'] + '.svg')

    try:
        f = open(output_file, 'wb')
    except IOError as e:
        print "I/O error({0}): {1}".format(e.errno, e.strerror)

    f.write(et.tostring(doc, pretty_print=True))
    f.close()


    return
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.