camlib.py 225 KB

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