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