camlib.py 137 KB

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