camlib.py 227 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870
  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 PyQt5 import QtWidgets, QtCore
  9. from io import StringIO
  10. import numpy as np
  11. from numpy.linalg import solve, norm
  12. import platform
  13. from copy import deepcopy
  14. import traceback
  15. from decimal import Decimal
  16. from rtree import index as rtindex
  17. from lxml import etree as ET
  18. # See: http://toblerity.org/shapely/manual.html
  19. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString, MultiPoint, MultiPolygon
  20. from shapely.geometry import box as shply_box
  21. from shapely.ops import cascaded_union, unary_union, polygonize
  22. import shapely.affinity as affinity
  23. from shapely.wkt import loads as sloads
  24. from shapely.wkt import dumps as sdumps
  25. from shapely.geometry.base import BaseGeometry
  26. from shapely.geometry import shape
  27. # needed for legacy mode
  28. # Used for solid polygons in Matplotlib
  29. from descartes.patch import PolygonPatch
  30. import collections
  31. from collections import Iterable
  32. import rasterio
  33. from rasterio.features import shapes
  34. import ezdxf
  35. # TODO: Commented for FlatCAM packaging with cx_freeze
  36. # from scipy.spatial import KDTree, Delaunay
  37. # from scipy.spatial import Delaunay
  38. from flatcamParsers.ParseSVG import *
  39. from flatcamParsers.ParseDXF import *
  40. if platform.architecture()[0] == '64bit':
  41. from ortools.constraint_solver import pywrapcp
  42. from ortools.constraint_solver import routing_enums_pb2
  43. import logging
  44. import FlatCAMApp
  45. import gettext
  46. import FlatCAMTranslation as fcTranslate
  47. import builtins
  48. fcTranslate.apply_language('strings')
  49. log = logging.getLogger('base2')
  50. log.setLevel(logging.DEBUG)
  51. formatter = logging.Formatter('[%(levelname)s] %(message)s')
  52. handler = logging.StreamHandler()
  53. handler.setFormatter(formatter)
  54. log.addHandler(handler)
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. class ParseError(Exception):
  58. pass
  59. class ApertureMacro:
  60. """
  61. Syntax of aperture macros.
  62. <AM command>: AM<Aperture macro name>*<Macro content>
  63. <Macro content>: {{<Variable definition>*}{<Primitive>*}}
  64. <Variable definition>: $K=<Arithmetic expression>
  65. <Primitive>: <Primitive code>,<Modifier>{,<Modifier>}|<Comment>
  66. <Modifier>: $M|< Arithmetic expression>
  67. <Comment>: 0 <Text>
  68. """
  69. # ## Regular expressions
  70. am1_re = re.compile(r'^%AM([^\*]+)\*(.+)?(%)?$')
  71. am2_re = re.compile(r'(.*)%$')
  72. amcomm_re = re.compile(r'^0(.*)')
  73. amprim_re = re.compile(r'^[1-9].*')
  74. amvar_re = re.compile(r'^\$([0-9a-zA-z]+)=(.*)')
  75. def __init__(self, name=None):
  76. self.name = name
  77. self.raw = ""
  78. # ## These below are recomputed for every aperture
  79. # ## definition, in other words, are temporary variables.
  80. self.primitives = []
  81. self.locvars = {}
  82. self.geometry = None
  83. def to_dict(self):
  84. """
  85. Returns the object in a serializable form. Only the name and
  86. raw are required.
  87. :return: Dictionary representing the object. JSON ready.
  88. :rtype: dict
  89. """
  90. return {
  91. 'name': self.name,
  92. 'raw': self.raw
  93. }
  94. def from_dict(self, d):
  95. """
  96. Populates the object from a serial representation created
  97. with ``self.to_dict()``.
  98. :param d: Serial representation of an ApertureMacro object.
  99. :return: None
  100. """
  101. for attr in ['name', 'raw']:
  102. setattr(self, attr, d[attr])
  103. def parse_content(self):
  104. """
  105. Creates numerical lists for all primitives in the aperture
  106. macro (in ``self.raw``) by replacing all variables by their
  107. values iteratively and evaluating expressions. Results
  108. are stored in ``self.primitives``.
  109. :return: None
  110. """
  111. # Cleanup
  112. self.raw = self.raw.replace('\n', '').replace('\r', '').strip(" *")
  113. self.primitives = []
  114. # Separate parts
  115. parts = self.raw.split('*')
  116. # ### Every part in the macro ####
  117. for part in parts:
  118. # ## Comments. Ignored.
  119. match = ApertureMacro.amcomm_re.search(part)
  120. if match:
  121. continue
  122. # ## Variables
  123. # These are variables defined locally inside the macro. They can be
  124. # numerical constant or defined in terms of previously define
  125. # variables, which can be defined locally or in an aperture
  126. # definition. All replacements occur here.
  127. match = ApertureMacro.amvar_re.search(part)
  128. if match:
  129. var = match.group(1)
  130. val = match.group(2)
  131. # Replace variables in value
  132. for v in self.locvars:
  133. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  134. # val = re.sub((r'\$'+str(v)+r'(?![0-9a-zA-Z])'), str(self.locvars[v]), val)
  135. val = val.replace('$' + str(v), str(self.locvars[v]))
  136. # Make all others 0
  137. val = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", val)
  138. # Change x with *
  139. val = re.sub(r'[xX]', "*", val)
  140. # Eval() and store.
  141. self.locvars[var] = eval(val)
  142. continue
  143. # ## Primitives
  144. # Each is an array. The first identifies the primitive, while the
  145. # rest depend on the primitive. All are strings representing a
  146. # number and may contain variable definition. The values of these
  147. # variables are defined in an aperture definition.
  148. match = ApertureMacro.amprim_re.search(part)
  149. if match:
  150. # ## Replace all variables
  151. for v in self.locvars:
  152. # replaced the following line with the next to fix Mentor custom apertures not parsed OK
  153. # part = re.sub(r'\$' + str(v) + r'(?![0-9a-zA-Z])', str(self.locvars[v]), part)
  154. part = part.replace('$' + str(v), str(self.locvars[v]))
  155. # Make all others 0
  156. part = re.sub(r'\$[0-9a-zA-Z](?![0-9a-zA-Z])', "0", part)
  157. # Change x with *
  158. part = re.sub(r'[xX]', "*", part)
  159. # ## Store
  160. elements = part.split(",")
  161. self.primitives.append([eval(x) for x in elements])
  162. continue
  163. log.warning("Unknown syntax of aperture macro part: %s" % str(part))
  164. def append(self, data):
  165. """
  166. Appends a string to the raw macro.
  167. :param data: Part of the macro.
  168. :type data: str
  169. :return: None
  170. """
  171. self.raw += data
  172. @staticmethod
  173. def default2zero(n, mods):
  174. """
  175. Pads the ``mods`` list with zeros resulting in an
  176. list of length n.
  177. :param n: Length of the resulting list.
  178. :type n: int
  179. :param mods: List to be padded.
  180. :type mods: list
  181. :return: Zero-padded list.
  182. :rtype: list
  183. """
  184. x = [0.0] * n
  185. na = len(mods)
  186. x[0:na] = mods
  187. return x
  188. @staticmethod
  189. def make_circle(mods):
  190. """
  191. :param mods: (Exposure 0/1, Diameter >=0, X-coord, Y-coord)
  192. :return:
  193. """
  194. pol, dia, x, y = ApertureMacro.default2zero(4, mods)
  195. return {"pol": int(pol), "geometry": Point(x, y).buffer(dia/2)}
  196. @staticmethod
  197. def make_vectorline(mods):
  198. """
  199. :param mods: (Exposure 0/1, Line width >= 0, X-start, Y-start, X-end, Y-end,
  200. rotation angle around origin in degrees)
  201. :return:
  202. """
  203. pol, width, xs, ys, xe, ye, angle = ApertureMacro.default2zero(7, mods)
  204. line = LineString([(xs, ys), (xe, ye)])
  205. box = line.buffer(width/2, cap_style=2)
  206. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  207. return {"pol": int(pol), "geometry": box_rotated}
  208. @staticmethod
  209. def make_centerline(mods):
  210. """
  211. :param mods: (Exposure 0/1, width >=0, height >=0, x-center, y-center,
  212. rotation angle around origin in degrees)
  213. :return:
  214. """
  215. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  216. box = shply_box(x-width/2, y-height/2, x+width/2, y+height/2)
  217. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  218. return {"pol": int(pol), "geometry": box_rotated}
  219. @staticmethod
  220. def make_lowerleftline(mods):
  221. """
  222. :param mods: (exposure 0/1, width >=0, height >=0, x-lowerleft, y-lowerleft,
  223. rotation angle around origin in degrees)
  224. :return:
  225. """
  226. pol, width, height, x, y, angle = ApertureMacro.default2zero(6, mods)
  227. box = shply_box(x, y, x+width, y+height)
  228. box_rotated = affinity.rotate(box, angle, origin=(0, 0))
  229. return {"pol": int(pol), "geometry": box_rotated}
  230. @staticmethod
  231. def make_outline(mods):
  232. """
  233. :param mods:
  234. :return:
  235. """
  236. pol = mods[0]
  237. n = mods[1]
  238. points = [(0, 0)]*(n+1)
  239. for i in range(n+1):
  240. points[i] = mods[2*i + 2:2*i + 4]
  241. angle = mods[2*n + 4]
  242. poly = Polygon(points)
  243. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  244. return {"pol": int(pol), "geometry": poly_rotated}
  245. @staticmethod
  246. def make_polygon(mods):
  247. """
  248. Note: Specs indicate that rotation is only allowed if the center
  249. (x, y) == (0, 0). I will tolerate breaking this rule.
  250. :param mods: (exposure 0/1, n_verts 3<=n<=12, x-center, y-center,
  251. diameter of circumscribed circle >=0, rotation angle around origin)
  252. :return:
  253. """
  254. pol, nverts, x, y, dia, angle = ApertureMacro.default2zero(6, mods)
  255. points = [(0, 0)]*nverts
  256. for i in range(nverts):
  257. points[i] = (x + 0.5 * dia * np.cos(2*np.pi * i/nverts),
  258. y + 0.5 * dia * np.sin(2*np.pi * i/nverts))
  259. poly = Polygon(points)
  260. poly_rotated = affinity.rotate(poly, angle, origin=(0, 0))
  261. return {"pol": int(pol), "geometry": poly_rotated}
  262. @staticmethod
  263. def make_moire(mods):
  264. """
  265. Note: Specs indicate that rotation is only allowed if the center
  266. (x, y) == (0, 0). I will tolerate breaking this rule.
  267. :param mods: (x-center, y-center, outer_dia_outer_ring, ring thickness,
  268. gap, max_rings, crosshair_thickness, crosshair_len, rotation
  269. angle around origin in degrees)
  270. :return:
  271. """
  272. x, y, dia, thickness, gap, nrings, cross_th, cross_len, angle = ApertureMacro.default2zero(9, mods)
  273. r = dia/2 - thickness/2
  274. result = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  275. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0) # Need a copy!
  276. i = 1 # Number of rings created so far
  277. # ## If the ring does not have an interior it means that it is
  278. # ## a disk. Then stop.
  279. while len(ring.interiors) > 0 and i < nrings:
  280. r -= thickness + gap
  281. if r <= 0:
  282. break
  283. ring = Point((x, y)).buffer(r).exterior.buffer(thickness/2.0)
  284. result = cascaded_union([result, ring])
  285. i += 1
  286. # ## Crosshair
  287. hor = LineString([(x - cross_len, y), (x + cross_len, y)]).buffer(cross_th/2.0, cap_style=2)
  288. ver = LineString([(x, y-cross_len), (x, y + cross_len)]).buffer(cross_th/2.0, cap_style=2)
  289. result = cascaded_union([result, hor, ver])
  290. return {"pol": 1, "geometry": result}
  291. @staticmethod
  292. def make_thermal(mods):
  293. """
  294. Note: Specs indicate that rotation is only allowed if the center
  295. (x, y) == (0, 0). I will tolerate breaking this rule.
  296. :param mods: [x-center, y-center, diameter-outside, diameter-inside,
  297. gap-thickness, rotation angle around origin]
  298. :return:
  299. """
  300. x, y, dout, din, t, angle = ApertureMacro.default2zero(6, mods)
  301. ring = Point((x, y)).buffer(dout/2.0).difference(Point((x, y)).buffer(din/2.0))
  302. hline = LineString([(x - dout/2.0, y), (x + dout/2.0, y)]).buffer(t/2.0, cap_style=3)
  303. vline = LineString([(x, y - dout/2.0), (x, y + dout/2.0)]).buffer(t/2.0, cap_style=3)
  304. thermal = ring.difference(hline.union(vline))
  305. return {"pol": 1, "geometry": thermal}
  306. def make_geometry(self, modifiers):
  307. """
  308. Runs the macro for the given modifiers and generates
  309. the corresponding geometry.
  310. :param modifiers: Modifiers (parameters) for this macro
  311. :type modifiers: list
  312. :return: Shapely geometry
  313. :rtype: shapely.geometry.polygon
  314. """
  315. # ## Primitive makers
  316. makers = {
  317. "1": ApertureMacro.make_circle,
  318. "2": ApertureMacro.make_vectorline,
  319. "20": ApertureMacro.make_vectorline,
  320. "21": ApertureMacro.make_centerline,
  321. "22": ApertureMacro.make_lowerleftline,
  322. "4": ApertureMacro.make_outline,
  323. "5": ApertureMacro.make_polygon,
  324. "6": ApertureMacro.make_moire,
  325. "7": ApertureMacro.make_thermal
  326. }
  327. # ## Store modifiers as local variables
  328. modifiers = modifiers or []
  329. modifiers = [float(m) for m in modifiers]
  330. self.locvars = {}
  331. for i in range(0, len(modifiers)):
  332. self.locvars[str(i + 1)] = modifiers[i]
  333. # ## Parse
  334. self.primitives = [] # Cleanup
  335. self.geometry = Polygon()
  336. self.parse_content()
  337. # ## Make the geometry
  338. for primitive in self.primitives:
  339. # Make the primitive
  340. prim_geo = makers[str(int(primitive[0]))](primitive[1:])
  341. # Add it (according to polarity)
  342. # if self.geometry is None and prim_geo['pol'] == 1:
  343. # self.geometry = prim_geo['geometry']
  344. # continue
  345. if prim_geo['pol'] == 1:
  346. self.geometry = self.geometry.union(prim_geo['geometry'])
  347. continue
  348. if prim_geo['pol'] == 0:
  349. self.geometry = self.geometry.difference(prim_geo['geometry'])
  350. continue
  351. return self.geometry
  352. class Geometry(object):
  353. """
  354. Base geometry class.
  355. """
  356. defaults = {
  357. "units": 'in',
  358. "geo_steps_per_circle": 128
  359. }
  360. def __init__(self, geo_steps_per_circle=None):
  361. # Units (in or mm)
  362. self.units = self.app.defaults["units"]
  363. # Final geometry: MultiPolygon or list (of geometry constructs)
  364. self.solid_geometry = None
  365. # Final geometry: MultiLineString or list (of LineString or Points)
  366. self.follow_geometry = None
  367. # Attributes to be included in serialization
  368. self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry']
  369. # Flattened geometry (list of paths only)
  370. self.flat_geometry = []
  371. # this is the calculated conversion factor when the file units are different than the ones in the app
  372. self.file_units_factor = 1
  373. # Index
  374. self.index = None
  375. self.geo_steps_per_circle = geo_steps_per_circle
  376. # variables to display the percentage of work done
  377. self.geo_len = 0
  378. self.old_disp_number = 0
  379. self.el_count = 0
  380. if self.app.is_legacy is False:
  381. self.temp_shapes = self.app.plotcanvas.new_shape_group()
  382. else:
  383. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  384. self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
  385. def plot_temp_shapes(self, element, color='red'):
  386. try:
  387. for sub_el in element:
  388. self.plot_temp_shapes(sub_el)
  389. except TypeError: # Element is not iterable...
  390. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  391. self.temp_shapes.add(tolerance=float(self.app.defaults["global_tolerance"]),
  392. shape=element, color=color, visible=True, layer=0)
  393. def make_index(self):
  394. self.flatten()
  395. self.index = FlatCAMRTree()
  396. for i, g in enumerate(self.flat_geometry):
  397. self.index.insert(i, g)
  398. def add_circle(self, origin, radius):
  399. """
  400. Adds a circle to the object.
  401. :param origin: Center of the circle.
  402. :param radius: Radius of the circle.
  403. :return: None
  404. """
  405. if self.solid_geometry is None:
  406. self.solid_geometry = []
  407. if type(self.solid_geometry) is list:
  408. self.solid_geometry.append(Point(origin).buffer(
  409. radius, int(int(self.geo_steps_per_circle) / 4)))
  410. return
  411. try:
  412. self.solid_geometry = self.solid_geometry.union(Point(origin).buffer(
  413. radius, int(int(self.geo_steps_per_circle) / 4)))
  414. except Exception as e:
  415. log.error("Failed to run union on polygons. %s" % str(e))
  416. return
  417. def add_polygon(self, points):
  418. """
  419. Adds a polygon to the object (by union)
  420. :param points: The vertices of the polygon.
  421. :return: None
  422. """
  423. if self.solid_geometry is None:
  424. self.solid_geometry = []
  425. if type(self.solid_geometry) is list:
  426. self.solid_geometry.append(Polygon(points))
  427. return
  428. try:
  429. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  430. except Exception as e:
  431. log.error("Failed to run union on polygons. %s" % str(e))
  432. return
  433. def add_polyline(self, points):
  434. """
  435. Adds a polyline to the object (by union)
  436. :param points: The vertices of the polyline.
  437. :return: None
  438. """
  439. if self.solid_geometry is None:
  440. self.solid_geometry = []
  441. if type(self.solid_geometry) is list:
  442. self.solid_geometry.append(LineString(points))
  443. return
  444. try:
  445. self.solid_geometry = self.solid_geometry.union(LineString(points))
  446. except Exception as e:
  447. log.error("Failed to run union on polylines. %s" % str(e))
  448. return
  449. def is_empty(self):
  450. if isinstance(self.solid_geometry, BaseGeometry):
  451. return self.solid_geometry.is_empty
  452. if isinstance(self.solid_geometry, list):
  453. return len(self.solid_geometry) == 0
  454. self.app.inform.emit('[ERROR_NOTCL] %s' %
  455. _("self.solid_geometry is neither BaseGeometry or list."))
  456. return
  457. def subtract_polygon(self, points):
  458. """
  459. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  460. i.e. it converts polygons into paths.
  461. :param points: The vertices of the polygon.
  462. :return: none
  463. """
  464. if self.solid_geometry is None:
  465. self.solid_geometry = []
  466. # pathonly should be allways True, otherwise polygons are not subtracted
  467. flat_geometry = self.flatten(pathonly=True)
  468. log.debug("%d paths" % len(flat_geometry))
  469. polygon = Polygon(points)
  470. toolgeo = cascaded_union(polygon)
  471. diffs = []
  472. for target in flat_geometry:
  473. if type(target) == LineString or type(target) == LinearRing:
  474. diffs.append(target.difference(toolgeo))
  475. else:
  476. log.warning("Not implemented.")
  477. self.solid_geometry = cascaded_union(diffs)
  478. def bounds(self):
  479. """
  480. Returns coordinates of rectangular bounds
  481. of geometry: (xmin, ymin, xmax, ymax).
  482. """
  483. # fixed issue of getting bounds only for one level lists of objects
  484. # now it can get bounds for nested lists of objects
  485. log.debug("camlib.Geometry.bounds()")
  486. if self.solid_geometry is None:
  487. log.debug("solid_geometry is None")
  488. return 0, 0, 0, 0
  489. def bounds_rec(obj):
  490. if type(obj) is list:
  491. minx = np.Inf
  492. miny = np.Inf
  493. maxx = -np.Inf
  494. maxy = -np.Inf
  495. for k in obj:
  496. if type(k) is dict:
  497. for key in k:
  498. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  499. minx = min(minx, minx_)
  500. miny = min(miny, miny_)
  501. maxx = max(maxx, maxx_)
  502. maxy = max(maxy, maxy_)
  503. else:
  504. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  505. minx = min(minx, minx_)
  506. miny = min(miny, miny_)
  507. maxx = max(maxx, maxx_)
  508. maxy = max(maxy, maxy_)
  509. return minx, miny, maxx, maxy
  510. else:
  511. # it's a Shapely object, return it's bounds
  512. return obj.bounds
  513. if self.multigeo is True:
  514. minx_list = []
  515. miny_list = []
  516. maxx_list = []
  517. maxy_list = []
  518. for tool in self.tools:
  519. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  520. minx_list.append(minx)
  521. miny_list.append(miny)
  522. maxx_list.append(maxx)
  523. maxy_list.append(maxy)
  524. return(min(minx_list), min(miny_list), max(maxx_list), max(maxy_list))
  525. else:
  526. bounds_coords = bounds_rec(self.solid_geometry)
  527. return bounds_coords
  528. # try:
  529. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  530. # def flatten(l, ltypes=(list, tuple)):
  531. # ltype = type(l)
  532. # l = list(l)
  533. # i = 0
  534. # while i < len(l):
  535. # while isinstance(l[i], ltypes):
  536. # if not l[i]:
  537. # l.pop(i)
  538. # i -= 1
  539. # break
  540. # else:
  541. # l[i:i + 1] = l[i]
  542. # i += 1
  543. # return ltype(l)
  544. #
  545. # log.debug("Geometry->bounds()")
  546. # if self.solid_geometry is None:
  547. # log.debug("solid_geometry is None")
  548. # return 0, 0, 0, 0
  549. #
  550. # if type(self.solid_geometry) is list:
  551. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  552. # if len(self.solid_geometry) == 0:
  553. # log.debug('solid_geometry is empty []')
  554. # return 0, 0, 0, 0
  555. # return cascaded_union(flatten(self.solid_geometry)).bounds
  556. # else:
  557. # return self.solid_geometry.bounds
  558. # except Exception as e:
  559. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  560. # log.debug("Geometry->bounds()")
  561. # if self.solid_geometry is None:
  562. # log.debug("solid_geometry is None")
  563. # return 0, 0, 0, 0
  564. #
  565. # if type(self.solid_geometry) is list:
  566. # # TODO: This can be done faster. See comment from Shapely mailing lists.
  567. # if len(self.solid_geometry) == 0:
  568. # log.debug('solid_geometry is empty []')
  569. # return 0, 0, 0, 0
  570. # return cascaded_union(self.solid_geometry).bounds
  571. # else:
  572. # return self.solid_geometry.bounds
  573. def find_polygon(self, point, geoset=None):
  574. """
  575. Find an object that object.contains(Point(point)) in
  576. poly, which can can be iterable, contain iterable of, or
  577. be itself an implementer of .contains().
  578. :param point: See description
  579. :param geoset: a polygon or list of polygons where to find if the param point is contained
  580. :return: Polygon containing point or None.
  581. """
  582. if geoset is None:
  583. geoset = self.solid_geometry
  584. try: # Iterable
  585. for sub_geo in geoset:
  586. p = self.find_polygon(point, geoset=sub_geo)
  587. if p is not None:
  588. return p
  589. except TypeError: # Non-iterable
  590. try: # Implements .contains()
  591. if isinstance(geoset, LinearRing):
  592. geoset = Polygon(geoset)
  593. if geoset.contains(Point(point)):
  594. return geoset
  595. except AttributeError: # Does not implement .contains()
  596. return None
  597. return None
  598. def get_interiors(self, geometry=None):
  599. interiors = []
  600. if geometry is None:
  601. geometry = self.solid_geometry
  602. # ## If iterable, expand recursively.
  603. try:
  604. for geo in geometry:
  605. interiors.extend(self.get_interiors(geometry=geo))
  606. # ## Not iterable, get the interiors if polygon.
  607. except TypeError:
  608. if type(geometry) == Polygon:
  609. interiors.extend(geometry.interiors)
  610. return interiors
  611. def get_exteriors(self, geometry=None):
  612. """
  613. Returns all exteriors of polygons in geometry. Uses
  614. ``self.solid_geometry`` if geometry is not provided.
  615. :param geometry: Shapely type or list or list of list of such.
  616. :return: List of paths constituting the exteriors
  617. of polygons in geometry.
  618. """
  619. exteriors = []
  620. if geometry is None:
  621. geometry = self.solid_geometry
  622. # ## If iterable, expand recursively.
  623. try:
  624. for geo in geometry:
  625. exteriors.extend(self.get_exteriors(geometry=geo))
  626. # ## Not iterable, get the exterior if polygon.
  627. except TypeError:
  628. if type(geometry) == Polygon:
  629. exteriors.append(geometry.exterior)
  630. return exteriors
  631. def flatten(self, geometry=None, reset=True, pathonly=False):
  632. """
  633. Creates a list of non-iterable linear geometry objects.
  634. Polygons are expanded into its exterior and interiors if specified.
  635. Results are placed in self.flat_geometry
  636. :param geometry: Shapely type or list or list of list of such.
  637. :param reset: Clears the contents of self.flat_geometry.
  638. :param pathonly: Expands polygons into linear elements.
  639. """
  640. if geometry is None:
  641. geometry = self.solid_geometry
  642. if reset:
  643. self.flat_geometry = []
  644. # ## If iterable, expand recursively.
  645. try:
  646. for geo in geometry:
  647. if geo is not None:
  648. self.flatten(geometry=geo,
  649. reset=False,
  650. pathonly=pathonly)
  651. # ## Not iterable, do the actual indexing and add.
  652. except TypeError:
  653. if pathonly and type(geometry) == Polygon:
  654. self.flat_geometry.append(geometry.exterior)
  655. self.flatten(geometry=geometry.interiors,
  656. reset=False,
  657. pathonly=True)
  658. else:
  659. self.flat_geometry.append(geometry)
  660. return self.flat_geometry
  661. # def make2Dstorage(self):
  662. #
  663. # self.flatten()
  664. #
  665. # def get_pts(o):
  666. # pts = []
  667. # if type(o) == Polygon:
  668. # g = o.exterior
  669. # pts += list(g.coords)
  670. # for i in o.interiors:
  671. # pts += list(i.coords)
  672. # else:
  673. # pts += list(o.coords)
  674. # return pts
  675. #
  676. # storage = FlatCAMRTreeStorage()
  677. # storage.get_points = get_pts
  678. # for shape in self.flat_geometry:
  679. # storage.insert(shape)
  680. # return storage
  681. # def flatten_to_paths(self, geometry=None, reset=True):
  682. # """
  683. # Creates a list of non-iterable linear geometry elements and
  684. # indexes them in rtree.
  685. #
  686. # :param geometry: Iterable geometry
  687. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  688. # :return: self.flat_geometry, self.flat_geometry_rtree
  689. # """
  690. #
  691. # if geometry is None:
  692. # geometry = self.solid_geometry
  693. #
  694. # if reset:
  695. # self.flat_geometry = []
  696. #
  697. # # ## If iterable, expand recursively.
  698. # try:
  699. # for geo in geometry:
  700. # self.flatten_to_paths(geometry=geo, reset=False)
  701. #
  702. # # ## Not iterable, do the actual indexing and add.
  703. # except TypeError:
  704. # if type(geometry) == Polygon:
  705. # g = geometry.exterior
  706. # self.flat_geometry.append(g)
  707. #
  708. # # ## Add first and last points of the path to the index.
  709. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  710. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  711. #
  712. # for interior in geometry.interiors:
  713. # g = interior
  714. # self.flat_geometry.append(g)
  715. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  716. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  717. # else:
  718. # g = geometry
  719. # self.flat_geometry.append(g)
  720. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  721. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  722. #
  723. # return self.flat_geometry, self.flat_geometry_rtree
  724. def isolation_geometry(self, offset, geometry=None, iso_type=2, corner=None, follow=None, passes=0):
  725. """
  726. Creates contours around geometry at a given
  727. offset distance.
  728. :param offset: Offset distance.
  729. :type offset: float
  730. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  731. :param corner: type of corner for the isolation: 0 = round; 1 = square; 2= beveled (line that connects the ends)
  732. :param follow: whether the geometry to be isolated is a follow_geometry
  733. :param passes: current pass out of possible multiple passes for which the isolation is done
  734. :return: The buffered geometry.
  735. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  736. """
  737. if self.app.abort_flag:
  738. # graceful abort requested by the user
  739. raise FlatCAMApp.GracefulException
  740. geo_iso = list()
  741. if follow:
  742. return geometry
  743. if geometry:
  744. working_geo = geometry
  745. else:
  746. working_geo = self.solid_geometry
  747. try:
  748. geo_len = len(working_geo)
  749. except TypeError:
  750. geo_len = 1
  751. old_disp_number = 0
  752. pol_nr = 0
  753. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  754. try:
  755. for pol in working_geo:
  756. if self.app.abort_flag:
  757. # graceful abort requested by the user
  758. raise FlatCAMApp.GracefulException
  759. if offset == 0:
  760. geo_iso.append(pol)
  761. else:
  762. corner_type = 1 if corner is None else corner
  763. geo_iso.append(pol.buffer(offset, int(int(self.geo_steps_per_circle) / 4), join_style=corner_type))
  764. pol_nr += 1
  765. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  766. if old_disp_number < disp_number <= 100:
  767. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  768. (_("Pass"), int(passes + 1), int(disp_number)))
  769. old_disp_number = disp_number
  770. except TypeError:
  771. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  772. # MultiPolygon (not an iterable)
  773. if offset == 0:
  774. geo_iso.append(working_geo)
  775. else:
  776. corner_type = 1 if corner is None else corner
  777. geo_iso.append(working_geo.buffer(offset, int(int(self.geo_steps_per_circle) / 4),
  778. join_style=corner_type))
  779. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  780. geo_iso = unary_union(geo_iso)
  781. self.app.proc_container.update_view_text('')
  782. # end of replaced block
  783. if iso_type == 2:
  784. return geo_iso
  785. elif iso_type == 0:
  786. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  787. return self.get_exteriors(geo_iso)
  788. elif iso_type == 1:
  789. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  790. return self.get_interiors(geo_iso)
  791. else:
  792. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  793. return "fail"
  794. def flatten_list(self, list):
  795. for item in list:
  796. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  797. yield from self.flatten_list(item)
  798. else:
  799. yield item
  800. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  801. """
  802. Imports shapes from an SVG file into the object's geometry.
  803. :param filename: Path to the SVG file.
  804. :type filename: str
  805. :param object_type: parameter passed further along
  806. :param flip: Flip the vertically.
  807. :type flip: bool
  808. :param units: FlatCAM units
  809. :return: None
  810. """
  811. log.debug("camlib.Geometry.import_svg()")
  812. # Parse into list of shapely objects
  813. svg_tree = ET.parse(filename)
  814. svg_root = svg_tree.getroot()
  815. # Change origin to bottom left
  816. # h = float(svg_root.get('height'))
  817. # w = float(svg_root.get('width'))
  818. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  819. geos = getsvggeo(svg_root, object_type)
  820. if flip:
  821. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  822. # Add to object
  823. if self.solid_geometry is None:
  824. self.solid_geometry = []
  825. if type(self.solid_geometry) is list:
  826. # self.solid_geometry.append(cascaded_union(geos))
  827. if type(geos) is list:
  828. self.solid_geometry += geos
  829. else:
  830. self.solid_geometry.append(geos)
  831. else: # It's shapely geometry
  832. # self.solid_geometry = cascaded_union([self.solid_geometry,
  833. # cascaded_union(geos)])
  834. self.solid_geometry = [self.solid_geometry, geos]
  835. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  836. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  837. geos_text = getsvgtext(svg_root, object_type, units=units)
  838. if geos_text is not None:
  839. geos_text_f = []
  840. if flip:
  841. # Change origin to bottom left
  842. for i in geos_text:
  843. _, minimy, _, maximy = i.bounds
  844. h2 = (maximy - minimy) * 0.5
  845. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  846. if geos_text_f:
  847. self.solid_geometry = self.solid_geometry + geos_text_f
  848. def import_dxf(self, filename, object_type=None, units='MM'):
  849. """
  850. Imports shapes from an DXF file into the object's geometry.
  851. :param filename: Path to the DXF file.
  852. :type filename: str
  853. :param units: Application units
  854. :type flip: str
  855. :return: None
  856. """
  857. # Parse into list of shapely objects
  858. dxf = ezdxf.readfile(filename)
  859. geos = getdxfgeo(dxf)
  860. # Add to object
  861. if self.solid_geometry is None:
  862. self.solid_geometry = []
  863. if type(self.solid_geometry) is list:
  864. if type(geos) is list:
  865. self.solid_geometry += geos
  866. else:
  867. self.solid_geometry.append(geos)
  868. else: # It's shapely geometry
  869. self.solid_geometry = [self.solid_geometry, geos]
  870. # flatten the self.solid_geometry list for import_dxf() to import DXF as Gerber
  871. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  872. if self.solid_geometry is not None:
  873. self.solid_geometry = cascaded_union(self.solid_geometry)
  874. else:
  875. return
  876. # commented until this function is ready
  877. # geos_text = getdxftext(dxf, object_type, units=units)
  878. # if geos_text is not None:
  879. # geos_text_f = []
  880. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  881. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=[128, 128, 128, 128]):
  882. """
  883. Imports shapes from an IMAGE file into the object's geometry.
  884. :param filename: Path to the IMAGE file.
  885. :type filename: str
  886. :param flip: Flip the object vertically.
  887. :type flip: bool
  888. :param units: FlatCAM units
  889. :param dpi: dots per inch on the imported image
  890. :param mode: how to import the image: as 'black' or 'color'
  891. :param mask: level of detail for the import
  892. :return: None
  893. """
  894. scale_factor = 0.264583333
  895. if units.lower() == 'mm':
  896. scale_factor = 25.4 / dpi
  897. else:
  898. scale_factor = 1 / dpi
  899. geos = []
  900. unscaled_geos = []
  901. with rasterio.open(filename) as src:
  902. # if filename.lower().rpartition('.')[-1] == 'bmp':
  903. # red = green = blue = src.read(1)
  904. # print("BMP")
  905. # elif filename.lower().rpartition('.')[-1] == 'png':
  906. # red, green, blue, alpha = src.read()
  907. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  908. # red, green, blue = src.read()
  909. red = green = blue = src.read(1)
  910. try:
  911. green = src.read(2)
  912. except Exception:
  913. pass
  914. try:
  915. blue = src.read(3)
  916. except Exception:
  917. pass
  918. if mode == 'black':
  919. mask_setting = red <= mask[0]
  920. total = red
  921. log.debug("Image import as monochrome.")
  922. else:
  923. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  924. total = np.zeros(red.shape, dtype=np.float32)
  925. for band in red, green, blue:
  926. total += band
  927. total /= 3
  928. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  929. (str(mask[1]), str(mask[2]), str(mask[3])))
  930. for geom, val in shapes(total, mask=mask_setting):
  931. unscaled_geos.append(shape(geom))
  932. for g in unscaled_geos:
  933. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  934. if flip:
  935. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  936. # Add to object
  937. if self.solid_geometry is None:
  938. self.solid_geometry = []
  939. if type(self.solid_geometry) is list:
  940. # self.solid_geometry.append(cascaded_union(geos))
  941. if type(geos) is list:
  942. self.solid_geometry += geos
  943. else:
  944. self.solid_geometry.append(geos)
  945. else: # It's shapely geometry
  946. self.solid_geometry = [self.solid_geometry, geos]
  947. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  948. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  949. self.solid_geometry = cascaded_union(self.solid_geometry)
  950. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  951. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  952. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  953. def size(self):
  954. """
  955. Returns (width, height) of rectangular
  956. bounds of geometry.
  957. """
  958. if self.solid_geometry is None:
  959. log.warning("Solid_geometry not computed yet.")
  960. return 0
  961. bounds = self.bounds()
  962. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  963. def get_empty_area(self, boundary=None):
  964. """
  965. Returns the complement of self.solid_geometry within
  966. the given boundary polygon. If not specified, it defaults to
  967. the rectangular bounding box of self.solid_geometry.
  968. """
  969. if boundary is None:
  970. boundary = self.solid_geometry.envelope
  971. return boundary.difference(self.solid_geometry)
  972. def clear_polygon(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  973. prog_plot=False):
  974. """
  975. Creates geometry inside a polygon for a tool to cover
  976. the whole area.
  977. This algorithm shrinks the edges of the polygon and takes
  978. the resulting edges as toolpaths.
  979. :param polygon: Polygon to clear.
  980. :param tooldia: Diameter of the tool.
  981. :param steps_per_circle: number of linear segments to be used to approximate a circle
  982. :param overlap: Overlap of toolpasses.
  983. :param connect: Draw lines between disjoint segments to
  984. minimize tool lifts.
  985. :param contour: Paint around the edges. Inconsequential in
  986. this painting method.
  987. :param prog_plot: boolean; if Ture use the progressive plotting
  988. :return:
  989. """
  990. # log.debug("camlib.clear_polygon()")
  991. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  992. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  993. # ## The toolpaths
  994. # Index first and last points in paths
  995. def get_pts(o):
  996. return [o.coords[0], o.coords[-1]]
  997. geoms = FlatCAMRTreeStorage()
  998. geoms.get_points = get_pts
  999. # Can only result in a Polygon or MultiPolygon
  1000. # NOTE: The resulting polygon can be "empty".
  1001. current = polygon.buffer((-tooldia / 1.999999), int(int(steps_per_circle) / 4))
  1002. if current.area == 0:
  1003. # Otherwise, trying to to insert current.exterior == None
  1004. # into the FlatCAMStorage will fail.
  1005. # print("Area is None")
  1006. return None
  1007. # current can be a MultiPolygon
  1008. try:
  1009. for p in current:
  1010. geoms.insert(p.exterior)
  1011. for i in p.interiors:
  1012. geoms.insert(i)
  1013. # Not a Multipolygon. Must be a Polygon
  1014. except TypeError:
  1015. geoms.insert(current.exterior)
  1016. for i in current.interiors:
  1017. geoms.insert(i)
  1018. while True:
  1019. if self.app.abort_flag:
  1020. # graceful abort requested by the user
  1021. raise FlatCAMApp.GracefulException
  1022. # provide the app with a way to process the GUI events when in a blocking loop
  1023. QtWidgets.QApplication.processEvents()
  1024. # Can only result in a Polygon or MultiPolygon
  1025. current = current.buffer(-tooldia * (1 - overlap), int(int(steps_per_circle) / 4))
  1026. if current.area > 0:
  1027. # current can be a MultiPolygon
  1028. try:
  1029. for p in current:
  1030. geoms.insert(p.exterior)
  1031. for i in p.interiors:
  1032. geoms.insert(i)
  1033. if prog_plot:
  1034. self.plot_temp_shapes(p)
  1035. # Not a Multipolygon. Must be a Polygon
  1036. except TypeError:
  1037. geoms.insert(current.exterior)
  1038. if prog_plot:
  1039. self.plot_temp_shapes(current.exterior)
  1040. for i in current.interiors:
  1041. geoms.insert(i)
  1042. if prog_plot:
  1043. self.plot_temp_shapes(i)
  1044. else:
  1045. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  1046. break
  1047. if prog_plot:
  1048. self.temp_shapes.redraw()
  1049. # Optimization: Reduce lifts
  1050. if connect:
  1051. # log.debug("Reducing tool lifts...")
  1052. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  1053. return geoms
  1054. def clear_polygon2(self, polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  1055. connect=True, contour=True, prog_plot=False):
  1056. """
  1057. Creates geometry inside a polygon for a tool to cover
  1058. the whole area.
  1059. This algorithm starts with a seed point inside the polygon
  1060. and draws circles around it. Arcs inside the polygons are
  1061. valid cuts. Finalizes by cutting around the inside edge of
  1062. the polygon.
  1063. :param polygon_to_clear: Shapely.geometry.Polygon
  1064. :param steps_per_circle: how many linear segments to use to approximate a circle
  1065. :param tooldia: Diameter of the tool
  1066. :param seedpoint: Shapely.geometry.Point or None
  1067. :param overlap: Tool fraction overlap bewteen passes
  1068. :param connect: Connect disjoint segment to minumize tool lifts
  1069. :param contour: Cut countour inside the polygon.
  1070. :return: List of toolpaths covering polygon.
  1071. :rtype: FlatCAMRTreeStorage | None
  1072. :param prog_plot: boolean; if True use the progressive plotting
  1073. """
  1074. # log.debug("camlib.clear_polygon2()")
  1075. # Current buffer radius
  1076. radius = tooldia / 2 * (1 - overlap)
  1077. # ## The toolpaths
  1078. # Index first and last points in paths
  1079. def get_pts(o):
  1080. return [o.coords[0], o.coords[-1]]
  1081. geoms = FlatCAMRTreeStorage()
  1082. geoms.get_points = get_pts
  1083. # Path margin
  1084. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))
  1085. if path_margin.is_empty or path_margin is None:
  1086. return
  1087. # Estimate good seedpoint if not provided.
  1088. if seedpoint is None:
  1089. seedpoint = path_margin.representative_point()
  1090. # Grow from seed until outside the box. The polygons will
  1091. # never have an interior, so take the exterior LinearRing.
  1092. while True:
  1093. if self.app.abort_flag:
  1094. # graceful abort requested by the user
  1095. raise FlatCAMApp.GracefulException
  1096. # provide the app with a way to process the GUI events when in a blocking loop
  1097. QtWidgets.QApplication.processEvents()
  1098. path = Point(seedpoint).buffer(radius, int(steps_per_circle / 4)).exterior
  1099. path = path.intersection(path_margin)
  1100. # Touches polygon?
  1101. if path.is_empty:
  1102. break
  1103. else:
  1104. # geoms.append(path)
  1105. # geoms.insert(path)
  1106. # path can be a collection of paths.
  1107. try:
  1108. for p in path:
  1109. geoms.insert(p)
  1110. if prog_plot:
  1111. self.plot_temp_shapes(p)
  1112. except TypeError:
  1113. geoms.insert(path)
  1114. if prog_plot:
  1115. self.plot_temp_shapes(path)
  1116. if prog_plot:
  1117. self.temp_shapes.redraw()
  1118. radius += tooldia * (1 - overlap)
  1119. # Clean inside edges (contours) of the original polygon
  1120. if contour:
  1121. outer_edges = [x.exterior for x in autolist(
  1122. polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4)))]
  1123. inner_edges = []
  1124. # Over resulting polygons
  1125. for x in autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle / 4))):
  1126. for y in x.interiors: # Over interiors of each polygon
  1127. inner_edges.append(y)
  1128. # geoms += outer_edges + inner_edges
  1129. for g in outer_edges + inner_edges:
  1130. geoms.insert(g)
  1131. if prog_plot:
  1132. self.plot_temp_shapes(g)
  1133. if prog_plot:
  1134. self.temp_shapes.redraw()
  1135. # Optimization connect touching paths
  1136. # log.debug("Connecting paths...")
  1137. # geoms = Geometry.path_connect(geoms)
  1138. # Optimization: Reduce lifts
  1139. if connect:
  1140. # log.debug("Reducing tool lifts...")
  1141. geoms = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  1142. return geoms
  1143. def clear_polygon3(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1144. prog_plot=False):
  1145. """
  1146. Creates geometry inside a polygon for a tool to cover
  1147. the whole area.
  1148. This algorithm draws horizontal lines inside the polygon.
  1149. :param polygon: The polygon being painted.
  1150. :type polygon: shapely.geometry.Polygon
  1151. :param tooldia: Tool diameter.
  1152. :param steps_per_circle: how many linear segments to use to approximate a circle
  1153. :param overlap: Tool path overlap percentage.
  1154. :param connect: Connect lines to avoid tool lifts.
  1155. :param contour: Paint around the edges.
  1156. :param prog_plot: boolean; if to use the progressive plotting
  1157. :return:
  1158. """
  1159. # log.debug("camlib.clear_polygon3()")
  1160. # ## The toolpaths
  1161. # Index first and last points in paths
  1162. def get_pts(o):
  1163. return [o.coords[0], o.coords[-1]]
  1164. geoms = FlatCAMRTreeStorage()
  1165. geoms.get_points = get_pts
  1166. lines_trimmed = []
  1167. # Bounding box
  1168. left, bot, right, top = polygon.bounds
  1169. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1170. # First line
  1171. y = top - tooldia / 1.99999999
  1172. while y > bot + tooldia / 1.999999999:
  1173. if self.app.abort_flag:
  1174. # graceful abort requested by the user
  1175. raise FlatCAMApp.GracefulException
  1176. # provide the app with a way to process the GUI events when in a blocking loop
  1177. QtWidgets.QApplication.processEvents()
  1178. line = LineString([(left, y), (right, y)])
  1179. line = line.intersection(margin_poly)
  1180. lines_trimmed.append(line)
  1181. y -= tooldia * (1 - overlap)
  1182. if prog_plot:
  1183. self.plot_temp_shapes(line)
  1184. self.temp_shapes.redraw()
  1185. # Last line
  1186. y = bot + tooldia / 2
  1187. line = LineString([(left, y), (right, y)])
  1188. line = line.intersection(margin_poly)
  1189. for ll in line:
  1190. lines_trimmed.append(ll)
  1191. if prog_plot:
  1192. self.plot_temp_shapes(line)
  1193. # Combine
  1194. # linesgeo = unary_union(lines)
  1195. # Trim to the polygon
  1196. # margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1197. # lines_trimmed = linesgeo.intersection(margin_poly)
  1198. if prog_plot:
  1199. self.temp_shapes.redraw()
  1200. lines_trimmed = unary_union(lines_trimmed)
  1201. # Add lines to storage
  1202. try:
  1203. for line in lines_trimmed:
  1204. geoms.insert(line)
  1205. except TypeError:
  1206. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1207. geoms.insert(lines_trimmed)
  1208. # Add margin (contour) to storage
  1209. if contour:
  1210. if isinstance(margin_poly, Polygon):
  1211. geoms.insert(margin_poly.exterior)
  1212. if prog_plot:
  1213. self.plot_temp_shapes(margin_poly.exterior)
  1214. for ints in margin_poly.interiors:
  1215. geoms.insert(ints)
  1216. if prog_plot:
  1217. self.plot_temp_shapes(ints)
  1218. elif isinstance(margin_poly, MultiPolygon):
  1219. for poly in margin_poly:
  1220. geoms.insert(poly.exterior)
  1221. if prog_plot:
  1222. self.plot_temp_shapes(poly.exterior)
  1223. for ints in poly.interiors:
  1224. geoms.insert(ints)
  1225. if prog_plot:
  1226. self.plot_temp_shapes(ints)
  1227. if prog_plot:
  1228. self.temp_shapes.redraw()
  1229. # Optimization: Reduce lifts
  1230. if connect:
  1231. # log.debug("Reducing tool lifts...")
  1232. geoms = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1233. return geoms
  1234. def scale(self, xfactor, yfactor, point=None):
  1235. """
  1236. Scales all of the object's geometry by a given factor. Override
  1237. this method.
  1238. :param xfactor: Number by which to scale on X axis.
  1239. :type xfactor: float
  1240. :param yfactor: Number by which to scale on Y axis.
  1241. :type yfactor: float
  1242. :param point: point to be used as reference for scaling; a tuple
  1243. :return: None
  1244. :rtype: None
  1245. """
  1246. return
  1247. def offset(self, vect):
  1248. """
  1249. Offset the geometry by the given vector. Override this method.
  1250. :param vect: (x, y) vector by which to offset the object.
  1251. :type vect: tuple
  1252. :return: None
  1253. """
  1254. return
  1255. @staticmethod
  1256. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  1257. """
  1258. Connects paths that results in a connection segment that is
  1259. within the paint area. This avoids unnecessary tool lifting.
  1260. :param storage: Geometry to be optimized.
  1261. :type storage: FlatCAMRTreeStorage
  1262. :param boundary: Polygon defining the limits of the paintable area.
  1263. :type boundary: Polygon
  1264. :param tooldia: Tool diameter.
  1265. :rtype tooldia: float
  1266. :param steps_per_circle: how many linear segments to use to approximate a circle
  1267. :param max_walk: Maximum allowable distance without lifting tool.
  1268. :type max_walk: float or None
  1269. :return: Optimized geometry.
  1270. :rtype: FlatCAMRTreeStorage
  1271. """
  1272. # If max_walk is not specified, the maximum allowed is
  1273. # 10 times the tool diameter
  1274. max_walk = max_walk or 10 * tooldia
  1275. # Assuming geolist is a flat list of flat elements
  1276. # ## Index first and last points in paths
  1277. def get_pts(o):
  1278. return [o.coords[0], o.coords[-1]]
  1279. # storage = FlatCAMRTreeStorage()
  1280. # storage.get_points = get_pts
  1281. #
  1282. # for shape in geolist:
  1283. # if shape is not None: # TODO: This shouldn't have happened.
  1284. # # Make LlinearRings into linestrings otherwise
  1285. # # When chaining the coordinates path is messed up.
  1286. # storage.insert(LineString(shape))
  1287. # #storage.insert(shape)
  1288. # ## Iterate over geometry paths getting the nearest each time.
  1289. #optimized_paths = []
  1290. optimized_paths = FlatCAMRTreeStorage()
  1291. optimized_paths.get_points = get_pts
  1292. path_count = 0
  1293. current_pt = (0, 0)
  1294. pt, geo = storage.nearest(current_pt)
  1295. storage.remove(geo)
  1296. geo = LineString(geo)
  1297. current_pt = geo.coords[-1]
  1298. try:
  1299. while True:
  1300. path_count += 1
  1301. # log.debug("Path %d" % path_count)
  1302. pt, candidate = storage.nearest(current_pt)
  1303. storage.remove(candidate)
  1304. candidate = LineString(candidate)
  1305. # If last point in geometry is the nearest
  1306. # then reverse coordinates.
  1307. # but prefer the first one if last == first
  1308. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  1309. candidate.coords = list(candidate.coords)[::-1]
  1310. # Straight line from current_pt to pt.
  1311. # Is the toolpath inside the geometry?
  1312. walk_path = LineString([current_pt, pt])
  1313. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle / 4))
  1314. if walk_cut.within(boundary) and walk_path.length < max_walk:
  1315. # log.debug("Walk to path #%d is inside. Joining." % path_count)
  1316. # Completely inside. Append...
  1317. geo.coords = list(geo.coords) + list(candidate.coords)
  1318. # try:
  1319. # last = optimized_paths[-1]
  1320. # last.coords = list(last.coords) + list(geo.coords)
  1321. # except IndexError:
  1322. # optimized_paths.append(geo)
  1323. else:
  1324. # Have to lift tool. End path.
  1325. # log.debug("Path #%d not within boundary. Next." % path_count)
  1326. # optimized_paths.append(geo)
  1327. optimized_paths.insert(geo)
  1328. geo = candidate
  1329. current_pt = geo.coords[-1]
  1330. # Next
  1331. # pt, geo = storage.nearest(current_pt)
  1332. except StopIteration: # Nothing left in storage.
  1333. # pass
  1334. optimized_paths.insert(geo)
  1335. return optimized_paths
  1336. @staticmethod
  1337. def path_connect(storage, origin=(0, 0)):
  1338. """
  1339. Simplifies paths in the FlatCAMRTreeStorage storage by
  1340. connecting paths that touch on their enpoints.
  1341. :param storage: Storage containing the initial paths.
  1342. :rtype storage: FlatCAMRTreeStorage
  1343. :return: Simplified storage.
  1344. :rtype: FlatCAMRTreeStorage
  1345. """
  1346. log.debug("path_connect()")
  1347. # ## Index first and last points in paths
  1348. def get_pts(o):
  1349. return [o.coords[0], o.coords[-1]]
  1350. #
  1351. # storage = FlatCAMRTreeStorage()
  1352. # storage.get_points = get_pts
  1353. #
  1354. # for shape in pathlist:
  1355. # if shape is not None: # TODO: This shouldn't have happened.
  1356. # storage.insert(shape)
  1357. path_count = 0
  1358. pt, geo = storage.nearest(origin)
  1359. storage.remove(geo)
  1360. # optimized_geometry = [geo]
  1361. optimized_geometry = FlatCAMRTreeStorage()
  1362. optimized_geometry.get_points = get_pts
  1363. # optimized_geometry.insert(geo)
  1364. try:
  1365. while True:
  1366. path_count += 1
  1367. _, left = storage.nearest(geo.coords[0])
  1368. # If left touches geo, remove left from original
  1369. # storage and append to geo.
  1370. if type(left) == LineString:
  1371. if left.coords[0] == geo.coords[0]:
  1372. storage.remove(left)
  1373. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  1374. continue
  1375. if left.coords[-1] == geo.coords[0]:
  1376. storage.remove(left)
  1377. geo.coords = list(left.coords) + list(geo.coords)
  1378. continue
  1379. if left.coords[0] == geo.coords[-1]:
  1380. storage.remove(left)
  1381. geo.coords = list(geo.coords) + list(left.coords)
  1382. continue
  1383. if left.coords[-1] == geo.coords[-1]:
  1384. storage.remove(left)
  1385. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  1386. continue
  1387. _, right = storage.nearest(geo.coords[-1])
  1388. # If right touches geo, remove left from original
  1389. # storage and append to geo.
  1390. if type(right) == LineString:
  1391. if right.coords[0] == geo.coords[-1]:
  1392. storage.remove(right)
  1393. geo.coords = list(geo.coords) + list(right.coords)
  1394. continue
  1395. if right.coords[-1] == geo.coords[-1]:
  1396. storage.remove(right)
  1397. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  1398. continue
  1399. if right.coords[0] == geo.coords[0]:
  1400. storage.remove(right)
  1401. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  1402. continue
  1403. if right.coords[-1] == geo.coords[0]:
  1404. storage.remove(right)
  1405. geo.coords = list(left.coords) + list(geo.coords)
  1406. continue
  1407. # right is either a LinearRing or it does not connect
  1408. # to geo (nothing left to connect to geo), so we continue
  1409. # with right as geo.
  1410. storage.remove(right)
  1411. if type(right) == LinearRing:
  1412. optimized_geometry.insert(right)
  1413. else:
  1414. # Cannot extend geo any further. Put it away.
  1415. optimized_geometry.insert(geo)
  1416. # Continue with right.
  1417. geo = right
  1418. except StopIteration: # Nothing found in storage.
  1419. optimized_geometry.insert(geo)
  1420. # print path_count
  1421. log.debug("path_count = %d" % path_count)
  1422. return optimized_geometry
  1423. def convert_units(self, obj_units):
  1424. """
  1425. Converts the units of the object to ``units`` by scaling all
  1426. the geometry appropriately. This call ``scale()``. Don't call
  1427. it again in descendents.
  1428. :param units: "IN" or "MM"
  1429. :type units: str
  1430. :return: Scaling factor resulting from unit change.
  1431. :rtype: float
  1432. """
  1433. if obj_units.upper() == self.units.upper():
  1434. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1435. return 1.0
  1436. if obj_units.upper() == "MM":
  1437. factor = 25.4
  1438. log.debug("camlib.Geometry.convert_units() --> Factor: 25.4")
  1439. elif obj_units.upper() == "IN":
  1440. factor = 1 / 25.4
  1441. log.debug("camlib.Geometry.convert_units() --> Factor: %s" % str(1 / 25.4))
  1442. else:
  1443. log.error("Unsupported units: %s" % str(obj_units))
  1444. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1445. return 1.0
  1446. self.units = obj_units
  1447. self.scale(factor, factor)
  1448. self.file_units_factor = factor
  1449. return factor
  1450. def to_dict(self):
  1451. """
  1452. Returns a representation of the object as a dictionary.
  1453. Attributes to include are listed in ``self.ser_attrs``.
  1454. :return: A dictionary-encoded copy of the object.
  1455. :rtype: dict
  1456. """
  1457. d = {}
  1458. for attr in self.ser_attrs:
  1459. d[attr] = getattr(self, attr)
  1460. return d
  1461. def from_dict(self, d):
  1462. """
  1463. Sets object's attributes from a dictionary.
  1464. Attributes to include are listed in ``self.ser_attrs``.
  1465. This method will look only for only and all the
  1466. attributes in ``self.ser_attrs``. They must all
  1467. be present. Use only for deserializing saved
  1468. objects.
  1469. :param d: Dictionary of attributes to set in the object.
  1470. :type d: dict
  1471. :return: None
  1472. """
  1473. for attr in self.ser_attrs:
  1474. setattr(self, attr, d[attr])
  1475. def union(self):
  1476. """
  1477. Runs a cascaded union on the list of objects in
  1478. solid_geometry.
  1479. :return: None
  1480. """
  1481. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1482. def export_svg(self, scale_stroke_factor=0.00,
  1483. scale_factor_x=None, scale_factor_y=None,
  1484. skew_factor_x=None, skew_factor_y=None,
  1485. skew_reference='center',
  1486. mirror=None):
  1487. """
  1488. Exports the Geometry Object as a SVG Element
  1489. :return: SVG Element
  1490. """
  1491. # Make sure we see a Shapely Geometry class and not a list
  1492. if str(type(self)) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  1493. flat_geo = []
  1494. if self.multigeo:
  1495. for tool in self.tools:
  1496. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1497. geom_svg = cascaded_union(flat_geo)
  1498. else:
  1499. geom_svg = cascaded_union(self.flatten())
  1500. else:
  1501. geom_svg = cascaded_union(self.flatten())
  1502. skew_ref = 'center'
  1503. if skew_reference != 'center':
  1504. xmin, ymin, xmax, ymax = geom_svg.bounds
  1505. if skew_reference == 'topleft':
  1506. skew_ref = (xmin, ymax)
  1507. elif skew_reference == 'bottomleft':
  1508. skew_ref = (xmin, ymin)
  1509. elif skew_reference == 'topright':
  1510. skew_ref = (xmax, ymax)
  1511. elif skew_reference == 'bottomright':
  1512. skew_ref = (xmax, ymin)
  1513. geom = geom_svg
  1514. if scale_factor_x:
  1515. geom = affinity.scale(geom_svg, scale_factor_x, 1.0)
  1516. if scale_factor_y:
  1517. geom = affinity.scale(geom_svg, 1.0, scale_factor_y)
  1518. if skew_factor_x:
  1519. geom = affinity.skew(geom_svg, skew_factor_x, 0.0, origin=skew_ref)
  1520. if skew_factor_y:
  1521. geom = affinity.skew(geom_svg, 0.0, skew_factor_y, origin=skew_ref)
  1522. if mirror:
  1523. if mirror == 'x':
  1524. geom = affinity.scale(geom_svg, 1.0, -1.0)
  1525. if mirror == 'y':
  1526. geom = affinity.scale(geom_svg, -1.0, 1.0)
  1527. if mirror == 'both':
  1528. geom = affinity.scale(geom_svg, -1.0, -1.0)
  1529. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1530. # If 0 or less which is invalid then default to 0.01
  1531. # This value appears to work for zooming, and getting the output svg line width
  1532. # to match that viewed on screen with FlatCam
  1533. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1534. if scale_stroke_factor <= 0:
  1535. scale_stroke_factor = 0.01
  1536. # Convert to a SVG
  1537. svg_elem = geom.svg(scale_factor=scale_stroke_factor)
  1538. return svg_elem
  1539. def mirror(self, axis, point):
  1540. """
  1541. Mirrors the object around a specified axis passign through
  1542. the given point.
  1543. :param axis: "X" or "Y" indicates around which axis to mirror.
  1544. :type axis: str
  1545. :param point: [x, y] point belonging to the mirror axis.
  1546. :type point: list
  1547. :return: None
  1548. """
  1549. log.debug("camlib.Geometry.mirror()")
  1550. px, py = point
  1551. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1552. def mirror_geom(obj):
  1553. if type(obj) is list:
  1554. new_obj = []
  1555. for g in obj:
  1556. new_obj.append(mirror_geom(g))
  1557. return new_obj
  1558. else:
  1559. try:
  1560. self.el_count += 1
  1561. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1562. if self.old_disp_number < disp_number <= 100:
  1563. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1564. self.old_disp_number = disp_number
  1565. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1566. except AttributeError:
  1567. return obj
  1568. try:
  1569. if self.multigeo is True:
  1570. for tool in self.tools:
  1571. # variables to display the percentage of work done
  1572. self.geo_len = 0
  1573. try:
  1574. for g in self.tools[tool]['solid_geometry']:
  1575. self.geo_len += 1
  1576. except TypeError:
  1577. self.geo_len = 1
  1578. self.old_disp_number = 0
  1579. self.el_count = 0
  1580. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1581. else:
  1582. # variables to display the percentage of work done
  1583. self.geo_len = 0
  1584. try:
  1585. for g in self.solid_geometry:
  1586. self.geo_len += 1
  1587. except TypeError:
  1588. self.geo_len = 1
  1589. self.old_disp_number = 0
  1590. self.el_count = 0
  1591. self.solid_geometry = mirror_geom(self.solid_geometry)
  1592. self.app.inform.emit('[success] %s...' %
  1593. _('Object was mirrored'))
  1594. except AttributeError:
  1595. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1596. _("Failed to mirror. No object selected"))
  1597. self.app.proc_container.new_text = ''
  1598. def rotate(self, angle, point):
  1599. """
  1600. Rotate an object by an angle (in degrees) around the provided coordinates.
  1601. Parameters
  1602. ----------
  1603. The angle of rotation are specified in degrees (default). Positive angles are
  1604. counter-clockwise and negative are clockwise rotations.
  1605. The point of origin can be a keyword 'center' for the bounding box
  1606. center (default), 'centroid' for the geometry's centroid, a Point object
  1607. or a coordinate tuple (x0, y0).
  1608. See shapely manual for more information:
  1609. http://toblerity.org/shapely/manual.html#affine-transformations
  1610. """
  1611. log.debug("camlib.Geometry.rotate()")
  1612. px, py = point
  1613. def rotate_geom(obj):
  1614. if type(obj) is list:
  1615. new_obj = []
  1616. for g in obj:
  1617. new_obj.append(rotate_geom(g))
  1618. return new_obj
  1619. else:
  1620. try:
  1621. self.el_count += 1
  1622. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1623. if self.old_disp_number < disp_number <= 100:
  1624. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1625. self.old_disp_number = disp_number
  1626. return affinity.rotate(obj, angle, origin=(px, py))
  1627. except AttributeError:
  1628. return obj
  1629. try:
  1630. if self.multigeo is True:
  1631. for tool in self.tools:
  1632. # variables to display the percentage of work done
  1633. self.geo_len = 0
  1634. try:
  1635. for g in self.tools[tool]['solid_geometry']:
  1636. self.geo_len += 1
  1637. except TypeError:
  1638. self.geo_len = 1
  1639. self.old_disp_number = 0
  1640. self.el_count = 0
  1641. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1642. else:
  1643. # variables to display the percentage of work done
  1644. self.geo_len = 0
  1645. try:
  1646. for g in self.solid_geometry:
  1647. self.geo_len += 1
  1648. except TypeError:
  1649. self.geo_len = 1
  1650. self.old_disp_number = 0
  1651. self.el_count = 0
  1652. self.solid_geometry = rotate_geom(self.solid_geometry)
  1653. self.app.inform.emit('[success] %s...' %
  1654. _('Object was rotated'))
  1655. except AttributeError:
  1656. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1657. _("Failed to rotate. No object selected"))
  1658. self.app.proc_container.new_text = ''
  1659. def skew(self, angle_x, angle_y, point):
  1660. """
  1661. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1662. Parameters
  1663. ----------
  1664. angle_x, angle_y : float, float
  1665. The shear angle(s) for the x and y axes respectively. These can be
  1666. specified in either degrees (default) or radians by setting
  1667. use_radians=True.
  1668. point: tuple of coordinates (x,y)
  1669. See shapely manual for more information:
  1670. http://toblerity.org/shapely/manual.html#affine-transformations
  1671. """
  1672. log.debug("camlib.Geometry.skew()")
  1673. px, py = point
  1674. def skew_geom(obj):
  1675. if type(obj) is list:
  1676. new_obj = []
  1677. for g in obj:
  1678. new_obj.append(skew_geom(g))
  1679. return new_obj
  1680. else:
  1681. try:
  1682. self.el_count += 1
  1683. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1684. if self.old_disp_number < disp_number <= 100:
  1685. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1686. self.old_disp_number = disp_number
  1687. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1688. except AttributeError:
  1689. return obj
  1690. try:
  1691. if self.multigeo is True:
  1692. for tool in self.tools:
  1693. # variables to display the percentage of work done
  1694. self.geo_len = 0
  1695. try:
  1696. for g in self.tools[tool]['solid_geometry']:
  1697. self.geo_len += 1
  1698. except TypeError:
  1699. self.geo_len = 1
  1700. self.old_disp_number = 0
  1701. self.el_count = 0
  1702. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1703. else:
  1704. # variables to display the percentage of work done
  1705. self.geo_len = 0
  1706. try:
  1707. for g in self.solid_geometry:
  1708. self.geo_len += 1
  1709. except TypeError:
  1710. self.geo_len = 1
  1711. self.old_disp_number = 0
  1712. self.el_count = 0
  1713. self.solid_geometry = skew_geom(self.solid_geometry)
  1714. self.app.inform.emit('[success] %s...' %
  1715. _('Object was skewed'))
  1716. except AttributeError:
  1717. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1718. _("Failed to skew. No object selected"))
  1719. self.app.proc_container.new_text = ''
  1720. # if type(self.solid_geometry) == list:
  1721. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  1722. # for g in self.solid_geometry]
  1723. # else:
  1724. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  1725. # origin=(px, py))
  1726. class AttrDict(dict):
  1727. def __init__(self, *args, **kwargs):
  1728. super(AttrDict, self).__init__(*args, **kwargs)
  1729. self.__dict__ = self
  1730. class CNCjob(Geometry):
  1731. """
  1732. Represents work to be done by a CNC machine.
  1733. *ATTRIBUTES*
  1734. * ``gcode_parsed`` (list): Each is a dictionary:
  1735. ===================== =========================================
  1736. Key Value
  1737. ===================== =========================================
  1738. geom (Shapely.LineString) Tool path (XY plane)
  1739. kind (string) "AB", A is "T" (travel) or
  1740. "C" (cut). B is "F" (fast) or "S" (slow).
  1741. ===================== =========================================
  1742. """
  1743. defaults = {
  1744. "global_zdownrate": None,
  1745. "pp_geometry_name":'default',
  1746. "pp_excellon_name":'default',
  1747. "excellon_optimization_type": "B",
  1748. }
  1749. settings = QtCore.QSettings("Open Source", "FlatCAM")
  1750. if settings.contains("machinist"):
  1751. machinist_setting = settings.value('machinist', type=int)
  1752. else:
  1753. machinist_setting = 0
  1754. def __init__(self,
  1755. units="in", kind="generic", tooldia=0.0,
  1756. z_cut=-0.002, z_move=0.1,
  1757. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  1758. pp_geometry_name='default', pp_excellon_name='default',
  1759. depthpercut=0.1,z_pdepth=-0.02,
  1760. spindlespeed=None, spindledir='CW', dwell=True, dwelltime=1000,
  1761. toolchangez=0.787402, toolchange_xy=[0.0, 0.0],
  1762. endz=2.0,
  1763. segx=None,
  1764. segy=None,
  1765. steps_per_circle=None):
  1766. # Used when parsing G-code arcs
  1767. self.steps_per_circle = int(self.app.defaults['cncjob_steps_per_circle'])
  1768. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  1769. self.kind = kind
  1770. self.origin_kind = None
  1771. self.units = units
  1772. self.z_cut = z_cut
  1773. self.tool_offset = {}
  1774. self.z_move = z_move
  1775. self.feedrate = feedrate
  1776. self.z_feedrate = feedrate_z
  1777. self.feedrate_rapid = feedrate_rapid
  1778. self.tooldia = tooldia
  1779. self.z_toolchange = toolchangez
  1780. self.xy_toolchange = toolchange_xy
  1781. self.toolchange_xy_type = None
  1782. self.toolC = tooldia
  1783. self.z_end = endz
  1784. self.z_depthpercut = depthpercut
  1785. self.unitcode = {"IN": "G20", "MM": "G21"}
  1786. self.feedminutecode = "G94"
  1787. # self.absolutecode = "G90"
  1788. # self.incrementalcode = "G91"
  1789. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1790. self.gcode = ""
  1791. self.gcode_parsed = None
  1792. self.pp_geometry_name = pp_geometry_name
  1793. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  1794. self.pp_excellon_name = pp_excellon_name
  1795. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  1796. self.pp_solderpaste_name = None
  1797. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  1798. self.f_plunge = None
  1799. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  1800. self.f_retract = None
  1801. # how much depth the probe can probe before error
  1802. self.z_pdepth = z_pdepth if z_pdepth else None
  1803. # the feedrate(speed) with which the probel travel while probing
  1804. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  1805. self.spindlespeed = spindlespeed
  1806. self.spindledir = spindledir
  1807. self.dwell = dwell
  1808. self.dwelltime = dwelltime
  1809. self.segx = float(segx) if segx is not None else 0.0
  1810. self.segy = float(segy) if segy is not None else 0.0
  1811. self.input_geometry_bounds = None
  1812. self.oldx = None
  1813. self.oldy = None
  1814. self.tool = 0.0
  1815. # here store the travelled distance
  1816. self.travel_distance = 0.0
  1817. # here store the routing time
  1818. self.routing_time = 0.0
  1819. # used for creating drill CCode geometry; will be updated in the generate_from_excellon_by_tool()
  1820. self.exc_drills = None
  1821. self.exc_tools = None
  1822. # search for toolchange parameters in the Toolchange Custom Code
  1823. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  1824. # search for toolchange code: M6
  1825. self.re_toolchange = re.compile(r'^\s*(M6)$')
  1826. # Attributes to be included in serialization
  1827. # Always append to it because it carries contents
  1828. # from Geometry.
  1829. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  1830. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  1831. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  1832. @property
  1833. def postdata(self):
  1834. return self.__dict__
  1835. def convert_units(self, units):
  1836. log.debug("camlib.CNCJob.convert_units()")
  1837. factor = Geometry.convert_units(self, units)
  1838. self.z_cut = float(self.z_cut) * factor
  1839. self.z_move *= factor
  1840. self.feedrate *= factor
  1841. self.z_feedrate *= factor
  1842. self.feedrate_rapid *= factor
  1843. self.tooldia *= factor
  1844. self.z_toolchange *= factor
  1845. self.z_end *= factor
  1846. self.z_depthpercut = float(self.z_depthpercut) * factor
  1847. return factor
  1848. def doformat(self, fun, **kwargs):
  1849. return self.doformat2(fun, **kwargs) + "\n"
  1850. def doformat2(self, fun, **kwargs):
  1851. attributes = AttrDict()
  1852. attributes.update(self.postdata)
  1853. attributes.update(kwargs)
  1854. try:
  1855. returnvalue = fun(attributes)
  1856. return returnvalue
  1857. except Exception:
  1858. self.app.log.error('Exception occurred within a postprocessor: ' + traceback.format_exc())
  1859. return ''
  1860. def parse_custom_toolchange_code(self, data):
  1861. text = data
  1862. match_list = self.re_toolchange_custom.findall(text)
  1863. if match_list:
  1864. for match in match_list:
  1865. command = match.strip('%')
  1866. try:
  1867. value = getattr(self, command)
  1868. except AttributeError:
  1869. self.app.inform.emit('[ERROR] %s: %s' %
  1870. (_("There is no such parameter"), str(match)))
  1871. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  1872. return 'fail'
  1873. text = text.replace(match, str(value))
  1874. return text
  1875. def optimized_travelling_salesman(self, points, start=None):
  1876. """
  1877. As solving the problem in the brute force way is too slow,
  1878. this function implements a simple heuristic: always
  1879. go to the nearest city.
  1880. Even if this algorithm is extremely simple, it works pretty well
  1881. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  1882. and runs very fast in O(N^2) time complexity.
  1883. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  1884. [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2],
  1885. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  1886. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  1887. [[0, 0], [6, 0], [10, 0]]
  1888. """
  1889. if start is None:
  1890. start = points[0]
  1891. must_visit = points
  1892. path = [start]
  1893. # must_visit.remove(start)
  1894. while must_visit:
  1895. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  1896. path.append(nearest)
  1897. must_visit.remove(nearest)
  1898. return path
  1899. def generate_from_excellon_by_tool(
  1900. self, exobj, tools="all", drillz = 3.0,
  1901. toolchange=False, toolchangez=0.1, toolchangexy='',
  1902. endz=2.0, startz=None,
  1903. excellon_optimization_type='B'):
  1904. """
  1905. Creates gcode for this object from an Excellon object
  1906. for the specified tools.
  1907. :param exobj: Excellon object to process
  1908. :type exobj: Excellon
  1909. :param tools: Comma separated tool names
  1910. :type: tools: str
  1911. :param drillz: drill Z depth
  1912. :type drillz: float
  1913. :param toolchange: Use tool change sequence between tools.
  1914. :type toolchange: bool
  1915. :param toolchangez: Height at which to perform the tool change.
  1916. :type toolchangez: float
  1917. :param toolchangexy: Toolchange X,Y position
  1918. :type toolchangexy: String containing 2 floats separated by comma
  1919. :param startz: Z position just before starting the job
  1920. :type startz: float
  1921. :param endz: final Z position to move to at the end of the CNC job
  1922. :type endz: float
  1923. :param excellon_optimization_type: Single character that defines which drill re-ordering optimisation algorithm
  1924. is to be used: 'M' for meta-heuristic and 'B' for basic
  1925. :type excellon_optimization_type: string
  1926. :return: None
  1927. :rtype: None
  1928. """
  1929. # create a local copy of the exobj.drills so it can be used for creating drill CCode geometry
  1930. self.exc_drills = deepcopy(exobj.drills)
  1931. self.exc_tools = deepcopy(exobj.tools)
  1932. self.z_cut = drillz
  1933. if self.machinist_setting == 0:
  1934. if drillz > 0:
  1935. self.app.inform.emit('[WARNING] %s' %
  1936. _("The Cut Z parameter has positive value. "
  1937. "It is the depth value to drill into material.\n"
  1938. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  1939. "therefore the app will convert the value to negative. "
  1940. "Check the resulting CNC code (Gcode etc)."))
  1941. self.z_cut = -drillz
  1942. elif drillz == 0:
  1943. self.app.inform.emit('[WARNING] %s: %s' %
  1944. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  1945. exobj.options['name']))
  1946. return 'fail'
  1947. self.z_toolchange = toolchangez
  1948. try:
  1949. if toolchangexy == '':
  1950. self.xy_toolchange = None
  1951. else:
  1952. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  1953. if len(self.xy_toolchange) < 2:
  1954. self.app.inform.emit('[ERROR]%s' %
  1955. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  1956. "in the format (x, y) \nbut now there is only one value, not two. "))
  1957. return 'fail'
  1958. except Exception as e:
  1959. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  1960. pass
  1961. self.startz = startz
  1962. self.z_end = endz
  1963. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  1964. p = self.pp_excellon
  1965. log.debug("Creating CNC Job from Excellon...")
  1966. # Tools
  1967. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  1968. # so we actually are sorting the tools by diameter
  1969. #sorted_tools = sorted(exobj.tools.items(), key=lambda t1: t1['C'])
  1970. sort = []
  1971. for k, v in list(exobj.tools.items()):
  1972. sort.append((k, v.get('C')))
  1973. sorted_tools = sorted(sort,key=lambda t1: t1[1])
  1974. if tools == "all":
  1975. tools = [i[0] for i in sorted_tools] # we get a array of ordered tools
  1976. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  1977. else:
  1978. selected_tools = [x.strip() for x in tools.split(",")] # we strip spaces and also separate the tools by ','
  1979. selected_tools = [t1 for t1 in selected_tools if t1 in selected_tools]
  1980. # Create a sorted list of selected tools from the sorted_tools list
  1981. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  1982. log.debug("Tools selected and sorted are: %s" % str(tools))
  1983. self.app.inform.emit(_("Creating a list of points to drill..."))
  1984. # Points (Group by tool)
  1985. points = {}
  1986. for drill in exobj.drills:
  1987. if self.app.abort_flag:
  1988. # graceful abort requested by the user
  1989. raise FlatCAMApp.GracefulException
  1990. if drill['tool'] in tools:
  1991. try:
  1992. points[drill['tool']].append(drill['point'])
  1993. except KeyError:
  1994. points[drill['tool']] = [drill['point']]
  1995. # log.debug("Found %d drills." % len(points))
  1996. self.gcode = []
  1997. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  1998. self.f_retract = self.app.defaults["excellon_f_retract"]
  1999. # Initialization
  2000. gcode = self.doformat(p.start_code)
  2001. gcode += self.doformat(p.feedrate_code)
  2002. if toolchange is False:
  2003. if self.xy_toolchange is not None:
  2004. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2005. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2006. else:
  2007. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  2008. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  2009. # Distance callback
  2010. class CreateDistanceCallback(object):
  2011. """Create callback to calculate distances between points."""
  2012. def __init__(self):
  2013. """Initialize distance array."""
  2014. locations = create_data_array()
  2015. size = len(locations)
  2016. self.matrix = {}
  2017. for from_node in range(size):
  2018. self.matrix[from_node] = {}
  2019. for to_node in range(size):
  2020. if from_node == to_node:
  2021. self.matrix[from_node][to_node] = 0
  2022. else:
  2023. x1 = locations[from_node][0]
  2024. y1 = locations[from_node][1]
  2025. x2 = locations[to_node][0]
  2026. y2 = locations[to_node][1]
  2027. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  2028. # def Distance(self, from_node, to_node):
  2029. # return int(self.matrix[from_node][to_node])
  2030. def Distance(self, from_index, to_index):
  2031. # Convert from routing variable Index to distance matrix NodeIndex.
  2032. from_node = manager.IndexToNode(from_index)
  2033. to_node = manager.IndexToNode(to_index)
  2034. return self.matrix[from_node][to_node]
  2035. # Create the data.
  2036. def create_data_array():
  2037. locations = []
  2038. for point in points[tool]:
  2039. locations.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2040. return locations
  2041. if self.xy_toolchange is not None:
  2042. self.oldx = self.xy_toolchange[0]
  2043. self.oldy = self.xy_toolchange[1]
  2044. else:
  2045. self.oldx = 0.0
  2046. self.oldy = 0.0
  2047. measured_distance = 0.0
  2048. measured_down_distance = 0.0
  2049. measured_up_to_zero_distance = 0.0
  2050. measured_lift_distance = 0.0
  2051. self.app.inform.emit('%s...' % _("Starting G-Code"))
  2052. current_platform = platform.architecture()[0]
  2053. if current_platform == '64bit':
  2054. used_excellon_optimization_type = excellon_optimization_type
  2055. if used_excellon_optimization_type == 'M':
  2056. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2057. if exobj.drills:
  2058. for tool in tools:
  2059. self.tool=tool
  2060. self.postdata['toolC'] = exobj.tools[tool]["C"]
  2061. self.tooldia = exobj.tools[tool]["C"]
  2062. if self.app.abort_flag:
  2063. # graceful abort requested by the user
  2064. raise FlatCAMApp.GracefulException
  2065. # ###############################################
  2066. # ############ Create the data. #################
  2067. # ###############################################
  2068. node_list = []
  2069. locations = create_data_array()
  2070. tsp_size = len(locations)
  2071. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2072. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2073. depot = 0
  2074. # Create routing model.
  2075. if tsp_size > 0:
  2076. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2077. routing = pywrapcp.RoutingModel(manager)
  2078. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2079. search_parameters.local_search_metaheuristic = (
  2080. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  2081. # Set search time limit in milliseconds.
  2082. if float(self.app.defaults["excellon_search_time"]) != 0:
  2083. search_parameters.time_limit.seconds = int(
  2084. float(self.app.defaults["excellon_search_time"]))
  2085. else:
  2086. search_parameters.time_limit.seconds = 3
  2087. # Callback to the distance function. The callback takes two
  2088. # arguments (the from and to node indices) and returns the distance between them.
  2089. dist_between_locations = CreateDistanceCallback()
  2090. dist_callback = dist_between_locations.Distance
  2091. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2092. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2093. # Solve, returns a solution if any.
  2094. assignment = routing.SolveWithParameters(search_parameters)
  2095. if assignment:
  2096. # Solution cost.
  2097. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2098. # Inspect solution.
  2099. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2100. route_number = 0
  2101. node = routing.Start(route_number)
  2102. start_node = node
  2103. while not routing.IsEnd(node):
  2104. if self.app.abort_flag:
  2105. # graceful abort requested by the user
  2106. raise FlatCAMApp.GracefulException
  2107. node_list.append(node)
  2108. node = assignment.Value(routing.NextVar(node))
  2109. else:
  2110. log.warning('No solution found.')
  2111. else:
  2112. log.warning('Specify an instance greater than 0.')
  2113. # ############################################# ##
  2114. # Only if tool has points.
  2115. if tool in points:
  2116. if self.app.abort_flag:
  2117. # graceful abort requested by the user
  2118. raise FlatCAMApp.GracefulException
  2119. # Tool change sequence (optional)
  2120. if toolchange:
  2121. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  2122. gcode += self.doformat(p.spindle_code) # Spindle start
  2123. if self.dwell is True:
  2124. gcode += self.doformat(p.dwell_code) # Dwell time
  2125. else:
  2126. gcode += self.doformat(p.spindle_code)
  2127. if self.dwell is True:
  2128. gcode += self.doformat(p.dwell_code) # Dwell time
  2129. if self.units == 'MM':
  2130. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2131. else:
  2132. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2133. self.app.inform.emit(
  2134. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2135. str(current_tooldia),
  2136. str(self.units))
  2137. )
  2138. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2139. # because the values for Z offset are created in build_ui()
  2140. try:
  2141. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2142. except KeyError:
  2143. z_offset = 0
  2144. self.z_cut += z_offset
  2145. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2146. if self.coordinates_type == "G90":
  2147. # Drillling! for Absolute coordinates type G90
  2148. # variables to display the percentage of work done
  2149. geo_len = len(node_list)
  2150. old_disp_number = 0
  2151. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2152. loc_nr = 0
  2153. for k in node_list:
  2154. if self.app.abort_flag:
  2155. # graceful abort requested by the user
  2156. raise FlatCAMApp.GracefulException
  2157. locx = locations[k][0]
  2158. locy = locations[k][1]
  2159. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2160. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2161. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2162. if self.f_retract is False:
  2163. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2164. measured_up_to_zero_distance += abs(self.z_cut)
  2165. measured_lift_distance += abs(self.z_move)
  2166. else:
  2167. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2168. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2169. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2170. self.oldx = locx
  2171. self.oldy = locy
  2172. loc_nr += 1
  2173. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2174. if old_disp_number < disp_number <= 100:
  2175. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2176. old_disp_number = disp_number
  2177. else:
  2178. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2179. return 'fail'
  2180. else:
  2181. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2182. "The loaded Excellon file has no drills ...")
  2183. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2184. _('The loaded Excellon file has no drills'))
  2185. return 'fail'
  2186. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  2187. if used_excellon_optimization_type == 'B':
  2188. log.debug("Using OR-Tools Basic drill path optimization.")
  2189. if exobj.drills:
  2190. for tool in tools:
  2191. if self.app.abort_flag:
  2192. # graceful abort requested by the user
  2193. raise FlatCAMApp.GracefulException
  2194. self.tool=tool
  2195. self.postdata['toolC']=exobj.tools[tool]["C"]
  2196. self.tooldia = exobj.tools[tool]["C"]
  2197. # ############################################# ##
  2198. node_list = []
  2199. locations = create_data_array()
  2200. tsp_size = len(locations)
  2201. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2202. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2203. depot = 0
  2204. # Create routing model.
  2205. if tsp_size > 0:
  2206. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2207. routing = pywrapcp.RoutingModel(manager)
  2208. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2209. # Callback to the distance function. The callback takes two
  2210. # arguments (the from and to node indices) and returns the distance between them.
  2211. dist_between_locations = CreateDistanceCallback()
  2212. dist_callback = dist_between_locations.Distance
  2213. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2214. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2215. # Solve, returns a solution if any.
  2216. assignment = routing.SolveWithParameters(search_parameters)
  2217. if assignment:
  2218. # Solution cost.
  2219. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2220. # Inspect solution.
  2221. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2222. route_number = 0
  2223. node = routing.Start(route_number)
  2224. start_node = node
  2225. while not routing.IsEnd(node):
  2226. node_list.append(node)
  2227. node = assignment.Value(routing.NextVar(node))
  2228. else:
  2229. log.warning('No solution found.')
  2230. else:
  2231. log.warning('Specify an instance greater than 0.')
  2232. # ############################################# ##
  2233. # Only if tool has points.
  2234. if tool in points:
  2235. if self.app.abort_flag:
  2236. # graceful abort requested by the user
  2237. raise FlatCAMApp.GracefulException
  2238. # Tool change sequence (optional)
  2239. if toolchange:
  2240. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  2241. gcode += self.doformat(p.spindle_code) # Spindle start)
  2242. if self.dwell is True:
  2243. gcode += self.doformat(p.dwell_code) # Dwell time
  2244. else:
  2245. gcode += self.doformat(p.spindle_code)
  2246. if self.dwell is True:
  2247. gcode += self.doformat(p.dwell_code) # Dwell time
  2248. if self.units == 'MM':
  2249. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2250. else:
  2251. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2252. self.app.inform.emit(
  2253. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2254. str(current_tooldia),
  2255. str(self.units))
  2256. )
  2257. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2258. # because the values for Z offset are created in build_ui()
  2259. try:
  2260. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2261. except KeyError:
  2262. z_offset = 0
  2263. self.z_cut += z_offset
  2264. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2265. if self.coordinates_type == "G90":
  2266. # Drillling! for Absolute coordinates type G90
  2267. # variables to display the percentage of work done
  2268. geo_len = len(node_list)
  2269. disp_number = 0
  2270. old_disp_number = 0
  2271. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2272. loc_nr = 0
  2273. for k in node_list:
  2274. if self.app.abort_flag:
  2275. # graceful abort requested by the user
  2276. raise FlatCAMApp.GracefulException
  2277. locx = locations[k][0]
  2278. locy = locations[k][1]
  2279. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2280. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2281. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2282. if self.f_retract is False:
  2283. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2284. measured_up_to_zero_distance += abs(self.z_cut)
  2285. measured_lift_distance += abs(self.z_move)
  2286. else:
  2287. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2288. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2289. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2290. self.oldx = locx
  2291. self.oldy = locy
  2292. loc_nr += 1
  2293. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2294. if old_disp_number < disp_number <= 100:
  2295. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2296. old_disp_number = disp_number
  2297. else:
  2298. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2299. return 'fail'
  2300. else:
  2301. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2302. "The loaded Excellon file has no drills ...")
  2303. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2304. _('The loaded Excellon file has no drills'))
  2305. return 'fail'
  2306. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  2307. else:
  2308. used_excellon_optimization_type = 'T'
  2309. if used_excellon_optimization_type == 'T':
  2310. log.debug("Using Travelling Salesman drill path optimization.")
  2311. for tool in tools:
  2312. if self.app.abort_flag:
  2313. # graceful abort requested by the user
  2314. raise FlatCAMApp.GracefulException
  2315. if exobj.drills:
  2316. self.tool = tool
  2317. self.postdata['toolC'] = exobj.tools[tool]["C"]
  2318. self.tooldia = exobj.tools[tool]["C"]
  2319. # Only if tool has points.
  2320. if tool in points:
  2321. if self.app.abort_flag:
  2322. # graceful abort requested by the user
  2323. raise FlatCAMApp.GracefulException
  2324. # Tool change sequence (optional)
  2325. if toolchange:
  2326. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  2327. gcode += self.doformat(p.spindle_code) # Spindle start)
  2328. if self.dwell is True:
  2329. gcode += self.doformat(p.dwell_code) # Dwell time
  2330. else:
  2331. gcode += self.doformat(p.spindle_code)
  2332. if self.dwell is True:
  2333. gcode += self.doformat(p.dwell_code) # Dwell time
  2334. if self.units == 'MM':
  2335. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  2336. else:
  2337. current_tooldia = float('%.4f' % float(exobj.tools[tool]["C"]))
  2338. self.app.inform.emit(
  2339. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2340. str(current_tooldia),
  2341. str(self.units))
  2342. )
  2343. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  2344. # because the values for Z offset are created in build_ui()
  2345. try:
  2346. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  2347. except KeyError:
  2348. z_offset = 0
  2349. self.z_cut += z_offset
  2350. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2351. if self.coordinates_type == "G90":
  2352. # Drillling! for Absolute coordinates type G90
  2353. altPoints = []
  2354. for point in points[tool]:
  2355. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2356. node_list = self.optimized_travelling_salesman(altPoints)
  2357. # variables to display the percentage of work done
  2358. geo_len = len(node_list)
  2359. disp_number = 0
  2360. old_disp_number = 0
  2361. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2362. loc_nr = 0
  2363. for point in node_list:
  2364. if self.app.abort_flag:
  2365. # graceful abort requested by the user
  2366. raise FlatCAMApp.GracefulException
  2367. gcode += self.doformat(p.rapid_code, x=point[0], y=point[1])
  2368. gcode += self.doformat(p.down_code, x=point[0], y=point[1])
  2369. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2370. if self.f_retract is False:
  2371. gcode += self.doformat(p.up_to_zero_code, x=point[0], y=point[1])
  2372. measured_up_to_zero_distance += abs(self.z_cut)
  2373. measured_lift_distance += abs(self.z_move)
  2374. else:
  2375. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2376. gcode += self.doformat(p.lift_code, x=point[0], y=point[1])
  2377. measured_distance += abs(distance_euclidian(point[0], point[1], self.oldx, self.oldy))
  2378. self.oldx = point[0]
  2379. self.oldy = point[1]
  2380. loc_nr += 1
  2381. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2382. if old_disp_number < disp_number <= 100:
  2383. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2384. old_disp_number = disp_number
  2385. else:
  2386. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2387. return 'fail'
  2388. else:
  2389. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2390. "The loaded Excellon file has no drills ...")
  2391. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  2392. _('The loaded Excellon file has no drills'))
  2393. return 'fail'
  2394. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  2395. gcode += self.doformat(p.spindle_stop_code) # Spindle stop
  2396. gcode += self.doformat(p.end_code, x=0, y=0)
  2397. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  2398. log.debug("The total travel distance including travel to end position is: %s" %
  2399. str(measured_distance) + '\n')
  2400. self.travel_distance = measured_distance
  2401. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  2402. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  2403. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  2404. # Marlin postprocessor and derivatives.
  2405. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  2406. lift_time = measured_lift_distance / self.feedrate_rapid
  2407. traveled_time = measured_distance / self.feedrate_rapid
  2408. self.routing_time += lift_time + traveled_time
  2409. self.gcode = gcode
  2410. self.app.inform.emit(_("Finished G-Code generation..."))
  2411. return 'OK'
  2412. def generate_from_multitool_geometry(
  2413. self, geometry, append=True,
  2414. tooldia=None, offset=0.0, tolerance=0, z_cut=1.0, z_move=2.0,
  2415. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  2416. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  2417. multidepth=False, depthpercut=None,
  2418. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0", extracut=False,
  2419. startz=None, endz=2.0, pp_geometry_name=None, tool_no=1):
  2420. """
  2421. Algorithm to generate from multitool Geometry.
  2422. Algorithm description:
  2423. ----------------------
  2424. Uses RTree to find the nearest path to follow.
  2425. :param geometry:
  2426. :param append:
  2427. :param tooldia:
  2428. :param offset:
  2429. :param tolerance:
  2430. :param z_cut:
  2431. :param z_move:
  2432. :param feedrate:
  2433. :param feedrate_z:
  2434. :param feedrate_rapid:
  2435. :param spindlespeed:
  2436. :param spindledir:
  2437. :param dwell:
  2438. :param dwelltime:
  2439. :param multidepth: If True, use multiple passes to reach the desired depth.
  2440. :param depthpercut: Maximum depth in each pass.
  2441. :param toolchange:
  2442. :param toolchangez:
  2443. :param toolchangexy:
  2444. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the
  2445. first point in path to ensure complete copper removal
  2446. :param startz:
  2447. :param endz:
  2448. :param pp_geometry_name:
  2449. :param tool_no:
  2450. :return: GCode - string
  2451. """
  2452. log.debug("Generate_from_multitool_geometry()")
  2453. temp_solid_geometry = []
  2454. if offset != 0.0:
  2455. for it in geometry:
  2456. # if the geometry is a closed shape then create a Polygon out of it
  2457. if isinstance(it, LineString):
  2458. c = it.coords
  2459. if c[0] == c[-1]:
  2460. it = Polygon(it)
  2461. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  2462. else:
  2463. temp_solid_geometry = geometry
  2464. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2465. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  2466. log.debug("%d paths" % len(flat_geometry))
  2467. self.tooldia = float(tooldia) if tooldia else None
  2468. self.z_cut = float(z_cut) if z_cut else None
  2469. self.z_move = float(z_move) if z_move is not None else None
  2470. self.feedrate = float(feedrate) if feedrate else None
  2471. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else None
  2472. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  2473. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  2474. self.spindledir = spindledir
  2475. self.dwell = dwell
  2476. self.dwelltime = float(dwelltime) if dwelltime else None
  2477. self.startz = float(startz) if startz is not None else None
  2478. self.z_end = float(endz) if endz is not None else None
  2479. self.z_depthpercut = float(depthpercut) if depthpercut else None
  2480. self.multidepth = multidepth
  2481. self.z_toolchange = float(toolchangez) if toolchangez is not None else None
  2482. # it servers in the postprocessor file
  2483. self.tool = tool_no
  2484. try:
  2485. if toolchangexy == '':
  2486. self.xy_toolchange = None
  2487. else:
  2488. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  2489. if len(self.xy_toolchange) < 2:
  2490. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2491. "in the format (x, y) \n"
  2492. "but now there is only one value, not two."))
  2493. return 'fail'
  2494. except Exception as e:
  2495. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  2496. pass
  2497. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  2498. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  2499. if self.z_cut is None:
  2500. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2501. _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  2502. "other parameters."))
  2503. return 'fail'
  2504. if self.machinist_setting == 0:
  2505. if self.z_cut > 0:
  2506. self.app.inform.emit('[WARNING] %s' %
  2507. _("The Cut Z parameter has positive value. "
  2508. "It is the depth value to cut into material.\n"
  2509. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2510. "therefore the app will convert the value to negative."
  2511. "Check the resulting CNC code (Gcode etc)."))
  2512. self.z_cut = -self.z_cut
  2513. elif self.z_cut == 0:
  2514. self.app.inform.emit('[WARNING] %s: %s' %
  2515. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  2516. self.options['name']))
  2517. return 'fail'
  2518. if self.z_move is None:
  2519. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  2520. return 'fail'
  2521. if self.z_move < 0:
  2522. self.app.inform.emit('[WARNING] %s' %
  2523. _("The Travel Z parameter has negative value. "
  2524. "It is the height value to travel between cuts.\n"
  2525. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  2526. "therefore the app will convert the value to positive."
  2527. "Check the resulting CNC code (Gcode etc)."))
  2528. self.z_move = -self.z_move
  2529. elif self.z_move == 0:
  2530. self.app.inform.emit('[WARNING] %s: %s' %
  2531. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  2532. self.options['name']))
  2533. return 'fail'
  2534. # made sure that depth_per_cut is no more then the z_cut
  2535. if abs(self.z_cut) < self.z_depthpercut:
  2536. self.z_depthpercut = abs(self.z_cut)
  2537. # ## Index first and last points in paths
  2538. # What points to index.
  2539. def get_pts(o):
  2540. return [o.coords[0], o.coords[-1]]
  2541. # Create the indexed storage.
  2542. storage = FlatCAMRTreeStorage()
  2543. storage.get_points = get_pts
  2544. # Store the geometry
  2545. log.debug("Indexing geometry before generating G-Code...")
  2546. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2547. for shape in flat_geometry:
  2548. if self.app.abort_flag:
  2549. # graceful abort requested by the user
  2550. raise FlatCAMApp.GracefulException
  2551. if shape is not None: # TODO: This shouldn't have happened.
  2552. storage.insert(shape)
  2553. # self.input_geometry_bounds = geometry.bounds()
  2554. if not append:
  2555. self.gcode = ""
  2556. # tell postprocessor the number of tool (for toolchange)
  2557. self.tool = tool_no
  2558. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2559. # given under the name 'toolC'
  2560. self.postdata['toolC'] = self.tooldia
  2561. # Initial G-Code
  2562. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  2563. p = self.pp_geometry
  2564. self.gcode = self.doformat(p.start_code)
  2565. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  2566. if toolchange is False:
  2567. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  2568. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  2569. if toolchange:
  2570. # if "line_xyz" in self.pp_geometry_name:
  2571. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2572. # else:
  2573. # self.gcode += self.doformat(p.toolchange_code)
  2574. self.gcode += self.doformat(p.toolchange_code)
  2575. if 'laser' not in self.pp_geometry_name:
  2576. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2577. else:
  2578. # for laser this will disable the laser
  2579. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  2580. if self.dwell is True:
  2581. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2582. else:
  2583. if 'laser' not in self.pp_geometry_name:
  2584. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2585. if self.dwell is True:
  2586. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2587. total_travel = 0.0
  2588. total_cut = 0.0
  2589. # ## Iterate over geometry paths getting the nearest each time.
  2590. log.debug("Starting G-Code...")
  2591. self.app.inform.emit(_("Starting G-Code..."))
  2592. path_count = 0
  2593. current_pt = (0, 0)
  2594. # variables to display the percentage of work done
  2595. geo_len = len(flat_geometry)
  2596. old_disp_number = 0
  2597. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  2598. if self.units == 'MM':
  2599. current_tooldia = float('%.2f' % float(self.tooldia))
  2600. else:
  2601. current_tooldia = float('%.4f' % float(self.tooldia))
  2602. self.app.inform.emit( '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2603. str(current_tooldia),
  2604. str(self.units)))
  2605. pt, geo = storage.nearest(current_pt)
  2606. try:
  2607. while True:
  2608. if self.app.abort_flag:
  2609. # graceful abort requested by the user
  2610. raise FlatCAMApp.GracefulException
  2611. path_count += 1
  2612. # Remove before modifying, otherwise deletion will fail.
  2613. storage.remove(geo)
  2614. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2615. # then reverse coordinates.
  2616. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2617. geo.coords = list(geo.coords)[::-1]
  2618. # ---------- Single depth/pass --------
  2619. if not multidepth:
  2620. # calculate the cut distance
  2621. total_cut = total_cut + geo.length
  2622. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance, old_point=current_pt)
  2623. # --------- Multi-pass ---------
  2624. else:
  2625. # calculate the cut distance
  2626. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  2627. nr_cuts = 0
  2628. depth = abs(self.z_cut)
  2629. while depth > 0:
  2630. nr_cuts += 1
  2631. depth -= float(self.z_depthpercut)
  2632. total_cut += (geo.length * nr_cuts)
  2633. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  2634. postproc=p, old_point=current_pt)
  2635. # calculate the total distance
  2636. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  2637. current_pt = geo.coords[-1]
  2638. pt, geo = storage.nearest(current_pt) # Next
  2639. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2640. if old_disp_number < disp_number <= 100:
  2641. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2642. old_disp_number = disp_number
  2643. except StopIteration: # Nothing found in storage.
  2644. pass
  2645. log.debug("Finished G-Code... %s paths traced." % path_count)
  2646. # add move to end position
  2647. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  2648. self.travel_distance += total_travel + total_cut
  2649. self.routing_time += total_cut / self.feedrate
  2650. # Finish
  2651. self.gcode += self.doformat(p.spindle_stop_code)
  2652. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  2653. self.gcode += self.doformat(p.end_code, x=0, y=0)
  2654. self.app.inform.emit('%s... %s %s.' %
  2655. (_("Finished G-Code generation"),
  2656. str(path_count),
  2657. _("paths traced")
  2658. )
  2659. )
  2660. return self.gcode
  2661. def generate_from_geometry_2(
  2662. self, geometry, append=True,
  2663. tooldia=None, offset=0.0, tolerance=0,
  2664. z_cut=1.0, z_move=2.0,
  2665. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  2666. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  2667. multidepth=False, depthpercut=None,
  2668. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0",
  2669. extracut=False, startz=None, endz=2.0,
  2670. pp_geometry_name=None, tool_no=1):
  2671. """
  2672. Second algorithm to generate from Geometry.
  2673. Algorithm description:
  2674. ----------------------
  2675. Uses RTree to find the nearest path to follow.
  2676. :param geometry:
  2677. :param append:
  2678. :param tooldia:
  2679. :param tolerance:
  2680. :param multidepth: If True, use multiple passes to reach
  2681. the desired depth.
  2682. :param depthpercut: Maximum depth in each pass.
  2683. :param extracut: Adds (or not) an extra cut at the end of each path
  2684. overlapping the first point in path to ensure complete copper removal
  2685. :return: None
  2686. """
  2687. if not isinstance(geometry, Geometry):
  2688. self.app.inform.emit('[ERROR] %s: %s' %
  2689. (_("Expected a Geometry, got"), type(geometry)))
  2690. return 'fail'
  2691. log.debug("Generate_from_geometry_2()")
  2692. # if solid_geometry is empty raise an exception
  2693. if not geometry.solid_geometry:
  2694. self.app.inform.emit(
  2695. '[ERROR_NOTCL] %s' % _("Trying to generate a CNC Job from a Geometry object without solid_geometry.")
  2696. )
  2697. temp_solid_geometry = list()
  2698. def bounds_rec(obj):
  2699. if type(obj) is list:
  2700. minx = np.Inf
  2701. miny = np.Inf
  2702. maxx = -np.Inf
  2703. maxy = -np.Inf
  2704. for k in obj:
  2705. if type(k) is dict:
  2706. for key in k:
  2707. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  2708. minx = min(minx, minx_)
  2709. miny = min(miny, miny_)
  2710. maxx = max(maxx, maxx_)
  2711. maxy = max(maxy, maxy_)
  2712. else:
  2713. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2714. minx = min(minx, minx_)
  2715. miny = min(miny, miny_)
  2716. maxx = max(maxx, maxx_)
  2717. maxy = max(maxy, maxy_)
  2718. return minx, miny, maxx, maxy
  2719. else:
  2720. # it's a Shapely object, return it's bounds
  2721. return obj.bounds
  2722. if offset != 0.0:
  2723. offset_for_use = offset
  2724. if offset < 0:
  2725. a, b, c, d = bounds_rec(geometry.solid_geometry)
  2726. # if the offset is less than half of the total length or less than half of the total width of the
  2727. # solid geometry it's obvious we can't do the offset
  2728. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  2729. self.app.inform.emit('[ERROR_NOTCL] %s' % _(
  2730. "The Tool Offset value is too negative to use "
  2731. "for the current_geometry.\n"
  2732. "Raise the value (in module) and try again."))
  2733. return 'fail'
  2734. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  2735. # to continue
  2736. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  2737. offset_for_use = offset - 0.0000000001
  2738. for it in geometry.solid_geometry:
  2739. # if the geometry is a closed shape then create a Polygon out of it
  2740. if isinstance(it, LineString):
  2741. c = it.coords
  2742. if c[0] == c[-1]:
  2743. it = Polygon(it)
  2744. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  2745. else:
  2746. temp_solid_geometry = geometry.solid_geometry
  2747. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2748. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  2749. log.debug("%d paths" % len(flat_geometry))
  2750. try:
  2751. self.tooldia = float(tooldia) if tooldia else None
  2752. except ValueError:
  2753. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia else None
  2754. self.z_cut = float(z_cut) if z_cut is not None else None
  2755. self.z_move = float(z_move) if z_move is not None else None
  2756. self.feedrate = float(feedrate) if feedrate else None
  2757. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else None
  2758. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  2759. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  2760. self.spindledir = spindledir
  2761. self.dwell = dwell
  2762. self.dwelltime = float(dwelltime) if dwelltime else None
  2763. self.startz = float(startz) if startz is not None else None
  2764. self.z_end = float(endz) if endz is not None else None
  2765. self.z_depthpercut = float(depthpercut) if depthpercut else None
  2766. self.multidepth = multidepth
  2767. self.z_toolchange = float(toolchangez) if toolchangez is not None else None
  2768. try:
  2769. if toolchangexy == '':
  2770. self.xy_toolchange = None
  2771. else:
  2772. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  2773. if len(self.xy_toolchange) < 2:
  2774. self.app.inform.emit('[ERROR] %s' %
  2775. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2776. "in the format (x, y) \nbut now there is only one value, not two. "))
  2777. return 'fail'
  2778. except Exception as e:
  2779. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  2780. pass
  2781. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  2782. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  2783. if self.machinist_setting == 0:
  2784. if self.z_cut is None:
  2785. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2786. _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  2787. "other parameters."))
  2788. return 'fail'
  2789. if self.z_cut > 0:
  2790. self.app.inform.emit('[WARNING] %s' %
  2791. _("The Cut Z parameter has positive value. "
  2792. "It is the depth value to cut into material.\n"
  2793. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2794. "therefore the app will convert the value to negative."
  2795. "Check the resulting CNC code (Gcode etc)."))
  2796. self.z_cut = -self.z_cut
  2797. elif self.z_cut == 0:
  2798. self.app.inform.emit('[WARNING] %s: %s' %
  2799. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  2800. geometry.options['name']))
  2801. return 'fail'
  2802. if self.z_move is None:
  2803. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2804. _("Travel Z parameter is None or zero."))
  2805. return 'fail'
  2806. if self.z_move < 0:
  2807. self.app.inform.emit('[WARNING] %s' %
  2808. _("The Travel Z parameter has negative value. "
  2809. "It is the height value to travel between cuts.\n"
  2810. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  2811. "therefore the app will convert the value to positive."
  2812. "Check the resulting CNC code (Gcode etc)."))
  2813. self.z_move = -self.z_move
  2814. elif self.z_move == 0:
  2815. self.app.inform.emit('[WARNING] %s: %s' %
  2816. (_("The Z Travel parameter is zero. "
  2817. "This is dangerous, skipping file"), self.options['name']))
  2818. return 'fail'
  2819. # made sure that depth_per_cut is no more then the z_cut
  2820. if abs(self.z_cut) < self.z_depthpercut:
  2821. self.z_depthpercut = abs(self.z_cut)
  2822. # ## Index first and last points in paths
  2823. # What points to index.
  2824. def get_pts(o):
  2825. return [o.coords[0], o.coords[-1]]
  2826. # Create the indexed storage.
  2827. storage = FlatCAMRTreeStorage()
  2828. storage.get_points = get_pts
  2829. # Store the geometry
  2830. log.debug("Indexing geometry before generating G-Code...")
  2831. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  2832. for shape in flat_geometry:
  2833. if self.app.abort_flag:
  2834. # graceful abort requested by the user
  2835. raise FlatCAMApp.GracefulException
  2836. if shape is not None: # TODO: This shouldn't have happened.
  2837. storage.insert(shape)
  2838. if not append:
  2839. self.gcode = ""
  2840. # tell postprocessor the number of tool (for toolchange)
  2841. self.tool = tool_no
  2842. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2843. # given under the name 'toolC'
  2844. self.postdata['toolC'] = self.tooldia
  2845. # Initial G-Code
  2846. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  2847. p = self.pp_geometry
  2848. self.oldx = 0.0
  2849. self.oldy = 0.0
  2850. self.gcode = self.doformat(p.start_code)
  2851. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  2852. if toolchange is False:
  2853. self.gcode += self.doformat(p.lift_code, x=self.oldx , y=self.oldy ) # Move (up) to travel height
  2854. self.gcode += self.doformat(p.startz_code, x=self.oldx , y=self.oldy )
  2855. if toolchange:
  2856. # if "line_xyz" in self.pp_geometry_name:
  2857. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2858. # else:
  2859. # self.gcode += self.doformat(p.toolchange_code)
  2860. self.gcode += self.doformat(p.toolchange_code)
  2861. if 'laser' not in self.pp_geometry_name:
  2862. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2863. else:
  2864. # for laser this will disable the laser
  2865. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  2866. if self.dwell is True:
  2867. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2868. else:
  2869. if 'laser' not in self.pp_geometry_name:
  2870. self.gcode += self.doformat(p.spindle_code) # Spindle start
  2871. if self.dwell is True:
  2872. self.gcode += self.doformat(p.dwell_code) # Dwell time
  2873. total_travel = 0.0
  2874. total_cut = 0.0
  2875. # Iterate over geometry paths getting the nearest each time.
  2876. log.debug("Starting G-Code...")
  2877. self.app.inform.emit(_("Starting G-Code..."))
  2878. # variables to display the percentage of work done
  2879. geo_len = len(flat_geometry)
  2880. disp_number = 0
  2881. old_disp_number = 0
  2882. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  2883. if self.units == 'MM':
  2884. current_tooldia = float('%.2f' % float(self.tooldia))
  2885. else:
  2886. current_tooldia = float('%.4f' % float(self.tooldia))
  2887. self.app.inform.emit(
  2888. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2889. str(current_tooldia),
  2890. str(self.units))
  2891. )
  2892. path_count = 0
  2893. current_pt = (0, 0)
  2894. pt, geo = storage.nearest(current_pt)
  2895. try:
  2896. while True:
  2897. if self.app.abort_flag:
  2898. # graceful abort requested by the user
  2899. raise FlatCAMApp.GracefulException
  2900. path_count += 1
  2901. # Remove before modifying, otherwise deletion will fail.
  2902. storage.remove(geo)
  2903. # If last point in geometry is the nearest but prefer the first one if last point == first point
  2904. # then reverse coordinates.
  2905. if pt != geo.coords[0] and pt == geo.coords[-1]:
  2906. geo.coords = list(geo.coords)[::-1]
  2907. # ---------- Single depth/pass --------
  2908. if not multidepth:
  2909. # calculate the cut distance
  2910. total_cut += geo.length
  2911. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance, old_point=current_pt)
  2912. # --------- Multi-pass ---------
  2913. else:
  2914. # calculate the cut distance
  2915. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  2916. nr_cuts = 0
  2917. depth = abs(self.z_cut)
  2918. while depth > 0:
  2919. nr_cuts += 1
  2920. depth -= float(self.z_depthpercut)
  2921. total_cut += (geo.length * nr_cuts)
  2922. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  2923. postproc=p, old_point=current_pt)
  2924. # calculate the travel distance
  2925. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  2926. current_pt = geo.coords[-1]
  2927. pt, geo = storage.nearest(current_pt) # Next
  2928. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  2929. if old_disp_number < disp_number <= 100:
  2930. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2931. old_disp_number = disp_number
  2932. except StopIteration: # Nothing found in storage.
  2933. pass
  2934. log.debug("Finishing G-Code... %s paths traced." % path_count)
  2935. # add move to end position
  2936. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  2937. self.travel_distance += total_travel + total_cut
  2938. self.routing_time += total_cut / self.feedrate
  2939. # Finish
  2940. self.gcode += self.doformat(p.spindle_stop_code)
  2941. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  2942. self.gcode += self.doformat(p.end_code, x=0, y=0)
  2943. self.app.inform.emit(
  2944. '%s... %s %s' % (_("Finished G-Code generation"), str(path_count), _(" paths traced."))
  2945. )
  2946. return self.gcode
  2947. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  2948. """
  2949. Algorithm to generate from multitool Geometry.
  2950. Algorithm description:
  2951. ----------------------
  2952. Uses RTree to find the nearest path to follow.
  2953. :return: Gcode string
  2954. """
  2955. log.debug("Generate_from_solderpaste_geometry()")
  2956. # ## Index first and last points in paths
  2957. # What points to index.
  2958. def get_pts(o):
  2959. return [o.coords[0], o.coords[-1]]
  2960. self.gcode = ""
  2961. if not kwargs:
  2962. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  2963. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2964. _("There is no tool data in the SolderPaste geometry."))
  2965. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  2966. # given under the name 'toolC'
  2967. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  2968. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  2969. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  2970. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  2971. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  2972. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  2973. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  2974. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  2975. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  2976. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  2977. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  2978. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  2979. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  2980. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  2981. self.postdata['toolC'] = kwargs['tooldia']
  2982. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  2983. else self.app.defaults['tools_solderpaste_pp']
  2984. p = self.app.postprocessors[self.pp_solderpaste_name]
  2985. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  2986. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  2987. log.debug("%d paths" % len(flat_geometry))
  2988. # Create the indexed storage.
  2989. storage = FlatCAMRTreeStorage()
  2990. storage.get_points = get_pts
  2991. # Store the geometry
  2992. log.debug("Indexing geometry before generating G-Code...")
  2993. for shape in flat_geometry:
  2994. if shape is not None:
  2995. storage.insert(shape)
  2996. # Initial G-Code
  2997. self.gcode = self.doformat(p.start_code)
  2998. self.gcode += self.doformat(p.spindle_off_code)
  2999. self.gcode += self.doformat(p.toolchange_code)
  3000. # ## Iterate over geometry paths getting the nearest each time.
  3001. log.debug("Starting SolderPaste G-Code...")
  3002. path_count = 0
  3003. current_pt = (0, 0)
  3004. # variables to display the percentage of work done
  3005. geo_len = len(flat_geometry)
  3006. disp_number = 0
  3007. old_disp_number = 0
  3008. pt, geo = storage.nearest(current_pt)
  3009. try:
  3010. while True:
  3011. if self.app.abort_flag:
  3012. # graceful abort requested by the user
  3013. raise FlatCAMApp.GracefulException
  3014. path_count += 1
  3015. # Remove before modifying, otherwise deletion will fail.
  3016. storage.remove(geo)
  3017. # If last point in geometry is the nearest but prefer the first one if last point == first point
  3018. # then reverse coordinates.
  3019. if pt != geo.coords[0] and pt == geo.coords[-1]:
  3020. geo.coords = list(geo.coords)[::-1]
  3021. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  3022. current_pt = geo.coords[-1]
  3023. pt, geo = storage.nearest(current_pt) # Next
  3024. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  3025. if old_disp_number < disp_number <= 100:
  3026. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3027. old_disp_number = disp_number
  3028. except StopIteration: # Nothing found in storage.
  3029. pass
  3030. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  3031. self.app.inform.emit('%s... %s %s' %
  3032. (_("Finished SolderPste G-Code generation"),
  3033. str(path_count),
  3034. _("paths traced.")
  3035. )
  3036. )
  3037. # Finish
  3038. self.gcode += self.doformat(p.lift_code)
  3039. self.gcode += self.doformat(p.end_code)
  3040. return self.gcode
  3041. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  3042. gcode = ''
  3043. path = geometry.coords
  3044. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3045. if self.coordinates_type == "G90":
  3046. # For Absolute coordinates type G90
  3047. first_x = path[0][0]
  3048. first_y = path[0][1]
  3049. else:
  3050. # For Incremental coordinates type G91
  3051. first_x = path[0][0] - old_point[0]
  3052. first_y = path[0][1] - old_point[1]
  3053. if type(geometry) == LineString or type(geometry) == LinearRing:
  3054. # Move fast to 1st point
  3055. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3056. # Move down to cutting depth
  3057. gcode += self.doformat(p.z_feedrate_code)
  3058. gcode += self.doformat(p.down_z_start_code)
  3059. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  3060. gcode += self.doformat(p.dwell_fwd_code)
  3061. gcode += self.doformat(p.feedrate_z_dispense_code)
  3062. gcode += self.doformat(p.lift_z_dispense_code)
  3063. gcode += self.doformat(p.feedrate_xy_code)
  3064. # Cutting...
  3065. prev_x = first_x
  3066. prev_y = first_y
  3067. for pt in path[1:]:
  3068. if self.coordinates_type == "G90":
  3069. # For Absolute coordinates type G90
  3070. next_x = pt[0]
  3071. next_y = pt[1]
  3072. else:
  3073. # For Incremental coordinates type G91
  3074. next_x = pt[0] - prev_x
  3075. next_y = pt[1] - prev_y
  3076. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  3077. prev_x = next_x
  3078. prev_y = next_y
  3079. # Up to travelling height.
  3080. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  3081. gcode += self.doformat(p.spindle_rev_code)
  3082. gcode += self.doformat(p.down_z_stop_code)
  3083. gcode += self.doformat(p.spindle_off_code)
  3084. gcode += self.doformat(p.dwell_rev_code)
  3085. gcode += self.doformat(p.z_feedrate_code)
  3086. gcode += self.doformat(p.lift_code)
  3087. elif type(geometry) == Point:
  3088. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  3089. gcode += self.doformat(p.feedrate_z_dispense_code)
  3090. gcode += self.doformat(p.down_z_start_code)
  3091. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  3092. gcode += self.doformat(p.dwell_fwd_code)
  3093. gcode += self.doformat(p.lift_z_dispense_code)
  3094. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  3095. gcode += self.doformat(p.spindle_rev_code)
  3096. gcode += self.doformat(p.spindle_off_code)
  3097. gcode += self.doformat(p.down_z_stop_code)
  3098. gcode += self.doformat(p.dwell_rev_code)
  3099. gcode += self.doformat(p.z_feedrate_code)
  3100. gcode += self.doformat(p.lift_code)
  3101. return gcode
  3102. def create_gcode_single_pass(self, geometry, extracut, tolerance, old_point=(0, 0)):
  3103. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  3104. gcode_single_pass = ''
  3105. if type(geometry) == LineString or type(geometry) == LinearRing:
  3106. if extracut is False:
  3107. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, old_point=old_point)
  3108. else:
  3109. if geometry.is_ring:
  3110. gcode_single_pass = self.linear2gcode_extra(geometry, tolerance=tolerance, old_point=old_point)
  3111. else:
  3112. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance, old_point=old_point)
  3113. elif type(geometry) == Point:
  3114. gcode_single_pass = self.point2gcode(geometry)
  3115. else:
  3116. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  3117. return
  3118. return gcode_single_pass
  3119. def create_gcode_multi_pass(self, geometry, extracut, tolerance, postproc, old_point=(0, 0)):
  3120. gcode_multi_pass = ''
  3121. if isinstance(self.z_cut, Decimal):
  3122. z_cut = self.z_cut
  3123. else:
  3124. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  3125. if self.z_depthpercut is None:
  3126. self.z_depthpercut = z_cut
  3127. elif not isinstance(self.z_depthpercut, Decimal):
  3128. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  3129. depth = 0
  3130. reverse = False
  3131. while depth > z_cut:
  3132. # Increase depth. Limit to z_cut.
  3133. depth -= self.z_depthpercut
  3134. if depth < z_cut:
  3135. depth = z_cut
  3136. # Cut at specific depth and do not lift the tool.
  3137. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  3138. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  3139. # is inconsequential.
  3140. if type(geometry) == LineString or type(geometry) == LinearRing:
  3141. if extracut is False:
  3142. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False,
  3143. old_point=old_point)
  3144. else:
  3145. if geometry.is_ring:
  3146. gcode_multi_pass += self.linear2gcode_extra(geometry, tolerance=tolerance, z_cut=depth,
  3147. up=False, old_point=old_point)
  3148. else:
  3149. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False,
  3150. old_point=old_point)
  3151. # Ignore multi-pass for points.
  3152. elif type(geometry) == Point:
  3153. gcode_multi_pass += self.point2gcode(geometry, old_point=old_point)
  3154. break # Ignoring ...
  3155. else:
  3156. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  3157. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  3158. if type(geometry) == LineString:
  3159. geometry.coords = list(geometry.coords)[::-1]
  3160. reverse = True
  3161. # If geometry is reversed, revert.
  3162. if reverse:
  3163. if type(geometry) == LineString:
  3164. geometry.coords = list(geometry.coords)[::-1]
  3165. # Lift the tool
  3166. gcode_multi_pass += self.doformat(postproc.lift_code, x=old_point[0], y=old_point[1])
  3167. return gcode_multi_pass
  3168. def codes_split(self, gline):
  3169. """
  3170. Parses a line of G-Code such as "G01 X1234 Y987" into
  3171. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  3172. :param gline: G-Code line string
  3173. :return: Dictionary with parsed line.
  3174. """
  3175. command = {}
  3176. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3177. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  3178. if match_z:
  3179. command['G'] = 0
  3180. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  3181. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  3182. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  3183. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  3184. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  3185. if match_pa:
  3186. command['G'] = 0
  3187. command['X'] = float(match_pa.group(1).replace(" ", ""))
  3188. command['Y'] = float(match_pa.group(2).replace(" ", ""))
  3189. match_pen = re.search(r"^(P[U|D])", gline)
  3190. if match_pen:
  3191. if match_pen.group(1) == 'PU':
  3192. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  3193. # therefore the move is of kind T (travel)
  3194. command['Z'] = 1
  3195. else:
  3196. command['Z'] = 0
  3197. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name or \
  3198. (self.pp_solderpaste_name is not None and 'Paste' in self.pp_solderpaste_name):
  3199. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  3200. if match_lsr:
  3201. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  3202. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  3203. match_lsr_pos = re.search(r"^(M0[3|5])", gline)
  3204. if match_lsr_pos:
  3205. if 'M05' in match_lsr_pos.group(1):
  3206. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  3207. # therefore the move is of kind T (travel)
  3208. command['Z'] = 1
  3209. else:
  3210. command['Z'] = 0
  3211. elif self.pp_solderpaste_name is not None:
  3212. if 'Paste' in self.pp_solderpaste_name:
  3213. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  3214. if match_paste:
  3215. command['X'] = float(match_paste.group(1).replace(" ", ""))
  3216. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  3217. else:
  3218. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  3219. while match:
  3220. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  3221. gline = gline[match.end():]
  3222. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  3223. return command
  3224. def gcode_parse(self, force_parsing=None):
  3225. """
  3226. G-Code parser (from self.gcode). Generates dictionary with
  3227. single-segment LineString's and "kind" indicating cut or travel,
  3228. fast or feedrate speed.
  3229. """
  3230. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  3231. # Results go here
  3232. geometry = []
  3233. # Last known instruction
  3234. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  3235. # Current path: temporary storage until tool is
  3236. # lifted or lowered.
  3237. if self.toolchange_xy_type == "excellon":
  3238. if self.app.defaults["excellon_toolchangexy"] == '':
  3239. pos_xy = [0, 0]
  3240. else:
  3241. pos_xy = [float(eval(a)) for a in self.app.defaults["excellon_toolchangexy"].split(",")]
  3242. else:
  3243. if self.app.defaults["geometry_toolchangexy"] == '':
  3244. pos_xy = [0, 0]
  3245. else:
  3246. pos_xy = [float(eval(a)) for a in self.app.defaults["geometry_toolchangexy"].split(",")]
  3247. path = [pos_xy]
  3248. # path = [(0, 0)]
  3249. self.app.inform.emit('%s: %d' % (_("Parsing GCode file. Number of lines"), len(self.gcode.splitlines())))
  3250. # Process every instruction
  3251. for line in StringIO(self.gcode):
  3252. if force_parsing is False or force_parsing is None:
  3253. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  3254. return "fail"
  3255. gobj = self.codes_split(line)
  3256. # ## Units
  3257. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  3258. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  3259. continue
  3260. # ## Changing height
  3261. if 'Z' in gobj:
  3262. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3263. pass
  3264. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  3265. pass
  3266. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  3267. pass
  3268. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  3269. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  3270. pass
  3271. else:
  3272. log.warning("Non-orthogonal motion: From %s" % str(current))
  3273. log.warning(" To: %s" % str(gobj))
  3274. current['Z'] = gobj['Z']
  3275. # Store the path into geometry and reset path
  3276. if len(path) > 1:
  3277. geometry.append({"geom": LineString(path),
  3278. "kind": kind})
  3279. path = [path[-1]] # Start with the last point of last path.
  3280. # create the geometry for the holes created when drilling Excellon drills
  3281. if self.origin_kind == 'excellon':
  3282. if current['Z'] < 0:
  3283. current_drill_point_coords = (float('%.4f' % current['X']), float('%.4f' % current['Y']))
  3284. # find the drill diameter knowing the drill coordinates
  3285. for pt_dict in self.exc_drills:
  3286. point_in_dict_coords = (float('%.4f' % pt_dict['point'].x),
  3287. float('%.4f' % pt_dict['point'].y))
  3288. if point_in_dict_coords == current_drill_point_coords:
  3289. tool = pt_dict['tool']
  3290. dia = self.exc_tools[tool]['C']
  3291. kind = ['C', 'F']
  3292. geometry.append({"geom": Point(current_drill_point_coords).
  3293. buffer(dia/2).exterior,
  3294. "kind": kind})
  3295. break
  3296. if 'G' in gobj:
  3297. current['G'] = int(gobj['G'])
  3298. if 'X' in gobj or 'Y' in gobj:
  3299. if 'X' in gobj:
  3300. x = gobj['X']
  3301. # current['X'] = x
  3302. else:
  3303. x = current['X']
  3304. if 'Y' in gobj:
  3305. y = gobj['Y']
  3306. else:
  3307. y = current['Y']
  3308. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  3309. if current['Z'] > 0:
  3310. kind[0] = 'T'
  3311. if current['G'] > 0:
  3312. kind[1] = 'S'
  3313. if current['G'] in [0, 1]: # line
  3314. path.append((x, y))
  3315. arcdir = [None, None, "cw", "ccw"]
  3316. if current['G'] in [2, 3]: # arc
  3317. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  3318. radius = np.sqrt(gobj['I']**2 + gobj['J']**2)
  3319. start = np.arctan2(-gobj['J'], -gobj['I'])
  3320. stop = np.arctan2(-center[1] + y, -center[0] + x)
  3321. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle / 4))
  3322. # Update current instruction
  3323. for code in gobj:
  3324. current[code] = gobj[code]
  3325. self.app.inform.emit('%s...' % _("Creating Geometry from the parsed GCode file. "))
  3326. # There might not be a change in height at the
  3327. # end, therefore, see here too if there is
  3328. # a final path.
  3329. if len(path) > 1:
  3330. geometry.append({"geom": LineString(path),
  3331. "kind": kind})
  3332. self.gcode_parsed = geometry
  3333. return geometry
  3334. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  3335. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  3336. # alpha={"T": 0.3, "C": 1.0}):
  3337. # """
  3338. # Creates a Matplotlib figure with a plot of the
  3339. # G-code job.
  3340. # """
  3341. # if tooldia is None:
  3342. # tooldia = self.tooldia
  3343. #
  3344. # fig = Figure(dpi=dpi)
  3345. # ax = fig.add_subplot(111)
  3346. # ax.set_aspect(1)
  3347. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  3348. # ax.set_xlim(xmin-margin, xmax+margin)
  3349. # ax.set_ylim(ymin-margin, ymax+margin)
  3350. #
  3351. # if tooldia == 0:
  3352. # for geo in self.gcode_parsed:
  3353. # linespec = '--'
  3354. # linecolor = color[geo['kind'][0]][1]
  3355. # if geo['kind'][0] == 'C':
  3356. # linespec = 'k-'
  3357. # x, y = geo['geom'].coords.xy
  3358. # ax.plot(x, y, linespec, color=linecolor)
  3359. # else:
  3360. # for geo in self.gcode_parsed:
  3361. # poly = geo['geom'].buffer(tooldia/2.0)
  3362. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  3363. # edgecolor=color[geo['kind'][0]][1],
  3364. # alpha=alpha[geo['kind'][0]], zorder=2)
  3365. # ax.add_patch(patch)
  3366. #
  3367. # return fig
  3368. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  3369. color={"T": ["#F0E24D4C", "#B5AB3A4C"], "C": ["#5E6CFFFF", "#4650BDFF"]},
  3370. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  3371. """
  3372. Plots the G-code job onto the given axes.
  3373. :param tooldia: Tool diameter.
  3374. :param dpi: Not used!
  3375. :param margin: Not used!
  3376. :param color: Color specification.
  3377. :param alpha: Transparency specification.
  3378. :param tool_tolerance: Tolerance when drawing the toolshape.
  3379. :param obj
  3380. :param visible
  3381. :param kind
  3382. :return: None
  3383. """
  3384. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3385. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  3386. path_num = 0
  3387. if tooldia is None:
  3388. tooldia = self.tooldia
  3389. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  3390. if isinstance(tooldia, list):
  3391. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  3392. if tooldia == 0:
  3393. for geo in gcode_parsed:
  3394. if kind == 'all':
  3395. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  3396. elif kind == 'travel':
  3397. if geo['kind'][0] == 'T':
  3398. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  3399. elif kind == 'cut':
  3400. if geo['kind'][0] == 'C':
  3401. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  3402. else:
  3403. text = []
  3404. pos = []
  3405. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3406. if self.coordinates_type == "G90":
  3407. # For Absolute coordinates type G90
  3408. for geo in gcode_parsed:
  3409. if geo['kind'][0] == 'T':
  3410. current_position = geo['geom'].coords[0]
  3411. if current_position not in pos:
  3412. pos.append(current_position)
  3413. path_num += 1
  3414. text.append(str(path_num))
  3415. current_position = geo['geom'].coords[-1]
  3416. if current_position not in pos:
  3417. pos.append(current_position)
  3418. path_num += 1
  3419. text.append(str(path_num))
  3420. # plot the geometry of Excellon objects
  3421. if self.origin_kind == 'excellon':
  3422. try:
  3423. poly = Polygon(geo['geom'])
  3424. except ValueError:
  3425. # if the geos are travel lines it will enter into Exception
  3426. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3427. poly = poly.simplify(tool_tolerance)
  3428. else:
  3429. # plot the geometry of any objects other than Excellon
  3430. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3431. poly = poly.simplify(tool_tolerance)
  3432. if kind == 'all':
  3433. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3434. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3435. elif kind == 'travel':
  3436. if geo['kind'][0] == 'T':
  3437. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3438. visible=visible, layer=2)
  3439. elif kind == 'cut':
  3440. if geo['kind'][0] == 'C':
  3441. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3442. visible=visible, layer=1)
  3443. else:
  3444. # For Incremental coordinates type G91
  3445. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3446. _('G91 coordinates not implemented ...'))
  3447. for geo in gcode_parsed:
  3448. if geo['kind'][0] == 'T':
  3449. current_position = geo['geom'].coords[0]
  3450. if current_position not in pos:
  3451. pos.append(current_position)
  3452. path_num += 1
  3453. text.append(str(path_num))
  3454. current_position = geo['geom'].coords[-1]
  3455. if current_position not in pos:
  3456. pos.append(current_position)
  3457. path_num += 1
  3458. text.append(str(path_num))
  3459. # plot the geometry of Excellon objects
  3460. if self.origin_kind == 'excellon':
  3461. try:
  3462. poly = Polygon(geo['geom'])
  3463. except ValueError:
  3464. # if the geos are travel lines it will enter into Exception
  3465. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3466. poly = poly.simplify(tool_tolerance)
  3467. else:
  3468. # plot the geometry of any objects other than Excellon
  3469. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3470. poly = poly.simplify(tool_tolerance)
  3471. if kind == 'all':
  3472. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3473. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3474. elif kind == 'travel':
  3475. if geo['kind'][0] == 'T':
  3476. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3477. visible=visible, layer=2)
  3478. elif kind == 'cut':
  3479. if geo['kind'][0] == 'C':
  3480. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3481. visible=visible, layer=1)
  3482. # current_x = gcode_parsed[0]['geom'].coords[0][0]
  3483. # current_y = gcode_parsed[0]['geom'].coords[0][1]
  3484. # old_pos = (
  3485. # current_x,
  3486. # current_y
  3487. # )
  3488. #
  3489. # for geo in gcode_parsed:
  3490. # if geo['kind'][0] == 'T':
  3491. # current_position = (
  3492. # geo['geom'].coords[0][0] + old_pos[0],
  3493. # geo['geom'].coords[0][1] + old_pos[1]
  3494. # )
  3495. # if current_position not in pos:
  3496. # pos.append(current_position)
  3497. # path_num += 1
  3498. # text.append(str(path_num))
  3499. #
  3500. # delta = (
  3501. # geo['geom'].coords[-1][0] - geo['geom'].coords[0][0],
  3502. # geo['geom'].coords[-1][1] - geo['geom'].coords[0][1]
  3503. # )
  3504. # current_position = (
  3505. # current_position[0] + geo['geom'].coords[-1][0],
  3506. # current_position[1] + geo['geom'].coords[-1][1]
  3507. # )
  3508. # if current_position not in pos:
  3509. # pos.append(current_position)
  3510. # path_num += 1
  3511. # text.append(str(path_num))
  3512. #
  3513. # # plot the geometry of Excellon objects
  3514. # if self.origin_kind == 'excellon':
  3515. # if isinstance(geo['geom'], Point):
  3516. # # if geo is Point
  3517. # current_position = (
  3518. # current_position[0] + geo['geom'].x,
  3519. # current_position[1] + geo['geom'].y
  3520. # )
  3521. # poly = Polygon(Point(current_position))
  3522. # elif isinstance(geo['geom'], LineString):
  3523. # # if the geos are travel lines (LineStrings)
  3524. # new_line_pts = []
  3525. # old_line_pos = deepcopy(current_position)
  3526. # for p in list(geo['geom'].coords):
  3527. # current_position = (
  3528. # current_position[0] + p[0],
  3529. # current_position[1] + p[1]
  3530. # )
  3531. # new_line_pts.append(current_position)
  3532. # old_line_pos = p
  3533. # new_line = LineString(new_line_pts)
  3534. #
  3535. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3536. # poly = poly.simplify(tool_tolerance)
  3537. # else:
  3538. # # plot the geometry of any objects other than Excellon
  3539. # new_line_pts = []
  3540. # old_line_pos = deepcopy(current_position)
  3541. # for p in list(geo['geom'].coords):
  3542. # current_position = (
  3543. # current_position[0] + p[0],
  3544. # current_position[1] + p[1]
  3545. # )
  3546. # new_line_pts.append(current_position)
  3547. # old_line_pos = p
  3548. # new_line = LineString(new_line_pts)
  3549. #
  3550. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3551. # poly = poly.simplify(tool_tolerance)
  3552. #
  3553. # old_pos = deepcopy(current_position)
  3554. #
  3555. # if kind == 'all':
  3556. # obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3557. # visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3558. # elif kind == 'travel':
  3559. # if geo['kind'][0] == 'T':
  3560. # obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3561. # visible=visible, layer=2)
  3562. # elif kind == 'cut':
  3563. # if geo['kind'][0] == 'C':
  3564. # obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3565. # visible=visible, layer=1)
  3566. try:
  3567. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  3568. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  3569. color=self.app.defaults["cncjob_annotation_fontcolor"])
  3570. except Exception as e:
  3571. pass
  3572. def create_geometry(self):
  3573. self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"),
  3574. str(len(self.gcode_parsed))))
  3575. # TODO: This takes forever. Too much data?
  3576. # self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3577. # This is much faster but not so nice to look at as you can see different segments of the geometry
  3578. self.solid_geometry = [geo['geom'] for geo in self.gcode_parsed]
  3579. return self.solid_geometry
  3580. # code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  3581. def segment(self, coords):
  3582. """
  3583. break long linear lines to make it more auto level friendly
  3584. """
  3585. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  3586. return list(coords)
  3587. path = [coords[0]]
  3588. # break the line in either x or y dimension only
  3589. def linebreak_single(line, dim, dmax):
  3590. if dmax <= 0:
  3591. return None
  3592. if line[1][dim] > line[0][dim]:
  3593. sign = 1.0
  3594. d = line[1][dim] - line[0][dim]
  3595. else:
  3596. sign = -1.0
  3597. d = line[0][dim] - line[1][dim]
  3598. if d > dmax:
  3599. # make sure we don't make any new lines too short
  3600. if d > dmax * 2:
  3601. dd = dmax
  3602. else:
  3603. dd = d / 2
  3604. other = dim ^ 1
  3605. return (line[0][dim] + dd * sign, line[0][other] + \
  3606. dd * (line[1][other] - line[0][other]) / d)
  3607. return None
  3608. # recursively breaks down a given line until it is within the
  3609. # required step size
  3610. def linebreak(line):
  3611. pt_new = linebreak_single(line, 0, self.segx)
  3612. if pt_new is None:
  3613. pt_new2 = linebreak_single(line, 1, self.segy)
  3614. else:
  3615. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  3616. if pt_new2 is not None:
  3617. pt_new = pt_new2[::-1]
  3618. if pt_new is None:
  3619. path.append(line[1])
  3620. else:
  3621. path.append(pt_new)
  3622. linebreak((pt_new, line[1]))
  3623. for pt in coords[1:]:
  3624. linebreak((path[-1], pt))
  3625. return path
  3626. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  3627. z_cut=None, z_move=None, zdownrate=None,
  3628. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3629. """
  3630. Generates G-code to cut along the linear feature.
  3631. :param linear: The path to cut along.
  3632. :type: Shapely.LinearRing or Shapely.Linear String
  3633. :param tolerance: All points in the simplified object will be within the
  3634. tolerance distance of the original geometry.
  3635. :type tolerance: float
  3636. :param feedrate: speed for cut on X - Y plane
  3637. :param feedrate_z: speed for cut on Z plane
  3638. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3639. :return: G-code to cut along the linear feature.
  3640. :rtype: str
  3641. """
  3642. if z_cut is None:
  3643. z_cut = self.z_cut
  3644. if z_move is None:
  3645. z_move = self.z_move
  3646. #
  3647. # if zdownrate is None:
  3648. # zdownrate = self.zdownrate
  3649. if feedrate is None:
  3650. feedrate = self.feedrate
  3651. if feedrate_z is None:
  3652. feedrate_z = self.z_feedrate
  3653. if feedrate_rapid is None:
  3654. feedrate_rapid = self.feedrate_rapid
  3655. # Simplify paths?
  3656. if tolerance > 0:
  3657. target_linear = linear.simplify(tolerance)
  3658. else:
  3659. target_linear = linear
  3660. gcode = ""
  3661. # path = list(target_linear.coords)
  3662. path = self.segment(target_linear.coords)
  3663. p = self.pp_geometry
  3664. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3665. if self.coordinates_type == "G90":
  3666. # For Absolute coordinates type G90
  3667. first_x = path[0][0]
  3668. first_y = path[0][1]
  3669. else:
  3670. # For Incremental coordinates type G91
  3671. first_x = path[0][0] - old_point[0]
  3672. first_y = path[0][1] - old_point[1]
  3673. # Move fast to 1st point
  3674. if not cont:
  3675. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3676. # Move down to cutting depth
  3677. if down:
  3678. # Different feedrate for vertical cut?
  3679. gcode += self.doformat(p.z_feedrate_code)
  3680. # gcode += self.doformat(p.feedrate_code)
  3681. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3682. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3683. # Cutting...
  3684. prev_x = first_x
  3685. prev_y = first_y
  3686. for pt in path[1:]:
  3687. if self.app.abort_flag:
  3688. # graceful abort requested by the user
  3689. raise FlatCAMApp.GracefulException
  3690. if self.coordinates_type == "G90":
  3691. # For Absolute coordinates type G90
  3692. next_x = pt[0]
  3693. next_y = pt[1]
  3694. else:
  3695. # For Incremental coordinates type G91
  3696. # next_x = pt[0] - prev_x
  3697. # next_y = pt[1] - prev_y
  3698. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3699. _('G91 coordinates not implemented ...'))
  3700. next_x = pt[0]
  3701. next_y = pt[1]
  3702. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3703. prev_x = pt[0]
  3704. prev_y = pt[1]
  3705. # Up to travelling height.
  3706. if up:
  3707. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  3708. return gcode
  3709. def linear2gcode_extra(self, linear, tolerance=0, down=True, up=True,
  3710. z_cut=None, z_move=None, zdownrate=None,
  3711. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3712. """
  3713. Generates G-code to cut along the linear feature.
  3714. :param linear: The path to cut along.
  3715. :type: Shapely.LinearRing or Shapely.Linear String
  3716. :param tolerance: All points in the simplified object will be within the
  3717. tolerance distance of the original geometry.
  3718. :type tolerance: float
  3719. :param feedrate: speed for cut on X - Y plane
  3720. :param feedrate_z: speed for cut on Z plane
  3721. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3722. :return: G-code to cut along the linear feature.
  3723. :rtype: str
  3724. """
  3725. if z_cut is None:
  3726. z_cut = self.z_cut
  3727. if z_move is None:
  3728. z_move = self.z_move
  3729. #
  3730. # if zdownrate is None:
  3731. # zdownrate = self.zdownrate
  3732. if feedrate is None:
  3733. feedrate = self.feedrate
  3734. if feedrate_z is None:
  3735. feedrate_z = self.z_feedrate
  3736. if feedrate_rapid is None:
  3737. feedrate_rapid = self.feedrate_rapid
  3738. # Simplify paths?
  3739. if tolerance > 0:
  3740. target_linear = linear.simplify(tolerance)
  3741. else:
  3742. target_linear = linear
  3743. gcode = ""
  3744. path = list(target_linear.coords)
  3745. p = self.pp_geometry
  3746. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3747. if self.coordinates_type == "G90":
  3748. # For Absolute coordinates type G90
  3749. first_x = path[0][0]
  3750. first_y = path[0][1]
  3751. else:
  3752. # For Incremental coordinates type G91
  3753. first_x = path[0][0] - old_point[0]
  3754. first_y = path[0][1] - old_point[1]
  3755. # Move fast to 1st point
  3756. if not cont:
  3757. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3758. # Move down to cutting depth
  3759. if down:
  3760. # Different feedrate for vertical cut?
  3761. if self.z_feedrate is not None:
  3762. gcode += self.doformat(p.z_feedrate_code)
  3763. # gcode += self.doformat(p.feedrate_code)
  3764. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3765. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3766. else:
  3767. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  3768. # Cutting...
  3769. prev_x = first_x
  3770. prev_y = first_y
  3771. for pt in path[1:]:
  3772. if self.app.abort_flag:
  3773. # graceful abort requested by the user
  3774. raise FlatCAMApp.GracefulException
  3775. if self.coordinates_type == "G90":
  3776. # For Absolute coordinates type G90
  3777. next_x = pt[0]
  3778. next_y = pt[1]
  3779. else:
  3780. # For Incremental coordinates type G91
  3781. # For Incremental coordinates type G91
  3782. # next_x = pt[0] - prev_x
  3783. # next_y = pt[1] - prev_y
  3784. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3785. _('G91 coordinates not implemented ...'))
  3786. next_x = pt[0]
  3787. next_y = pt[1]
  3788. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3789. prev_x = pt[0]
  3790. prev_y = pt[1]
  3791. # this line is added to create an extra cut over the first point in patch
  3792. # to make sure that we remove the copper leftovers
  3793. # Linear motion to the 1st point in the cut path
  3794. if self.coordinates_type == "G90":
  3795. # For Absolute coordinates type G90
  3796. last_x = path[1][0]
  3797. last_y = path[1][1]
  3798. else:
  3799. # For Incremental coordinates type G91
  3800. last_x = path[1][0] - first_x
  3801. last_y = path[1][1] - first_y
  3802. gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  3803. # Up to travelling height.
  3804. if up:
  3805. gcode += self.doformat(p.lift_code, x=last_x, y=last_y, z_move=z_move) # Stop cutting
  3806. return gcode
  3807. def point2gcode(self, point, old_point=(0, 0)):
  3808. gcode = ""
  3809. if self.app.abort_flag:
  3810. # graceful abort requested by the user
  3811. raise FlatCAMApp.GracefulException
  3812. path = list(point.coords)
  3813. p = self.pp_geometry
  3814. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3815. if self.coordinates_type == "G90":
  3816. # For Absolute coordinates type G90
  3817. first_x = path[0][0]
  3818. first_y = path[0][1]
  3819. else:
  3820. # For Incremental coordinates type G91
  3821. # first_x = path[0][0] - old_point[0]
  3822. # first_y = path[0][1] - old_point[1]
  3823. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3824. _('G91 coordinates not implemented ...'))
  3825. first_x = path[0][0]
  3826. first_y = path[0][1]
  3827. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  3828. if self.z_feedrate is not None:
  3829. gcode += self.doformat(p.z_feedrate_code)
  3830. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut)
  3831. gcode += self.doformat(p.feedrate_code)
  3832. else:
  3833. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut) # Start cutting
  3834. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  3835. return gcode
  3836. def export_svg(self, scale_stroke_factor=0.00):
  3837. """
  3838. Exports the CNC Job as a SVG Element
  3839. :scale_factor: float
  3840. :return: SVG Element string
  3841. """
  3842. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  3843. # If not specified then try and use the tool diameter
  3844. # This way what is on screen will match what is outputed for the svg
  3845. # This is quite a useful feature for svg's used with visicut
  3846. if scale_stroke_factor <= 0:
  3847. scale_stroke_factor = self.options['tooldia'] / 2
  3848. # If still 0 then default to 0.05
  3849. # This value appears to work for zooming, and getting the output svg line width
  3850. # to match that viewed on screen with FlatCam
  3851. if scale_stroke_factor == 0:
  3852. scale_stroke_factor = 0.01
  3853. # Separate the list of cuts and travels into 2 distinct lists
  3854. # This way we can add different formatting / colors to both
  3855. cuts = []
  3856. travels = []
  3857. for g in self.gcode_parsed:
  3858. if self.app.abort_flag:
  3859. # graceful abort requested by the user
  3860. raise FlatCAMApp.GracefulException
  3861. if g['kind'][0] == 'C': cuts.append(g)
  3862. if g['kind'][0] == 'T': travels.append(g)
  3863. # Used to determine the overall board size
  3864. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3865. # Convert the cuts and travels into single geometry objects we can render as svg xml
  3866. if travels:
  3867. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  3868. if self.app.abort_flag:
  3869. # graceful abort requested by the user
  3870. raise FlatCAMApp.GracefulException
  3871. if cuts:
  3872. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  3873. # Render the SVG Xml
  3874. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  3875. # It's better to have the travels sitting underneath the cuts for visicut
  3876. svg_elem = ""
  3877. if travels:
  3878. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  3879. if cuts:
  3880. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  3881. return svg_elem
  3882. def bounds(self):
  3883. """
  3884. Returns coordinates of rectangular bounds
  3885. of geometry: (xmin, ymin, xmax, ymax).
  3886. """
  3887. # fixed issue of getting bounds only for one level lists of objects
  3888. # now it can get bounds for nested lists of objects
  3889. log.debug("camlib.CNCJob.bounds()")
  3890. def bounds_rec(obj):
  3891. if type(obj) is list:
  3892. minx = np.Inf
  3893. miny = np.Inf
  3894. maxx = -np.Inf
  3895. maxy = -np.Inf
  3896. for k in obj:
  3897. if type(k) is dict:
  3898. for key in k:
  3899. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3900. minx = min(minx, minx_)
  3901. miny = min(miny, miny_)
  3902. maxx = max(maxx, maxx_)
  3903. maxy = max(maxy, maxy_)
  3904. else:
  3905. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3906. minx = min(minx, minx_)
  3907. miny = min(miny, miny_)
  3908. maxx = max(maxx, maxx_)
  3909. maxy = max(maxy, maxy_)
  3910. return minx, miny, maxx, maxy
  3911. else:
  3912. # it's a Shapely object, return it's bounds
  3913. return obj.bounds
  3914. if self.multitool is False:
  3915. log.debug("CNCJob->bounds()")
  3916. if self.solid_geometry is None:
  3917. log.debug("solid_geometry is None")
  3918. return 0, 0, 0, 0
  3919. bounds_coords = bounds_rec(self.solid_geometry)
  3920. else:
  3921. minx = np.Inf
  3922. miny = np.Inf
  3923. maxx = -np.Inf
  3924. maxy = -np.Inf
  3925. for k, v in self.cnc_tools.items():
  3926. minx = np.Inf
  3927. miny = np.Inf
  3928. maxx = -np.Inf
  3929. maxy = -np.Inf
  3930. try:
  3931. for k in v['solid_geometry']:
  3932. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3933. minx = min(minx, minx_)
  3934. miny = min(miny, miny_)
  3935. maxx = max(maxx, maxx_)
  3936. maxy = max(maxy, maxy_)
  3937. except TypeError:
  3938. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  3939. minx = min(minx, minx_)
  3940. miny = min(miny, miny_)
  3941. maxx = max(maxx, maxx_)
  3942. maxy = max(maxy, maxy_)
  3943. bounds_coords = minx, miny, maxx, maxy
  3944. return bounds_coords
  3945. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  3946. def scale(self, xfactor, yfactor=None, point=None):
  3947. """
  3948. Scales all the geometry on the XY plane in the object by the
  3949. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  3950. not altered.
  3951. :param factor: Number by which to scale the object.
  3952. :type factor: float
  3953. :param point: the (x,y) coords for the point of origin of scale
  3954. :type tuple of floats
  3955. :return: None
  3956. :rtype: None
  3957. """
  3958. log.debug("camlib.CNCJob.scale()")
  3959. if yfactor is None:
  3960. yfactor = xfactor
  3961. if point is None:
  3962. px = 0
  3963. py = 0
  3964. else:
  3965. px, py = point
  3966. def scale_g(g):
  3967. """
  3968. :param g: 'g' parameter it's a gcode string
  3969. :return: scaled gcode string
  3970. """
  3971. temp_gcode = ''
  3972. header_start = False
  3973. header_stop = False
  3974. units = self.app.defaults['units'].upper()
  3975. lines = StringIO(g)
  3976. for line in lines:
  3977. # this changes the GCODE header ---- UGLY HACK
  3978. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  3979. header_start = True
  3980. if "G20" in line or "G21" in line:
  3981. header_start = False
  3982. header_stop = True
  3983. if header_start is True:
  3984. header_stop = False
  3985. if "in" in line:
  3986. if units == 'MM':
  3987. line = line.replace("in", "mm")
  3988. if "mm" in line:
  3989. if units == 'IN':
  3990. line = line.replace("mm", "in")
  3991. # find any float number in header (even multiple on the same line) and convert it
  3992. numbers_in_header = re.findall(self.g_nr_re, line)
  3993. if numbers_in_header:
  3994. for nr in numbers_in_header:
  3995. new_nr = float(nr) * xfactor
  3996. # replace the updated string
  3997. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  3998. )
  3999. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  4000. if header_stop is True:
  4001. if "G20" in line:
  4002. if units == 'MM':
  4003. line = line.replace("G20", "G21")
  4004. if "G21" in line:
  4005. if units == 'IN':
  4006. line = line.replace("G21", "G20")
  4007. # find the X group
  4008. match_x = self.g_x_re.search(line)
  4009. if match_x:
  4010. if match_x.group(1) is not None:
  4011. new_x = float(match_x.group(1)[1:]) * xfactor
  4012. # replace the updated string
  4013. line = line.replace(
  4014. match_x.group(1),
  4015. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  4016. )
  4017. # find the Y group
  4018. match_y = self.g_y_re.search(line)
  4019. if match_y:
  4020. if match_y.group(1) is not None:
  4021. new_y = float(match_y.group(1)[1:]) * yfactor
  4022. line = line.replace(
  4023. match_y.group(1),
  4024. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4025. )
  4026. # find the Z group
  4027. match_z = self.g_z_re.search(line)
  4028. if match_z:
  4029. if match_z.group(1) is not None:
  4030. new_z = float(match_z.group(1)[1:]) * xfactor
  4031. line = line.replace(
  4032. match_z.group(1),
  4033. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  4034. )
  4035. # find the F group
  4036. match_f = self.g_f_re.search(line)
  4037. if match_f:
  4038. if match_f.group(1) is not None:
  4039. new_f = float(match_f.group(1)[1:]) * xfactor
  4040. line = line.replace(
  4041. match_f.group(1),
  4042. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  4043. )
  4044. # find the T group (tool dia on toolchange)
  4045. match_t = self.g_t_re.search(line)
  4046. if match_t:
  4047. if match_t.group(1) is not None:
  4048. new_t = float(match_t.group(1)[1:]) * xfactor
  4049. line = line.replace(
  4050. match_t.group(1),
  4051. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  4052. )
  4053. temp_gcode += line
  4054. lines.close()
  4055. header_stop = False
  4056. return temp_gcode
  4057. if self.multitool is False:
  4058. # offset Gcode
  4059. self.gcode = scale_g(self.gcode)
  4060. # variables to display the percentage of work done
  4061. self.geo_len = 0
  4062. try:
  4063. for g in self.gcode_parsed:
  4064. self.geo_len += 1
  4065. except TypeError:
  4066. self.geo_len = 1
  4067. self.old_disp_number = 0
  4068. self.el_count = 0
  4069. # scale geometry
  4070. for g in self.gcode_parsed:
  4071. try:
  4072. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  4073. except AttributeError:
  4074. return g['geom']
  4075. self.el_count += 1
  4076. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4077. if self.old_disp_number < disp_number <= 100:
  4078. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4079. self.old_disp_number = disp_number
  4080. self.create_geometry()
  4081. else:
  4082. for k, v in self.cnc_tools.items():
  4083. # scale Gcode
  4084. v['gcode'] = scale_g(v['gcode'])
  4085. # variables to display the percentage of work done
  4086. self.geo_len = 0
  4087. try:
  4088. for g in v['gcode_parsed']:
  4089. self.geo_len += 1
  4090. except TypeError:
  4091. self.geo_len = 1
  4092. self.old_disp_number = 0
  4093. self.el_count = 0
  4094. # scale gcode_parsed
  4095. for g in v['gcode_parsed']:
  4096. try:
  4097. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  4098. except AttributeError:
  4099. return g['geom']
  4100. self.el_count += 1
  4101. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4102. if self.old_disp_number < disp_number <= 100:
  4103. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4104. self.old_disp_number = disp_number
  4105. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  4106. self.create_geometry()
  4107. self.app.proc_container.new_text = ''
  4108. def offset(self, vect):
  4109. """
  4110. Offsets all the geometry on the XY plane in the object by the
  4111. given vector.
  4112. Offsets all the GCODE on the XY plane in the object by the
  4113. given vector.
  4114. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  4115. :param vect: (x, y) offset vector.
  4116. :type vect: tuple
  4117. :return: None
  4118. """
  4119. log.debug("camlib.CNCJob.offset()")
  4120. dx, dy = vect
  4121. def offset_g(g):
  4122. """
  4123. :param g: 'g' parameter it's a gcode string
  4124. :return: offseted gcode string
  4125. """
  4126. temp_gcode = ''
  4127. lines = StringIO(g)
  4128. for line in lines:
  4129. # find the X group
  4130. match_x = self.g_x_re.search(line)
  4131. if match_x:
  4132. if match_x.group(1) is not None:
  4133. # get the coordinate and add X offset
  4134. new_x = float(match_x.group(1)[1:]) + dx
  4135. # replace the updated string
  4136. line = line.replace(
  4137. match_x.group(1),
  4138. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  4139. )
  4140. match_y = self.g_y_re.search(line)
  4141. if match_y:
  4142. if match_y.group(1) is not None:
  4143. new_y = float(match_y.group(1)[1:]) + dy
  4144. line = line.replace(
  4145. match_y.group(1),
  4146. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4147. )
  4148. temp_gcode += line
  4149. lines.close()
  4150. return temp_gcode
  4151. if self.multitool is False:
  4152. # offset Gcode
  4153. self.gcode = offset_g(self.gcode)
  4154. # variables to display the percentage of work done
  4155. self.geo_len = 0
  4156. try:
  4157. for g in self.gcode_parsed:
  4158. self.geo_len += 1
  4159. except TypeError:
  4160. self.geo_len = 1
  4161. self.old_disp_number = 0
  4162. self.el_count = 0
  4163. # offset geometry
  4164. for g in self.gcode_parsed:
  4165. try:
  4166. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  4167. except AttributeError:
  4168. return g['geom']
  4169. self.el_count += 1
  4170. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4171. if self.old_disp_number < disp_number <= 100:
  4172. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4173. self.old_disp_number = disp_number
  4174. self.create_geometry()
  4175. else:
  4176. for k, v in self.cnc_tools.items():
  4177. # offset Gcode
  4178. v['gcode'] = offset_g(v['gcode'])
  4179. # variables to display the percentage of work done
  4180. self.geo_len = 0
  4181. try:
  4182. for g in v['gcode_parsed']:
  4183. self.geo_len += 1
  4184. except TypeError:
  4185. self.geo_len = 1
  4186. self.old_disp_number = 0
  4187. self.el_count = 0
  4188. # offset gcode_parsed
  4189. for g in v['gcode_parsed']:
  4190. try:
  4191. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  4192. except AttributeError:
  4193. return g['geom']
  4194. self.el_count += 1
  4195. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4196. if self.old_disp_number < disp_number <= 100:
  4197. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4198. self.old_disp_number = disp_number
  4199. # for the bounding box
  4200. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  4201. self.app.proc_container.new_text = ''
  4202. def mirror(self, axis, point):
  4203. """
  4204. Mirror the geometrys of an object by an given axis around the coordinates of the 'point'
  4205. :param angle:
  4206. :param point: tupple of coordinates (x,y)
  4207. :return:
  4208. """
  4209. log.debug("camlib.CNCJob.mirror()")
  4210. px, py = point
  4211. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  4212. # variables to display the percentage of work done
  4213. self.geo_len = 0
  4214. try:
  4215. for g in self.gcode_parsed:
  4216. self.geo_len += 1
  4217. except TypeError:
  4218. self.geo_len = 1
  4219. self.old_disp_number = 0
  4220. self.el_count = 0
  4221. for g in self.gcode_parsed:
  4222. try:
  4223. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  4224. except AttributeError:
  4225. return g['geom']
  4226. self.el_count += 1
  4227. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4228. if self.old_disp_number < disp_number <= 100:
  4229. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4230. self.old_disp_number = disp_number
  4231. self.create_geometry()
  4232. self.app.proc_container.new_text = ''
  4233. def skew(self, angle_x, angle_y, point):
  4234. """
  4235. Shear/Skew the geometries of an object by angles along x and y dimensions.
  4236. Parameters
  4237. ----------
  4238. angle_x, angle_y : float, float
  4239. The shear angle(s) for the x and y axes respectively. These can be
  4240. specified in either degrees (default) or radians by setting
  4241. use_radians=True.
  4242. point: tupple of coordinates (x,y)
  4243. See shapely manual for more information:
  4244. http://toblerity.org/shapely/manual.html#affine-transformations
  4245. """
  4246. log.debug("camlib.CNCJob.skew()")
  4247. px, py = point
  4248. # variables to display the percentage of work done
  4249. self.geo_len = 0
  4250. try:
  4251. for g in self.gcode_parsed:
  4252. self.geo_len += 1
  4253. except TypeError:
  4254. self.geo_len = 1
  4255. self.old_disp_number = 0
  4256. self.el_count = 0
  4257. for g in self.gcode_parsed:
  4258. try:
  4259. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  4260. except AttributeError:
  4261. return g['geom']
  4262. self.el_count += 1
  4263. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4264. if self.old_disp_number < disp_number <= 100:
  4265. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4266. self.old_disp_number = disp_number
  4267. self.create_geometry()
  4268. self.app.proc_container.new_text = ''
  4269. def rotate(self, angle, point):
  4270. """
  4271. Rotate the geometrys of an object by an given angle around the coordinates of the 'point'
  4272. :param angle:
  4273. :param point: tupple of coordinates (x,y)
  4274. :return:
  4275. """
  4276. log.debug("camlib.CNCJob.rotate()")
  4277. px, py = point
  4278. # variables to display the percentage of work done
  4279. self.geo_len = 0
  4280. try:
  4281. for g in self.gcode_parsed:
  4282. self.geo_len += 1
  4283. except TypeError:
  4284. self.geo_len = 1
  4285. self.old_disp_number = 0
  4286. self.el_count = 0
  4287. for g in self.gcode_parsed:
  4288. try:
  4289. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  4290. except AttributeError:
  4291. return g['geom']
  4292. self.el_count += 1
  4293. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4294. if self.old_disp_number < disp_number <= 100:
  4295. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4296. self.old_disp_number = disp_number
  4297. self.create_geometry()
  4298. self.app.proc_container.new_text = ''
  4299. def get_bounds(geometry_list):
  4300. xmin = np.Inf
  4301. ymin = np.Inf
  4302. xmax = -np.Inf
  4303. ymax = -np.Inf
  4304. for gs in geometry_list:
  4305. try:
  4306. gxmin, gymin, gxmax, gymax = gs.bounds()
  4307. xmin = min([xmin, gxmin])
  4308. ymin = min([ymin, gymin])
  4309. xmax = max([xmax, gxmax])
  4310. ymax = max([ymax, gymax])
  4311. except Exception:
  4312. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  4313. return [xmin, ymin, xmax, ymax]
  4314. def arc(center, radius, start, stop, direction, steps_per_circ):
  4315. """
  4316. Creates a list of point along the specified arc.
  4317. :param center: Coordinates of the center [x, y]
  4318. :type center: list
  4319. :param radius: Radius of the arc.
  4320. :type radius: float
  4321. :param start: Starting angle in radians
  4322. :type start: float
  4323. :param stop: End angle in radians
  4324. :type stop: float
  4325. :param direction: Orientation of the arc, "CW" or "CCW"
  4326. :type direction: string
  4327. :param steps_per_circ: Number of straight line segments to
  4328. represent a circle.
  4329. :type steps_per_circ: int
  4330. :return: The desired arc, as list of tuples
  4331. :rtype: list
  4332. """
  4333. # TODO: Resolution should be established by maximum error from the exact arc.
  4334. da_sign = {"cw": -1.0, "ccw": 1.0}
  4335. points = []
  4336. if direction == "ccw" and stop <= start:
  4337. stop += 2 * np.pi
  4338. if direction == "cw" and stop >= start:
  4339. stop -= 2 * np.pi
  4340. angle = abs(stop - start)
  4341. # angle = stop-start
  4342. steps = max([int(np.ceil(angle / (2 * np.pi) * steps_per_circ)), 2])
  4343. delta_angle = da_sign[direction] * angle * 1.0 / steps
  4344. for i in range(steps + 1):
  4345. theta = start + delta_angle * i
  4346. points.append((center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta)))
  4347. return points
  4348. def arc2(p1, p2, center, direction, steps_per_circ):
  4349. r = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  4350. start = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  4351. stop = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  4352. return arc(center, r, start, stop, direction, steps_per_circ)
  4353. def arc_angle(start, stop, direction):
  4354. if direction == "ccw" and stop <= start:
  4355. stop += 2 * np.pi
  4356. if direction == "cw" and stop >= start:
  4357. stop -= 2 * np.pi
  4358. angle = abs(stop - start)
  4359. return angle
  4360. # def find_polygon(poly, point):
  4361. # """
  4362. # Find an object that object.contains(Point(point)) in
  4363. # poly, which can can be iterable, contain iterable of, or
  4364. # be itself an implementer of .contains().
  4365. #
  4366. # :param poly: See description
  4367. # :return: Polygon containing point or None.
  4368. # """
  4369. #
  4370. # if poly is None:
  4371. # return None
  4372. #
  4373. # try:
  4374. # for sub_poly in poly:
  4375. # p = find_polygon(sub_poly, point)
  4376. # if p is not None:
  4377. # return p
  4378. # except TypeError:
  4379. # try:
  4380. # if poly.contains(Point(point)):
  4381. # return poly
  4382. # except AttributeError:
  4383. # return None
  4384. #
  4385. # return None
  4386. def to_dict(obj):
  4387. """
  4388. Makes the following types into serializable form:
  4389. * ApertureMacro
  4390. * BaseGeometry
  4391. :param obj: Shapely geometry.
  4392. :type obj: BaseGeometry
  4393. :return: Dictionary with serializable form if ``obj`` was
  4394. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  4395. """
  4396. if isinstance(obj, ApertureMacro):
  4397. return {
  4398. "__class__": "ApertureMacro",
  4399. "__inst__": obj.to_dict()
  4400. }
  4401. if isinstance(obj, BaseGeometry):
  4402. return {
  4403. "__class__": "Shply",
  4404. "__inst__": sdumps(obj)
  4405. }
  4406. return obj
  4407. def dict2obj(d):
  4408. """
  4409. Default deserializer.
  4410. :param d: Serializable dictionary representation of an object
  4411. to be reconstructed.
  4412. :return: Reconstructed object.
  4413. """
  4414. if '__class__' in d and '__inst__' in d:
  4415. if d['__class__'] == "Shply":
  4416. return sloads(d['__inst__'])
  4417. if d['__class__'] == "ApertureMacro":
  4418. am = ApertureMacro()
  4419. am.from_dict(d['__inst__'])
  4420. return am
  4421. return d
  4422. else:
  4423. return d
  4424. # def plotg(geo, solid_poly=False, color="black"):
  4425. # try:
  4426. # __ = iter(geo)
  4427. # except:
  4428. # geo = [geo]
  4429. #
  4430. # for g in geo:
  4431. # if type(g) == Polygon:
  4432. # if solid_poly:
  4433. # patch = PolygonPatch(g,
  4434. # facecolor="#BBF268",
  4435. # edgecolor="#006E20",
  4436. # alpha=0.75,
  4437. # zorder=2)
  4438. # ax = subplot(111)
  4439. # ax.add_patch(patch)
  4440. # else:
  4441. # x, y = g.exterior.coords.xy
  4442. # plot(x, y, color=color)
  4443. # for ints in g.interiors:
  4444. # x, y = ints.coords.xy
  4445. # plot(x, y, color=color)
  4446. # continue
  4447. #
  4448. # if type(g) == LineString or type(g) == LinearRing:
  4449. # x, y = g.coords.xy
  4450. # plot(x, y, color=color)
  4451. # continue
  4452. #
  4453. # if type(g) == Point:
  4454. # x, y = g.coords.xy
  4455. # plot(x, y, 'o')
  4456. # continue
  4457. #
  4458. # try:
  4459. # __ = iter(g)
  4460. # plotg(g, color=color)
  4461. # except:
  4462. # log.error("Cannot plot: " + str(type(g)))
  4463. # continue
  4464. # def alpha_shape(points, alpha):
  4465. # """
  4466. # Compute the alpha shape (concave hull) of a set of points.
  4467. #
  4468. # @param points: Iterable container of points.
  4469. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  4470. # numbers don't fall inward as much as larger numbers. Too large,
  4471. # and you lose everything!
  4472. # """
  4473. # if len(points) < 4:
  4474. # # When you have a triangle, there is no sense in computing an alpha
  4475. # # shape.
  4476. # return MultiPoint(list(points)).convex_hull
  4477. #
  4478. # def add_edge(edges, edge_points, coords, i, j):
  4479. # """Add a line between the i-th and j-th points, if not in the list already"""
  4480. # if (i, j) in edges or (j, i) in edges:
  4481. # # already added
  4482. # return
  4483. # edges.add( (i, j) )
  4484. # edge_points.append(coords[ [i, j] ])
  4485. #
  4486. # coords = np.array([point.coords[0] for point in points])
  4487. #
  4488. # tri = Delaunay(coords)
  4489. # edges = set()
  4490. # edge_points = []
  4491. # # loop over triangles:
  4492. # # ia, ib, ic = indices of corner points of the triangle
  4493. # for ia, ib, ic in tri.vertices:
  4494. # pa = coords[ia]
  4495. # pb = coords[ib]
  4496. # pc = coords[ic]
  4497. #
  4498. # # Lengths of sides of triangle
  4499. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  4500. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  4501. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  4502. #
  4503. # # Semiperimeter of triangle
  4504. # s = (a + b + c)/2.0
  4505. #
  4506. # # Area of triangle by Heron's formula
  4507. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  4508. # circum_r = a*b*c/(4.0*area)
  4509. #
  4510. # # Here's the radius filter.
  4511. # #print circum_r
  4512. # if circum_r < 1.0/alpha:
  4513. # add_edge(edges, edge_points, coords, ia, ib)
  4514. # add_edge(edges, edge_points, coords, ib, ic)
  4515. # add_edge(edges, edge_points, coords, ic, ia)
  4516. #
  4517. # m = MultiLineString(edge_points)
  4518. # triangles = list(polygonize(m))
  4519. # return cascaded_union(triangles), edge_points
  4520. # def voronoi(P):
  4521. # """
  4522. # Returns a list of all edges of the voronoi diagram for the given input points.
  4523. # """
  4524. # delauny = Delaunay(P)
  4525. # triangles = delauny.points[delauny.vertices]
  4526. #
  4527. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  4528. # long_lines_endpoints = []
  4529. #
  4530. # lineIndices = []
  4531. # for i, triangle in enumerate(triangles):
  4532. # circum_center = circum_centers[i]
  4533. # for j, neighbor in enumerate(delauny.neighbors[i]):
  4534. # if neighbor != -1:
  4535. # lineIndices.append((i, neighbor))
  4536. # else:
  4537. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  4538. # ps = np.array((ps[1], -ps[0]))
  4539. #
  4540. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  4541. # di = middle - triangle[j]
  4542. #
  4543. # ps /= np.linalg.norm(ps)
  4544. # di /= np.linalg.norm(di)
  4545. #
  4546. # if np.dot(di, ps) < 0.0:
  4547. # ps *= -1000.0
  4548. # else:
  4549. # ps *= 1000.0
  4550. #
  4551. # long_lines_endpoints.append(circum_center + ps)
  4552. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  4553. #
  4554. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  4555. #
  4556. # # filter out any duplicate lines
  4557. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  4558. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  4559. # lineIndicesUnique = np.unique(lineIndicesTupled)
  4560. #
  4561. # return vertices, lineIndicesUnique
  4562. #
  4563. #
  4564. # def triangle_csc(pts):
  4565. # rows, cols = pts.shape
  4566. #
  4567. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  4568. # [np.ones((1, rows)), np.zeros((1, 1))]])
  4569. #
  4570. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  4571. # x = np.linalg.solve(A,b)
  4572. # bary_coords = x[:-1]
  4573. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  4574. #
  4575. #
  4576. # def voronoi_cell_lines(points, vertices, lineIndices):
  4577. # """
  4578. # Returns a mapping from a voronoi cell to its edges.
  4579. #
  4580. # :param points: shape (m,2)
  4581. # :param vertices: shape (n,2)
  4582. # :param lineIndices: shape (o,2)
  4583. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  4584. # """
  4585. # kd = KDTree(points)
  4586. #
  4587. # cells = collections.defaultdict(list)
  4588. # for i1, i2 in lineIndices:
  4589. # v1, v2 = vertices[i1], vertices[i2]
  4590. # mid = (v1+v2)/2
  4591. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  4592. # cells[p1Idx].append((i1, i2))
  4593. # cells[p2Idx].append((i1, i2))
  4594. #
  4595. # return cells
  4596. #
  4597. #
  4598. # def voronoi_edges2polygons(cells):
  4599. # """
  4600. # Transforms cell edges into polygons.
  4601. #
  4602. # :param cells: as returned from voronoi_cell_lines
  4603. # :rtype: dict point index -> list of vertex indices which form a polygon
  4604. # """
  4605. #
  4606. # # first, close the outer cells
  4607. # for pIdx, lineIndices_ in cells.items():
  4608. # dangling_lines = []
  4609. # for i1, i2 in lineIndices_:
  4610. # p = (i1, i2)
  4611. # connections = filter(lambda k: p != k and
  4612. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  4613. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  4614. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  4615. # assert 1 <= len(connections) <= 2
  4616. # if len(connections) == 1:
  4617. # dangling_lines.append((i1, i2))
  4618. # assert len(dangling_lines) in [0, 2]
  4619. # if len(dangling_lines) == 2:
  4620. # (i11, i12), (i21, i22) = dangling_lines
  4621. # s = (i11, i12)
  4622. # t = (i21, i22)
  4623. #
  4624. # # determine which line ends are unconnected
  4625. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  4626. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  4627. # i11Unconnected = len(connected) == 0
  4628. #
  4629. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  4630. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  4631. # i21Unconnected = len(connected) == 0
  4632. #
  4633. # startIdx = i11 if i11Unconnected else i12
  4634. # endIdx = i21 if i21Unconnected else i22
  4635. #
  4636. # cells[pIdx].append((startIdx, endIdx))
  4637. #
  4638. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  4639. # polys = dict()
  4640. # for pIdx, lineIndices_ in cells.items():
  4641. # # get a directed graph which contains both directions and arbitrarily follow one of both
  4642. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  4643. # directedGraphMap = collections.defaultdict(list)
  4644. # for (i1, i2) in directedGraph:
  4645. # directedGraphMap[i1].append(i2)
  4646. # orderedEdges = []
  4647. # currentEdge = directedGraph[0]
  4648. # while len(orderedEdges) < len(lineIndices_):
  4649. # i1 = currentEdge[1]
  4650. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  4651. # nextEdge = (i1, i2)
  4652. # orderedEdges.append(nextEdge)
  4653. # currentEdge = nextEdge
  4654. #
  4655. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  4656. #
  4657. # return polys
  4658. #
  4659. #
  4660. # def voronoi_polygons(points):
  4661. # """
  4662. # Returns the voronoi polygon for each input point.
  4663. #
  4664. # :param points: shape (n,2)
  4665. # :rtype: list of n polygons where each polygon is an array of vertices
  4666. # """
  4667. # vertices, lineIndices = voronoi(points)
  4668. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  4669. # polys = voronoi_edges2polygons(cells)
  4670. # polylist = []
  4671. # for i in range(len(points)):
  4672. # poly = vertices[np.asarray(polys[i])]
  4673. # polylist.append(poly)
  4674. # return polylist
  4675. #
  4676. #
  4677. # class Zprofile:
  4678. # def __init__(self):
  4679. #
  4680. # # data contains lists of [x, y, z]
  4681. # self.data = []
  4682. #
  4683. # # Computed voronoi polygons (shapely)
  4684. # self.polygons = []
  4685. # pass
  4686. #
  4687. # # def plot_polygons(self):
  4688. # # axes = plt.subplot(1, 1, 1)
  4689. # #
  4690. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  4691. # #
  4692. # # for poly in self.polygons:
  4693. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  4694. # # axes.add_patch(p)
  4695. #
  4696. # def init_from_csv(self, filename):
  4697. # pass
  4698. #
  4699. # def init_from_string(self, zpstring):
  4700. # pass
  4701. #
  4702. # def init_from_list(self, zplist):
  4703. # self.data = zplist
  4704. #
  4705. # def generate_polygons(self):
  4706. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  4707. #
  4708. # def normalize(self, origin):
  4709. # pass
  4710. #
  4711. # def paste(self, path):
  4712. # """
  4713. # Return a list of dictionaries containing the parts of the original
  4714. # path and their z-axis offset.
  4715. # """
  4716. #
  4717. # # At most one region/polygon will contain the path
  4718. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  4719. #
  4720. # if len(containing) > 0:
  4721. # return [{"path": path, "z": self.data[containing[0]][2]}]
  4722. #
  4723. # # All region indexes that intersect with the path
  4724. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  4725. #
  4726. # return [{"path": path.intersection(self.polygons[i]),
  4727. # "z": self.data[i][2]} for i in crossing]
  4728. def autolist(obj):
  4729. try:
  4730. __ = iter(obj)
  4731. return obj
  4732. except TypeError:
  4733. return [obj]
  4734. def three_point_circle(p1, p2, p3):
  4735. """
  4736. Computes the center and radius of a circle from
  4737. 3 points on its circumference.
  4738. :param p1: Point 1
  4739. :param p2: Point 2
  4740. :param p3: Point 3
  4741. :return: center, radius
  4742. """
  4743. # Midpoints
  4744. a1 = (p1 + p2) / 2.0
  4745. a2 = (p2 + p3) / 2.0
  4746. # Normals
  4747. b1 = np.dot((p2 - p1), np.array([[0, -1], [1, 0]], dtype=np.float32))
  4748. b2 = np.dot((p3 - p2), np.array([[0, 1], [-1, 0]], dtype=np.float32))
  4749. # Params
  4750. try:
  4751. T = solve(np.transpose(np.array([-b1, b2])), a1 - a2)
  4752. except Exception as e:
  4753. log.debug("camlib.three_point_circle() --> %s" % str(e))
  4754. return
  4755. # Center
  4756. center = a1 + b1 * T[0]
  4757. # Radius
  4758. radius = np.linalg.norm(center - p1)
  4759. return center, radius, T[0]
  4760. def distance(pt1, pt2):
  4761. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  4762. def distance_euclidian(x1, y1, x2, y2):
  4763. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  4764. class FlatCAMRTree(object):
  4765. """
  4766. Indexes geometry (Any object with "cooords" property containing
  4767. a list of tuples with x, y values). Objects are indexed by
  4768. all their points by default. To index by arbitrary points,
  4769. override self.points2obj.
  4770. """
  4771. def __init__(self):
  4772. # Python RTree Index
  4773. self.rti = rtindex.Index()
  4774. # ## Track object-point relationship
  4775. # Each is list of points in object.
  4776. self.obj2points = []
  4777. # Index is index in rtree, value is index of
  4778. # object in obj2points.
  4779. self.points2obj = []
  4780. self.get_points = lambda go: go.coords
  4781. def grow_obj2points(self, idx):
  4782. """
  4783. Increases the size of self.obj2points to fit
  4784. idx + 1 items.
  4785. :param idx: Index to fit into list.
  4786. :return: None
  4787. """
  4788. if len(self.obj2points) > idx:
  4789. # len == 2, idx == 1, ok.
  4790. return
  4791. else:
  4792. # len == 2, idx == 2, need 1 more.
  4793. # range(2, 3)
  4794. for i in range(len(self.obj2points), idx + 1):
  4795. self.obj2points.append([])
  4796. def insert(self, objid, obj):
  4797. self.grow_obj2points(objid)
  4798. self.obj2points[objid] = []
  4799. for pt in self.get_points(obj):
  4800. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  4801. self.obj2points[objid].append(len(self.points2obj))
  4802. self.points2obj.append(objid)
  4803. def remove_obj(self, objid, obj):
  4804. # Use all ptids to delete from index
  4805. for i, pt in enumerate(self.get_points(obj)):
  4806. try:
  4807. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  4808. except IndexError:
  4809. pass
  4810. def nearest(self, pt):
  4811. """
  4812. Will raise StopIteration if no items are found.
  4813. :param pt:
  4814. :return:
  4815. """
  4816. return next(self.rti.nearest(pt, objects=True))
  4817. class FlatCAMRTreeStorage(FlatCAMRTree):
  4818. """
  4819. Just like FlatCAMRTree it indexes geometry, but also serves
  4820. as storage for the geometry.
  4821. """
  4822. def __init__(self):
  4823. # super(FlatCAMRTreeStorage, self).__init__()
  4824. super().__init__()
  4825. self.objects = []
  4826. # Optimization attempt!
  4827. self.indexes = {}
  4828. def insert(self, obj):
  4829. self.objects.append(obj)
  4830. idx = len(self.objects) - 1
  4831. # Note: Shapely objects are not hashable any more, althought
  4832. # there seem to be plans to re-introduce the feature in
  4833. # version 2.0. For now, we will index using the object's id,
  4834. # but it's important to remember that shapely geometry is
  4835. # mutable, ie. it can be modified to a totally different shape
  4836. # and continue to have the same id.
  4837. # self.indexes[obj] = idx
  4838. self.indexes[id(obj)] = idx
  4839. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  4840. super().insert(idx, obj)
  4841. # @profile
  4842. def remove(self, obj):
  4843. # See note about self.indexes in insert().
  4844. # objidx = self.indexes[obj]
  4845. objidx = self.indexes[id(obj)]
  4846. # Remove from list
  4847. self.objects[objidx] = None
  4848. # Remove from index
  4849. self.remove_obj(objidx, obj)
  4850. def get_objects(self):
  4851. return (o for o in self.objects if o is not None)
  4852. def nearest(self, pt):
  4853. """
  4854. Returns the nearest matching points and the object
  4855. it belongs to.
  4856. :param pt: Query point.
  4857. :return: (match_x, match_y), Object owner of
  4858. matching point.
  4859. :rtype: tuple
  4860. """
  4861. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  4862. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  4863. # class myO:
  4864. # def __init__(self, coords):
  4865. # self.coords = coords
  4866. #
  4867. #
  4868. # def test_rti():
  4869. #
  4870. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4871. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4872. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4873. #
  4874. # os = [o1, o2]
  4875. #
  4876. # idx = FlatCAMRTree()
  4877. #
  4878. # for o in range(len(os)):
  4879. # idx.insert(o, os[o])
  4880. #
  4881. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4882. #
  4883. # idx.remove_obj(0, o1)
  4884. #
  4885. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4886. #
  4887. # idx.remove_obj(1, o2)
  4888. #
  4889. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4890. #
  4891. #
  4892. # def test_rtis():
  4893. #
  4894. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4895. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4896. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4897. #
  4898. # os = [o1, o2]
  4899. #
  4900. # idx = FlatCAMRTreeStorage()
  4901. #
  4902. # for o in range(len(os)):
  4903. # idx.insert(os[o])
  4904. #
  4905. # #os = None
  4906. # #o1 = None
  4907. # #o2 = None
  4908. #
  4909. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4910. #
  4911. # idx.remove(idx.nearest((2,0))[1])
  4912. #
  4913. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4914. #
  4915. # idx.remove(idx.nearest((0,0))[1])
  4916. #
  4917. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]