camlib.py 262 KB

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