camlib.py 227 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866
  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):
  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. # Process every instruction
  3263. for line in StringIO(self.gcode):
  3264. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  3265. return "fail"
  3266. gobj = self.codes_split(line)
  3267. # ## Units
  3268. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  3269. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  3270. continue
  3271. # ## Changing height
  3272. if 'Z' in gobj:
  3273. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  3274. pass
  3275. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  3276. pass
  3277. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  3278. pass
  3279. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  3280. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  3281. pass
  3282. else:
  3283. log.warning("Non-orthogonal motion: From %s" % str(current))
  3284. log.warning(" To: %s" % str(gobj))
  3285. current['Z'] = gobj['Z']
  3286. # Store the path into geometry and reset path
  3287. if len(path) > 1:
  3288. geometry.append({"geom": LineString(path),
  3289. "kind": kind})
  3290. path = [path[-1]] # Start with the last point of last path.
  3291. # create the geometry for the holes created when drilling Excellon drills
  3292. if self.origin_kind == 'excellon':
  3293. if current['Z'] < 0:
  3294. current_drill_point_coords = (float('%.4f' % current['X']), float('%.4f' % current['Y']))
  3295. # find the drill diameter knowing the drill coordinates
  3296. for pt_dict in self.exc_drills:
  3297. point_in_dict_coords = (float('%.4f' % pt_dict['point'].x),
  3298. float('%.4f' % pt_dict['point'].y))
  3299. if point_in_dict_coords == current_drill_point_coords:
  3300. tool = pt_dict['tool']
  3301. dia = self.exc_tools[tool]['C']
  3302. kind = ['C', 'F']
  3303. geometry.append({"geom": Point(current_drill_point_coords).
  3304. buffer(dia/2).exterior,
  3305. "kind": kind})
  3306. break
  3307. if 'G' in gobj:
  3308. current['G'] = int(gobj['G'])
  3309. if 'X' in gobj or 'Y' in gobj:
  3310. if 'X' in gobj:
  3311. x = gobj['X']
  3312. # current['X'] = x
  3313. else:
  3314. x = current['X']
  3315. if 'Y' in gobj:
  3316. y = gobj['Y']
  3317. else:
  3318. y = current['Y']
  3319. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  3320. if current['Z'] > 0:
  3321. kind[0] = 'T'
  3322. if current['G'] > 0:
  3323. kind[1] = 'S'
  3324. if current['G'] in [0, 1]: # line
  3325. path.append((x, y))
  3326. arcdir = [None, None, "cw", "ccw"]
  3327. if current['G'] in [2, 3]: # arc
  3328. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  3329. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  3330. start = arctan2(-gobj['J'], -gobj['I'])
  3331. stop = arctan2(-center[1] + y, -center[0] + x)
  3332. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle / 4))
  3333. # Update current instruction
  3334. for code in gobj:
  3335. current[code] = gobj[code]
  3336. # There might not be a change in height at the
  3337. # end, therefore, see here too if there is
  3338. # a final path.
  3339. if len(path) > 1:
  3340. geometry.append({"geom": LineString(path),
  3341. "kind": kind})
  3342. self.gcode_parsed = geometry
  3343. return geometry
  3344. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  3345. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  3346. # alpha={"T": 0.3, "C": 1.0}):
  3347. # """
  3348. # Creates a Matplotlib figure with a plot of the
  3349. # G-code job.
  3350. # """
  3351. # if tooldia is None:
  3352. # tooldia = self.tooldia
  3353. #
  3354. # fig = Figure(dpi=dpi)
  3355. # ax = fig.add_subplot(111)
  3356. # ax.set_aspect(1)
  3357. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  3358. # ax.set_xlim(xmin-margin, xmax+margin)
  3359. # ax.set_ylim(ymin-margin, ymax+margin)
  3360. #
  3361. # if tooldia == 0:
  3362. # for geo in self.gcode_parsed:
  3363. # linespec = '--'
  3364. # linecolor = color[geo['kind'][0]][1]
  3365. # if geo['kind'][0] == 'C':
  3366. # linespec = 'k-'
  3367. # x, y = geo['geom'].coords.xy
  3368. # ax.plot(x, y, linespec, color=linecolor)
  3369. # else:
  3370. # for geo in self.gcode_parsed:
  3371. # poly = geo['geom'].buffer(tooldia/2.0)
  3372. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  3373. # edgecolor=color[geo['kind'][0]][1],
  3374. # alpha=alpha[geo['kind'][0]], zorder=2)
  3375. # ax.add_patch(patch)
  3376. #
  3377. # return fig
  3378. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  3379. color={"T": ["#F0E24D4C", "#B5AB3A4C"], "C": ["#5E6CFFFF", "#4650BDFF"]},
  3380. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  3381. """
  3382. Plots the G-code job onto the given axes.
  3383. :param tooldia: Tool diameter.
  3384. :param dpi: Not used!
  3385. :param margin: Not used!
  3386. :param color: Color specification.
  3387. :param alpha: Transparency specification.
  3388. :param tool_tolerance: Tolerance when drawing the toolshape.
  3389. :param obj
  3390. :param visible
  3391. :param kind
  3392. :return: None
  3393. """
  3394. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3395. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  3396. path_num = 0
  3397. if tooldia is None:
  3398. tooldia = self.tooldia
  3399. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  3400. if isinstance(tooldia, list):
  3401. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  3402. if tooldia == 0:
  3403. for geo in gcode_parsed:
  3404. if kind == 'all':
  3405. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  3406. elif kind == 'travel':
  3407. if geo['kind'][0] == 'T':
  3408. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  3409. elif kind == 'cut':
  3410. if geo['kind'][0] == 'C':
  3411. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  3412. else:
  3413. text = []
  3414. pos = []
  3415. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3416. if self.coordinates_type == "G90":
  3417. # For Absolute coordinates type G90
  3418. for geo in gcode_parsed:
  3419. if geo['kind'][0] == 'T':
  3420. current_position = geo['geom'].coords[0]
  3421. if current_position not in pos:
  3422. pos.append(current_position)
  3423. path_num += 1
  3424. text.append(str(path_num))
  3425. current_position = geo['geom'].coords[-1]
  3426. if current_position not in pos:
  3427. pos.append(current_position)
  3428. path_num += 1
  3429. text.append(str(path_num))
  3430. # plot the geometry of Excellon objects
  3431. if self.origin_kind == 'excellon':
  3432. try:
  3433. poly = Polygon(geo['geom'])
  3434. except ValueError:
  3435. # if the geos are travel lines it will enter into Exception
  3436. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3437. poly = poly.simplify(tool_tolerance)
  3438. else:
  3439. # plot the geometry of any objects other than Excellon
  3440. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3441. poly = poly.simplify(tool_tolerance)
  3442. if kind == 'all':
  3443. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3444. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3445. elif kind == 'travel':
  3446. if geo['kind'][0] == 'T':
  3447. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3448. visible=visible, layer=2)
  3449. elif kind == 'cut':
  3450. if geo['kind'][0] == 'C':
  3451. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3452. visible=visible, layer=1)
  3453. else:
  3454. # For Incremental coordinates type G91
  3455. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3456. _('G91 coordinates not implemented ...'))
  3457. for geo in gcode_parsed:
  3458. if geo['kind'][0] == 'T':
  3459. current_position = geo['geom'].coords[0]
  3460. if current_position not in pos:
  3461. pos.append(current_position)
  3462. path_num += 1
  3463. text.append(str(path_num))
  3464. current_position = geo['geom'].coords[-1]
  3465. if current_position not in pos:
  3466. pos.append(current_position)
  3467. path_num += 1
  3468. text.append(str(path_num))
  3469. # plot the geometry of Excellon objects
  3470. if self.origin_kind == 'excellon':
  3471. try:
  3472. poly = Polygon(geo['geom'])
  3473. except ValueError:
  3474. # if the geos are travel lines it will enter into Exception
  3475. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3476. poly = poly.simplify(tool_tolerance)
  3477. else:
  3478. # plot the geometry of any objects other than Excellon
  3479. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3480. poly = poly.simplify(tool_tolerance)
  3481. if kind == 'all':
  3482. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3483. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3484. elif kind == 'travel':
  3485. if geo['kind'][0] == 'T':
  3486. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3487. visible=visible, layer=2)
  3488. elif kind == 'cut':
  3489. if geo['kind'][0] == 'C':
  3490. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3491. visible=visible, layer=1)
  3492. # current_x = gcode_parsed[0]['geom'].coords[0][0]
  3493. # current_y = gcode_parsed[0]['geom'].coords[0][1]
  3494. # old_pos = (
  3495. # current_x,
  3496. # current_y
  3497. # )
  3498. #
  3499. # for geo in gcode_parsed:
  3500. # if geo['kind'][0] == 'T':
  3501. # current_position = (
  3502. # geo['geom'].coords[0][0] + old_pos[0],
  3503. # geo['geom'].coords[0][1] + old_pos[1]
  3504. # )
  3505. # if current_position not in pos:
  3506. # pos.append(current_position)
  3507. # path_num += 1
  3508. # text.append(str(path_num))
  3509. #
  3510. # delta = (
  3511. # geo['geom'].coords[-1][0] - geo['geom'].coords[0][0],
  3512. # geo['geom'].coords[-1][1] - geo['geom'].coords[0][1]
  3513. # )
  3514. # current_position = (
  3515. # current_position[0] + geo['geom'].coords[-1][0],
  3516. # current_position[1] + geo['geom'].coords[-1][1]
  3517. # )
  3518. # if current_position not in pos:
  3519. # pos.append(current_position)
  3520. # path_num += 1
  3521. # text.append(str(path_num))
  3522. #
  3523. # # plot the geometry of Excellon objects
  3524. # if self.origin_kind == 'excellon':
  3525. # if isinstance(geo['geom'], Point):
  3526. # # if geo is Point
  3527. # current_position = (
  3528. # current_position[0] + geo['geom'].x,
  3529. # current_position[1] + geo['geom'].y
  3530. # )
  3531. # poly = Polygon(Point(current_position))
  3532. # elif isinstance(geo['geom'], LineString):
  3533. # # if the geos are travel lines (LineStrings)
  3534. # new_line_pts = []
  3535. # old_line_pos = deepcopy(current_position)
  3536. # for p in list(geo['geom'].coords):
  3537. # current_position = (
  3538. # current_position[0] + p[0],
  3539. # current_position[1] + p[1]
  3540. # )
  3541. # new_line_pts.append(current_position)
  3542. # old_line_pos = p
  3543. # new_line = LineString(new_line_pts)
  3544. #
  3545. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3546. # poly = poly.simplify(tool_tolerance)
  3547. # else:
  3548. # # plot the geometry of any objects other than Excellon
  3549. # new_line_pts = []
  3550. # old_line_pos = deepcopy(current_position)
  3551. # for p in list(geo['geom'].coords):
  3552. # current_position = (
  3553. # current_position[0] + p[0],
  3554. # current_position[1] + p[1]
  3555. # )
  3556. # new_line_pts.append(current_position)
  3557. # old_line_pos = p
  3558. # new_line = LineString(new_line_pts)
  3559. #
  3560. # poly = new_line.buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  3561. # poly = poly.simplify(tool_tolerance)
  3562. #
  3563. # old_pos = deepcopy(current_position)
  3564. #
  3565. # if kind == 'all':
  3566. # obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  3567. # visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  3568. # elif kind == 'travel':
  3569. # if geo['kind'][0] == 'T':
  3570. # obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  3571. # visible=visible, layer=2)
  3572. # elif kind == 'cut':
  3573. # if geo['kind'][0] == 'C':
  3574. # obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  3575. # visible=visible, layer=1)
  3576. try:
  3577. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  3578. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  3579. color=self.app.defaults["cncjob_annotation_fontcolor"])
  3580. except Exception as e:
  3581. pass
  3582. def create_geometry(self):
  3583. # TODO: This takes forever. Too much data?
  3584. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3585. return self.solid_geometry
  3586. # code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  3587. def segment(self, coords):
  3588. """
  3589. break long linear lines to make it more auto level friendly
  3590. """
  3591. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  3592. return list(coords)
  3593. path = [coords[0]]
  3594. # break the line in either x or y dimension only
  3595. def linebreak_single(line, dim, dmax):
  3596. if dmax <= 0:
  3597. return None
  3598. if line[1][dim] > line[0][dim]:
  3599. sign = 1.0
  3600. d = line[1][dim] - line[0][dim]
  3601. else:
  3602. sign = -1.0
  3603. d = line[0][dim] - line[1][dim]
  3604. if d > dmax:
  3605. # make sure we don't make any new lines too short
  3606. if d > dmax * 2:
  3607. dd = dmax
  3608. else:
  3609. dd = d / 2
  3610. other = dim ^ 1
  3611. return (line[0][dim] + dd * sign, line[0][other] + \
  3612. dd * (line[1][other] - line[0][other]) / d)
  3613. return None
  3614. # recursively breaks down a given line until it is within the
  3615. # required step size
  3616. def linebreak(line):
  3617. pt_new = linebreak_single(line, 0, self.segx)
  3618. if pt_new is None:
  3619. pt_new2 = linebreak_single(line, 1, self.segy)
  3620. else:
  3621. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  3622. if pt_new2 is not None:
  3623. pt_new = pt_new2[::-1]
  3624. if pt_new is None:
  3625. path.append(line[1])
  3626. else:
  3627. path.append(pt_new)
  3628. linebreak((pt_new, line[1]))
  3629. for pt in coords[1:]:
  3630. linebreak((path[-1], pt))
  3631. return path
  3632. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  3633. z_cut=None, z_move=None, zdownrate=None,
  3634. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3635. """
  3636. Generates G-code to cut along the linear feature.
  3637. :param linear: The path to cut along.
  3638. :type: Shapely.LinearRing or Shapely.Linear String
  3639. :param tolerance: All points in the simplified object will be within the
  3640. tolerance distance of the original geometry.
  3641. :type tolerance: float
  3642. :param feedrate: speed for cut on X - Y plane
  3643. :param feedrate_z: speed for cut on Z plane
  3644. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3645. :return: G-code to cut along the linear feature.
  3646. :rtype: str
  3647. """
  3648. if z_cut is None:
  3649. z_cut = self.z_cut
  3650. if z_move is None:
  3651. z_move = self.z_move
  3652. #
  3653. # if zdownrate is None:
  3654. # zdownrate = self.zdownrate
  3655. if feedrate is None:
  3656. feedrate = self.feedrate
  3657. if feedrate_z is None:
  3658. feedrate_z = self.z_feedrate
  3659. if feedrate_rapid is None:
  3660. feedrate_rapid = self.feedrate_rapid
  3661. # Simplify paths?
  3662. if tolerance > 0:
  3663. target_linear = linear.simplify(tolerance)
  3664. else:
  3665. target_linear = linear
  3666. gcode = ""
  3667. # path = list(target_linear.coords)
  3668. path = self.segment(target_linear.coords)
  3669. p = self.pp_geometry
  3670. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3671. if self.coordinates_type == "G90":
  3672. # For Absolute coordinates type G90
  3673. first_x = path[0][0]
  3674. first_y = path[0][1]
  3675. else:
  3676. # For Incremental coordinates type G91
  3677. first_x = path[0][0] - old_point[0]
  3678. first_y = path[0][1] - old_point[1]
  3679. # Move fast to 1st point
  3680. if not cont:
  3681. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3682. # Move down to cutting depth
  3683. if down:
  3684. # Different feedrate for vertical cut?
  3685. gcode += self.doformat(p.z_feedrate_code)
  3686. # gcode += self.doformat(p.feedrate_code)
  3687. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3688. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3689. # Cutting...
  3690. prev_x = first_x
  3691. prev_y = first_y
  3692. for pt in path[1:]:
  3693. if self.app.abort_flag:
  3694. # graceful abort requested by the user
  3695. raise FlatCAMApp.GracefulException
  3696. if self.coordinates_type == "G90":
  3697. # For Absolute coordinates type G90
  3698. next_x = pt[0]
  3699. next_y = pt[1]
  3700. else:
  3701. # For Incremental coordinates type G91
  3702. # next_x = pt[0] - prev_x
  3703. # next_y = pt[1] - prev_y
  3704. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3705. _('G91 coordinates not implemented ...'))
  3706. next_x = pt[0]
  3707. next_y = pt[1]
  3708. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3709. prev_x = pt[0]
  3710. prev_y = pt[1]
  3711. # Up to travelling height.
  3712. if up:
  3713. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  3714. return gcode
  3715. def linear2gcode_extra(self, linear, tolerance=0, down=True, up=True,
  3716. z_cut=None, z_move=None, zdownrate=None,
  3717. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  3718. """
  3719. Generates G-code to cut along the linear feature.
  3720. :param linear: The path to cut along.
  3721. :type: Shapely.LinearRing or Shapely.Linear String
  3722. :param tolerance: All points in the simplified object will be within the
  3723. tolerance distance of the original geometry.
  3724. :type tolerance: float
  3725. :param feedrate: speed for cut on X - Y plane
  3726. :param feedrate_z: speed for cut on Z plane
  3727. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  3728. :return: G-code to cut along the linear feature.
  3729. :rtype: str
  3730. """
  3731. if z_cut is None:
  3732. z_cut = self.z_cut
  3733. if z_move is None:
  3734. z_move = self.z_move
  3735. #
  3736. # if zdownrate is None:
  3737. # zdownrate = self.zdownrate
  3738. if feedrate is None:
  3739. feedrate = self.feedrate
  3740. if feedrate_z is None:
  3741. feedrate_z = self.z_feedrate
  3742. if feedrate_rapid is None:
  3743. feedrate_rapid = self.feedrate_rapid
  3744. # Simplify paths?
  3745. if tolerance > 0:
  3746. target_linear = linear.simplify(tolerance)
  3747. else:
  3748. target_linear = linear
  3749. gcode = ""
  3750. path = list(target_linear.coords)
  3751. p = self.pp_geometry
  3752. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3753. if self.coordinates_type == "G90":
  3754. # For Absolute coordinates type G90
  3755. first_x = path[0][0]
  3756. first_y = path[0][1]
  3757. else:
  3758. # For Incremental coordinates type G91
  3759. first_x = path[0][0] - old_point[0]
  3760. first_y = path[0][1] - old_point[1]
  3761. # Move fast to 1st point
  3762. if not cont:
  3763. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  3764. # Move down to cutting depth
  3765. if down:
  3766. # Different feedrate for vertical cut?
  3767. if self.z_feedrate is not None:
  3768. gcode += self.doformat(p.z_feedrate_code)
  3769. # gcode += self.doformat(p.feedrate_code)
  3770. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  3771. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  3772. else:
  3773. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  3774. # Cutting...
  3775. prev_x = first_x
  3776. prev_y = first_y
  3777. for pt in path[1:]:
  3778. if self.app.abort_flag:
  3779. # graceful abort requested by the user
  3780. raise FlatCAMApp.GracefulException
  3781. if self.coordinates_type == "G90":
  3782. # For Absolute coordinates type G90
  3783. next_x = pt[0]
  3784. next_y = pt[1]
  3785. else:
  3786. # For Incremental coordinates type G91
  3787. # For Incremental coordinates type G91
  3788. # next_x = pt[0] - prev_x
  3789. # next_y = pt[1] - prev_y
  3790. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3791. _('G91 coordinates not implemented ...'))
  3792. next_x = pt[0]
  3793. next_y = pt[1]
  3794. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  3795. prev_x = pt[0]
  3796. prev_y = pt[1]
  3797. # this line is added to create an extra cut over the first point in patch
  3798. # to make sure that we remove the copper leftovers
  3799. # Linear motion to the 1st point in the cut path
  3800. if self.coordinates_type == "G90":
  3801. # For Absolute coordinates type G90
  3802. last_x = path[1][0]
  3803. last_y = path[1][1]
  3804. else:
  3805. # For Incremental coordinates type G91
  3806. last_x = path[1][0] - first_x
  3807. last_y = path[1][1] - first_y
  3808. gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  3809. # Up to travelling height.
  3810. if up:
  3811. gcode += self.doformat(p.lift_code, x=last_x, y=last_y, z_move=z_move) # Stop cutting
  3812. return gcode
  3813. def point2gcode(self, point, old_point=(0, 0)):
  3814. gcode = ""
  3815. if self.app.abort_flag:
  3816. # graceful abort requested by the user
  3817. raise FlatCAMApp.GracefulException
  3818. path = list(point.coords)
  3819. p = self.pp_geometry
  3820. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3821. if self.coordinates_type == "G90":
  3822. # For Absolute coordinates type G90
  3823. first_x = path[0][0]
  3824. first_y = path[0][1]
  3825. else:
  3826. # For Incremental coordinates type G91
  3827. # first_x = path[0][0] - old_point[0]
  3828. # first_y = path[0][1] - old_point[1]
  3829. self.app.inform.emit('[ERROR_NOTCL] %s' %
  3830. _('G91 coordinates not implemented ...'))
  3831. first_x = path[0][0]
  3832. first_y = path[0][1]
  3833. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  3834. if self.z_feedrate is not None:
  3835. gcode += self.doformat(p.z_feedrate_code)
  3836. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut)
  3837. gcode += self.doformat(p.feedrate_code)
  3838. else:
  3839. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut = self.z_cut) # Start cutting
  3840. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  3841. return gcode
  3842. def export_svg(self, scale_stroke_factor=0.00):
  3843. """
  3844. Exports the CNC Job as a SVG Element
  3845. :scale_factor: float
  3846. :return: SVG Element string
  3847. """
  3848. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  3849. # If not specified then try and use the tool diameter
  3850. # This way what is on screen will match what is outputed for the svg
  3851. # This is quite a useful feature for svg's used with visicut
  3852. if scale_stroke_factor <= 0:
  3853. scale_stroke_factor = self.options['tooldia'] / 2
  3854. # If still 0 then default to 0.05
  3855. # This value appears to work for zooming, and getting the output svg line width
  3856. # to match that viewed on screen with FlatCam
  3857. if scale_stroke_factor == 0:
  3858. scale_stroke_factor = 0.01
  3859. # Separate the list of cuts and travels into 2 distinct lists
  3860. # This way we can add different formatting / colors to both
  3861. cuts = []
  3862. travels = []
  3863. for g in self.gcode_parsed:
  3864. if self.app.abort_flag:
  3865. # graceful abort requested by the user
  3866. raise FlatCAMApp.GracefulException
  3867. if g['kind'][0] == 'C': cuts.append(g)
  3868. if g['kind'][0] == 'T': travels.append(g)
  3869. # Used to determine the overall board size
  3870. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  3871. # Convert the cuts and travels into single geometry objects we can render as svg xml
  3872. if travels:
  3873. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  3874. if self.app.abort_flag:
  3875. # graceful abort requested by the user
  3876. raise FlatCAMApp.GracefulException
  3877. if cuts:
  3878. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  3879. # Render the SVG Xml
  3880. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  3881. # It's better to have the travels sitting underneath the cuts for visicut
  3882. svg_elem = ""
  3883. if travels:
  3884. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  3885. if cuts:
  3886. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  3887. return svg_elem
  3888. def bounds(self):
  3889. """
  3890. Returns coordinates of rectangular bounds
  3891. of geometry: (xmin, ymin, xmax, ymax).
  3892. """
  3893. # fixed issue of getting bounds only for one level lists of objects
  3894. # now it can get bounds for nested lists of objects
  3895. log.debug("camlib.CNCJob.bounds()")
  3896. def bounds_rec(obj):
  3897. if type(obj) is list:
  3898. minx = Inf
  3899. miny = Inf
  3900. maxx = -Inf
  3901. maxy = -Inf
  3902. for k in obj:
  3903. if type(k) is dict:
  3904. for key in k:
  3905. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3906. minx = min(minx, minx_)
  3907. miny = min(miny, miny_)
  3908. maxx = max(maxx, maxx_)
  3909. maxy = max(maxy, maxy_)
  3910. else:
  3911. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3912. minx = min(minx, minx_)
  3913. miny = min(miny, miny_)
  3914. maxx = max(maxx, maxx_)
  3915. maxy = max(maxy, maxy_)
  3916. return minx, miny, maxx, maxy
  3917. else:
  3918. # it's a Shapely object, return it's bounds
  3919. return obj.bounds
  3920. if self.multitool is False:
  3921. log.debug("CNCJob->bounds()")
  3922. if self.solid_geometry is None:
  3923. log.debug("solid_geometry is None")
  3924. return 0, 0, 0, 0
  3925. bounds_coords = bounds_rec(self.solid_geometry)
  3926. else:
  3927. minx = Inf
  3928. miny = Inf
  3929. maxx = -Inf
  3930. maxy = -Inf
  3931. for k, v in self.cnc_tools.items():
  3932. minx = Inf
  3933. miny = Inf
  3934. maxx = -Inf
  3935. maxy = -Inf
  3936. try:
  3937. for k in v['solid_geometry']:
  3938. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3939. minx = min(minx, minx_)
  3940. miny = min(miny, miny_)
  3941. maxx = max(maxx, maxx_)
  3942. maxy = max(maxy, maxy_)
  3943. except TypeError:
  3944. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  3945. minx = min(minx, minx_)
  3946. miny = min(miny, miny_)
  3947. maxx = max(maxx, maxx_)
  3948. maxy = max(maxy, maxy_)
  3949. bounds_coords = minx, miny, maxx, maxy
  3950. return bounds_coords
  3951. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  3952. def scale(self, xfactor, yfactor=None, point=None):
  3953. """
  3954. Scales all the geometry on the XY plane in the object by the
  3955. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  3956. not altered.
  3957. :param factor: Number by which to scale the object.
  3958. :type factor: float
  3959. :param point: the (x,y) coords for the point of origin of scale
  3960. :type tuple of floats
  3961. :return: None
  3962. :rtype: None
  3963. """
  3964. log.debug("camlib.CNCJob.scale()")
  3965. if yfactor is None:
  3966. yfactor = xfactor
  3967. if point is None:
  3968. px = 0
  3969. py = 0
  3970. else:
  3971. px, py = point
  3972. def scale_g(g):
  3973. """
  3974. :param g: 'g' parameter it's a gcode string
  3975. :return: scaled gcode string
  3976. """
  3977. temp_gcode = ''
  3978. header_start = False
  3979. header_stop = False
  3980. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3981. lines = StringIO(g)
  3982. for line in lines:
  3983. # this changes the GCODE header ---- UGLY HACK
  3984. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  3985. header_start = True
  3986. if "G20" in line or "G21" in line:
  3987. header_start = False
  3988. header_stop = True
  3989. if header_start is True:
  3990. header_stop = False
  3991. if "in" in line:
  3992. if units == 'MM':
  3993. line = line.replace("in", "mm")
  3994. if "mm" in line:
  3995. if units == 'IN':
  3996. line = line.replace("mm", "in")
  3997. # find any float number in header (even multiple on the same line) and convert it
  3998. numbers_in_header = re.findall(self.g_nr_re, line)
  3999. if numbers_in_header:
  4000. for nr in numbers_in_header:
  4001. new_nr = float(nr) * xfactor
  4002. # replace the updated string
  4003. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  4004. )
  4005. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  4006. if header_stop is True:
  4007. if "G20" in line:
  4008. if units == 'MM':
  4009. line = line.replace("G20", "G21")
  4010. if "G21" in line:
  4011. if units == 'IN':
  4012. line = line.replace("G21", "G20")
  4013. # find the X group
  4014. match_x = self.g_x_re.search(line)
  4015. if match_x:
  4016. if match_x.group(1) is not None:
  4017. new_x = float(match_x.group(1)[1:]) * xfactor
  4018. # replace the updated string
  4019. line = line.replace(
  4020. match_x.group(1),
  4021. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  4022. )
  4023. # find the Y group
  4024. match_y = self.g_y_re.search(line)
  4025. if match_y:
  4026. if match_y.group(1) is not None:
  4027. new_y = float(match_y.group(1)[1:]) * yfactor
  4028. line = line.replace(
  4029. match_y.group(1),
  4030. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4031. )
  4032. # find the Z group
  4033. match_z = self.g_z_re.search(line)
  4034. if match_z:
  4035. if match_z.group(1) is not None:
  4036. new_z = float(match_z.group(1)[1:]) * xfactor
  4037. line = line.replace(
  4038. match_z.group(1),
  4039. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  4040. )
  4041. # find the F group
  4042. match_f = self.g_f_re.search(line)
  4043. if match_f:
  4044. if match_f.group(1) is not None:
  4045. new_f = float(match_f.group(1)[1:]) * xfactor
  4046. line = line.replace(
  4047. match_f.group(1),
  4048. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  4049. )
  4050. # find the T group (tool dia on toolchange)
  4051. match_t = self.g_t_re.search(line)
  4052. if match_t:
  4053. if match_t.group(1) is not None:
  4054. new_t = float(match_t.group(1)[1:]) * xfactor
  4055. line = line.replace(
  4056. match_t.group(1),
  4057. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  4058. )
  4059. temp_gcode += line
  4060. lines.close()
  4061. header_stop = False
  4062. return temp_gcode
  4063. if self.multitool is False:
  4064. # offset Gcode
  4065. self.gcode = scale_g(self.gcode)
  4066. # variables to display the percentage of work done
  4067. self.geo_len = 0
  4068. try:
  4069. for g in self.gcode_parsed:
  4070. self.geo_len += 1
  4071. except TypeError:
  4072. self.geo_len = 1
  4073. self.old_disp_number = 0
  4074. self.el_count = 0
  4075. # scale geometry
  4076. for g in self.gcode_parsed:
  4077. try:
  4078. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  4079. except AttributeError:
  4080. return g['geom']
  4081. self.el_count += 1
  4082. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4083. if self.old_disp_number < disp_number <= 100:
  4084. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4085. self.old_disp_number = disp_number
  4086. self.create_geometry()
  4087. else:
  4088. for k, v in self.cnc_tools.items():
  4089. # scale Gcode
  4090. v['gcode'] = scale_g(v['gcode'])
  4091. # variables to display the percentage of work done
  4092. self.geo_len = 0
  4093. try:
  4094. for g in v['gcode_parsed']:
  4095. self.geo_len += 1
  4096. except TypeError:
  4097. self.geo_len = 1
  4098. self.old_disp_number = 0
  4099. self.el_count = 0
  4100. # scale gcode_parsed
  4101. for g in v['gcode_parsed']:
  4102. try:
  4103. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  4104. except AttributeError:
  4105. return g['geom']
  4106. self.el_count += 1
  4107. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4108. if self.old_disp_number < disp_number <= 100:
  4109. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4110. self.old_disp_number = disp_number
  4111. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  4112. self.create_geometry()
  4113. self.app.proc_container.new_text = ''
  4114. def offset(self, vect):
  4115. """
  4116. Offsets all the geometry on the XY plane in the object by the
  4117. given vector.
  4118. Offsets all the GCODE on the XY plane in the object by the
  4119. given vector.
  4120. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  4121. :param vect: (x, y) offset vector.
  4122. :type vect: tuple
  4123. :return: None
  4124. """
  4125. log.debug("camlib.CNCJob.offset()")
  4126. dx, dy = vect
  4127. def offset_g(g):
  4128. """
  4129. :param g: 'g' parameter it's a gcode string
  4130. :return: offseted gcode string
  4131. """
  4132. temp_gcode = ''
  4133. lines = StringIO(g)
  4134. for line in lines:
  4135. # find the X group
  4136. match_x = self.g_x_re.search(line)
  4137. if match_x:
  4138. if match_x.group(1) is not None:
  4139. # get the coordinate and add X offset
  4140. new_x = float(match_x.group(1)[1:]) + dx
  4141. # replace the updated string
  4142. line = line.replace(
  4143. match_x.group(1),
  4144. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  4145. )
  4146. match_y = self.g_y_re.search(line)
  4147. if match_y:
  4148. if match_y.group(1) is not None:
  4149. new_y = float(match_y.group(1)[1:]) + dy
  4150. line = line.replace(
  4151. match_y.group(1),
  4152. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  4153. )
  4154. temp_gcode += line
  4155. lines.close()
  4156. return temp_gcode
  4157. if self.multitool is False:
  4158. # offset Gcode
  4159. self.gcode = offset_g(self.gcode)
  4160. # variables to display the percentage of work done
  4161. self.geo_len = 0
  4162. try:
  4163. for g in self.gcode_parsed:
  4164. self.geo_len += 1
  4165. except TypeError:
  4166. self.geo_len = 1
  4167. self.old_disp_number = 0
  4168. self.el_count = 0
  4169. # offset geometry
  4170. for g in self.gcode_parsed:
  4171. try:
  4172. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  4173. except AttributeError:
  4174. return g['geom']
  4175. self.el_count += 1
  4176. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4177. if self.old_disp_number < disp_number <= 100:
  4178. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4179. self.old_disp_number = disp_number
  4180. self.create_geometry()
  4181. else:
  4182. for k, v in self.cnc_tools.items():
  4183. # offset Gcode
  4184. v['gcode'] = offset_g(v['gcode'])
  4185. # variables to display the percentage of work done
  4186. self.geo_len = 0
  4187. try:
  4188. for g in v['gcode_parsed']:
  4189. self.geo_len += 1
  4190. except TypeError:
  4191. self.geo_len = 1
  4192. self.old_disp_number = 0
  4193. self.el_count = 0
  4194. # offset gcode_parsed
  4195. for g in v['gcode_parsed']:
  4196. try:
  4197. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  4198. except AttributeError:
  4199. return g['geom']
  4200. self.el_count += 1
  4201. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4202. if self.old_disp_number < disp_number <= 100:
  4203. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4204. self.old_disp_number = disp_number
  4205. # for the bounding box
  4206. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  4207. self.app.proc_container.new_text = ''
  4208. def mirror(self, axis, point):
  4209. """
  4210. Mirror the geometrys of an object by an given axis around the coordinates of the 'point'
  4211. :param angle:
  4212. :param point: tupple of coordinates (x,y)
  4213. :return:
  4214. """
  4215. log.debug("camlib.CNCJob.mirror()")
  4216. px, py = point
  4217. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  4218. # variables to display the percentage of work done
  4219. self.geo_len = 0
  4220. try:
  4221. for g in self.gcode_parsed:
  4222. self.geo_len += 1
  4223. except TypeError:
  4224. self.geo_len = 1
  4225. self.old_disp_number = 0
  4226. self.el_count = 0
  4227. for g in self.gcode_parsed:
  4228. try:
  4229. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  4230. except AttributeError:
  4231. return g['geom']
  4232. self.el_count += 1
  4233. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4234. if self.old_disp_number < disp_number <= 100:
  4235. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4236. self.old_disp_number = disp_number
  4237. self.create_geometry()
  4238. self.app.proc_container.new_text = ''
  4239. def skew(self, angle_x, angle_y, point):
  4240. """
  4241. Shear/Skew the geometries of an object by angles along x and y dimensions.
  4242. Parameters
  4243. ----------
  4244. angle_x, angle_y : float, float
  4245. The shear angle(s) for the x and y axes respectively. These can be
  4246. specified in either degrees (default) or radians by setting
  4247. use_radians=True.
  4248. point: tupple of coordinates (x,y)
  4249. See shapely manual for more information:
  4250. http://toblerity.org/shapely/manual.html#affine-transformations
  4251. """
  4252. log.debug("camlib.CNCJob.skew()")
  4253. px, py = point
  4254. # variables to display the percentage of work done
  4255. self.geo_len = 0
  4256. try:
  4257. for g in self.gcode_parsed:
  4258. self.geo_len += 1
  4259. except TypeError:
  4260. self.geo_len = 1
  4261. self.old_disp_number = 0
  4262. self.el_count = 0
  4263. for g in self.gcode_parsed:
  4264. try:
  4265. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  4266. except AttributeError:
  4267. return g['geom']
  4268. self.el_count += 1
  4269. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4270. if self.old_disp_number < disp_number <= 100:
  4271. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4272. self.old_disp_number = disp_number
  4273. self.create_geometry()
  4274. self.app.proc_container.new_text = ''
  4275. def rotate(self, angle, point):
  4276. """
  4277. Rotate the geometrys of an object by an given angle around the coordinates of the 'point'
  4278. :param angle:
  4279. :param point: tupple of coordinates (x,y)
  4280. :return:
  4281. """
  4282. log.debug("camlib.CNCJob.rotate()")
  4283. px, py = point
  4284. # variables to display the percentage of work done
  4285. self.geo_len = 0
  4286. try:
  4287. for g in self.gcode_parsed:
  4288. self.geo_len += 1
  4289. except TypeError:
  4290. self.geo_len = 1
  4291. self.old_disp_number = 0
  4292. self.el_count = 0
  4293. for g in self.gcode_parsed:
  4294. try:
  4295. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  4296. except AttributeError:
  4297. return g['geom']
  4298. self.el_count += 1
  4299. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  4300. if self.old_disp_number < disp_number <= 100:
  4301. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4302. self.old_disp_number = disp_number
  4303. self.create_geometry()
  4304. self.app.proc_container.new_text = ''
  4305. def get_bounds(geometry_list):
  4306. xmin = Inf
  4307. ymin = Inf
  4308. xmax = -Inf
  4309. ymax = -Inf
  4310. for gs in geometry_list:
  4311. try:
  4312. gxmin, gymin, gxmax, gymax = gs.bounds()
  4313. xmin = min([xmin, gxmin])
  4314. ymin = min([ymin, gymin])
  4315. xmax = max([xmax, gxmax])
  4316. ymax = max([ymax, gymax])
  4317. except:
  4318. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  4319. return [xmin, ymin, xmax, ymax]
  4320. def arc(center, radius, start, stop, direction, steps_per_circ):
  4321. """
  4322. Creates a list of point along the specified arc.
  4323. :param center: Coordinates of the center [x, y]
  4324. :type center: list
  4325. :param radius: Radius of the arc.
  4326. :type radius: float
  4327. :param start: Starting angle in radians
  4328. :type start: float
  4329. :param stop: End angle in radians
  4330. :type stop: float
  4331. :param direction: Orientation of the arc, "CW" or "CCW"
  4332. :type direction: string
  4333. :param steps_per_circ: Number of straight line segments to
  4334. represent a circle.
  4335. :type steps_per_circ: int
  4336. :return: The desired arc, as list of tuples
  4337. :rtype: list
  4338. """
  4339. # TODO: Resolution should be established by maximum error from the exact arc.
  4340. da_sign = {"cw": -1.0, "ccw": 1.0}
  4341. points = []
  4342. if direction == "ccw" and stop <= start:
  4343. stop += 2 * pi
  4344. if direction == "cw" and stop >= start:
  4345. stop -= 2 * pi
  4346. angle = abs(stop - start)
  4347. # angle = stop-start
  4348. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  4349. delta_angle = da_sign[direction] * angle * 1.0 / steps
  4350. for i in range(steps + 1):
  4351. theta = start + delta_angle * i
  4352. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  4353. return points
  4354. def arc2(p1, p2, center, direction, steps_per_circ):
  4355. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  4356. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  4357. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  4358. return arc(center, r, start, stop, direction, steps_per_circ)
  4359. def arc_angle(start, stop, direction):
  4360. if direction == "ccw" and stop <= start:
  4361. stop += 2 * pi
  4362. if direction == "cw" and stop >= start:
  4363. stop -= 2 * pi
  4364. angle = abs(stop - start)
  4365. return angle
  4366. # def find_polygon(poly, point):
  4367. # """
  4368. # Find an object that object.contains(Point(point)) in
  4369. # poly, which can can be iterable, contain iterable of, or
  4370. # be itself an implementer of .contains().
  4371. #
  4372. # :param poly: See description
  4373. # :return: Polygon containing point or None.
  4374. # """
  4375. #
  4376. # if poly is None:
  4377. # return None
  4378. #
  4379. # try:
  4380. # for sub_poly in poly:
  4381. # p = find_polygon(sub_poly, point)
  4382. # if p is not None:
  4383. # return p
  4384. # except TypeError:
  4385. # try:
  4386. # if poly.contains(Point(point)):
  4387. # return poly
  4388. # except AttributeError:
  4389. # return None
  4390. #
  4391. # return None
  4392. def to_dict(obj):
  4393. """
  4394. Makes the following types into serializable form:
  4395. * ApertureMacro
  4396. * BaseGeometry
  4397. :param obj: Shapely geometry.
  4398. :type obj: BaseGeometry
  4399. :return: Dictionary with serializable form if ``obj`` was
  4400. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  4401. """
  4402. if isinstance(obj, ApertureMacro):
  4403. return {
  4404. "__class__": "ApertureMacro",
  4405. "__inst__": obj.to_dict()
  4406. }
  4407. if isinstance(obj, BaseGeometry):
  4408. return {
  4409. "__class__": "Shply",
  4410. "__inst__": sdumps(obj)
  4411. }
  4412. return obj
  4413. def dict2obj(d):
  4414. """
  4415. Default deserializer.
  4416. :param d: Serializable dictionary representation of an object
  4417. to be reconstructed.
  4418. :return: Reconstructed object.
  4419. """
  4420. if '__class__' in d and '__inst__' in d:
  4421. if d['__class__'] == "Shply":
  4422. return sloads(d['__inst__'])
  4423. if d['__class__'] == "ApertureMacro":
  4424. am = ApertureMacro()
  4425. am.from_dict(d['__inst__'])
  4426. return am
  4427. return d
  4428. else:
  4429. return d
  4430. # def plotg(geo, solid_poly=False, color="black"):
  4431. # try:
  4432. # __ = iter(geo)
  4433. # except:
  4434. # geo = [geo]
  4435. #
  4436. # for g in geo:
  4437. # if type(g) == Polygon:
  4438. # if solid_poly:
  4439. # patch = PolygonPatch(g,
  4440. # facecolor="#BBF268",
  4441. # edgecolor="#006E20",
  4442. # alpha=0.75,
  4443. # zorder=2)
  4444. # ax = subplot(111)
  4445. # ax.add_patch(patch)
  4446. # else:
  4447. # x, y = g.exterior.coords.xy
  4448. # plot(x, y, color=color)
  4449. # for ints in g.interiors:
  4450. # x, y = ints.coords.xy
  4451. # plot(x, y, color=color)
  4452. # continue
  4453. #
  4454. # if type(g) == LineString or type(g) == LinearRing:
  4455. # x, y = g.coords.xy
  4456. # plot(x, y, color=color)
  4457. # continue
  4458. #
  4459. # if type(g) == Point:
  4460. # x, y = g.coords.xy
  4461. # plot(x, y, 'o')
  4462. # continue
  4463. #
  4464. # try:
  4465. # __ = iter(g)
  4466. # plotg(g, color=color)
  4467. # except:
  4468. # log.error("Cannot plot: " + str(type(g)))
  4469. # continue
  4470. # def alpha_shape(points, alpha):
  4471. # """
  4472. # Compute the alpha shape (concave hull) of a set of points.
  4473. #
  4474. # @param points: Iterable container of points.
  4475. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  4476. # numbers don't fall inward as much as larger numbers. Too large,
  4477. # and you lose everything!
  4478. # """
  4479. # if len(points) < 4:
  4480. # # When you have a triangle, there is no sense in computing an alpha
  4481. # # shape.
  4482. # return MultiPoint(list(points)).convex_hull
  4483. #
  4484. # def add_edge(edges, edge_points, coords, i, j):
  4485. # """Add a line between the i-th and j-th points, if not in the list already"""
  4486. # if (i, j) in edges or (j, i) in edges:
  4487. # # already added
  4488. # return
  4489. # edges.add( (i, j) )
  4490. # edge_points.append(coords[ [i, j] ])
  4491. #
  4492. # coords = np.array([point.coords[0] for point in points])
  4493. #
  4494. # tri = Delaunay(coords)
  4495. # edges = set()
  4496. # edge_points = []
  4497. # # loop over triangles:
  4498. # # ia, ib, ic = indices of corner points of the triangle
  4499. # for ia, ib, ic in tri.vertices:
  4500. # pa = coords[ia]
  4501. # pb = coords[ib]
  4502. # pc = coords[ic]
  4503. #
  4504. # # Lengths of sides of triangle
  4505. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  4506. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  4507. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  4508. #
  4509. # # Semiperimeter of triangle
  4510. # s = (a + b + c)/2.0
  4511. #
  4512. # # Area of triangle by Heron's formula
  4513. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  4514. # circum_r = a*b*c/(4.0*area)
  4515. #
  4516. # # Here's the radius filter.
  4517. # #print circum_r
  4518. # if circum_r < 1.0/alpha:
  4519. # add_edge(edges, edge_points, coords, ia, ib)
  4520. # add_edge(edges, edge_points, coords, ib, ic)
  4521. # add_edge(edges, edge_points, coords, ic, ia)
  4522. #
  4523. # m = MultiLineString(edge_points)
  4524. # triangles = list(polygonize(m))
  4525. # return cascaded_union(triangles), edge_points
  4526. # def voronoi(P):
  4527. # """
  4528. # Returns a list of all edges of the voronoi diagram for the given input points.
  4529. # """
  4530. # delauny = Delaunay(P)
  4531. # triangles = delauny.points[delauny.vertices]
  4532. #
  4533. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  4534. # long_lines_endpoints = []
  4535. #
  4536. # lineIndices = []
  4537. # for i, triangle in enumerate(triangles):
  4538. # circum_center = circum_centers[i]
  4539. # for j, neighbor in enumerate(delauny.neighbors[i]):
  4540. # if neighbor != -1:
  4541. # lineIndices.append((i, neighbor))
  4542. # else:
  4543. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  4544. # ps = np.array((ps[1], -ps[0]))
  4545. #
  4546. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  4547. # di = middle - triangle[j]
  4548. #
  4549. # ps /= np.linalg.norm(ps)
  4550. # di /= np.linalg.norm(di)
  4551. #
  4552. # if np.dot(di, ps) < 0.0:
  4553. # ps *= -1000.0
  4554. # else:
  4555. # ps *= 1000.0
  4556. #
  4557. # long_lines_endpoints.append(circum_center + ps)
  4558. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  4559. #
  4560. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  4561. #
  4562. # # filter out any duplicate lines
  4563. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  4564. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  4565. # lineIndicesUnique = np.unique(lineIndicesTupled)
  4566. #
  4567. # return vertices, lineIndicesUnique
  4568. #
  4569. #
  4570. # def triangle_csc(pts):
  4571. # rows, cols = pts.shape
  4572. #
  4573. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  4574. # [np.ones((1, rows)), np.zeros((1, 1))]])
  4575. #
  4576. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  4577. # x = np.linalg.solve(A,b)
  4578. # bary_coords = x[:-1]
  4579. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  4580. #
  4581. #
  4582. # def voronoi_cell_lines(points, vertices, lineIndices):
  4583. # """
  4584. # Returns a mapping from a voronoi cell to its edges.
  4585. #
  4586. # :param points: shape (m,2)
  4587. # :param vertices: shape (n,2)
  4588. # :param lineIndices: shape (o,2)
  4589. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  4590. # """
  4591. # kd = KDTree(points)
  4592. #
  4593. # cells = collections.defaultdict(list)
  4594. # for i1, i2 in lineIndices:
  4595. # v1, v2 = vertices[i1], vertices[i2]
  4596. # mid = (v1+v2)/2
  4597. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  4598. # cells[p1Idx].append((i1, i2))
  4599. # cells[p2Idx].append((i1, i2))
  4600. #
  4601. # return cells
  4602. #
  4603. #
  4604. # def voronoi_edges2polygons(cells):
  4605. # """
  4606. # Transforms cell edges into polygons.
  4607. #
  4608. # :param cells: as returned from voronoi_cell_lines
  4609. # :rtype: dict point index -> list of vertex indices which form a polygon
  4610. # """
  4611. #
  4612. # # first, close the outer cells
  4613. # for pIdx, lineIndices_ in cells.items():
  4614. # dangling_lines = []
  4615. # for i1, i2 in lineIndices_:
  4616. # p = (i1, i2)
  4617. # connections = filter(lambda k: p != k and
  4618. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  4619. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  4620. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  4621. # assert 1 <= len(connections) <= 2
  4622. # if len(connections) == 1:
  4623. # dangling_lines.append((i1, i2))
  4624. # assert len(dangling_lines) in [0, 2]
  4625. # if len(dangling_lines) == 2:
  4626. # (i11, i12), (i21, i22) = dangling_lines
  4627. # s = (i11, i12)
  4628. # t = (i21, i22)
  4629. #
  4630. # # determine which line ends are unconnected
  4631. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  4632. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  4633. # i11Unconnected = len(connected) == 0
  4634. #
  4635. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  4636. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  4637. # i21Unconnected = len(connected) == 0
  4638. #
  4639. # startIdx = i11 if i11Unconnected else i12
  4640. # endIdx = i21 if i21Unconnected else i22
  4641. #
  4642. # cells[pIdx].append((startIdx, endIdx))
  4643. #
  4644. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  4645. # polys = dict()
  4646. # for pIdx, lineIndices_ in cells.items():
  4647. # # get a directed graph which contains both directions and arbitrarily follow one of both
  4648. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  4649. # directedGraphMap = collections.defaultdict(list)
  4650. # for (i1, i2) in directedGraph:
  4651. # directedGraphMap[i1].append(i2)
  4652. # orderedEdges = []
  4653. # currentEdge = directedGraph[0]
  4654. # while len(orderedEdges) < len(lineIndices_):
  4655. # i1 = currentEdge[1]
  4656. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  4657. # nextEdge = (i1, i2)
  4658. # orderedEdges.append(nextEdge)
  4659. # currentEdge = nextEdge
  4660. #
  4661. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  4662. #
  4663. # return polys
  4664. #
  4665. #
  4666. # def voronoi_polygons(points):
  4667. # """
  4668. # Returns the voronoi polygon for each input point.
  4669. #
  4670. # :param points: shape (n,2)
  4671. # :rtype: list of n polygons where each polygon is an array of vertices
  4672. # """
  4673. # vertices, lineIndices = voronoi(points)
  4674. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  4675. # polys = voronoi_edges2polygons(cells)
  4676. # polylist = []
  4677. # for i in range(len(points)):
  4678. # poly = vertices[np.asarray(polys[i])]
  4679. # polylist.append(poly)
  4680. # return polylist
  4681. #
  4682. #
  4683. # class Zprofile:
  4684. # def __init__(self):
  4685. #
  4686. # # data contains lists of [x, y, z]
  4687. # self.data = []
  4688. #
  4689. # # Computed voronoi polygons (shapely)
  4690. # self.polygons = []
  4691. # pass
  4692. #
  4693. # # def plot_polygons(self):
  4694. # # axes = plt.subplot(1, 1, 1)
  4695. # #
  4696. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  4697. # #
  4698. # # for poly in self.polygons:
  4699. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  4700. # # axes.add_patch(p)
  4701. #
  4702. # def init_from_csv(self, filename):
  4703. # pass
  4704. #
  4705. # def init_from_string(self, zpstring):
  4706. # pass
  4707. #
  4708. # def init_from_list(self, zplist):
  4709. # self.data = zplist
  4710. #
  4711. # def generate_polygons(self):
  4712. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  4713. #
  4714. # def normalize(self, origin):
  4715. # pass
  4716. #
  4717. # def paste(self, path):
  4718. # """
  4719. # Return a list of dictionaries containing the parts of the original
  4720. # path and their z-axis offset.
  4721. # """
  4722. #
  4723. # # At most one region/polygon will contain the path
  4724. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  4725. #
  4726. # if len(containing) > 0:
  4727. # return [{"path": path, "z": self.data[containing[0]][2]}]
  4728. #
  4729. # # All region indexes that intersect with the path
  4730. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  4731. #
  4732. # return [{"path": path.intersection(self.polygons[i]),
  4733. # "z": self.data[i][2]} for i in crossing]
  4734. def autolist(obj):
  4735. try:
  4736. __ = iter(obj)
  4737. return obj
  4738. except TypeError:
  4739. return [obj]
  4740. def three_point_circle(p1, p2, p3):
  4741. """
  4742. Computes the center and radius of a circle from
  4743. 3 points on its circumference.
  4744. :param p1: Point 1
  4745. :param p2: Point 2
  4746. :param p3: Point 3
  4747. :return: center, radius
  4748. """
  4749. # Midpoints
  4750. a1 = (p1 + p2) / 2.0
  4751. a2 = (p2 + p3) / 2.0
  4752. # Normals
  4753. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  4754. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  4755. # Params
  4756. try:
  4757. T = solve(transpose(array([-b1, b2])), a1 - a2)
  4758. except Exception as e:
  4759. log.debug("camlib.three_point_circle() --> %s" % str(e))
  4760. return
  4761. # Center
  4762. center = a1 + b1 * T[0]
  4763. # Radius
  4764. radius = np.linalg.norm(center - p1)
  4765. return center, radius, T[0]
  4766. def distance(pt1, pt2):
  4767. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  4768. def distance_euclidian(x1, y1, x2, y2):
  4769. return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  4770. class FlatCAMRTree(object):
  4771. """
  4772. Indexes geometry (Any object with "cooords" property containing
  4773. a list of tuples with x, y values). Objects are indexed by
  4774. all their points by default. To index by arbitrary points,
  4775. override self.points2obj.
  4776. """
  4777. def __init__(self):
  4778. # Python RTree Index
  4779. self.rti = rtindex.Index()
  4780. # ## Track object-point relationship
  4781. # Each is list of points in object.
  4782. self.obj2points = []
  4783. # Index is index in rtree, value is index of
  4784. # object in obj2points.
  4785. self.points2obj = []
  4786. self.get_points = lambda go: go.coords
  4787. def grow_obj2points(self, idx):
  4788. """
  4789. Increases the size of self.obj2points to fit
  4790. idx + 1 items.
  4791. :param idx: Index to fit into list.
  4792. :return: None
  4793. """
  4794. if len(self.obj2points) > idx:
  4795. # len == 2, idx == 1, ok.
  4796. return
  4797. else:
  4798. # len == 2, idx == 2, need 1 more.
  4799. # range(2, 3)
  4800. for i in range(len(self.obj2points), idx + 1):
  4801. self.obj2points.append([])
  4802. def insert(self, objid, obj):
  4803. self.grow_obj2points(objid)
  4804. self.obj2points[objid] = []
  4805. for pt in self.get_points(obj):
  4806. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  4807. self.obj2points[objid].append(len(self.points2obj))
  4808. self.points2obj.append(objid)
  4809. def remove_obj(self, objid, obj):
  4810. # Use all ptids to delete from index
  4811. for i, pt in enumerate(self.get_points(obj)):
  4812. try:
  4813. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  4814. except IndexError:
  4815. pass
  4816. def nearest(self, pt):
  4817. """
  4818. Will raise StopIteration if no items are found.
  4819. :param pt:
  4820. :return:
  4821. """
  4822. return next(self.rti.nearest(pt, objects=True))
  4823. class FlatCAMRTreeStorage(FlatCAMRTree):
  4824. """
  4825. Just like FlatCAMRTree it indexes geometry, but also serves
  4826. as storage for the geometry.
  4827. """
  4828. def __init__(self):
  4829. # super(FlatCAMRTreeStorage, self).__init__()
  4830. super().__init__()
  4831. self.objects = []
  4832. # Optimization attempt!
  4833. self.indexes = {}
  4834. def insert(self, obj):
  4835. self.objects.append(obj)
  4836. idx = len(self.objects) - 1
  4837. # Note: Shapely objects are not hashable any more, althought
  4838. # there seem to be plans to re-introduce the feature in
  4839. # version 2.0. For now, we will index using the object's id,
  4840. # but it's important to remember that shapely geometry is
  4841. # mutable, ie. it can be modified to a totally different shape
  4842. # and continue to have the same id.
  4843. # self.indexes[obj] = idx
  4844. self.indexes[id(obj)] = idx
  4845. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  4846. super().insert(idx, obj)
  4847. # @profile
  4848. def remove(self, obj):
  4849. # See note about self.indexes in insert().
  4850. # objidx = self.indexes[obj]
  4851. objidx = self.indexes[id(obj)]
  4852. # Remove from list
  4853. self.objects[objidx] = None
  4854. # Remove from index
  4855. self.remove_obj(objidx, obj)
  4856. def get_objects(self):
  4857. return (o for o in self.objects if o is not None)
  4858. def nearest(self, pt):
  4859. """
  4860. Returns the nearest matching points and the object
  4861. it belongs to.
  4862. :param pt: Query point.
  4863. :return: (match_x, match_y), Object owner of
  4864. matching point.
  4865. :rtype: tuple
  4866. """
  4867. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  4868. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  4869. # class myO:
  4870. # def __init__(self, coords):
  4871. # self.coords = coords
  4872. #
  4873. #
  4874. # def test_rti():
  4875. #
  4876. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4877. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4878. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4879. #
  4880. # os = [o1, o2]
  4881. #
  4882. # idx = FlatCAMRTree()
  4883. #
  4884. # for o in range(len(os)):
  4885. # idx.insert(o, os[o])
  4886. #
  4887. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4888. #
  4889. # idx.remove_obj(0, o1)
  4890. #
  4891. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4892. #
  4893. # idx.remove_obj(1, o2)
  4894. #
  4895. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4896. #
  4897. #
  4898. # def test_rtis():
  4899. #
  4900. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  4901. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  4902. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  4903. #
  4904. # os = [o1, o2]
  4905. #
  4906. # idx = FlatCAMRTreeStorage()
  4907. #
  4908. # for o in range(len(os)):
  4909. # idx.insert(os[o])
  4910. #
  4911. # #os = None
  4912. # #o1 = None
  4913. # #o2 = None
  4914. #
  4915. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4916. #
  4917. # idx.remove(idx.nearest((2,0))[1])
  4918. #
  4919. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  4920. #
  4921. # idx.remove(idx.nearest((0,0))[1])
  4922. #
  4923. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]