camlib.py 353 KB

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