camlib.py 371 KB

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