camlib.py 364 KB

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