camlib.py 236 KB

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