camlib.py 356 KB

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