camlib.py 153 KB

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