camlib.py 360 KB

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