camlib.py 139 KB

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