camlib.py 135 KB

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