camlib.py 307 KB

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