camlib.py 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. #from __future__ import division
  9. #from scipy import optimize
  10. #import traceback
  11. from cStringIO import StringIO
  12. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, dot, float32, \
  13. transpose
  14. from numpy.linalg import solve, norm
  15. from matplotlib.figure import Figure
  16. import re
  17. import sys
  18. import traceback
  19. from decimal import Decimal
  20. import collections
  21. import numpy as np
  22. import matplotlib
  23. #import matplotlib.pyplot as plt
  24. #from scipy.spatial import Delaunay, KDTree
  25. from rtree import index as rtindex
  26. # See: http://toblerity.org/shapely/manual.html
  27. from shapely.geometry import Polygon, LineString, Point, LinearRing
  28. from shapely.geometry import MultiPoint, MultiPolygon
  29. from shapely.geometry import box as shply_box
  30. from shapely.ops import cascaded_union
  31. import shapely.affinity as affinity
  32. from shapely.wkt import loads as sloads
  33. from shapely.wkt import dumps as sdumps
  34. from shapely.geometry.base import BaseGeometry
  35. # Used for solid polygons in Matplotlib
  36. from descartes.patch import PolygonPatch
  37. import simplejson as json
  38. # TODO: Commented for FlatCAM packaging with cx_freeze
  39. #from matplotlib.pyplot import plot, subplot
  40. import xml.etree.ElementTree as ET
  41. from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
  42. import itertools
  43. import xml.etree.ElementTree as ET
  44. from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, parse_path
  45. from svgparse import *
  46. import logging
  47. log = logging.getLogger('base2')
  48. log.setLevel(logging.DEBUG)
  49. # log.setLevel(logging.WARNING)
  50. # log.setLevel(logging.INFO)
  51. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  52. handler = logging.StreamHandler()
  53. handler.setFormatter(formatter)
  54. log.addHandler(handler)
  55. class ParseError(Exception):
  56. pass
  57. class Geometry(object):
  58. """
  59. Base geometry class.
  60. """
  61. defaults = {
  62. "init_units": 'in'
  63. }
  64. def __init__(self):
  65. # Units (in or mm)
  66. self.units = Geometry.defaults["init_units"]
  67. # Final geometry: MultiPolygon or list (of geometry constructs)
  68. self.solid_geometry = None
  69. # Attributes to be included in serialization
  70. self.ser_attrs = ['units', 'solid_geometry']
  71. # Flattened geometry (list of paths only)
  72. self.flat_geometry = []
  73. # Index
  74. self.index = None
  75. def make_index(self):
  76. self.flatten()
  77. self.index = FlatCAMRTree()
  78. for i, g in enumerate(self.flat_geometry):
  79. self.index.insert(i, g)
  80. def add_circle(self, origin, radius):
  81. """
  82. Adds a circle to the object.
  83. :param origin: Center of the circle.
  84. :param radius: Radius of the circle.
  85. :return: None
  86. """
  87. # TODO: Decide what solid_geometry is supposed to be and how we append to it.
  88. if self.solid_geometry is None:
  89. self.solid_geometry = []
  90. if type(self.solid_geometry) is list:
  91. self.solid_geometry.append(Point(origin).buffer(radius))
  92. return
  93. try:
  94. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(radius))
  95. except:
  96. #print "Failed to run union on polygons."
  97. log.error("Failed to run union on polygons.")
  98. raise
  99. def add_polygon(self, points):
  100. """
  101. Adds a polygon to the object (by union)
  102. :param points: The vertices of the polygon.
  103. :return: None
  104. """
  105. if self.solid_geometry is None:
  106. self.solid_geometry = []
  107. if type(self.solid_geometry) is list:
  108. self.solid_geometry.append(Polygon(points))
  109. return
  110. try:
  111. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  112. except:
  113. #print "Failed to run union on polygons."
  114. log.error("Failed to run union on polygons.")
  115. raise
  116. def add_polyline(self, points):
  117. """
  118. Adds a polyline to the object (by union)
  119. :param points: The vertices of the polyline.
  120. :return: None
  121. """
  122. if self.solid_geometry is None:
  123. self.solid_geometry = []
  124. if type(self.solid_geometry) is list:
  125. self.solid_geometry.append(LineString(points))
  126. return
  127. try:
  128. self.solid_geometry = self.solid_geometry.union(LineString(points))
  129. except:
  130. #print "Failed to run union on polygons."
  131. log.error("Failed to run union on polylines.")
  132. raise
  133. def is_empty(self):
  134. if isinstance(self.solid_geometry, BaseGeometry):
  135. return self.solid_geometry.is_empty
  136. if isinstance(self.solid_geometry, list):
  137. return len(self.solid_geometry) == 0
  138. raise Exception("self.solid_geometry is neither BaseGeometry or list.")
  139. def subtract_polygon(self, points):
  140. """
  141. Subtract polygon from the given object. This only operates on the paths in the original geometry, i.e. it converts polygons into paths.
  142. :param points: The vertices of the polygon.
  143. :return: none
  144. """
  145. if self.solid_geometry is None:
  146. self.solid_geometry = []
  147. #pathonly should be allways True, otherwise polygons are not subtracted
  148. flat_geometry = self.flatten(pathonly=True)
  149. log.debug("%d paths" % len(flat_geometry))
  150. polygon=Polygon(points)
  151. toolgeo=cascaded_union(polygon)
  152. diffs=[]
  153. for target in flat_geometry:
  154. if type(target) == LineString or type(target) == LinearRing:
  155. diffs.append(target.difference(toolgeo))
  156. else:
  157. log.warning("Not implemented.")
  158. self.solid_geometry=cascaded_union(diffs)
  159. def bounds(self):
  160. """
  161. Returns coordinates of rectangular bounds
  162. of geometry: (xmin, ymin, xmax, ymax).
  163. """
  164. log.debug("Geometry->bounds()")
  165. if self.solid_geometry is None:
  166. log.debug("solid_geometry is None")
  167. return 0, 0, 0, 0
  168. if type(self.solid_geometry) is list:
  169. # TODO: This can be done faster. See comment from Shapely mailing lists.
  170. if len(self.solid_geometry) == 0:
  171. log.debug('solid_geometry is empty []')
  172. return 0, 0, 0, 0
  173. return cascaded_union(self.solid_geometry).bounds
  174. else:
  175. return self.solid_geometry.bounds
  176. def find_polygon(self, point, geoset=None):
  177. """
  178. Find an object that object.contains(Point(point)) in
  179. geoset, which can can be iterable, contain iterables of, or
  180. be itself an implementer of .contains().
  181. Note:
  182. * Shapely Polygons will work as expected here. Linearrings
  183. will only yield true if the point is in the perimeter.
  184. :param point: See description
  185. :param geoset: Set to search. If none, the defaults to
  186. self.solid_geometry.
  187. :return: Polygon containing point or None.
  188. """
  189. if geoset is None:
  190. geoset = self.solid_geometry
  191. try: # Iterable
  192. for sub_geo in geoset:
  193. p = self.find_polygon(point, geoset=sub_geo)
  194. if p is not None:
  195. return p
  196. except TypeError: # Non-iterable
  197. try: # Implements .contains()
  198. if geoset.contains(Point(point)):
  199. return geoset
  200. except AttributeError: # Does not implement .contains()
  201. return None
  202. return None
  203. def get_interiors(self, geometry=None):
  204. interiors = []
  205. if geometry is None:
  206. geometry = self.solid_geometry
  207. ## If iterable, expand recursively.
  208. try:
  209. for geo in geometry:
  210. interiors.extend(self.get_interiors(geometry=geo))
  211. ## Not iterable, get the exterior if polygon.
  212. except TypeError:
  213. if type(geometry) == Polygon:
  214. interiors.extend(geometry.interiors)
  215. return interiors
  216. def get_exteriors(self, geometry=None):
  217. """
  218. Returns all exteriors of polygons in geometry. Uses
  219. ``self.solid_geometry`` if geometry is not provided.
  220. :param geometry: Shapely type or list or list of list of such.
  221. :return: List of paths constituting the exteriors
  222. of polygons in geometry.
  223. """
  224. exteriors = []
  225. if geometry is None:
  226. geometry = self.solid_geometry
  227. ## If iterable, expand recursively.
  228. try:
  229. for geo in geometry:
  230. exteriors.extend(self.get_exteriors(geometry=geo))
  231. ## Not iterable, get the exterior if polygon.
  232. except TypeError:
  233. if type(geometry) == Polygon:
  234. exteriors.append(geometry.exterior)
  235. return exteriors
  236. def flatten(self, geometry=None, reset=True, pathonly=False):
  237. """
  238. Creates a list of non-iterable linear geometry objects.
  239. Polygons are expanded into its exterior and interiors if specified.
  240. Results are placed in self.flat_geoemtry
  241. :param geometry: Shapely type or list or list of list of such.
  242. :param reset: Clears the contents of self.flat_geometry.
  243. :param pathonly: Expands polygons into linear elements.
  244. """
  245. if geometry is None:
  246. geometry = self.solid_geometry
  247. if reset:
  248. self.flat_geometry = []
  249. ## If iterable, expand recursively.
  250. try:
  251. for geo in geometry:
  252. self.flatten(geometry=geo,
  253. reset=False,
  254. pathonly=pathonly)
  255. ## Not iterable, do the actual indexing and add.
  256. except TypeError:
  257. if pathonly and type(geometry) == Polygon:
  258. self.flat_geometry.append(geometry.exterior)
  259. self.flatten(geometry=geometry.interiors,
  260. reset=False,
  261. pathonly=True)
  262. else:
  263. self.flat_geometry.append(geometry)
  264. return self.flat_geometry
  265. # def make2Dstorage(self):
  266. #
  267. # self.flatten()
  268. #
  269. # def get_pts(o):
  270. # pts = []
  271. # if type(o) == Polygon:
  272. # g = o.exterior
  273. # pts += list(g.coords)
  274. # for i in o.interiors:
  275. # pts += list(i.coords)
  276. # else:
  277. # pts += list(o.coords)
  278. # return pts
  279. #
  280. # storage = FlatCAMRTreeStorage()
  281. # storage.get_points = get_pts
  282. # for shape in self.flat_geometry:
  283. # storage.insert(shape)
  284. # return storage
  285. # def flatten_to_paths(self, geometry=None, reset=True):
  286. # """
  287. # Creates a list of non-iterable linear geometry elements and
  288. # indexes them in rtree.
  289. #
  290. # :param geometry: Iterable geometry
  291. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  292. # :return: self.flat_geometry, self.flat_geometry_rtree
  293. # """
  294. #
  295. # if geometry is None:
  296. # geometry = self.solid_geometry
  297. #
  298. # if reset:
  299. # self.flat_geometry = []
  300. #
  301. # ## If iterable, expand recursively.
  302. # try:
  303. # for geo in geometry:
  304. # self.flatten_to_paths(geometry=geo, reset=False)
  305. #
  306. # ## Not iterable, do the actual indexing and add.
  307. # except TypeError:
  308. # if type(geometry) == Polygon:
  309. # g = geometry.exterior
  310. # self.flat_geometry.append(g)
  311. #
  312. # ## Add first and last points of the path to the index.
  313. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  314. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  315. #
  316. # for interior in geometry.interiors:
  317. # g = interior
  318. # self.flat_geometry.append(g)
  319. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  320. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  321. # else:
  322. # g = geometry
  323. # self.flat_geometry.append(g)
  324. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  325. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  326. #
  327. # return self.flat_geometry, self.flat_geometry_rtree
  328. def isolation_geometry(self, offset):
  329. """
  330. Creates contours around geometry at a given
  331. offset distance.
  332. :param offset: Offset distance.
  333. :type offset: float
  334. :return: The buffered geometry.
  335. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  336. """
  337. return self.solid_geometry.buffer(offset)
  338. def import_svg(self, filename, flip=True):
  339. """
  340. Imports shapes from an SVG file into the object's geometry.
  341. :param filename: Path to the SVG file.
  342. :type filename: str
  343. :param flip: Flip the vertically.
  344. :type flip: bool
  345. :return: None
  346. """
  347. # Parse into list of shapely objects
  348. svg_tree = ET.parse(filename)
  349. svg_root = svg_tree.getroot()
  350. # Change origin to bottom left
  351. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  352. geos = getsvggeo(svg_root)
  353. if flip:
  354. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  355. # Add to object
  356. if self.solid_geometry is None:
  357. self.solid_geometry = []
  358. if type(self.solid_geometry) is list:
  359. # self.solid_geometry.append(cascaded_union(geos))
  360. if type(geos) is list:
  361. self.solid_geometry += geos
  362. else:
  363. self.solid_geometry.append(geos)
  364. else: # It's shapely geometry
  365. # self.solid_geometry = cascaded_union([self.solid_geometry,
  366. # cascaded_union(geos)])
  367. self.solid_geometry = [self.solid_geometry, geos]
  368. def size(self):
  369. """
  370. Returns (width, height) of rectangular
  371. bounds of geometry.
  372. """
  373. if self.solid_geometry is None:
  374. log.warning("Solid_geometry not computed yet.")
  375. return 0
  376. bounds = self.bounds()
  377. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  378. def get_empty_area(self, boundary=None):
  379. """
  380. Returns the complement of self.solid_geometry within
  381. the given boundary polygon. If not specified, it defaults to
  382. the rectangular bounding box of self.solid_geometry.
  383. """
  384. if boundary is None:
  385. boundary = self.solid_geometry.envelope
  386. return boundary.difference(self.solid_geometry)
  387. @staticmethod
  388. def clear_polygon(polygon, tooldia, overlap=0.15):
  389. """
  390. Creates geometry inside a polygon for a tool to cover
  391. the whole area.
  392. This algorithm shrinks the edges of the polygon and takes
  393. the resulting edges as toolpaths.
  394. :param polygon: Polygon to clear.
  395. :param tooldia: Diameter of the tool.
  396. :param overlap: Overlap of toolpasses.
  397. :return:
  398. """
  399. log.debug("camlib.clear_polygon()")
  400. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  401. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  402. ## The toolpaths
  403. # Index first and last points in paths
  404. def get_pts(o):
  405. return [o.coords[0], o.coords[-1]]
  406. geoms = FlatCAMRTreeStorage()
  407. geoms.get_points = get_pts
  408. # Can only result in a Polygon or MultiPolygon
  409. # NOTE: The resulting polygon can be "empty".
  410. current = polygon.buffer(-tooldia / 2.0)
  411. if current.area == 0:
  412. # Otherwise, trying to to insert current.exterior == None
  413. # into the FlatCAMStorage will fail.
  414. return None
  415. # current can be a MultiPolygon
  416. try:
  417. for p in current:
  418. geoms.insert(p.exterior)
  419. for i in p.interiors:
  420. geoms.insert(i)
  421. # Not a Multipolygon. Must be a Polygon
  422. except TypeError:
  423. geoms.insert(current.exterior)
  424. for i in current.interiors:
  425. geoms.insert(i)
  426. while True:
  427. # Can only result in a Polygon or MultiPolygon
  428. current = current.buffer(-tooldia * (1 - overlap))
  429. if current.area > 0:
  430. # current can be a MultiPolygon
  431. try:
  432. for p in current:
  433. geoms.insert(p.exterior)
  434. for i in p.interiors:
  435. geoms.insert(i)
  436. # Not a Multipolygon. Must be a Polygon
  437. except TypeError:
  438. geoms.insert(current.exterior)
  439. for i in current.interiors:
  440. geoms.insert(i)
  441. else:
  442. break
  443. # Optimization: Reduce lifts
  444. log.debug("Reducing tool lifts...")
  445. geoms = Geometry.paint_connect(geoms, polygon, tooldia)
  446. return geoms
  447. @staticmethod
  448. def clear_polygon2(polygon, tooldia, seedpoint=None, overlap=0.15):
  449. """
  450. Creates geometry inside a polygon for a tool to cover
  451. the whole area.
  452. This algorithm starts with a seed point inside the polygon
  453. and draws circles around it. Arcs inside the polygons are
  454. valid cuts. Finalizes by cutting around the inside edge of
  455. the polygon.
  456. :param polygon: Shapely.geometry.Polygon
  457. :param tooldia: Diameter of the tool
  458. :param seedpoint: Shapely.geometry.Point or None
  459. :param overlap: Tool fraction overlap bewteen passes
  460. :return: List of toolpaths covering polygon.
  461. :rtype: FlatCAMRTreeStorage | None
  462. """
  463. log.debug("camlib.clear_polygon2()")
  464. # Current buffer radius
  465. radius = tooldia / 2 * (1 - overlap)
  466. ## The toolpaths
  467. # Index first and last points in paths
  468. def get_pts(o):
  469. return [o.coords[0], o.coords[-1]]
  470. geoms = FlatCAMRTreeStorage()
  471. geoms.get_points = get_pts
  472. # Path margin
  473. path_margin = polygon.buffer(-tooldia / 2)
  474. # Estimate good seedpoint if not provided.
  475. if seedpoint is None:
  476. seedpoint = path_margin.representative_point()
  477. # Grow from seed until outside the box. The polygons will
  478. # never have an interior, so take the exterior LinearRing.
  479. while 1:
  480. path = Point(seedpoint).buffer(radius).exterior
  481. path = path.intersection(path_margin)
  482. # Touches polygon?
  483. if path.is_empty:
  484. break
  485. else:
  486. #geoms.append(path)
  487. #geoms.insert(path)
  488. # path can be a collection of paths.
  489. try:
  490. for p in path:
  491. geoms.insert(p)
  492. except TypeError:
  493. geoms.insert(path)
  494. radius += tooldia * (1 - overlap)
  495. # Clean inside edges of the original polygon
  496. outer_edges = [x.exterior for x in autolist(polygon.buffer(-tooldia / 2))]
  497. inner_edges = []
  498. for x in autolist(polygon.buffer(-tooldia / 2)): # Over resulting polygons
  499. for y in x.interiors: # Over interiors of each polygon
  500. inner_edges.append(y)
  501. #geoms += outer_edges + inner_edges
  502. for g in outer_edges + inner_edges:
  503. geoms.insert(g)
  504. # Optimization connect touching paths
  505. # log.debug("Connecting paths...")
  506. # geoms = Geometry.path_connect(geoms)
  507. # Optimization: Reduce lifts
  508. log.debug("Reducing tool lifts...")
  509. geoms = Geometry.paint_connect(geoms, polygon, tooldia)
  510. return geoms
  511. def scale(self, factor):
  512. """
  513. Scales all of the object's geometry by a given factor. Override
  514. this method.
  515. :param factor: Number by which to scale.
  516. :type factor: float
  517. :return: None
  518. :rtype: None
  519. """
  520. return
  521. def offset(self, vect):
  522. """
  523. Offset the geometry by the given vector. Override this method.
  524. :param vect: (x, y) vector by which to offset the object.
  525. :type vect: tuple
  526. :return: None
  527. """
  528. return
  529. @staticmethod
  530. def paint_connect(storage, boundary, tooldia, max_walk=None):
  531. """
  532. Connects paths that results in a connection segment that is
  533. within the paint area. This avoids unnecessary tool lifting.
  534. :param storage: Geometry to be optimized.
  535. :type storage: FlatCAMRTreeStorage
  536. :param boundary: Polygon defining the limits of the paintable area.
  537. :type boundary: Polygon
  538. :param tooldia: Tool diameter.
  539. :rtype tooldia: float
  540. :param max_walk: Maximum allowable distance without lifting tool.
  541. :type max_walk: float or None
  542. :return: Optimized geometry.
  543. :rtype: FlatCAMRTreeStorage
  544. """
  545. # If max_walk is not specified, the maximum allowed is
  546. # 10 times the tool diameter
  547. max_walk = max_walk or 10 * tooldia
  548. # Assuming geolist is a flat list of flat elements
  549. ## Index first and last points in paths
  550. def get_pts(o):
  551. return [o.coords[0], o.coords[-1]]
  552. # storage = FlatCAMRTreeStorage()
  553. # storage.get_points = get_pts
  554. #
  555. # for shape in geolist:
  556. # if shape is not None: # TODO: This shouldn't have happened.
  557. # # Make LlinearRings into linestrings otherwise
  558. # # When chaining the coordinates path is messed up.
  559. # storage.insert(LineString(shape))
  560. # #storage.insert(shape)
  561. ## Iterate over geometry paths getting the nearest each time.
  562. #optimized_paths = []
  563. optimized_paths = FlatCAMRTreeStorage()
  564. optimized_paths.get_points = get_pts
  565. path_count = 0
  566. current_pt = (0, 0)
  567. pt, geo = storage.nearest(current_pt)
  568. storage.remove(geo)
  569. geo = LineString(geo)
  570. current_pt = geo.coords[-1]
  571. try:
  572. while True:
  573. path_count += 1
  574. #log.debug("Path %d" % path_count)
  575. pt, candidate = storage.nearest(current_pt)
  576. storage.remove(candidate)
  577. candidate = LineString(candidate)
  578. # If last point in geometry is the nearest
  579. # then reverse coordinates.
  580. # but prefer the first one if last == first
  581. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  582. candidate.coords = list(candidate.coords)[::-1]
  583. # Straight line from current_pt to pt.
  584. # Is the toolpath inside the geometry?
  585. walk_path = LineString([current_pt, pt])
  586. walk_cut = walk_path.buffer(tooldia / 2)
  587. if walk_cut.within(boundary) and walk_path.length < max_walk:
  588. #log.debug("Walk to path #%d is inside. Joining." % path_count)
  589. # Completely inside. Append...
  590. geo.coords = list(geo.coords) + list(candidate.coords)
  591. # try:
  592. # last = optimized_paths[-1]
  593. # last.coords = list(last.coords) + list(geo.coords)
  594. # except IndexError:
  595. # optimized_paths.append(geo)
  596. else:
  597. # Have to lift tool. End path.
  598. #log.debug("Path #%d not within boundary. Next." % path_count)
  599. #optimized_paths.append(geo)
  600. optimized_paths.insert(geo)
  601. geo = candidate
  602. current_pt = geo.coords[-1]
  603. # Next
  604. #pt, geo = storage.nearest(current_pt)
  605. except StopIteration: # Nothing left in storage.
  606. #pass
  607. optimized_paths.insert(geo)
  608. return optimized_paths
  609. @staticmethod
  610. def path_connect(storage, origin=(0, 0)):
  611. """
  612. Simplifies paths in the FlatCAMRTreeStorage storage by
  613. connecting paths that touch on their enpoints.
  614. :param storage: Storage containing the initial paths.
  615. :rtype storage: FlatCAMRTreeStorage
  616. :return: Simplified storage.
  617. :rtype: FlatCAMRTreeStorage
  618. """
  619. log.debug("path_connect()")
  620. ## Index first and last points in paths
  621. def get_pts(o):
  622. return [o.coords[0], o.coords[-1]]
  623. #
  624. # storage = FlatCAMRTreeStorage()
  625. # storage.get_points = get_pts
  626. #
  627. # for shape in pathlist:
  628. # if shape is not None: # TODO: This shouldn't have happened.
  629. # storage.insert(shape)
  630. path_count = 0
  631. pt, geo = storage.nearest(origin)
  632. storage.remove(geo)
  633. #optimized_geometry = [geo]
  634. optimized_geometry = FlatCAMRTreeStorage()
  635. optimized_geometry.get_points = get_pts
  636. #optimized_geometry.insert(geo)
  637. try:
  638. while True:
  639. path_count += 1
  640. #print "geo is", geo
  641. _, left = storage.nearest(geo.coords[0])
  642. #print "left is", left
  643. # If left touches geo, remove left from original
  644. # storage and append to geo.
  645. if type(left) == LineString:
  646. if left.coords[0] == geo.coords[0]:
  647. storage.remove(left)
  648. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  649. continue
  650. if left.coords[-1] == geo.coords[0]:
  651. storage.remove(left)
  652. geo.coords = list(left.coords) + list(geo.coords)
  653. continue
  654. if left.coords[0] == geo.coords[-1]:
  655. storage.remove(left)
  656. geo.coords = list(geo.coords) + list(left.coords)
  657. continue
  658. if left.coords[-1] == geo.coords[-1]:
  659. storage.remove(left)
  660. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  661. continue
  662. _, right = storage.nearest(geo.coords[-1])
  663. #print "right is", right
  664. # If right touches geo, remove left from original
  665. # storage and append to geo.
  666. if type(right) == LineString:
  667. if right.coords[0] == geo.coords[-1]:
  668. storage.remove(right)
  669. geo.coords = list(geo.coords) + list(right.coords)
  670. continue
  671. if right.coords[-1] == geo.coords[-1]:
  672. storage.remove(right)
  673. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  674. continue
  675. if right.coords[0] == geo.coords[0]:
  676. storage.remove(right)
  677. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  678. continue
  679. if right.coords[-1] == geo.coords[0]:
  680. storage.remove(right)
  681. geo.coords = list(left.coords) + list(geo.coords)
  682. continue
  683. # right is either a LinearRing or it does not connect
  684. # to geo (nothing left to connect to geo), so we continue
  685. # with right as geo.
  686. storage.remove(right)
  687. if type(right) == LinearRing:
  688. optimized_geometry.insert(right)
  689. else:
  690. # Cannot exteng geo any further. Put it away.
  691. optimized_geometry.insert(geo)
  692. # Continue with right.
  693. geo = right
  694. except StopIteration: # Nothing found in storage.
  695. optimized_geometry.insert(geo)
  696. #print path_count
  697. log.debug("path_count = %d" % path_count)
  698. return optimized_geometry
  699. def convert_units(self, units):
  700. """
  701. Converts the units of the object to ``units`` by scaling all
  702. the geometry appropriately. This call ``scale()``. Don't call
  703. it again in descendents.
  704. :param units: "IN" or "MM"
  705. :type units: str
  706. :return: Scaling factor resulting from unit change.
  707. :rtype: float
  708. """
  709. log.debug("Geometry.convert_units()")
  710. if units.upper() == self.units.upper():
  711. return 1.0
  712. if units.upper() == "MM":
  713. factor = 25.4
  714. elif units.upper() == "IN":
  715. factor = 1 / 25.4
  716. else:
  717. log.error("Unsupported units: %s" % str(units))
  718. return 1.0
  719. self.units = units
  720. self.scale(factor)
  721. return factor
  722. def to_dict(self):
  723. """
  724. Returns a respresentation of the object as a dictionary.
  725. Attributes to include are listed in ``self.ser_attrs``.
  726. :return: A dictionary-encoded copy of the object.
  727. :rtype: dict
  728. """
  729. d = {}
  730. for attr in self.ser_attrs:
  731. d[attr] = getattr(self, attr)
  732. return d
  733. def from_dict(self, d):
  734. """
  735. Sets object's attributes from a dictionary.
  736. Attributes to include are listed in ``self.ser_attrs``.
  737. This method will look only for only and all the
  738. attributes in ``self.ser_attrs``. They must all
  739. be present. Use only for deserializing saved
  740. objects.
  741. :param d: Dictionary of attributes to set in the object.
  742. :type d: dict
  743. :return: None
  744. """
  745. for attr in self.ser_attrs:
  746. setattr(self, attr, d[attr])
  747. def union(self):
  748. """
  749. Runs a cascaded union on the list of objects in
  750. solid_geometry.
  751. :return: None
  752. """
  753. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  754. def export_svg(self, scale_factor=0.00):
  755. """
  756. Exports the Gemoetry Object as a SVG Element
  757. :return: SVG Element
  758. """
  759. # Make sure we see a Shapely Geometry class and not a list
  760. geom = cascaded_union(self.flatten())
  761. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  762. # If 0 or less which is invalid then default to 0.05
  763. # This value appears to work for zooming, and getting the output svg line width
  764. # to match that viewed on screen with FlatCam
  765. if scale_factor <= 0:
  766. scale_factor = 0.05
  767. # Convert to a SVG
  768. svg_elem = geom.svg(scale_factor=scale_factor)
  769. return svg_elem
  770. def mirror(self, axis, point):
  771. """
  772. Mirrors the object around a specified axis passign through
  773. the given point.
  774. :param axis: "X" or "Y" indicates around which axis to mirror.
  775. :type axis: str
  776. :param point: [x, y] point belonging to the mirror axis.
  777. :type point: list
  778. :return: None
  779. """
  780. px, py = point
  781. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  782. def mirror_geom(obj):
  783. if type(obj) is list:
  784. new_obj = []
  785. for g in obj:
  786. new_obj.append(mirror_geom(g))
  787. return new_obj
  788. else:
  789. return affinity.scale(obj,xscale,yscale,origin=(px,py))
  790. self.solid_geometry = mirror_geom(self.solid_geometry)
  791. class ApertureMacro:
  792. """
  793. Syntax of aperture macros.
  794. <AM command>: AM<Aperture macro name>*<Macro content>
  795. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  796. <Variable definition>: $K=<Arithmetic expression>
  797. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  798. <Modifier>: $M|< Arithmetic expression>
  799. <Comment>: 0 <Text>
  800. """
  801. ## Regular expressions
  802. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  803. am2_re = re.compile(r'(.*)%$')
  804. amcomm_re = re.compile(r'^0(.*)')
  805. amprim_re = re.compile(r'^[1-9].*')
  806. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  807. def __init__(self, name=None):
  808. self.name = name
  809. self.raw = ""
  810. ## These below are recomputed for every aperture
  811. ## definition, in other words, are temporary variables.
  812. self.primitives = []
  813. self.locvars = {}
  814. self.geometry = None
  815. def to_dict(self):
  816. """
  817. Returns the object in a serializable form. Only the name and
  818. raw are required.
  819. :return: Dictionary representing the object. JSON ready.
  820. :rtype: dict
  821. """
  822. return {
  823. 'name': self.name,
  824. 'raw': self.raw
  825. }
  826. def from_dict(self, d):
  827. """
  828. Populates the object from a serial representation created
  829. with ``self.to_dict()``.
  830. :param d: Serial representation of an ApertureMacro object.
  831. :return: None
  832. """
  833. for attr in ['name', 'raw']:
  834. setattr(self, attr, d[attr])
  835. def parse_content(self):
  836. """
  837. Creates numerical lists for all primitives in the aperture
  838. macro (in ``self.raw``) by replacing all variables by their
  839. values iteratively and evaluating expressions. Results
  840. are stored in ``self.primitives``.
  841. :return: None
  842. """
  843. # Cleanup
  844. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  845. self.primitives = []
  846. # Separate parts
  847. parts = self.raw.split('*')
  848. #### Every part in the macro ####
  849. for part in parts:
  850. ### Comments. Ignored.
  851. match = ApertureMacro.amcomm_re.search(part)
  852. if match:
  853. continue
  854. ### Variables
  855. # These are variables defined locally inside the macro. They can be
  856. # numerical constant or defind in terms of previously define
  857. # variables, which can be defined locally or in an aperture
  858. # definition. All replacements ocurr here.
  859. match = ApertureMacro.amvar_re.search(part)
  860. if match:
  861. var = match.group(1)
  862. val = match.group(2)
  863. # Replace variables in value
  864. for v in self.locvars:
  865. val = re.sub(r'\$'+str(v)+r'(?![0-9a-zA-Z])', str(self.locvars[v]), val)
  866. # Make all others 0
  867. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  868. # Change x with *
  869. val = re.sub(r'[xX]', "*", val)
  870. # Eval() and store.
  871. self.locvars[var] = eval(val)
  872. continue
  873. ### Primitives
  874. # Each is an array. The first identifies the primitive, while the
  875. # rest depend on the primitive. All are strings representing a
  876. # number and may contain variable definition. The values of these
  877. # variables are defined in an aperture definition.
  878. match = ApertureMacro.amprim_re.search(part)
  879. if match:
  880. ## Replace all variables
  881. for v in self.locvars:
  882. part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  883. # Make all others 0
  884. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  885. # Change x with *
  886. part = re.sub(r'[xX]', "*", part)
  887. ## Store
  888. elements = part.split(",")
  889. self.primitives.append([eval(x) for x in elements])
  890. continue
  891. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  892. def append(self, data):
  893. """
  894. Appends a string to the raw macro.
  895. :param data: Part of the macro.
  896. :type data: str
  897. :return: None
  898. """
  899. self.raw += data
  900. @staticmethod
  901. def default2zero(n, mods):
  902. """
  903. Pads the ``mods`` list with zeros resulting in an
  904. list of length n.
  905. :param n: Length of the resulting list.
  906. :type n: int
  907. :param mods: List to be padded.
  908. :type mods: list
  909. :return: Zero-padded list.
  910. :rtype: list
  911. """
  912. x = [0.0] * n
  913. na = len(mods)
  914. x[0:na] = mods
  915. return x
  916. @staticmethod
  917. def make_circle(mods):
  918. """
  919. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  920. :return:
  921. """
  922. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  923. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  924. @staticmethod
  925. def make_vectorline(mods):
  926. """
  927. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  928. rotation angle around origin in degrees)
  929. :return:
  930. """
  931. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  932. line = LineString([(xs, ys), (xe, ye)])
  933. box = line.buffer(width/2, cap_style=2)
  934. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  935. return {"pol": int(pol), "geometry": box_rotated}
  936. @staticmethod
  937. def make_centerline(mods):
  938. """
  939. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  940. rotation angle around origin in degrees)
  941. :return:
  942. """
  943. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  944. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  945. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  946. return {"pol": int(pol), "geometry": box_rotated}
  947. @staticmethod
  948. def make_lowerleftline(mods):
  949. """
  950. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  951. rotation angle around origin in degrees)
  952. :return:
  953. """
  954. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  955. box = shply_box(x, y, x+width, y+height)
  956. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  957. return {"pol": int(pol), "geometry": box_rotated}
  958. @staticmethod
  959. def make_outline(mods):
  960. """
  961. :param mods:
  962. :return:
  963. """
  964. pol = mods[0]
  965. n = mods[1]
  966. points = [(0, 0)]*(n+1)
  967. for i in range(n+1):
  968. points[i] = mods[2*i + 2:2*i + 4]
  969. angle = mods[2*n + 4]
  970. poly = Polygon(points)
  971. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  972. return {"pol": int(pol), "geometry": poly_rotated}
  973. @staticmethod
  974. def make_polygon(mods):
  975. """
  976. Note: Specs indicate that rotation is only allowed if the center
  977. (x, y) == (0, 0). I will tolerate breaking this rule.
  978. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  979. diameter of circumscribed circle >=0, rotation angle around origin)
  980. :return:
  981. """
  982. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  983. points = [(0, 0)]*nverts
  984. for i in range(nverts):
  985. points[i] = (x + 0.5 * dia * cos(2*pi * i/nverts),
  986. y + 0.5 * dia * sin(2*pi * i/nverts))
  987. poly = Polygon(points)
  988. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  989. return {"pol": int(pol), "geometry": poly_rotated}
  990. @staticmethod
  991. def make_moire(mods):
  992. """
  993. Note: Specs indicate that rotation is only allowed if the center
  994. (x, y) == (0, 0). I will tolerate breaking this rule.
  995. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  996. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  997. angle around origin in degrees)
  998. :return:
  999. """
  1000. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  1001. r = dia/2 - thickness/2
  1002. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  1003. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  1004. i = 1 # Number of rings created so far
  1005. ## If the ring does not have an interior it means that it is
  1006. ## a disk. Then stop.
  1007. while len(ring.interiors) > 0 and i < nrings:
  1008. r -= thickness + gap
  1009. if r <= 0:
  1010. break
  1011. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  1012. result = cascaded_union([result, ring])
  1013. i += 1
  1014. ## Crosshair
  1015. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  1016. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  1017. result = cascaded_union([result, hor, ver])
  1018. return {"pol": 1, "geometry": result}
  1019. @staticmethod
  1020. def make_thermal(mods):
  1021. """
  1022. Note: Specs indicate that rotation is only allowed if the center
  1023. (x, y) == (0, 0). I will tolerate breaking this rule.
  1024. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  1025. gap-thickness, rotation angle around origin]
  1026. :return:
  1027. """
  1028. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  1029. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  1030. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  1031. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  1032. thermal = ring.difference(hline.union(vline))
  1033. return {"pol": 1, "geometry": thermal}
  1034. def make_geometry(self, modifiers):
  1035. """
  1036. Runs the macro for the given modifiers and generates
  1037. the corresponding geometry.
  1038. :param modifiers: Modifiers (parameters) for this macro
  1039. :type modifiers: list
  1040. :return: Shapely geometry
  1041. :rtype: shapely.geometry.polygon
  1042. """
  1043. ## Primitive makers
  1044. makers = {
  1045. "1": ApertureMacro.make_circle,
  1046. "2": ApertureMacro.make_vectorline,
  1047. "20": ApertureMacro.make_vectorline,
  1048. "21": ApertureMacro.make_centerline,
  1049. "22": ApertureMacro.make_lowerleftline,
  1050. "4": ApertureMacro.make_outline,
  1051. "5": ApertureMacro.make_polygon,
  1052. "6": ApertureMacro.make_moire,
  1053. "7": ApertureMacro.make_thermal
  1054. }
  1055. ## Store modifiers as local variables
  1056. modifiers = modifiers or []
  1057. modifiers = [float(m) for m in modifiers]
  1058. self.locvars = {}
  1059. for i in range(0, len(modifiers)):
  1060. self.locvars[str(i + 1)] = modifiers[i]
  1061. ## Parse
  1062. self.primitives = [] # Cleanup
  1063. self.geometry = Polygon()
  1064. self.parse_content()
  1065. ## Make the geometry
  1066. for primitive in self.primitives:
  1067. # Make the primitive
  1068. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  1069. # Add it (according to polarity)
  1070. # if self.geometry is None and prim_geo['pol'] == 1:
  1071. # self.geometry = prim_geo['geometry']
  1072. # continue
  1073. if prim_geo['pol'] == 1:
  1074. self.geometry = self.geometry.union(prim_geo['geometry'])
  1075. continue
  1076. if prim_geo['pol'] == 0:
  1077. self.geometry = self.geometry.difference(prim_geo['geometry'])
  1078. continue
  1079. return self.geometry
  1080. class Gerber (Geometry):
  1081. """
  1082. **ATTRIBUTES**
  1083. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  1084. The values are dictionaries key/value pairs which describe the aperture. The
  1085. type key is always present and the rest depend on the key:
  1086. +-----------+-----------------------------------+
  1087. | Key | Value |
  1088. +===========+===================================+
  1089. | type | (str) "C", "R", "O", "P", or "AP" |
  1090. +-----------+-----------------------------------+
  1091. | others | Depend on ``type`` |
  1092. +-----------+-----------------------------------+
  1093. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  1094. that can be instanciated with different parameters in an aperture
  1095. definition. See ``apertures`` above. The key is the name of the macro,
  1096. and the macro itself, the value, is a ``Aperture_Macro`` object.
  1097. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  1098. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  1099. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  1100. *buffering* (or thickening) the ``paths`` with the aperture. These are
  1101. generated from ``paths`` in ``buffer_paths()``.
  1102. **USAGE**::
  1103. g = Gerber()
  1104. g.parse_file(filename)
  1105. g.create_geometry()
  1106. do_something(s.solid_geometry)
  1107. """
  1108. defaults = {
  1109. "steps_per_circle": 40,
  1110. "use_buffer_for_union": True
  1111. }
  1112. def __init__(self, steps_per_circle=None):
  1113. """
  1114. The constructor takes no parameters. Use ``gerber.parse_files()``
  1115. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  1116. :return: Gerber object
  1117. :rtype: Gerber
  1118. """
  1119. # Initialize parent
  1120. Geometry.__init__(self)
  1121. self.solid_geometry = Polygon()
  1122. # Number format
  1123. self.int_digits = 3
  1124. """Number of integer digits in Gerber numbers. Used during parsing."""
  1125. self.frac_digits = 4
  1126. """Number of fraction digits in Gerber numbers. Used during parsing."""
  1127. ## Gerber elements ##
  1128. # Apertures {'id':{'type':chr,
  1129. # ['size':float], ['width':float],
  1130. # ['height':float]}, ...}
  1131. self.apertures = {}
  1132. # Aperture Macros
  1133. self.aperture_macros = {}
  1134. # Attributes to be included in serialization
  1135. # Always append to it because it carries contents
  1136. # from Geometry.
  1137. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  1138. 'aperture_macros', 'solid_geometry']
  1139. #### Parser patterns ####
  1140. # FS - Format Specification
  1141. # The format of X and Y must be the same!
  1142. # L-omit leading zeros, T-omit trailing zeros
  1143. # A-absolute notation, I-incremental notation
  1144. self.fmt_re = re.compile(r'%FS([LT])([AI])X(\d)(\d)Y\d\d\*%$')
  1145. # Mode (IN/MM)
  1146. self.mode_re = re.compile(r'^%MO(IN|MM)\*%$')
  1147. # Comment G04|G4
  1148. self.comm_re = re.compile(r'^G0?4(.*)$')
  1149. # AD - Aperture definition
  1150. # Aperture Macro names: Name = [a-zA-Z_.$]{[a-zA-Z_.0-9]+}
  1151. # NOTE: Adding "-" to support output from Upverter.
  1152. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.\-]*)(?:,(.*))?\*%$')
  1153. # AM - Aperture Macro
  1154. # Beginning of macro (Ends with *%):
  1155. #self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  1156. # Tool change
  1157. # May begin with G54 but that is deprecated
  1158. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  1159. # G01... - Linear interpolation plus flashes with coordinates
  1160. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1161. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  1162. # Operation code alone, usually just D03 (Flash)
  1163. self.opcode_re = re.compile(r'^D0?([123])\*$')
  1164. # G02/3... - Circular interpolation with coordinates
  1165. # 2-clockwise, 3-counterclockwise
  1166. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1167. # Optional start with G02 or G03, optional end with D01 or D02 with
  1168. # optional coordinates but at least one in any order.
  1169. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))' +
  1170. '?(?=.*I([\+-]?\d+))?(?=.*J([\+-]?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  1171. # G01/2/3 Occurring without coordinates
  1172. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  1173. # Single D74 or multi D75 quadrant for circular interpolation
  1174. self.quad_re = re.compile(r'^G7([45])\*$')
  1175. # Region mode on
  1176. # In region mode, D01 starts a region
  1177. # and D02 ends it. A new region can be started again
  1178. # with D01. All contours must be closed before
  1179. # D02 or G37.
  1180. self.regionon_re = re.compile(r'^G36\*$')
  1181. # Region mode off
  1182. # Will end a region and come off region mode.
  1183. # All contours must be closed before D02 or G37.
  1184. self.regionoff_re = re.compile(r'^G37\*$')
  1185. # End of file
  1186. self.eof_re = re.compile(r'^M02\*')
  1187. # IP - Image polarity
  1188. self.pol_re = re.compile(r'^%IP(POS|NEG)\*%$')
  1189. # LP - Level polarity
  1190. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  1191. # Units (OBSOLETE)
  1192. self.units_re = re.compile(r'^G7([01])\*$')
  1193. # Absolute/Relative G90/1 (OBSOLETE)
  1194. self.absrel_re = re.compile(r'^G9([01])\*$')
  1195. # Aperture macros
  1196. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  1197. self.am2_re = re.compile(r'(.*)%$')
  1198. # How to discretize a circle.
  1199. self.steps_per_circ = steps_per_circle or Gerber.defaults['steps_per_circle']
  1200. self.use_buffer_for_union = self.defaults["use_buffer_for_union"]
  1201. def scale(self, factor):
  1202. """
  1203. Scales the objects' geometry on the XY plane by a given factor.
  1204. These are:
  1205. * ``buffered_paths``
  1206. * ``flash_geometry``
  1207. * ``solid_geometry``
  1208. * ``regions``
  1209. NOTE:
  1210. Does not modify the data used to create these elements. If these
  1211. are recreated, the scaling will be lost. This behavior was modified
  1212. because of the complexity reached in this class.
  1213. :param factor: Number by which to scale.
  1214. :type factor: float
  1215. :rtype : None
  1216. """
  1217. ## solid_geometry ???
  1218. # It's a cascaded union of objects.
  1219. self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  1220. factor, origin=(0, 0))
  1221. # # Now buffered_paths, flash_geometry and solid_geometry
  1222. # self.create_geometry()
  1223. def offset(self, vect):
  1224. """
  1225. Offsets the objects' geometry on the XY plane by a given vector.
  1226. These are:
  1227. * ``buffered_paths``
  1228. * ``flash_geometry``
  1229. * ``solid_geometry``
  1230. * ``regions``
  1231. NOTE:
  1232. Does not modify the data used to create these elements. If these
  1233. are recreated, the scaling will be lost. This behavior was modified
  1234. because of the complexity reached in this class.
  1235. :param vect: (x, y) offset vector.
  1236. :type vect: tuple
  1237. :return: None
  1238. """
  1239. dx, dy = vect
  1240. ## Solid geometry
  1241. self.solid_geometry = affinity.translate(self.solid_geometry, xoff=dx, yoff=dy)
  1242. # def mirror(self, axis, point):
  1243. # """
  1244. # Mirrors the object around a specified axis passign through
  1245. # the given point. What is affected:
  1246. #
  1247. # * ``buffered_paths``
  1248. # * ``flash_geometry``
  1249. # * ``solid_geometry``
  1250. # * ``regions``
  1251. #
  1252. # NOTE:
  1253. # Does not modify the data used to create these elements. If these
  1254. # are recreated, the scaling will be lost. This behavior was modified
  1255. # because of the complexity reached in this class.
  1256. #
  1257. # :param axis: "X" or "Y" indicates around which axis to mirror.
  1258. # :type axis: str
  1259. # :param point: [x, y] point belonging to the mirror axis.
  1260. # :type point: list
  1261. # :return: None
  1262. # """
  1263. #
  1264. # px, py = point
  1265. # xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1266. #
  1267. # ## solid_geometry ???
  1268. # # It's a cascaded union of objects.
  1269. # self.solid_geometry = affinity.scale(self.solid_geometry,
  1270. # xscale, yscale, origin=(px, py))
  1271. def aperture_parse(self, apertureId, apertureType, apParameters):
  1272. """
  1273. Parse gerber aperture definition into dictionary of apertures.
  1274. The following kinds and their attributes are supported:
  1275. * *Circular (C)*: size (float)
  1276. * *Rectangle (R)*: width (float), height (float)
  1277. * *Obround (O)*: width (float), height (float).
  1278. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  1279. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  1280. :param apertureId: Id of the aperture being defined.
  1281. :param apertureType: Type of the aperture.
  1282. :param apParameters: Parameters of the aperture.
  1283. :type apertureId: str
  1284. :type apertureType: str
  1285. :type apParameters: str
  1286. :return: Identifier of the aperture.
  1287. :rtype: str
  1288. """
  1289. # Found some Gerber with a leading zero in the aperture id and the
  1290. # referenced it without the zero, so this is a hack to handle that.
  1291. apid = str(int(apertureId))
  1292. try: # Could be empty for aperture macros
  1293. paramList = apParameters.split('X')
  1294. except:
  1295. paramList = None
  1296. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  1297. self.apertures[apid] = {"type": "C",
  1298. "size": float(paramList[0])}
  1299. return apid
  1300. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  1301. self.apertures[apid] = {"type": "R",
  1302. "width": float(paramList[0]),
  1303. "height": float(paramList[1]),
  1304. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1305. return apid
  1306. if apertureType == "O": # Obround
  1307. self.apertures[apid] = {"type": "O",
  1308. "width": float(paramList[0]),
  1309. "height": float(paramList[1]),
  1310. "size": sqrt(float(paramList[0])**2 + float(paramList[1])**2)} # Hack
  1311. return apid
  1312. if apertureType == "P": # Polygon (regular)
  1313. self.apertures[apid] = {"type": "P",
  1314. "diam": float(paramList[0]),
  1315. "nVertices": int(paramList[1]),
  1316. "size": float(paramList[0])} # Hack
  1317. if len(paramList) >= 3:
  1318. self.apertures[apid]["rotation"] = float(paramList[2])
  1319. return apid
  1320. if apertureType in self.aperture_macros:
  1321. self.apertures[apid] = {"type": "AM",
  1322. "macro": self.aperture_macros[apertureType],
  1323. "modifiers": paramList}
  1324. return apid
  1325. log.warning("Aperture not implemented: %s" % str(apertureType))
  1326. return None
  1327. def parse_file(self, filename, follow=False):
  1328. """
  1329. Calls Gerber.parse_lines() with generator of lines
  1330. read from the given file. Will split the lines if multiple
  1331. statements are found in a single original line.
  1332. The following line is split into two::
  1333. G54D11*G36*
  1334. First is ``G54D11*`` and seconds is ``G36*``.
  1335. :param filename: Gerber file to parse.
  1336. :type filename: str
  1337. :param follow: If true, will not create polygons, just lines
  1338. following the gerber path.
  1339. :type follow: bool
  1340. :return: None
  1341. """
  1342. with open(filename, 'r') as gfile:
  1343. def line_generator():
  1344. for line in gfile:
  1345. line = line.strip(' \r\n')
  1346. while len(line) > 0:
  1347. # If ends with '%' leave as is.
  1348. if line[-1] == '%':
  1349. yield line
  1350. break
  1351. # Split after '*' if any.
  1352. starpos = line.find('*')
  1353. if starpos > -1:
  1354. cleanline = line[:starpos + 1]
  1355. yield cleanline
  1356. line = line[starpos + 1:]
  1357. # Otherwise leave as is.
  1358. else:
  1359. # yield cleanline
  1360. yield line
  1361. break
  1362. self.parse_lines(line_generator(), follow=follow)
  1363. #@profile
  1364. def parse_lines(self, glines, follow=False):
  1365. """
  1366. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  1367. ``self.flashes``, ``self.regions`` and ``self.units``.
  1368. :param glines: Gerber code as list of strings, each element being
  1369. one line of the source file.
  1370. :type glines: list
  1371. :param follow: If true, will not create polygons, just lines
  1372. following the gerber path.
  1373. :type follow: bool
  1374. :return: None
  1375. :rtype: None
  1376. """
  1377. # Coordinates of the current path, each is [x, y]
  1378. path = []
  1379. # Polygons are stored here until there is a change in polarity.
  1380. # Only then they are combined via cascaded_union and added or
  1381. # subtracted from solid_geometry. This is ~100 times faster than
  1382. # applyng a union for every new polygon.
  1383. poly_buffer = []
  1384. last_path_aperture = None
  1385. current_aperture = None
  1386. # 1,2 or 3 from "G01", "G02" or "G03"
  1387. current_interpolation_mode = None
  1388. # 1 or 2 from "D01" or "D02"
  1389. # Note this is to support deprecated Gerber not putting
  1390. # an operation code at the end of every coordinate line.
  1391. current_operation_code = None
  1392. # Current coordinates
  1393. current_x = None
  1394. current_y = None
  1395. # Absolute or Relative/Incremental coordinates
  1396. # Not implemented
  1397. absolute = True
  1398. # How to interpret circular interpolation: SINGLE or MULTI
  1399. quadrant_mode = None
  1400. # Indicates we are parsing an aperture macro
  1401. current_macro = None
  1402. # Indicates the current polarity: D-Dark, C-Clear
  1403. current_polarity = 'D'
  1404. # If a region is being defined
  1405. making_region = False
  1406. #### Parsing starts here ####
  1407. line_num = 0
  1408. gline = ""
  1409. try:
  1410. for gline in glines:
  1411. line_num += 1
  1412. ### Cleanup
  1413. gline = gline.strip(' \r\n')
  1414. #log.debug("%3s %s" % (line_num, gline))
  1415. ### Aperture Macros
  1416. # Having this at the beggining will slow things down
  1417. # but macros can have complicated statements than could
  1418. # be caught by other patterns.
  1419. if current_macro is None: # No macro started yet
  1420. match = self.am1_re.search(gline)
  1421. # Start macro if match, else not an AM, carry on.
  1422. if match:
  1423. log.debug("Starting macro. Line %d: %s" % (line_num, gline))
  1424. current_macro = match.group(1)
  1425. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  1426. if match.group(2): # Append
  1427. self.aperture_macros[current_macro].append(match.group(2))
  1428. if match.group(3): # Finish macro
  1429. #self.aperture_macros[current_macro].parse_content()
  1430. current_macro = None
  1431. log.debug("Macro complete in 1 line.")
  1432. continue
  1433. else: # Continue macro
  1434. log.debug("Continuing macro. Line %d." % line_num)
  1435. match = self.am2_re.search(gline)
  1436. if match: # Finish macro
  1437. log.debug("End of macro. Line %d." % line_num)
  1438. self.aperture_macros[current_macro].append(match.group(1))
  1439. #self.aperture_macros[current_macro].parse_content()
  1440. current_macro = None
  1441. else: # Append
  1442. self.aperture_macros[current_macro].append(gline)
  1443. continue
  1444. ### G01 - Linear interpolation plus flashes
  1445. # Operation code (D0x) missing is deprecated... oh well I will support it.
  1446. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  1447. match = self.lin_re.search(gline)
  1448. if match:
  1449. # Dxx alone?
  1450. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  1451. # try:
  1452. # current_operation_code = int(match.group(4))
  1453. # except:
  1454. # pass # A line with just * will match too.
  1455. # continue
  1456. # NOTE: Letting it continue allows it to react to the
  1457. # operation code.
  1458. # Parse coordinates
  1459. if match.group(2) is not None:
  1460. current_x = parse_gerber_number(match.group(2), self.frac_digits)
  1461. if match.group(3) is not None:
  1462. current_y = parse_gerber_number(match.group(3), self.frac_digits)
  1463. # Parse operation code
  1464. if match.group(4) is not None:
  1465. current_operation_code = int(match.group(4))
  1466. # Pen down: add segment
  1467. if current_operation_code == 1:
  1468. path.append([current_x, current_y])
  1469. last_path_aperture = current_aperture
  1470. elif current_operation_code == 2:
  1471. if len(path) > 1:
  1472. ## --- BUFFERED ---
  1473. if making_region:
  1474. if follow:
  1475. geo = Polygon()
  1476. else:
  1477. geo = Polygon(path)
  1478. else:
  1479. if last_path_aperture is None:
  1480. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1481. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  1482. #log.debug("Line %d: Setting aperture to %s before buffering." % (line_num, last_path_aperture))
  1483. if follow:
  1484. geo = LineString(path)
  1485. else:
  1486. geo = LineString(path).buffer(width / 2)
  1487. if not geo.is_empty:
  1488. poly_buffer.append(geo)
  1489. path = [[current_x, current_y]] # Start new path
  1490. # Flash
  1491. # Not allowed in region mode.
  1492. elif current_operation_code == 3:
  1493. # Create path draw so far.
  1494. if len(path) > 1:
  1495. # --- Buffered ----
  1496. width = self.apertures[last_path_aperture]["size"]
  1497. if follow:
  1498. geo = LineString(path)
  1499. else:
  1500. geo = LineString(path).buffer(width / 2)
  1501. if not geo.is_empty:
  1502. poly_buffer.append(geo)
  1503. # Reset path starting point
  1504. path = [[current_x, current_y]]
  1505. # --- BUFFERED ---
  1506. # Draw the flash
  1507. if follow:
  1508. continue
  1509. flash = Gerber.create_flash_geometry(Point([current_x, current_y]),
  1510. self.apertures[current_aperture])
  1511. if not flash.is_empty:
  1512. poly_buffer.append(flash)
  1513. continue
  1514. ### G02/3 - Circular interpolation
  1515. # 2-clockwise, 3-counterclockwise
  1516. match = self.circ_re.search(gline)
  1517. if match:
  1518. arcdir = [None, None, "cw", "ccw"]
  1519. mode, x, y, i, j, d = match.groups()
  1520. try:
  1521. x = parse_gerber_number(x, self.frac_digits)
  1522. except:
  1523. x = current_x
  1524. try:
  1525. y = parse_gerber_number(y, self.frac_digits)
  1526. except:
  1527. y = current_y
  1528. try:
  1529. i = parse_gerber_number(i, self.frac_digits)
  1530. except:
  1531. i = 0
  1532. try:
  1533. j = parse_gerber_number(j, self.frac_digits)
  1534. except:
  1535. j = 0
  1536. if quadrant_mode is None:
  1537. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  1538. log.error(gline)
  1539. continue
  1540. if mode is None and current_interpolation_mode not in [2, 3]:
  1541. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  1542. log.error(gline)
  1543. continue
  1544. elif mode is not None:
  1545. current_interpolation_mode = int(mode)
  1546. # Set operation code if provided
  1547. if d is not None:
  1548. current_operation_code = int(d)
  1549. # Nothing created! Pen Up.
  1550. if current_operation_code == 2:
  1551. log.warning("Arc with D2. (%d)" % line_num)
  1552. if len(path) > 1:
  1553. if last_path_aperture is None:
  1554. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1555. # --- BUFFERED ---
  1556. width = self.apertures[last_path_aperture]["size"]
  1557. if follow:
  1558. buffered = LineString(path)
  1559. else:
  1560. buffered = LineString(path).buffer(width / 2)
  1561. if not buffered.is_empty:
  1562. poly_buffer.append(buffered)
  1563. current_x = x
  1564. current_y = y
  1565. path = [[current_x, current_y]] # Start new path
  1566. continue
  1567. # Flash should not happen here
  1568. if current_operation_code == 3:
  1569. log.error("Trying to flash within arc. (%d)" % line_num)
  1570. continue
  1571. if quadrant_mode == 'MULTI':
  1572. center = [i + current_x, j + current_y]
  1573. radius = sqrt(i ** 2 + j ** 2)
  1574. start = arctan2(-j, -i) # Start angle
  1575. # Numerical errors might prevent start == stop therefore
  1576. # we check ahead of time. This should result in a
  1577. # 360 degree arc.
  1578. if current_x == x and current_y == y:
  1579. stop = start
  1580. else:
  1581. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1582. this_arc = arc(center, radius, start, stop,
  1583. arcdir[current_interpolation_mode],
  1584. self.steps_per_circ)
  1585. # The last point in the computed arc can have
  1586. # numerical errors. The exact final point is the
  1587. # specified (x, y). Replace.
  1588. this_arc[-1] = (x, y)
  1589. # Last point in path is current point
  1590. # current_x = this_arc[-1][0]
  1591. # current_y = this_arc[-1][1]
  1592. current_x, current_y = x, y
  1593. # Append
  1594. path += this_arc
  1595. last_path_aperture = current_aperture
  1596. continue
  1597. if quadrant_mode == 'SINGLE':
  1598. center_candidates = [
  1599. [i + current_x, j + current_y],
  1600. [-i + current_x, j + current_y],
  1601. [i + current_x, -j + current_y],
  1602. [-i + current_x, -j + current_y]
  1603. ]
  1604. valid = False
  1605. log.debug("I: %f J: %f" % (i, j))
  1606. for center in center_candidates:
  1607. radius = sqrt(i ** 2 + j ** 2)
  1608. # Make sure radius to start is the same as radius to end.
  1609. radius2 = sqrt((center[0] - x) ** 2 + (center[1] - y) ** 2)
  1610. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  1611. continue # Not a valid center.
  1612. # Correct i and j and continue as with multi-quadrant.
  1613. i = center[0] - current_x
  1614. j = center[1] - current_y
  1615. start = arctan2(-j, -i) # Start angle
  1616. stop = arctan2(-center[1] + y, -center[0] + x) # Stop angle
  1617. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1618. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1619. (current_x, current_y, center[0], center[1], x, y))
  1620. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1621. (start * 180 / pi, stop * 180 / pi, arcdir[current_interpolation_mode],
  1622. angle * 180 / pi, pi / 2 * 180 / pi, angle <= (pi + 1e-6) / 2))
  1623. if angle <= (pi + 1e-6) / 2:
  1624. log.debug("########## ACCEPTING ARC ############")
  1625. this_arc = arc(center, radius, start, stop,
  1626. arcdir[current_interpolation_mode],
  1627. self.steps_per_circ)
  1628. # Replace with exact values
  1629. this_arc[-1] = (x, y)
  1630. # current_x = this_arc[-1][0]
  1631. # current_y = this_arc[-1][1]
  1632. current_x, current_y = x, y
  1633. path += this_arc
  1634. last_path_aperture = current_aperture
  1635. valid = True
  1636. break
  1637. if valid:
  1638. continue
  1639. else:
  1640. log.warning("Invalid arc in line %d." % line_num)
  1641. ### Operation code alone
  1642. # Operation code alone, usually just D03 (Flash)
  1643. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  1644. match = self.opcode_re.search(gline)
  1645. if match:
  1646. current_operation_code = int(match.group(1))
  1647. if current_operation_code == 3:
  1648. ## --- Buffered ---
  1649. try:
  1650. log.debug("Bare op-code %d." % current_operation_code)
  1651. # flash = Gerber.create_flash_geometry(Point(path[-1]),
  1652. # self.apertures[current_aperture])
  1653. if follow:
  1654. continue
  1655. flash = Gerber.create_flash_geometry(Point(current_x, current_y),
  1656. self.apertures[current_aperture])
  1657. if not flash.is_empty:
  1658. poly_buffer.append(flash)
  1659. except IndexError:
  1660. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  1661. continue
  1662. ### G74/75* - Single or multiple quadrant arcs
  1663. match = self.quad_re.search(gline)
  1664. if match:
  1665. if match.group(1) == '4':
  1666. quadrant_mode = 'SINGLE'
  1667. else:
  1668. quadrant_mode = 'MULTI'
  1669. continue
  1670. ### G36* - Begin region
  1671. if self.regionon_re.search(gline):
  1672. if len(path) > 1:
  1673. # Take care of what is left in the path
  1674. ## --- Buffered ---
  1675. width = self.apertures[last_path_aperture]["size"]
  1676. if follow:
  1677. geo = LineString(path)
  1678. else:
  1679. geo = LineString(path).buffer(width/2)
  1680. if not geo.is_empty:
  1681. poly_buffer.append(geo)
  1682. path = [path[-1]]
  1683. making_region = True
  1684. continue
  1685. ### G37* - End region
  1686. if self.regionoff_re.search(gline):
  1687. making_region = False
  1688. # Only one path defines region?
  1689. # This can happen if D02 happened before G37 and
  1690. # is not and error.
  1691. if len(path) < 3:
  1692. # print "ERROR: Path contains less than 3 points:"
  1693. # print path
  1694. # print "Line (%d): " % line_num, gline
  1695. # path = []
  1696. #path = [[current_x, current_y]]
  1697. continue
  1698. # For regions we may ignore an aperture that is None
  1699. # self.regions.append({"polygon": Polygon(path),
  1700. # "aperture": last_path_aperture})
  1701. # --- Buffered ---
  1702. if follow:
  1703. region = Polygon()
  1704. else:
  1705. region = Polygon(path)
  1706. if not region.is_valid:
  1707. if not follow:
  1708. region = region.buffer(0)
  1709. if not region.is_empty:
  1710. poly_buffer.append(region)
  1711. path = [[current_x, current_y]] # Start new path
  1712. continue
  1713. ### Aperture definitions %ADD...
  1714. match = self.ad_re.search(gline)
  1715. if match:
  1716. log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  1717. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  1718. continue
  1719. ### G01/2/3* - Interpolation mode change
  1720. # Can occur along with coordinates and operation code but
  1721. # sometimes by itself (handled here).
  1722. # Example: G01*
  1723. match = self.interp_re.search(gline)
  1724. if match:
  1725. current_interpolation_mode = int(match.group(1))
  1726. continue
  1727. ### Tool/aperture change
  1728. # Example: D12*
  1729. match = self.tool_re.search(gline)
  1730. if match:
  1731. current_aperture = match.group(1)
  1732. log.debug("Line %d: Aperture change to (%s)" % (line_num, match.group(1)))
  1733. log.debug(self.apertures[current_aperture])
  1734. # Take care of the current path with the previous tool
  1735. if len(path) > 1:
  1736. # --- Buffered ----
  1737. width = self.apertures[last_path_aperture]["size"]
  1738. if follow:
  1739. geo = LineString(path)
  1740. else:
  1741. geo = LineString(path).buffer(width / 2)
  1742. if not geo.is_empty:
  1743. poly_buffer.append(geo)
  1744. path = [path[-1]]
  1745. continue
  1746. ### Polarity change
  1747. # Example: %LPD*% or %LPC*%
  1748. # If polarity changes, creates geometry from current
  1749. # buffer, then adds or subtracts accordingly.
  1750. match = self.lpol_re.search(gline)
  1751. if match:
  1752. if len(path) > 1 and current_polarity != match.group(1):
  1753. # --- Buffered ----
  1754. width = self.apertures[last_path_aperture]["size"]
  1755. if follow:
  1756. geo = LineString(path)
  1757. else:
  1758. geo = LineString(path).buffer(width / 2)
  1759. if not geo.is_empty:
  1760. poly_buffer.append(geo)
  1761. path = [path[-1]]
  1762. # --- Apply buffer ---
  1763. # If added for testing of bug #83
  1764. # TODO: Remove when bug fixed
  1765. if len(poly_buffer) > 0:
  1766. if current_polarity == 'D':
  1767. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  1768. else:
  1769. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  1770. poly_buffer = []
  1771. current_polarity = match.group(1)
  1772. continue
  1773. ### Number format
  1774. # Example: %FSLAX24Y24*%
  1775. # TODO: This is ignoring most of the format. Implement the rest.
  1776. match = self.fmt_re.search(gline)
  1777. if match:
  1778. absolute = {'A': True, 'I': False}
  1779. self.int_digits = int(match.group(3))
  1780. self.frac_digits = int(match.group(4))
  1781. continue
  1782. ### Mode (IN/MM)
  1783. # Example: %MOIN*%
  1784. match = self.mode_re.search(gline)
  1785. if match:
  1786. #self.units = match.group(1)
  1787. # Changed for issue #80
  1788. self.convert_units(match.group(1))
  1789. continue
  1790. ### Units (G70/1) OBSOLETE
  1791. match = self.units_re.search(gline)
  1792. if match:
  1793. #self.units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  1794. # Changed for issue #80
  1795. self.convert_units({'0': 'IN', '1': 'MM'}[match.group(1)])
  1796. continue
  1797. ### Absolute/relative coordinates G90/1 OBSOLETE
  1798. match = self.absrel_re.search(gline)
  1799. if match:
  1800. absolute = {'0': True, '1': False}[match.group(1)]
  1801. continue
  1802. #### Ignored lines
  1803. ## Comments
  1804. match = self.comm_re.search(gline)
  1805. if match:
  1806. continue
  1807. ## EOF
  1808. match = self.eof_re.search(gline)
  1809. if match:
  1810. continue
  1811. ### Line did not match any pattern. Warn user.
  1812. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1813. if len(path) > 1:
  1814. # EOF, create shapely LineString if something still in path
  1815. ## --- Buffered ---
  1816. width = self.apertures[last_path_aperture]["size"]
  1817. if follow:
  1818. geo = LineString(path)
  1819. else:
  1820. geo = LineString(path).buffer(width / 2)
  1821. if not geo.is_empty:
  1822. poly_buffer.append(geo)
  1823. # --- Apply buffer ---
  1824. if follow:
  1825. self.solid_geometry = poly_buffer
  1826. return
  1827. log.warn("Joining %d polygons." % len(poly_buffer))
  1828. if self.use_buffer_for_union:
  1829. log.debug("Union by buffer...")
  1830. new_poly = MultiPolygon(poly_buffer)
  1831. new_poly = new_poly.buffer(0.00000001)
  1832. new_poly = new_poly.buffer(-0.00000001)
  1833. log.warn("Union(buffer) done.")
  1834. else:
  1835. log.debug("Union by union()...")
  1836. new_poly = cascaded_union(poly_buffer)
  1837. new_poly = new_poly.buffer(0)
  1838. log.warn("Union done.")
  1839. if current_polarity == 'D':
  1840. self.solid_geometry = self.solid_geometry.union(new_poly)
  1841. else:
  1842. self.solid_geometry = self.solid_geometry.difference(new_poly)
  1843. except Exception, err:
  1844. ex_type, ex, tb = sys.exc_info()
  1845. traceback.print_tb(tb)
  1846. #print traceback.format_exc()
  1847. log.error("PARSING FAILED. Line %d: %s" % (line_num, gline))
  1848. raise ParseError("Line %d: %s" % (line_num, gline), repr(err))
  1849. @staticmethod
  1850. def create_flash_geometry(location, aperture):
  1851. log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  1852. if type(location) == list:
  1853. location = Point(location)
  1854. if aperture['type'] == 'C': # Circles
  1855. return location.buffer(aperture['size'] / 2)
  1856. if aperture['type'] == 'R': # Rectangles
  1857. loc = location.coords[0]
  1858. width = aperture['width']
  1859. height = aperture['height']
  1860. minx = loc[0] - width / 2
  1861. maxx = loc[0] + width / 2
  1862. miny = loc[1] - height / 2
  1863. maxy = loc[1] + height / 2
  1864. return shply_box(minx, miny, maxx, maxy)
  1865. if aperture['type'] == 'O': # Obround
  1866. loc = location.coords[0]
  1867. width = aperture['width']
  1868. height = aperture['height']
  1869. if width > height:
  1870. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  1871. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  1872. c1 = p1.buffer(height * 0.5)
  1873. c2 = p2.buffer(height * 0.5)
  1874. else:
  1875. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  1876. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  1877. c1 = p1.buffer(width * 0.5)
  1878. c2 = p2.buffer(width * 0.5)
  1879. return cascaded_union([c1, c2]).convex_hull
  1880. if aperture['type'] == 'P': # Regular polygon
  1881. loc = location.coords[0]
  1882. diam = aperture['diam']
  1883. n_vertices = aperture['nVertices']
  1884. points = []
  1885. for i in range(0, n_vertices):
  1886. x = loc[0] + 0.5 * diam * (cos(2 * pi * i / n_vertices))
  1887. y = loc[1] + 0.5 * diam * (sin(2 * pi * i / n_vertices))
  1888. points.append((x, y))
  1889. ply = Polygon(points)
  1890. if 'rotation' in aperture:
  1891. ply = affinity.rotate(ply, aperture['rotation'])
  1892. return ply
  1893. if aperture['type'] == 'AM': # Aperture Macro
  1894. loc = location.coords[0]
  1895. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1896. if flash_geo.is_empty:
  1897. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  1898. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1899. log.warning("Unknown aperture type: %s" % aperture['type'])
  1900. return None
  1901. def create_geometry(self):
  1902. """
  1903. Geometry from a Gerber file is made up entirely of polygons.
  1904. Every stroke (linear or circular) has an aperture which gives
  1905. it thickness. Additionally, aperture strokes have non-zero area,
  1906. and regions naturally do as well.
  1907. :rtype : None
  1908. :return: None
  1909. """
  1910. # self.buffer_paths()
  1911. #
  1912. # self.fix_regions()
  1913. #
  1914. # self.do_flashes()
  1915. #
  1916. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1917. # [poly['polygon'] for poly in self.regions] +
  1918. # self.flash_geometry)
  1919. def get_bounding_box(self, margin=0.0, rounded=False):
  1920. """
  1921. Creates and returns a rectangular polygon bounding at a distance of
  1922. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1923. can optionally have rounded corners of radius equal to margin.
  1924. :param margin: Distance to enlarge the rectangular bounding
  1925. box in both positive and negative, x and y axes.
  1926. :type margin: float
  1927. :param rounded: Wether or not to have rounded corners.
  1928. :type rounded: bool
  1929. :return: The bounding box.
  1930. :rtype: Shapely.Polygon
  1931. """
  1932. bbox = self.solid_geometry.envelope.buffer(margin)
  1933. if not rounded:
  1934. bbox = bbox.envelope
  1935. return bbox
  1936. class Excellon(Geometry):
  1937. """
  1938. *ATTRIBUTES*
  1939. * ``tools`` (dict): The key is the tool name and the value is
  1940. a dictionary specifying the tool:
  1941. ================ ====================================
  1942. Key Value
  1943. ================ ====================================
  1944. C Diameter of the tool
  1945. Others Not supported (Ignored).
  1946. ================ ====================================
  1947. * ``drills`` (list): Each is a dictionary:
  1948. ================ ====================================
  1949. Key Value
  1950. ================ ====================================
  1951. point (Shapely.Point) Where to drill
  1952. tool (str) A key in ``tools``
  1953. ================ ====================================
  1954. """
  1955. defaults = {
  1956. "zeros": "L"
  1957. }
  1958. def __init__(self, zeros=None):
  1959. """
  1960. The constructor takes no parameters.
  1961. :return: Excellon object.
  1962. :rtype: Excellon
  1963. """
  1964. Geometry.__init__(self)
  1965. self.tools = {}
  1966. self.drills = []
  1967. ## IN|MM -> Units are inherited from Geometry
  1968. #self.units = units
  1969. # Trailing "T" or leading "L" (default)
  1970. #self.zeros = "T"
  1971. self.zeros = zeros or self.defaults["zeros"]
  1972. # Attributes to be included in serialization
  1973. # Always append to it because it carries contents
  1974. # from Geometry.
  1975. self.ser_attrs += ['tools', 'drills', 'zeros']
  1976. #### Patterns ####
  1977. # Regex basics:
  1978. # ^ - beginning
  1979. # $ - end
  1980. # *: 0 or more, +: 1 or more, ?: 0 or 1
  1981. # M48 - Beggining of Part Program Header
  1982. self.hbegin_re = re.compile(r'^M48$')
  1983. # M95 or % - End of Part Program Header
  1984. # NOTE: % has different meaning in the body
  1985. self.hend_re = re.compile(r'^(?:M95|%)$')
  1986. # FMAT Excellon format
  1987. # Ignored in the parser
  1988. #self.fmat_re = re.compile(r'^FMAT,([12])$')
  1989. # Number format and units
  1990. # INCH uses 6 digits
  1991. # METRIC uses 5/6
  1992. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?$')
  1993. # Tool definition/parameters (?= is look-ahead
  1994. # NOTE: This might be an overkill!
  1995. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  1996. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  1997. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  1998. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  1999. self.toolset_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))?' +
  2000. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  2001. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  2002. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  2003. # Tool select
  2004. # Can have additional data after tool number but
  2005. # is ignored if present in the header.
  2006. # Warning: This will match toolset_re too.
  2007. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  2008. self.toolsel_re = re.compile(r'^T(\d+)')
  2009. # Comment
  2010. self.comm_re = re.compile(r'^;(.*)$')
  2011. # Absolute/Incremental G90/G91
  2012. self.absinc_re = re.compile(r'^G9([01])$')
  2013. # Modes of operation
  2014. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  2015. self.modes_re = re.compile(r'^G0([012345])')
  2016. # Measuring mode
  2017. # 1-metric, 2-inch
  2018. self.meas_re = re.compile(r'^M7([12])$')
  2019. # Coordinates
  2020. #self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  2021. #self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  2022. self.coordsperiod_re = re.compile(r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]')
  2023. self.coordsnoperiod_re = re.compile(r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]')
  2024. # R - Repeat hole (# times, X offset, Y offset)
  2025. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  2026. # Various stop/pause commands
  2027. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  2028. # Parse coordinates
  2029. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  2030. def parse_file(self, filename):
  2031. """
  2032. Reads the specified file as array of lines as
  2033. passes it to ``parse_lines()``.
  2034. :param filename: The file to be read and parsed.
  2035. :type filename: str
  2036. :return: None
  2037. """
  2038. efile = open(filename, 'r')
  2039. estr = efile.readlines()
  2040. efile.close()
  2041. self.parse_lines(estr)
  2042. def parse_lines(self, elines):
  2043. """
  2044. Main Excellon parser.
  2045. :param elines: List of strings, each being a line of Excellon code.
  2046. :type elines: list
  2047. :return: None
  2048. """
  2049. # State variables
  2050. current_tool = ""
  2051. in_header = False
  2052. current_x = None
  2053. current_y = None
  2054. #### Parsing starts here ####
  2055. line_num = 0 # Line number
  2056. eline = ""
  2057. try:
  2058. for eline in elines:
  2059. line_num += 1
  2060. #log.debug("%3d %s" % (line_num, str(eline)))
  2061. ### Cleanup lines
  2062. eline = eline.strip(' \r\n')
  2063. ## Header Begin (M48) ##
  2064. if self.hbegin_re.search(eline):
  2065. in_header = True
  2066. continue
  2067. ## Header End ##
  2068. if self.hend_re.search(eline):
  2069. in_header = False
  2070. continue
  2071. ## Alternative units format M71/M72
  2072. # Supposed to be just in the body (yes, the body)
  2073. # but some put it in the header (PADS for example).
  2074. # Will detect anywhere. Occurrence will change the
  2075. # object's units.
  2076. match = self.meas_re.match(eline)
  2077. if match:
  2078. #self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  2079. # Modified for issue #80
  2080. self.convert_units({"1": "MM", "2": "IN"}[match.group(1)])
  2081. log.debug(" Units: %s" % self.units)
  2082. continue
  2083. #### Body ####
  2084. if not in_header:
  2085. ## Tool change ##
  2086. match = self.toolsel_re.search(eline)
  2087. if match:
  2088. current_tool = str(int(match.group(1)))
  2089. log.debug("Tool change: %s" % current_tool)
  2090. continue
  2091. ## Coordinates without period ##
  2092. match = self.coordsnoperiod_re.search(eline)
  2093. if match:
  2094. try:
  2095. #x = float(match.group(1))/10000
  2096. x = self.parse_number(match.group(1))
  2097. current_x = x
  2098. except TypeError:
  2099. x = current_x
  2100. try:
  2101. #y = float(match.group(2))/10000
  2102. y = self.parse_number(match.group(2))
  2103. current_y = y
  2104. except TypeError:
  2105. y = current_y
  2106. if x is None or y is None:
  2107. log.error("Missing coordinates")
  2108. continue
  2109. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  2110. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  2111. continue
  2112. ## Coordinates with period: Use literally. ##
  2113. match = self.coordsperiod_re.search(eline)
  2114. if match:
  2115. try:
  2116. x = float(match.group(1))
  2117. current_x = x
  2118. except TypeError:
  2119. x = current_x
  2120. try:
  2121. y = float(match.group(2))
  2122. current_y = y
  2123. except TypeError:
  2124. y = current_y
  2125. if x is None or y is None:
  2126. log.error("Missing coordinates")
  2127. continue
  2128. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  2129. log.debug("{:15} {:8} {:8}".format(eline, x, y))
  2130. continue
  2131. #### Header ####
  2132. if in_header:
  2133. ## Tool definitions ##
  2134. match = self.toolset_re.search(eline)
  2135. if match:
  2136. name = str(int(match.group(1)))
  2137. spec = {
  2138. "C": float(match.group(2)),
  2139. # "F": float(match.group(3)),
  2140. # "S": float(match.group(4)),
  2141. # "B": float(match.group(5)),
  2142. # "H": float(match.group(6)),
  2143. # "Z": float(match.group(7))
  2144. }
  2145. self.tools[name] = spec
  2146. log.debug(" Tool definition: %s %s" % (name, spec))
  2147. continue
  2148. ## Units and number format ##
  2149. match = self.units_re.match(eline)
  2150. if match:
  2151. self.zeros = match.group(2) or self.zeros # "T" or "L". Might be empty
  2152. #self.units = {"INCH": "IN", "METRIC": "MM"}[match.group(1)]
  2153. # Modified for issue #80
  2154. self.convert_units({"INCH": "IN", "METRIC": "MM"}[match.group(1)])
  2155. log.debug(" Units/Format: %s %s" % (self.units, self.zeros))
  2156. continue
  2157. log.warning("Line ignored: %s" % eline)
  2158. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  2159. except Exception as e:
  2160. log.error("PARSING FAILED. Line %d: %s" % (line_num, eline))
  2161. raise
  2162. def parse_number(self, number_str):
  2163. """
  2164. Parses coordinate numbers without period.
  2165. :param number_str: String representing the numerical value.
  2166. :type number_str: str
  2167. :return: Floating point representation of the number
  2168. :rtype: foat
  2169. """
  2170. if self.zeros == "L":
  2171. # With leading zeros, when you type in a coordinate,
  2172. # the leading zeros must always be included. Trailing zeros
  2173. # are unneeded and may be left off. The CNC-7 will automatically add them.
  2174. # r'^[-\+]?(0*)(\d*)'
  2175. # 6 digits are divided by 10^4
  2176. # If less than size digits, they are automatically added,
  2177. # 5 digits then are divided by 10^3 and so on.
  2178. match = self.leadingzeros_re.search(number_str)
  2179. if self.units.lower() == "in":
  2180. return float(number_str) / \
  2181. (10 ** (len(match.group(1)) + len(match.group(2)) - 2))
  2182. else:
  2183. return float(number_str) / \
  2184. (10 ** (len(match.group(1)) + len(match.group(2)) - 3))
  2185. else: # Trailing
  2186. # You must show all zeros to the right of the number and can omit
  2187. # all zeros to the left of the number. The CNC-7 will count the number
  2188. # of digits you typed and automatically fill in the missing zeros.
  2189. if self.units.lower() == "in": # Inches is 00.0000
  2190. return float(number_str) / 10000
  2191. else:
  2192. return float(number_str) / 1000 # Metric is 000.000
  2193. def create_geometry(self):
  2194. """
  2195. Creates circles of the tool diameter at every point
  2196. specified in ``self.drills``.
  2197. :return: None
  2198. """
  2199. self.solid_geometry = []
  2200. for drill in self.drills:
  2201. # poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  2202. tooldia = self.tools[drill['tool']]['C']
  2203. poly = drill['point'].buffer(tooldia / 2.0)
  2204. self.solid_geometry.append(poly)
  2205. def scale(self, factor):
  2206. """
  2207. Scales geometry on the XY plane in the object by a given factor.
  2208. Tool sizes, feedrates an Z-plane dimensions are untouched.
  2209. :param factor: Number by which to scale the object.
  2210. :type factor: float
  2211. :return: None
  2212. :rtype: NOne
  2213. """
  2214. # Drills
  2215. for drill in self.drills:
  2216. drill['point'] = affinity.scale(drill['point'], factor, factor, origin=(0, 0))
  2217. self.create_geometry()
  2218. def offset(self, vect):
  2219. """
  2220. Offsets geometry on the XY plane in the object by a given vector.
  2221. :param vect: (x, y) offset vector.
  2222. :type vect: tuple
  2223. :return: None
  2224. """
  2225. dx, dy = vect
  2226. # Drills
  2227. for drill in self.drills:
  2228. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  2229. # Recreate geometry
  2230. self.create_geometry()
  2231. def mirror(self, axis, point):
  2232. """
  2233. :param axis: "X" or "Y" indicates around which axis to mirror.
  2234. :type axis: str
  2235. :param point: [x, y] point belonging to the mirror axis.
  2236. :type point: list
  2237. :return: None
  2238. """
  2239. px, py = point
  2240. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2241. # Modify data
  2242. for drill in self.drills:
  2243. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  2244. # Recreate geometry
  2245. self.create_geometry()
  2246. def convert_units(self, units):
  2247. factor = Geometry.convert_units(self, units)
  2248. # Tools
  2249. for tname in self.tools:
  2250. self.tools[tname]["C"] *= factor
  2251. self.create_geometry()
  2252. return factor
  2253. class CNCjob(Geometry):
  2254. """
  2255. Represents work to be done by a CNC machine.
  2256. *ATTRIBUTES*
  2257. * ``gcode_parsed`` (list): Each is a dictionary:
  2258. ===================== =========================================
  2259. Key Value
  2260. ===================== =========================================
  2261. geom (Shapely.LineString) Tool path (XY plane)
  2262. kind (string) "AB", A is "T" (travel) or
  2263. "C" (cut). B is "F" (fast) or "S" (slow).
  2264. ===================== =========================================
  2265. """
  2266. defaults = {
  2267. "zdownrate": None,
  2268. "coordinate_format": "X%.4fY%.4f"
  2269. }
  2270. def __init__(self,
  2271. units="in",
  2272. kind="generic",
  2273. z_move=0.1,
  2274. feedrate=3.0,
  2275. z_cut=-0.002,
  2276. tooldia=0.0,
  2277. zdownrate=None,
  2278. spindlespeed=None):
  2279. Geometry.__init__(self)
  2280. self.kind = kind
  2281. self.units = units
  2282. self.z_cut = z_cut
  2283. self.z_move = z_move
  2284. self.feedrate = feedrate
  2285. self.tooldia = tooldia
  2286. self.unitcode = {"IN": "G20", "MM": "G21"}
  2287. # TODO: G04 Does not exist. It's G4 and now we are handling in postprocessing.
  2288. #self.pausecode = "G04 P1"
  2289. self.feedminutecode = "G94"
  2290. self.absolutecode = "G90"
  2291. self.gcode = ""
  2292. self.input_geometry_bounds = None
  2293. self.gcode_parsed = None
  2294. self.steps_per_circ = 20 # Used when parsing G-code arcs
  2295. if zdownrate is not None:
  2296. self.zdownrate = float(zdownrate)
  2297. elif CNCjob.defaults["zdownrate"] is not None:
  2298. self.zdownrate = float(CNCjob.defaults["zdownrate"])
  2299. else:
  2300. self.zdownrate = None
  2301. self.spindlespeed = spindlespeed
  2302. # Attributes to be included in serialization
  2303. # Always append to it because it carries contents
  2304. # from Geometry.
  2305. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'feedrate', 'tooldia',
  2306. 'gcode', 'input_geometry_bounds', 'gcode_parsed',
  2307. 'steps_per_circ']
  2308. def convert_units(self, units):
  2309. factor = Geometry.convert_units(self, units)
  2310. log.debug("CNCjob.convert_units()")
  2311. self.z_cut *= factor
  2312. self.z_move *= factor
  2313. self.feedrate *= factor
  2314. self.tooldia *= factor
  2315. return factor
  2316. def generate_from_excellon_by_tool(self, exobj, tools="all",
  2317. toolchange=False, toolchangez=0.1):
  2318. """
  2319. Creates gcode for this object from an Excellon object
  2320. for the specified tools.
  2321. :param exobj: Excellon object to process
  2322. :type exobj: Excellon
  2323. :param tools: Comma separated tool names
  2324. :type: tools: str
  2325. :return: None
  2326. :rtype: None
  2327. """
  2328. log.debug("Creating CNC Job from Excellon...")
  2329. # Tools
  2330. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  2331. # so we actually are sorting the tools by diameter
  2332. sorted_tools = sorted(exobj.tools.items(), key = lambda x: x[1])
  2333. if tools == "all":
  2334. tools = [i[0] for i in sorted_tools] # we get a array of ordered tools
  2335. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  2336. else:
  2337. selected_tools = [x.strip() for x in tools.split(",")] # we strip spaces and also separate the tools by ','
  2338. selected_tools = filter(lambda i: i in selected_tools, selected_tools)
  2339. # Create a sorted list of selected tools from the sorted_tools list
  2340. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  2341. log.debug("Tools selected and sorted are: %s" % str(tools))
  2342. # Points (Group by tool)
  2343. points = {}
  2344. for drill in exobj.drills:
  2345. if drill['tool'] in tools:
  2346. try:
  2347. points[drill['tool']].append(drill['point'])
  2348. except KeyError:
  2349. points[drill['tool']] = [drill['point']]
  2350. #log.debug("Found %d drills." % len(points))
  2351. self.gcode = []
  2352. # Basic G-Code macros
  2353. t = "G00 " + CNCjob.defaults["coordinate_format"] + "\n"
  2354. down = "G01 Z%.4f\n" % self.z_cut
  2355. up = "G00 Z%.4f\n" % self.z_move
  2356. up_to_zero = "G01 Z0\n"
  2357. # Initialization
  2358. gcode = self.unitcode[self.units.upper()] + "\n"
  2359. gcode += self.absolutecode + "\n"
  2360. gcode += self.feedminutecode + "\n"
  2361. gcode += "F%.2f\n" % self.feedrate
  2362. gcode += "G00 Z%.4f\n" % self.z_move # Move to travel height
  2363. if self.spindlespeed is not None:
  2364. # Spindle start with configured speed
  2365. gcode += "M03 S%d\n" % int(self.spindlespeed)
  2366. else:
  2367. gcode += "M03\n" # Spindle start
  2368. #gcode += self.pausecode + "\n"
  2369. for tool in tools:
  2370. # Only if tool has points.
  2371. if tool in points:
  2372. # Tool change sequence (optional)
  2373. if toolchange:
  2374. gcode += "G00 Z%.4f\n" % toolchangez
  2375. gcode += "T%d\n" % int(tool) # Indicate tool slot (for automatic tool changer)
  2376. gcode += "M5\n" # Spindle Stop
  2377. gcode += "M6\n" # Tool change
  2378. gcode += "(MSG, Change to tool dia=%.4f)\n" % exobj.tools[tool]["C"]
  2379. gcode += "M0\n" # Temporary machine stop
  2380. if self.spindlespeed is not None:
  2381. # Spindle start with configured speed
  2382. gcode += "M03 S%d\n" % int(self.spindlespeed)
  2383. else:
  2384. gcode += "M03\n" # Spindle start
  2385. # Drillling!
  2386. for point in points[tool]:
  2387. x, y = point.coords.xy
  2388. gcode += t % (x[0], y[0])
  2389. gcode += down + up_to_zero + up
  2390. gcode += t % (0, 0)
  2391. gcode += "M05\n" # Spindle stop
  2392. self.gcode = gcode
  2393. def generate_from_geometry_2(self,
  2394. geometry,
  2395. append=True,
  2396. tooldia=None,
  2397. tolerance=0,
  2398. multidepth=False,
  2399. depthpercut=None):
  2400. """
  2401. Second algorithm to generate from Geometry.
  2402. ALgorithm description:
  2403. ----------------------
  2404. Uses RTree to find the nearest path to follow.
  2405. :param geometry:
  2406. :param append:
  2407. :param tooldia:
  2408. :param tolerance:
  2409. :param multidepth: If True, use multiple passes to reach
  2410. the desired depth.
  2411. :param depthpercut: Maximum depth in each pass.
  2412. :return: None
  2413. """
  2414. assert isinstance(geometry, Geometry), \
  2415. "Expected a Geometry, got %s" % type(geometry)
  2416. log.debug("generate_from_geometry_2()")
  2417. ## Flatten the geometry
  2418. # Only linear elements (no polygons) remain.
  2419. flat_geometry = geometry.flatten(pathonly=True)
  2420. log.debug("%d paths" % len(flat_geometry))
  2421. ## Index first and last points in paths
  2422. # What points to index.
  2423. def get_pts(o):
  2424. return [o.coords[0], o.coords[-1]]
  2425. # Create the indexed storage.
  2426. storage = FlatCAMRTreeStorage()
  2427. storage.get_points = get_pts
  2428. # Store the geometry
  2429. log.debug("Indexing geometry before generating G-Code...")
  2430. for shape in flat_geometry:
  2431. if shape is not None: # TODO: This shouldn't have happened.
  2432. storage.insert(shape)
  2433. if tooldia is not None:
  2434. self.tooldia = tooldia
  2435. # self.input_geometry_bounds = geometry.bounds()
  2436. if not append:
  2437. self.gcode = ""
  2438. # Initial G-Code
  2439. self.gcode = self.unitcode[self.units.upper()] + "\n"
  2440. self.gcode += self.absolutecode + "\n"
  2441. self.gcode += self.feedminutecode + "\n"
  2442. self.gcode += "F%.2f\n" % self.feedrate
  2443. self.gcode += "G00 Z%.4f\n" % self.z_move # Move (up) to travel height
  2444. if self.spindlespeed is not None:
  2445. self.gcode += "M03 S%d\n" % int(self.spindlespeed) # Spindle start with configured speed
  2446. else:
  2447. self.gcode += "M03\n" # Spindle start
  2448. #self.gcode += self.pausecode + "\n"
  2449. ## Iterate over geometry paths getting the nearest each time.
  2450. log.debug("Starting G-Code...")
  2451. path_count = 0
  2452. current_pt = (0, 0)
  2453. pt, geo = storage.nearest(current_pt)
  2454. try:
  2455. while True:
  2456. path_count += 1
  2457. #print "Current: ", "(%.3f, %.3f)" % current_pt
  2458. # Remove before modifying, otherwise
  2459. # deletion will fail.
  2460. storage.remove(geo)
  2461. # If last point in geometry is the nearest
  2462. # but prefer the first one if last point == first point
  2463. # then reverse coordinates.
  2464. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2465. geo.coords = list(geo.coords)[::-1]
  2466. #---------- Single depth/pass --------
  2467. if not multidepth:
  2468. # G-code
  2469. # Note: self.linear2gcode() and self.point2gcode() will
  2470. # lower and raise the tool every time.
  2471. if type(geo) == LineString or type(geo) == LinearRing:
  2472. self.gcode += self.linear2gcode(geo, tolerance=tolerance)
  2473. elif type(geo) == Point:
  2474. self.gcode += self.point2gcode(geo)
  2475. else:
  2476. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  2477. #--------- Multi-pass ---------
  2478. else:
  2479. if isinstance(self.z_cut, Decimal):
  2480. z_cut = self.z_cut
  2481. else:
  2482. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  2483. if depthpercut is None:
  2484. depthpercut = z_cut
  2485. elif not isinstance(depthpercut, Decimal):
  2486. depthpercut = Decimal(depthpercut).quantize(Decimal('0.000000001'))
  2487. depth = 0
  2488. reverse = False
  2489. while depth > z_cut:
  2490. # Increase depth. Limit to z_cut.
  2491. depth -= depthpercut
  2492. if depth < z_cut:
  2493. depth = z_cut
  2494. # Cut at specific depth and do not lift the tool.
  2495. # Note: linear2gcode() will use G00 to move to the
  2496. # first point in the path, but it should be already
  2497. # at the first point if the tool is down (in the material).
  2498. # So, an extra G00 should show up but is inconsequential.
  2499. if type(geo) == LineString or type(geo) == LinearRing:
  2500. self.gcode += self.linear2gcode(geo, tolerance=tolerance,
  2501. zcut=depth,
  2502. up=False)
  2503. # Ignore multi-pass for points.
  2504. elif type(geo) == Point:
  2505. self.gcode += self.point2gcode(geo)
  2506. break # Ignoring ...
  2507. else:
  2508. log.warning("G-code generation not implemented for %s" % (str(type(geo))))
  2509. # Reverse coordinates if not a loop so we can continue
  2510. # cutting without returning to the beginhing.
  2511. if type(geo) == LineString:
  2512. geo.coords = list(geo.coords)[::-1]
  2513. reverse = True
  2514. # If geometry is reversed, revert.
  2515. if reverse:
  2516. if type(geo) == LineString:
  2517. geo.coords = list(geo.coords)[::-1]
  2518. # Lift the tool
  2519. self.gcode += "G00 Z%.4f\n" % self.z_move
  2520. # self.gcode += "( End of path. )\n"
  2521. # Did deletion at the beginning.
  2522. # Delete from index, update current location and continue.
  2523. #rti.delete(hits[0], geo.coords[0])
  2524. #rti.delete(hits[0], geo.coords[-1])
  2525. current_pt = geo.coords[-1]
  2526. # Next
  2527. pt, geo = storage.nearest(current_pt)
  2528. except StopIteration: # Nothing found in storage.
  2529. pass
  2530. log.debug("%s paths traced." % path_count)
  2531. # Finish
  2532. self.gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2533. self.gcode += "G00 X0Y0\n"
  2534. self.gcode += "M05\n" # Spindle stop
  2535. @staticmethod
  2536. def codes_split(gline):
  2537. """
  2538. Parses a line of G-Code such as "G01 X1234 Y987" into
  2539. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  2540. :param gline: G-Code line string
  2541. :return: Dictionary with parsed line.
  2542. """
  2543. command = {}
  2544. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  2545. while match:
  2546. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  2547. gline = gline[match.end():]
  2548. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  2549. return command
  2550. def gcode_parse(self):
  2551. """
  2552. G-Code parser (from self.gcode). Generates dictionary with
  2553. single-segment LineString's and "kind" indicating cut or travel,
  2554. fast or feedrate speed.
  2555. """
  2556. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2557. # Results go here
  2558. geometry = []
  2559. # Last known instruction
  2560. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  2561. # Current path: temporary storage until tool is
  2562. # lifted or lowered.
  2563. path = [(0, 0)]
  2564. # Process every instruction
  2565. for line in StringIO(self.gcode):
  2566. gobj = self.codes_split(line)
  2567. ## Units
  2568. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  2569. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  2570. continue
  2571. ## Changing height
  2572. if 'Z' in gobj:
  2573. if ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  2574. log.warning("Non-orthogonal motion: From %s" % str(current))
  2575. log.warning(" To: %s" % str(gobj))
  2576. current['Z'] = gobj['Z']
  2577. # Store the path into geometry and reset path
  2578. if len(path) > 1:
  2579. geometry.append({"geom": LineString(path),
  2580. "kind": kind})
  2581. path = [path[-1]] # Start with the last point of last path.
  2582. if 'G' in gobj:
  2583. current['G'] = int(gobj['G'])
  2584. if 'X' in gobj or 'Y' in gobj:
  2585. if 'X' in gobj:
  2586. x = gobj['X']
  2587. else:
  2588. x = current['X']
  2589. if 'Y' in gobj:
  2590. y = gobj['Y']
  2591. else:
  2592. y = current['Y']
  2593. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  2594. if current['Z'] > 0:
  2595. kind[0] = 'T'
  2596. if current['G'] > 0:
  2597. kind[1] = 'S'
  2598. arcdir = [None, None, "cw", "ccw"]
  2599. if current['G'] in [0, 1]: # line
  2600. path.append((x, y))
  2601. if current['G'] in [2, 3]: # arc
  2602. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  2603. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  2604. start = arctan2(-gobj['J'], -gobj['I'])
  2605. stop = arctan2(-center[1] + y, -center[0] + x)
  2606. path += arc(center, radius, start, stop,
  2607. arcdir[current['G']],
  2608. self.steps_per_circ)
  2609. # Update current instruction
  2610. for code in gobj:
  2611. current[code] = gobj[code]
  2612. # There might not be a change in height at the
  2613. # end, therefore, see here too if there is
  2614. # a final path.
  2615. if len(path) > 1:
  2616. geometry.append({"geom": LineString(path),
  2617. "kind": kind})
  2618. self.gcode_parsed = geometry
  2619. return geometry
  2620. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  2621. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2622. # alpha={"T": 0.3, "C": 1.0}):
  2623. # """
  2624. # Creates a Matplotlib figure with a plot of the
  2625. # G-code job.
  2626. # """
  2627. # if tooldia is None:
  2628. # tooldia = self.tooldia
  2629. #
  2630. # fig = Figure(dpi=dpi)
  2631. # ax = fig.add_subplot(111)
  2632. # ax.set_aspect(1)
  2633. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  2634. # ax.set_xlim(xmin-margin, xmax+margin)
  2635. # ax.set_ylim(ymin-margin, ymax+margin)
  2636. #
  2637. # if tooldia == 0:
  2638. # for geo in self.gcode_parsed:
  2639. # linespec = '--'
  2640. # linecolor = color[geo['kind'][0]][1]
  2641. # if geo['kind'][0] == 'C':
  2642. # linespec = 'k-'
  2643. # x, y = geo['geom'].coords.xy
  2644. # ax.plot(x, y, linespec, color=linecolor)
  2645. # else:
  2646. # for geo in self.gcode_parsed:
  2647. # poly = geo['geom'].buffer(tooldia/2.0)
  2648. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2649. # edgecolor=color[geo['kind'][0]][1],
  2650. # alpha=alpha[geo['kind'][0]], zorder=2)
  2651. # ax.add_patch(patch)
  2652. #
  2653. # return fig
  2654. def plot2(self, axes, tooldia=None, dpi=75, margin=0.1,
  2655. color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  2656. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005):
  2657. """
  2658. Plots the G-code job onto the given axes.
  2659. :param axes: Matplotlib axes on which to plot.
  2660. :param tooldia: Tool diameter.
  2661. :param dpi: Not used!
  2662. :param margin: Not used!
  2663. :param color: Color specification.
  2664. :param alpha: Transparency specification.
  2665. :param tool_tolerance: Tolerance when drawing the toolshape.
  2666. :return: None
  2667. """
  2668. path_num = 0
  2669. if tooldia is None:
  2670. tooldia = self.tooldia
  2671. if tooldia == 0:
  2672. for geo in self.gcode_parsed:
  2673. linespec = '--'
  2674. linecolor = color[geo['kind'][0]][1]
  2675. if geo['kind'][0] == 'C':
  2676. linespec = 'k-'
  2677. x, y = geo['geom'].coords.xy
  2678. axes.plot(x, y, linespec, color=linecolor)
  2679. else:
  2680. for geo in self.gcode_parsed:
  2681. path_num += 1
  2682. axes.annotate(str(path_num), xy=geo['geom'].coords[0],
  2683. xycoords='data')
  2684. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  2685. patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  2686. edgecolor=color[geo['kind'][0]][1],
  2687. alpha=alpha[geo['kind'][0]], zorder=2)
  2688. axes.add_patch(patch)
  2689. def create_geometry(self):
  2690. # TODO: This takes forever. Too much data?
  2691. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  2692. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  2693. zcut=None, ztravel=None, downrate=None,
  2694. feedrate=None, cont=False):
  2695. """
  2696. Generates G-code to cut along the linear feature.
  2697. :param linear: The path to cut along.
  2698. :type: Shapely.LinearRing or Shapely.Linear String
  2699. :param tolerance: All points in the simplified object will be within the
  2700. tolerance distance of the original geometry.
  2701. :type tolerance: float
  2702. :return: G-code to cut along the linear feature.
  2703. :rtype: str
  2704. """
  2705. if zcut is None:
  2706. zcut = self.z_cut
  2707. if ztravel is None:
  2708. ztravel = self.z_move
  2709. if downrate is None:
  2710. downrate = self.zdownrate
  2711. if feedrate is None:
  2712. feedrate = self.feedrate
  2713. t = "G0%d " + CNCjob.defaults["coordinate_format"] + "\n"
  2714. # Simplify paths?
  2715. if tolerance > 0:
  2716. target_linear = linear.simplify(tolerance)
  2717. else:
  2718. target_linear = linear
  2719. gcode = ""
  2720. path = list(target_linear.coords)
  2721. # Move fast to 1st point
  2722. if not cont:
  2723. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2724. # Move down to cutting depth
  2725. if down:
  2726. # Different feedrate for vertical cut?
  2727. if self.zdownrate is not None:
  2728. gcode += "F%.2f\n" % downrate
  2729. gcode += "G01 Z%.4f\n" % zcut # Start cutting
  2730. gcode += "F%.2f\n" % feedrate # Restore feedrate
  2731. else:
  2732. gcode += "G01 Z%.4f\n" % zcut # Start cutting
  2733. # Cutting...
  2734. for pt in path[1:]:
  2735. gcode += t % (1, pt[0], pt[1]) # Linear motion to point
  2736. # Up to travelling height.
  2737. if up:
  2738. gcode += "G00 Z%.4f\n" % ztravel # Stop cutting
  2739. return gcode
  2740. def point2gcode(self, point):
  2741. gcode = ""
  2742. #t = "G0%d X%.4fY%.4f\n"
  2743. t = "G0%d " + CNCjob.defaults["coordinate_format"] + "\n"
  2744. path = list(point.coords)
  2745. gcode += t % (0, path[0][0], path[0][1]) # Move to first point
  2746. if self.zdownrate is not None:
  2747. gcode += "F%.2f\n" % self.zdownrate
  2748. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2749. gcode += "F%.2f\n" % self.feedrate
  2750. else:
  2751. gcode += "G01 Z%.4f\n" % self.z_cut # Start cutting
  2752. gcode += "G00 Z%.4f\n" % self.z_move # Stop cutting
  2753. return gcode
  2754. def scale(self, factor):
  2755. """
  2756. Scales all the geometry on the XY plane in the object by the
  2757. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  2758. not altered.
  2759. :param factor: Number by which to scale the object.
  2760. :type factor: float
  2761. :return: None
  2762. :rtype: None
  2763. """
  2764. for g in self.gcode_parsed:
  2765. g['geom'] = affinity.scale(g['geom'], factor, factor, origin=(0, 0))
  2766. self.create_geometry()
  2767. def offset(self, vect):
  2768. """
  2769. Offsets all the geometry on the XY plane in the object by the
  2770. given vector.
  2771. :param vect: (x, y) offset vector.
  2772. :type vect: tuple
  2773. :return: None
  2774. """
  2775. dx, dy = vect
  2776. for g in self.gcode_parsed:
  2777. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  2778. self.create_geometry()
  2779. def export_svg(self, scale_factor=0.00):
  2780. """
  2781. Exports the CNC Job as a SVG Element
  2782. :scale_factor: float
  2783. :return: SVG Element string
  2784. """
  2785. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  2786. # If not specified then try and use the tool diameter
  2787. # This way what is on screen will match what is outputed for the svg
  2788. # This is quite a useful feature for svg's used with visicut
  2789. if scale_factor <= 0:
  2790. scale_factor = self.options['tooldia'] / 2
  2791. # If still 0 then defailt to 0.05
  2792. # This value appears to work for zooming, and getting the output svg line width
  2793. # to match that viewed on screen with FlatCam
  2794. if scale_factor == 0:
  2795. scale_factor = 0.05
  2796. # Seperate the list of cuts and travels into 2 distinct lists
  2797. # This way we can add different formatting / colors to both
  2798. cuts = []
  2799. travels = []
  2800. for g in self.gcode_parsed:
  2801. if g['kind'][0] == 'C': cuts.append(g)
  2802. if g['kind'][0] == 'T': travels.append(g)
  2803. # Used to determine the overall board size
  2804. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  2805. # Convert the cuts and travels into single geometry objects we can render as svg xml
  2806. if travels:
  2807. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  2808. if cuts:
  2809. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  2810. # Render the SVG Xml
  2811. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  2812. # It's better to have the travels sitting underneath the cuts for visicut
  2813. svg_elem = ""
  2814. if travels:
  2815. svg_elem = travelsgeom.svg(scale_factor=scale_factor, stroke_color="#F0E24D")
  2816. if cuts:
  2817. svg_elem += cutsgeom.svg(scale_factor=scale_factor, stroke_color="#5E6CFF")
  2818. return svg_elem
  2819. # def get_bounds(geometry_set):
  2820. # xmin = Inf
  2821. # ymin = Inf
  2822. # xmax = -Inf
  2823. # ymax = -Inf
  2824. #
  2825. # #print "Getting bounds of:", str(geometry_set)
  2826. # for gs in geometry_set:
  2827. # try:
  2828. # gxmin, gymin, gxmax, gymax = geometry_set[gs].bounds()
  2829. # xmin = min([xmin, gxmin])
  2830. # ymin = min([ymin, gymin])
  2831. # xmax = max([xmax, gxmax])
  2832. # ymax = max([ymax, gymax])
  2833. # except:
  2834. # print "DEV WARNING: Tried to get bounds of empty geometry."
  2835. #
  2836. # return [xmin, ymin, xmax, ymax]
  2837. def get_bounds(geometry_list):
  2838. xmin = Inf
  2839. ymin = Inf
  2840. xmax = -Inf
  2841. ymax = -Inf
  2842. #print "Getting bounds of:", str(geometry_set)
  2843. for gs in geometry_list:
  2844. try:
  2845. gxmin, gymin, gxmax, gymax = gs.bounds()
  2846. xmin = min([xmin, gxmin])
  2847. ymin = min([ymin, gymin])
  2848. xmax = max([xmax, gxmax])
  2849. ymax = max([ymax, gymax])
  2850. except:
  2851. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  2852. return [xmin, ymin, xmax, ymax]
  2853. def arc(center, radius, start, stop, direction, steps_per_circ):
  2854. """
  2855. Creates a list of point along the specified arc.
  2856. :param center: Coordinates of the center [x, y]
  2857. :type center: list
  2858. :param radius: Radius of the arc.
  2859. :type radius: float
  2860. :param start: Starting angle in radians
  2861. :type start: float
  2862. :param stop: End angle in radians
  2863. :type stop: float
  2864. :param direction: Orientation of the arc, "CW" or "CCW"
  2865. :type direction: string
  2866. :param steps_per_circ: Number of straight line segments to
  2867. represent a circle.
  2868. :type steps_per_circ: int
  2869. :return: The desired arc, as list of tuples
  2870. :rtype: list
  2871. """
  2872. # TODO: Resolution should be established by maximum error from the exact arc.
  2873. da_sign = {"cw": -1.0, "ccw": 1.0}
  2874. points = []
  2875. if direction == "ccw" and stop <= start:
  2876. stop += 2 * pi
  2877. if direction == "cw" and stop >= start:
  2878. stop -= 2 * pi
  2879. angle = abs(stop - start)
  2880. #angle = stop-start
  2881. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  2882. delta_angle = da_sign[direction] * angle * 1.0 / steps
  2883. for i in range(steps + 1):
  2884. theta = start + delta_angle * i
  2885. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  2886. return points
  2887. def arc2(p1, p2, center, direction, steps_per_circ):
  2888. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  2889. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  2890. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  2891. return arc(center, r, start, stop, direction, steps_per_circ)
  2892. def arc_angle(start, stop, direction):
  2893. if direction == "ccw" and stop <= start:
  2894. stop += 2 * pi
  2895. if direction == "cw" and stop >= start:
  2896. stop -= 2 * pi
  2897. angle = abs(stop - start)
  2898. return angle
  2899. # def find_polygon(poly, point):
  2900. # """
  2901. # Find an object that object.contains(Point(point)) in
  2902. # poly, which can can be iterable, contain iterable of, or
  2903. # be itself an implementer of .contains().
  2904. #
  2905. # :param poly: See description
  2906. # :return: Polygon containing point or None.
  2907. # """
  2908. #
  2909. # if poly is None:
  2910. # return None
  2911. #
  2912. # try:
  2913. # for sub_poly in poly:
  2914. # p = find_polygon(sub_poly, point)
  2915. # if p is not None:
  2916. # return p
  2917. # except TypeError:
  2918. # try:
  2919. # if poly.contains(Point(point)):
  2920. # return poly
  2921. # except AttributeError:
  2922. # return None
  2923. #
  2924. # return None
  2925. def to_dict(obj):
  2926. """
  2927. Makes the following types into serializable form:
  2928. * ApertureMacro
  2929. * BaseGeometry
  2930. :param obj: Shapely geometry.
  2931. :type obj: BaseGeometry
  2932. :return: Dictionary with serializable form if ``obj`` was
  2933. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  2934. """
  2935. if isinstance(obj, ApertureMacro):
  2936. return {
  2937. "__class__": "ApertureMacro",
  2938. "__inst__": obj.to_dict()
  2939. }
  2940. if isinstance(obj, BaseGeometry):
  2941. return {
  2942. "__class__": "Shply",
  2943. "__inst__": sdumps(obj)
  2944. }
  2945. return obj
  2946. def dict2obj(d):
  2947. """
  2948. Default deserializer.
  2949. :param d: Serializable dictionary representation of an object
  2950. to be reconstructed.
  2951. :return: Reconstructed object.
  2952. """
  2953. if '__class__' in d and '__inst__' in d:
  2954. if d['__class__'] == "Shply":
  2955. return sloads(d['__inst__'])
  2956. if d['__class__'] == "ApertureMacro":
  2957. am = ApertureMacro()
  2958. am.from_dict(d['__inst__'])
  2959. return am
  2960. return d
  2961. else:
  2962. return d
  2963. def plotg(geo, solid_poly=False, color="black"):
  2964. try:
  2965. _ = iter(geo)
  2966. except:
  2967. geo = [geo]
  2968. for g in geo:
  2969. if type(g) == Polygon:
  2970. if solid_poly:
  2971. patch = PolygonPatch(g,
  2972. facecolor="#BBF268",
  2973. edgecolor="#006E20",
  2974. alpha=0.75,
  2975. zorder=2)
  2976. ax = subplot(111)
  2977. ax.add_patch(patch)
  2978. else:
  2979. x, y = g.exterior.coords.xy
  2980. plot(x, y, color=color)
  2981. for ints in g.interiors:
  2982. x, y = ints.coords.xy
  2983. plot(x, y, color=color)
  2984. continue
  2985. if type(g) == LineString or type(g) == LinearRing:
  2986. x, y = g.coords.xy
  2987. plot(x, y, color=color)
  2988. continue
  2989. if type(g) == Point:
  2990. x, y = g.coords.xy
  2991. plot(x, y, 'o')
  2992. continue
  2993. try:
  2994. _ = iter(g)
  2995. plotg(g, color=color)
  2996. except:
  2997. log.error("Cannot plot: " + str(type(g)))
  2998. continue
  2999. def parse_gerber_number(strnumber, frac_digits):
  3000. """
  3001. Parse a single number of Gerber coordinates.
  3002. :param strnumber: String containing a number in decimal digits
  3003. from a coordinate data block, possibly with a leading sign.
  3004. :type strnumber: str
  3005. :param frac_digits: Number of digits used for the fractional
  3006. part of the number
  3007. :type frac_digits: int
  3008. :return: The number in floating point.
  3009. :rtype: float
  3010. """
  3011. return int(strnumber) * (10 ** (-frac_digits))
  3012. # def voronoi(P):
  3013. # """
  3014. # Returns a list of all edges of the voronoi diagram for the given input points.
  3015. # """
  3016. # delauny = Delaunay(P)
  3017. # triangles = delauny.points[delauny.vertices]
  3018. #
  3019. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  3020. # long_lines_endpoints = []
  3021. #
  3022. # lineIndices = []
  3023. # for i, triangle in enumerate(triangles):
  3024. # circum_center = circum_centers[i]
  3025. # for j, neighbor in enumerate(delauny.neighbors[i]):
  3026. # if neighbor != -1:
  3027. # lineIndices.append((i, neighbor))
  3028. # else:
  3029. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  3030. # ps = np.array((ps[1], -ps[0]))
  3031. #
  3032. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  3033. # di = middle - triangle[j]
  3034. #
  3035. # ps /= np.linalg.norm(ps)
  3036. # di /= np.linalg.norm(di)
  3037. #
  3038. # if np.dot(di, ps) < 0.0:
  3039. # ps *= -1000.0
  3040. # else:
  3041. # ps *= 1000.0
  3042. #
  3043. # long_lines_endpoints.append(circum_center + ps)
  3044. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  3045. #
  3046. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  3047. #
  3048. # # filter out any duplicate lines
  3049. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  3050. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  3051. # lineIndicesUnique = np.unique(lineIndicesTupled)
  3052. #
  3053. # return vertices, lineIndicesUnique
  3054. #
  3055. #
  3056. # def triangle_csc(pts):
  3057. # rows, cols = pts.shape
  3058. #
  3059. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  3060. # [np.ones((1, rows)), np.zeros((1, 1))]])
  3061. #
  3062. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  3063. # x = np.linalg.solve(A,b)
  3064. # bary_coords = x[:-1]
  3065. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  3066. #
  3067. #
  3068. # def voronoi_cell_lines(points, vertices, lineIndices):
  3069. # """
  3070. # Returns a mapping from a voronoi cell to its edges.
  3071. #
  3072. # :param points: shape (m,2)
  3073. # :param vertices: shape (n,2)
  3074. # :param lineIndices: shape (o,2)
  3075. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  3076. # """
  3077. # kd = KDTree(points)
  3078. #
  3079. # cells = collections.defaultdict(list)
  3080. # for i1, i2 in lineIndices:
  3081. # v1, v2 = vertices[i1], vertices[i2]
  3082. # mid = (v1+v2)/2
  3083. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  3084. # cells[p1Idx].append((i1, i2))
  3085. # cells[p2Idx].append((i1, i2))
  3086. #
  3087. # return cells
  3088. #
  3089. #
  3090. # def voronoi_edges2polygons(cells):
  3091. # """
  3092. # Transforms cell edges into polygons.
  3093. #
  3094. # :param cells: as returned from voronoi_cell_lines
  3095. # :rtype: dict point index -> list of vertex indices which form a polygon
  3096. # """
  3097. #
  3098. # # first, close the outer cells
  3099. # for pIdx, lineIndices_ in cells.items():
  3100. # dangling_lines = []
  3101. # for i1, i2 in lineIndices_:
  3102. # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  3103. # assert 1 <= len(connections) <= 2
  3104. # if len(connections) == 1:
  3105. # dangling_lines.append((i1, i2))
  3106. # assert len(dangling_lines) in [0, 2]
  3107. # if len(dangling_lines) == 2:
  3108. # (i11, i12), (i21, i22) = dangling_lines
  3109. #
  3110. # # determine which line ends are unconnected
  3111. # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  3112. # i11Unconnected = len(connected) == 0
  3113. #
  3114. # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  3115. # i21Unconnected = len(connected) == 0
  3116. #
  3117. # startIdx = i11 if i11Unconnected else i12
  3118. # endIdx = i21 if i21Unconnected else i22
  3119. #
  3120. # cells[pIdx].append((startIdx, endIdx))
  3121. #
  3122. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  3123. # polys = dict()
  3124. # for pIdx, lineIndices_ in cells.items():
  3125. # # get a directed graph which contains both directions and arbitrarily follow one of both
  3126. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  3127. # directedGraphMap = collections.defaultdict(list)
  3128. # for (i1, i2) in directedGraph:
  3129. # directedGraphMap[i1].append(i2)
  3130. # orderedEdges = []
  3131. # currentEdge = directedGraph[0]
  3132. # while len(orderedEdges) < len(lineIndices_):
  3133. # i1 = currentEdge[1]
  3134. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  3135. # nextEdge = (i1, i2)
  3136. # orderedEdges.append(nextEdge)
  3137. # currentEdge = nextEdge
  3138. #
  3139. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  3140. #
  3141. # return polys
  3142. #
  3143. #
  3144. # def voronoi_polygons(points):
  3145. # """
  3146. # Returns the voronoi polygon for each input point.
  3147. #
  3148. # :param points: shape (n,2)
  3149. # :rtype: list of n polygons where each polygon is an array of vertices
  3150. # """
  3151. # vertices, lineIndices = voronoi(points)
  3152. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  3153. # polys = voronoi_edges2polygons(cells)
  3154. # polylist = []
  3155. # for i in xrange(len(points)):
  3156. # poly = vertices[np.asarray(polys[i])]
  3157. # polylist.append(poly)
  3158. # return polylist
  3159. #
  3160. #
  3161. # class Zprofile:
  3162. # def __init__(self):
  3163. #
  3164. # # data contains lists of [x, y, z]
  3165. # self.data = []
  3166. #
  3167. # # Computed voronoi polygons (shapely)
  3168. # self.polygons = []
  3169. # pass
  3170. #
  3171. # def plot_polygons(self):
  3172. # axes = plt.subplot(1, 1, 1)
  3173. #
  3174. # plt.axis([-0.05, 1.05, -0.05, 1.05])
  3175. #
  3176. # for poly in self.polygons:
  3177. # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  3178. # axes.add_patch(p)
  3179. #
  3180. # def init_from_csv(self, filename):
  3181. # pass
  3182. #
  3183. # def init_from_string(self, zpstring):
  3184. # pass
  3185. #
  3186. # def init_from_list(self, zplist):
  3187. # self.data = zplist
  3188. #
  3189. # def generate_polygons(self):
  3190. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  3191. #
  3192. # def normalize(self, origin):
  3193. # pass
  3194. #
  3195. # def paste(self, path):
  3196. # """
  3197. # Return a list of dictionaries containing the parts of the original
  3198. # path and their z-axis offset.
  3199. # """
  3200. #
  3201. # # At most one region/polygon will contain the path
  3202. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  3203. #
  3204. # if len(containing) > 0:
  3205. # return [{"path": path, "z": self.data[containing[0]][2]}]
  3206. #
  3207. # # All region indexes that intersect with the path
  3208. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  3209. #
  3210. # return [{"path": path.intersection(self.polygons[i]),
  3211. # "z": self.data[i][2]} for i in crossing]
  3212. def autolist(obj):
  3213. try:
  3214. _ = iter(obj)
  3215. return obj
  3216. except TypeError:
  3217. return [obj]
  3218. def three_point_circle(p1, p2, p3):
  3219. """
  3220. Computes the center and radius of a circle from
  3221. 3 points on its circumference.
  3222. :param p1: Point 1
  3223. :param p2: Point 2
  3224. :param p3: Point 3
  3225. :return: center, radius
  3226. """
  3227. # Midpoints
  3228. a1 = (p1 + p2) / 2.0
  3229. a2 = (p2 + p3) / 2.0
  3230. # Normals
  3231. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  3232. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  3233. # Params
  3234. T = solve(transpose(array([-b1, b2])), a1 - a2)
  3235. # Center
  3236. center = a1 + b1 * T[0]
  3237. # Radius
  3238. radius = norm(center - p1)
  3239. return center, radius, T[0]
  3240. def distance(pt1, pt2):
  3241. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  3242. class FlatCAMRTree(object):
  3243. """
  3244. Indexes geometry (Any object with "cooords" property containing
  3245. a list of tuples with x, y values). Objects are indexed by
  3246. all their points by default. To index by arbitrary points,
  3247. override self.points2obj.
  3248. """
  3249. def __init__(self):
  3250. # Python RTree Index
  3251. self.rti = rtindex.Index()
  3252. ## Track object-point relationship
  3253. # Each is list of points in object.
  3254. self.obj2points = []
  3255. # Index is index in rtree, value is index of
  3256. # object in obj2points.
  3257. self.points2obj = []
  3258. self.get_points = lambda go: go.coords
  3259. def grow_obj2points(self, idx):
  3260. """
  3261. Increases the size of self.obj2points to fit
  3262. idx + 1 items.
  3263. :param idx: Index to fit into list.
  3264. :return: None
  3265. """
  3266. if len(self.obj2points) > idx:
  3267. # len == 2, idx == 1, ok.
  3268. return
  3269. else:
  3270. # len == 2, idx == 2, need 1 more.
  3271. # range(2, 3)
  3272. for i in range(len(self.obj2points), idx + 1):
  3273. self.obj2points.append([])
  3274. def insert(self, objid, obj):
  3275. self.grow_obj2points(objid)
  3276. self.obj2points[objid] = []
  3277. for pt in self.get_points(obj):
  3278. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  3279. self.obj2points[objid].append(len(self.points2obj))
  3280. self.points2obj.append(objid)
  3281. def remove_obj(self, objid, obj):
  3282. # Use all ptids to delete from index
  3283. for i, pt in enumerate(self.get_points(obj)):
  3284. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  3285. def nearest(self, pt):
  3286. """
  3287. Will raise StopIteration if no items are found.
  3288. :param pt:
  3289. :return:
  3290. """
  3291. return self.rti.nearest(pt, objects=True).next()
  3292. class FlatCAMRTreeStorage(FlatCAMRTree):
  3293. """
  3294. Just like FlatCAMRTree it indexes geometry, but also serves
  3295. as storage for the geometry.
  3296. """
  3297. def __init__(self):
  3298. super(FlatCAMRTreeStorage, self).__init__()
  3299. self.objects = []
  3300. # Optimization attempt!
  3301. self.indexes = {}
  3302. def insert(self, obj):
  3303. self.objects.append(obj)
  3304. idx = len(self.objects) - 1
  3305. # Note: Shapely objects are not hashable any more, althought
  3306. # there seem to be plans to re-introduce the feature in
  3307. # version 2.0. For now, we will index using the object's id,
  3308. # but it's important to remember that shapely geometry is
  3309. # mutable, ie. it can be modified to a totally different shape
  3310. # and continue to have the same id.
  3311. # self.indexes[obj] = idx
  3312. self.indexes[id(obj)] = idx
  3313. super(FlatCAMRTreeStorage, self).insert(idx, obj)
  3314. #@profile
  3315. def remove(self, obj):
  3316. # See note about self.indexes in insert().
  3317. # objidx = self.indexes[obj]
  3318. objidx = self.indexes[id(obj)]
  3319. # Remove from list
  3320. self.objects[objidx] = None
  3321. # Remove from index
  3322. self.remove_obj(objidx, obj)
  3323. def get_objects(self):
  3324. return (o for o in self.objects if o is not None)
  3325. def nearest(self, pt):
  3326. """
  3327. Returns the nearest matching points and the object
  3328. it belongs to.
  3329. :param pt: Query point.
  3330. :return: (match_x, match_y), Object owner of
  3331. matching point.
  3332. :rtype: tuple
  3333. """
  3334. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  3335. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  3336. # class myO:
  3337. # def __init__(self, coords):
  3338. # self.coords = coords
  3339. #
  3340. #
  3341. # def test_rti():
  3342. #
  3343. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  3344. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  3345. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  3346. #
  3347. # os = [o1, o2]
  3348. #
  3349. # idx = FlatCAMRTree()
  3350. #
  3351. # for o in range(len(os)):
  3352. # idx.insert(o, os[o])
  3353. #
  3354. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3355. #
  3356. # idx.remove_obj(0, o1)
  3357. #
  3358. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3359. #
  3360. # idx.remove_obj(1, o2)
  3361. #
  3362. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3363. #
  3364. #
  3365. # def test_rtis():
  3366. #
  3367. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  3368. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  3369. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  3370. #
  3371. # os = [o1, o2]
  3372. #
  3373. # idx = FlatCAMRTreeStorage()
  3374. #
  3375. # for o in range(len(os)):
  3376. # idx.insert(os[o])
  3377. #
  3378. # #os = None
  3379. # #o1 = None
  3380. # #o2 = None
  3381. #
  3382. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3383. #
  3384. # idx.remove(idx.nearest((2,0))[1])
  3385. #
  3386. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  3387. #
  3388. # idx.remove(idx.nearest((0,0))[1])
  3389. #
  3390. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]