camlib.py 228 KB

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