camlib.py 264 KB

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