camlib.py 303 KB

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