camlib.py 313 KB

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