camlib.py 262 KB

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