camlib.py 312 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591
  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. from numpy.linalg import solve, norm
  11. import platform
  12. from copy import deepcopy
  13. import traceback
  14. from decimal import Decimal
  15. from rtree import index as rtindex
  16. from lxml import etree as ET
  17. # See: http://toblerity.org/shapely/manual.html
  18. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString, MultiPoint, MultiPolygon
  19. from shapely.geometry import box as shply_box
  20. from shapely.ops import cascaded_union, unary_union, substring
  21. import shapely.affinity as affinity
  22. from shapely.wkt import loads as sloads
  23. from shapely.wkt import dumps as sdumps
  24. from shapely.geometry.base import BaseGeometry
  25. from shapely.geometry import shape
  26. # ---------------------------------------
  27. # NEEDED for Legacy mode
  28. # Used for solid polygons in Matplotlib
  29. from descartes.patch import PolygonPatch
  30. # ---------------------------------------
  31. from collections import Iterable
  32. import rasterio
  33. from rasterio.features import shapes
  34. import ezdxf
  35. from Common import GracefulException as grace
  36. # Commented for FlatCAM packaging with cx_freeze
  37. # from scipy.spatial import KDTree, Delaunay
  38. # from scipy.spatial import Delaunay
  39. from appParsers.ParseSVG import *
  40. from appParsers.ParseDXF import *
  41. if platform.architecture()[0] == '64bit':
  42. from ortools.constraint_solver import pywrapcp
  43. from ortools.constraint_solver import routing_enums_pb2
  44. import logging
  45. import gettext
  46. import appTranslation 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. self.drawing_tolerance = 0.0
  365. self.tools = None
  366. # Final geometry: MultiPolygon or list (of geometry constructs)
  367. self.solid_geometry = None
  368. # Final geometry: MultiLineString or list (of LineString or Points)
  369. self.follow_geometry = None
  370. # Attributes to be included in serialization
  371. self.ser_attrs = ["units", 'solid_geometry', 'follow_geometry']
  372. # Flattened geometry (list of paths only)
  373. self.flat_geometry = []
  374. # this is the calculated conversion factor when the file units are different than the ones in the app
  375. self.file_units_factor = 1
  376. # Index
  377. self.index = None
  378. self.geo_steps_per_circle = geo_steps_per_circle
  379. # variables to display the percentage of work done
  380. self.geo_len = 0
  381. self.old_disp_number = 0
  382. self.el_count = 0
  383. if self.app.is_legacy is False:
  384. self.temp_shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  385. else:
  386. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  387. self.temp_shapes = ShapeCollectionLegacy(obj=self, app=self.app, name='camlib.geometry')
  388. def plot_temp_shapes(self, element, color='red'):
  389. try:
  390. for sub_el in element:
  391. self.plot_temp_shapes(sub_el)
  392. except TypeError: # Element is not iterable...
  393. # self.add_shape(shape=element, color=color, visible=visible, layer=0)
  394. self.temp_shapes.add(tolerance=float(self.app.defaults["global_tolerance"]),
  395. shape=element, color=color, visible=True, layer=0)
  396. def make_index(self):
  397. self.flatten()
  398. self.index = FlatCAMRTree()
  399. for i, g in enumerate(self.flat_geometry):
  400. self.index.insert(i, g)
  401. def add_circle(self, origin, radius):
  402. """
  403. Adds a circle to the object.
  404. :param origin: Center of the circle.
  405. :param radius: Radius of the circle.
  406. :return: None
  407. """
  408. if self.solid_geometry is None:
  409. self.solid_geometry = []
  410. if type(self.solid_geometry) is list:
  411. self.solid_geometry.append(Point(origin).buffer(radius, int(self.geo_steps_per_circle)))
  412. return
  413. try:
  414. self.solid_geometry = self.solid_geometry.union(
  415. Point(origin).buffer(radius, int(self.geo_steps_per_circle))
  416. )
  417. except Exception as e:
  418. log.error("Failed to run union on polygons. %s" % str(e))
  419. return
  420. def add_polygon(self, points):
  421. """
  422. Adds a polygon to the object (by union)
  423. :param points: The vertices of the polygon.
  424. :return: None
  425. """
  426. if self.solid_geometry is None:
  427. self.solid_geometry = []
  428. if type(self.solid_geometry) is list:
  429. self.solid_geometry.append(Polygon(points))
  430. return
  431. try:
  432. self.solid_geometry = self.solid_geometry.union(Polygon(points))
  433. except Exception as e:
  434. log.error("Failed to run union on polygons. %s" % str(e))
  435. return
  436. def add_polyline(self, points):
  437. """
  438. Adds a polyline to the object (by union)
  439. :param points: The vertices of the polyline.
  440. :return: None
  441. """
  442. if self.solid_geometry is None:
  443. self.solid_geometry = []
  444. if type(self.solid_geometry) is list:
  445. self.solid_geometry.append(LineString(points))
  446. return
  447. try:
  448. self.solid_geometry = self.solid_geometry.union(LineString(points))
  449. except Exception as e:
  450. log.error("Failed to run union on polylines. %s" % str(e))
  451. return
  452. def is_empty(self):
  453. if isinstance(self.solid_geometry, BaseGeometry) or isinstance(self.solid_geometry, Polygon) or \
  454. isinstance(self.solid_geometry, MultiPolygon):
  455. return self.solid_geometry.is_empty
  456. if isinstance(self.solid_geometry, list):
  457. return len(self.solid_geometry) == 0
  458. self.app.inform.emit('[ERROR_NOTCL] %s' % _("self.solid_geometry is neither BaseGeometry or list."))
  459. return
  460. def subtract_polygon(self, points):
  461. """
  462. Subtract polygon from the given object. This only operates on the paths in the original geometry,
  463. i.e. it converts polygons into paths.
  464. :param points: The vertices of the polygon.
  465. :return: none
  466. """
  467. if self.solid_geometry is None:
  468. self.solid_geometry = []
  469. # pathonly should be allways True, otherwise polygons are not subtracted
  470. flat_geometry = self.flatten(pathonly=True)
  471. log.debug("%d paths" % len(flat_geometry))
  472. if not isinstance(points, Polygon):
  473. polygon = Polygon(points)
  474. else:
  475. polygon = points
  476. toolgeo = cascaded_union(polygon)
  477. diffs = []
  478. for target in flat_geometry:
  479. if isinstance(target, LineString) or isinstance(target, LineString) or isinstance(target, MultiLineString):
  480. diffs.append(target.difference(toolgeo))
  481. else:
  482. log.warning("Not implemented.")
  483. self.solid_geometry = unary_union(diffs)
  484. def bounds(self, flatten=False):
  485. """
  486. Returns coordinates of rectangular bounds
  487. of geometry: (xmin, ymin, xmax, ymax).
  488. :param flatten: will flatten the solid_geometry if True
  489. :return:
  490. """
  491. # fixed issue of getting bounds only for one level lists of objects
  492. # now it can get bounds for nested lists of objects
  493. log.debug("camlib.Geometry.bounds()")
  494. if self.solid_geometry is None:
  495. log.debug("solid_geometry is None")
  496. return 0, 0, 0, 0
  497. def bounds_rec(obj):
  498. if type(obj) is list:
  499. gminx = np.Inf
  500. gminy = np.Inf
  501. gmaxx = -np.Inf
  502. gmaxy = -np.Inf
  503. for k in obj:
  504. if type(k) is dict:
  505. for key in k:
  506. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  507. gminx = min(gminx, minx_)
  508. gminy = min(gminy, miny_)
  509. gmaxx = max(gmaxx, maxx_)
  510. gmaxy = max(gmaxy, maxy_)
  511. else:
  512. try:
  513. if k.is_empty:
  514. continue
  515. except Exception:
  516. pass
  517. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  518. gminx = min(gminx, minx_)
  519. gminy = min(gminy, miny_)
  520. gmaxx = max(gmaxx, maxx_)
  521. gmaxy = max(gmaxy, maxy_)
  522. return gminx, gminy, gmaxx, gmaxy
  523. else:
  524. # it's a Shapely object, return it's bounds
  525. return obj.bounds
  526. if self.multigeo is True:
  527. minx_list = []
  528. miny_list = []
  529. maxx_list = []
  530. maxy_list = []
  531. for tool in self.tools:
  532. working_geo = self.tools[tool]['solid_geometry']
  533. if flatten:
  534. self.flatten(geometry=working_geo, reset=True)
  535. working_geo = self.flat_geometry
  536. minx, miny, maxx, maxy = bounds_rec(working_geo)
  537. minx_list.append(minx)
  538. miny_list.append(miny)
  539. maxx_list.append(maxx)
  540. maxy_list.append(maxy)
  541. return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
  542. else:
  543. if flatten:
  544. self.flatten(reset=True)
  545. self.solid_geometry = self.flat_geometry
  546. bounds_coords = bounds_rec(self.solid_geometry)
  547. return bounds_coords
  548. # try:
  549. # # from here: http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
  550. # def flatten(l, ltypes=(list, tuple)):
  551. # ltype = type(l)
  552. # l = list(l)
  553. # i = 0
  554. # while i < len(l):
  555. # while isinstance(l[i], ltypes):
  556. # if not l[i]:
  557. # l.pop(i)
  558. # i -= 1
  559. # break
  560. # else:
  561. # l[i:i + 1] = l[i]
  562. # i += 1
  563. # return ltype(l)
  564. #
  565. # log.debug("Geometry->bounds()")
  566. # if self.solid_geometry is None:
  567. # log.debug("solid_geometry is None")
  568. # return 0, 0, 0, 0
  569. #
  570. # if type(self.solid_geometry) is list:
  571. # if len(self.solid_geometry) == 0:
  572. # log.debug('solid_geometry is empty []')
  573. # return 0, 0, 0, 0
  574. # return cascaded_union(flatten(self.solid_geometry)).bounds
  575. # else:
  576. # return self.solid_geometry.bounds
  577. # except Exception as e:
  578. # self.app.inform.emit("[ERROR_NOTCL] Error cause: %s" % str(e))
  579. # log.debug("Geometry->bounds()")
  580. # if self.solid_geometry is None:
  581. # log.debug("solid_geometry is None")
  582. # return 0, 0, 0, 0
  583. #
  584. # if type(self.solid_geometry) is list:
  585. # if len(self.solid_geometry) == 0:
  586. # log.debug('solid_geometry is empty []')
  587. # return 0, 0, 0, 0
  588. # return cascaded_union(self.solid_geometry).bounds
  589. # else:
  590. # return self.solid_geometry.bounds
  591. def find_polygon(self, point, geoset=None):
  592. """
  593. Find an object that object.contains(Point(point)) in
  594. poly, which can can be iterable, contain iterable of, or
  595. be itself an implementer of .contains().
  596. :param point: See description
  597. :param geoset: a polygon or list of polygons where to find if the param point is contained
  598. :return: Polygon containing point or None.
  599. """
  600. if geoset is None:
  601. geoset = self.solid_geometry
  602. try: # Iterable
  603. for sub_geo in geoset:
  604. p = self.find_polygon(point, geoset=sub_geo)
  605. if p is not None:
  606. return p
  607. except TypeError: # Non-iterable
  608. try: # Implements .contains()
  609. if isinstance(geoset, LinearRing):
  610. geoset = Polygon(geoset)
  611. if geoset.contains(Point(point)):
  612. return geoset
  613. except AttributeError: # Does not implement .contains()
  614. return None
  615. return None
  616. def get_interiors(self, geometry=None):
  617. interiors = []
  618. if geometry is None:
  619. geometry = self.solid_geometry
  620. # ## If iterable, expand recursively.
  621. try:
  622. for geo in geometry:
  623. interiors.extend(self.get_interiors(geometry=geo))
  624. # ## Not iterable, get the interiors if polygon.
  625. except TypeError:
  626. if type(geometry) == Polygon:
  627. interiors.extend(geometry.interiors)
  628. return interiors
  629. def get_exteriors(self, geometry=None):
  630. """
  631. Returns all exteriors of polygons in geometry. Uses
  632. ``self.solid_geometry`` if geometry is not provided.
  633. :param geometry: Shapely type or list or list of list of such.
  634. :return: List of paths constituting the exteriors
  635. of polygons in geometry.
  636. """
  637. exteriors = []
  638. if geometry is None:
  639. geometry = self.solid_geometry
  640. # ## If iterable, expand recursively.
  641. try:
  642. for geo in geometry:
  643. exteriors.extend(self.get_exteriors(geometry=geo))
  644. # ## Not iterable, get the exterior if polygon.
  645. except TypeError:
  646. if type(geometry) == Polygon:
  647. exteriors.append(geometry.exterior)
  648. return exteriors
  649. def flatten(self, geometry=None, reset=True, pathonly=False):
  650. """
  651. Creates a list of non-iterable linear geometry objects.
  652. Polygons are expanded into its exterior and interiors if specified.
  653. Results are placed in self.flat_geometry
  654. :param geometry: Shapely type or list or list of list of such.
  655. :param reset: Clears the contents of self.flat_geometry.
  656. :param pathonly: Expands polygons into linear elements.
  657. """
  658. if geometry is None:
  659. geometry = self.solid_geometry
  660. if reset:
  661. self.flat_geometry = []
  662. # ## If iterable, expand recursively.
  663. try:
  664. for geo in geometry:
  665. if geo is not None:
  666. self.flatten(geometry=geo,
  667. reset=False,
  668. pathonly=pathonly)
  669. # ## Not iterable, do the actual indexing and add.
  670. except TypeError:
  671. if pathonly and type(geometry) == Polygon:
  672. self.flat_geometry.append(geometry.exterior)
  673. self.flatten(geometry=geometry.interiors,
  674. reset=False,
  675. pathonly=True)
  676. else:
  677. self.flat_geometry.append(geometry)
  678. return self.flat_geometry
  679. # def make2Dstorage(self):
  680. #
  681. # self.flatten()
  682. #
  683. # def get_pts(o):
  684. # pts = []
  685. # if type(o) == Polygon:
  686. # g = o.exterior
  687. # pts += list(g.coords)
  688. # for i in o.interiors:
  689. # pts += list(i.coords)
  690. # else:
  691. # pts += list(o.coords)
  692. # return pts
  693. #
  694. # storage = FlatCAMRTreeStorage()
  695. # storage.get_points = get_pts
  696. # for shape in self.flat_geometry:
  697. # storage.insert(shape)
  698. # return storage
  699. # def flatten_to_paths(self, geometry=None, reset=True):
  700. # """
  701. # Creates a list of non-iterable linear geometry elements and
  702. # indexes them in rtree.
  703. #
  704. # :param geometry: Iterable geometry
  705. # :param reset: Wether to clear (True) or append (False) to self.flat_geometry
  706. # :return: self.flat_geometry, self.flat_geometry_rtree
  707. # """
  708. #
  709. # if geometry is None:
  710. # geometry = self.solid_geometry
  711. #
  712. # if reset:
  713. # self.flat_geometry = []
  714. #
  715. # # ## If iterable, expand recursively.
  716. # try:
  717. # for geo in geometry:
  718. # self.flatten_to_paths(geometry=geo, reset=False)
  719. #
  720. # # ## Not iterable, do the actual indexing and add.
  721. # except TypeError:
  722. # if type(geometry) == Polygon:
  723. # g = geometry.exterior
  724. # self.flat_geometry.append(g)
  725. #
  726. # # ## Add first and last points of the path to the index.
  727. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  728. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  729. #
  730. # for interior in geometry.interiors:
  731. # g = interior
  732. # self.flat_geometry.append(g)
  733. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  734. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  735. # else:
  736. # g = geometry
  737. # self.flat_geometry.append(g)
  738. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[0])
  739. # self.flat_geometry_rtree.insert(len(self.flat_geometry) - 1, g.coords[-1])
  740. #
  741. # return self.flat_geometry, self.flat_geometry_rtree
  742. def isolation_geometry(self, offset, geometry=None, iso_type=2, corner=None, follow=None, passes=0,
  743. prog_plot=False):
  744. """
  745. Creates contours around geometry at a given
  746. offset distance.
  747. :param offset: Offset distance.
  748. :type offset: float
  749. :param geometry The geometry to work with
  750. :param iso_type: type of isolation, can be 0 = exteriors or 1 = interiors or 2 = both (complete)
  751. :param corner: type of corner for the isolation:
  752. 0 = round; 1 = square; 2= beveled (line that connects the ends)
  753. :param follow: whether the geometry to be isolated is a follow_geometry
  754. :param passes: current pass out of possible multiple passes for which the isolation is done
  755. :param prog_plot: type of plotting: "normal" or "progressive"
  756. :return: The buffered geometry.
  757. :rtype: Shapely.MultiPolygon or Shapely.Polygon
  758. """
  759. if self.app.abort_flag:
  760. # graceful abort requested by the user
  761. raise grace
  762. geo_iso = []
  763. if follow:
  764. return geometry
  765. if geometry:
  766. working_geo = geometry
  767. else:
  768. working_geo = self.solid_geometry
  769. try:
  770. geo_len = len(working_geo)
  771. except TypeError:
  772. geo_len = 1
  773. old_disp_number = 0
  774. pol_nr = 0
  775. # yet, it can be done by issuing an unary_union in the end, thus getting rid of the overlapping geo
  776. try:
  777. for pol in working_geo:
  778. if self.app.abort_flag:
  779. # graceful abort requested by the user
  780. raise grace
  781. if offset == 0:
  782. temp_geo = pol
  783. else:
  784. corner_type = 1 if corner is None else corner
  785. temp_geo = pol.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  786. geo_iso.append(temp_geo)
  787. pol_nr += 1
  788. # activity view update
  789. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  790. if old_disp_number < disp_number <= 100:
  791. self.app.proc_container.update_view_text(' %s %d: %d%%' %
  792. (_("Pass"), int(passes + 1), int(disp_number)))
  793. old_disp_number = disp_number
  794. except TypeError:
  795. # taking care of the case when the self.solid_geometry is just a single Polygon, not a list or a
  796. # MultiPolygon (not an iterable)
  797. if offset == 0:
  798. temp_geo = working_geo
  799. else:
  800. corner_type = 1 if corner is None else corner
  801. temp_geo = working_geo.buffer(offset, int(self.geo_steps_per_circle), join_style=corner_type)
  802. geo_iso.append(temp_geo)
  803. self.app.proc_container.update_view_text(' %s' % _("Buffering"))
  804. geo_iso = unary_union(geo_iso)
  805. self.app.proc_container.update_view_text('')
  806. # end of replaced block
  807. if iso_type == 2:
  808. ret_geo = geo_iso
  809. elif iso_type == 0:
  810. self.app.proc_container.update_view_text(' %s' % _("Get Exteriors"))
  811. ret_geo = self.get_exteriors(geo_iso)
  812. elif iso_type == 1:
  813. self.app.proc_container.update_view_text(' %s' % _("Get Interiors"))
  814. ret_geo = self.get_interiors(geo_iso)
  815. else:
  816. log.debug("Geometry.isolation_geometry() --> Type of isolation not supported")
  817. return "fail"
  818. if prog_plot == 'progressive':
  819. for elem in ret_geo:
  820. self.plot_temp_shapes(elem)
  821. return ret_geo
  822. def flatten_list(self, obj_list):
  823. for item in obj_list:
  824. if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
  825. yield from self.flatten_list(item)
  826. else:
  827. yield item
  828. def import_svg(self, filename, object_type=None, flip=True, units='MM'):
  829. """
  830. Imports shapes from an SVG file into the object's geometry.
  831. :param filename: Path to the SVG file.
  832. :type filename: str
  833. :param object_type: parameter passed further along
  834. :param flip: Flip the vertically.
  835. :type flip: bool
  836. :param units: FlatCAM units
  837. :return: None
  838. """
  839. log.debug("camlib.Geometry.import_svg()")
  840. # Parse into list of shapely objects
  841. svg_tree = ET.parse(filename)
  842. svg_root = svg_tree.getroot()
  843. # Change origin to bottom left
  844. # h = float(svg_root.get('height'))
  845. # w = float(svg_root.get('width'))
  846. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  847. geos = getsvggeo(svg_root, object_type)
  848. if flip:
  849. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  850. # Add to object
  851. if self.solid_geometry is None:
  852. self.solid_geometry = []
  853. if type(self.solid_geometry) is list:
  854. if type(geos) is list:
  855. self.solid_geometry += geos
  856. else:
  857. self.solid_geometry.append(geos)
  858. else: # It's shapely geometry
  859. self.solid_geometry = [self.solid_geometry, geos]
  860. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  861. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  862. geos_text = getsvgtext(svg_root, object_type, units=units)
  863. if geos_text is not None:
  864. geos_text_f = []
  865. if flip:
  866. # Change origin to bottom left
  867. for i in geos_text:
  868. _, minimy, _, maximy = i.bounds
  869. h2 = (maximy - minimy) * 0.5
  870. geos_text_f.append(translate(scale(i, 1.0, -1.0, origin=(0, 0)), yoff=(h + h2)))
  871. if geos_text_f:
  872. self.solid_geometry = self.solid_geometry + geos_text_f
  873. def import_dxf(self, filename, object_type=None, units='MM'):
  874. """
  875. Imports shapes from an DXF file into the object's geometry.
  876. :param filename: Path to the DXF file.
  877. :type filename: str
  878. :param object_type:
  879. :param units: Application units
  880. :return: None
  881. """
  882. # Parse into list of shapely objects
  883. dxf = ezdxf.readfile(filename)
  884. geos = getdxfgeo(dxf)
  885. # Add to object
  886. if self.solid_geometry is None:
  887. self.solid_geometry = []
  888. if type(self.solid_geometry) is list:
  889. if type(geos) is list:
  890. self.solid_geometry += geos
  891. else:
  892. self.solid_geometry.append(geos)
  893. else: # It's shapely geometry
  894. self.solid_geometry = [self.solid_geometry, geos]
  895. # flatten the self.solid_geometry list for import_dxf() to import DXF as Gerber
  896. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  897. if self.solid_geometry is not None:
  898. self.solid_geometry = cascaded_union(self.solid_geometry)
  899. else:
  900. return
  901. # commented until this function is ready
  902. # geos_text = getdxftext(dxf, object_type, units=units)
  903. # if geos_text is not None:
  904. # geos_text_f = []
  905. # self.solid_geometry = [self.solid_geometry, geos_text_f]
  906. def import_image(self, filename, flip=True, units='MM', dpi=96, mode='black', mask=None):
  907. """
  908. Imports shapes from an IMAGE file into the object's geometry.
  909. :param filename: Path to the IMAGE file.
  910. :type filename: str
  911. :param flip: Flip the object vertically.
  912. :type flip: bool
  913. :param units: FlatCAM units
  914. :type units: str
  915. :param dpi: dots per inch on the imported image
  916. :param mode: how to import the image: as 'black' or 'color'
  917. :type mode: str
  918. :param mask: level of detail for the import
  919. :return: None
  920. """
  921. if mask is None:
  922. mask = [128, 128, 128, 128]
  923. scale_factor = 25.4 / dpi if units.lower() == 'mm' else 1 / dpi
  924. geos = []
  925. unscaled_geos = []
  926. with rasterio.open(filename) as src:
  927. # if filename.lower().rpartition('.')[-1] == 'bmp':
  928. # red = green = blue = src.read(1)
  929. # print("BMP")
  930. # elif filename.lower().rpartition('.')[-1] == 'png':
  931. # red, green, blue, alpha = src.read()
  932. # elif filename.lower().rpartition('.')[-1] == 'jpg':
  933. # red, green, blue = src.read()
  934. red = green = blue = src.read(1)
  935. try:
  936. green = src.read(2)
  937. except Exception:
  938. pass
  939. try:
  940. blue = src.read(3)
  941. except Exception:
  942. pass
  943. if mode == 'black':
  944. mask_setting = red <= mask[0]
  945. total = red
  946. log.debug("Image import as monochrome.")
  947. else:
  948. mask_setting = (red <= mask[1]) + (green <= mask[2]) + (blue <= mask[3])
  949. total = np.zeros(red.shape, dtype=np.float32)
  950. for band in red, green, blue:
  951. total += band
  952. total /= 3
  953. log.debug("Image import as colored. Thresholds are: R = %s , G = %s, B = %s" %
  954. (str(mask[1]), str(mask[2]), str(mask[3])))
  955. for geom, val in shapes(total, mask=mask_setting):
  956. unscaled_geos.append(shape(geom))
  957. for g in unscaled_geos:
  958. geos.append(scale(g, scale_factor, scale_factor, origin=(0, 0)))
  959. if flip:
  960. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0))) for g in geos]
  961. # Add to object
  962. if self.solid_geometry is None:
  963. self.solid_geometry = []
  964. if type(self.solid_geometry) is list:
  965. # self.solid_geometry.append(cascaded_union(geos))
  966. if type(geos) is list:
  967. self.solid_geometry += geos
  968. else:
  969. self.solid_geometry.append(geos)
  970. else: # It's shapely geometry
  971. self.solid_geometry = [self.solid_geometry, geos]
  972. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  973. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  974. self.solid_geometry = cascaded_union(self.solid_geometry)
  975. # self.solid_geometry = MultiPolygon(self.solid_geometry)
  976. # self.solid_geometry = self.solid_geometry.buffer(0.00000001)
  977. # self.solid_geometry = self.solid_geometry.buffer(-0.00000001)
  978. def size(self):
  979. """
  980. Returns (width, height) of rectangular
  981. bounds of geometry.
  982. """
  983. if self.solid_geometry is None:
  984. log.warning("Solid_geometry not computed yet.")
  985. return 0
  986. bounds = self.bounds()
  987. return bounds[2] - bounds[0], bounds[3] - bounds[1]
  988. def get_empty_area(self, boundary=None):
  989. """
  990. Returns the complement of self.solid_geometry within
  991. the given boundary polygon. If not specified, it defaults to
  992. the rectangular bounding box of self.solid_geometry.
  993. """
  994. if boundary is None:
  995. boundary = self.solid_geometry.envelope
  996. return boundary.difference(self.solid_geometry)
  997. def clear_polygon(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  998. prog_plot=False):
  999. """
  1000. Creates geometry inside a polygon for a tool to cover
  1001. the whole area.
  1002. This algorithm shrinks the edges of the polygon and takes
  1003. the resulting edges as toolpaths.
  1004. :param polygon: Polygon to clear.
  1005. :param tooldia: Diameter of the tool.
  1006. :param steps_per_circle: number of linear segments to be used to approximate a circle
  1007. :param overlap: Overlap of toolpasses.
  1008. :param connect: Draw lines between disjoint segments to
  1009. minimize tool lifts.
  1010. :param contour: Paint around the edges. Inconsequential in
  1011. this painting method.
  1012. :param prog_plot: boolean; if Ture use the progressive plotting
  1013. :return:
  1014. """
  1015. # log.debug("camlib.clear_polygon()")
  1016. assert type(polygon) == Polygon or type(polygon) == MultiPolygon, \
  1017. "Expected a Polygon or MultiPolygon, got %s" % type(polygon)
  1018. # ## The toolpaths
  1019. # Index first and last points in paths
  1020. def get_pts(o):
  1021. return [o.coords[0], o.coords[-1]]
  1022. geoms = FlatCAMRTreeStorage()
  1023. geoms.get_points = get_pts
  1024. # Can only result in a Polygon or MultiPolygon
  1025. # NOTE: The resulting polygon can be "empty".
  1026. current = polygon.buffer((-tooldia / 1.999999), int(steps_per_circle))
  1027. if current.area == 0:
  1028. # Otherwise, trying to to insert current.exterior == None
  1029. # into the FlatCAMStorage will fail.
  1030. # print("Area is None")
  1031. return None
  1032. # current can be a MultiPolygon
  1033. try:
  1034. for p in current:
  1035. geoms.insert(p.exterior)
  1036. for i in p.interiors:
  1037. geoms.insert(i)
  1038. # Not a Multipolygon. Must be a Polygon
  1039. except TypeError:
  1040. geoms.insert(current.exterior)
  1041. for i in current.interiors:
  1042. geoms.insert(i)
  1043. while True:
  1044. if self.app.abort_flag:
  1045. # graceful abort requested by the user
  1046. raise grace
  1047. # provide the app with a way to process the GUI events when in a blocking loop
  1048. QtWidgets.QApplication.processEvents()
  1049. # Can only result in a Polygon or MultiPolygon
  1050. current = current.buffer(-tooldia * (1 - overlap), int(steps_per_circle))
  1051. if current.area > 0:
  1052. # current can be a MultiPolygon
  1053. try:
  1054. for p in current:
  1055. geoms.insert(p.exterior)
  1056. for i in p.interiors:
  1057. geoms.insert(i)
  1058. if prog_plot:
  1059. self.plot_temp_shapes(p)
  1060. # Not a Multipolygon. Must be a Polygon
  1061. except TypeError:
  1062. geoms.insert(current.exterior)
  1063. if prog_plot:
  1064. self.plot_temp_shapes(current.exterior)
  1065. for i in current.interiors:
  1066. geoms.insert(i)
  1067. if prog_plot:
  1068. self.plot_temp_shapes(i)
  1069. else:
  1070. log.debug("camlib.Geometry.clear_polygon() --> Current Area is zero")
  1071. break
  1072. if prog_plot:
  1073. self.temp_shapes.redraw()
  1074. # Optimization: Reduce lifts
  1075. if connect:
  1076. # log.debug("Reducing tool lifts...")
  1077. geoms = Geometry.paint_connect(geoms, polygon, tooldia, int(steps_per_circle))
  1078. return geoms
  1079. def clear_polygon2(self, polygon_to_clear, tooldia, steps_per_circle, seedpoint=None, overlap=0.15,
  1080. connect=True, contour=True, prog_plot=False):
  1081. """
  1082. Creates geometry inside a polygon for a tool to cover
  1083. the whole area.
  1084. This algorithm starts with a seed point inside the polygon
  1085. and draws circles around it. Arcs inside the polygons are
  1086. valid cuts. Finalizes by cutting around the inside edge of
  1087. the polygon.
  1088. :param polygon_to_clear: Shapely.geometry.Polygon
  1089. :param steps_per_circle: how many linear segments to use to approximate a circle
  1090. :param tooldia: Diameter of the tool
  1091. :param seedpoint: Shapely.geometry.Point or None
  1092. :param overlap: Tool fraction overlap bewteen passes
  1093. :param connect: Connect disjoint segment to minumize tool lifts
  1094. :param contour: Cut countour inside the polygon.
  1095. :param prog_plot: boolean; if True use the progressive plotting
  1096. :return: List of toolpaths covering polygon.
  1097. :rtype: FlatCAMRTreeStorage | None
  1098. """
  1099. # log.debug("camlib.clear_polygon2()")
  1100. # Current buffer radius
  1101. radius = tooldia / 2 * (1 - overlap)
  1102. # ## The toolpaths
  1103. # Index first and last points in paths
  1104. def get_pts(o):
  1105. return [o.coords[0], o.coords[-1]]
  1106. geoms = FlatCAMRTreeStorage()
  1107. geoms.get_points = get_pts
  1108. # Path margin
  1109. path_margin = polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle))
  1110. if path_margin.is_empty or path_margin is None:
  1111. return None
  1112. # Estimate good seedpoint if not provided.
  1113. if seedpoint is None:
  1114. seedpoint = path_margin.representative_point()
  1115. # Grow from seed until outside the box. The polygons will
  1116. # never have an interior, so take the exterior LinearRing.
  1117. while True:
  1118. if self.app.abort_flag:
  1119. # graceful abort requested by the user
  1120. raise grace
  1121. # provide the app with a way to process the GUI events when in a blocking loop
  1122. QtWidgets.QApplication.processEvents()
  1123. path = Point(seedpoint).buffer(radius, int(steps_per_circle)).exterior
  1124. path = path.intersection(path_margin)
  1125. # Touches polygon?
  1126. if path.is_empty:
  1127. break
  1128. else:
  1129. # geoms.append(path)
  1130. # geoms.insert(path)
  1131. # path can be a collection of paths.
  1132. try:
  1133. for p in path:
  1134. geoms.insert(p)
  1135. if prog_plot:
  1136. self.plot_temp_shapes(p)
  1137. except TypeError:
  1138. geoms.insert(path)
  1139. if prog_plot:
  1140. self.plot_temp_shapes(path)
  1141. if prog_plot:
  1142. self.temp_shapes.redraw()
  1143. radius += tooldia * (1 - overlap)
  1144. # Clean inside edges (contours) of the original polygon
  1145. if contour:
  1146. buffered_poly = autolist(polygon_to_clear.buffer(-tooldia / 2, int(steps_per_circle)))
  1147. outer_edges = [x.exterior for x in buffered_poly]
  1148. inner_edges = []
  1149. # Over resulting polygons
  1150. for x in buffered_poly:
  1151. for y in x.interiors: # Over interiors of each polygon
  1152. inner_edges.append(y)
  1153. # geoms += outer_edges + inner_edges
  1154. for g in outer_edges + inner_edges:
  1155. if g and not g.is_empty:
  1156. geoms.insert(g)
  1157. if prog_plot:
  1158. self.plot_temp_shapes(g)
  1159. if prog_plot:
  1160. self.temp_shapes.redraw()
  1161. # Optimization connect touching paths
  1162. # log.debug("Connecting paths...")
  1163. # geoms = Geometry.path_connect(geoms)
  1164. # Optimization: Reduce lifts
  1165. if connect:
  1166. # log.debug("Reducing tool lifts...")
  1167. geoms_conn = Geometry.paint_connect(geoms, polygon_to_clear, tooldia, steps_per_circle)
  1168. if geoms_conn:
  1169. return geoms_conn
  1170. return geoms
  1171. def clear_polygon3(self, polygon, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1172. prog_plot=False):
  1173. """
  1174. Creates geometry inside a polygon for a tool to cover
  1175. the whole area.
  1176. This algorithm draws horizontal lines inside the polygon.
  1177. :param polygon: The polygon being painted.
  1178. :type polygon: shapely.geometry.Polygon
  1179. :param tooldia: Tool diameter.
  1180. :param steps_per_circle: how many linear segments to use to approximate a circle
  1181. :param overlap: Tool path overlap percentage.
  1182. :param connect: Connect lines to avoid tool lifts.
  1183. :param contour: Paint around the edges.
  1184. :param prog_plot: boolean; if to use the progressive plotting
  1185. :return:
  1186. """
  1187. # log.debug("camlib.clear_polygon3()")
  1188. if not isinstance(polygon, Polygon):
  1189. log.debug("camlib.Geometry.clear_polygon3() --> Not a Polygon but %s" % str(type(polygon)))
  1190. return None
  1191. # ## The toolpaths
  1192. # Index first and last points in paths
  1193. def get_pts(o):
  1194. return [o.coords[0], o.coords[-1]]
  1195. geoms = FlatCAMRTreeStorage()
  1196. geoms.get_points = get_pts
  1197. lines_trimmed = []
  1198. # Bounding box
  1199. left, bot, right, top = polygon.bounds
  1200. try:
  1201. margin_poly = polygon.buffer(-tooldia / 1.99999999, (int(steps_per_circle)))
  1202. except Exception:
  1203. log.debug("camlib.Geometry.clear_polygon3() --> Could not buffer the Polygon")
  1204. return None
  1205. # decide the direction of the lines
  1206. if abs(left - right) >= abs(top - bot):
  1207. # First line
  1208. try:
  1209. y = top - tooldia / 1.99999999
  1210. while y > bot + tooldia / 1.999999999:
  1211. if self.app.abort_flag:
  1212. # graceful abort requested by the user
  1213. raise grace
  1214. # provide the app with a way to process the GUI events when in a blocking loop
  1215. QtWidgets.QApplication.processEvents()
  1216. line = LineString([(left, y), (right, y)])
  1217. line = line.intersection(margin_poly)
  1218. lines_trimmed.append(line)
  1219. y -= tooldia * (1 - overlap)
  1220. if prog_plot:
  1221. self.plot_temp_shapes(line)
  1222. self.temp_shapes.redraw()
  1223. # Last line
  1224. y = bot + tooldia / 2
  1225. line = LineString([(left, y), (right, y)])
  1226. line = line.intersection(margin_poly)
  1227. try:
  1228. for ll in line:
  1229. lines_trimmed.append(ll)
  1230. if prog_plot:
  1231. self.plot_temp_shapes(ll)
  1232. except TypeError:
  1233. lines_trimmed.append(line)
  1234. if prog_plot:
  1235. self.plot_temp_shapes(line)
  1236. except Exception as e:
  1237. log.debug('camlib.Geometry.clear_polygon3() Processing poly --> %s' % str(e))
  1238. return None
  1239. else:
  1240. # First line
  1241. try:
  1242. x = left + tooldia / 1.99999999
  1243. while x < right - tooldia / 1.999999999:
  1244. if self.app.abort_flag:
  1245. # graceful abort requested by the user
  1246. raise grace
  1247. # provide the app with a way to process the GUI events when in a blocking loop
  1248. QtWidgets.QApplication.processEvents()
  1249. line = LineString([(x, top), (x, bot)])
  1250. line = line.intersection(margin_poly)
  1251. lines_trimmed.append(line)
  1252. x += tooldia * (1 - overlap)
  1253. if prog_plot:
  1254. self.plot_temp_shapes(line)
  1255. self.temp_shapes.redraw()
  1256. # Last line
  1257. x = right + tooldia / 2
  1258. line = LineString([(x, top), (x, bot)])
  1259. line = line.intersection(margin_poly)
  1260. try:
  1261. for ll in line:
  1262. lines_trimmed.append(ll)
  1263. if prog_plot:
  1264. self.plot_temp_shapes(ll)
  1265. except TypeError:
  1266. lines_trimmed.append(line)
  1267. if prog_plot:
  1268. self.plot_temp_shapes(line)
  1269. except Exception as e:
  1270. log.debug('camlib.Geometry.clear_polygon3() Processing poly --> %s' % str(e))
  1271. return None
  1272. if prog_plot:
  1273. self.temp_shapes.redraw()
  1274. lines_trimmed = unary_union(lines_trimmed)
  1275. # Add lines to storage
  1276. try:
  1277. for line in lines_trimmed:
  1278. if isinstance(line, LineString) or isinstance(line, LinearRing):
  1279. if not line.is_empty:
  1280. geoms.insert(line)
  1281. else:
  1282. log.debug("camlib.Geometry.clear_polygon3(). Not a line: %s" % str(type(line)))
  1283. except TypeError:
  1284. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1285. if not lines_trimmed.is_empty:
  1286. geoms.insert(lines_trimmed)
  1287. # Add margin (contour) to storage
  1288. if contour:
  1289. try:
  1290. for poly in margin_poly:
  1291. if isinstance(poly, Polygon) and not poly.is_empty:
  1292. geoms.insert(poly.exterior)
  1293. if prog_plot:
  1294. self.plot_temp_shapes(poly.exterior)
  1295. for ints in poly.interiors:
  1296. geoms.insert(ints)
  1297. if prog_plot:
  1298. self.plot_temp_shapes(ints)
  1299. except TypeError:
  1300. if isinstance(margin_poly, Polygon) and not margin_poly.is_empty:
  1301. marg_ext = margin_poly.exterior
  1302. geoms.insert(marg_ext)
  1303. if prog_plot:
  1304. self.plot_temp_shapes(margin_poly.exterior)
  1305. for ints in margin_poly.interiors:
  1306. geoms.insert(ints)
  1307. if prog_plot:
  1308. self.plot_temp_shapes(ints)
  1309. if prog_plot:
  1310. self.temp_shapes.redraw()
  1311. # Optimization: Reduce lifts
  1312. if connect:
  1313. # log.debug("Reducing tool lifts...")
  1314. geoms_conn = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1315. if geoms_conn:
  1316. return geoms_conn
  1317. return geoms
  1318. def fill_with_lines(self, line, aperture_size, tooldia, steps_per_circle, overlap=0.15, connect=True, contour=True,
  1319. prog_plot=False):
  1320. """
  1321. Creates geometry of lines inside a polygon for a tool to cover
  1322. the whole area.
  1323. This algorithm draws parallel lines inside the polygon.
  1324. :param line: The target line that create painted polygon.
  1325. :param aperture_size: the size of the aperture that is used to draw the 'line' as a polygon
  1326. :type line: shapely.geometry.LineString or shapely.geometry.MultiLineString
  1327. :param tooldia: Tool diameter.
  1328. :param steps_per_circle: how many linear segments to use to approximate a circle
  1329. :param overlap: Tool path overlap percentage.
  1330. :param connect: Connect lines to avoid tool lifts.
  1331. :param contour: Paint around the edges.
  1332. :param prog_plot: boolean; if to use the progressive plotting
  1333. :return:
  1334. """
  1335. # log.debug("camlib.fill_with_lines()")
  1336. if not isinstance(line, LineString):
  1337. log.debug("camlib.Geometry.fill_with_lines() --> Not a LineString/MultiLineString but %s" % str(type(line)))
  1338. return None
  1339. # ## The toolpaths
  1340. # Index first and last points in paths
  1341. def get_pts(o):
  1342. return [o.coords[0], o.coords[-1]]
  1343. geoms = FlatCAMRTreeStorage()
  1344. geoms.get_points = get_pts
  1345. lines_trimmed = []
  1346. polygon = line.buffer(aperture_size / 2.0, int(steps_per_circle))
  1347. try:
  1348. margin_poly = polygon.buffer(-tooldia / 2.0, int(steps_per_circle))
  1349. except Exception:
  1350. log.debug("camlib.Geometry.fill_with_lines() --> Could not buffer the Polygon, tool diameter too high")
  1351. return None
  1352. # First line
  1353. try:
  1354. delta = 0
  1355. while delta < aperture_size / 2:
  1356. if self.app.abort_flag:
  1357. # graceful abort requested by the user
  1358. raise grace
  1359. # provide the app with a way to process the GUI events when in a blocking loop
  1360. QtWidgets.QApplication.processEvents()
  1361. new_line = line.parallel_offset(distance=delta, side='left', resolution=int(steps_per_circle))
  1362. new_line = new_line.intersection(margin_poly)
  1363. lines_trimmed.append(new_line)
  1364. new_line = line.parallel_offset(distance=delta, side='right', resolution=int(steps_per_circle))
  1365. new_line = new_line.intersection(margin_poly)
  1366. lines_trimmed.append(new_line)
  1367. delta += tooldia * (1 - overlap)
  1368. if prog_plot:
  1369. self.plot_temp_shapes(new_line)
  1370. self.temp_shapes.redraw()
  1371. # Last line
  1372. delta = (aperture_size / 2) - (tooldia / 2.00000001)
  1373. new_line = line.parallel_offset(distance=delta, side='left', resolution=int(steps_per_circle))
  1374. new_line = new_line.intersection(margin_poly)
  1375. except Exception as e:
  1376. log.debug('camlib.Geometry.fill_with_lines() Processing poly --> %s' % str(e))
  1377. return None
  1378. try:
  1379. for ll in new_line:
  1380. lines_trimmed.append(ll)
  1381. if prog_plot:
  1382. self.plot_temp_shapes(ll)
  1383. except TypeError:
  1384. lines_trimmed.append(new_line)
  1385. if prog_plot:
  1386. self.plot_temp_shapes(new_line)
  1387. new_line = line.parallel_offset(distance=delta, side='right', resolution=int(steps_per_circle))
  1388. new_line = new_line.intersection(margin_poly)
  1389. try:
  1390. for ll in new_line:
  1391. lines_trimmed.append(ll)
  1392. if prog_plot:
  1393. self.plot_temp_shapes(ll)
  1394. except TypeError:
  1395. lines_trimmed.append(new_line)
  1396. if prog_plot:
  1397. self.plot_temp_shapes(new_line)
  1398. if prog_plot:
  1399. self.temp_shapes.redraw()
  1400. lines_trimmed = unary_union(lines_trimmed)
  1401. # Add lines to storage
  1402. try:
  1403. for line in lines_trimmed:
  1404. if isinstance(line, LineString) or isinstance(line, LinearRing):
  1405. geoms.insert(line)
  1406. else:
  1407. log.debug("camlib.Geometry.fill_with_lines(). Not a line: %s" % str(type(line)))
  1408. except TypeError:
  1409. # in case lines_trimmed are not iterable (Linestring, LinearRing)
  1410. geoms.insert(lines_trimmed)
  1411. # Add margin (contour) to storage
  1412. if contour:
  1413. try:
  1414. for poly in margin_poly:
  1415. if isinstance(poly, Polygon) and not poly.is_empty:
  1416. geoms.insert(poly.exterior)
  1417. if prog_plot:
  1418. self.plot_temp_shapes(poly.exterior)
  1419. for ints in poly.interiors:
  1420. geoms.insert(ints)
  1421. if prog_plot:
  1422. self.plot_temp_shapes(ints)
  1423. except TypeError:
  1424. if isinstance(margin_poly, Polygon) and not margin_poly.is_empty:
  1425. marg_ext = margin_poly.exterior
  1426. geoms.insert(marg_ext)
  1427. if prog_plot:
  1428. self.plot_temp_shapes(margin_poly.exterior)
  1429. for ints in margin_poly.interiors:
  1430. geoms.insert(ints)
  1431. if prog_plot:
  1432. self.plot_temp_shapes(ints)
  1433. if prog_plot:
  1434. self.temp_shapes.redraw()
  1435. # Optimization: Reduce lifts
  1436. if connect:
  1437. # log.debug("Reducing tool lifts...")
  1438. geoms_conn = Geometry.paint_connect(geoms, polygon, tooldia, steps_per_circle)
  1439. if geoms_conn:
  1440. return geoms_conn
  1441. return geoms
  1442. def scale(self, xfactor, yfactor, point=None):
  1443. """
  1444. Scales all of the object's geometry by a given factor. Override
  1445. this method.
  1446. :param xfactor: Number by which to scale on X axis.
  1447. :type xfactor: float
  1448. :param yfactor: Number by which to scale on Y axis.
  1449. :type yfactor: float
  1450. :param point: point to be used as reference for scaling; a tuple
  1451. :return: None
  1452. :rtype: None
  1453. """
  1454. return
  1455. def offset(self, vect):
  1456. """
  1457. Offset the geometry by the given vector. Override this method.
  1458. :param vect: (x, y) vector by which to offset the object.
  1459. :type vect: tuple
  1460. :return: None
  1461. """
  1462. return
  1463. @staticmethod
  1464. def paint_connect(storage, boundary, tooldia, steps_per_circle, max_walk=None):
  1465. """
  1466. Connects paths that results in a connection segment that is
  1467. within the paint area. This avoids unnecessary tool lifting.
  1468. :param storage: Geometry to be optimized.
  1469. :type storage: FlatCAMRTreeStorage
  1470. :param boundary: Polygon defining the limits of the paintable area.
  1471. :type boundary: Polygon
  1472. :param tooldia: Tool diameter.
  1473. :rtype tooldia: float
  1474. :param steps_per_circle: how many linear segments to use to approximate a circle
  1475. :param max_walk: Maximum allowable distance without lifting tool.
  1476. :type max_walk: float or None
  1477. :return: Optimized geometry.
  1478. :rtype: FlatCAMRTreeStorage
  1479. """
  1480. # If max_walk is not specified, the maximum allowed is
  1481. # 10 times the tool diameter
  1482. max_walk = max_walk or 10 * tooldia
  1483. # Assuming geolist is a flat list of flat elements
  1484. # ## Index first and last points in paths
  1485. def get_pts(o):
  1486. return [o.coords[0], o.coords[-1]]
  1487. # storage = FlatCAMRTreeStorage()
  1488. # storage.get_points = get_pts
  1489. #
  1490. # for shape in geolist:
  1491. # if shape is not None:
  1492. # # Make LlinearRings into linestrings otherwise
  1493. # # When chaining the coordinates path is messed up.
  1494. # storage.insert(LineString(shape))
  1495. # #storage.insert(shape)
  1496. # ## Iterate over geometry paths getting the nearest each time.
  1497. # optimized_paths = []
  1498. optimized_paths = FlatCAMRTreeStorage()
  1499. optimized_paths.get_points = get_pts
  1500. path_count = 0
  1501. current_pt = (0, 0)
  1502. try:
  1503. pt, geo = storage.nearest(current_pt)
  1504. except StopIteration:
  1505. log.debug("camlib.Geometry.paint_connect(). Storage empty")
  1506. return None
  1507. storage.remove(geo)
  1508. geo = LineString(geo)
  1509. current_pt = geo.coords[-1]
  1510. try:
  1511. while True:
  1512. path_count += 1
  1513. # log.debug("Path %d" % path_count)
  1514. pt, candidate = storage.nearest(current_pt)
  1515. storage.remove(candidate)
  1516. candidate = LineString(candidate)
  1517. # If last point in geometry is the nearest
  1518. # then reverse coordinates.
  1519. # but prefer the first one if last == first
  1520. if pt != candidate.coords[0] and pt == candidate.coords[-1]:
  1521. candidate.coords = list(candidate.coords)[::-1]
  1522. # Straight line from current_pt to pt.
  1523. # Is the toolpath inside the geometry?
  1524. walk_path = LineString([current_pt, pt])
  1525. walk_cut = walk_path.buffer(tooldia / 2, int(steps_per_circle))
  1526. if walk_cut.within(boundary) and walk_path.length < max_walk:
  1527. # log.debug("Walk to path #%d is inside. Joining." % path_count)
  1528. # Completely inside. Append...
  1529. geo.coords = list(geo.coords) + list(candidate.coords)
  1530. # try:
  1531. # last = optimized_paths[-1]
  1532. # last.coords = list(last.coords) + list(geo.coords)
  1533. # except IndexError:
  1534. # optimized_paths.append(geo)
  1535. else:
  1536. # Have to lift tool. End path.
  1537. # log.debug("Path #%d not within boundary. Next." % path_count)
  1538. # optimized_paths.append(geo)
  1539. optimized_paths.insert(geo)
  1540. geo = candidate
  1541. current_pt = geo.coords[-1]
  1542. # Next
  1543. # pt, geo = storage.nearest(current_pt)
  1544. except StopIteration: # Nothing left in storage.
  1545. # pass
  1546. optimized_paths.insert(geo)
  1547. return optimized_paths
  1548. @staticmethod
  1549. def path_connect(storage, origin=(0, 0)):
  1550. """
  1551. Simplifies paths in the FlatCAMRTreeStorage storage by
  1552. connecting paths that touch on their endpoints.
  1553. :param storage: Storage containing the initial paths.
  1554. :rtype storage: FlatCAMRTreeStorage
  1555. :param origin: tuple; point from which to calculate the nearest point
  1556. :return: Simplified storage.
  1557. :rtype: FlatCAMRTreeStorage
  1558. """
  1559. log.debug("path_connect()")
  1560. # ## Index first and last points in paths
  1561. def get_pts(o):
  1562. return [o.coords[0], o.coords[-1]]
  1563. #
  1564. # storage = FlatCAMRTreeStorage()
  1565. # storage.get_points = get_pts
  1566. #
  1567. # for shape in pathlist:
  1568. # if shape is not None:
  1569. # storage.insert(shape)
  1570. path_count = 0
  1571. pt, geo = storage.nearest(origin)
  1572. storage.remove(geo)
  1573. # optimized_geometry = [geo]
  1574. optimized_geometry = FlatCAMRTreeStorage()
  1575. optimized_geometry.get_points = get_pts
  1576. # optimized_geometry.insert(geo)
  1577. try:
  1578. while True:
  1579. path_count += 1
  1580. _, left = storage.nearest(geo.coords[0])
  1581. # If left touches geo, remove left from original
  1582. # storage and append to geo.
  1583. if type(left) == LineString:
  1584. if left.coords[0] == geo.coords[0]:
  1585. storage.remove(left)
  1586. geo.coords = list(geo.coords)[::-1] + list(left.coords)
  1587. continue
  1588. if left.coords[-1] == geo.coords[0]:
  1589. storage.remove(left)
  1590. geo.coords = list(left.coords) + list(geo.coords)
  1591. continue
  1592. if left.coords[0] == geo.coords[-1]:
  1593. storage.remove(left)
  1594. geo.coords = list(geo.coords) + list(left.coords)
  1595. continue
  1596. if left.coords[-1] == geo.coords[-1]:
  1597. storage.remove(left)
  1598. geo.coords = list(geo.coords) + list(left.coords)[::-1]
  1599. continue
  1600. _, right = storage.nearest(geo.coords[-1])
  1601. # If right touches geo, remove left from original
  1602. # storage and append to geo.
  1603. if type(right) == LineString:
  1604. if right.coords[0] == geo.coords[-1]:
  1605. storage.remove(right)
  1606. geo.coords = list(geo.coords) + list(right.coords)
  1607. continue
  1608. if right.coords[-1] == geo.coords[-1]:
  1609. storage.remove(right)
  1610. geo.coords = list(geo.coords) + list(right.coords)[::-1]
  1611. continue
  1612. if right.coords[0] == geo.coords[0]:
  1613. storage.remove(right)
  1614. geo.coords = list(geo.coords)[::-1] + list(right.coords)
  1615. continue
  1616. if right.coords[-1] == geo.coords[0]:
  1617. storage.remove(right)
  1618. geo.coords = list(left.coords) + list(geo.coords)
  1619. continue
  1620. # right is either a LinearRing or it does not connect
  1621. # to geo (nothing left to connect to geo), so we continue
  1622. # with right as geo.
  1623. storage.remove(right)
  1624. if type(right) == LinearRing:
  1625. optimized_geometry.insert(right)
  1626. else:
  1627. # Cannot extend geo any further. Put it away.
  1628. optimized_geometry.insert(geo)
  1629. # Continue with right.
  1630. geo = right
  1631. except StopIteration: # Nothing found in storage.
  1632. optimized_geometry.insert(geo)
  1633. # print path_count
  1634. log.debug("path_count = %d" % path_count)
  1635. return optimized_geometry
  1636. def convert_units(self, obj_units):
  1637. """
  1638. Converts the units of the object to ``units`` by scaling all
  1639. the geometry appropriately. This call ``scale()``. Don't call
  1640. it again in descendents.
  1641. :param obj_units: "IN" or "MM"
  1642. :type obj_units: str
  1643. :return: Scaling factor resulting from unit change.
  1644. :rtype: float
  1645. """
  1646. if obj_units.upper() == self.units.upper():
  1647. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1648. return 1.0
  1649. if obj_units.upper() == "MM":
  1650. factor = 25.4
  1651. log.debug("camlib.Geometry.convert_units() --> Factor: 25.4")
  1652. elif obj_units.upper() == "IN":
  1653. factor = 1 / 25.4
  1654. log.debug("camlib.Geometry.convert_units() --> Factor: %s" % str(1 / 25.4))
  1655. else:
  1656. log.error("Unsupported units: %s" % str(obj_units))
  1657. log.debug("camlib.Geometry.convert_units() --> Factor: 1")
  1658. return 1.0
  1659. self.units = obj_units
  1660. self.scale(factor, factor)
  1661. self.file_units_factor = factor
  1662. return factor
  1663. def to_dict(self):
  1664. """
  1665. Returns a representation of the object as a dictionary.
  1666. Attributes to include are listed in ``self.ser_attrs``.
  1667. :return: A dictionary-encoded copy of the object.
  1668. :rtype: dict
  1669. """
  1670. d = {}
  1671. for attr in self.ser_attrs:
  1672. d[attr] = getattr(self, attr)
  1673. return d
  1674. def from_dict(self, d):
  1675. """
  1676. Sets object's attributes from a dictionary.
  1677. Attributes to include are listed in ``self.ser_attrs``.
  1678. This method will look only for only and all the
  1679. attributes in ``self.ser_attrs``. They must all
  1680. be present. Use only for deserializing saved
  1681. objects.
  1682. :param d: Dictionary of attributes to set in the object.
  1683. :type d: dict
  1684. :return: None
  1685. """
  1686. for attr in self.ser_attrs:
  1687. setattr(self, attr, d[attr])
  1688. def union(self):
  1689. """
  1690. Runs a cascaded union on the list of objects in
  1691. solid_geometry.
  1692. :return: None
  1693. """
  1694. self.solid_geometry = [cascaded_union(self.solid_geometry)]
  1695. def export_svg(self, scale_stroke_factor=0.00,
  1696. scale_factor_x=None, scale_factor_y=None,
  1697. skew_factor_x=None, skew_factor_y=None,
  1698. skew_reference='center',
  1699. mirror=None):
  1700. """
  1701. Exports the Geometry Object as a SVG Element
  1702. :return: SVG Element
  1703. """
  1704. # Make sure we see a Shapely Geometry class and not a list
  1705. if self.kind.lower() == 'geometry':
  1706. flat_geo = []
  1707. if self.multigeo:
  1708. for tool in self.tools:
  1709. flat_geo += self.flatten(self.tools[tool]['solid_geometry'])
  1710. geom_svg = cascaded_union(flat_geo)
  1711. else:
  1712. geom_svg = cascaded_union(self.flatten())
  1713. else:
  1714. geom_svg = cascaded_union(self.flatten())
  1715. skew_ref = 'center'
  1716. if skew_reference != 'center':
  1717. xmin, ymin, xmax, ymax = geom_svg.bounds
  1718. if skew_reference == 'topleft':
  1719. skew_ref = (xmin, ymax)
  1720. elif skew_reference == 'bottomleft':
  1721. skew_ref = (xmin, ymin)
  1722. elif skew_reference == 'topright':
  1723. skew_ref = (xmax, ymax)
  1724. elif skew_reference == 'bottomright':
  1725. skew_ref = (xmax, ymin)
  1726. geom = geom_svg
  1727. if scale_factor_x:
  1728. geom = affinity.scale(geom_svg, scale_factor_x, 1.0)
  1729. if scale_factor_y:
  1730. geom = affinity.scale(geom_svg, 1.0, scale_factor_y)
  1731. if skew_factor_x:
  1732. geom = affinity.skew(geom_svg, skew_factor_x, 0.0, origin=skew_ref)
  1733. if skew_factor_y:
  1734. geom = affinity.skew(geom_svg, 0.0, skew_factor_y, origin=skew_ref)
  1735. if mirror:
  1736. if mirror == 'x':
  1737. geom = affinity.scale(geom_svg, 1.0, -1.0)
  1738. if mirror == 'y':
  1739. geom = affinity.scale(geom_svg, -1.0, 1.0)
  1740. if mirror == 'both':
  1741. geom = affinity.scale(geom_svg, -1.0, -1.0)
  1742. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  1743. # If 0 or less which is invalid then default to 0.01
  1744. # This value appears to work for zooming, and getting the output svg line width
  1745. # to match that viewed on screen with FlatCam
  1746. # MS: I choose a factor of 0.01 so the scale is right for PCB UV film
  1747. if scale_stroke_factor <= 0:
  1748. scale_stroke_factor = 0.01
  1749. # Convert to a SVG
  1750. svg_elem = geom.svg(scale_factor=scale_stroke_factor)
  1751. return svg_elem
  1752. def mirror(self, axis, point):
  1753. """
  1754. Mirrors the object around a specified axis passign through
  1755. the given point.
  1756. :param axis: "X" or "Y" indicates around which axis to mirror.
  1757. :type axis: str
  1758. :param point: [x, y] point belonging to the mirror axis.
  1759. :type point: list
  1760. :return: None
  1761. """
  1762. log.debug("camlib.Geometry.mirror()")
  1763. px, py = point
  1764. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1765. def mirror_geom(obj):
  1766. if type(obj) is list:
  1767. new_obj = []
  1768. for g in obj:
  1769. new_obj.append(mirror_geom(g))
  1770. return new_obj
  1771. else:
  1772. try:
  1773. self.el_count += 1
  1774. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1775. if self.old_disp_number < disp_number <= 100:
  1776. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1777. self.old_disp_number = disp_number
  1778. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1779. except AttributeError:
  1780. return obj
  1781. try:
  1782. if self.multigeo is True:
  1783. for tool in self.tools:
  1784. # variables to display the percentage of work done
  1785. self.geo_len = 0
  1786. try:
  1787. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1788. except TypeError:
  1789. self.geo_len = 1
  1790. self.old_disp_number = 0
  1791. self.el_count = 0
  1792. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1793. else:
  1794. # variables to display the percentage of work done
  1795. self.geo_len = 0
  1796. try:
  1797. self.geo_len = len(self.solid_geometry)
  1798. except TypeError:
  1799. self.geo_len = 1
  1800. self.old_disp_number = 0
  1801. self.el_count = 0
  1802. self.solid_geometry = mirror_geom(self.solid_geometry)
  1803. self.app.inform.emit('[success] %s...' % _('Object was mirrored'))
  1804. except AttributeError:
  1805. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to mirror. No object selected"))
  1806. self.app.proc_container.new_text = ''
  1807. def rotate(self, angle, point):
  1808. """
  1809. Rotate an object by an angle (in degrees) around the provided coordinates.
  1810. :param angle:
  1811. The angle of rotation are specified in degrees (default). Positive angles are
  1812. counter-clockwise and negative are clockwise rotations.
  1813. :param point:
  1814. The point of origin can be a keyword 'center' for the bounding box
  1815. center (default), 'centroid' for the geometry's centroid, a Point object
  1816. or a coordinate tuple (x0, y0).
  1817. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  1818. """
  1819. log.debug("camlib.Geometry.rotate()")
  1820. px, py = point
  1821. def rotate_geom(obj):
  1822. try:
  1823. new_obj = []
  1824. for g in obj:
  1825. new_obj.append(rotate_geom(g))
  1826. return new_obj
  1827. except TypeError:
  1828. try:
  1829. self.el_count += 1
  1830. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1831. if self.old_disp_number < disp_number <= 100:
  1832. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1833. self.old_disp_number = disp_number
  1834. return affinity.rotate(obj, angle, origin=(px, py))
  1835. except AttributeError:
  1836. return obj
  1837. try:
  1838. if self.multigeo is True:
  1839. for tool in self.tools:
  1840. # variables to display the percentage of work done
  1841. self.geo_len = 0
  1842. try:
  1843. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1844. except TypeError:
  1845. self.geo_len = 1
  1846. self.old_disp_number = 0
  1847. self.el_count = 0
  1848. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1849. else:
  1850. # variables to display the percentage of work done
  1851. self.geo_len = 0
  1852. try:
  1853. self.geo_len = len(self.solid_geometry)
  1854. except TypeError:
  1855. self.geo_len = 1
  1856. self.old_disp_number = 0
  1857. self.el_count = 0
  1858. self.solid_geometry = rotate_geom(self.solid_geometry)
  1859. self.app.inform.emit('[success] %s...' % _('Object was rotated'))
  1860. except AttributeError:
  1861. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to rotate. No object selected"))
  1862. self.app.proc_container.new_text = ''
  1863. def skew(self, angle_x, angle_y, point):
  1864. """
  1865. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1866. :param angle_x:
  1867. :param angle_y:
  1868. angle_x, angle_y : float, float
  1869. The shear angle(s) for the x and y axes respectively. These can be
  1870. specified in either degrees (default) or radians by setting
  1871. use_radians=True.
  1872. :param point: Origin point for Skew
  1873. point: tuple of coordinates (x,y)
  1874. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  1875. """
  1876. log.debug("camlib.Geometry.skew()")
  1877. px, py = point
  1878. def skew_geom(obj):
  1879. try:
  1880. new_obj = []
  1881. for g in obj:
  1882. new_obj.append(skew_geom(g))
  1883. return new_obj
  1884. except TypeError:
  1885. try:
  1886. self.el_count += 1
  1887. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1888. if self.old_disp_number < disp_number <= 100:
  1889. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1890. self.old_disp_number = disp_number
  1891. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1892. except AttributeError:
  1893. return obj
  1894. try:
  1895. if self.multigeo is True:
  1896. for tool in self.tools:
  1897. # variables to display the percentage of work done
  1898. self.geo_len = 0
  1899. try:
  1900. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1901. except TypeError:
  1902. self.geo_len = 1
  1903. self.old_disp_number = 0
  1904. self.el_count = 0
  1905. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1906. else:
  1907. # variables to display the percentage of work done
  1908. self.geo_len = 0
  1909. try:
  1910. self.geo_len = len(self.solid_geometry)
  1911. except TypeError:
  1912. self.geo_len = 1
  1913. self.old_disp_number = 0
  1914. self.el_count = 0
  1915. self.solid_geometry = skew_geom(self.solid_geometry)
  1916. self.app.inform.emit('[success] %s...' % _('Object was skewed'))
  1917. except AttributeError:
  1918. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to skew. No object selected"))
  1919. self.app.proc_container.new_text = ''
  1920. # if type(self.solid_geometry) == list:
  1921. # self.solid_geometry = [affinity.skew(g, angle_x, angle_y, origin=(px, py))
  1922. # for g in self.solid_geometry]
  1923. # else:
  1924. # self.solid_geometry = affinity.skew(self.solid_geometry, angle_x, angle_y,
  1925. # origin=(px, py))
  1926. def buffer(self, distance, join, factor):
  1927. """
  1928. :param distance: if 'factor' is True then distance is the factor
  1929. :param join: The kind of join used by the shapely buffer method: round, square or bevel
  1930. :param factor: True or False (None)
  1931. :return:
  1932. """
  1933. log.debug("camlib.Geometry.buffer()")
  1934. if distance == 0:
  1935. return
  1936. def buffer_geom(obj):
  1937. if type(obj) is list:
  1938. new_obj = []
  1939. for g in obj:
  1940. new_obj.append(buffer_geom(g))
  1941. return new_obj
  1942. else:
  1943. try:
  1944. self.el_count += 1
  1945. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1946. if self.old_disp_number < disp_number <= 100:
  1947. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1948. self.old_disp_number = disp_number
  1949. if factor is None:
  1950. return obj.buffer(distance, resolution=self.geo_steps_per_circle, join_style=join)
  1951. else:
  1952. return affinity.scale(obj, xfact=distance, yfact=distance, origin='center')
  1953. except AttributeError:
  1954. return obj
  1955. try:
  1956. if self.multigeo is True:
  1957. for tool in self.tools:
  1958. # variables to display the percentage of work done
  1959. self.geo_len = 0
  1960. try:
  1961. self.geo_len += len(self.tools[tool]['solid_geometry'])
  1962. except TypeError:
  1963. self.geo_len += 1
  1964. self.old_disp_number = 0
  1965. self.el_count = 0
  1966. res = buffer_geom(self.tools[tool]['solid_geometry'])
  1967. try:
  1968. __ = iter(res)
  1969. self.tools[tool]['solid_geometry'] = res
  1970. except TypeError:
  1971. self.tools[tool]['solid_geometry'] = [res]
  1972. # variables to display the percentage of work done
  1973. self.geo_len = 0
  1974. try:
  1975. self.geo_len = len(self.solid_geometry)
  1976. except TypeError:
  1977. self.geo_len = 1
  1978. self.old_disp_number = 0
  1979. self.el_count = 0
  1980. self.solid_geometry = buffer_geom(self.solid_geometry)
  1981. self.app.inform.emit('[success] %s...' % _('Object was buffered'))
  1982. except AttributeError:
  1983. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed to buffer. No object selected"))
  1984. self.app.proc_container.new_text = ''
  1985. class AttrDict(dict):
  1986. def __init__(self, *args, **kwargs):
  1987. super(AttrDict, self).__init__(*args, **kwargs)
  1988. self.__dict__ = self
  1989. class CNCjob(Geometry):
  1990. """
  1991. Represents work to be done by a CNC machine.
  1992. *ATTRIBUTES*
  1993. * ``gcode_parsed`` (list): Each is a dictionary:
  1994. ===================== =========================================
  1995. Key Value
  1996. ===================== =========================================
  1997. geom (Shapely.LineString) Tool path (XY plane)
  1998. kind (string) "AB", A is "T" (travel) or
  1999. "C" (cut). B is "F" (fast) or "S" (slow).
  2000. ===================== =========================================
  2001. """
  2002. defaults = {
  2003. "global_zdownrate": None,
  2004. "pp_geometry_name": 'default',
  2005. "pp_excellon_name": 'default',
  2006. "excellon_optimization_type": "B",
  2007. }
  2008. settings = QtCore.QSettings("Open Source", "FlatCAM")
  2009. if settings.contains("machinist"):
  2010. machinist_setting = settings.value('machinist', type=int)
  2011. else:
  2012. machinist_setting = 0
  2013. def __init__(self,
  2014. units="in", kind="generic", tooldia=0.0,
  2015. z_cut=-0.002, z_move=0.1,
  2016. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  2017. pp_geometry_name='default', pp_excellon_name='default',
  2018. depthpercut=0.1, z_pdepth=-0.02,
  2019. spindlespeed=None, spindledir='CW', dwell=True, dwelltime=1000,
  2020. toolchangez=0.787402, toolchange_xy='0.0,0.0',
  2021. endz=2.0, endxy='',
  2022. segx=None,
  2023. segy=None,
  2024. steps_per_circle=None):
  2025. self.decimals = self.app.decimals
  2026. # Used when parsing G-code arcs
  2027. self.steps_per_circle = steps_per_circle if steps_per_circle is not None else \
  2028. int(self.app.defaults['cncjob_steps_per_circle'])
  2029. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  2030. self.kind = kind
  2031. self.units = units
  2032. self.z_cut = z_cut
  2033. self.z_move = z_move
  2034. self.feedrate = feedrate
  2035. self.z_feedrate = feedrate_z
  2036. self.feedrate_rapid = feedrate_rapid
  2037. self.tooldia = tooldia
  2038. self.toolchange = False
  2039. self.z_toolchange = toolchangez
  2040. self.xy_toolchange = toolchange_xy
  2041. self.toolchange_xy_type = None
  2042. self.toolC = tooldia
  2043. self.startz = None
  2044. self.z_end = endz
  2045. self.xy_end = endxy
  2046. self.multidepth = False
  2047. self.z_depthpercut = depthpercut
  2048. self.extracut_length = None
  2049. # used by the self.generate_from_excellon_by_tool() method
  2050. # but set directly before the actual usage of the method with obj.excellon_optimization_type = value
  2051. self.excellon_optimization_type = 'No'
  2052. # if set True then the GCode generation will use UI; used in Excellon GVode for now
  2053. self.use_ui = False
  2054. self.unitcode = {"IN": "G20", "MM": "G21"}
  2055. self.feedminutecode = "G94"
  2056. # self.absolutecode = "G90"
  2057. # self.incrementalcode = "G91"
  2058. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2059. self.gcode = ""
  2060. self.gcode_parsed = None
  2061. self.pp_geometry_name = pp_geometry_name
  2062. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  2063. self.pp_excellon_name = pp_excellon_name
  2064. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  2065. self.pp_solderpaste_name = None
  2066. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  2067. self.f_plunge = None
  2068. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  2069. self.f_retract = None
  2070. # how much depth the probe can probe before error
  2071. self.z_pdepth = z_pdepth if z_pdepth else None
  2072. # the feedrate(speed) with which the probel travel while probing
  2073. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  2074. self.spindlespeed = spindlespeed
  2075. self.spindledir = spindledir
  2076. self.dwell = dwell
  2077. self.dwelltime = dwelltime
  2078. self.segx = float(segx) if segx is not None else 0.0
  2079. self.segy = float(segy) if segy is not None else 0.0
  2080. self.input_geometry_bounds = None
  2081. self.oldx = None
  2082. self.oldy = None
  2083. self.tool = 0.0
  2084. # here store the travelled distance
  2085. self.travel_distance = 0.0
  2086. # here store the routing time
  2087. self.routing_time = 0.0
  2088. # store here the Excellon source object tools to be accessible locally
  2089. self.exc_tools = None
  2090. # search for toolchange parameters in the Toolchange Custom Code
  2091. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  2092. # search for toolchange code: M6
  2093. self.re_toolchange = re.compile(r'^\s*(M6)$')
  2094. # Attributes to be included in serialization
  2095. # Always append to it because it carries contents
  2096. # from Geometry.
  2097. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  2098. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  2099. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  2100. @property
  2101. def postdata(self):
  2102. """
  2103. This will return all the attributes of the class in the form of a dictionary
  2104. :return: Class attributes
  2105. :rtype: dict
  2106. """
  2107. return self.__dict__
  2108. def convert_units(self, units):
  2109. """
  2110. Will convert the parameters in the class that are relevant, from metric to imperial and reverse
  2111. :param units: FlatCAM units
  2112. :type units: str
  2113. :return: conversion factor
  2114. :rtype: float
  2115. """
  2116. log.debug("camlib.CNCJob.convert_units()")
  2117. factor = Geometry.convert_units(self, units)
  2118. self.z_cut = float(self.z_cut) * factor
  2119. self.z_move *= factor
  2120. self.feedrate *= factor
  2121. self.z_feedrate *= factor
  2122. self.feedrate_rapid *= factor
  2123. self.tooldia *= factor
  2124. self.z_toolchange *= factor
  2125. self.z_end *= factor
  2126. self.z_depthpercut = float(self.z_depthpercut) * factor
  2127. return factor
  2128. def doformat(self, fun, **kwargs):
  2129. return self.doformat2(fun, **kwargs) + "\n"
  2130. def doformat2(self, fun, **kwargs):
  2131. """
  2132. This method will call one of the current preprocessor methods having as parameters all the attributes of
  2133. current class to which will add the kwargs parameters
  2134. :param fun: One of the methods inside the preprocessor classes which get loaded here in the 'p' object
  2135. :type fun: class 'function'
  2136. :param kwargs: keyword args which will update attributes of the current class
  2137. :type kwargs: dict
  2138. :return: Gcode line
  2139. :rtype: str
  2140. """
  2141. attributes = AttrDict()
  2142. attributes.update(self.postdata)
  2143. attributes.update(kwargs)
  2144. try:
  2145. returnvalue = fun(attributes)
  2146. return returnvalue
  2147. except Exception:
  2148. self.app.log.error('Exception occurred within a preprocessor: ' + traceback.format_exc())
  2149. return ''
  2150. def parse_custom_toolchange_code(self, data):
  2151. """
  2152. Will parse a text and get a toolchange sequence in text format suitable to be included in a Gcode file.
  2153. The '%' symbol is used to surround class variables name and must be removed in the returned string.
  2154. After that, the class variables (attributes) are replaced with the current values. The result is returned.
  2155. :param data: Toolchange sequence
  2156. :type data: str
  2157. :return: Processed toolchange sequence
  2158. :rtype: str
  2159. """
  2160. text = data
  2161. match_list = self.re_toolchange_custom.findall(text)
  2162. if match_list:
  2163. for match in match_list:
  2164. command = match.strip('%')
  2165. try:
  2166. value = getattr(self, command)
  2167. except AttributeError:
  2168. self.app.inform.emit('[ERROR] %s: %s' %
  2169. (_("There is no such parameter"), str(match)))
  2170. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  2171. return 'fail'
  2172. text = text.replace(match, str(value))
  2173. return text
  2174. # Distance callback
  2175. class CreateDistanceCallback(object):
  2176. """Create callback to calculate distances between points."""
  2177. def __init__(self, locs, manager):
  2178. self.manager = manager
  2179. self.matrix = {}
  2180. if locs:
  2181. size = len(locs)
  2182. for from_node in range(size):
  2183. self.matrix[from_node] = {}
  2184. for to_node in range(size):
  2185. if from_node == to_node:
  2186. self.matrix[from_node][to_node] = 0
  2187. else:
  2188. x1 = locs[from_node][0]
  2189. y1 = locs[from_node][1]
  2190. x2 = locs[to_node][0]
  2191. y2 = locs[to_node][1]
  2192. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  2193. # def Distance(self, from_node, to_node):
  2194. # return int(self.matrix[from_node][to_node])
  2195. def Distance(self, from_index, to_index):
  2196. # Convert from routing variable Index to distance matrix NodeIndex.
  2197. from_node = self.manager.IndexToNode(from_index)
  2198. to_node = self.manager.IndexToNode(to_index)
  2199. return self.matrix[from_node][to_node]
  2200. @staticmethod
  2201. def create_tool_data_array(points):
  2202. # Create the data.
  2203. loc_list = []
  2204. for pt in points:
  2205. loc_list.append((pt.coords.xy[0][0], pt.coords.xy[1][0]))
  2206. return loc_list
  2207. def optimized_ortools_meta(self, locations, start=None):
  2208. optimized_path = []
  2209. tsp_size = len(locations)
  2210. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2211. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2212. depot = 0 if start is None else start
  2213. # Create routing model.
  2214. if tsp_size > 0:
  2215. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2216. routing = pywrapcp.RoutingModel(manager)
  2217. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2218. search_parameters.local_search_metaheuristic = (
  2219. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  2220. # Set search time limit in milliseconds.
  2221. if float(self.app.defaults["excellon_search_time"]) != 0:
  2222. search_parameters.time_limit.seconds = int(
  2223. float(self.app.defaults["excellon_search_time"]))
  2224. else:
  2225. search_parameters.time_limit.seconds = 3
  2226. # Callback to the distance function. The callback takes two
  2227. # arguments (the from and to node indices) and returns the distance between them.
  2228. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  2229. # if there are no distances then go to the next tool
  2230. if not dist_between_locations:
  2231. return
  2232. dist_callback = dist_between_locations.Distance
  2233. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2234. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2235. # Solve, returns a solution if any.
  2236. assignment = routing.SolveWithParameters(search_parameters)
  2237. if assignment:
  2238. # Solution cost.
  2239. log.info("OR-tools metaheuristics - Total distance: " + str(assignment.ObjectiveValue()))
  2240. # Inspect solution.
  2241. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2242. route_number = 0
  2243. node = routing.Start(route_number)
  2244. start_node = node
  2245. while not routing.IsEnd(node):
  2246. if self.app.abort_flag:
  2247. # graceful abort requested by the user
  2248. raise grace
  2249. optimized_path.append(node)
  2250. node = assignment.Value(routing.NextVar(node))
  2251. else:
  2252. log.warning('OR-tools metaheuristics - No solution found.')
  2253. else:
  2254. log.warning('OR-tools metaheuristics - Specify an instance greater than 0.')
  2255. return optimized_path
  2256. # ############################################# ##
  2257. def optimized_ortools_basic(self, locations, start=None):
  2258. optimized_path = []
  2259. tsp_size = len(locations)
  2260. num_routes = 1 # The number of routes, which is 1 in the TSP.
  2261. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  2262. depot = 0 if start is None else start
  2263. # Create routing model.
  2264. if tsp_size > 0:
  2265. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  2266. routing = pywrapcp.RoutingModel(manager)
  2267. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  2268. # Callback to the distance function. The callback takes two
  2269. # arguments (the from and to node indices) and returns the distance between them.
  2270. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  2271. # if there are no distances then go to the next tool
  2272. if not dist_between_locations:
  2273. return
  2274. dist_callback = dist_between_locations.Distance
  2275. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  2276. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  2277. # Solve, returns a solution if any.
  2278. assignment = routing.SolveWithParameters(search_parameters)
  2279. if assignment:
  2280. # Solution cost.
  2281. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  2282. # Inspect solution.
  2283. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  2284. route_number = 0
  2285. node = routing.Start(route_number)
  2286. start_node = node
  2287. while not routing.IsEnd(node):
  2288. optimized_path.append(node)
  2289. node = assignment.Value(routing.NextVar(node))
  2290. else:
  2291. log.warning('No solution found.')
  2292. else:
  2293. log.warning('Specify an instance greater than 0.')
  2294. return optimized_path
  2295. # ############################################# ##
  2296. def optimized_travelling_salesman(self, points, start=None):
  2297. """
  2298. As solving the problem in the brute force way is too slow,
  2299. this function implements a simple heuristic: always
  2300. go to the nearest city.
  2301. Even if this algorithm is extremely simple, it works pretty well
  2302. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  2303. and runs very fast in O(N^2) time complexity.
  2304. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  2305. [[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],
  2306. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  2307. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  2308. [[0, 0], [6, 0], [10, 0]]
  2309. :param points: List of tuples with x, y coordinates
  2310. :type points: list
  2311. :param start: a tuple with a x,y coordinates of the start point
  2312. :type start: tuple
  2313. :return: List of points ordered in a optimized way
  2314. :rtype: list
  2315. """
  2316. if start is None:
  2317. start = points[0]
  2318. must_visit = points
  2319. path = [start]
  2320. # must_visit.remove(start)
  2321. while must_visit:
  2322. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  2323. path.append(nearest)
  2324. must_visit.remove(nearest)
  2325. return path
  2326. def check_zcut(self, zcut):
  2327. if zcut > 0:
  2328. self.app.inform.emit('[WARNING] %s' %
  2329. _("The Cut Z parameter has positive value. "
  2330. "It is the depth value to drill into material.\n"
  2331. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  2332. "therefore the app will convert the value to negative. "
  2333. "Check the resulting CNC code (Gcode etc)."))
  2334. return -zcut
  2335. elif zcut == 0:
  2336. self.app.inform.emit('[WARNING] %s.' % _("The Cut Z parameter is zero. There will be no cut, aborting"))
  2337. return 'fail'
  2338. def generate_from_excellon_by_tool(self, exobj, tools="all", order='fwd', use_ui=False):
  2339. """
  2340. Creates Gcode for this object from an Excellon object
  2341. for the specified tools.
  2342. :param exobj: Excellon object to process
  2343. :type exobj: Excellon
  2344. :param tools: Comma separated tool names
  2345. :type tools: str
  2346. :param order: order of tools processing: "fwd", "rev" or "no"
  2347. :type order: str
  2348. :param use_ui: if True the method will use parameters set in UI
  2349. :type use_ui: bool
  2350. :return: None
  2351. :rtype: None
  2352. """
  2353. # #############################################################################################################
  2354. # #############################################################################################################
  2355. # create a local copy of the exobj.tools so it can be used for creating drill CCode geometry
  2356. # #############################################################################################################
  2357. # #############################################################################################################
  2358. self.exc_tools = deepcopy(exobj.tools)
  2359. # the Excellon GCode preprocessor will use this info in the start_code() method
  2360. self.use_ui = True if use_ui else False
  2361. # Z_cut parameter
  2362. if self.machinist_setting == 0:
  2363. self.z_cut = self.check_zcut(zcut=self.z_cut)
  2364. if self.z_cut == 'fail':
  2365. return 'fail'
  2366. # multidepth use this
  2367. old_zcut = deepcopy(self.z_cut)
  2368. # XY_toolchange parameter
  2369. try:
  2370. if self.xy_toolchange == '':
  2371. self.xy_toolchange = None
  2372. else:
  2373. self.xy_toolchange = re.sub('[()\[\]]', '', str(self.xy_toolchange)) if self.xy_toolchange else None
  2374. if self.xy_toolchange:
  2375. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  2376. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  2377. self.app.inform.emit('[ERROR]%s' %
  2378. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  2379. "in the format (x, y) \nbut now there is only one value, not two. "))
  2380. return 'fail'
  2381. except Exception as e:
  2382. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  2383. pass
  2384. # XY_end parameter
  2385. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  2386. if self.xy_end and self.xy_end != '':
  2387. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  2388. if self.xy_end and len(self.xy_end) < 2:
  2389. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  2390. "in the format (x, y) but now there is only one value, not two."))
  2391. return 'fail'
  2392. # Prepprocessor
  2393. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  2394. p = self.pp_excellon
  2395. log.debug("Creating CNC Job from Excellon...")
  2396. # #############################################################################################################
  2397. # #############################################################################################################
  2398. # TOOLS
  2399. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  2400. # so we actually are sorting the tools by diameter
  2401. # #############################################################################################################
  2402. # #############################################################################################################
  2403. all_tools = []
  2404. for tool_as_key, v in list(self.exc_tools.items()):
  2405. all_tools.append((int(tool_as_key), float(v['tooldia'])))
  2406. if order == 'fwd':
  2407. sorted_tools = sorted(all_tools, key=lambda t1: t1[1])
  2408. elif order == 'rev':
  2409. sorted_tools = sorted(all_tools, key=lambda t1: t1[1], reverse=True)
  2410. else:
  2411. sorted_tools = all_tools
  2412. if tools == "all":
  2413. selected_tools = [i[0] for i in all_tools] # we get a array of ordered tools
  2414. else:
  2415. selected_tools = eval(tools)
  2416. # Create a sorted list of selected tools from the sorted_tools list
  2417. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  2418. log.debug("Tools sorted are: %s" % str(tools))
  2419. # #############################################################################################################
  2420. # #############################################################################################################
  2421. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2422. # running this method from a Tcl Command
  2423. # #############################################################################################################
  2424. # #############################################################################################################
  2425. build_tools_in_use_list = False
  2426. if 'Tools_in_use' not in self.options:
  2427. self.options['Tools_in_use'] = []
  2428. # if the list is empty (either we just added the key or it was already there but empty) signal to build it
  2429. if not self.options['Tools_in_use']:
  2430. build_tools_in_use_list = True
  2431. # #############################################################################################################
  2432. # #############################################################################################################
  2433. # fill the data into the self.exc_cnc_tools dictionary
  2434. # #############################################################################################################
  2435. # #############################################################################################################
  2436. for it in all_tools:
  2437. for to_ol in tools:
  2438. if to_ol == it[0]:
  2439. sol_geo = []
  2440. drill_no = 0
  2441. if 'drills' in exobj.tools[to_ol]:
  2442. drill_no = len(exobj.tools[to_ol]['drills'])
  2443. for drill in exobj.tools[to_ol]['drills']:
  2444. sol_geo.append(drill.buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle))
  2445. slot_no = 0
  2446. if 'slots' in exobj.tools[to_ol]:
  2447. slot_no = len(exobj.tools[to_ol]['slots'])
  2448. for slot in exobj.tools[to_ol]['slots']:
  2449. start = (slot[0].x, slot[0].y)
  2450. stop = (slot[1].x, slot[1].y)
  2451. sol_geo.append(
  2452. LineString([start, stop]).buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle)
  2453. )
  2454. if self.use_ui:
  2455. try:
  2456. z_off = float(exobj.tools[it[0]]['data']['offset']) * (-1)
  2457. except KeyError:
  2458. z_off = 0
  2459. else:
  2460. z_off = 0
  2461. default_data = {}
  2462. for k, v in list(self.options.items()):
  2463. default_data[k] = deepcopy(v)
  2464. self.exc_cnc_tools[it[1]] = {}
  2465. self.exc_cnc_tools[it[1]]['tool'] = it[0]
  2466. self.exc_cnc_tools[it[1]]['nr_drills'] = drill_no
  2467. self.exc_cnc_tools[it[1]]['nr_slots'] = slot_no
  2468. self.exc_cnc_tools[it[1]]['offset_z'] = z_off
  2469. self.exc_cnc_tools[it[1]]['data'] = default_data
  2470. self.exc_cnc_tools[it[1]]['solid_geometry'] = deepcopy(sol_geo)
  2471. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  2472. # running this method from a Tcl Command
  2473. if build_tools_in_use_list is True:
  2474. self.options['Tools_in_use'].append(
  2475. [it[0], it[1], drill_no, slot_no]
  2476. )
  2477. self.app.inform.emit(_("Creating a list of points to drill..."))
  2478. # #############################################################################################################
  2479. # #############################################################################################################
  2480. # Points (Group by tool): a dictionary of shapely Point geo elements grouped by tool number
  2481. # #############################################################################################################
  2482. # #############################################################################################################
  2483. points = {}
  2484. for tool, tool_dict in self.exc_tools.items():
  2485. if tool in tools:
  2486. if self.app.abort_flag:
  2487. # graceful abort requested by the user
  2488. raise grace
  2489. if 'drills' in tool_dict and tool_dict['drills']:
  2490. for drill_pt in tool_dict['drills']:
  2491. try:
  2492. points[tool].append(drill_pt)
  2493. except KeyError:
  2494. points[tool] = [drill_pt]
  2495. log.debug("Found %d TOOLS with drills." % len(points))
  2496. # check if there are drill points in the exclusion areas.
  2497. # If we find any within the exclusion areas return 'fail'
  2498. for tool in points:
  2499. for pt in points[tool]:
  2500. for area in self.app.exc_areas.exclusion_areas_storage:
  2501. pt_buf = pt.buffer(self.exc_tools[tool]['tooldia'] / 2.0)
  2502. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  2503. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  2504. return 'fail'
  2505. # this holds the resulting GCode
  2506. self.gcode = []
  2507. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  2508. self.f_retract = self.app.defaults["excellon_f_retract"]
  2509. # #############################################################################################################
  2510. # #############################################################################################################
  2511. # Initialization
  2512. # #############################################################################################################
  2513. # #############################################################################################################
  2514. gcode = self.doformat(p.start_code)
  2515. if use_ui is False:
  2516. gcode += self.doformat(p.z_feedrate_code)
  2517. if self.toolchange is False:
  2518. if self.xy_toolchange is not None:
  2519. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2520. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  2521. else:
  2522. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  2523. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  2524. if self.xy_toolchange is not None:
  2525. self.oldx = self.xy_toolchange[0]
  2526. self.oldy = self.xy_toolchange[1]
  2527. else:
  2528. self.oldx = 0.0
  2529. self.oldy = 0.0
  2530. measured_distance = 0.0
  2531. measured_down_distance = 0.0
  2532. measured_up_to_zero_distance = 0.0
  2533. measured_lift_distance = 0.0
  2534. # #############################################################################################################
  2535. # #############################################################################################################
  2536. # GCODE creation
  2537. # #############################################################################################################
  2538. # #############################################################################################################
  2539. self.app.inform.emit('%s...' % _("Starting G-Code"))
  2540. has_drills = None
  2541. for tool, tool_dict in self.exc_tools.items():
  2542. if 'drills' in tool_dict and tool_dict['drills']:
  2543. has_drills = True
  2544. break
  2545. if not has_drills:
  2546. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  2547. "The loaded Excellon file has no drills ...")
  2548. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  2549. return 'fail'
  2550. current_platform = platform.architecture()[0]
  2551. if current_platform == '64bit':
  2552. used_excellon_optimization_type = self.excellon_optimization_type
  2553. else:
  2554. used_excellon_optimization_type = 'T'
  2555. # #############################################################################################################
  2556. # #############################################################################################################
  2557. # ################################## DRILLING !!! #########################################################
  2558. # #############################################################################################################
  2559. # #############################################################################################################
  2560. if used_excellon_optimization_type == 'M':
  2561. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2562. elif used_excellon_optimization_type == 'B':
  2563. log.debug("Using OR-Tools Basic drill path optimization.")
  2564. elif used_excellon_optimization_type == 'T':
  2565. log.debug("Using Travelling Salesman drill path optimization.")
  2566. else:
  2567. log.debug("Using no path optimization.")
  2568. if self.toolchange is True:
  2569. for tool in tools:
  2570. # check if it has drills
  2571. if not self.exc_tools[tool]['drills']:
  2572. continue
  2573. if self.app.abort_flag:
  2574. # graceful abort requested by the user
  2575. raise grace
  2576. self.tool = tool
  2577. self.tooldia = self.exc_tools[tool]["tooldia"]
  2578. self.postdata['toolC'] = self.tooldia
  2579. if self.use_ui:
  2580. self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  2581. self.feedrate = self.exc_tools[tool]['data']['feedrate']
  2582. self.z_cut = self.exc_tools[tool]['data']['cutz']
  2583. gcode += self.doformat(p.z_feedrate_code)
  2584. if self.machinist_setting == 0:
  2585. if self.z_cut > 0:
  2586. self.app.inform.emit('[WARNING] %s' %
  2587. _("The Cut Z parameter has positive value. "
  2588. "It is the depth value to drill into material.\n"
  2589. "The Cut Z parameter needs to have a negative value, "
  2590. "assuming it is a typo "
  2591. "therefore the app will convert the value to negative. "
  2592. "Check the resulting CNC code (Gcode etc)."))
  2593. self.z_cut = -self.z_cut
  2594. elif self.z_cut == 0:
  2595. self.app.inform.emit('[WARNING] %s: %s' %
  2596. (_(
  2597. "The Cut Z parameter is zero. There will be no cut, "
  2598. "skipping file"),
  2599. exobj.options['name']))
  2600. return 'fail'
  2601. old_zcut = deepcopy(self.z_cut)
  2602. self.z_move = self.exc_tools[tool]['data']['travelz']
  2603. self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  2604. self.dwell = self.exc_tools[tool]['data']['dwell']
  2605. self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  2606. self.multidepth = self.exc_tools[tool]['data']['multidepth']
  2607. self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  2608. else:
  2609. old_zcut = deepcopy(self.z_cut)
  2610. # #########################################################################################################
  2611. # ############ Create the data. #################
  2612. # #########################################################################################################
  2613. locations = []
  2614. altPoints = []
  2615. optimized_path = []
  2616. if used_excellon_optimization_type == 'M':
  2617. if tool in points:
  2618. locations = self.create_tool_data_array(points=points[tool])
  2619. # if there are no locations then go to the next tool
  2620. if not locations:
  2621. continue
  2622. optimized_path = self.optimized_ortools_meta(locations=locations)
  2623. elif used_excellon_optimization_type == 'B':
  2624. if tool in points:
  2625. locations = self.create_tool_data_array(points=points[tool])
  2626. # if there are no locations then go to the next tool
  2627. if not locations:
  2628. continue
  2629. optimized_path = self.optimized_ortools_basic(locations=locations)
  2630. elif used_excellon_optimization_type == 'T':
  2631. for point in points[tool]:
  2632. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2633. optimized_path = self.optimized_travelling_salesman(altPoints)
  2634. else:
  2635. # it's actually not optimized path but here we build a list of (x,y) coordinates
  2636. # out of the tool's drills
  2637. for drill in self.exc_tools[tool]['drills']:
  2638. unoptimized_coords = (
  2639. drill.x,
  2640. drill.y
  2641. )
  2642. optimized_path.append(unoptimized_coords)
  2643. # #########################################################################################################
  2644. # #########################################################################################################
  2645. # Only if there are locations to drill
  2646. if not optimized_path:
  2647. continue
  2648. if self.app.abort_flag:
  2649. # graceful abort requested by the user
  2650. raise grace
  2651. # Tool change sequence (optional)
  2652. if self.toolchange:
  2653. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  2654. # Spindle start
  2655. gcode += self.doformat(p.spindle_code)
  2656. # Dwell time
  2657. if self.dwell is True:
  2658. gcode += self.doformat(p.dwell_code)
  2659. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  2660. self.app.inform.emit(
  2661. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2662. str(current_tooldia),
  2663. str(self.units))
  2664. )
  2665. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2666. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  2667. # because the values for Z offset are created in build_ui()
  2668. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2669. try:
  2670. z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  2671. except KeyError:
  2672. z_offset = 0
  2673. self.z_cut = z_offset + old_zcut
  2674. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2675. if self.coordinates_type == "G90":
  2676. # Drillling! for Absolute coordinates type G90
  2677. # variables to display the percentage of work done
  2678. geo_len = len(optimized_path)
  2679. old_disp_number = 0
  2680. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2681. loc_nr = 0
  2682. for point in optimized_path:
  2683. if self.app.abort_flag:
  2684. # graceful abort requested by the user
  2685. raise grace
  2686. if used_excellon_optimization_type == 'T':
  2687. locx = point[0]
  2688. locy = point[1]
  2689. else:
  2690. locx = locations[point][0]
  2691. locy = locations[point][1]
  2692. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  2693. end_point=(locx, locy),
  2694. tooldia=current_tooldia)
  2695. prev_z = None
  2696. for travel in travels:
  2697. locx = travel[1][0]
  2698. locy = travel[1][1]
  2699. if travel[0] is not None:
  2700. # move to next point
  2701. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2702. # raise to safe Z (travel[0]) each time because safe Z may be different
  2703. self.z_move = travel[0]
  2704. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2705. # restore z_move
  2706. self.z_move = self.exc_tools[tool]['data']['travelz']
  2707. else:
  2708. if prev_z is not None:
  2709. # move to next point
  2710. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2711. # we assume that previously the z_move was altered therefore raise to
  2712. # the travel_z (z_move)
  2713. self.z_move = self.exc_tools[tool]['data']['travelz']
  2714. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2715. else:
  2716. # move to next point
  2717. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2718. # store prev_z
  2719. prev_z = travel[0]
  2720. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2721. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  2722. doc = deepcopy(self.z_cut)
  2723. self.z_cut = 0.0
  2724. while abs(self.z_cut) < abs(doc):
  2725. self.z_cut -= self.z_depthpercut
  2726. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  2727. self.z_cut = doc
  2728. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2729. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2730. if self.f_retract is False:
  2731. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2732. measured_up_to_zero_distance += abs(self.z_cut)
  2733. measured_lift_distance += abs(self.z_move)
  2734. else:
  2735. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2736. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2737. else:
  2738. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2739. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2740. if self.f_retract is False:
  2741. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2742. measured_up_to_zero_distance += abs(self.z_cut)
  2743. measured_lift_distance += abs(self.z_move)
  2744. else:
  2745. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2746. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2747. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2748. self.oldx = locx
  2749. self.oldy = locy
  2750. loc_nr += 1
  2751. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2752. if old_disp_number < disp_number <= 100:
  2753. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2754. old_disp_number = disp_number
  2755. else:
  2756. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2757. return 'fail'
  2758. self.z_cut = deepcopy(old_zcut)
  2759. else:
  2760. # We are not using Toolchange therefore we need to decide which tool properties to use
  2761. one_tool = 1
  2762. all_points = []
  2763. for tool in points:
  2764. # check if it has drills
  2765. if not points[tool]:
  2766. continue
  2767. all_points += points[tool]
  2768. if self.app.abort_flag:
  2769. # graceful abort requested by the user
  2770. raise grace
  2771. self.tool = one_tool
  2772. self.tooldia = self.exc_tools[one_tool]["tooldia"]
  2773. self.postdata['toolC'] = self.tooldia
  2774. if self.use_ui:
  2775. self.z_feedrate = self.exc_tools[one_tool]['data']['feedrate_z']
  2776. self.feedrate = self.exc_tools[one_tool]['data']['feedrate']
  2777. self.z_cut = self.exc_tools[one_tool]['data']['cutz']
  2778. gcode += self.doformat(p.z_feedrate_code)
  2779. if self.machinist_setting == 0:
  2780. if self.z_cut > 0:
  2781. self.app.inform.emit('[WARNING] %s' %
  2782. _("The Cut Z parameter has positive value. "
  2783. "It is the depth value to drill into material.\n"
  2784. "The Cut Z parameter needs to have a negative value, "
  2785. "assuming it is a typo "
  2786. "therefore the app will convert the value to negative. "
  2787. "Check the resulting CNC code (Gcode etc)."))
  2788. self.z_cut = -self.z_cut
  2789. elif self.z_cut == 0:
  2790. self.app.inform.emit('[WARNING] %s: %s' %
  2791. (_(
  2792. "The Cut Z parameter is zero. There will be no cut, "
  2793. "skipping file"),
  2794. exobj.options['name']))
  2795. return 'fail'
  2796. old_zcut = deepcopy(self.z_cut)
  2797. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2798. self.spindlespeed = self.exc_tools[one_tool]['data']['spindlespeed']
  2799. self.dwell = self.exc_tools[one_tool]['data']['dwell']
  2800. self.dwelltime = self.exc_tools[one_tool]['data']['dwelltime']
  2801. self.multidepth = self.exc_tools[one_tool]['data']['multidepth']
  2802. self.z_depthpercut = self.exc_tools[one_tool]['data']['depthperpass']
  2803. else:
  2804. old_zcut = deepcopy(self.z_cut)
  2805. # #########################################################################################################
  2806. # ############ Create the data. #################
  2807. # #########################################################################################################
  2808. locations = []
  2809. altPoints = []
  2810. optimized_path = []
  2811. if used_excellon_optimization_type == 'M':
  2812. if all_points:
  2813. locations = self.create_tool_data_array(points=all_points)
  2814. # if there are no locations then go to the next tool
  2815. if not locations:
  2816. return 'fail'
  2817. optimized_path = self.optimized_ortools_meta(locations=locations)
  2818. elif used_excellon_optimization_type == 'B':
  2819. if all_points:
  2820. locations = self.create_tool_data_array(points=all_points)
  2821. # if there are no locations then go to the next tool
  2822. if not locations:
  2823. return 'fail'
  2824. optimized_path = self.optimized_ortools_basic(locations=locations)
  2825. elif used_excellon_optimization_type == 'T':
  2826. for point in all_points:
  2827. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  2828. optimized_path = self.optimized_travelling_salesman(altPoints)
  2829. else:
  2830. # it's actually not optimized path but here we build a list of (x,y) coordinates
  2831. # out of the tool's drills
  2832. for pt in all_points:
  2833. unoptimized_coords = (
  2834. pt.x,
  2835. pt.y
  2836. )
  2837. optimized_path.append(unoptimized_coords)
  2838. # #########################################################################################################
  2839. # #########################################################################################################
  2840. # Only if there are locations to drill
  2841. if not optimized_path:
  2842. return 'fail'
  2843. if self.app.abort_flag:
  2844. # graceful abort requested by the user
  2845. raise grace
  2846. # Spindle start
  2847. gcode += self.doformat(p.spindle_code)
  2848. # Dwell time
  2849. if self.dwell is True:
  2850. gcode += self.doformat(p.dwell_code)
  2851. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[one_tool]["tooldia"])))
  2852. self.app.inform.emit(
  2853. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  2854. str(current_tooldia),
  2855. str(self.units))
  2856. )
  2857. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2858. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  2859. # because the values for Z offset are created in build_ui()
  2860. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  2861. try:
  2862. z_offset = float(self.exc_tools[one_tool]['data']['offset']) * (-1)
  2863. except KeyError:
  2864. z_offset = 0
  2865. self.z_cut = z_offset + old_zcut
  2866. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  2867. if self.coordinates_type == "G90":
  2868. # Drillling! for Absolute coordinates type G90
  2869. # variables to display the percentage of work done
  2870. geo_len = len(optimized_path)
  2871. old_disp_number = 0
  2872. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  2873. loc_nr = 0
  2874. for point in optimized_path:
  2875. if self.app.abort_flag:
  2876. # graceful abort requested by the user
  2877. raise grace
  2878. if used_excellon_optimization_type == 'T':
  2879. locx = point[0]
  2880. locy = point[1]
  2881. else:
  2882. locx = locations[point][0]
  2883. locy = locations[point][1]
  2884. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  2885. end_point=(locx, locy),
  2886. tooldia=current_tooldia)
  2887. prev_z = None
  2888. for travel in travels:
  2889. locx = travel[1][0]
  2890. locy = travel[1][1]
  2891. if travel[0] is not None:
  2892. # move to next point
  2893. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2894. # raise to safe Z (travel[0]) each time because safe Z may be different
  2895. self.z_move = travel[0]
  2896. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2897. # restore z_move
  2898. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2899. else:
  2900. if prev_z is not None:
  2901. # move to next point
  2902. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2903. # we assume that previously the z_move was altered therefore raise to
  2904. # the travel_z (z_move)
  2905. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  2906. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2907. else:
  2908. # move to next point
  2909. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2910. # store prev_z
  2911. prev_z = travel[0]
  2912. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  2913. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  2914. doc = deepcopy(self.z_cut)
  2915. self.z_cut = 0.0
  2916. while abs(self.z_cut) < abs(doc):
  2917. self.z_cut -= self.z_depthpercut
  2918. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  2919. self.z_cut = doc
  2920. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2921. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2922. if self.f_retract is False:
  2923. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2924. measured_up_to_zero_distance += abs(self.z_cut)
  2925. measured_lift_distance += abs(self.z_move)
  2926. else:
  2927. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2928. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2929. else:
  2930. gcode += self.doformat(p.down_code, x=locx, y=locy)
  2931. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  2932. if self.f_retract is False:
  2933. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  2934. measured_up_to_zero_distance += abs(self.z_cut)
  2935. measured_lift_distance += abs(self.z_move)
  2936. else:
  2937. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  2938. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  2939. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  2940. self.oldx = locx
  2941. self.oldy = locy
  2942. loc_nr += 1
  2943. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  2944. if old_disp_number < disp_number <= 100:
  2945. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  2946. old_disp_number = disp_number
  2947. else:
  2948. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  2949. return 'fail'
  2950. self.z_cut = deepcopy(old_zcut)
  2951. if used_excellon_optimization_type == 'M':
  2952. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  2953. elif used_excellon_optimization_type == 'B':
  2954. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  2955. elif used_excellon_optimization_type == 'T':
  2956. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  2957. else:
  2958. log.debug("The total travel distance with with no optimization is: %s" % str(measured_distance))
  2959. # if used_excellon_optimization_type == 'M':
  2960. # log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  2961. #
  2962. # if has_drills:
  2963. # for tool in tools:
  2964. # if self.app.abort_flag:
  2965. # # graceful abort requested by the user
  2966. # raise grace
  2967. #
  2968. # self.tool = tool
  2969. # self.tooldia = self.exc_tools[tool]["tooldia"]
  2970. # self.postdata['toolC'] = self.tooldia
  2971. #
  2972. # if self.use_ui:
  2973. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  2974. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  2975. # gcode += self.doformat(p.z_feedrate_code)
  2976. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  2977. #
  2978. # if self.machinist_setting == 0:
  2979. # if self.z_cut > 0:
  2980. # self.app.inform.emit('[WARNING] %s' %
  2981. # _("The Cut Z parameter has positive value. "
  2982. # "It is the depth value to drill into material.\n"
  2983. # "The Cut Z parameter needs to have a negative value, "
  2984. # "assuming it is a typo "
  2985. # "therefore the app will convert the value to negative. "
  2986. # "Check the resulting CNC code (Gcode etc)."))
  2987. # self.z_cut = -self.z_cut
  2988. # elif self.z_cut == 0:
  2989. # self.app.inform.emit('[WARNING] %s: %s' %
  2990. # (_(
  2991. # "The Cut Z parameter is zero. There will be no cut, "
  2992. # "skipping file"),
  2993. # exobj.options['name']))
  2994. # return 'fail'
  2995. #
  2996. # old_zcut = deepcopy(self.z_cut)
  2997. #
  2998. # self.z_move = self.exc_tools[tool]['data']['travelz']
  2999. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3000. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3001. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3002. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3003. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3004. # else:
  3005. # old_zcut = deepcopy(self.z_cut)
  3006. #
  3007. # # ###############################################
  3008. # # ############ Create the data. #################
  3009. # # ###############################################
  3010. # locations = self.create_tool_data_array(tool=tool, points=points)
  3011. # # if there are no locations then go to the next tool
  3012. # if not locations:
  3013. # continue
  3014. # optimized_path = self.optimized_ortools_meta(locations=locations)
  3015. #
  3016. # # Only if tool has points.
  3017. # if tool in points:
  3018. # if self.app.abort_flag:
  3019. # # graceful abort requested by the user
  3020. # raise grace
  3021. #
  3022. # # Tool change sequence (optional)
  3023. # if self.toolchange:
  3024. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3025. # # Spindle start
  3026. # gcode += self.doformat(p.spindle_code)
  3027. # # Dwell time
  3028. # if self.dwell is True:
  3029. # gcode += self.doformat(p.dwell_code)
  3030. #
  3031. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3032. #
  3033. # self.app.inform.emit(
  3034. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3035. # str(current_tooldia),
  3036. # str(self.units))
  3037. # )
  3038. #
  3039. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3040. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3041. # # because the values for Z offset are created in build_ui()
  3042. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3043. # try:
  3044. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3045. # except KeyError:
  3046. # z_offset = 0
  3047. # self.z_cut = z_offset + old_zcut
  3048. #
  3049. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3050. # if self.coordinates_type == "G90":
  3051. # # Drillling! for Absolute coordinates type G90
  3052. # # variables to display the percentage of work done
  3053. # geo_len = len(optimized_path)
  3054. #
  3055. # old_disp_number = 0
  3056. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3057. #
  3058. # loc_nr = 0
  3059. # for k in optimized_path:
  3060. # if self.app.abort_flag:
  3061. # # graceful abort requested by the user
  3062. # raise grace
  3063. #
  3064. # locx = locations[k][0]
  3065. # locy = locations[k][1]
  3066. #
  3067. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3068. # end_point=(locx, locy),
  3069. # tooldia=current_tooldia)
  3070. # prev_z = None
  3071. # for travel in travels:
  3072. # locx = travel[1][0]
  3073. # locy = travel[1][1]
  3074. #
  3075. # if travel[0] is not None:
  3076. # # move to next point
  3077. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3078. #
  3079. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3080. # self.z_move = travel[0]
  3081. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3082. #
  3083. # # restore z_move
  3084. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3085. # else:
  3086. # if prev_z is not None:
  3087. # # move to next point
  3088. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3089. #
  3090. # # we assume that previously the z_move was altered therefore raise to
  3091. # # the travel_z (z_move)
  3092. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3093. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3094. # else:
  3095. # # move to next point
  3096. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3097. #
  3098. # # store prev_z
  3099. # prev_z = travel[0]
  3100. #
  3101. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3102. #
  3103. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3104. # doc = deepcopy(self.z_cut)
  3105. # self.z_cut = 0.0
  3106. #
  3107. # while abs(self.z_cut) < abs(doc):
  3108. #
  3109. # self.z_cut -= self.z_depthpercut
  3110. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3111. # self.z_cut = doc
  3112. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3113. #
  3114. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3115. #
  3116. # if self.f_retract is False:
  3117. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3118. # measured_up_to_zero_distance += abs(self.z_cut)
  3119. # measured_lift_distance += abs(self.z_move)
  3120. # else:
  3121. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3122. #
  3123. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3124. #
  3125. # else:
  3126. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3127. #
  3128. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3129. #
  3130. # if self.f_retract is False:
  3131. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3132. # measured_up_to_zero_distance += abs(self.z_cut)
  3133. # measured_lift_distance += abs(self.z_move)
  3134. # else:
  3135. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3136. #
  3137. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3138. #
  3139. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3140. # self.oldx = locx
  3141. # self.oldy = locy
  3142. #
  3143. # loc_nr += 1
  3144. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3145. #
  3146. # if old_disp_number < disp_number <= 100:
  3147. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3148. # old_disp_number = disp_number
  3149. #
  3150. # else:
  3151. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3152. # return 'fail'
  3153. # self.z_cut = deepcopy(old_zcut)
  3154. # else:
  3155. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3156. # "The loaded Excellon file has no drills ...")
  3157. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3158. # return 'fail'
  3159. #
  3160. # log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  3161. #
  3162. # elif used_excellon_optimization_type == 'B':
  3163. # log.debug("Using OR-Tools Basic drill path optimization.")
  3164. #
  3165. # if has_drills:
  3166. # for tool in tools:
  3167. # if self.app.abort_flag:
  3168. # # graceful abort requested by the user
  3169. # raise grace
  3170. #
  3171. # self.tool = tool
  3172. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3173. # self.postdata['toolC'] = self.tooldia
  3174. #
  3175. # if self.use_ui:
  3176. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3177. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3178. # gcode += self.doformat(p.z_feedrate_code)
  3179. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3180. #
  3181. # if self.machinist_setting == 0:
  3182. # if self.z_cut > 0:
  3183. # self.app.inform.emit('[WARNING] %s' %
  3184. # _("The Cut Z parameter has positive value. "
  3185. # "It is the depth value to drill into material.\n"
  3186. # "The Cut Z parameter needs to have a negative value, "
  3187. # "assuming it is a typo "
  3188. # "therefore the app will convert the value to negative. "
  3189. # "Check the resulting CNC code (Gcode etc)."))
  3190. # self.z_cut = -self.z_cut
  3191. # elif self.z_cut == 0:
  3192. # self.app.inform.emit('[WARNING] %s: %s' %
  3193. # (_(
  3194. # "The Cut Z parameter is zero. There will be no cut, "
  3195. # "skipping file"),
  3196. # exobj.options['name']))
  3197. # return 'fail'
  3198. #
  3199. # old_zcut = deepcopy(self.z_cut)
  3200. #
  3201. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3202. #
  3203. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3204. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3205. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3206. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3207. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3208. # else:
  3209. # old_zcut = deepcopy(self.z_cut)
  3210. #
  3211. # # ###############################################
  3212. # # ############ Create the data. #################
  3213. # # ###############################################
  3214. # locations = self.create_tool_data_array(tool=tool, points=points)
  3215. # # if there are no locations then go to the next tool
  3216. # if not locations:
  3217. # continue
  3218. # optimized_path = self.optimized_ortools_basic(locations=locations)
  3219. #
  3220. # # Only if tool has points.
  3221. # if tool in points:
  3222. # if self.app.abort_flag:
  3223. # # graceful abort requested by the user
  3224. # raise grace
  3225. #
  3226. # # Tool change sequence (optional)
  3227. # if self.toolchange:
  3228. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3229. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3230. # if self.dwell is True:
  3231. # gcode += self.doformat(p.dwell_code) # Dwell time
  3232. # else:
  3233. # gcode += self.doformat(p.spindle_code)
  3234. # if self.dwell is True:
  3235. # gcode += self.doformat(p.dwell_code) # Dwell time
  3236. #
  3237. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3238. #
  3239. # self.app.inform.emit(
  3240. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3241. # str(current_tooldia),
  3242. # str(self.units))
  3243. # )
  3244. #
  3245. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3246. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3247. # # because the values for Z offset are created in build_ui()
  3248. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3249. # try:
  3250. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3251. # except KeyError:
  3252. # z_offset = 0
  3253. # self.z_cut = z_offset + old_zcut
  3254. #
  3255. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3256. # if self.coordinates_type == "G90":
  3257. # # Drillling! for Absolute coordinates type G90
  3258. # # variables to display the percentage of work done
  3259. # geo_len = len(optimized_path)
  3260. # old_disp_number = 0
  3261. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3262. #
  3263. # loc_nr = 0
  3264. # for k in optimized_path:
  3265. # if self.app.abort_flag:
  3266. # # graceful abort requested by the user
  3267. # raise grace
  3268. #
  3269. # locx = locations[k][0]
  3270. # locy = locations[k][1]
  3271. #
  3272. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3273. # end_point=(locx, locy),
  3274. # tooldia=current_tooldia)
  3275. # prev_z = None
  3276. # for travel in travels:
  3277. # locx = travel[1][0]
  3278. # locy = travel[1][1]
  3279. #
  3280. # if travel[0] is not None:
  3281. # # move to next point
  3282. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3283. #
  3284. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3285. # self.z_move = travel[0]
  3286. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3287. #
  3288. # # restore z_move
  3289. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3290. # else:
  3291. # if prev_z is not None:
  3292. # # move to next point
  3293. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3294. #
  3295. # # we assume that previously the z_move was altered therefore raise to
  3296. # # the travel_z (z_move)
  3297. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3298. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3299. # else:
  3300. # # move to next point
  3301. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3302. #
  3303. # # store prev_z
  3304. # prev_z = travel[0]
  3305. #
  3306. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3307. #
  3308. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3309. # doc = deepcopy(self.z_cut)
  3310. # self.z_cut = 0.0
  3311. #
  3312. # while abs(self.z_cut) < abs(doc):
  3313. #
  3314. # self.z_cut -= self.z_depthpercut
  3315. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3316. # self.z_cut = doc
  3317. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3318. #
  3319. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3320. #
  3321. # if self.f_retract is False:
  3322. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3323. # measured_up_to_zero_distance += abs(self.z_cut)
  3324. # measured_lift_distance += abs(self.z_move)
  3325. # else:
  3326. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3327. #
  3328. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3329. #
  3330. # else:
  3331. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3332. #
  3333. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3334. #
  3335. # if self.f_retract is False:
  3336. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3337. # measured_up_to_zero_distance += abs(self.z_cut)
  3338. # measured_lift_distance += abs(self.z_move)
  3339. # else:
  3340. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3341. #
  3342. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3343. #
  3344. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3345. # self.oldx = locx
  3346. # self.oldy = locy
  3347. #
  3348. # loc_nr += 1
  3349. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3350. #
  3351. # if old_disp_number < disp_number <= 100:
  3352. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3353. # old_disp_number = disp_number
  3354. #
  3355. # else:
  3356. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3357. # return 'fail'
  3358. # self.z_cut = deepcopy(old_zcut)
  3359. # else:
  3360. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3361. # "The loaded Excellon file has no drills ...")
  3362. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3363. # return 'fail'
  3364. #
  3365. # log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  3366. #
  3367. # elif used_excellon_optimization_type == 'T':
  3368. # log.debug("Using Travelling Salesman drill path optimization.")
  3369. #
  3370. # for tool in tools:
  3371. # if self.app.abort_flag:
  3372. # # graceful abort requested by the user
  3373. # raise grace
  3374. #
  3375. # if has_drills:
  3376. # self.tool = tool
  3377. # self.tooldia = self.exc_tools[tool]["tooldia"]
  3378. # self.postdata['toolC'] = self.tooldia
  3379. #
  3380. # if self.use_ui:
  3381. # self.z_feedrate = self.exc_tools[tool]['data']['feedrate_z']
  3382. # self.feedrate = self.exc_tools[tool]['data']['feedrate']
  3383. # gcode += self.doformat(p.z_feedrate_code)
  3384. #
  3385. # self.z_cut = self.exc_tools[tool]['data']['cutz']
  3386. #
  3387. # if self.machinist_setting == 0:
  3388. # if self.z_cut > 0:
  3389. # self.app.inform.emit('[WARNING] %s' %
  3390. # _("The Cut Z parameter has positive value. "
  3391. # "It is the depth value to drill into material.\n"
  3392. # "The Cut Z parameter needs to have a negative value, "
  3393. # "assuming it is a typo "
  3394. # "therefore the app will convert the value to negative. "
  3395. # "Check the resulting CNC code (Gcode etc)."))
  3396. # self.z_cut = -self.z_cut
  3397. # elif self.z_cut == 0:
  3398. # self.app.inform.emit('[WARNING] %s: %s' %
  3399. # (_(
  3400. # "The Cut Z parameter is zero. There will be no cut, "
  3401. # "skipping file"),
  3402. # exobj.options['name']))
  3403. # return 'fail'
  3404. #
  3405. # old_zcut = deepcopy(self.z_cut)
  3406. #
  3407. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3408. # self.spindlespeed = self.exc_tools[tool]['data']['spindlespeed']
  3409. # self.dwell = self.exc_tools[tool]['data']['dwell']
  3410. # self.dwelltime = self.exc_tools[tool]['data']['dwelltime']
  3411. # self.multidepth = self.exc_tools[tool]['data']['multidepth']
  3412. # self.z_depthpercut = self.exc_tools[tool]['data']['depthperpass']
  3413. # else:
  3414. # old_zcut = deepcopy(self.z_cut)
  3415. #
  3416. # # ###############################################
  3417. # # ############ Create the data. #################
  3418. # # ###############################################
  3419. # altPoints = []
  3420. # for point in points[tool]:
  3421. # altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  3422. # optimized_path = self.optimized_travelling_salesman(altPoints)
  3423. #
  3424. # # Only if tool has points.
  3425. # if tool in points:
  3426. # if self.app.abort_flag:
  3427. # # graceful abort requested by the user
  3428. # raise grace
  3429. #
  3430. # # Tool change sequence (optional)
  3431. # if self.toolchange:
  3432. # gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  3433. # gcode += self.doformat(p.spindle_code) # Spindle start)
  3434. # if self.dwell is True:
  3435. # gcode += self.doformat(p.dwell_code) # Dwell time
  3436. # else:
  3437. # gcode += self.doformat(p.spindle_code)
  3438. # if self.dwell is True:
  3439. # gcode += self.doformat(p.dwell_code) # Dwell time
  3440. #
  3441. # current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  3442. #
  3443. # self.app.inform.emit(
  3444. # '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3445. # str(current_tooldia),
  3446. # str(self.units))
  3447. # )
  3448. #
  3449. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3450. # # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  3451. # # because the values for Z offset are created in build_ui()
  3452. # # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  3453. # try:
  3454. # z_offset = float(self.exc_tools[tool]['data']['offset']) * (-1)
  3455. # except KeyError:
  3456. # z_offset = 0
  3457. # self.z_cut = z_offset + old_zcut
  3458. #
  3459. # self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  3460. # if self.coordinates_type == "G90":
  3461. # # Drillling! for Absolute coordinates type G90
  3462. # # variables to display the percentage of work done
  3463. # geo_len = len(optimized_path)
  3464. # old_disp_number = 0
  3465. # log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  3466. #
  3467. # loc_nr = 0
  3468. # for point in optimized_path:
  3469. # if self.app.abort_flag:
  3470. # # graceful abort requested by the user
  3471. # raise grace
  3472. #
  3473. # locx = point[0]
  3474. # locy = point[1]
  3475. #
  3476. # travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  3477. # end_point=(locx, locy),
  3478. # tooldia=current_tooldia)
  3479. # prev_z = None
  3480. # for travel in travels:
  3481. # locx = travel[1][0]
  3482. # locy = travel[1][1]
  3483. #
  3484. # if travel[0] is not None:
  3485. # # move to next point
  3486. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3487. #
  3488. # # raise to safe Z (travel[0]) each time because safe Z may be different
  3489. # self.z_move = travel[0]
  3490. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3491. #
  3492. # # restore z_move
  3493. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3494. # else:
  3495. # if prev_z is not None:
  3496. # # move to next point
  3497. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3498. #
  3499. # # we assume that previously the z_move was altered therefore raise to
  3500. # # the travel_z (z_move)
  3501. # self.z_move = self.exc_tools[tool]['data']['travelz']
  3502. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3503. # else:
  3504. # # move to next point
  3505. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3506. #
  3507. # # store prev_z
  3508. # prev_z = travel[0]
  3509. #
  3510. # # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  3511. #
  3512. # if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  3513. # doc = deepcopy(self.z_cut)
  3514. # self.z_cut = 0.0
  3515. #
  3516. # while abs(self.z_cut) < abs(doc):
  3517. #
  3518. # self.z_cut -= self.z_depthpercut
  3519. # if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  3520. # self.z_cut = doc
  3521. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3522. #
  3523. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3524. #
  3525. # if self.f_retract is False:
  3526. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3527. # measured_up_to_zero_distance += abs(self.z_cut)
  3528. # measured_lift_distance += abs(self.z_move)
  3529. # else:
  3530. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3531. #
  3532. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3533. #
  3534. # else:
  3535. # gcode += self.doformat(p.down_code, x=locx, y=locy)
  3536. #
  3537. # measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  3538. #
  3539. # if self.f_retract is False:
  3540. # gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  3541. # measured_up_to_zero_distance += abs(self.z_cut)
  3542. # measured_lift_distance += abs(self.z_move)
  3543. # else:
  3544. # measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  3545. #
  3546. # gcode += self.doformat(p.lift_code, x=locx, y=locy)
  3547. #
  3548. # measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  3549. # self.oldx = locx
  3550. # self.oldy = locy
  3551. #
  3552. # loc_nr += 1
  3553. # disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  3554. #
  3555. # if old_disp_number < disp_number <= 100:
  3556. # self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3557. # old_disp_number = disp_number
  3558. # else:
  3559. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  3560. # return 'fail'
  3561. # else:
  3562. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  3563. # "The loaded Excellon file has no drills ...")
  3564. # self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  3565. # return 'fail'
  3566. # self.z_cut = deepcopy(old_zcut)
  3567. # log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  3568. #
  3569. # else:
  3570. # log.debug("camlib.CNCJob.generate_from_excellon_by_tool(): Chosen drill optimization doesn't exist.")
  3571. # return 'fail'
  3572. # Spindle stop
  3573. gcode += self.doformat(p.spindle_stop_code)
  3574. # Move to End position
  3575. gcode += self.doformat(p.end_code, x=0, y=0)
  3576. # #############################################################################################################
  3577. # ############################# Calculate DISTANCE and ESTIMATED TIME #########################################
  3578. # #############################################################################################################
  3579. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  3580. log.debug("The total travel distance including travel to end position is: %s" %
  3581. str(measured_distance) + '\n')
  3582. self.travel_distance = measured_distance
  3583. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  3584. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  3585. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  3586. # Marlin preprocessor and derivatives.
  3587. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  3588. lift_time = measured_lift_distance / self.feedrate_rapid
  3589. traveled_time = measured_distance / self.feedrate_rapid
  3590. self.routing_time += lift_time + traveled_time
  3591. # #############################################################################################################
  3592. # ############################# Store the GCODE for further usage ############################################
  3593. # #############################################################################################################
  3594. self.gcode = gcode
  3595. self.app.inform.emit(_("Finished G-Code generation..."))
  3596. return 'OK'
  3597. def generate_from_multitool_geometry(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=1.0,
  3598. z_move=2.0, feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  3599. spindlespeed=None, spindledir='CW', dwell=False, dwelltime=1.0,
  3600. multidepth=False, depthpercut=None, toolchange=False, toolchangez=1.0,
  3601. toolchangexy="0.0, 0.0", extracut=False, extracut_length=0.2,
  3602. startz=None, endz=2.0, endxy='', pp_geometry_name=None, tool_no=1):
  3603. """
  3604. Algorithm to generate from multitool Geometry.
  3605. Algorithm description:
  3606. ----------------------
  3607. Uses RTree to find the nearest path to follow.
  3608. :param geometry:
  3609. :param append:
  3610. :param tooldia:
  3611. :param offset:
  3612. :param tolerance:
  3613. :param z_cut:
  3614. :param z_move:
  3615. :param feedrate:
  3616. :param feedrate_z:
  3617. :param feedrate_rapid:
  3618. :param spindlespeed:
  3619. :param spindledir: Direction of rotation for the spindle. If using GRBL laser mode will
  3620. adjust the laser mode
  3621. :param dwell:
  3622. :param dwelltime:
  3623. :param multidepth: If True, use multiple passes to reach the desired depth.
  3624. :param depthpercut: Maximum depth in each pass.
  3625. :param toolchange:
  3626. :param toolchangez:
  3627. :param toolchangexy:
  3628. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the
  3629. first point in path to ensure complete copper removal
  3630. :param extracut_length: Extra cut legth at the end of the path
  3631. :param startz:
  3632. :param endz:
  3633. :param endxy:
  3634. :param pp_geometry_name:
  3635. :param tool_no:
  3636. :return: GCode - string
  3637. """
  3638. log.debug("Generate_from_multitool_geometry()")
  3639. temp_solid_geometry = []
  3640. if offset != 0.0:
  3641. for it in geometry:
  3642. # if the geometry is a closed shape then create a Polygon out of it
  3643. if isinstance(it, LineString):
  3644. c = it.coords
  3645. if c[0] == c[-1]:
  3646. it = Polygon(it)
  3647. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  3648. else:
  3649. temp_solid_geometry = geometry
  3650. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  3651. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  3652. log.debug("%d paths" % len(flat_geometry))
  3653. try:
  3654. self.tooldia = float(tooldia)
  3655. except Exception as e:
  3656. self.app.inform.emit('[ERROR] %s\n%s' % (_("Failed."), str(e)))
  3657. return 'fail'
  3658. self.z_cut = float(z_cut) if z_cut else None
  3659. self.z_move = float(z_move) if z_move is not None else None
  3660. self.feedrate = float(feedrate) if feedrate else self.app.defaults["geometry_feedrate"]
  3661. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  3662. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else self.app.defaults["geometry_feedrate_rapid"]
  3663. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 else None
  3664. self.spindledir = spindledir
  3665. self.dwell = dwell
  3666. self.dwelltime = float(dwelltime) if dwelltime else self.app.defaults["geometry_dwelltime"]
  3667. self.startz = float(startz) if startz is not None else self.app.defaults["geometry_startz"]
  3668. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  3669. self.xy_end = re.sub('[()\[\]]', '', str(endxy)) if endxy else self.app.defaults["geometry_endxy"]
  3670. if self.xy_end and self.xy_end != '':
  3671. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  3672. if self.xy_end and len(self.xy_end) < 2:
  3673. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  3674. "in the format (x, y) but now there is only one value, not two."))
  3675. return 'fail'
  3676. self.z_depthpercut = float(depthpercut) if depthpercut else self.app.defaults["geometry_depthperpass"]
  3677. self.multidepth = multidepth
  3678. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  3679. # it servers in the preprocessor file
  3680. self.tool = tool_no
  3681. try:
  3682. if toolchangexy == '':
  3683. self.xy_toolchange = None
  3684. else:
  3685. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) \
  3686. if toolchangexy else self.app.defaults["geometry_toolchangexy"]
  3687. if self.xy_toolchange and self.xy_toolchange != '':
  3688. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  3689. if len(self.xy_toolchange) < 2:
  3690. self.app.inform.emit('[ERROR] %s' % _("The Toolchange X,Y field in Edit -> Preferences has to be "
  3691. "in the format (x, y) \n"
  3692. "but now there is only one value, not two."))
  3693. return 'fail'
  3694. except Exception as e:
  3695. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  3696. pass
  3697. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  3698. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  3699. if self.z_cut is None:
  3700. if 'laser' not in self.pp_geometry_name:
  3701. self.app.inform.emit(
  3702. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  3703. "other parameters."))
  3704. return 'fail'
  3705. else:
  3706. self.z_cut = 0
  3707. if self.machinist_setting == 0:
  3708. if self.z_cut > 0:
  3709. self.app.inform.emit('[WARNING] %s' %
  3710. _("The Cut Z parameter has positive value. "
  3711. "It is the depth value to cut into material.\n"
  3712. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  3713. "therefore the app will convert the value to negative."
  3714. "Check the resulting CNC code (Gcode etc)."))
  3715. self.z_cut = -self.z_cut
  3716. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  3717. self.app.inform.emit('[WARNING] %s: %s' %
  3718. (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  3719. self.options['name']))
  3720. return 'fail'
  3721. if self.z_move is None:
  3722. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  3723. return 'fail'
  3724. if self.z_move < 0:
  3725. self.app.inform.emit('[WARNING] %s' %
  3726. _("The Travel Z parameter has negative value. "
  3727. "It is the height value to travel between cuts.\n"
  3728. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  3729. "therefore the app will convert the value to positive."
  3730. "Check the resulting CNC code (Gcode etc)."))
  3731. self.z_move = -self.z_move
  3732. elif self.z_move == 0:
  3733. self.app.inform.emit('[WARNING] %s: %s' %
  3734. (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  3735. self.options['name']))
  3736. return 'fail'
  3737. # made sure that depth_per_cut is no more then the z_cut
  3738. if abs(self.z_cut) < self.z_depthpercut:
  3739. self.z_depthpercut = abs(self.z_cut)
  3740. # ## Index first and last points in paths
  3741. # What points to index.
  3742. def get_pts(o):
  3743. return [o.coords[0], o.coords[-1]]
  3744. # Create the indexed storage.
  3745. storage = FlatCAMRTreeStorage()
  3746. storage.get_points = get_pts
  3747. # Store the geometry
  3748. log.debug("Indexing geometry before generating G-Code...")
  3749. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  3750. for geo_shape in flat_geometry:
  3751. if self.app.abort_flag:
  3752. # graceful abort requested by the user
  3753. raise grace
  3754. if geo_shape is not None:
  3755. storage.insert(geo_shape)
  3756. # self.input_geometry_bounds = geometry.bounds()
  3757. if not append:
  3758. self.gcode = ""
  3759. # tell preprocessor the number of tool (for toolchange)
  3760. self.tool = tool_no
  3761. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  3762. # given under the name 'toolC'
  3763. self.postdata['toolC'] = self.tooldia
  3764. # Initial G-Code
  3765. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  3766. p = self.pp_geometry
  3767. self.gcode = self.doformat(p.start_code)
  3768. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  3769. if toolchange is False:
  3770. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  3771. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  3772. if toolchange:
  3773. # if "line_xyz" in self.pp_geometry_name:
  3774. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  3775. # else:
  3776. # self.gcode += self.doformat(p.toolchange_code)
  3777. self.gcode += self.doformat(p.toolchange_code)
  3778. if 'laser' not in self.pp_geometry_name:
  3779. self.gcode += self.doformat(p.spindle_code) # Spindle start
  3780. else:
  3781. # for laser this will disable the laser
  3782. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  3783. if self.dwell is True:
  3784. self.gcode += self.doformat(p.dwell_code) # Dwell time
  3785. else:
  3786. if 'laser' not in self.pp_geometry_name:
  3787. self.gcode += self.doformat(p.spindle_code) # Spindle start
  3788. if self.dwell is True:
  3789. self.gcode += self.doformat(p.dwell_code) # Dwell time
  3790. total_travel = 0.0
  3791. total_cut = 0.0
  3792. # ## Iterate over geometry paths getting the nearest each time.
  3793. log.debug("Starting G-Code...")
  3794. self.app.inform.emit('%s...' % _("Starting G-Code"))
  3795. path_count = 0
  3796. current_pt = (0, 0)
  3797. # variables to display the percentage of work done
  3798. geo_len = len(flat_geometry)
  3799. old_disp_number = 0
  3800. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  3801. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  3802. self.app.inform.emit('%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  3803. str(current_tooldia),
  3804. str(self.units)))
  3805. pt, geo = storage.nearest(current_pt)
  3806. try:
  3807. while True:
  3808. if self.app.abort_flag:
  3809. # graceful abort requested by the user
  3810. raise grace
  3811. path_count += 1
  3812. # Remove before modifying, otherwise deletion will fail.
  3813. storage.remove(geo)
  3814. # If last point in geometry is the nearest but prefer the first one if last point == first point
  3815. # then reverse coordinates.
  3816. if pt != geo.coords[0] and pt == geo.coords[-1]:
  3817. geo.coords = list(geo.coords)[::-1]
  3818. # ---------- Single depth/pass --------
  3819. if not multidepth:
  3820. # calculate the cut distance
  3821. total_cut = total_cut + geo.length
  3822. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, extracut_length,
  3823. tolerance, z_move=z_move, old_point=current_pt)
  3824. # --------- Multi-pass ---------
  3825. else:
  3826. # calculate the cut distance
  3827. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  3828. nr_cuts = 0
  3829. depth = abs(self.z_cut)
  3830. while depth > 0:
  3831. nr_cuts += 1
  3832. depth -= float(self.z_depthpercut)
  3833. total_cut += (geo.length * nr_cuts)
  3834. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, extracut_length,
  3835. tolerance, z_move=z_move, postproc=p,
  3836. old_point=current_pt)
  3837. # calculate the total distance
  3838. total_travel = total_travel + abs(distance(pt1=current_pt, pt2=pt))
  3839. current_pt = geo.coords[-1]
  3840. pt, geo = storage.nearest(current_pt) # Next
  3841. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  3842. if old_disp_number < disp_number <= 100:
  3843. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  3844. old_disp_number = disp_number
  3845. except StopIteration: # Nothing found in storage.
  3846. pass
  3847. log.debug("Finished G-Code... %s paths traced." % path_count)
  3848. # add move to end position
  3849. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  3850. self.travel_distance += total_travel + total_cut
  3851. self.routing_time += total_cut / self.feedrate
  3852. # Finish
  3853. self.gcode += self.doformat(p.spindle_stop_code)
  3854. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  3855. self.gcode += self.doformat(p.end_code, x=0, y=0)
  3856. self.app.inform.emit(
  3857. '%s... %s %s.' % (_("Finished G-Code generation"), str(path_count), _("paths traced"))
  3858. )
  3859. return self.gcode
  3860. def generate_from_geometry_2(self, geometry, append=True, tooldia=None, offset=0.0, tolerance=0, z_cut=None,
  3861. z_move=None, feedrate=None, feedrate_z=None, feedrate_rapid=None, spindlespeed=None,
  3862. spindledir='CW', dwell=False, dwelltime=None, multidepth=False, depthpercut=None,
  3863. toolchange=False, toolchangez=None, toolchangexy="0.0, 0.0", extracut=False,
  3864. extracut_length=None, startz=None, endz=None, endxy='', pp_geometry_name=None,
  3865. tool_no=1):
  3866. """
  3867. Second algorithm to generate from Geometry.
  3868. Algorithm description:
  3869. ----------------------
  3870. Uses RTree to find the nearest path to follow.
  3871. :param geometry:
  3872. :param append:
  3873. :param tooldia:
  3874. :param offset:
  3875. :param tolerance:
  3876. :param z_cut:
  3877. :param z_move:
  3878. :param feedrate:
  3879. :param feedrate_z:
  3880. :param feedrate_rapid:
  3881. :param spindlespeed:
  3882. :param spindledir:
  3883. :param dwell:
  3884. :param dwelltime:
  3885. :param multidepth: If True, use multiple passes to reach the desired depth.
  3886. :param depthpercut: Maximum depth in each pass.
  3887. :param toolchange:
  3888. :param toolchangez:
  3889. :param toolchangexy:
  3890. :param extracut: Adds (or not) an extra cut at the end of each path overlapping the first point in
  3891. path to ensure complete copper removal
  3892. :param extracut_length: The extra cut length
  3893. :param startz:
  3894. :param endz:
  3895. :param endxy:
  3896. :param pp_geometry_name:
  3897. :param tool_no:
  3898. :return: None
  3899. """
  3900. if not isinstance(geometry, Geometry):
  3901. self.app.inform.emit('[ERROR] %s: %s' % (_("Expected a Geometry, got"), type(geometry)))
  3902. return 'fail'
  3903. log.debug("Executing camlib.CNCJob.generate_from_geometry_2()")
  3904. # if solid_geometry is empty raise an exception
  3905. if not geometry.solid_geometry:
  3906. self.app.inform.emit(
  3907. '[ERROR_NOTCL] %s' % _("Trying to generate a CNC Job from a Geometry object without solid_geometry.")
  3908. )
  3909. temp_solid_geometry = []
  3910. def bounds_rec(obj):
  3911. if type(obj) is list:
  3912. minx = np.Inf
  3913. miny = np.Inf
  3914. maxx = -np.Inf
  3915. maxy = -np.Inf
  3916. for k in obj:
  3917. if type(k) is dict:
  3918. for key in k:
  3919. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3920. minx = min(minx, minx_)
  3921. miny = min(miny, miny_)
  3922. maxx = max(maxx, maxx_)
  3923. maxy = max(maxy, maxy_)
  3924. else:
  3925. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3926. minx = min(minx, minx_)
  3927. miny = min(miny, miny_)
  3928. maxx = max(maxx, maxx_)
  3929. maxy = max(maxy, maxy_)
  3930. return minx, miny, maxx, maxy
  3931. else:
  3932. # it's a Shapely object, return it's bounds
  3933. return obj.bounds
  3934. if offset != 0.0:
  3935. offset_for_use = offset
  3936. if offset < 0:
  3937. a, b, c, d = bounds_rec(geometry.solid_geometry)
  3938. # if the offset is less than half of the total length or less than half of the total width of the
  3939. # solid geometry it's obvious we can't do the offset
  3940. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  3941. self.app.inform.emit(
  3942. '[ERROR_NOTCL] %s' %
  3943. _("The Tool Offset value is too negative to use for the current_geometry.\n"
  3944. "Raise the value (in module) and try again.")
  3945. )
  3946. return 'fail'
  3947. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  3948. # to continue
  3949. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  3950. offset_for_use = offset - 0.0000000001
  3951. for it in geometry.solid_geometry:
  3952. # if the geometry is a closed shape then create a Polygon out of it
  3953. if isinstance(it, LineString):
  3954. c = it.coords
  3955. if c[0] == c[-1]:
  3956. it = Polygon(it)
  3957. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  3958. else:
  3959. temp_solid_geometry = geometry.solid_geometry
  3960. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  3961. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  3962. log.debug("%d paths" % len(flat_geometry))
  3963. default_dia = None
  3964. if isinstance(self.app.defaults["geometry_cnctooldia"], float):
  3965. default_dia = self.app.defaults["geometry_cnctooldia"]
  3966. else:
  3967. try:
  3968. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  3969. tools_diameters = [eval(a) for a in tools_string if a != '']
  3970. default_dia = tools_diameters[0] if tools_diameters else 0.0
  3971. except Exception as e:
  3972. self.app.log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  3973. try:
  3974. self.tooldia = float(tooldia) if tooldia else default_dia
  3975. except ValueError:
  3976. self.tooldia = [float(el) for el in tooldia.split(',') if el != ''] if tooldia is not None else default_dia
  3977. if self.tooldia is None:
  3978. self.app.inform.emit('[ERROR] %s' % _("Failed."))
  3979. return 'fail'
  3980. self.z_cut = float(z_cut) if z_cut is not None else self.app.defaults["geometry_cutz"]
  3981. self.z_move = float(z_move) if z_move is not None else self.app.defaults["geometry_travelz"]
  3982. self.feedrate = float(feedrate) if feedrate is not None else self.app.defaults["geometry_feedrate"]
  3983. self.z_feedrate = float(feedrate_z) if feedrate_z is not None else self.app.defaults["geometry_feedrate_z"]
  3984. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid is not None else \
  3985. self.app.defaults["geometry_feedrate_rapid"]
  3986. self.spindlespeed = int(spindlespeed) if spindlespeed != 0 and spindlespeed is not None else None
  3987. self.spindledir = spindledir
  3988. self.dwell = dwell
  3989. self.dwelltime = float(dwelltime) if dwelltime is not None else self.app.defaults["geometry_dwelltime"]
  3990. self.startz = float(startz) if startz is not None and startz != '' else self.app.defaults["geometry_startz"]
  3991. self.z_end = float(endz) if endz is not None else self.app.defaults["geometry_endz"]
  3992. self.xy_end = endxy if endxy != '' and endxy else self.app.defaults["geometry_endxy"]
  3993. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  3994. if self.xy_end is not None and self.xy_end != '':
  3995. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  3996. if self.xy_end and len(self.xy_end) < 2:
  3997. self.app.inform.emit('[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  3998. "in the format (x, y) but now there is only one value, not two."))
  3999. return 'fail'
  4000. self.z_depthpercut = float(depthpercut) if depthpercut is not None and depthpercut != 0 else abs(self.z_cut)
  4001. self.multidepth = multidepth
  4002. self.z_toolchange = float(toolchangez) if toolchangez is not None else self.app.defaults["geometry_toolchangez"]
  4003. self.extracut_length = float(extracut_length) if extracut_length is not None else \
  4004. self.app.defaults["geometry_extracut_length"]
  4005. try:
  4006. if toolchangexy == '':
  4007. self.xy_toolchange = None
  4008. else:
  4009. self.xy_toolchange = re.sub('[()\[\]]', '', str(toolchangexy)) if self.xy_toolchange else None
  4010. if self.xy_toolchange and self.xy_toolchange != '':
  4011. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  4012. if len(self.xy_toolchange) < 2:
  4013. msg = _("The Toolchange X,Y field in Edit -> Preferences has to be in the format (x, y)\n"
  4014. "but now there is only one value, not two.")
  4015. self.app.inform.emit('[ERROR] %s' % msg)
  4016. return 'fail'
  4017. except Exception as e:
  4018. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4019. pass
  4020. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4021. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4022. if self.machinist_setting == 0:
  4023. if self.z_cut is None:
  4024. if 'laser' not in self.pp_geometry_name:
  4025. self.app.inform.emit(
  4026. '[ERROR_NOTCL] %s' % _("Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4027. "other parameters.")
  4028. )
  4029. return 'fail'
  4030. else:
  4031. self.z_cut = 0.0
  4032. if self.z_cut > 0:
  4033. self.app.inform.emit('[WARNING] %s' %
  4034. _("The Cut Z parameter has positive value. "
  4035. "It is the depth value to cut into material.\n"
  4036. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4037. "therefore the app will convert the value to negative."
  4038. "Check the resulting CNC code (Gcode etc)."))
  4039. self.z_cut = -self.z_cut
  4040. elif self.z_cut == 0 and 'laser' not in self.pp_geometry_name:
  4041. self.app.inform.emit(
  4042. '[WARNING] %s: %s' % (_("The Cut Z parameter is zero. There will be no cut, skipping file"),
  4043. geometry.options['name'])
  4044. )
  4045. return 'fail'
  4046. if self.z_move is None:
  4047. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Travel Z parameter is None or zero."))
  4048. return 'fail'
  4049. if self.z_move < 0:
  4050. self.app.inform.emit('[WARNING] %s' %
  4051. _("The Travel Z parameter has negative value. "
  4052. "It is the height value to travel between cuts.\n"
  4053. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4054. "therefore the app will convert the value to positive."
  4055. "Check the resulting CNC code (Gcode etc)."))
  4056. self.z_move = -self.z_move
  4057. elif self.z_move == 0:
  4058. self.app.inform.emit(
  4059. '[WARNING] %s: %s' % (_("The Z Travel parameter is zero. This is dangerous, skipping file"),
  4060. self.options['name'])
  4061. )
  4062. return 'fail'
  4063. # made sure that depth_per_cut is no more then the z_cut
  4064. try:
  4065. if abs(self.z_cut) < self.z_depthpercut:
  4066. self.z_depthpercut = abs(self.z_cut)
  4067. except TypeError:
  4068. self.z_depthpercut = abs(self.z_cut)
  4069. # ## Index first and last points in paths
  4070. # What points to index.
  4071. def get_pts(o):
  4072. return [o.coords[0], o.coords[-1]]
  4073. # Create the indexed storage.
  4074. storage = FlatCAMRTreeStorage()
  4075. storage.get_points = get_pts
  4076. # Store the geometry
  4077. log.debug("Indexing geometry before generating G-Code...")
  4078. self.app.inform.emit(_("Indexing geometry before generating G-Code..."))
  4079. for geo_shape in flat_geometry:
  4080. if self.app.abort_flag:
  4081. # graceful abort requested by the user
  4082. raise grace
  4083. if geo_shape is not None:
  4084. storage.insert(geo_shape)
  4085. if not append:
  4086. self.gcode = ""
  4087. # tell preprocessor the number of tool (for toolchange)
  4088. self.tool = tool_no
  4089. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4090. # given under the name 'toolC'
  4091. # this is a fancy way of adding a class attribute (which should be added in the __init__ method) without doing
  4092. # it there :)
  4093. self.postdata['toolC'] = self.tooldia
  4094. # Initial G-Code
  4095. self.pp_geometry = self.app.preprocessors[self.pp_geometry_name]
  4096. # the 'p' local attribute is a reference to the current preprocessor class
  4097. p = self.pp_geometry
  4098. self.oldx = 0.0
  4099. self.oldy = 0.0
  4100. self.gcode = self.doformat(p.start_code)
  4101. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4102. if toolchange is False:
  4103. # all the x and y parameters in self.doformat() are used only by some preprocessors not by all
  4104. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4105. self.gcode += self.doformat(p.startz_code, x=self.oldx, y=self.oldy)
  4106. if toolchange:
  4107. # if "line_xyz" in self.pp_geometry_name:
  4108. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4109. # else:
  4110. # self.gcode += self.doformat(p.toolchange_code)
  4111. self.gcode += self.doformat(p.toolchange_code)
  4112. if 'laser' not in self.pp_geometry_name:
  4113. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4114. else:
  4115. # for laser this will disable the laser
  4116. self.gcode += self.doformat(p.lift_code, x=self.oldx, y=self.oldy) # Move (up) to travel height
  4117. if self.dwell is True:
  4118. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4119. else:
  4120. if 'laser' not in self.pp_geometry_name:
  4121. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4122. if self.dwell is True:
  4123. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4124. total_travel = 0.0
  4125. total_cut = 0.0
  4126. # Iterate over geometry paths getting the nearest each time.
  4127. log.debug("Starting G-Code...")
  4128. self.app.inform.emit('%s...' % _("Starting G-Code"))
  4129. # variables to display the percentage of work done
  4130. geo_len = len(flat_geometry)
  4131. old_disp_number = 0
  4132. log.warning("Number of paths for which to generate GCode: %s" % str(geo_len))
  4133. current_tooldia = float('%.*f' % (self.decimals, float(self.tooldia)))
  4134. self.app.inform.emit(
  4135. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"), str(current_tooldia), str(self.units))
  4136. )
  4137. path_count = 0
  4138. current_pt = (0, 0)
  4139. pt, geo = storage.nearest(current_pt)
  4140. # when nothing is left in the storage a StopIteration exception will be raised therefore stopping
  4141. # the whole process including the infinite loop while True below.
  4142. try:
  4143. while True:
  4144. if self.app.abort_flag:
  4145. # graceful abort requested by the user
  4146. raise grace
  4147. path_count += 1
  4148. # Remove before modifying, otherwise deletion will fail.
  4149. storage.remove(geo)
  4150. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4151. # then reverse coordinates.
  4152. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4153. geo.coords = list(geo.coords)[::-1]
  4154. # ---------- Single depth/pass --------
  4155. if not multidepth:
  4156. # calculate the cut distance
  4157. total_cut += geo.length
  4158. self.gcode += self.create_gcode_single_pass(geo, current_tooldia, extracut, self.extracut_length,
  4159. tolerance, z_move=z_move, old_point=current_pt)
  4160. # --------- Multi-pass ---------
  4161. else:
  4162. # calculate the cut distance
  4163. # due of the number of cuts (multi depth) it has to multiplied by the number of cuts
  4164. nr_cuts = 0
  4165. depth = abs(self.z_cut)
  4166. while depth > 0:
  4167. nr_cuts += 1
  4168. depth -= float(self.z_depthpercut)
  4169. total_cut += (geo.length * nr_cuts)
  4170. self.gcode += self.create_gcode_multi_pass(geo, current_tooldia, extracut, self.extracut_length,
  4171. tolerance, z_move=z_move, postproc=p,
  4172. old_point=current_pt)
  4173. # calculate the travel distance
  4174. total_travel += abs(distance(pt1=current_pt, pt2=pt))
  4175. current_pt = geo.coords[-1]
  4176. pt, geo = storage.nearest(current_pt) # Next
  4177. # update the activity counter (lower left side of the app, status bar)
  4178. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4179. if old_disp_number < disp_number <= 100:
  4180. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4181. old_disp_number = disp_number
  4182. except StopIteration: # Nothing found in storage.
  4183. pass
  4184. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4185. # add move to end position
  4186. total_travel += abs(distance_euclidian(current_pt[0], current_pt[1], 0, 0))
  4187. self.travel_distance += total_travel + total_cut
  4188. self.routing_time += total_cut / self.feedrate
  4189. # Finish
  4190. self.gcode += self.doformat(p.spindle_stop_code)
  4191. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4192. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4193. self.app.inform.emit(
  4194. '%s... %s %s' % (_("Finished G-Code generation"), str(path_count), _(" paths traced."))
  4195. )
  4196. return self.gcode
  4197. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  4198. """
  4199. Algorithm to generate from multitool Geometry.
  4200. Algorithm description:
  4201. ----------------------
  4202. Uses RTree to find the nearest path to follow.
  4203. :return: Gcode string
  4204. """
  4205. log.debug("Generate_from_solderpaste_geometry()")
  4206. # ## Index first and last points in paths
  4207. # What points to index.
  4208. def get_pts(o):
  4209. return [o.coords[0], o.coords[-1]]
  4210. self.gcode = ""
  4211. if not kwargs:
  4212. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  4213. self.app.inform.emit('[ERROR_NOTCL] %s' %
  4214. _("There is no tool data in the SolderPaste geometry."))
  4215. # this is the tool diameter, it is used as such to accommodate the preprocessor who need the tool diameter
  4216. # given under the name 'toolC'
  4217. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  4218. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  4219. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  4220. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  4221. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  4222. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  4223. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  4224. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  4225. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  4226. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  4227. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  4228. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  4229. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  4230. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  4231. self.postdata['toolC'] = kwargs['tooldia']
  4232. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  4233. else self.app.defaults['tools_solderpaste_pp']
  4234. p = self.app.preprocessors[self.pp_solderpaste_name]
  4235. # ## Flatten the geometry. Only linear elements (no polygons) remain.
  4236. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  4237. log.debug("%d paths" % len(flat_geometry))
  4238. # Create the indexed storage.
  4239. storage = FlatCAMRTreeStorage()
  4240. storage.get_points = get_pts
  4241. # Store the geometry
  4242. log.debug("Indexing geometry before generating G-Code...")
  4243. for geo_shape in flat_geometry:
  4244. if self.app.abort_flag:
  4245. # graceful abort requested by the user
  4246. raise grace
  4247. if geo_shape is not None:
  4248. storage.insert(geo_shape)
  4249. # Initial G-Code
  4250. self.gcode = self.doformat(p.start_code)
  4251. self.gcode += self.doformat(p.spindle_off_code)
  4252. self.gcode += self.doformat(p.toolchange_code)
  4253. # ## Iterate over geometry paths getting the nearest each time.
  4254. log.debug("Starting SolderPaste G-Code...")
  4255. path_count = 0
  4256. current_pt = (0, 0)
  4257. # variables to display the percentage of work done
  4258. geo_len = len(flat_geometry)
  4259. old_disp_number = 0
  4260. pt, geo = storage.nearest(current_pt)
  4261. try:
  4262. while True:
  4263. if self.app.abort_flag:
  4264. # graceful abort requested by the user
  4265. raise grace
  4266. path_count += 1
  4267. # Remove before modifying, otherwise deletion will fail.
  4268. storage.remove(geo)
  4269. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4270. # then reverse coordinates.
  4271. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4272. geo.coords = list(geo.coords)[::-1]
  4273. self.gcode += self.create_soldepaste_gcode(geo, p=p, old_point=current_pt)
  4274. current_pt = geo.coords[-1]
  4275. pt, geo = storage.nearest(current_pt) # Next
  4276. disp_number = int(np.interp(path_count, [0, geo_len], [0, 100]))
  4277. if old_disp_number < disp_number <= 100:
  4278. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  4279. old_disp_number = disp_number
  4280. except StopIteration: # Nothing found in storage.
  4281. pass
  4282. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  4283. self.app.inform.emit(
  4284. '%s... %s %s' % (_("Finished SolderPaste G-Code generation"), str(path_count), _("paths traced."))
  4285. )
  4286. # Finish
  4287. self.gcode += self.doformat(p.lift_code)
  4288. self.gcode += self.doformat(p.end_code)
  4289. return self.gcode
  4290. def create_soldepaste_gcode(self, geometry, p, old_point=(0, 0)):
  4291. gcode = ''
  4292. path = geometry.coords
  4293. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4294. if self.coordinates_type == "G90":
  4295. # For Absolute coordinates type G90
  4296. first_x = path[0][0]
  4297. first_y = path[0][1]
  4298. else:
  4299. # For Incremental coordinates type G91
  4300. first_x = path[0][0] - old_point[0]
  4301. first_y = path[0][1] - old_point[1]
  4302. if type(geometry) == LineString or type(geometry) == LinearRing:
  4303. # Move fast to 1st point
  4304. gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  4305. # Move down to cutting depth
  4306. gcode += self.doformat(p.z_feedrate_code)
  4307. gcode += self.doformat(p.down_z_start_code)
  4308. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4309. gcode += self.doformat(p.dwell_fwd_code)
  4310. gcode += self.doformat(p.feedrate_z_dispense_code)
  4311. gcode += self.doformat(p.lift_z_dispense_code)
  4312. gcode += self.doformat(p.feedrate_xy_code)
  4313. # Cutting...
  4314. prev_x = first_x
  4315. prev_y = first_y
  4316. for pt in path[1:]:
  4317. if self.coordinates_type == "G90":
  4318. # For Absolute coordinates type G90
  4319. next_x = pt[0]
  4320. next_y = pt[1]
  4321. else:
  4322. # For Incremental coordinates type G91
  4323. next_x = pt[0] - prev_x
  4324. next_y = pt[1] - prev_y
  4325. gcode += self.doformat(p.linear_code, x=next_x, y=next_y) # Linear motion to point
  4326. prev_x = next_x
  4327. prev_y = next_y
  4328. # Up to travelling height.
  4329. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  4330. gcode += self.doformat(p.spindle_rev_code)
  4331. gcode += self.doformat(p.down_z_stop_code)
  4332. gcode += self.doformat(p.spindle_off_code)
  4333. gcode += self.doformat(p.dwell_rev_code)
  4334. gcode += self.doformat(p.z_feedrate_code)
  4335. gcode += self.doformat(p.lift_code)
  4336. elif type(geometry) == Point:
  4337. gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  4338. gcode += self.doformat(p.feedrate_z_dispense_code)
  4339. gcode += self.doformat(p.down_z_start_code)
  4340. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4341. gcode += self.doformat(p.dwell_fwd_code)
  4342. gcode += self.doformat(p.lift_z_dispense_code)
  4343. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  4344. gcode += self.doformat(p.spindle_rev_code)
  4345. gcode += self.doformat(p.spindle_off_code)
  4346. gcode += self.doformat(p.down_z_stop_code)
  4347. gcode += self.doformat(p.dwell_rev_code)
  4348. gcode += self.doformat(p.z_feedrate_code)
  4349. gcode += self.doformat(p.lift_code)
  4350. return gcode
  4351. def create_gcode_single_pass(self, geometry, cdia, extracut, extracut_length, tolerance, z_move, old_point=(0, 0)):
  4352. """
  4353. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  4354. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  4355. :type geometry: LineString, LinearRing
  4356. :param cdia: Tool diameter
  4357. :type cdia: float
  4358. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  4359. :type extracut: bool
  4360. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  4361. :type extracut_length: float
  4362. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  4363. :type tolerance: float
  4364. :param z_move: Travel Z
  4365. :type z_move: float
  4366. :param old_point: Previous point
  4367. :type old_point: tuple
  4368. :return: Gcode
  4369. :rtype: str
  4370. """
  4371. # p = postproc
  4372. if type(geometry) == LineString or type(geometry) == LinearRing:
  4373. if extracut is False or not geometry.is_ring:
  4374. gcode_single_pass = self.linear2gcode(geometry, cdia, z_move=z_move, tolerance=tolerance,
  4375. old_point=old_point)
  4376. else:
  4377. gcode_single_pass = self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  4378. z_move=z_move, old_point=old_point)
  4379. elif type(geometry) == Point:
  4380. gcode_single_pass = self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  4381. else:
  4382. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  4383. return
  4384. return gcode_single_pass
  4385. def create_gcode_multi_pass(self, geometry, cdia, extracut, extracut_length, tolerance, postproc, z_move,
  4386. old_point=(0, 0)):
  4387. """
  4388. :param geometry: A Shapely Geometry (LineString or LinearRing) which is the path to be cut
  4389. :type geometry: LineString, LinearRing
  4390. :param cdia: Tool diameter
  4391. :type cdia: float
  4392. :param extracut: Will add an extra cut over the point where start of the cut is met with the end cut
  4393. :type extracut: bool
  4394. :param extracut_length: The length of the extra cut: half before the meeting point, half after
  4395. :type extracut_length: float
  4396. :param tolerance: Tolerance used to simplify the paths (making them mre rough)
  4397. :type tolerance: float
  4398. :param postproc: Preprocessor class
  4399. :type postproc: class
  4400. :param z_move: Travel Z
  4401. :type z_move: float
  4402. :param old_point: Previous point
  4403. :type old_point: tuple
  4404. :return: Gcode
  4405. :rtype: str
  4406. """
  4407. p = postproc
  4408. gcode_multi_pass = ''
  4409. if isinstance(self.z_cut, Decimal):
  4410. z_cut = self.z_cut
  4411. else:
  4412. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  4413. if self.z_depthpercut is None:
  4414. self.z_depthpercut = z_cut
  4415. elif not isinstance(self.z_depthpercut, Decimal):
  4416. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  4417. depth = 0
  4418. reverse = False
  4419. while depth > z_cut:
  4420. # Increase depth. Limit to z_cut.
  4421. depth -= self.z_depthpercut
  4422. if depth < z_cut:
  4423. depth = z_cut
  4424. # Cut at specific depth and do not lift the tool.
  4425. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  4426. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  4427. # is inconsequential.
  4428. if type(geometry) == LineString or type(geometry) == LinearRing:
  4429. if extracut is False or not geometry.is_ring:
  4430. gcode_multi_pass += self.linear2gcode(geometry, cdia, tolerance=tolerance, z_cut=depth, up=False,
  4431. z_move=z_move, old_point=old_point)
  4432. else:
  4433. gcode_multi_pass += self.linear2gcode_extra(geometry, cdia, extracut_length, tolerance=tolerance,
  4434. z_move=z_move, z_cut=depth, up=False,
  4435. old_point=old_point)
  4436. # Ignore multi-pass for points.
  4437. elif type(geometry) == Point:
  4438. gcode_multi_pass += self.point2gcode(geometry, cdia, z_move=z_move, old_point=old_point)
  4439. break # Ignoring ...
  4440. else:
  4441. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  4442. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  4443. if type(geometry) == LineString:
  4444. geometry.coords = list(geometry.coords)[::-1]
  4445. reverse = True
  4446. # If geometry is reversed, revert.
  4447. if reverse:
  4448. if type(geometry) == LineString:
  4449. geometry.coords = list(geometry.coords)[::-1]
  4450. # Lift the tool
  4451. gcode_multi_pass += self.doformat(p.lift_code, x=old_point[0], y=old_point[1])
  4452. return gcode_multi_pass
  4453. def codes_split(self, gline):
  4454. """
  4455. Parses a line of G-Code such as "G01 X1234 Y987" into
  4456. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  4457. :param gline: G-Code line string
  4458. :type gline: str
  4459. :return: Dictionary with parsed line.
  4460. :rtype: dict
  4461. """
  4462. command = {}
  4463. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4464. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  4465. if match_z:
  4466. command['G'] = 0
  4467. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  4468. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  4469. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  4470. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  4471. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  4472. if match_pa:
  4473. command['G'] = 0
  4474. command['X'] = float(match_pa.group(1).replace(" ", "")) / 40
  4475. command['Y'] = float(match_pa.group(2).replace(" ", "")) / 40
  4476. match_pen = re.search(r"^(P[U|D])", gline)
  4477. if match_pen:
  4478. if match_pen.group(1) == 'PU':
  4479. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  4480. # therefore the move is of kind T (travel)
  4481. command['Z'] = 1
  4482. else:
  4483. command['Z'] = 0
  4484. elif 'laser' in self.pp_excellon_name.lower() or 'laser' in self.pp_geometry_name.lower() or \
  4485. (self.pp_solderpaste_name is not None and 'paste' in self.pp_solderpaste_name.lower()):
  4486. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  4487. if match_lsr:
  4488. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  4489. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  4490. match_lsr_pos = re.search(r"^(M0?[3-5])", gline)
  4491. if match_lsr_pos:
  4492. if 'M05' in match_lsr_pos.group(1) or 'M5' in match_lsr_pos.group(1):
  4493. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  4494. # therefore the move is of kind T (travel)
  4495. command['Z'] = 1
  4496. else:
  4497. command['Z'] = 0
  4498. match_lsr_pos_2 = re.search(r"^(M10[6|7])", gline)
  4499. if match_lsr_pos_2:
  4500. if 'M107' in match_lsr_pos_2.group(1):
  4501. command['Z'] = 1
  4502. else:
  4503. command['Z'] = 0
  4504. elif self.pp_solderpaste_name is not None:
  4505. if 'Paste' in self.pp_solderpaste_name:
  4506. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  4507. if match_paste:
  4508. command['X'] = float(match_paste.group(1).replace(" ", ""))
  4509. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  4510. else:
  4511. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  4512. while match:
  4513. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  4514. gline = gline[match.end():]
  4515. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  4516. return command
  4517. def gcode_parse(self, force_parsing=None):
  4518. """
  4519. G-Code parser (from self.gcode). Generates dictionary with
  4520. single-segment LineString's and "kind" indicating cut or travel,
  4521. fast or feedrate speed.
  4522. Will return a dict in the format:
  4523. {
  4524. "geom": LineString(path),
  4525. "kind": kind
  4526. }
  4527. where kind can be either ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4528. :param force_parsing:
  4529. :type force_parsing:
  4530. :return:
  4531. :rtype: dict
  4532. """
  4533. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4534. # Results go here
  4535. geometry = []
  4536. # Last known instruction
  4537. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  4538. # Current path: temporary storage until tool is
  4539. # lifted or lowered.
  4540. if self.toolchange_xy_type == "excellon":
  4541. if self.app.defaults["excellon_toolchangexy"] == '' or self.app.defaults["excellon_toolchangexy"] is None:
  4542. pos_xy = (0, 0)
  4543. else:
  4544. pos_xy = self.app.defaults["excellon_toolchangexy"]
  4545. try:
  4546. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  4547. except Exception:
  4548. if len(pos_xy) != 2:
  4549. pos_xy = (0, 0)
  4550. else:
  4551. if self.app.defaults["geometry_toolchangexy"] == '' or self.app.defaults["geometry_toolchangexy"] is None:
  4552. pos_xy = (0, 0)
  4553. else:
  4554. pos_xy = self.app.defaults["geometry_toolchangexy"]
  4555. try:
  4556. pos_xy = [float(eval(a)) for a in pos_xy.split(",")]
  4557. except Exception:
  4558. if len(pos_xy) != 2:
  4559. pos_xy = (0, 0)
  4560. path = [pos_xy]
  4561. # path = [(0, 0)]
  4562. gcode_lines_list = self.gcode.splitlines()
  4563. self.app.inform.emit('%s: %d' % (_("Parsing GCode file. Number of lines"), len(gcode_lines_list)))
  4564. # Process every instruction
  4565. for line in gcode_lines_list:
  4566. if force_parsing is False or force_parsing is None:
  4567. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  4568. return "fail"
  4569. gobj = self.codes_split(line)
  4570. # ## Units
  4571. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  4572. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  4573. continue
  4574. # TODO take into consideration the tools and update the travel line thickness
  4575. if 'T' in gobj:
  4576. pass
  4577. # ## Changing height
  4578. if 'Z' in gobj:
  4579. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  4580. pass
  4581. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  4582. pass
  4583. elif 'laser' in self.pp_excellon_name or 'laser' in self.pp_geometry_name:
  4584. pass
  4585. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  4586. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  4587. pass
  4588. else:
  4589. log.warning("Non-orthogonal motion: From %s" % str(current))
  4590. log.warning(" To: %s" % str(gobj))
  4591. current['Z'] = gobj['Z']
  4592. # Store the path into geometry and reset path
  4593. if len(path) > 1:
  4594. geometry.append({"geom": LineString(path),
  4595. "kind": kind})
  4596. path = [path[-1]] # Start with the last point of last path.
  4597. # create the geometry for the holes created when drilling Excellon drills
  4598. if self.origin_kind == 'excellon':
  4599. if current['Z'] < 0:
  4600. current_drill_point_coords = (
  4601. float('%.*f' % (self.decimals, current['X'])),
  4602. float('%.*f' % (self.decimals, current['Y']))
  4603. )
  4604. # find the drill diameter knowing the drill coordinates
  4605. break_loop = False
  4606. for tool, tool_dict in self.exc_tools.items():
  4607. if 'drills' in tool_dict:
  4608. for drill_pt in tool_dict['drills']:
  4609. point_in_dict_coords = (
  4610. float('%.*f' % (self.decimals, drill_pt.x)),
  4611. float('%.*f' % (self.decimals, drill_pt.y))
  4612. )
  4613. if point_in_dict_coords == current_drill_point_coords:
  4614. dia = self.exc_tools[tool]['tooldia']
  4615. kind = ['C', 'F']
  4616. geometry.append(
  4617. {
  4618. "geom": Point(current_drill_point_coords).buffer(dia / 2.0).exterior,
  4619. "kind": kind
  4620. }
  4621. )
  4622. break_loop = True
  4623. break
  4624. if break_loop:
  4625. break
  4626. if 'G' in gobj:
  4627. current['G'] = int(gobj['G'])
  4628. if 'X' in gobj or 'Y' in gobj:
  4629. if 'X' in gobj:
  4630. x = gobj['X']
  4631. # current['X'] = x
  4632. else:
  4633. x = current['X']
  4634. if 'Y' in gobj:
  4635. y = gobj['Y']
  4636. else:
  4637. y = current['Y']
  4638. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  4639. if current['Z'] > 0:
  4640. kind[0] = 'T'
  4641. if current['G'] > 0:
  4642. kind[1] = 'S'
  4643. if current['G'] in [0, 1]: # line
  4644. path.append((x, y))
  4645. arcdir = [None, None, "cw", "ccw"]
  4646. if current['G'] in [2, 3]: # arc
  4647. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  4648. radius = np.sqrt(gobj['I'] ** 2 + gobj['J'] ** 2)
  4649. start = np.arctan2(-gobj['J'], -gobj['I'])
  4650. stop = np.arctan2(-center[1] + y, -center[0] + x)
  4651. path += arc(center, radius, start, stop, arcdir[current['G']], int(self.steps_per_circle))
  4652. current['X'] = x
  4653. current['Y'] = y
  4654. # Update current instruction
  4655. for code in gobj:
  4656. current[code] = gobj[code]
  4657. self.app.inform.emit('%s...' % _("Creating Geometry from the parsed GCode file. "))
  4658. # There might not be a change in height at the
  4659. # end, therefore, see here too if there is
  4660. # a final path.
  4661. if len(path) > 1:
  4662. geometry.append(
  4663. {
  4664. "geom": LineString(path),
  4665. "kind": kind
  4666. }
  4667. )
  4668. self.gcode_parsed = geometry
  4669. return geometry
  4670. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  4671. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  4672. # alpha={"T": 0.3, "C": 1.0}):
  4673. # """
  4674. # Creates a Matplotlib figure with a plot of the
  4675. # G-code job.
  4676. # """
  4677. # if tooldia is None:
  4678. # tooldia = self.tooldia
  4679. #
  4680. # fig = Figure(dpi=dpi)
  4681. # ax = fig.add_subplot(111)
  4682. # ax.set_aspect(1)
  4683. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  4684. # ax.set_xlim(xmin-margin, xmax+margin)
  4685. # ax.set_ylim(ymin-margin, ymax+margin)
  4686. #
  4687. # if tooldia == 0:
  4688. # for geo in self.gcode_parsed:
  4689. # linespec = '--'
  4690. # linecolor = color[geo['kind'][0]][1]
  4691. # if geo['kind'][0] == 'C':
  4692. # linespec = 'k-'
  4693. # x, y = geo['geom'].coords.xy
  4694. # ax.plot(x, y, linespec, color=linecolor)
  4695. # else:
  4696. # for geo in self.gcode_parsed:
  4697. # poly = geo['geom'].buffer(tooldia/2.0)
  4698. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  4699. # edgecolor=color[geo['kind'][0]][1],
  4700. # alpha=alpha[geo['kind'][0]], zorder=2)
  4701. # ax.add_patch(patch)
  4702. #
  4703. # return fig
  4704. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  4705. color=None, alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  4706. """
  4707. Plots the G-code job onto the given axes.
  4708. :param tooldia: Tool diameter.
  4709. :type tooldia: float
  4710. :param dpi: Not used!
  4711. :type dpi: float
  4712. :param margin: Not used!
  4713. :type margin: float
  4714. :param gcode_parsed: Parsed Gcode
  4715. :type gcode_parsed: str
  4716. :param color: Color specification.
  4717. :type color: str
  4718. :param alpha: Transparency specification.
  4719. :type alpha: dict
  4720. :param tool_tolerance: Tolerance when drawing the toolshape.
  4721. :type tool_tolerance: float
  4722. :param obj: The object for whih to plot
  4723. :type obj: class
  4724. :param visible: Visibility status
  4725. :type visible: bool
  4726. :param kind: Can be: "travel", "cut", "all"
  4727. :type kind: str
  4728. :return: None
  4729. :rtype:
  4730. """
  4731. # units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4732. if color is None:
  4733. color = {
  4734. "T": [self.app.defaults["cncjob_travel_fill"], self.app.defaults["cncjob_travel_line"]],
  4735. "C": [self.app.defaults["cncjob_plot_fill"], self.app.defaults["cncjob_plot_line"]]
  4736. }
  4737. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  4738. path_num = 0
  4739. if tooldia is None:
  4740. tooldia = self.tooldia
  4741. # this should be unlikely unless when upstream the tooldia is a tuple made by one dia and a comma like (2.4,)
  4742. if isinstance(tooldia, list):
  4743. tooldia = tooldia[0] if tooldia[0] is not None else self.tooldia
  4744. if tooldia == 0:
  4745. for geo in gcode_parsed:
  4746. if kind == 'all':
  4747. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  4748. elif kind == 'travel':
  4749. if geo['kind'][0] == 'T':
  4750. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  4751. elif kind == 'cut':
  4752. if geo['kind'][0] == 'C':
  4753. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  4754. else:
  4755. text = []
  4756. pos = []
  4757. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4758. if self.coordinates_type == "G90":
  4759. # For Absolute coordinates type G90
  4760. for geo in gcode_parsed:
  4761. if geo['kind'][0] == 'T':
  4762. current_position = geo['geom'].coords[0]
  4763. if current_position not in pos:
  4764. pos.append(current_position)
  4765. path_num += 1
  4766. text.append(str(path_num))
  4767. current_position = geo['geom'].coords[-1]
  4768. if current_position not in pos:
  4769. pos.append(current_position)
  4770. path_num += 1
  4771. text.append(str(path_num))
  4772. # plot the geometry of Excellon objects
  4773. if self.origin_kind == 'excellon':
  4774. try:
  4775. if geo['kind'][0] == 'T':
  4776. # if the geos are travel lines it will enter into Exception
  4777. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999),
  4778. resolution=self.steps_per_circle)
  4779. else:
  4780. poly = Polygon(geo['geom'])
  4781. poly = poly.simplify(tool_tolerance)
  4782. except Exception:
  4783. # deal here with unexpected plot errors due of LineStrings not valid
  4784. continue
  4785. # try:
  4786. # poly = Polygon(geo['geom'])
  4787. # except ValueError:
  4788. # # if the geos are travel lines it will enter into Exception
  4789. # poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4790. # poly = poly.simplify(tool_tolerance)
  4791. # except Exception:
  4792. # # deal here with unexpected plot errors due of LineStrings not valid
  4793. # continue
  4794. else:
  4795. # plot the geometry of any objects other than Excellon
  4796. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4797. poly = poly.simplify(tool_tolerance)
  4798. if kind == 'all':
  4799. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  4800. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  4801. elif kind == 'travel':
  4802. if geo['kind'][0] == 'T':
  4803. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  4804. visible=visible, layer=2)
  4805. elif kind == 'cut':
  4806. if geo['kind'][0] == 'C':
  4807. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  4808. visible=visible, layer=1)
  4809. else:
  4810. # For Incremental coordinates type G91
  4811. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  4812. for geo in gcode_parsed:
  4813. if geo['kind'][0] == 'T':
  4814. current_position = geo['geom'].coords[0]
  4815. if current_position not in pos:
  4816. pos.append(current_position)
  4817. path_num += 1
  4818. text.append(str(path_num))
  4819. current_position = geo['geom'].coords[-1]
  4820. if current_position not in pos:
  4821. pos.append(current_position)
  4822. path_num += 1
  4823. text.append(str(path_num))
  4824. # plot the geometry of Excellon objects
  4825. if self.origin_kind == 'excellon':
  4826. try:
  4827. poly = Polygon(geo['geom'])
  4828. except ValueError:
  4829. # if the geos are travel lines it will enter into Exception
  4830. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4831. poly = poly.simplify(tool_tolerance)
  4832. else:
  4833. # plot the geometry of any objects other than Excellon
  4834. poly = geo['geom'].buffer(distance=(tooldia / 1.99999999), resolution=self.steps_per_circle)
  4835. poly = poly.simplify(tool_tolerance)
  4836. if kind == 'all':
  4837. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  4838. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  4839. elif kind == 'travel':
  4840. if geo['kind'][0] == 'T':
  4841. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  4842. visible=visible, layer=2)
  4843. elif kind == 'cut':
  4844. if geo['kind'][0] == 'C':
  4845. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  4846. visible=visible, layer=1)
  4847. try:
  4848. if self.app.defaults['global_theme'] == 'white':
  4849. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  4850. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  4851. color=self.app.defaults["cncjob_annotation_fontcolor"])
  4852. else:
  4853. # invert the color
  4854. old_color = self.app.defaults["cncjob_annotation_fontcolor"].lower()
  4855. new_color = ''
  4856. code = {}
  4857. l1 = "#;0123456789abcdef"
  4858. l2 = "#;fedcba9876543210"
  4859. for i in range(len(l1)):
  4860. code[l1[i]] = l2[i]
  4861. for x in range(len(old_color)):
  4862. new_color += code[old_color[x]]
  4863. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'],
  4864. font_size=self.app.defaults["cncjob_annotation_fontsize"],
  4865. color=new_color)
  4866. except Exception as e:
  4867. log.debug("CNCJob.plot2() --> annotations --> %s" % str(e))
  4868. def create_geometry(self):
  4869. """
  4870. It is used by the Excellon objects. Will create the solid_geometry which will be an attribute of the
  4871. Excellon object class.
  4872. :return: List of Shapely geometry elements
  4873. :rtype: list
  4874. """
  4875. # TODO: This takes forever. Too much data?
  4876. # self.app.inform.emit('%s: %s' % (_("Unifying Geometry from parsed Geometry segments"),
  4877. # str(len(self.gcode_parsed))))
  4878. # self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  4879. # This is much faster but not so nice to look at as you can see different segments of the geometry
  4880. self.solid_geometry = [geo['geom'] for geo in self.gcode_parsed]
  4881. return self.solid_geometry
  4882. def segment(self, coords):
  4883. """
  4884. Break long linear lines to make it more auto level friendly.
  4885. Code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  4886. :param coords: List of coordinates tuples
  4887. :type coords: list
  4888. :return: A path; list with the multiple coordinates breaking a line.
  4889. :rtype: list
  4890. """
  4891. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  4892. return list(coords)
  4893. path = [coords[0]]
  4894. # break the line in either x or y dimension only
  4895. def linebreak_single(line, dim, dmax):
  4896. if dmax <= 0:
  4897. return None
  4898. if line[1][dim] > line[0][dim]:
  4899. sign = 1.0
  4900. d = line[1][dim] - line[0][dim]
  4901. else:
  4902. sign = -1.0
  4903. d = line[0][dim] - line[1][dim]
  4904. if d > dmax:
  4905. # make sure we don't make any new lines too short
  4906. if d > dmax * 2:
  4907. dd = dmax
  4908. else:
  4909. dd = d / 2
  4910. other = dim ^ 1
  4911. return (line[0][dim] + dd * sign, line[0][other] + \
  4912. dd * (line[1][other] - line[0][other]) / d)
  4913. return None
  4914. # recursively breaks down a given line until it is within the
  4915. # required step size
  4916. def linebreak(line):
  4917. pt_new = linebreak_single(line, 0, self.segx)
  4918. if pt_new is None:
  4919. pt_new2 = linebreak_single(line, 1, self.segy)
  4920. else:
  4921. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  4922. if pt_new2 is not None:
  4923. pt_new = pt_new2[::-1]
  4924. if pt_new is None:
  4925. path.append(line[1])
  4926. else:
  4927. path.append(pt_new)
  4928. linebreak((pt_new, line[1]))
  4929. for pt in coords[1:]:
  4930. linebreak((path[-1], pt))
  4931. return path
  4932. def linear2gcode(self, linear, dia, tolerance=0, down=True, up=True, z_cut=None, z_move=None, zdownrate=None,
  4933. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  4934. """
  4935. Generates G-code to cut along the linear feature.
  4936. :param linear: The path to cut along.
  4937. :type: Shapely.LinearRing or Shapely.Linear String
  4938. :param dia: The tool diameter that is going on the path
  4939. :type dia: float
  4940. :param tolerance: All points in the simplified object will be within the
  4941. tolerance distance of the original geometry.
  4942. :type tolerance: float
  4943. :param down:
  4944. :param up:
  4945. :param z_cut:
  4946. :param z_move:
  4947. :param zdownrate:
  4948. :param feedrate: speed for cut on X - Y plane
  4949. :param feedrate_z: speed for cut on Z plane
  4950. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  4951. :param cont:
  4952. :param old_point:
  4953. :return: G-code to cut along the linear feature.
  4954. """
  4955. if z_cut is None:
  4956. z_cut = self.z_cut
  4957. if z_move is None:
  4958. z_move = self.z_move
  4959. #
  4960. # if zdownrate is None:
  4961. # zdownrate = self.zdownrate
  4962. if feedrate is None:
  4963. feedrate = self.feedrate
  4964. if feedrate_z is None:
  4965. feedrate_z = self.z_feedrate
  4966. if feedrate_rapid is None:
  4967. feedrate_rapid = self.feedrate_rapid
  4968. # Simplify paths?
  4969. if tolerance > 0:
  4970. target_linear = linear.simplify(tolerance)
  4971. else:
  4972. target_linear = linear
  4973. gcode = ""
  4974. # path = list(target_linear.coords)
  4975. path = self.segment(target_linear.coords)
  4976. p = self.pp_geometry
  4977. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  4978. if self.coordinates_type == "G90":
  4979. # For Absolute coordinates type G90
  4980. first_x = path[0][0]
  4981. first_y = path[0][1]
  4982. else:
  4983. # For Incremental coordinates type G91
  4984. first_x = path[0][0] - old_point[0]
  4985. first_y = path[0][1] - old_point[1]
  4986. # Move fast to 1st point
  4987. if not cont:
  4988. current_tooldia = dia
  4989. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  4990. end_point=(first_x, first_y),
  4991. tooldia=current_tooldia)
  4992. prev_z = None
  4993. for travel in travels:
  4994. locx = travel[1][0]
  4995. locy = travel[1][1]
  4996. if travel[0] is not None:
  4997. # move to next point
  4998. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  4999. # raise to safe Z (travel[0]) each time because safe Z may be different
  5000. self.z_move = travel[0]
  5001. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5002. # restore z_move
  5003. self.z_move = z_move
  5004. else:
  5005. if prev_z is not None:
  5006. # move to next point
  5007. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5008. # we assume that previously the z_move was altered therefore raise to
  5009. # the travel_z (z_move)
  5010. self.z_move = z_move
  5011. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5012. else:
  5013. # move to next point
  5014. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5015. # store prev_z
  5016. prev_z = travel[0]
  5017. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5018. # Move down to cutting depth
  5019. if down:
  5020. # Different feedrate for vertical cut?
  5021. gcode += self.doformat(p.z_feedrate_code)
  5022. # gcode += self.doformat(p.feedrate_code)
  5023. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5024. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5025. # Cutting...
  5026. prev_x = first_x
  5027. prev_y = first_y
  5028. for pt in path[1:]:
  5029. if self.app.abort_flag:
  5030. # graceful abort requested by the user
  5031. raise grace
  5032. if self.coordinates_type == "G90":
  5033. # For Absolute coordinates type G90
  5034. next_x = pt[0]
  5035. next_y = pt[1]
  5036. else:
  5037. # For Incremental coordinates type G91
  5038. # next_x = pt[0] - prev_x
  5039. # next_y = pt[1] - prev_y
  5040. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5041. next_x = pt[0]
  5042. next_y = pt[1]
  5043. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5044. prev_x = pt[0]
  5045. prev_y = pt[1]
  5046. # Up to travelling height.
  5047. if up:
  5048. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # Stop cutting
  5049. return gcode
  5050. def linear2gcode_extra(self, linear, dia, extracut_length, tolerance=0, down=True, up=True,
  5051. z_cut=None, z_move=None, zdownrate=None,
  5052. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False, old_point=(0, 0)):
  5053. """
  5054. Generates G-code to cut along the linear feature.
  5055. :param linear: The path to cut along.
  5056. :type: Shapely.LinearRing or Shapely.Linear String
  5057. :param dia: The tool diameter that is going on the path
  5058. :type dia: float
  5059. :param extracut_length: how much to cut extra over the first point at the end of the path
  5060. :param tolerance: All points in the simplified object will be within the
  5061. tolerance distance of the original geometry.
  5062. :type tolerance: float
  5063. :param down:
  5064. :param up:
  5065. :param z_cut:
  5066. :param z_move:
  5067. :param zdownrate:
  5068. :param feedrate: speed for cut on X - Y plane
  5069. :param feedrate_z: speed for cut on Z plane
  5070. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5071. :param cont:
  5072. :param old_point:
  5073. :return: G-code to cut along the linear feature.
  5074. :rtype: str
  5075. """
  5076. if z_cut is None:
  5077. z_cut = self.z_cut
  5078. if z_move is None:
  5079. z_move = self.z_move
  5080. #
  5081. # if zdownrate is None:
  5082. # zdownrate = self.zdownrate
  5083. if feedrate is None:
  5084. feedrate = self.feedrate
  5085. if feedrate_z is None:
  5086. feedrate_z = self.z_feedrate
  5087. if feedrate_rapid is None:
  5088. feedrate_rapid = self.feedrate_rapid
  5089. # Simplify paths?
  5090. if tolerance > 0:
  5091. target_linear = linear.simplify(tolerance)
  5092. else:
  5093. target_linear = linear
  5094. gcode = ""
  5095. path = list(target_linear.coords)
  5096. p = self.pp_geometry
  5097. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5098. if self.coordinates_type == "G90":
  5099. # For Absolute coordinates type G90
  5100. first_x = path[0][0]
  5101. first_y = path[0][1]
  5102. else:
  5103. # For Incremental coordinates type G91
  5104. first_x = path[0][0] - old_point[0]
  5105. first_y = path[0][1] - old_point[1]
  5106. # Move fast to 1st point
  5107. if not cont:
  5108. current_tooldia = dia
  5109. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5110. end_point=(first_x, first_y),
  5111. tooldia=current_tooldia)
  5112. prev_z = None
  5113. for travel in travels:
  5114. locx = travel[1][0]
  5115. locy = travel[1][1]
  5116. if travel[0] is not None:
  5117. # move to next point
  5118. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5119. # raise to safe Z (travel[0]) each time because safe Z may be different
  5120. self.z_move = travel[0]
  5121. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5122. # restore z_move
  5123. self.z_move = z_move
  5124. else:
  5125. if prev_z is not None:
  5126. # move to next point
  5127. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5128. # we assume that previously the z_move was altered therefore raise to
  5129. # the travel_z (z_move)
  5130. self.z_move = z_move
  5131. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5132. else:
  5133. # move to next point
  5134. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5135. # store prev_z
  5136. prev_z = travel[0]
  5137. # gcode += self.doformat(p.rapid_code, x=first_x, y=first_y) # Move to first point
  5138. # Move down to cutting depth
  5139. if down:
  5140. # Different feedrate for vertical cut?
  5141. if self.z_feedrate is not None:
  5142. gcode += self.doformat(p.z_feedrate_code)
  5143. # gcode += self.doformat(p.feedrate_code)
  5144. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut)
  5145. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5146. else:
  5147. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=z_cut) # Start cutting
  5148. # Cutting...
  5149. prev_x = first_x
  5150. prev_y = first_y
  5151. for pt in path[1:]:
  5152. if self.app.abort_flag:
  5153. # graceful abort requested by the user
  5154. raise grace
  5155. if self.coordinates_type == "G90":
  5156. # For Absolute coordinates type G90
  5157. next_x = pt[0]
  5158. next_y = pt[1]
  5159. else:
  5160. # For Incremental coordinates type G91
  5161. # For Incremental coordinates type G91
  5162. # next_x = pt[0] - prev_x
  5163. # next_y = pt[1] - prev_y
  5164. self.app.inform.emit('[ERROR_NOTCL] %s' % _('G91 coordinates not implemented ...'))
  5165. next_x = pt[0]
  5166. next_y = pt[1]
  5167. gcode += self.doformat(p.linear_code, x=next_x, y=next_y, z=z_cut) # Linear motion to point
  5168. prev_x = next_x
  5169. prev_y = next_y
  5170. # this line is added to create an extra cut over the first point in patch
  5171. # to make sure that we remove the copper leftovers
  5172. # Linear motion to the 1st point in the cut path
  5173. # if self.coordinates_type == "G90":
  5174. # # For Absolute coordinates type G90
  5175. # last_x = path[1][0]
  5176. # last_y = path[1][1]
  5177. # else:
  5178. # # For Incremental coordinates type G91
  5179. # last_x = path[1][0] - first_x
  5180. # last_y = path[1][1] - first_y
  5181. # gcode += self.doformat(p.linear_code, x=last_x, y=last_y)
  5182. # the first point for extracut is always mandatory if the extracut is enabled. But if the length of distance
  5183. # between point 0 and point 1 is more than the distance we set for the extra cut then make an interpolation
  5184. # along the path and find the point at the distance extracut_length
  5185. if extracut_length == 0.0:
  5186. extra_path = [path[-1], path[0], path[1]]
  5187. new_x = extra_path[0][0]
  5188. new_y = extra_path[0][1]
  5189. # this is an extra line therefore lift the milling bit
  5190. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  5191. # move fast to the new first point
  5192. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  5193. # lower the milling bit
  5194. # Different feedrate for vertical cut?
  5195. if self.z_feedrate is not None:
  5196. gcode += self.doformat(p.z_feedrate_code)
  5197. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  5198. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5199. else:
  5200. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  5201. # start cutting the extra line
  5202. last_pt = extra_path[0]
  5203. for pt in extra_path[1:]:
  5204. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5205. last_pt = pt
  5206. # go back to the original point
  5207. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1])
  5208. last_pt = path[0]
  5209. else:
  5210. # go to the point that is 5% in length before the end (therefore 95% length from start of the line),
  5211. # along the line to be cut
  5212. if extracut_length >= target_linear.length:
  5213. extracut_length = target_linear.length
  5214. # ---------------------------------------------
  5215. # first half
  5216. # ---------------------------------------------
  5217. start_length = target_linear.length - (extracut_length * 0.5)
  5218. extra_line = substring(target_linear, start_length, target_linear.length)
  5219. extra_path = list(extra_line.coords)
  5220. new_x = extra_path[0][0]
  5221. new_y = extra_path[0][1]
  5222. # this is an extra line therefore lift the milling bit
  5223. gcode += self.doformat(p.lift_code, x=prev_x, y=prev_y, z_move=z_move) # lift
  5224. # move fast to the new first point
  5225. gcode += self.doformat(p.rapid_code, x=new_x, y=new_y)
  5226. # lower the milling bit
  5227. # Different feedrate for vertical cut?
  5228. if self.z_feedrate is not None:
  5229. gcode += self.doformat(p.z_feedrate_code)
  5230. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut)
  5231. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5232. else:
  5233. gcode += self.doformat(p.down_code, x=new_x, y=new_y, z_cut=z_cut) # Start cutting
  5234. # start cutting the extra line
  5235. for pt in extra_path[1:]:
  5236. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5237. # ---------------------------------------------
  5238. # second half
  5239. # ---------------------------------------------
  5240. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  5241. extra_path = list(extra_line.coords)
  5242. # start cutting the extra line
  5243. last_pt = extra_path[0]
  5244. for pt in extra_path[1:]:
  5245. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5246. last_pt = pt
  5247. # ---------------------------------------------
  5248. # back to original start point, cutting
  5249. # ---------------------------------------------
  5250. extra_line = substring(target_linear, 0, (extracut_length * 0.5))
  5251. extra_path = list(extra_line.coords)[::-1]
  5252. # start cutting the extra line
  5253. last_pt = extra_path[0]
  5254. for pt in extra_path[1:]:
  5255. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5256. last_pt = pt
  5257. # if extracut_length == 0.0:
  5258. # gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1])
  5259. # last_pt = path[1]
  5260. # else:
  5261. # if abs(distance(path[1], path[0])) > extracut_length:
  5262. # i_point = LineString([path[0], path[1]]).interpolate(extracut_length)
  5263. # gcode += self.doformat(p.linear_code, x=i_point.x, y=i_point.y)
  5264. # last_pt = (i_point.x, i_point.y)
  5265. # else:
  5266. # last_pt = path[0]
  5267. # for pt in path[1:]:
  5268. # extracut_distance = abs(distance(pt, last_pt))
  5269. # if extracut_distance <= extracut_length:
  5270. # gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1])
  5271. # last_pt = pt
  5272. # else:
  5273. # break
  5274. # Up to travelling height.
  5275. if up:
  5276. gcode += self.doformat(p.lift_code, x=last_pt[0], y=last_pt[1], z_move=z_move) # Stop cutting
  5277. return gcode
  5278. def point2gcode(self, point, dia, z_move=None, old_point=(0, 0)):
  5279. """
  5280. :param point: A Shapely Point
  5281. :type point: Point
  5282. :param dia: The tool diameter that is going on the path
  5283. :type dia: float
  5284. :param z_move: Travel Z
  5285. :type z_move: float
  5286. :param old_point: Old point coordinates from which we moved to the 'point'
  5287. :type old_point: tuple
  5288. :return: G-code to cut on the Point feature.
  5289. :rtype: str
  5290. """
  5291. gcode = ""
  5292. if self.app.abort_flag:
  5293. # graceful abort requested by the user
  5294. raise grace
  5295. path = list(point.coords)
  5296. p = self.pp_geometry
  5297. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  5298. if self.coordinates_type == "G90":
  5299. # For Absolute coordinates type G90
  5300. first_x = path[0][0]
  5301. first_y = path[0][1]
  5302. else:
  5303. # For Incremental coordinates type G91
  5304. # first_x = path[0][0] - old_point[0]
  5305. # first_y = path[0][1] - old_point[1]
  5306. self.app.inform.emit('[ERROR_NOTCL] %s' %
  5307. _('G91 coordinates not implemented ...'))
  5308. first_x = path[0][0]
  5309. first_y = path[0][1]
  5310. current_tooldia = dia
  5311. travels = self.app.exc_areas.travel_coordinates(start_point=(old_point[0], old_point[1]),
  5312. end_point=(first_x, first_y),
  5313. tooldia=current_tooldia)
  5314. prev_z = None
  5315. for travel in travels:
  5316. locx = travel[1][0]
  5317. locy = travel[1][1]
  5318. if travel[0] is not None:
  5319. # move to next point
  5320. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5321. # raise to safe Z (travel[0]) each time because safe Z may be different
  5322. self.z_move = travel[0]
  5323. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5324. # restore z_move
  5325. self.z_move = z_move
  5326. else:
  5327. if prev_z is not None:
  5328. # move to next point
  5329. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5330. # we assume that previously the z_move was altered therefore raise to
  5331. # the travel_z (z_move)
  5332. self.z_move = z_move
  5333. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  5334. else:
  5335. # move to next point
  5336. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  5337. # store prev_z
  5338. prev_z = travel[0]
  5339. # gcode += self.doformat(p.linear_code, x=first_x, y=first_y) # Move to first point
  5340. if self.z_feedrate is not None:
  5341. gcode += self.doformat(p.z_feedrate_code)
  5342. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut)
  5343. gcode += self.doformat(p.feedrate_code)
  5344. else:
  5345. gcode += self.doformat(p.down_code, x=first_x, y=first_y, z_cut=self.z_cut) # Start cutting
  5346. gcode += self.doformat(p.lift_code, x=first_x, y=first_y) # Stop cutting
  5347. return gcode
  5348. def export_svg(self, scale_stroke_factor=0.00):
  5349. """
  5350. Exports the CNC Job as a SVG Element
  5351. :param scale_stroke_factor: A factor to scale the SVG geometry
  5352. :type scale_stroke_factor: float
  5353. :return: SVG Element string
  5354. :rtype: str
  5355. """
  5356. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  5357. # If not specified then try and use the tool diameter
  5358. # This way what is on screen will match what is outputed for the svg
  5359. # This is quite a useful feature for svg's used with visicut
  5360. if scale_stroke_factor <= 0:
  5361. scale_stroke_factor = self.options['tooldia'] / 2
  5362. # If still 0 then default to 0.05
  5363. # This value appears to work for zooming, and getting the output svg line width
  5364. # to match that viewed on screen with FlatCam
  5365. if scale_stroke_factor == 0:
  5366. scale_stroke_factor = 0.01
  5367. # Separate the list of cuts and travels into 2 distinct lists
  5368. # This way we can add different formatting / colors to both
  5369. cuts = []
  5370. travels = []
  5371. cutsgeom = ''
  5372. travelsgeom = ''
  5373. for g in self.gcode_parsed:
  5374. if self.app.abort_flag:
  5375. # graceful abort requested by the user
  5376. raise grace
  5377. if g['kind'][0] == 'C':
  5378. cuts.append(g)
  5379. if g['kind'][0] == 'T':
  5380. travels.append(g)
  5381. # Used to determine the overall board size
  5382. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5383. # Convert the cuts and travels into single geometry objects we can render as svg xml
  5384. if travels:
  5385. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  5386. if self.app.abort_flag:
  5387. # graceful abort requested by the user
  5388. raise grace
  5389. if cuts:
  5390. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  5391. # Render the SVG Xml
  5392. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  5393. # It's better to have the travels sitting underneath the cuts for visicut
  5394. svg_elem = ""
  5395. if travels:
  5396. svg_elem = travelsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#F0E24D")
  5397. if cuts:
  5398. svg_elem += cutsgeom.svg(scale_factor=scale_stroke_factor, stroke_color="#5E6CFF")
  5399. return svg_elem
  5400. def bounds(self, flatten=None):
  5401. """
  5402. Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  5403. :param flatten: Not used, it is here for compatibility with base class method
  5404. :type flatten: bool
  5405. :return: Bounding values in format (xmin, ymin, xmax, ymax)
  5406. :rtype: tuple
  5407. """
  5408. log.debug("camlib.CNCJob.bounds()")
  5409. def bounds_rec(obj):
  5410. if type(obj) is list:
  5411. cminx = np.Inf
  5412. cminy = np.Inf
  5413. cmaxx = -np.Inf
  5414. cmaxy = -np.Inf
  5415. for k in obj:
  5416. if type(k) is dict:
  5417. for key in k:
  5418. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  5419. cminx = min(cminx, minx_)
  5420. cminy = min(cminy, miny_)
  5421. cmaxx = max(cmaxx, maxx_)
  5422. cmaxy = max(cmaxy, maxy_)
  5423. else:
  5424. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5425. cminx = min(cminx, minx_)
  5426. cminy = min(cminy, miny_)
  5427. cmaxx = max(cmaxx, maxx_)
  5428. cmaxy = max(cmaxy, maxy_)
  5429. return cminx, cminy, cmaxx, cmaxy
  5430. else:
  5431. # it's a Shapely object, return it's bounds
  5432. return obj.bounds
  5433. if self.multitool is False:
  5434. log.debug("CNCJob->bounds()")
  5435. if self.solid_geometry is None:
  5436. log.debug("solid_geometry is None")
  5437. return 0, 0, 0, 0
  5438. bounds_coords = bounds_rec(self.solid_geometry)
  5439. else:
  5440. minx = np.Inf
  5441. miny = np.Inf
  5442. maxx = -np.Inf
  5443. maxy = -np.Inf
  5444. for k, v in self.cnc_tools.items():
  5445. minx = np.Inf
  5446. miny = np.Inf
  5447. maxx = -np.Inf
  5448. maxy = -np.Inf
  5449. try:
  5450. for k in v['solid_geometry']:
  5451. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5452. minx = min(minx, minx_)
  5453. miny = min(miny, miny_)
  5454. maxx = max(maxx, maxx_)
  5455. maxy = max(maxy, maxy_)
  5456. except TypeError:
  5457. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  5458. minx = min(minx, minx_)
  5459. miny = min(miny, miny_)
  5460. maxx = max(maxx, maxx_)
  5461. maxy = max(maxy, maxy_)
  5462. bounds_coords = minx, miny, maxx, maxy
  5463. return bounds_coords
  5464. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  5465. def scale(self, xfactor, yfactor=None, point=None):
  5466. """
  5467. Scales all the geometry on the XY plane in the object by the
  5468. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  5469. not altered.
  5470. :param factor: Number by which to scale the object.
  5471. :type factor: float
  5472. :param point: the (x,y) coords for the point of origin of scale
  5473. :type tuple of floats
  5474. :return: None
  5475. :rtype: None
  5476. """
  5477. log.debug("camlib.CNCJob.scale()")
  5478. if yfactor is None:
  5479. yfactor = xfactor
  5480. if point is None:
  5481. px = 0
  5482. py = 0
  5483. else:
  5484. px, py = point
  5485. def scale_g(g):
  5486. """
  5487. :param g: 'g' parameter it's a gcode string
  5488. :return: scaled gcode string
  5489. """
  5490. temp_gcode = ''
  5491. header_start = False
  5492. header_stop = False
  5493. units = self.app.defaults['units'].upper()
  5494. lines = StringIO(g)
  5495. for line in lines:
  5496. # this changes the GCODE header ---- UGLY HACK
  5497. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  5498. header_start = True
  5499. if "G20" in line or "G21" in line:
  5500. header_start = False
  5501. header_stop = True
  5502. if header_start is True:
  5503. header_stop = False
  5504. if "in" in line:
  5505. if units == 'MM':
  5506. line = line.replace("in", "mm")
  5507. if "mm" in line:
  5508. if units == 'IN':
  5509. line = line.replace("mm", "in")
  5510. # find any float number in header (even multiple on the same line) and convert it
  5511. numbers_in_header = re.findall(self.g_nr_re, line)
  5512. if numbers_in_header:
  5513. for nr in numbers_in_header:
  5514. new_nr = float(nr) * xfactor
  5515. # replace the updated string
  5516. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  5517. )
  5518. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  5519. if header_stop is True:
  5520. if "G20" in line:
  5521. if units == 'MM':
  5522. line = line.replace("G20", "G21")
  5523. if "G21" in line:
  5524. if units == 'IN':
  5525. line = line.replace("G21", "G20")
  5526. # find the X group
  5527. match_x = self.g_x_re.search(line)
  5528. if match_x:
  5529. if match_x.group(1) is not None:
  5530. new_x = float(match_x.group(1)[1:]) * xfactor
  5531. # replace the updated string
  5532. line = line.replace(
  5533. match_x.group(1),
  5534. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5535. )
  5536. # find the Y group
  5537. match_y = self.g_y_re.search(line)
  5538. if match_y:
  5539. if match_y.group(1) is not None:
  5540. new_y = float(match_y.group(1)[1:]) * yfactor
  5541. line = line.replace(
  5542. match_y.group(1),
  5543. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5544. )
  5545. # find the Z group
  5546. match_z = self.g_z_re.search(line)
  5547. if match_z:
  5548. if match_z.group(1) is not None:
  5549. new_z = float(match_z.group(1)[1:]) * xfactor
  5550. line = line.replace(
  5551. match_z.group(1),
  5552. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  5553. )
  5554. # find the F group
  5555. match_f = self.g_f_re.search(line)
  5556. if match_f:
  5557. if match_f.group(1) is not None:
  5558. new_f = float(match_f.group(1)[1:]) * xfactor
  5559. line = line.replace(
  5560. match_f.group(1),
  5561. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  5562. )
  5563. # find the T group (tool dia on toolchange)
  5564. match_t = self.g_t_re.search(line)
  5565. if match_t:
  5566. if match_t.group(1) is not None:
  5567. new_t = float(match_t.group(1)[1:]) * xfactor
  5568. line = line.replace(
  5569. match_t.group(1),
  5570. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  5571. )
  5572. temp_gcode += line
  5573. lines.close()
  5574. header_stop = False
  5575. return temp_gcode
  5576. if self.multitool is False:
  5577. # offset Gcode
  5578. self.gcode = scale_g(self.gcode)
  5579. # variables to display the percentage of work done
  5580. self.geo_len = 0
  5581. try:
  5582. self.geo_len = len(self.gcode_parsed)
  5583. except TypeError:
  5584. self.geo_len = 1
  5585. self.old_disp_number = 0
  5586. self.el_count = 0
  5587. # scale geometry
  5588. for g in self.gcode_parsed:
  5589. try:
  5590. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5591. except AttributeError:
  5592. return g['geom']
  5593. self.el_count += 1
  5594. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5595. if self.old_disp_number < disp_number <= 100:
  5596. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5597. self.old_disp_number = disp_number
  5598. self.create_geometry()
  5599. else:
  5600. for k, v in self.cnc_tools.items():
  5601. # scale Gcode
  5602. v['gcode'] = scale_g(v['gcode'])
  5603. # variables to display the percentage of work done
  5604. self.geo_len = 0
  5605. try:
  5606. self.geo_len = len(v['gcode_parsed'])
  5607. except TypeError:
  5608. self.geo_len = 1
  5609. self.old_disp_number = 0
  5610. self.el_count = 0
  5611. # scale gcode_parsed
  5612. for g in v['gcode_parsed']:
  5613. try:
  5614. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5615. except AttributeError:
  5616. return g['geom']
  5617. self.el_count += 1
  5618. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5619. if self.old_disp_number < disp_number <= 100:
  5620. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5621. self.old_disp_number = disp_number
  5622. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5623. self.create_geometry()
  5624. self.app.proc_container.new_text = ''
  5625. def offset(self, vect):
  5626. """
  5627. Offsets all the geometry on the XY plane in the object by the
  5628. given vector.
  5629. Offsets all the GCODE on the XY plane in the object by the
  5630. given vector.
  5631. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  5632. :param vect: (x, y) offset vector.
  5633. :type vect: tuple
  5634. :return: None
  5635. """
  5636. log.debug("camlib.CNCJob.offset()")
  5637. dx, dy = vect
  5638. def offset_g(g):
  5639. """
  5640. :param g: 'g' parameter it's a gcode string
  5641. :return: offseted gcode string
  5642. """
  5643. temp_gcode = ''
  5644. lines = StringIO(g)
  5645. for line in lines:
  5646. # find the X group
  5647. match_x = self.g_x_re.search(line)
  5648. if match_x:
  5649. if match_x.group(1) is not None:
  5650. # get the coordinate and add X offset
  5651. new_x = float(match_x.group(1)[1:]) + dx
  5652. # replace the updated string
  5653. line = line.replace(
  5654. match_x.group(1),
  5655. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5656. )
  5657. match_y = self.g_y_re.search(line)
  5658. if match_y:
  5659. if match_y.group(1) is not None:
  5660. new_y = float(match_y.group(1)[1:]) + dy
  5661. line = line.replace(
  5662. match_y.group(1),
  5663. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5664. )
  5665. temp_gcode += line
  5666. lines.close()
  5667. return temp_gcode
  5668. if self.multitool is False:
  5669. # offset Gcode
  5670. self.gcode = offset_g(self.gcode)
  5671. # variables to display the percentage of work done
  5672. self.geo_len = 0
  5673. try:
  5674. self.geo_len = len(self.gcode_parsed)
  5675. except TypeError:
  5676. self.geo_len = 1
  5677. self.old_disp_number = 0
  5678. self.el_count = 0
  5679. # offset geometry
  5680. for g in self.gcode_parsed:
  5681. try:
  5682. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5683. except AttributeError:
  5684. return g['geom']
  5685. self.el_count += 1
  5686. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5687. if self.old_disp_number < disp_number <= 100:
  5688. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5689. self.old_disp_number = disp_number
  5690. self.create_geometry()
  5691. else:
  5692. for k, v in self.cnc_tools.items():
  5693. # offset Gcode
  5694. v['gcode'] = offset_g(v['gcode'])
  5695. # variables to display the percentage of work done
  5696. self.geo_len = 0
  5697. try:
  5698. self.geo_len = len(v['gcode_parsed'])
  5699. except TypeError:
  5700. self.geo_len = 1
  5701. self.old_disp_number = 0
  5702. self.el_count = 0
  5703. # offset gcode_parsed
  5704. for g in v['gcode_parsed']:
  5705. try:
  5706. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5707. except AttributeError:
  5708. return g['geom']
  5709. self.el_count += 1
  5710. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5711. if self.old_disp_number < disp_number <= 100:
  5712. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5713. self.old_disp_number = disp_number
  5714. # for the bounding box
  5715. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5716. self.app.proc_container.new_text = ''
  5717. def mirror(self, axis, point):
  5718. """
  5719. Mirror the geometry of an object by an given axis around the coordinates of the 'point'
  5720. :param axis: Axis for Mirror
  5721. :param point: tuple of coordinates (x,y). Point of origin for Mirror
  5722. :return:
  5723. """
  5724. log.debug("camlib.CNCJob.mirror()")
  5725. px, py = point
  5726. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  5727. # variables to display the percentage of work done
  5728. self.geo_len = 0
  5729. try:
  5730. self.geo_len = len(self.gcode_parsed)
  5731. except TypeError:
  5732. self.geo_len = 1
  5733. self.old_disp_number = 0
  5734. self.el_count = 0
  5735. for g in self.gcode_parsed:
  5736. try:
  5737. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  5738. except AttributeError:
  5739. return g['geom']
  5740. self.el_count += 1
  5741. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5742. if self.old_disp_number < disp_number <= 100:
  5743. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5744. self.old_disp_number = disp_number
  5745. self.create_geometry()
  5746. self.app.proc_container.new_text = ''
  5747. def skew(self, angle_x, angle_y, point):
  5748. """
  5749. Shear/Skew the geometries of an object by angles along x and y dimensions.
  5750. :param angle_x:
  5751. :param angle_y:
  5752. angle_x, angle_y : float, float
  5753. The shear angle(s) for the x and y axes respectively. These can be
  5754. specified in either degrees (default) or radians by setting
  5755. use_radians=True.
  5756. :param point: tupple of coordinates (x,y)
  5757. See shapely manual for more information: http://toblerity.org/shapely/manual.html#affine-transformations
  5758. """
  5759. log.debug("camlib.CNCJob.skew()")
  5760. px, py = point
  5761. # variables to display the percentage of work done
  5762. self.geo_len = 0
  5763. try:
  5764. self.geo_len = len(self.gcode_parsed)
  5765. except TypeError:
  5766. self.geo_len = 1
  5767. self.old_disp_number = 0
  5768. self.el_count = 0
  5769. for g in self.gcode_parsed:
  5770. try:
  5771. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y, origin=(px, py))
  5772. except AttributeError:
  5773. return g['geom']
  5774. self.el_count += 1
  5775. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5776. if self.old_disp_number < disp_number <= 100:
  5777. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5778. self.old_disp_number = disp_number
  5779. self.create_geometry()
  5780. self.app.proc_container.new_text = ''
  5781. def rotate(self, angle, point):
  5782. """
  5783. Rotate the geometry of an object by an given angle around the coordinates of the 'point'
  5784. :param angle: Angle of Rotation
  5785. :param point: tuple of coordinates (x,y). Origin point for Rotation
  5786. :return:
  5787. """
  5788. log.debug("camlib.CNCJob.rotate()")
  5789. px, py = point
  5790. # variables to display the percentage of work done
  5791. self.geo_len = 0
  5792. try:
  5793. self.geo_len = len(self.gcode_parsed)
  5794. except TypeError:
  5795. self.geo_len = 1
  5796. self.old_disp_number = 0
  5797. self.el_count = 0
  5798. for g in self.gcode_parsed:
  5799. try:
  5800. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  5801. except AttributeError:
  5802. return g['geom']
  5803. self.el_count += 1
  5804. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  5805. if self.old_disp_number < disp_number <= 100:
  5806. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  5807. self.old_disp_number = disp_number
  5808. self.create_geometry()
  5809. self.app.proc_container.new_text = ''
  5810. def get_bounds(geometry_list):
  5811. """
  5812. Will return limit values for a list of geometries
  5813. :param geometry_list: List of geometries for which to calculate the bounds limits
  5814. :return:
  5815. """
  5816. xmin = np.Inf
  5817. ymin = np.Inf
  5818. xmax = -np.Inf
  5819. ymax = -np.Inf
  5820. for gs in geometry_list:
  5821. try:
  5822. gxmin, gymin, gxmax, gymax = gs.bounds()
  5823. xmin = min([xmin, gxmin])
  5824. ymin = min([ymin, gymin])
  5825. xmax = max([xmax, gxmax])
  5826. ymax = max([ymax, gymax])
  5827. except Exception:
  5828. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  5829. return [xmin, ymin, xmax, ymax]
  5830. def arc(center, radius, start, stop, direction, steps_per_circ):
  5831. """
  5832. Creates a list of point along the specified arc.
  5833. :param center: Coordinates of the center [x, y]
  5834. :type center: list
  5835. :param radius: Radius of the arc.
  5836. :type radius: float
  5837. :param start: Starting angle in radians
  5838. :type start: float
  5839. :param stop: End angle in radians
  5840. :type stop: float
  5841. :param direction: Orientation of the arc, "CW" or "CCW"
  5842. :type direction: string
  5843. :param steps_per_circ: Number of straight line segments to
  5844. represent a circle.
  5845. :type steps_per_circ: int
  5846. :return: The desired arc, as list of tuples
  5847. :rtype: list
  5848. """
  5849. # TODO: Resolution should be established by maximum error from the exact arc.
  5850. da_sign = {"cw": -1.0, "ccw": 1.0}
  5851. points = []
  5852. if direction == "ccw" and stop <= start:
  5853. stop += 2 * np.pi
  5854. if direction == "cw" and stop >= start:
  5855. stop -= 2 * np.pi
  5856. angle = abs(stop - start)
  5857. # angle = stop-start
  5858. steps = max([int(np.ceil(angle / (2 * np.pi) * steps_per_circ)), 2])
  5859. delta_angle = da_sign[direction] * angle * 1.0 / steps
  5860. for i in range(steps + 1):
  5861. theta = start + delta_angle * i
  5862. points.append((center[0] + radius * np.cos(theta), center[1] + radius * np.sin(theta)))
  5863. return points
  5864. def arc2(p1, p2, center, direction, steps_per_circ):
  5865. r = np.sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  5866. start = np.arctan2(p1[1] - center[1], p1[0] - center[0])
  5867. stop = np.arctan2(p2[1] - center[1], p2[0] - center[0])
  5868. return arc(center, r, start, stop, direction, steps_per_circ)
  5869. def arc_angle(start, stop, direction):
  5870. if direction == "ccw" and stop <= start:
  5871. stop += 2 * np.pi
  5872. if direction == "cw" and stop >= start:
  5873. stop -= 2 * np.pi
  5874. angle = abs(stop - start)
  5875. return angle
  5876. # def find_polygon(poly, point):
  5877. # """
  5878. # Find an object that object.contains(Point(point)) in
  5879. # poly, which can can be iterable, contain iterable of, or
  5880. # be itself an implementer of .contains().
  5881. #
  5882. # :param poly: See description
  5883. # :return: Polygon containing point or None.
  5884. # """
  5885. #
  5886. # if poly is None:
  5887. # return None
  5888. #
  5889. # try:
  5890. # for sub_poly in poly:
  5891. # p = find_polygon(sub_poly, point)
  5892. # if p is not None:
  5893. # return p
  5894. # except TypeError:
  5895. # try:
  5896. # if poly.contains(Point(point)):
  5897. # return poly
  5898. # except AttributeError:
  5899. # return None
  5900. #
  5901. # return None
  5902. def to_dict(obj):
  5903. """
  5904. Makes the following types into serializable form:
  5905. * ApertureMacro
  5906. * BaseGeometry
  5907. :param obj: Shapely geometry.
  5908. :type obj: BaseGeometry
  5909. :return: Dictionary with serializable form if ``obj`` was
  5910. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  5911. """
  5912. if isinstance(obj, ApertureMacro):
  5913. return {
  5914. "__class__": "ApertureMacro",
  5915. "__inst__": obj.to_dict()
  5916. }
  5917. if isinstance(obj, BaseGeometry):
  5918. return {
  5919. "__class__": "Shply",
  5920. "__inst__": sdumps(obj)
  5921. }
  5922. return obj
  5923. def dict2obj(d):
  5924. """
  5925. Default deserializer.
  5926. :param d: Serializable dictionary representation of an object
  5927. to be reconstructed.
  5928. :return: Reconstructed object.
  5929. """
  5930. if '__class__' in d and '__inst__' in d:
  5931. if d['__class__'] == "Shply":
  5932. return sloads(d['__inst__'])
  5933. if d['__class__'] == "ApertureMacro":
  5934. am = ApertureMacro()
  5935. am.from_dict(d['__inst__'])
  5936. return am
  5937. return d
  5938. else:
  5939. return d
  5940. # def plotg(geo, solid_poly=False, color="black"):
  5941. # try:
  5942. # __ = iter(geo)
  5943. # except:
  5944. # geo = [geo]
  5945. #
  5946. # for g in geo:
  5947. # if type(g) == Polygon:
  5948. # if solid_poly:
  5949. # patch = PolygonPatch(g,
  5950. # facecolor="#BBF268",
  5951. # edgecolor="#006E20",
  5952. # alpha=0.75,
  5953. # zorder=2)
  5954. # ax = subplot(111)
  5955. # ax.add_patch(patch)
  5956. # else:
  5957. # x, y = g.exterior.coords.xy
  5958. # plot(x, y, color=color)
  5959. # for ints in g.interiors:
  5960. # x, y = ints.coords.xy
  5961. # plot(x, y, color=color)
  5962. # continue
  5963. #
  5964. # if type(g) == LineString or type(g) == LinearRing:
  5965. # x, y = g.coords.xy
  5966. # plot(x, y, color=color)
  5967. # continue
  5968. #
  5969. # if type(g) == Point:
  5970. # x, y = g.coords.xy
  5971. # plot(x, y, 'o')
  5972. # continue
  5973. #
  5974. # try:
  5975. # __ = iter(g)
  5976. # plotg(g, color=color)
  5977. # except:
  5978. # log.error("Cannot plot: " + str(type(g)))
  5979. # continue
  5980. # def alpha_shape(points, alpha):
  5981. # """
  5982. # Compute the alpha shape (concave hull) of a set of points.
  5983. #
  5984. # @param points: Iterable container of points.
  5985. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  5986. # numbers don't fall inward as much as larger numbers. Too large,
  5987. # and you lose everything!
  5988. # """
  5989. # if len(points) < 4:
  5990. # # When you have a triangle, there is no sense in computing an alpha
  5991. # # shape.
  5992. # return MultiPoint(list(points)).convex_hull
  5993. #
  5994. # def add_edge(edges, edge_points, coords, i, j):
  5995. # """Add a line between the i-th and j-th points, if not in the list already"""
  5996. # if (i, j) in edges or (j, i) in edges:
  5997. # # already added
  5998. # return
  5999. # edges.add( (i, j) )
  6000. # edge_points.append(coords[ [i, j] ])
  6001. #
  6002. # coords = np.array([point.coords[0] for point in points])
  6003. #
  6004. # tri = Delaunay(coords)
  6005. # edges = set()
  6006. # edge_points = []
  6007. # # loop over triangles:
  6008. # # ia, ib, ic = indices of corner points of the triangle
  6009. # for ia, ib, ic in tri.vertices:
  6010. # pa = coords[ia]
  6011. # pb = coords[ib]
  6012. # pc = coords[ic]
  6013. #
  6014. # # Lengths of sides of triangle
  6015. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  6016. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  6017. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  6018. #
  6019. # # Semiperimeter of triangle
  6020. # s = (a + b + c)/2.0
  6021. #
  6022. # # Area of triangle by Heron's formula
  6023. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  6024. # circum_r = a*b*c/(4.0*area)
  6025. #
  6026. # # Here's the radius filter.
  6027. # #print circum_r
  6028. # if circum_r < 1.0/alpha:
  6029. # add_edge(edges, edge_points, coords, ia, ib)
  6030. # add_edge(edges, edge_points, coords, ib, ic)
  6031. # add_edge(edges, edge_points, coords, ic, ia)
  6032. #
  6033. # m = MultiLineString(edge_points)
  6034. # triangles = list(polygonize(m))
  6035. # return cascaded_union(triangles), edge_points
  6036. # def voronoi(P):
  6037. # """
  6038. # Returns a list of all edges of the voronoi diagram for the given input points.
  6039. # """
  6040. # delauny = Delaunay(P)
  6041. # triangles = delauny.points[delauny.vertices]
  6042. #
  6043. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  6044. # long_lines_endpoints = []
  6045. #
  6046. # lineIndices = []
  6047. # for i, triangle in enumerate(triangles):
  6048. # circum_center = circum_centers[i]
  6049. # for j, neighbor in enumerate(delauny.neighbors[i]):
  6050. # if neighbor != -1:
  6051. # lineIndices.append((i, neighbor))
  6052. # else:
  6053. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  6054. # ps = np.array((ps[1], -ps[0]))
  6055. #
  6056. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  6057. # di = middle - triangle[j]
  6058. #
  6059. # ps /= np.linalg.norm(ps)
  6060. # di /= np.linalg.norm(di)
  6061. #
  6062. # if np.dot(di, ps) < 0.0:
  6063. # ps *= -1000.0
  6064. # else:
  6065. # ps *= 1000.0
  6066. #
  6067. # long_lines_endpoints.append(circum_center + ps)
  6068. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  6069. #
  6070. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  6071. #
  6072. # # filter out any duplicate lines
  6073. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  6074. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  6075. # lineIndicesUnique = np.unique(lineIndicesTupled)
  6076. #
  6077. # return vertices, lineIndicesUnique
  6078. #
  6079. #
  6080. # def triangle_csc(pts):
  6081. # rows, cols = pts.shape
  6082. #
  6083. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  6084. # [np.ones((1, rows)), np.zeros((1, 1))]])
  6085. #
  6086. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  6087. # x = np.linalg.solve(A,b)
  6088. # bary_coords = x[:-1]
  6089. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  6090. #
  6091. #
  6092. # def voronoi_cell_lines(points, vertices, lineIndices):
  6093. # """
  6094. # Returns a mapping from a voronoi cell to its edges.
  6095. #
  6096. # :param points: shape (m,2)
  6097. # :param vertices: shape (n,2)
  6098. # :param lineIndices: shape (o,2)
  6099. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  6100. # """
  6101. # kd = KDTree(points)
  6102. #
  6103. # cells = collections.defaultdict(list)
  6104. # for i1, i2 in lineIndices:
  6105. # v1, v2 = vertices[i1], vertices[i2]
  6106. # mid = (v1+v2)/2
  6107. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  6108. # cells[p1Idx].append((i1, i2))
  6109. # cells[p2Idx].append((i1, i2))
  6110. #
  6111. # return cells
  6112. #
  6113. #
  6114. # def voronoi_edges2polygons(cells):
  6115. # """
  6116. # Transforms cell edges into polygons.
  6117. #
  6118. # :param cells: as returned from voronoi_cell_lines
  6119. # :rtype: dict point index -> list of vertex indices which form a polygon
  6120. # """
  6121. #
  6122. # # first, close the outer cells
  6123. # for pIdx, lineIndices_ in cells.items():
  6124. # dangling_lines = []
  6125. # for i1, i2 in lineIndices_:
  6126. # p = (i1, i2)
  6127. # connections = filter(lambda k: p != k and
  6128. # (p[0] == k[0] or p[0] == k[1] or p[1] == k[0] or p[1] == k[1]), lineIndices_)
  6129. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and
  6130. # (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  6131. # assert 1 <= len(connections) <= 2
  6132. # if len(connections) == 1:
  6133. # dangling_lines.append((i1, i2))
  6134. # assert len(dangling_lines) in [0, 2]
  6135. # if len(dangling_lines) == 2:
  6136. # (i11, i12), (i21, i22) = dangling_lines
  6137. # s = (i11, i12)
  6138. # t = (i21, i22)
  6139. #
  6140. # # determine which line ends are unconnected
  6141. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  6142. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  6143. # i11Unconnected = len(connected) == 0
  6144. #
  6145. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  6146. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  6147. # i21Unconnected = len(connected) == 0
  6148. #
  6149. # startIdx = i11 if i11Unconnected else i12
  6150. # endIdx = i21 if i21Unconnected else i22
  6151. #
  6152. # cells[pIdx].append((startIdx, endIdx))
  6153. #
  6154. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  6155. # polys = {}
  6156. # for pIdx, lineIndices_ in cells.items():
  6157. # # get a directed graph which contains both directions and arbitrarily follow one of both
  6158. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  6159. # directedGraphMap = collections.defaultdict(list)
  6160. # for (i1, i2) in directedGraph:
  6161. # directedGraphMap[i1].append(i2)
  6162. # orderedEdges = []
  6163. # currentEdge = directedGraph[0]
  6164. # while len(orderedEdges) < len(lineIndices_):
  6165. # i1 = currentEdge[1]
  6166. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  6167. # nextEdge = (i1, i2)
  6168. # orderedEdges.append(nextEdge)
  6169. # currentEdge = nextEdge
  6170. #
  6171. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  6172. #
  6173. # return polys
  6174. #
  6175. #
  6176. # def voronoi_polygons(points):
  6177. # """
  6178. # Returns the voronoi polygon for each input point.
  6179. #
  6180. # :param points: shape (n,2)
  6181. # :rtype: list of n polygons where each polygon is an array of vertices
  6182. # """
  6183. # vertices, lineIndices = voronoi(points)
  6184. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  6185. # polys = voronoi_edges2polygons(cells)
  6186. # polylist = []
  6187. # for i in range(len(points)):
  6188. # poly = vertices[np.asarray(polys[i])]
  6189. # polylist.append(poly)
  6190. # return polylist
  6191. #
  6192. #
  6193. # class Zprofile:
  6194. # def __init__(self):
  6195. #
  6196. # # data contains lists of [x, y, z]
  6197. # self.data = []
  6198. #
  6199. # # Computed voronoi polygons (shapely)
  6200. # self.polygons = []
  6201. # pass
  6202. #
  6203. # # def plot_polygons(self):
  6204. # # axes = plt.subplot(1, 1, 1)
  6205. # #
  6206. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  6207. # #
  6208. # # for poly in self.polygons:
  6209. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  6210. # # axes.add_patch(p)
  6211. #
  6212. # def init_from_csv(self, filename):
  6213. # pass
  6214. #
  6215. # def init_from_string(self, zpstring):
  6216. # pass
  6217. #
  6218. # def init_from_list(self, zplist):
  6219. # self.data = zplist
  6220. #
  6221. # def generate_polygons(self):
  6222. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  6223. #
  6224. # def normalize(self, origin):
  6225. # pass
  6226. #
  6227. # def paste(self, path):
  6228. # """
  6229. # Return a list of dictionaries containing the parts of the original
  6230. # path and their z-axis offset.
  6231. # """
  6232. #
  6233. # # At most one region/polygon will contain the path
  6234. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  6235. #
  6236. # if len(containing) > 0:
  6237. # return [{"path": path, "z": self.data[containing[0]][2]}]
  6238. #
  6239. # # All region indexes that intersect with the path
  6240. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  6241. #
  6242. # return [{"path": path.intersection(self.polygons[i]),
  6243. # "z": self.data[i][2]} for i in crossing]
  6244. def autolist(obj):
  6245. try:
  6246. __ = iter(obj)
  6247. return obj
  6248. except TypeError:
  6249. return [obj]
  6250. def three_point_circle(p1, p2, p3):
  6251. """
  6252. Computes the center and radius of a circle from
  6253. 3 points on its circumference.
  6254. :param p1: Point 1
  6255. :param p2: Point 2
  6256. :param p3: Point 3
  6257. :return: center, radius
  6258. """
  6259. # Midpoints
  6260. a1 = (p1 + p2) / 2.0
  6261. a2 = (p2 + p3) / 2.0
  6262. # Normals
  6263. b1 = np.dot((p2 - p1), np.array([[0, -1], [1, 0]], dtype=np.float32))
  6264. b2 = np.dot((p3 - p2), np.array([[0, 1], [-1, 0]], dtype=np.float32))
  6265. # Params
  6266. try:
  6267. T = solve(np.transpose(np.array([-b1, b2])), a1 - a2)
  6268. except Exception as e:
  6269. log.debug("camlib.three_point_circle() --> %s" % str(e))
  6270. return
  6271. # Center
  6272. center = a1 + b1 * T[0]
  6273. # Radius
  6274. radius = np.linalg.norm(center - p1)
  6275. return center, radius, T[0]
  6276. def distance(pt1, pt2):
  6277. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  6278. def distance_euclidian(x1, y1, x2, y2):
  6279. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  6280. class FlatCAMRTree(object):
  6281. """
  6282. Indexes geometry (Any object with "cooords" property containing
  6283. a list of tuples with x, y values). Objects are indexed by
  6284. all their points by default. To index by arbitrary points,
  6285. override self.points2obj.
  6286. """
  6287. def __init__(self):
  6288. # Python RTree Index
  6289. self.rti = rtindex.Index()
  6290. # ## Track object-point relationship
  6291. # Each is list of points in object.
  6292. self.obj2points = []
  6293. # Index is index in rtree, value is index of
  6294. # object in obj2points.
  6295. self.points2obj = []
  6296. self.get_points = lambda go: go.coords
  6297. def grow_obj2points(self, idx):
  6298. """
  6299. Increases the size of self.obj2points to fit
  6300. idx + 1 items.
  6301. :param idx: Index to fit into list.
  6302. :return: None
  6303. """
  6304. if len(self.obj2points) > idx:
  6305. # len == 2, idx == 1, ok.
  6306. return
  6307. else:
  6308. # len == 2, idx == 2, need 1 more.
  6309. # range(2, 3)
  6310. for i in range(len(self.obj2points), idx + 1):
  6311. self.obj2points.append([])
  6312. def insert(self, objid, obj):
  6313. self.grow_obj2points(objid)
  6314. self.obj2points[objid] = []
  6315. for pt in self.get_points(obj):
  6316. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  6317. self.obj2points[objid].append(len(self.points2obj))
  6318. self.points2obj.append(objid)
  6319. def remove_obj(self, objid, obj):
  6320. # Use all ptids to delete from index
  6321. for i, pt in enumerate(self.get_points(obj)):
  6322. try:
  6323. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  6324. except IndexError:
  6325. pass
  6326. def nearest(self, pt):
  6327. """
  6328. Will raise StopIteration if no items are found.
  6329. :param pt:
  6330. :return:
  6331. """
  6332. return next(self.rti.nearest(pt, objects=True))
  6333. class FlatCAMRTreeStorage(FlatCAMRTree):
  6334. """
  6335. Just like FlatCAMRTree it indexes geometry, but also serves
  6336. as storage for the geometry.
  6337. """
  6338. def __init__(self):
  6339. # super(FlatCAMRTreeStorage, self).__init__()
  6340. super().__init__()
  6341. self.objects = []
  6342. # Optimization attempt!
  6343. self.indexes = {}
  6344. def insert(self, obj):
  6345. self.objects.append(obj)
  6346. idx = len(self.objects) - 1
  6347. # Note: Shapely objects are not hashable any more, although
  6348. # there seem to be plans to re-introduce the feature in
  6349. # version 2.0. For now, we will index using the object's id,
  6350. # but it's important to remember that shapely geometry is
  6351. # mutable, ie. it can be modified to a totally different shape
  6352. # and continue to have the same id.
  6353. # self.indexes[obj] = idx
  6354. self.indexes[id(obj)] = idx
  6355. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  6356. super().insert(idx, obj)
  6357. # @profile
  6358. def remove(self, obj):
  6359. # See note about self.indexes in insert().
  6360. # objidx = self.indexes[obj]
  6361. objidx = self.indexes[id(obj)]
  6362. # Remove from list
  6363. self.objects[objidx] = None
  6364. # Remove from index
  6365. self.remove_obj(objidx, obj)
  6366. def get_objects(self):
  6367. return (o for o in self.objects if o is not None)
  6368. def nearest(self, pt):
  6369. """
  6370. Returns the nearest matching points and the object
  6371. it belongs to.
  6372. :param pt: Query point.
  6373. :return: (match_x, match_y), Object owner of
  6374. matching point.
  6375. :rtype: tuple
  6376. """
  6377. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  6378. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  6379. # class myO:
  6380. # def __init__(self, coords):
  6381. # self.coords = coords
  6382. #
  6383. #
  6384. # def test_rti():
  6385. #
  6386. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6387. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6388. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6389. #
  6390. # os = [o1, o2]
  6391. #
  6392. # idx = FlatCAMRTree()
  6393. #
  6394. # for o in range(len(os)):
  6395. # idx.insert(o, os[o])
  6396. #
  6397. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6398. #
  6399. # idx.remove_obj(0, o1)
  6400. #
  6401. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6402. #
  6403. # idx.remove_obj(1, o2)
  6404. #
  6405. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6406. #
  6407. #
  6408. # def test_rtis():
  6409. #
  6410. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6411. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6412. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6413. #
  6414. # os = [o1, o2]
  6415. #
  6416. # idx = FlatCAMRTreeStorage()
  6417. #
  6418. # for o in range(len(os)):
  6419. # idx.insert(os[o])
  6420. #
  6421. # #os = None
  6422. # #o1 = None
  6423. # #o2 = None
  6424. #
  6425. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6426. #
  6427. # idx.remove(idx.nearest((2,0))[1])
  6428. #
  6429. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6430. #
  6431. # idx.remove(idx.nearest((0,0))[1])
  6432. #
  6433. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]