camlib.py 137 KB

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