camlib.py 252 KB

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