camlib.py 136 KB

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