camlib.py 315 KB

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