camlib.py 376 KB

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