-
Notifications
You must be signed in to change notification settings - Fork 5
/
camlib.py
8561 lines (7192 loc) · 346 KB
/
camlib.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
# ########################################################## ##
# FlatCAM: 2D Post-processing for Manufacturing #
# http://flatcam.org #
# Author: Juan Pablo Caram (c) #
# Date: 2/5/2014 #
# MIT Licence #
# ########################################################## ##
import shapely
from PyQt6 import QtWidgets
from appCommon.Common import GracefulException as grace
# from scipy.spatial import KDTree, Delaunay
# from scipy.spatial import Delaunay
from appParsers.ParseSVG import svgparselength, svgparse_viewbox, getsvggeo, getsvgtext
from appParsers.ParseDXF import getdxfgeo
from numpy.linalg import solve
import platform
import traceback
from decimal import Decimal
from copy import deepcopy
from collections.abc import Iterable
from copy import copy
from rtree import index as rtindex
from lxml import etree as ET
from io import StringIO
import ezdxf
import math
# See: http://toblerity.org/shapely/manual.html
from shapely import Polygon, Point, LinearRing, MultiPoint, MultiLineString, MultiPolygon, LineString
from shapely import box as shply_box
from shapely.ops import unary_union, substring, linemerge
import shapely.affinity as affinity
from shapely.affinity import scale, translate
from shapely.wkt import loads as sloads
from shapely.wkt import dumps as sdumps
from shapely.geometry.base import BaseGeometry
from shapely import union, difference
# ---------------------------------------
# NEEDED for Legacy mode
# Used for solid polygons in Matplotlib
from descartes.patch import PolygonPatch # noqa
# ---------------------------------------
import logging
import re
import numpy as np
import gettext
import appTranslation as fcTranslate
import builtins
HAS_ORTOOLS = True
if platform.architecture()[0] == '64bit':
try:
from ortools.constraint_solver import pywrapcp # noqa
from ortools.constraint_solver import routing_enums_pb2 # noqa
except ModuleNotFoundError:
HAS_ORTOOLS = False
fcTranslate.apply_language('strings')
log = logging.getLogger('base2')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(levelname)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
if '_' not in builtins.__dict__:
_ = gettext.gettext
class ParseError(Exception):
pass
class ApertureMacro:
"""
Syntax of aperture macros.
<AM command>: AM<Aperture macro name>*<Macro content>
<Macro content>: {{<Variable definition>*}{<Primitive>*}}
<Variable definition>: $K=<Arithmetic expression>
<Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
<Modifier>: $M|< Arithmetic expression>
<Comment>: 0 <Text>
"""
# ## Regular expressions
am1_re = re.compile(r'^%AM([^*]+)\*(.+)?(%)?$')
am2_re = re.compile(r'(.*)%$')
am_comm_re = re.compile(r'^0(.*)')
am_prim_re = re.compile(r'^[1-9].*')
am_var_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
def __init__(self, name=None):
self.name = name
self.raw = ""
# ## These below are recomputed for every aperture
# ## definition, in other words, are temporary variables.
self.primitives = []
self.loc_vars = {}
self.geometry = None
def to_dict(self):
"""
Returns the object in a serializable form. Only the name and
raw are required.
:return: Dictionary representing the object. JSON ready.
:rtype: dict
"""
return {
'name': self.name,
'raw': self.raw
}
def from_dict(self, d):
"""
Populates the object from a serial representation created
with ``self.to_dict()``.
:param d: Serial representation of an ApertureMacro object.
:return: None
"""
for attr in ['name', 'raw']:
setattr(self, attr, d[attr])
def parse_content(self):
"""
Creates numerical lists for all primitives in the aperture
macro (in ``self.raw``) by replacing all variables by their
values iteratively and evaluating expressions. Results
are stored in ``self.primitives``.
:return: None
"""
# Cleanup
self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
self.primitives = []
# Separate parts
parts = self.raw.split('*')
# ### Every part in the macro ####
for part in parts:
# ## Comments. Ignored.
match = ApertureMacro.am_comm_re.search(part)
if match:
continue
# ## Variables
# These are variables defined locally inside the macro. They can be
# numerical constant or defined in terms of previously define
# variables, which can be defined locally or in an aperture
# definition. All replacements occur here.
match = ApertureMacro.am_var_re.search(part)
if match:
var = match.group(1)
val = match.group(2)
# Replace variables in value
for v in self.loc_vars:
# replaced the following line with the next to fix Mentor custom apertures not parsed OK
# val = re.sub((r'\$'+str(v)+r'(?![0-9a-zA-Z])'), str(self.locvars[v]), val)
val = val.replace('$' + str(v), str(self.loc_vars[v]))
# Make all others 0
val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
# Change x with *
val = re.sub(r'[xX]', "*", val)
# Eval() and store.
self.loc_vars[var] = eval(val)
continue
# ## Primitives
# Each is an array. The first identifies the primitive, while the
# rest depend on the primitive. All are strings representing a
# number and may contain variable definition. The values of these
# variables are defined in an aperture definition.
match = ApertureMacro.am_prim_re.search(part)
if match:
# ## Replace all variables
for v in self.loc_vars:
part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.loc_vars[v]), part)
# Sometimes the 'X' char is used instead of * for multiplication
part = re.sub(r'[Xx]', "*", part)
# Make all others 0
part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
self.primitives.append([eval(x) for x in part.split(",")])
continue
log.warning("Unknown syntax of aperture macro part: %s" % str(part))
def append(self, data):
"""
Appends a string to the raw macro.
:param data: Part of the macro.
:type data: str
:return: None
"""
self.raw += data
@staticmethod
def default2zero(n, mods):
"""
Pads the ``mods`` list with zeros resulting in an
list of length n.
:param n: Length of the resulting list.
:type n: int
:param mods: List to be padded.
:type mods: list
:return: Zero-padded list.
:rtype: list
"""
x = [0.0] * n
na = len(mods)
x[0:na] = mods
return x
@staticmethod
def make_circle(mods):
"""
:param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
:return:
"""
val = ApertureMacro.default2zero(4, mods)
pol = val[0]
dia = val[1]
x = val[2]
y = val[3]
# pol, dia, x, y = ApertureMacro.default2zero(4, mods)
return {"pol": int(pol), "geometry": Point(x, y).buffer(dia / 2)}
@staticmethod
def make_vector_line(mods):
"""
:param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
rotation angle around origin in degrees)
:return:
"""
val = ApertureMacro.default2zero(7, mods)
pol = val[0]
width = val[1]
xs = val[2]
ys = val[3]
xe = val[4]
ye = val[5]
angle = val[6]
# pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
line = LineString([(xs, ys), (xe, ye)])
box = line.buffer(width / 2, cap_style=2)
box_rotated = affinity.rotate(box, angle, origin=(0, 0))
return {"pol": int(pol), "geometry": box_rotated}
@staticmethod
def make_center_line(mods):
"""
:param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
rotation angle around origin in degrees)
:return:
"""
# pol, width, height, x, y, angle = ApertureMacro.default2zero(4, mods)
val = ApertureMacro.default2zero(4, mods)
pol = val[0]
width = val[1]
height = val[2]
x = val[3]
y = val[4]
angle = val[5]
box = shply_box(x - width / 2, y - height / 2, x + width / 2, y + height / 2)
box_rotated = affinity.rotate(box, angle, origin=(0, 0))
return {"pol": int(pol), "geometry": box_rotated}
@staticmethod
def make_lower_left_line(mods):
"""
:param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
rotation angle around origin in degrees)
:return:
"""
# pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
val = ApertureMacro.default2zero(6, mods)
pol = val[0]
width = val[1]
height = val[2]
x = val[3]
y = val[4]
angle = val[5]
box = shply_box(x, y, x + width, y + height)
box_rotated = affinity.rotate(box, angle, origin=(0, 0))
return {"pol": int(pol), "geometry": box_rotated}
@staticmethod
def make_outline(mods):
"""
:param mods:
:return:
"""
pol = mods[0]
# n = mods[1]
# points = [(0, 0)] * (n + 1)
#
# for i in range(n + 1):
# points[i] = mods[2 * i + 2:2 * i + 4]
#
# angle = mods[2 * n + 4]
# ---------------------------
# added to fix the issue on Allegro 17.2 Gerber's which have fewer points than declared
# discard first 2 values (exposure and vertex points number) and last one (rotation)
vertex_list = mods[2:-1]
# rotation is the last value
angle = mods[-1]
# vertex points number is second value
vtx_nr = mods[1]
n = int(len(vertex_list) / 2)
points = [(0, 0)] * n
for i in range(n):
start = 2 * i
stop = (2 * i) + 2
points[i] = vertex_list[start:stop]
# Fix for KiCAD 7.0.7 who is too lazy to respect the Gerber specification which says
# that the last point should always be the first
if len(points) < vtx_nr:
points.append(points[0])
# ---------------------------
poly = Polygon(points)
poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
return {"pol": int(pol), "geometry": poly_rotated}
@staticmethod
def make_polygon(mods):
"""
Note: Specs indicate that rotation is only allowed if the center
(x, y) == (0, 0). I will tolerate breaking this rule.
:param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
diameter of circumscribed circle >=0, rotation angle around origin)
:return:
"""
# pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
val = ApertureMacro.default2zero(6, mods)
pol = val[0]
nverts = val[1]
x = val[2]
y = val[3]
dia = val[4]
angle = val[5]
points = [(0, 0)] * nverts
for i in range(nverts):
points[i] = (x + 0.5 * dia * np.cos(2 * np.pi * i / nverts),
y + 0.5 * dia * np.sin(2 * np.pi * i / nverts))
poly = Polygon(points)
poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
return {"pol": int(pol), "geometry": poly_rotated}
@staticmethod
def make_moire(mods):
"""
Note: Specs indicate that rotation is only allowed if the center
(x, y) == (0, 0). I will tolerate breaking this rule.
:param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
gap, max_rings, crosshair_thickness, crosshair_len, rotation
angle around origin in degrees)
:return:
"""
# x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
val = ApertureMacro.default2zero(9, mods)
x = val[0]
y = val[1]
dia = val[2]
thickness = val[3]
gap = val[4]
nrings = val[5]
cross_th = val[6]
cross_len = val[7]
# angle = val[8]
r = dia / 2 - thickness / 2
result = Point((x, y)).buffer(r).exterior.buffer(thickness / 2.0)
ring = Point((x, y)).buffer(r).exterior.buffer(thickness / 2.0) # Need a copy!
i = 1 # Number of rings created so far
# ## If the ring does not have an interior it means that it is
# ## a disk. Then stop.
while len(ring.interiors) > 0 and i < nrings:
r -= thickness + gap
if r <= 0:
break
ring = Point((x, y)).buffer(r).exterior.buffer(thickness / 2.0)
result = unary_union([result, ring])
i += 1
# ## Crosshair
hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th / 2.0, cap_style=2)
ver = LineString([(x, y - cross_len), (x, y + cross_len)]).buffer(cross_th / 2.0, cap_style=2)
result = unary_union([result, hor, ver])
return {"pol": 1, "geometry": result}
@staticmethod
def make_thermal(mods):
"""
Note: Specs indicate that rotation is only allowed if the center
(x, y) == (0, 0). I will tolerate breaking this rule.
:param mods: [x-center, y-center, diameter-outside, diameter-inside,
gap-thickness, rotation angle around origin]
:return:
"""
# x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
val = ApertureMacro.default2zero(6, mods)
x = val[0]
y = val[1]
dout = val[2]
din = val[3]
t = val[4]
# angle = val[5]
ring = Point((x, y)).buffer(dout / 2.0).difference(Point((x, y)).buffer(din / 2.0))
hline = LineString([(x - dout / 2.0, y), (x + dout / 2.0, y)]).buffer(t / 2.0, cap_style=3)
vline = LineString([(x, y - dout / 2.0), (x, y + dout / 2.0)]).buffer(t / 2.0, cap_style=3)
thermal = ring.difference(hline.union(vline))
return {"pol": 1, "geometry": thermal}
def make_geometry(self, modifiers: list):
"""
Runs the macro for the given modifiers and generates
the corresponding geometry.
:param modifiers: Modifiers (parameters) for this macro
:type modifiers: list
:return: Shapely geometry
:rtype: shapely.geometry.polygon
"""
# ## Primitive makers
makers = {
"1": ApertureMacro.make_circle,
"2": ApertureMacro.make_vector_line,
"20": ApertureMacro.make_vector_line,
"21": ApertureMacro.make_center_line,
"22": ApertureMacro.make_lower_left_line,
"4": ApertureMacro.make_outline,
"5": ApertureMacro.make_polygon,
"6": ApertureMacro.make_moire,
"7": ApertureMacro.make_thermal
}
# ## Store modifiers as local variables
modifiers = modifiers or []
modifiers = [float(m) for m in modifiers]
self.loc_vars = {}
for i in range(0, len(modifiers)):
self.loc_vars[str(i + 1)] = modifiers[i]
# ## Parse
self.primitives = [] # Cleanup
self.geometry = Polygon()
self.parse_content()
# ## Make the geometry
for primitive in self.primitives:
# Make the primitive
prim_geo = makers[str(int(primitive[0]))](primitive[1:])
# Add it (according to polarity)
# if self.geometry is None and prim_geo['pol'] == 1:
# self.geometry = prim_geo['geometry']
# continue
if prim_geo['pol'] == 1:
if self.geometry.is_empty:
self.geometry = prim_geo['geometry']
continue
self.geometry = union(self.geometry, prim_geo['geometry'])
continue
if prim_geo['pol'] == 0:
self.geometry = difference(self.geometry, prim_geo['geometry'])
continue
return self.geometry
class Geometry(object):
"""
Base geometry class.
"""
defaults = {
"units": 'mm',
# "geo_steps_per_circle": 128
}
def __init__(self, geo_steps_per_circle=None):
# Units (in or mm)
self.units = self.app.app_units
self.decimals = self.app.decimals
self.drawing_tolerance = 0.0
self.tools = None
# Final geometry: MultiPolygon or list (of geometry constructs)
self.solid_geometry = None
# Final geometry: MultiLineString or list (of LineString or Points)
self.follow_geometry = None
# Flattened geometry (list of paths only)
self.flat_geometry = []
# this is the calculated conversion factor when the file units are different than the ones in the app
self.file_units_factor = 1
# Index
self.index = None
self.geo_steps_per_circle = geo_steps_per_circle
# variables to display the percentage of work done
self.geo_len = 0
self.old_disp_number = 0
self.el_count = 0
if self.app.use_3d_engine:
self.temp_shapes = self.app.plotcanvas.new_shape_collection(layers=1)
else:
from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
# Attributes to be included in serialization
self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry', 'tools']
def plot_temp_shapes(self, element, color='red'):
try:
for sub_el in element:
self.plot_temp_shapes(sub_el)
except TypeError: # Element is not iterable...
# self.add_shape(shape=element, color=color, visible=visible, layer=0)
self.temp_shapes.add(tolerance=float(self.app.options["global_tolerance"]),
shape=element, color=color, visible=True, layer=0)
def make_index(self):
self.flatten()
self.index = AppRTree()
for i, g in enumerate(self.flat_geometry):
self.index.insert(i, g)
def add_circle(self, origin, radius, tool=None):
"""
Adds a circle to the object.
:param origin: Center of the circle.
:param radius: Radius of the circle.
:param tool: A tool in the Tools dictionary attribute of the object
:return: None
"""
if self.solid_geometry is None:
self.solid_geometry = []
new_circle = Point(origin).buffer(radius, int(self.geo_steps_per_circle))
if not new_circle.is_valid:
return "fail"
# add to the solid_geometry
try:
self.solid_geometry.append(new_circle)
except TypeError:
try:
self.solid_geometry = self.solid_geometry.union(new_circle)
except Exception as e:
self.app.log.error("Failed to run union on polygons. %s" % str(e))
return "fail"
# add in tools solid_geometry
if tool is None or tool not in self.tools:
tool = 1
self.tools[tool]['solid_geometry'].append(new_circle)
# calculate bounds
try:
xmin, ymin, xmax, ymax = self.bounds()
self.obj_options['xmin'] = xmin
self.obj_options['ymin'] = ymin
self.obj_options['xmax'] = xmax
self.obj_options['ymax'] = ymax
except Exception as e:
self.app.log.error("Failed. The object has no bounds properties. %s" % str(e))
def add_polygon(self, points, tool=None):
"""
Adds a polygon to the object (by union)
:param points: The vertices of the polygon.
:param tool: A tool in the Tools dictionary attribute of the object
:return: None
"""
if self.solid_geometry is None:
self.solid_geometry = []
new_poly = Polygon(points)
if not new_poly.is_valid:
return "fail"
# add to the solid_geometry
if type(self.solid_geometry) is list:
self.solid_geometry.append(new_poly)
else:
try:
self.solid_geometry = self.solid_geometry.union(Polygon(points))
except Exception as e:
self.app.log.error("Failed to run union on polygons. %s" % str(e))
return "fail"
# add in tools solid_geometry
if tool is None or tool not in self.tools:
tool = 1
self.tools[tool]['solid_geometry'].append(new_poly)
# calculate bounds
try:
xmin, ymin, xmax, ymax = self.bounds()
self.obj_options['xmin'] = xmin
self.obj_options['ymin'] = ymin
self.obj_options['xmax'] = xmax
self.obj_options['ymax'] = ymax
except Exception as e:
self.app.log.error("Failed. The object has no bounds properties. %s" % str(e))
def add_polyline(self, points, tool=None):
"""
Adds a polyline to the object (by union)
:param points: The vertices of the polyline.
:param tool: A tool in the Tools dictionary attribute of the object
:return: None
"""
if self.solid_geometry is None:
self.solid_geometry = []
new_line = LineString(points)
if not new_line.is_valid:
return "fail"
# add to the solid_geometry
if type(self.solid_geometry) is list:
self.solid_geometry.append(new_line)
else:
try:
self.solid_geometry = self.solid_geometry.union(new_line)
except Exception as e:
self.app.log.error("Failed to run union on polylines. %s" % str(e))
return "fail"
# add in tools solid_geometry
if tool is None or tool not in self.tools:
tool = 1
self.tools[tool]['solid_geometry'].append(new_line)
# calculate bounds
try:
xmin, ymin, xmax, ymax = self.bounds()
self.obj_options['xmin'] = xmin
self.obj_options['ymin'] = ymin
self.obj_options['xmax'] = xmax
self.obj_options['ymax'] = ymax
except Exception as e:
self.app.log.error("Failed. The object has no bounds properties. %s" % str(e))
def is_empty(self):
if isinstance(self.solid_geometry, BaseGeometry) or isinstance(self.solid_geometry, Polygon) or \
isinstance(self.solid_geometry, MultiPolygon):
return self.solid_geometry.is_empty
if isinstance(self.solid_geometry, list):
return len(self.solid_geometry) == 0
self.app.inform.emit('[ERROR_NOTCL] %s' % _("self.solid_geometry is neither BaseGeometry or list."))
return
def subtract_polygon(self, points):
"""
Subtract polygon from the given object. This only operates on the paths in the original geometry,
i.e. it converts polygons into paths.
:param points: The vertices of the polygon.
:return: none
"""
if self.solid_geometry is None:
self.solid_geometry = []
# pathonly should be allways True, otherwise polygons are not subtracted
flat_geometry = self.flatten(pathonly=True)
self.app.log.debug("%d paths" % len(flat_geometry))
if not isinstance(points, Polygon):
polygon = Polygon(points)
else:
polygon = points
toolgeo = unary_union(polygon)
diffs = []
for target in flat_geometry:
if isinstance(target, LineString) or isinstance(target, LineString) or isinstance(target, MultiLineString):
diffs.append(target.difference(toolgeo))
else:
self.app.log.warning("Not implemented.")
self.solid_geometry = unary_union(diffs)
def bounds(self, flatten=False):
"""
Returns coordinates of rectangular bounds
of geometry: (xmin, ymin, xmax, ymax).
:param flatten: will flatten the solid_geometry if True
:return:
"""
# fixed issue of getting bounds only for one level lists of objects
# now it can get bounds for nested lists of objects
self.app.log.debug("camlib.Geometry.bounds()")
def bounds_rec(obj):
if type(obj) is list:
gminx = np.Inf
gminy = np.Inf
gmaxx = -np.Inf
gmaxy = -np.Inf
for k in obj:
if type(k) is dict:
for key in k:
minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
gminx = min(gminx, minx_)
gminy = min(gminy, miny_)
gmaxx = max(gmaxx, maxx_)
gmaxy = max(gmaxy, maxy_)
else:
try:
if k.is_empty:
continue
except Exception:
pass
minx_, miny_, maxx_, maxy_ = bounds_rec(k)
gminx = min(gminx, minx_)
gminy = min(gminy, miny_)
gmaxx = max(gmaxx, maxx_)
gmaxy = max(gmaxy, maxy_)
return gminx, gminy, gmaxx, gmaxy
else:
# it's a Shapely object, return it's bounds
return obj.bounds
if self.multigeo is True:
minx_list = []
miny_list = []
maxx_list = []
maxy_list = []
for tool in self.tools:
working_geo = self.tools[tool]['solid_geometry']
if not working_geo:
continue
if flatten:
self.flatten(geometry=working_geo, reset=True)
working_geo = self.flat_geometry
minx, miny, maxx, maxy = bounds_rec(working_geo)
minx_list.append(minx)
miny_list.append(miny)
maxx_list.append(maxx)
maxy_list.append(maxy)
if not minx_list and not miny_list and not maxx_list and not maxy_list:
self.app.log.debug("solid_geometry is None")
return 0, 0, 0, 0
return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
else:
if self.solid_geometry is None:
self.app.log.debug("solid_geometry is None")
return 0, 0, 0, 0
if flatten:
self.flatten(reset=True)
self.solid_geometry = self.flat_geometry
bounds_coords = bounds_rec(self.solid_geometry)
return bounds_coords
# try:
# # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
# def flatten(l, ltypes=(list, tuple)):
# ltype = type(l)
# l = list(l)
# i = 0
# while i < len(l):
# while isinstance(l[i], ltypes):
# if not l[i]:
# l.pop(i)
# i -= 1
# break
# else:
# l[i:i + 1] = l[i]
# i += 1
# return ltype(l)
#
# log.debug("Geometry->bounds()")
# if self.solid_geometry is None:
# log.debug("solid_geometry is None")
# return 0, 0, 0, 0
#
# if type(self.solid_geometry) is list:
# if len(self.solid_geometry) == 0:
# log.debug('solid_geometry is empty []')
# return 0, 0, 0, 0
# return unary_union(flatten(self.solid_geometry)).bounds
# else:
# return self.solid_geometry.bounds
# except Exception as e:
# self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
# log.debug("Geometry->bounds()")
# if self.solid_geometry is None:
# log.debug("solid_geometry is None")
# return 0, 0, 0, 0
#
# if type(self.solid_geometry) is list:
# if len(self.solid_geometry) == 0:
# log.debug('solid_geometry is empty []')
# return 0, 0, 0, 0
# return unary_union(self.solid_geometry).bounds
# else:
# return self.solid_geometry.bounds
def find_polygon(self, point, geoset=None) -> shapely.Polygon | None:
"""
Find an object that object.contains(Point(point)) in
poly, which can can be iterable, contain iterable of, or
be itself an implementer of .contains().
:param point: See description
:param geoset: a polygon or list of polygons where to find if the param point is contained
:return: Polygon containing point or None.
"""
if geoset is None:
geoset = self.solid_geometry
try: # Iterable
for sub_geo in geoset:
p = self.find_polygon(point, geoset=sub_geo)
if p is not None:
return p
except TypeError: # Non-iterable
try: # Implements .contains()
if isinstance(geoset, LinearRing):
geoset = Polygon(geoset)
if geoset.contains(Point(point)):
return geoset
except AttributeError: # Does not implement .contains()
return None
return None
def get_interiors(self, geometry=None):
interiors = []
if geometry is None:
geometry = self.solid_geometry
w_geo = flatten_shapely_geometry(geometry)
for geo in w_geo:
try:
interiors.append(geo.interiors)
except Exception:
continue
return interiors
def get_exteriors(self, geometry=None):
"""
Returns all exteriors of polygons in geometry. Uses
``self.solid_geometry`` if geometry is not provided.
:param geometry: Shapely type or list or list of list of such.
:return: List of paths constituting the exteriors
of polygons in geometry.
"""
exteriors = []
if geometry is None:
geometry = self.solid_geometry
w_geo = flatten_shapely_geometry(geometry)
for geo in w_geo:
try:
exteriors.append(geo.exterior)
except Exception:
continue
return exteriors
def flatten(self, geometry=None, reset=True, pathonly=False):
"""
Creates a list of non-iterable linear geometry objects.
Polygons are expanded into its exterior and interiors if specified.
Results are placed in self.flat_geometry
:param geometry: Shapely type, or list, or a list of lists of such.
:param reset: Clears the contents of self.flat_geometry.
:param pathonly: Expands polygons into linear elements.
"""
if geometry is None:
geometry = self.solid_geometry
if reset:
self.flat_geometry = []
# ## If iterable, expand recursively.
try:
work_geo = geometry.geoms if isinstance(geometry, (MultiPolygon, MultiLineString)) else geometry
for geo in work_geo:
if geo is not None:
self.flatten(geometry=geo,
reset=False,
pathonly=pathonly)
# ## Not iterable, do the actual indexing and add.
except TypeError:
if pathonly and isinstance(geometry, Polygon):
ext_geo = geometry.exterior
ints_geo = geometry.interiors
if ext_geo is not None and not ext_geo.is_empty:
self.flat_geometry.append(ext_geo)
self.flatten(geometry=ints_geo, reset=False, pathonly=True)
else:
if geometry is not None and not geometry.is_empty:
self.flat_geometry.append(geometry)
return self.flat_geometry