camlib.py 134 KB

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