-
Notifications
You must be signed in to change notification settings - Fork 1
/
BuildPCB.py
686 lines (548 loc) · 22.2 KB
/
BuildPCB.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
import bpy
import csv
import sys
import os
from mathutils import Vector, Matrix, Quaternion
import time
# Useful colours
# Finishes
hasl = (0.6, 0.6, 0.6, 1.0)
enig = (0.865, 0.524, 0.0, 1.0)
# Silk colours
white = (1.0, 1.0, 1.0, 1.0)
black = (0.0, 0.0, 0.0, 1.0)
# Mask colours
red = (0.347, 0.000, 0.022, 1.0)
green = (0.0, 0.25, 0.0, 1.0)
blue = (0.0, 0.195, 0.828, 1.0)
purple = (0.174, 0.0, 0.574, 1.0)
yellow = (0.814, 0.429, 0.0, 1.0)
# black - use silk colour
# white - use silk colour
class PCBImport(bpy.types.Operator):
# Location where all your converted files are stored
file_root = "/home/matt/Dropbox/Projects/SoundStick/Render/"
# Base name of the files
file_name = "SoundStick"
# Colour you want for the mask: blue, red, green, purple, black, white, yellow
color = black
# Finish for the board: hasl, enig
finish = hasl
# Silk screen colour: black, white
silk = white
# Lower left coordinate of the board in PCB
page_height = 127
board_top = 68
board_bottom = 94
offset_x = 39
offset_y = (board_bottom - (board_top - (page_height-board_bottom)))
# Location where all the component library files are stored
component_root = "/home/matt/Dropbox/gEDA/Models/components"
# Whether or not to join everything into one single object
doJoin = False
# List of manual rotations in the form of {"refdes": angle, "refdes": angle...}
rotations = {
"U105": 90,
"Q101": 90,
"Q102": 90,
}
dnp = {
"PAD101": 1,
"PAD102": 1,
"PAD103": 1,
"PAD104": 1,
"PAD105": 1,
"PAD106": 1,
"PAD107": 1,
"PAD108": 1,
"PAD109": 1,
"PAD111": 1,
"PAD112": 1,
"PAD113": 1,
"PAD114": 1,
"PAD115": 1,
"PAD116": 1,
"PAD117": 1,
"PAD118": 1,
"PAD119": 1,
"PAD120": 1,
"PAD121": 1,
"PAD122": 1,
"PAD124": 1,
"PAD125": 1,
"TP101": 1,
"TP102": 1,
"TP103": 1,
"TP104": 1,
"TP105": 1,
}
bl_label = "Import gEDA PCB Models"
bl_idname = "wm.modal_timer_operator"
bl_options = {'BLOCKING'}
file_outline = file_root + file_name + ".outline.svg"
file_drill = file_root + file_name + ".plated-drill.cnc"
file_csv = file_root + file_name + ".xy"
txt = None
outlineCurve = None
pcb = None
objects = None
def NormalInDirection(self, normal, direction, limit = 0.5 ):
return direction.dot( normal ) > limit
def GoingUp(self, normal, limit = 0.5 ):
return self.NormalInDirection( normal, Vector( (0, 0, 1 ) ), limit )
def GoingDown(self, normal, limit = 0.5 ):
return self.NormalInDirection( normal, Vector( (0, 0, -1 ) ), limit )
def GoingLeft(self, normal, limit = 0.5 ):
return self.NormalInDirection( normal, Vector( (-1, 0, 0) ), limit)
def GoingRight(self, normal, limit = 0.5 ):
return self.NormalInDirection( normal, Vector( (1, 0, 0) ), limit)
def GoingFore(self, normal, limit = 0.5 ):
return self.NormalInDirection( normal, Vector( (0, 1, 0) ), limit)
def GoingBack(self, normal, limit = 0.5 ):
return self.NormalInDirection( normal, Vector( (0, -1, 0) ), limit)
def GoingSide(self, normal, limit = 0.5 ):
return self.GoingUp( normal, limit ) == False and self.GoingDown( normal, limit ) == False
def setViewOrientation(self,vec, angle = 0):
for win in bpy.data.window_managers[0].windows:
for a in win.screen.areas:
if (a.type == "VIEW_3D"):
for s in a.spaces:
if (s.type == "VIEW_3D"):
view = s
s.region_3d.view_rotation = Quaternion(vec, angle)
def projectFromView(self):
print("Project from view")
for oWindow in bpy.context.window_manager.windows:
oScreen = oWindow.screen
for oArea in oScreen.areas:
print ("Area type: " + oArea.type)
if oArea.type == 'VIEW_3D':
for oRegion in oArea.regions:
if oRegion.type == 'WINDOW':
self.setMode('EDIT')
override = {'window': oWindow, 'screen': oScreen, 'area': oArea, 'region': oRegion, 'scene': bpy.context.scene, 'edit_object': bpy.context.edit_object, 'active_object': bpy.context.active_object, 'selected_objects': bpy.context.selected_objects}
bpy.ops.uv.project_from_view(override , camera_bounds=False, correct_aspect=False, scale_to_bounds=True)
def clearMeshSelections(self):
self.setMode('EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
self.setMode('OBJECT')
def meshSelectAll(self):
self.setMode('EDIT')
bpy.ops.mesh.select_all(action='SELECT')
self.setMode('OBJECT')
def setMode(self, newmode):
bpy.ops.object.mode_set(mode=newmode, toggle=False)
def deselectAll(self):
bpy.ops.object.select_all(action='DESELECT')
def selectAll(self):
bpy.ops.object.select_all(action='SELECT')
def openBuildReport(self):
self.txt = bpy.data.texts.get("BuildReport.txt")
if not self.txt:
self.txt = bpy.data.texts.new("BuildReport.txt")
self.txt.clear()
def deleteExistingBoard(self):
self.deselectAll()
for ob in bpy.data.objects:
if ob.name == self.file_name:
self.setSelect(ob, True)
bpy.ops.object.delete()
self.deselectAll()
def deleteOrphans(self):
self.deselectAll()
for m in bpy.data.materials:
if (m.users == 0):
bpy.data.materials.remove(m)
for m in bpy.data.meshes:
if (m.users == 0):
bpy.data.meshes.remove(m)
for m in bpy.data.images:
if (m.users == 0):
bpy.data.images.remove(m)
def vabs(self, v):
return (abs(v[0]), abs(v[1]), abs(v[2]))
############################
# Version abstraction routines
def version(self):
return bpy.app.version[0] + (bpy.app.version[1]/100)
def setSelect(self, object, state):
if self.version() < 2.80:
object.select = state
else:
object.select_set(state)
def getSelect(self, object):
if self.version() < 2.80:
return object.select
else:
return object.select_get()
def setActiveObject(self, object):
if self.version() < 2.80:
bpy.context.scene.objects.active = object
else:
bpy.context.view_layer.objects.active = object
def linkObject(self, object):
if self.version() < 2.80:
bpy.context.scene.objects.link(object)
else:
bpy.context.scene.collection.objects.link(object)
#
#########################################
def matchingVertices(self, f1, f2):
count = 0
for v1 in f1.vertices:
for v2 in f2.vertices:
if v1 == v2:
count += 1
return count
def selectOuterFaces(self, object):
faces = object.data.polygons
for f in faces:
f.select = False
sideFaces = [f for f in faces if self.GoingSide(f.normal)]
maxObject = None
maxArea = 0
linkedFaces = []
for f in sideFaces:
if (len(f.vertices) == 4):
if f.area > maxArea:
maxArea = f.area
maxObject = f
sideFaces.remove(maxObject)
linkedFaces.append(maxObject)
while True:
print("-----------------------------------")
foundsome = False
foundFaces = []
for testface in linkedFaces:
for face in sideFaces:
if len(face.vertices) == 4:
mv = self.matchingVertices(testface, face)
if (mv == 2):
print("(" + str(testface.vertices[0]) + ", " + str(testface.vertices[1]) + ", " + str(testface.vertices[2]) + ", " + str(testface.vertices[3]) + ")")
print("(" + str(face.vertices[0]) + ", " + str(face.vertices[1]) + ", " + str(face.vertices[2]) + ", " + str(face.vertices[3]) + ")")
print(mv)
print("")
if face not in foundFaces:
foundFaces.append(face)
foundsome = True
for face in foundFaces:
sideFaces.remove(face)
linkedFaces.append(face)
if not foundsome:
break
for f in linkedFaces:
f.select = True
def importOutline(self):
self.selectAll()
bpy.ops.import_curve.svg(filepath = self.file_outline)
outline = [c for c in bpy.context.scene.objects if not self.getSelect(c)]
self.deselectAll()
self.outlineCurve = outline[0]
self.outlineCurve.location = [self.offset_x, self.offset_y, -0.8]
def drillBoard(self):
drillsDone = []
self.selectAll()
with open(self.file_drill, newline='', encoding='ISO-8859-15') as f:
content = f.read().splitlines()
drills = {}
inHeader = True
drillWidth = 0
bits = []
holes = []
nbits = 0
for line in content:
if line == '%':
inHeader = False
continue
if inHeader:
if line.startswith('T'):
parts = line.split('C')
drills[parts[0]] = float(parts[1])
else:
if line.startswith('T'):
drillWidth = drills[line]
continue
if line.startswith('X'):
nbits = nbits + 1
coords = line[1:].split('Y')
x = float(coords[0])
y = float(coords[1])
x = x / 1000
y = y / 1000
pos = Vector((x, y, 0))
if (pos not in drillsDone):
drillsDone.append(pos)
bpy.ops.curve.primitive_bezier_circle_add(radius = drillWidth / 2, location = (x, y, -0.8))
holes.append(bpy.context.active_object);
self.deselectAll()
for c in holes:
self.setSelect(c, True)
self.setSelect(self.outlineCurve, True)
self.setActiveObject(self.outlineCurve)
bpy.ops.object.join()
def extrudeBoard(self):
self.outlineCurve.data.extrude = 0.8
self.outlineCurve.data.dimensions = "2D"
self.outlineCurve.data.fill_mode = 'BOTH'
bpy.ops.object.convert(target='MESH')
self.meshSelectAll()
self.setMode('EDIT')
bpy.ops.mesh.remove_doubles(threshold = 0.01)
self.setMode('OBJECT')
self.pcb = bpy.context.object
self.pcb.name = 'PCB'
def loadMaterials(self):
with bpy.data.libraries.load(self.component_root + "/materials.blend", link=True) as (data_from, data_to):
data_to.materials = ["Metal", "PCB Texture", "PCB Substrate"]
top = None
try:
top = bpy.data.materials['PCB Top']
except:
top = bpy.data.materials['PCB Texture'].copy();
top.name = "PCB Top"
btm = None
try:
btm = bpy.data.materials['PCB Bottom']
except:
btm = bpy.data.materials['PCB Texture'].copy();
btm.name = "PCB Bottom"
top.node_tree.nodes['copper'].image = bpy.data.images.load(filepath = self.file_root + "/" + self.file_name + ".top.png")
top.node_tree.nodes['soldermask'].image = bpy.data.images.load(filepath = self.file_root + "/" + self.file_name + ".topmask.png")
top.node_tree.nodes['silk'].image = bpy.data.images.load(filepath = self.file_root + "/" + self.file_name + ".topsilk-cropped.png")
top.node_tree.nodes['pcbtexture'].inputs['Color'].default_value = self.color
top.node_tree.nodes['pcbtexture'].inputs['Finish'].default_value = self.finish
top.node_tree.nodes['pcbtexture'].inputs['Silk Color'].default_value = self.silk
top.node_tree.nodes['mapping'].scale = (0.996, 0.996, 1)
top.node_tree.nodes['mapping'].translation = (0, 0.0055, 0)
btm.node_tree.nodes['copper'].image = bpy.data.images.load(filepath = self.file_root + "/" + self.file_name + ".bottom.png")
btm.node_tree.nodes['soldermask'].image = bpy.data.images.load(filepath = self.file_root + "/" + self.file_name + ".bottommask.png")
btm.node_tree.nodes['silk'].image = bpy.data.images.load(filepath = self.file_root + "/" + self.file_name + ".bottomsilk-cropped.png")
btm.node_tree.nodes['pcbtexture'].inputs['Color'].default_value = self.color
btm.node_tree.nodes['pcbtexture'].inputs['Finish'].default_value = self.finish
btm.node_tree.nodes['pcbtexture'].inputs['Silk Color'].default_value = self.silk
btm.node_tree.nodes['mapping'].scale = (0.996, -0.996, 1)
btm.node_tree.nodes['mapping'].translation = (0, 0-.0002, 0)
self.pcb.data.materials.append(bpy.data.materials['Metal'])
self.pcb.data.materials.append(top)
self.pcb.data.materials.append(btm)
self.pcb.data.materials.append(bpy.data.materials['PCB Substrate'])
bpy.data.materials.remove(bpy.data.materials['SVGMat'])
def facesTouching(self, one, two):
return False
def faceArea(self, f):
return f.area
def assignMaterials(self):
# Metal
self.clearMeshSelections()
self.setMode('OBJECT')
for face in self.pcb.data.polygons:
face.select = self.GoingSide(face.normal)
self.pcb.active_material_index = 0
self.setMode('EDIT')
bpy.ops.object.material_slot_assign()
self.setMode('OBJECT')
## PCBTop
self.clearMeshSelections()
for face in self.pcb.data.polygons:
face.select = self.GoingUp(face.normal)
self.pcb.active_material_index = 1
self.setMode('EDIT')
bpy.ops.object.material_slot_assign()
self.setMode('OBJECT')
# PCBBottom
self.clearMeshSelections()
for face in self.pcb.data.polygons:
face.select = self.GoingDown(face.normal)
self.pcb.active_material_index = 2
self.setMode('EDIT')
bpy.ops.object.material_slot_assign()
self.setMode('OBJECT')
# PCB Substrate
# This one is a little harder. First
# select all the side faces.
# Second work out which is the biggest -
# that's guaranteed to be an outside face.
# Then repeatedly look through all the side
# faces finding any that touch that first one.
# Add them to an array, then repeat looking
# for any faces that touch any in the array.
self.selectOuterFaces(self.pcb)
self.pcb.active_material_index = 3
self.setMode('EDIT')
bpy.ops.object.material_slot_assign()
self.setMode('OBJECT')
def selectTopView(self):
self.clearMeshSelections()
self.setMode('OBJECT')
for face in self.pcb.data.polygons:
face.select = self.GoingUp(face.normal)
self.setViewOrientation((0, 0, 1))
def selectBottomView(self):
self.clearMeshSelections()
self.setMode('OBJECT')
for face in self.pcb.data.polygons:
face.select = self.GoingDown(face.normal)
self.setViewOrientation((1, 0, 0), 3.141592653)
def populate(self):
self.setMode('OBJECT')
with open(self.file_csv, newline='', encoding='ISO-8859-15') as fobj:
reader = csv.reader(filter(lambda row: row[0] != '#', fobj))
layout_table = list(reader)
required = list(col[1] for col in layout_table)
compfiles = []
for compfile in os.listdir(self.component_root):
if compfile.lower().endswith('.blend'):
compfiles.append(self.component_root + os.sep + compfile)
for compfile in compfiles:
self.txt.write("Loading models from " + compfile + "\n")
with bpy.data.libraries.load(compfile, link=True) as (data_from, data_to):
found = [value for value in data_from.meshes if value in required]
for f in found:
self.txt.write(" Found: " + f + "\n")
data_to.meshes = found
required = [value for value in required if value not in data_from.meshes]
self.txt.write("\nMissing components:\n")
for missing in required:
self.txt.write(" " + missing + "\n")
objects_data = bpy.data.objects
objects_scene = bpy.context.scene.objects
self.deselectAll()
self.objects = []
for id, name, value, x, y, rot, side in layout_table:
if id == "(unknown)":
continue
z = 0
yrot = 0
if side == "bottom":
z = -1.6
yrot = 180 / 57.2957795
loc = tuple(float(val) for val in (x, y, z))
frot = float(rot)
try:
if rotations[id]:
frot = rotations[id]
except:
pass
try:
if self.dnp[id] == 1:
continue
except:
pass
frot = frot / 57.2957795
zrot = tuple(float(val) for val in (0, yrot, frot))
oname = id + " - " + name
for ob in bpy.data.objects:
if ob.name.startswith(id + " - "):
self.setSelect(ob, True)
bpy.ops.object.delete()
mesh = bpy.data.meshes.get(name)
dupli = objects_data.new(oname, mesh)
dupli.location = loc
dupli.rotation_euler = zrot
self.linkObject(dupli)
self.objects.append(oname)
def cleanup(self):
self.deselectAll()
if self.doJoin:
for ob in self.objects:
self.setSelect(bpy.data.objects[ob], True)
self.setSelect(bpy.data.objects['PCB'], True)
self.setActiveObject(bpy.data.objects['PCB'])
bpy.ops.object.join()
self.setActiveObject(bpy.data.objects['PCB'])
else:
for ob in self.objects:
bpy.data.objects[ob].parent = self.pcb
bpy.data.objects[ob].location[0] -= self.pcb.location[0]
bpy.data.objects[ob].location[1] -= self.pcb.location[1]
bpy.data.objects[ob].location[2] -= self.pcb.location[2]
for ob in self.objects:
self.setSelect(bpy.data.objects[ob], False)
self.setSelect(self.pcb, True)
self.setActiveObject(self.pcb)
bpy.context.object.data.name = self.file_name
bpy.context.object.name = self.file_name
bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_MASS')
self.pcb.location = [0, 0, 0]
try:
bpy.data.cameras[0].dof.focus_object=self.pcb
except:
pass
## Modal stuff
_timer = None
_tick = 0
_phase = 0
def modal(self, context, event):
if event.type == 'TIMER':
dir(event)
self.stopTimer()
now = int(time.time() * 1000)
passed = now - self._tick
self._tick = now
print(str(self._phase) + ": " + str(passed))
if (passed < 1000):
# Strange extra ticks
self.startTimer()
return {'PASS_THROUGH'}
if (self._phase == 0):
print("START")
self.openBuildReport()
self.deleteExistingBoard()
self.deleteOrphans()
self.importOutline()
self.drillBoard()
self.extrudeBoard()
self.loadMaterials()
self.assignMaterials()
self.selectTopView()
self._phase+=1
self.startTimer()
print("Phase 0 done");
return {'PASS_THROUGH'}
if (self._phase == 1):
self.projectFromView()
self.selectBottomView()
self._phase+=1
self.startTimer()
print("Phase 1 done");
return {'PASS_THROUGH'}
if (self._phase == 2):
self.projectFromView()
self.populate()
self.deleteOrphans()
self.setViewOrientation((1, 1, 1), 0.2)
self._phase+=1
self.startTimer()
print("Phase 2 done")
return {'PASS_THROUGH'}
if (self._phase == 3):
self.cleanup()
print("END")
return {'FINISHED'}
return {'PASS_THROUGH'}
wm = None
context = None
def startTimer(self):
self._timer = self.wm.event_timer_add(2, window=self.context.window)
def stopTimer(self):
self.wm.event_timer_remove(self._timer)
def execute(self, context):
self._tick = int(time.time() * 1000) - self._tick
print("Starting...")
self.wm = context.window_manager
self.context = context
self.startTimer()
self.wm.modal_handler_add(self)
self._phase = 0
return {'RUNNING_MODAL'}
def cancel(self, context):
self.stopTimer()
def register():
bpy.utils.register_class(PCBImport)
print("Registered modal")
bpy.ops.wm.modal_timer_operator()
def unregister():
bpy.utils.unregister_class(PCBImport)
print("Unregistered modal")
if __name__ == "__main__":
register()