camlib.py 265 KB

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