camlib.py 366 KB

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