camlib.py 228 KB

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