camlib.py 375 KB

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