camlib.py 270 KB

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