camlib.py 230 KB

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