camlib.py 317 KB

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