camlib.py 360 KB

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