camlib.py 307 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755
  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. geo_s = None
  2196. geo_f = None
  2197. if last_path_aperture is None:
  2198. if '0' not in self.apertures:
  2199. self.apertures['0'] = {}
  2200. self.apertures['0']['type'] = 'REG'
  2201. self.apertures['0']['size'] = 0.0
  2202. self.apertures['0']['geometry'] = []
  2203. last_path_aperture = '0'
  2204. width = 0
  2205. else:
  2206. width = self.apertures[last_path_aperture]["size"]
  2207. if making_region:
  2208. try:
  2209. geo_s = Polygon(path)
  2210. except ValueError:
  2211. log.warning(
  2212. "Not enough points in path to create a Polygon %s %s" % (gline, line_num))
  2213. try:
  2214. geo_f = LineString(path)
  2215. except ValueError:
  2216. log.warning(
  2217. "Not enough points in path to create a LineString %s %s" % (gline, line_num))
  2218. else:
  2219. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2220. geo_f = LineString(path)
  2221. if self.apertures[last_path_aperture]["type"] != 'R':
  2222. poly_buffer.append(deepcopy(geo_s))
  2223. follow_buffer.append(deepcopy(geo_f))
  2224. geo_dict = dict()
  2225. geo_dict['follow'] = geo_f
  2226. if geo_s:
  2227. if self.is_lpc:
  2228. geo_dict['clear'] = deepcopy(geo_s)
  2229. else:
  2230. geo_dict['solid'] = deepcopy(geo_s)
  2231. try:
  2232. self.apertures[last_path_aperture]['geometry'].append(geo_dict)
  2233. except KeyError:
  2234. self.apertures[last_path_aperture]['geometry'] = []
  2235. self.apertures[last_path_aperture]['geometry'].append(geo_dict)
  2236. # if linear_x or linear_y are None, ignore those
  2237. if linear_x is not None and linear_y is not None:
  2238. path = [[linear_x, linear_y]] # Start new path
  2239. else:
  2240. self.app.inform.emit(_("[WARNING] Coordinates missing, line ignored: %s") % str(gline))
  2241. self.app.inform.emit(_("[WARNING_NOTCL] GERBER file might be CORRUPT. Check the file !!!"))
  2242. # Flash
  2243. # Not allowed in region mode.
  2244. elif current_operation_code == 3:
  2245. width = self.apertures[last_path_aperture]["size"]
  2246. # finish the path draw until now
  2247. if len(path) > 1 and self.apertures[last_path_aperture]["type"] != 'R':
  2248. geo_f = LineString(path)
  2249. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2250. follow_buffer.append(geo_f)
  2251. poly_buffer.append(geo_s)
  2252. geo_dict = dict()
  2253. geo_dict['follow'] = geo_f
  2254. if self.is_lpc:
  2255. geo_dict['clear'] = geo_s
  2256. else:
  2257. geo_dict['solid'] = geo_s
  2258. try:
  2259. self.apertures[last_path_aperture]['geometry'].append(geo_dict)
  2260. except KeyError:
  2261. self.apertures[last_path_aperture]['geometry'] = []
  2262. self.apertures[last_path_aperture]['geometry'].append(geo_dict)
  2263. # Reset path starting point
  2264. path = [[linear_x, linear_y]]
  2265. # Draw the flash
  2266. geo_f = Point(linear_x, linear_y)
  2267. geo_s = Gerber.create_flash_geometry(
  2268. Point([linear_x, linear_y]),
  2269. self.apertures[current_aperture],
  2270. int(self.steps_per_circle)
  2271. )
  2272. follow_buffer.append(geo_f)
  2273. if not geo_s.is_empty:
  2274. poly_buffer.append(geo_s)
  2275. geo_dict = dict()
  2276. geo_dict['follow'] = geo_f
  2277. if not geo_s.is_empty:
  2278. if self.is_lpc:
  2279. geo_dict['clear'] = geo_s
  2280. else:
  2281. geo_dict['solid'] = geo_s
  2282. try:
  2283. self.apertures[current_aperture]['geometry'].append(geo_dict)
  2284. except KeyError:
  2285. self.apertures[current_aperture]['geometry'] = []
  2286. self.apertures[current_aperture]['geometry'].append(geo_dict)
  2287. # maybe those lines are not exactly needed but it is easier to read the program as those coordinates
  2288. # are used in case that circular interpolation is encountered within the Gerber file
  2289. current_x = linear_x
  2290. current_y = linear_y
  2291. # log.debug("Line_number=%3s X=%s Y=%s (%s)" % (line_num, linear_x, linear_y, gline))
  2292. continue
  2293. ### G74/75* - Single or multiple quadrant arcs
  2294. match = self.quad_re.search(gline)
  2295. if match:
  2296. if match.group(1) == '4':
  2297. quadrant_mode = 'SINGLE'
  2298. else:
  2299. quadrant_mode = 'MULTI'
  2300. continue
  2301. ### G02/3 - Circular interpolation
  2302. # 2-clockwise, 3-counterclockwise
  2303. # Ex. format: G03 X0 Y50 I-50 J0 where the X, Y coords are the coords of the End Point
  2304. match = self.circ_re.search(gline)
  2305. if match:
  2306. arcdir = [None, None, "cw", "ccw"]
  2307. mode, circular_x, circular_y, i, j, d = match.groups()
  2308. try:
  2309. circular_x = parse_gerber_number(circular_x,
  2310. self.int_digits, self.frac_digits, self.gerber_zeros)
  2311. except:
  2312. circular_x = current_x
  2313. try:
  2314. circular_y = parse_gerber_number(circular_y,
  2315. self.int_digits, self.frac_digits, self.gerber_zeros)
  2316. except:
  2317. circular_y = current_y
  2318. # According to Gerber specification i and j are not modal, which means that when i or j are missing,
  2319. # they are to be interpreted as being zero
  2320. try:
  2321. i = parse_gerber_number(i, self.int_digits, self.frac_digits, self.gerber_zeros)
  2322. except:
  2323. i = 0
  2324. try:
  2325. j = parse_gerber_number(j, self.int_digits, self.frac_digits, self.gerber_zeros)
  2326. except:
  2327. j = 0
  2328. if quadrant_mode is None:
  2329. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  2330. log.error(gline)
  2331. continue
  2332. if mode is None and current_interpolation_mode not in [2, 3]:
  2333. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  2334. log.error(gline)
  2335. continue
  2336. elif mode is not None:
  2337. current_interpolation_mode = int(mode)
  2338. # Set operation code if provided
  2339. if d is not None:
  2340. current_operation_code = int(d)
  2341. # Nothing created! Pen Up.
  2342. if current_operation_code == 2:
  2343. log.warning("Arc with D2. (%d)" % line_num)
  2344. # if we have something drawn until this moment, add it
  2345. if len(path) > 1:
  2346. # if last_path_aperture is None:
  2347. # log.warning("No aperture defined for curent path. (%d)" % line_num)
  2348. if last_path_aperture is None:
  2349. if '0' not in self.apertures:
  2350. self.apertures['0'] = {}
  2351. self.apertures['0']['type'] = 'REG'
  2352. self.apertures['0']['size'] = 0.0
  2353. self.apertures['0']['geometry'] = []
  2354. last_path_aperture = '0'
  2355. width = 0
  2356. # --- BUFFERED ---
  2357. width = self.apertures[last_path_aperture]["size"]
  2358. geo_f = LineString(path)
  2359. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2360. if not geo_s.is_empty:
  2361. follow_buffer.append(geo_f)
  2362. poly_buffer.append(geo_s)
  2363. geo_dict = dict()
  2364. geo_dict['follow'] = geo_f
  2365. if not geo_s.is_empty:
  2366. if self.is_lpc:
  2367. geo_dict['clear'] = geo_s
  2368. else:
  2369. geo_dict['solid'] = geo_s
  2370. try:
  2371. self.apertures[last_path_aperture]['geometry'].append(geo_dict)
  2372. except KeyError:
  2373. self.apertures[last_path_aperture]['geometry'] = []
  2374. self.apertures[last_path_aperture]['geometry'].append(geo_dict)
  2375. current_x = circular_x
  2376. current_y = circular_y
  2377. path = [[current_x, current_y]] # Start new path
  2378. continue
  2379. # Flash should not happen here
  2380. if current_operation_code == 3:
  2381. log.error("Trying to flash within arc. (%d)" % line_num)
  2382. continue
  2383. if quadrant_mode == 'MULTI':
  2384. center = [i + current_x, j + current_y]
  2385. radius = sqrt(i ** 2 + j ** 2)
  2386. start = arctan2(-j, -i) # Start angle
  2387. # Numerical errors might prevent start == stop therefore
  2388. # we check ahead of time. This should result in a
  2389. # 360 degree arc.
  2390. if current_x == circular_x and current_y == circular_y:
  2391. stop = start
  2392. else:
  2393. stop = arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  2394. this_arc = arc(center, radius, start, stop,
  2395. arcdir[current_interpolation_mode],
  2396. int(self.steps_per_circle))
  2397. # The last point in the computed arc can have
  2398. # numerical errors. The exact final point is the
  2399. # specified (x, y). Replace.
  2400. this_arc[-1] = (circular_x, circular_y)
  2401. # Last point in path is current point
  2402. # current_x = this_arc[-1][0]
  2403. # current_y = this_arc[-1][1]
  2404. current_x, current_y = circular_x, circular_y
  2405. # Append
  2406. path += this_arc
  2407. last_path_aperture = current_aperture
  2408. continue
  2409. if quadrant_mode == 'SINGLE':
  2410. center_candidates = [
  2411. [i + current_x, j + current_y],
  2412. [-i + current_x, j + current_y],
  2413. [i + current_x, -j + current_y],
  2414. [-i + current_x, -j + current_y]
  2415. ]
  2416. valid = False
  2417. log.debug("I: %f J: %f" % (i, j))
  2418. for center in center_candidates:
  2419. radius = sqrt(i ** 2 + j ** 2)
  2420. # Make sure radius to start is the same as radius to end.
  2421. radius2 = sqrt((center[0] - circular_x) ** 2 + (center[1] - circular_y) ** 2)
  2422. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  2423. continue # Not a valid center.
  2424. # Correct i and j and continue as with multi-quadrant.
  2425. i = center[0] - current_x
  2426. j = center[1] - current_y
  2427. start = arctan2(-j, -i) # Start angle
  2428. stop = arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  2429. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  2430. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  2431. (current_x, current_y, center[0], center[1], circular_x, circular_y))
  2432. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  2433. (start * 180 / pi, stop * 180 / pi, arcdir[current_interpolation_mode],
  2434. angle * 180 / pi, pi / 2 * 180 / pi, angle <= (pi + 1e-6) / 2))
  2435. if angle <= (pi + 1e-6) / 2:
  2436. log.debug("########## ACCEPTING ARC ############")
  2437. this_arc = arc(center, radius, start, stop,
  2438. arcdir[current_interpolation_mode],
  2439. int(self.steps_per_circle))
  2440. # Replace with exact values
  2441. this_arc[-1] = (circular_x, circular_y)
  2442. # current_x = this_arc[-1][0]
  2443. # current_y = this_arc[-1][1]
  2444. current_x, current_y = circular_x, circular_y
  2445. path += this_arc
  2446. last_path_aperture = current_aperture
  2447. valid = True
  2448. break
  2449. if valid:
  2450. continue
  2451. else:
  2452. log.warning("Invalid arc in line %d." % line_num)
  2453. ## EOF
  2454. match = self.eof_re.search(gline)
  2455. if match:
  2456. continue
  2457. ### Line did not match any pattern. Warn user.
  2458. log.warning("Line ignored (%d): %s" % (line_num, gline))
  2459. if len(path) > 1:
  2460. # In case that G01 (moving) aperture is rectangular, there is no need to still create
  2461. # another geo since we already created a shapely box using the start and end coordinates found in
  2462. # path variable. We do it only for other apertures than 'R' type
  2463. if self.apertures[last_path_aperture]["type"] != 'R':
  2464. # EOF, create shapely LineString if something still in path
  2465. width = self.apertures[last_path_aperture]["size"]
  2466. geo_f = LineString(path)
  2467. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  2468. follow_buffer.append(geo_f)
  2469. if not geo_s.is_empty:
  2470. poly_buffer.append(geo_s)
  2471. geo_dict = dict()
  2472. geo_dict['follow'] = geo_f
  2473. if not geo_s.is_empty:
  2474. if self.is_lpc:
  2475. geo_dict['clear'] = geo_s
  2476. else:
  2477. geo_dict['solid'] = geo_s
  2478. try:
  2479. self.apertures[last_path_aperture]['geometry'].append(geo_dict)
  2480. except KeyError:
  2481. self.apertures[last_path_aperture]['geometry'] = []
  2482. self.apertures[last_path_aperture]['geometry'].append(geo_dict)
  2483. # --- Apply buffer ---
  2484. # this treats the case when we are storing geometry as paths
  2485. self.follow_geometry = follow_buffer
  2486. # this treats the case when we are storing geometry as solids
  2487. log.warning("Joining %d polygons." % len(poly_buffer))
  2488. if len(poly_buffer) == 0:
  2489. log.error("Object is not Gerber file or empty. Aborting Object creation.")
  2490. return 'fail'
  2491. if self.use_buffer_for_union:
  2492. log.debug("Union by buffer...")
  2493. new_poly = MultiPolygon(poly_buffer)
  2494. new_poly = new_poly.buffer(0.00000001)
  2495. new_poly = new_poly.buffer(-0.00000001)
  2496. log.warning("Union(buffer) done.")
  2497. else:
  2498. log.debug("Union by union()...")
  2499. new_poly = cascaded_union(poly_buffer)
  2500. new_poly = new_poly.buffer(0, int(self.steps_per_circle / 4))
  2501. log.warning("Union done.")
  2502. if current_polarity == 'D':
  2503. self.solid_geometry = self.solid_geometry.union(new_poly)
  2504. else:
  2505. self.solid_geometry = self.solid_geometry.difference(new_poly)
  2506. except Exception as err:
  2507. ex_type, ex, tb = sys.exc_info()
  2508. traceback.print_tb(tb)
  2509. #print traceback.format_exc()
  2510. log.error("Gerber PARSING FAILED. Line %d: %s" % (line_num, gline))
  2511. loc = 'Gerber Line #%d Gerber Line Content: %s\n' % (line_num, gline) + repr(err)
  2512. self.app.inform.emit(_("[ERROR]Gerber Parser ERROR.\n%s:") % loc)
  2513. @staticmethod
  2514. def create_flash_geometry(location, aperture, steps_per_circle=None):
  2515. # log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  2516. if steps_per_circle is None:
  2517. steps_per_circle = 64
  2518. if type(location) == list:
  2519. location = Point(location)
  2520. if aperture['type'] == 'C': # Circles
  2521. return location.buffer(aperture['size'] / 2, int(steps_per_circle / 4))
  2522. if aperture['type'] == 'R': # Rectangles
  2523. loc = location.coords[0]
  2524. width = aperture['width']
  2525. height = aperture['height']
  2526. minx = loc[0] - width / 2
  2527. maxx = loc[0] + width / 2
  2528. miny = loc[1] - height / 2
  2529. maxy = loc[1] + height / 2
  2530. return shply_box(minx, miny, maxx, maxy)
  2531. if aperture['type'] == 'O': # Obround
  2532. loc = location.coords[0]
  2533. width = aperture['width']
  2534. height = aperture['height']
  2535. if width > height:
  2536. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  2537. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  2538. c1 = p1.buffer(height * 0.5, int(steps_per_circle / 4))
  2539. c2 = p2.buffer(height * 0.5, int(steps_per_circle / 4))
  2540. else:
  2541. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  2542. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  2543. c1 = p1.buffer(width * 0.5, int(steps_per_circle / 4))
  2544. c2 = p2.buffer(width * 0.5, int(steps_per_circle / 4))
  2545. return cascaded_union([c1, c2]).convex_hull
  2546. if aperture['type'] == 'P': # Regular polygon
  2547. loc = location.coords[0]
  2548. diam = aperture['diam']
  2549. n_vertices = aperture['nVertices']
  2550. points = []
  2551. for i in range(0, n_vertices):
  2552. x = loc[0] + 0.5 * diam * (cos(2 * pi * i / n_vertices))
  2553. y = loc[1] + 0.5 * diam * (sin(2 * pi * i / n_vertices))
  2554. points.append((x, y))
  2555. ply = Polygon(points)
  2556. if 'rotation' in aperture:
  2557. ply = affinity.rotate(ply, aperture['rotation'])
  2558. return ply
  2559. if aperture['type'] == 'AM': # Aperture Macro
  2560. loc = location.coords[0]
  2561. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  2562. if flash_geo.is_empty:
  2563. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  2564. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  2565. log.warning("Unknown aperture type: %s" % aperture['type'])
  2566. return None
  2567. def create_geometry(self):
  2568. """
  2569. Geometry from a Gerber file is made up entirely of polygons.
  2570. Every stroke (linear or circular) has an aperture which gives
  2571. it thickness. Additionally, aperture strokes have non-zero area,
  2572. and regions naturally do as well.
  2573. :rtype : None
  2574. :return: None
  2575. """
  2576. pass
  2577. # self.buffer_paths()
  2578. #
  2579. # self.fix_regions()
  2580. #
  2581. # self.do_flashes()
  2582. #
  2583. # self.solid_geometry = cascaded_union(self.buffered_paths +
  2584. # [poly['polygon'] for poly in self.regions] +
  2585. # self.flash_geometry)
  2586. def get_bounding_box(self, margin=0.0, rounded=False):
  2587. """
  2588. Creates and returns a rectangular polygon bounding at a distance of
  2589. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  2590. can optionally have rounded corners of radius equal to margin.
  2591. :param margin: Distance to enlarge the rectangular bounding
  2592. box in both positive and negative, x and y axes.
  2593. :type margin: float
  2594. :param rounded: Wether or not to have rounded corners.
  2595. :type rounded: bool
  2596. :return: The bounding box.
  2597. :rtype: Shapely.Polygon
  2598. """
  2599. bbox = self.solid_geometry.envelope.buffer(margin)
  2600. if not rounded:
  2601. bbox = bbox.envelope
  2602. return bbox
  2603. def bounds(self):
  2604. """
  2605. Returns coordinates of rectangular bounds
  2606. of Gerber geometry: (xmin, ymin, xmax, ymax).
  2607. """
  2608. # fixed issue of getting bounds only for one level lists of objects
  2609. # now it can get bounds for nested lists of objects
  2610. log.debug("Gerber->bounds()")
  2611. if self.solid_geometry is None:
  2612. log.debug("solid_geometry is None")
  2613. return 0, 0, 0, 0
  2614. def bounds_rec(obj):
  2615. if type(obj) is list and type(obj) is not MultiPolygon:
  2616. minx = Inf
  2617. miny = Inf
  2618. maxx = -Inf
  2619. maxy = -Inf
  2620. for k in obj:
  2621. if type(k) is dict:
  2622. for key in k:
  2623. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  2624. minx = min(minx, minx_)
  2625. miny = min(miny, miny_)
  2626. maxx = max(maxx, maxx_)
  2627. maxy = max(maxy, maxy_)
  2628. else:
  2629. if not k.is_empty:
  2630. try:
  2631. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2632. except Exception as e:
  2633. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  2634. return
  2635. minx = min(minx, minx_)
  2636. miny = min(miny, miny_)
  2637. maxx = max(maxx, maxx_)
  2638. maxy = max(maxy, maxy_)
  2639. return minx, miny, maxx, maxy
  2640. else:
  2641. # it's a Shapely object, return it's bounds
  2642. return obj.bounds
  2643. bounds_coords = bounds_rec(self.solid_geometry)
  2644. return bounds_coords
  2645. def scale(self, xfactor, yfactor=None, point=None):
  2646. """
  2647. Scales the objects' geometry on the XY plane by a given factor.
  2648. These are:
  2649. * ``buffered_paths``
  2650. * ``flash_geometry``
  2651. * ``solid_geometry``
  2652. * ``regions``
  2653. NOTE:
  2654. Does not modify the data used to create these elements. If these
  2655. are recreated, the scaling will be lost. This behavior was modified
  2656. because of the complexity reached in this class.
  2657. :param factor: Number by which to scale.
  2658. :type factor: float
  2659. :rtype : None
  2660. """
  2661. log.debug("camlib.Gerber.scale()")
  2662. try:
  2663. xfactor = float(xfactor)
  2664. except:
  2665. self.app.inform.emit(_("[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  2666. return
  2667. if yfactor is None:
  2668. yfactor = xfactor
  2669. else:
  2670. try:
  2671. yfactor = float(yfactor)
  2672. except:
  2673. self.app.inform.emit(_("[ERROR_NOTCL] Scale factor has to be a number: integer or float."))
  2674. return
  2675. if point is None:
  2676. px = 0
  2677. py = 0
  2678. else:
  2679. px, py = point
  2680. def scale_geom(obj):
  2681. if type(obj) is list:
  2682. new_obj = []
  2683. for g in obj:
  2684. new_obj.append(scale_geom(g))
  2685. return new_obj
  2686. else:
  2687. return affinity.scale(obj, xfactor, yfactor, origin=(px, py))
  2688. self.solid_geometry = scale_geom(self.solid_geometry)
  2689. self.follow_geometry = scale_geom(self.follow_geometry)
  2690. # we need to scale the geometry stored in the Gerber apertures, too
  2691. try:
  2692. for apid in self.apertures:
  2693. if 'geometry' in self.apertures[apid]:
  2694. for geo_el in self.apertures[apid]['geometry']:
  2695. if 'solid' in geo_el:
  2696. geo_el['solid'] = scale_geom(geo_el['solid'])
  2697. if 'follow' in geo_el:
  2698. geo_el['follow'] = scale_geom(geo_el['follow'])
  2699. if 'clear' in geo_el:
  2700. geo_el['clear'] = scale_geom(geo_el['clear'])
  2701. except Exception as e:
  2702. log.debug('camlib.Gerber.scale() Exception --> %s' % str(e))
  2703. return 'fail'
  2704. self.app.inform.emit(_("[success] Gerber Scale done."))
  2705. def offset(self, vect):
  2706. """
  2707. Offsets the objects' geometry on the XY plane by a given vector.
  2708. These are:
  2709. * ``buffered_paths``
  2710. * ``flash_geometry``
  2711. * ``solid_geometry``
  2712. * ``regions``
  2713. NOTE:
  2714. Does not modify the data used to create these elements. If these
  2715. are recreated, the scaling will be lost. This behavior was modified
  2716. because of the complexity reached in this class.
  2717. :param vect: (x, y) offset vector.
  2718. :type vect: tuple
  2719. :return: None
  2720. """
  2721. try:
  2722. dx, dy = vect
  2723. except TypeError:
  2724. self.app.inform.emit(_("[ERROR_NOTCL] An (x,y) pair of values are needed. "
  2725. "Probable you entered only one value in the Offset field."))
  2726. return
  2727. def offset_geom(obj):
  2728. if type(obj) is list:
  2729. new_obj = []
  2730. for g in obj:
  2731. new_obj.append(offset_geom(g))
  2732. return new_obj
  2733. else:
  2734. return affinity.translate(obj, xoff=dx, yoff=dy)
  2735. ## Solid geometry
  2736. self.solid_geometry = offset_geom(self.solid_geometry)
  2737. self.follow_geometry = offset_geom(self.follow_geometry)
  2738. # we need to offset the geometry stored in the Gerber apertures, too
  2739. try:
  2740. for apid in self.apertures:
  2741. if 'geometry' in self.apertures[apid]:
  2742. for geo_el in self.apertures[apid]['geometry']:
  2743. if 'solid' in geo_el:
  2744. geo_el['solid'] = offset_geom(geo_el['solid'])
  2745. if 'follow' in geo_el:
  2746. geo_el['follow'] = offset_geom(geo_el['follow'])
  2747. if 'clear' in geo_el:
  2748. geo_el['clear'] = offset_geom(geo_el['clear'])
  2749. except Exception as e:
  2750. log.debug('camlib.Gerber.offset() Exception --> %s' % str(e))
  2751. return 'fail'
  2752. self.app.inform.emit(_("[success] Gerber Offset done."))
  2753. def mirror(self, axis, point):
  2754. """
  2755. Mirrors the object around a specified axis passing through
  2756. the given point. What is affected:
  2757. * ``buffered_paths``
  2758. * ``flash_geometry``
  2759. * ``solid_geometry``
  2760. * ``regions``
  2761. NOTE:
  2762. Does not modify the data used to create these elements. If these
  2763. are recreated, the scaling will be lost. This behavior was modified
  2764. because of the complexity reached in this class.
  2765. :param axis: "X" or "Y" indicates around which axis to mirror.
  2766. :type axis: str
  2767. :param point: [x, y] point belonging to the mirror axis.
  2768. :type point: list
  2769. :return: None
  2770. """
  2771. px, py = point
  2772. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  2773. def mirror_geom(obj):
  2774. if type(obj) is list:
  2775. new_obj = []
  2776. for g in obj:
  2777. new_obj.append(mirror_geom(g))
  2778. return new_obj
  2779. else:
  2780. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  2781. self.solid_geometry = mirror_geom(self.solid_geometry)
  2782. self.follow_geometry = mirror_geom(self.follow_geometry)
  2783. # we need to mirror the geometry stored in the Gerber apertures, too
  2784. try:
  2785. for apid in self.apertures:
  2786. if 'geometry' in self.apertures[apid]:
  2787. for geo_el in self.apertures[apid]['geometry']:
  2788. if 'solid' in geo_el:
  2789. geo_el['solid'] = mirror_geom(geo_el['solid'])
  2790. if 'follow' in geo_el:
  2791. geo_el['follow'] = mirror_geom(geo_el['follow'])
  2792. if 'clear' in geo_el:
  2793. geo_el['clear'] = mirror_geom(geo_el['clear'])
  2794. except Exception as e:
  2795. log.debug('camlib.Gerber.mirror() Exception --> %s' % str(e))
  2796. return 'fail'
  2797. self.app.inform.emit(_("[success] Gerber Mirror done."))
  2798. def skew(self, angle_x, angle_y, point):
  2799. """
  2800. Shear/Skew the geometries of an object by angles along x and y dimensions.
  2801. Parameters
  2802. ----------
  2803. xs, ys : float, float
  2804. The shear angle(s) for the x and y axes respectively. These can be
  2805. specified in either degrees (default) or radians by setting
  2806. use_radians=True.
  2807. See shapely manual for more information:
  2808. http://toblerity.org/shapely/manual.html#affine-transformations
  2809. """
  2810. px, py = point
  2811. def skew_geom(obj):
  2812. if type(obj) is list:
  2813. new_obj = []
  2814. for g in obj:
  2815. new_obj.append(skew_geom(g))
  2816. return new_obj
  2817. else:
  2818. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  2819. self.solid_geometry = skew_geom(self.solid_geometry)
  2820. self.follow_geometry = skew_geom(self.follow_geometry)
  2821. # we need to skew the geometry stored in the Gerber apertures, too
  2822. try:
  2823. for apid in self.apertures:
  2824. if 'geometry' in self.apertures[apid]:
  2825. for geo_el in self.apertures[apid]['geometry']:
  2826. if 'solid' in geo_el:
  2827. geo_el['solid'] = skew_geom(geo_el['solid'])
  2828. if 'follow' in geo_el:
  2829. geo_el['follow'] = skew_geom(geo_el['follow'])
  2830. if 'clear' in geo_el:
  2831. geo_el['clear'] = skew_geom(geo_el['clear'])
  2832. except Exception as e:
  2833. log.debug('camlib.Gerber.skew() Exception --> %s' % str(e))
  2834. return 'fail'
  2835. self.app.inform.emit(_("[success] Gerber Skew done."))
  2836. def rotate(self, angle, point):
  2837. """
  2838. Rotate an object by a given angle around given coords (point)
  2839. :param angle:
  2840. :param point:
  2841. :return:
  2842. """
  2843. px, py = point
  2844. def rotate_geom(obj):
  2845. if type(obj) is list:
  2846. new_obj = []
  2847. for g in obj:
  2848. new_obj.append(rotate_geom(g))
  2849. return new_obj
  2850. else:
  2851. return affinity.rotate(obj, angle, origin=(px, py))
  2852. self.solid_geometry = rotate_geom(self.solid_geometry)
  2853. self.follow_geometry = rotate_geom(self.follow_geometry)
  2854. # we need to rotate the geometry stored in the Gerber apertures, too
  2855. try:
  2856. for apid in self.apertures:
  2857. if 'geometry' in self.apertures[apid]:
  2858. for geo_el in self.apertures[apid]['geometry']:
  2859. if 'solid' in geo_el:
  2860. geo_el['solid'] = rotate_geom(geo_el['solid'])
  2861. if 'follow' in geo_el:
  2862. geo_el['follow'] = rotate_geom(geo_el['follow'])
  2863. if 'clear' in geo_el:
  2864. geo_el['clear'] = rotate_geom(geo_el['clear'])
  2865. except Exception as e:
  2866. log.debug('camlib.Gerber.rotate() Exception --> %s' % str(e))
  2867. return 'fail'
  2868. self.app.inform.emit(_("[success] Gerber Rotate done."))
  2869. class Excellon(Geometry):
  2870. """
  2871. *ATTRIBUTES*
  2872. * ``tools`` (dict): The key is the tool name and the value is
  2873. a dictionary specifying the tool:
  2874. ================ ====================================
  2875. Key Value
  2876. ================ ====================================
  2877. C Diameter of the tool
  2878. solid_geometry Geometry list for each tool
  2879. Others Not supported (Ignored).
  2880. ================ ====================================
  2881. * ``drills`` (list): Each is a dictionary:
  2882. ================ ====================================
  2883. Key Value
  2884. ================ ====================================
  2885. point (Shapely.Point) Where to drill
  2886. tool (str) A key in ``tools``
  2887. ================ ====================================
  2888. * ``slots`` (list): Each is a dictionary
  2889. ================ ====================================
  2890. Key Value
  2891. ================ ====================================
  2892. start (Shapely.Point) Start point of the slot
  2893. stop (Shapely.Point) Stop point of the slot
  2894. tool (str) A key in ``tools``
  2895. ================ ====================================
  2896. """
  2897. defaults = {
  2898. "zeros": "L",
  2899. "excellon_format_upper_mm": '3',
  2900. "excellon_format_lower_mm": '3',
  2901. "excellon_format_upper_in": '2',
  2902. "excellon_format_lower_in": '4',
  2903. "excellon_units": 'INCH',
  2904. "geo_steps_per_circle": '64'
  2905. }
  2906. def __init__(self, zeros=None, excellon_format_upper_mm=None, excellon_format_lower_mm=None,
  2907. excellon_format_upper_in=None, excellon_format_lower_in=None, excellon_units=None,
  2908. geo_steps_per_circle=None):
  2909. """
  2910. The constructor takes no parameters.
  2911. :return: Excellon object.
  2912. :rtype: Excellon
  2913. """
  2914. if geo_steps_per_circle is None:
  2915. geo_steps_per_circle = int(Excellon.defaults['geo_steps_per_circle'])
  2916. self.geo_steps_per_circle = int(geo_steps_per_circle)
  2917. Geometry.__init__(self, geo_steps_per_circle=int(geo_steps_per_circle))
  2918. # dictionary to store tools, see above for description
  2919. self.tools = {}
  2920. # list to store the drills, see above for description
  2921. self.drills = []
  2922. # self.slots (list) to store the slots; each is a dictionary
  2923. self.slots = []
  2924. self.source_file = ''
  2925. # it serve to flag if a start routing or a stop routing was encountered
  2926. # if a stop is encounter and this flag is still 0 (so there is no stop for a previous start) issue error
  2927. self.routing_flag = 1
  2928. self.match_routing_start = None
  2929. self.match_routing_stop = None
  2930. self.num_tools = [] # List for keeping the tools sorted
  2931. self.index_per_tool = {} # Dictionary to store the indexed points for each tool
  2932. ## IN|MM -> Units are inherited from Geometry
  2933. #self.units = units
  2934. # Trailing "T" or leading "L" (default)
  2935. #self.zeros = "T"
  2936. self.zeros = zeros or self.defaults["zeros"]
  2937. self.zeros_found = self.zeros
  2938. self.units_found = self.units
  2939. # this will serve as a default if the Excellon file has no info regarding of tool diameters (this info may be
  2940. # in another file like for PCB WIzard ECAD software
  2941. self.toolless_diam = 1.0
  2942. # signal that the Excellon file has no tool diameter informations and the tools have bogus (random) diameter
  2943. self.diameterless = False
  2944. # Excellon format
  2945. self.excellon_format_upper_in = excellon_format_upper_in or self.defaults["excellon_format_upper_in"]
  2946. self.excellon_format_lower_in = excellon_format_lower_in or self.defaults["excellon_format_lower_in"]
  2947. self.excellon_format_upper_mm = excellon_format_upper_mm or self.defaults["excellon_format_upper_mm"]
  2948. self.excellon_format_lower_mm = excellon_format_lower_mm or self.defaults["excellon_format_lower_mm"]
  2949. self.excellon_units = excellon_units or self.defaults["excellon_units"]
  2950. # detected Excellon format is stored here:
  2951. self.excellon_format = None
  2952. # Attributes to be included in serialization
  2953. # Always append to it because it carries contents
  2954. # from Geometry.
  2955. self.ser_attrs += ['tools', 'drills', 'zeros', 'excellon_format_upper_mm', 'excellon_format_lower_mm',
  2956. 'excellon_format_upper_in', 'excellon_format_lower_in', 'excellon_units', 'slots',
  2957. 'source_file']
  2958. #### Patterns ####
  2959. # Regex basics:
  2960. # ^ - beginning
  2961. # $ - end
  2962. # *: 0 or more, +: 1 or more, ?: 0 or 1
  2963. # M48 - Beginning of Part Program Header
  2964. self.hbegin_re = re.compile(r'^M48$')
  2965. # ;HEADER - Beginning of Allegro Program Header
  2966. self.allegro_hbegin_re = re.compile(r'\;\s*(HEADER)')
  2967. # M95 or % - End of Part Program Header
  2968. # NOTE: % has different meaning in the body
  2969. self.hend_re = re.compile(r'^(?:M95|%)$')
  2970. # FMAT Excellon format
  2971. # Ignored in the parser
  2972. #self.fmat_re = re.compile(r'^FMAT,([12])$')
  2973. # Uunits and possible Excellon zeros and possible Excellon format
  2974. # INCH uses 6 digits
  2975. # METRIC uses 5/6
  2976. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?,?(\d*\.\d+)?.*$')
  2977. # Tool definition/parameters (?= is look-ahead
  2978. # NOTE: This might be an overkill!
  2979. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  2980. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  2981. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  2982. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  2983. self.toolset_re = re.compile(r'^T(\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.detect_gcode_re = re.compile(r'^G2([01])$')
  2988. # Tool select
  2989. # Can have additional data after tool number but
  2990. # is ignored if present in the header.
  2991. # Warning: This will match toolset_re too.
  2992. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  2993. self.toolsel_re = re.compile(r'^T(\d+)')
  2994. # Headerless toolset
  2995. # self.toolset_hl_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))')
  2996. self.toolset_hl_re = re.compile(r'^T(\d+)(?:.?C(\d+\.?\d*))?')
  2997. # Comment
  2998. self.comm_re = re.compile(r'^;(.*)$')
  2999. # Absolute/Incremental G90/G91
  3000. self.absinc_re = re.compile(r'^G9([01])$')
  3001. # Modes of operation
  3002. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  3003. self.modes_re = re.compile(r'^G0([012345])')
  3004. # Measuring mode
  3005. # 1-metric, 2-inch
  3006. self.meas_re = re.compile(r'^M7([12])$')
  3007. # Coordinates
  3008. # self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  3009. # self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  3010. coordsperiod_re_string = r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]'
  3011. self.coordsperiod_re = re.compile(coordsperiod_re_string)
  3012. coordsnoperiod_re_string = r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]'
  3013. self.coordsnoperiod_re = re.compile(coordsnoperiod_re_string)
  3014. # Slots parsing
  3015. slots_re_string = r'^([^G]+)G85(.*)$'
  3016. self.slots_re = re.compile(slots_re_string)
  3017. # R - Repeat hole (# times, X offset, Y offset)
  3018. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  3019. # Various stop/pause commands
  3020. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  3021. # Allegro Excellon format support
  3022. self.tool_units_re = re.compile(r'(\;\s*Holesize \d+.\s*\=\s*(\d+.\d+).*(MILS|MM))')
  3023. # Altium Excellon format support
  3024. # it's a comment like this: ";FILE_FORMAT=2:5"
  3025. self.altium_format = re.compile(r'^;\s*(?:FILE_FORMAT)?(?:Format)?[=|:]\s*(\d+)[:|.](\d+).*$')
  3026. # Parse coordinates
  3027. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  3028. # Repeating command
  3029. self.repeat_re = re.compile(r'R(\d+)')
  3030. def parse_file(self, filename=None, file_obj=None):
  3031. """
  3032. Reads the specified file as array of lines as
  3033. passes it to ``parse_lines()``.
  3034. :param filename: The file to be read and parsed.
  3035. :type filename: str
  3036. :return: None
  3037. """
  3038. if file_obj:
  3039. estr = file_obj
  3040. else:
  3041. if filename is None:
  3042. return "fail"
  3043. efile = open(filename, 'r')
  3044. estr = efile.readlines()
  3045. efile.close()
  3046. try:
  3047. self.parse_lines(estr)
  3048. except:
  3049. return "fail"
  3050. def parse_lines(self, elines):
  3051. """
  3052. Main Excellon parser.
  3053. :param elines: List of strings, each being a line of Excellon code.
  3054. :type elines: list
  3055. :return: None
  3056. """
  3057. # State variables
  3058. current_tool = ""
  3059. in_header = False
  3060. headerless = False
  3061. current_x = None
  3062. current_y = None
  3063. slot_current_x = None
  3064. slot_current_y = None
  3065. name_tool = 0
  3066. allegro_warning = False
  3067. line_units_found = False
  3068. repeating_x = 0
  3069. repeating_y = 0
  3070. repeat = 0
  3071. line_units = ''
  3072. #### Parsing starts here ####
  3073. line_num = 0 # Line number
  3074. eline = ""
  3075. try:
  3076. for eline in elines:
  3077. line_num += 1
  3078. # log.debug("%3d %s" % (line_num, str(eline)))
  3079. self.source_file += eline
  3080. # Cleanup lines
  3081. eline = eline.strip(' \r\n')
  3082. # Excellon files and Gcode share some extensions therefore if we detect G20 or G21 it's GCODe
  3083. # and we need to exit from here
  3084. if self.detect_gcode_re.search(eline):
  3085. log.warning("This is GCODE mark: %s" % eline)
  3086. self.app.inform.emit(_('[ERROR_NOTCL] This is GCODE mark: %s') % eline)
  3087. return
  3088. # Header Begin (M48) #
  3089. if self.hbegin_re.search(eline):
  3090. in_header = True
  3091. log.warning("Found start of the header: %s" % eline)
  3092. continue
  3093. # Allegro Header Begin (;HEADER) #
  3094. if self.allegro_hbegin_re.search(eline):
  3095. in_header = True
  3096. allegro_warning = True
  3097. log.warning("Found ALLEGRO start of the header: %s" % eline)
  3098. continue
  3099. # Search for Header End #
  3100. # Since there might be comments in the header that include header end char (% or M95)
  3101. # we ignore the lines starting with ';' that contains such header end chars because it is not a
  3102. # real header end.
  3103. if self.comm_re.search(eline):
  3104. match = self.tool_units_re.search(eline)
  3105. if match:
  3106. if line_units_found is False:
  3107. line_units_found = True
  3108. line_units = match.group(3)
  3109. self.convert_units({"MILS": "IN", "MM": "MM"}[line_units])
  3110. log.warning("Type of Allegro UNITS found inline in comments: %s" % line_units)
  3111. if match.group(2):
  3112. name_tool += 1
  3113. if line_units == 'MILS':
  3114. spec = {"C": (float(match.group(2)) / 1000)}
  3115. self.tools[str(name_tool)] = spec
  3116. log.debug(" Tool definition: %s %s" % (name_tool, spec))
  3117. else:
  3118. spec = {"C": float(match.group(2))}
  3119. self.tools[str(name_tool)] = spec
  3120. log.debug(" Tool definition: %s %s" % (name_tool, spec))
  3121. spec['solid_geometry'] = []
  3122. continue
  3123. # search for Altium Excellon Format / Sprint Layout who is included as a comment
  3124. match = self.altium_format.search(eline)
  3125. if match:
  3126. self.excellon_format_upper_mm = match.group(1)
  3127. self.excellon_format_lower_mm = match.group(2)
  3128. self.excellon_format_upper_in = match.group(1)
  3129. self.excellon_format_lower_in = match.group(2)
  3130. log.warning("Altium Excellon format preset found in comments: %s:%s" %
  3131. (match.group(1), match.group(2)))
  3132. continue
  3133. else:
  3134. log.warning("Line ignored, it's a comment: %s" % eline)
  3135. else:
  3136. if self.hend_re.search(eline):
  3137. if in_header is False or bool(self.tools) is False:
  3138. log.warning("Found end of the header but there is no header: %s" % eline)
  3139. log.warning("The only useful data in header are tools, units and format.")
  3140. log.warning("Therefore we will create units and format based on defaults.")
  3141. headerless = True
  3142. try:
  3143. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.excellon_units])
  3144. except Exception as e:
  3145. log.warning("Units could not be converted: %s" % str(e))
  3146. in_header = False
  3147. # for Allegro type of Excellons we reset name_tool variable so we can reuse it for toolchange
  3148. if allegro_warning is True:
  3149. name_tool = 0
  3150. log.warning("Found end of the header: %s" % eline)
  3151. continue
  3152. ## Alternative units format M71/M72
  3153. # Supposed to be just in the body (yes, the body)
  3154. # but some put it in the header (PADS for example).
  3155. # Will detect anywhere. Occurrence will change the
  3156. # object's units.
  3157. match = self.meas_re.match(eline)
  3158. if match:
  3159. #self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  3160. # Modified for issue #80
  3161. self.convert_units({"1": "MM", "2": "IN"}[match.group(1)])
  3162. log.debug(" Units: %s" % self.units)
  3163. if self.units == 'MM':
  3164. log.warning("Excellon format preset is: %s" % self.excellon_format_upper_mm + \
  3165. ':' + str(self.excellon_format_lower_mm))
  3166. else:
  3167. log.warning("Excellon format preset is: %s" % self.excellon_format_upper_in + \
  3168. ':' + str(self.excellon_format_lower_in))
  3169. continue
  3170. #### Body ####
  3171. if not in_header:
  3172. ## Tool change ##
  3173. match = self.toolsel_re.search(eline)
  3174. if match:
  3175. current_tool = str(int(match.group(1)))
  3176. log.debug("Tool change: %s" % current_tool)
  3177. if bool(headerless):
  3178. match = self.toolset_hl_re.search(eline)
  3179. if match:
  3180. name = str(int(match.group(1)))
  3181. try:
  3182. diam = float(match.group(2))
  3183. except:
  3184. # it's possible that tool definition has only tool number and no diameter info
  3185. # (those could be in another file like PCB Wizard do)
  3186. # then match.group(2) = None and float(None) will create the exception
  3187. # the bellow construction is so each tool will have a slightly different diameter
  3188. # starting with a default value, to allow Excellon editing after that
  3189. self.diameterless = True
  3190. self.app.inform.emit(_("[WARNING] No tool diameter info's. See shell.\n"
  3191. "A tool change event: T%s was found but the Excellon file "
  3192. "have no informations regarding the tool "
  3193. "diameters therefore the application will try to load it by "
  3194. "using some 'fake' diameters.\nThe user needs to edit the "
  3195. "resulting Excellon object and change the diameters to "
  3196. "reflect the real diameters.") % current_tool)
  3197. if self.excellon_units == 'MM':
  3198. diam = self.toolless_diam + (int(current_tool) - 1) / 100
  3199. else:
  3200. diam = (self.toolless_diam + (int(current_tool) - 1) / 100) / 25.4
  3201. spec = {
  3202. "C": diam,
  3203. }
  3204. spec['solid_geometry'] = []
  3205. self.tools[name] = spec
  3206. log.debug(" Tool definition out of header: %s %s" % (name, spec))
  3207. continue
  3208. ## Allegro Type Tool change ##
  3209. if allegro_warning is True:
  3210. match = self.absinc_re.search(eline)
  3211. match1 = self.stop_re.search(eline)
  3212. if match or match1:
  3213. name_tool += 1
  3214. current_tool = str(name_tool)
  3215. log.debug(" Tool change for Allegro type of Excellon: %s" % current_tool)
  3216. continue
  3217. ## Slots parsing for drilled slots (contain G85)
  3218. # a Excellon drilled slot line may look like this:
  3219. # X01125Y0022244G85Y0027756
  3220. match = self.slots_re.search(eline)
  3221. if match:
  3222. # signal that there are milling slots operations
  3223. self.defaults['excellon_drills'] = False
  3224. # the slot start coordinates group is to the left of G85 command (group(1) )
  3225. # the slot stop coordinates group is to the right of G85 command (group(2) )
  3226. start_coords_match = match.group(1)
  3227. stop_coords_match = match.group(2)
  3228. # Slot coordinates without period ##
  3229. # get the coordinates for slot start and for slot stop into variables
  3230. start_coords_noperiod = self.coordsnoperiod_re.search(start_coords_match)
  3231. stop_coords_noperiod = self.coordsnoperiod_re.search(stop_coords_match)
  3232. if start_coords_noperiod:
  3233. try:
  3234. slot_start_x = self.parse_number(start_coords_noperiod.group(1))
  3235. slot_current_x = slot_start_x
  3236. except TypeError:
  3237. slot_start_x = slot_current_x
  3238. except:
  3239. return
  3240. try:
  3241. slot_start_y = self.parse_number(start_coords_noperiod.group(2))
  3242. slot_current_y = slot_start_y
  3243. except TypeError:
  3244. slot_start_y = slot_current_y
  3245. except:
  3246. return
  3247. try:
  3248. slot_stop_x = self.parse_number(stop_coords_noperiod.group(1))
  3249. slot_current_x = slot_stop_x
  3250. except TypeError:
  3251. slot_stop_x = slot_current_x
  3252. except:
  3253. return
  3254. try:
  3255. slot_stop_y = self.parse_number(stop_coords_noperiod.group(2))
  3256. slot_current_y = slot_stop_y
  3257. except TypeError:
  3258. slot_stop_y = slot_current_y
  3259. except:
  3260. return
  3261. if (slot_start_x is None or slot_start_y is None or
  3262. slot_stop_x is None or slot_stop_y is None):
  3263. log.error("Slots are missing some or all coordinates.")
  3264. continue
  3265. # we have a slot
  3266. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  3267. slot_start_y, slot_stop_x,
  3268. slot_stop_y]))
  3269. # store current tool diameter as slot diameter
  3270. slot_dia = 0.05
  3271. try:
  3272. slot_dia = float(self.tools[current_tool]['C'])
  3273. except:
  3274. pass
  3275. log.debug(
  3276. 'Milling/Drilling slot with tool %s, diam=%f' % (
  3277. current_tool,
  3278. slot_dia
  3279. )
  3280. )
  3281. self.slots.append(
  3282. {
  3283. 'start': Point(slot_start_x, slot_start_y),
  3284. 'stop': Point(slot_stop_x, slot_stop_y),
  3285. 'tool': current_tool
  3286. }
  3287. )
  3288. continue
  3289. # Slot coordinates with period: Use literally. ##
  3290. # get the coordinates for slot start and for slot stop into variables
  3291. start_coords_period = self.coordsperiod_re.search(start_coords_match)
  3292. stop_coords_period = self.coordsperiod_re.search(stop_coords_match)
  3293. if start_coords_period:
  3294. try:
  3295. slot_start_x = float(start_coords_period.group(1))
  3296. slot_current_x = slot_start_x
  3297. except TypeError:
  3298. slot_start_x = slot_current_x
  3299. except:
  3300. return
  3301. try:
  3302. slot_start_y = float(start_coords_period.group(2))
  3303. slot_current_y = slot_start_y
  3304. except TypeError:
  3305. slot_start_y = slot_current_y
  3306. except:
  3307. return
  3308. try:
  3309. slot_stop_x = float(stop_coords_period.group(1))
  3310. slot_current_x = slot_stop_x
  3311. except TypeError:
  3312. slot_stop_x = slot_current_x
  3313. except:
  3314. return
  3315. try:
  3316. slot_stop_y = float(stop_coords_period.group(2))
  3317. slot_current_y = slot_stop_y
  3318. except TypeError:
  3319. slot_stop_y = slot_current_y
  3320. except:
  3321. return
  3322. if (slot_start_x is None or slot_start_y is None or
  3323. slot_stop_x is None or slot_stop_y is None):
  3324. log.error("Slots are missing some or all coordinates.")
  3325. continue
  3326. # we have a slot
  3327. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  3328. slot_start_y, slot_stop_x, slot_stop_y]))
  3329. # store current tool diameter as slot diameter
  3330. slot_dia = 0.05
  3331. try:
  3332. slot_dia = float(self.tools[current_tool]['C'])
  3333. except:
  3334. pass
  3335. log.debug(
  3336. 'Milling/Drilling slot with tool %s, diam=%f' % (
  3337. current_tool,
  3338. slot_dia
  3339. )
  3340. )
  3341. self.slots.append(
  3342. {
  3343. 'start': Point(slot_start_x, slot_start_y),
  3344. 'stop': Point(slot_stop_x, slot_stop_y),
  3345. 'tool': current_tool
  3346. }
  3347. )
  3348. continue
  3349. ## Coordinates without period ##
  3350. match = self.coordsnoperiod_re.search(eline)
  3351. if match:
  3352. matchr = self.repeat_re.search(eline)
  3353. if matchr:
  3354. repeat = int(matchr.group(1))
  3355. try:
  3356. x = self.parse_number(match.group(1))
  3357. repeating_x = current_x
  3358. current_x = x
  3359. except TypeError:
  3360. x = current_x
  3361. repeating_x = 0
  3362. except:
  3363. return
  3364. try:
  3365. y = self.parse_number(match.group(2))
  3366. repeating_y = current_y
  3367. current_y = y
  3368. except TypeError:
  3369. y = current_y
  3370. repeating_y = 0
  3371. except:
  3372. return
  3373. if x is None or y is None:
  3374. log.error("Missing coordinates")
  3375. continue
  3376. ## Excellon Routing parse
  3377. if len(re.findall("G00", eline)) > 0:
  3378. self.match_routing_start = 'G00'
  3379. # signal that there are milling slots operations
  3380. self.defaults['excellon_drills'] = False
  3381. self.routing_flag = 0
  3382. slot_start_x = x
  3383. slot_start_y = y
  3384. continue
  3385. if self.routing_flag == 0:
  3386. if len(re.findall("G01", eline)) > 0:
  3387. self.match_routing_stop = 'G01'
  3388. # signal that there are milling slots operations
  3389. self.defaults['excellon_drills'] = False
  3390. self.routing_flag = 1
  3391. slot_stop_x = x
  3392. slot_stop_y = y
  3393. self.slots.append(
  3394. {
  3395. 'start': Point(slot_start_x, slot_start_y),
  3396. 'stop': Point(slot_stop_x, slot_stop_y),
  3397. 'tool': current_tool
  3398. }
  3399. )
  3400. continue
  3401. if self.match_routing_start is None and self.match_routing_stop is None:
  3402. if repeat == 0:
  3403. # signal that there are drill operations
  3404. self.defaults['excellon_drills'] = True
  3405. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  3406. else:
  3407. coordx = x
  3408. coordy = y
  3409. while repeat > 0:
  3410. if repeating_x:
  3411. coordx = (repeat * x) + repeating_x
  3412. if repeating_y:
  3413. coordy = (repeat * y) + repeating_y
  3414. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  3415. repeat -= 1
  3416. repeating_x = repeating_y = 0
  3417. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  3418. continue
  3419. ## Coordinates with period: Use literally. ##
  3420. match = self.coordsperiod_re.search(eline)
  3421. if match:
  3422. matchr = self.repeat_re.search(eline)
  3423. if matchr:
  3424. repeat = int(matchr.group(1))
  3425. if match:
  3426. # signal that there are drill operations
  3427. self.defaults['excellon_drills'] = True
  3428. try:
  3429. x = float(match.group(1))
  3430. repeating_x = current_x
  3431. current_x = x
  3432. except TypeError:
  3433. x = current_x
  3434. repeating_x = 0
  3435. try:
  3436. y = float(match.group(2))
  3437. repeating_y = current_y
  3438. current_y = y
  3439. except TypeError:
  3440. y = current_y
  3441. repeating_y = 0
  3442. if x is None or y is None:
  3443. log.error("Missing coordinates")
  3444. continue
  3445. ## Excellon Routing parse
  3446. if len(re.findall("G00", eline)) > 0:
  3447. self.match_routing_start = 'G00'
  3448. # signal that there are milling slots operations
  3449. self.defaults['excellon_drills'] = False
  3450. self.routing_flag = 0
  3451. slot_start_x = x
  3452. slot_start_y = y
  3453. continue
  3454. if self.routing_flag == 0:
  3455. if len(re.findall("G01", eline)) > 0:
  3456. self.match_routing_stop = 'G01'
  3457. # signal that there are milling slots operations
  3458. self.defaults['excellon_drills'] = False
  3459. self.routing_flag = 1
  3460. slot_stop_x = x
  3461. slot_stop_y = y
  3462. self.slots.append(
  3463. {
  3464. 'start': Point(slot_start_x, slot_start_y),
  3465. 'stop': Point(slot_stop_x, slot_stop_y),
  3466. 'tool': current_tool
  3467. }
  3468. )
  3469. continue
  3470. if self.match_routing_start is None and self.match_routing_stop is None:
  3471. # signal that there are drill operations
  3472. if repeat == 0:
  3473. # signal that there are drill operations
  3474. self.defaults['excellon_drills'] = True
  3475. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  3476. else:
  3477. coordx = x
  3478. coordy = y
  3479. while repeat > 0:
  3480. if repeating_x:
  3481. coordx = (repeat * x) + repeating_x
  3482. if repeating_y:
  3483. coordy = (repeat * y) + repeating_y
  3484. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  3485. repeat -= 1
  3486. repeating_x = repeating_y = 0
  3487. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  3488. continue
  3489. #### Header ####
  3490. if in_header:
  3491. ## Tool definitions ##
  3492. match = self.toolset_re.search(eline)
  3493. if match:
  3494. name = str(int(match.group(1)))
  3495. spec = {
  3496. "C": float(match.group(2)),
  3497. # "F": float(match.group(3)),
  3498. # "S": float(match.group(4)),
  3499. # "B": float(match.group(5)),
  3500. # "H": float(match.group(6)),
  3501. # "Z": float(match.group(7))
  3502. }
  3503. spec['solid_geometry'] = []
  3504. self.tools[name] = spec
  3505. log.debug(" Tool definition: %s %s" % (name, spec))
  3506. continue
  3507. ## Units and number format ##
  3508. match = self.units_re.match(eline)
  3509. if match:
  3510. self.units_found = match.group(1)
  3511. self.zeros = match.group(2) # "T" or "L". Might be empty
  3512. self.excellon_format = match.group(3)
  3513. if self.excellon_format:
  3514. upper = len(self.excellon_format.partition('.')[0])
  3515. lower = len(self.excellon_format.partition('.')[2])
  3516. if self.units == 'MM':
  3517. self.excellon_format_upper_mm = upper
  3518. self.excellon_format_lower_mm = lower
  3519. else:
  3520. self.excellon_format_upper_in = upper
  3521. self.excellon_format_lower_in = lower
  3522. # Modified for issue #80
  3523. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.units_found])
  3524. # log.warning(" Units/Format: %s %s" % (self.units, self.zeros))
  3525. log.warning("Units: %s" % self.units)
  3526. if self.units == 'MM':
  3527. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3528. ':' + str(self.excellon_format_lower_mm))
  3529. else:
  3530. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3531. ':' + str(self.excellon_format_lower_in))
  3532. log.warning("Type of zeros found inline: %s" % self.zeros)
  3533. continue
  3534. # Search for units type again it might be alone on the line
  3535. if "INCH" in eline:
  3536. line_units = "INCH"
  3537. # Modified for issue #80
  3538. self.convert_units({"INCH": "IN", "METRIC": "MM"}[line_units])
  3539. log.warning("Type of UNITS found inline: %s" % line_units)
  3540. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3541. ':' + str(self.excellon_format_lower_in))
  3542. # TODO: not working
  3543. #FlatCAMApp.App.inform.emit("Detected INLINE: %s" % str(eline))
  3544. continue
  3545. elif "METRIC" in eline:
  3546. line_units = "METRIC"
  3547. # Modified for issue #80
  3548. self.convert_units({"INCH": "IN", "METRIC": "MM"}[line_units])
  3549. log.warning("Type of UNITS found inline: %s" % line_units)
  3550. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3551. ':' + str(self.excellon_format_lower_mm))
  3552. # TODO: not working
  3553. #FlatCAMApp.App.inform.emit("Detected INLINE: %s" % str(eline))
  3554. continue
  3555. # Search for zeros type again because it might be alone on the line
  3556. match = re.search(r'[LT]Z',eline)
  3557. if match:
  3558. self.zeros = match.group()
  3559. log.warning("Type of zeros found: %s" % self.zeros)
  3560. continue
  3561. ## Units and number format outside header##
  3562. match = self.units_re.match(eline)
  3563. if match:
  3564. self.units_found = match.group(1)
  3565. self.zeros = match.group(2) # "T" or "L". Might be empty
  3566. self.excellon_format = match.group(3)
  3567. if self.excellon_format:
  3568. upper = len(self.excellon_format.partition('.')[0])
  3569. lower = len(self.excellon_format.partition('.')[2])
  3570. if self.units == 'MM':
  3571. self.excellon_format_upper_mm = upper
  3572. self.excellon_format_lower_mm = lower
  3573. else:
  3574. self.excellon_format_upper_in = upper
  3575. self.excellon_format_lower_in = lower
  3576. # Modified for issue #80
  3577. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.units_found])
  3578. # log.warning(" Units/Format: %s %s" % (self.units, self.zeros))
  3579. log.warning("Units: %s" % self.units)
  3580. if self.units == 'MM':
  3581. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_mm) +
  3582. ':' + str(self.excellon_format_lower_mm))
  3583. else:
  3584. log.warning("Excellon format preset is: %s" % str(self.excellon_format_upper_in) +
  3585. ':' + str(self.excellon_format_lower_in))
  3586. log.warning("Type of zeros found outside header, inline: %s" % self.zeros)
  3587. log.warning("UNITS found outside header")
  3588. continue
  3589. log.warning("Line ignored: %s" % eline)
  3590. # make sure that since we are in headerless mode, we convert the tools only after the file parsing
  3591. # is finished since the tools definitions are spread in the Excellon body. We use as units the value
  3592. # from self.defaults['excellon_units']
  3593. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  3594. except Exception as e:
  3595. log.error("Excellon PARSING FAILED. Line %d: %s" % (line_num, eline))
  3596. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  3597. msg += _('[ERROR] Excellon Parser error.\nParsing Failed. Line {l_nr}: {line}\n').format(l_nr=line_num, line=eline)
  3598. msg += traceback.format_exc()
  3599. self.app.inform.emit(msg)
  3600. return "fail"
  3601. def parse_number(self, number_str):
  3602. """
  3603. Parses coordinate numbers without period.
  3604. :param number_str: String representing the numerical value.
  3605. :type number_str: str
  3606. :return: Floating point representation of the number
  3607. :rtype: float
  3608. """
  3609. match = self.leadingzeros_re.search(number_str)
  3610. nr_length = len(match.group(1)) + len(match.group(2))
  3611. try:
  3612. if self.zeros == "L" or self.zeros == "LZ":
  3613. # With leading zeros, when you type in a coordinate,
  3614. # the leading zeros must always be included. Trailing zeros
  3615. # are unneeded and may be left off. The CNC-7 will automatically add them.
  3616. # r'^[-\+]?(0*)(\d*)'
  3617. # 6 digits are divided by 10^4
  3618. # If less than size digits, they are automatically added,
  3619. # 5 digits then are divided by 10^3 and so on.
  3620. if self.units.lower() == "in":
  3621. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_in)))
  3622. else:
  3623. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_mm)))
  3624. return result
  3625. else: # Trailing
  3626. # You must show all zeros to the right of the number and can omit
  3627. # all zeros to the left of the number. The CNC-7 will count the number
  3628. # of digits you typed and automatically fill in the missing zeros.
  3629. ## flatCAM expects 6digits
  3630. # flatCAM expects the number of digits entered into the defaults
  3631. if self.units.lower() == "in": # Inches is 00.0000
  3632. result = float(number_str) / (10 ** (float(self.excellon_format_lower_in)))
  3633. else: # Metric is 000.000
  3634. result = float(number_str) / (10 ** (float(self.excellon_format_lower_mm)))
  3635. return result
  3636. except Exception as e:
  3637. log.error("Aborted. Operation could not be completed due of %s" % str(e))
  3638. return
  3639. def create_geometry(self):
  3640. """
  3641. Creates circles of the tool diameter at every point
  3642. specified in ``self.drills``. Also creates geometries (polygons)
  3643. for the slots as specified in ``self.slots``
  3644. All the resulting geometry is stored into self.solid_geometry list.
  3645. The list self.solid_geometry has 2 elements: first is a dict with the drills geometry,
  3646. and second element is another similar dict that contain the slots geometry.
  3647. Each dict has as keys the tool diameters and as values lists with Shapely objects, the geometries
  3648. ================ ====================================
  3649. Key Value
  3650. ================ ====================================
  3651. tool_diameter list of (Shapely.Point) Where to drill
  3652. ================ ====================================
  3653. :return: None
  3654. """
  3655. self.solid_geometry = []
  3656. try:
  3657. # clear the solid_geometry in self.tools
  3658. for tool in self.tools:
  3659. self.tools[tool]['solid_geometry'][:] = []
  3660. for drill in self.drills:
  3661. # poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  3662. if drill['tool'] is '':
  3663. self.app.inform.emit(_("[WARNING] Excellon.create_geometry() -> a drill location was skipped "
  3664. "due of not having a tool associated.\n"
  3665. "Check the resulting GCode."))
  3666. log.debug("Excellon.create_geometry() -> a drill location was skipped "
  3667. "due of not having a tool associated")
  3668. continue
  3669. tooldia = self.tools[drill['tool']]['C']
  3670. poly = drill['point'].buffer(tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  3671. # self.solid_geometry.append(poly)
  3672. self.tools[drill['tool']]['solid_geometry'].append(poly)
  3673. for slot in self.slots:
  3674. slot_tooldia = self.tools[slot['tool']]['C']
  3675. start = slot['start']
  3676. stop = slot['stop']
  3677. lines_string = LineString([start, stop])
  3678. poly = lines_string.buffer(slot_tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  3679. # self.solid_geometry.append(poly)
  3680. self.tools[slot['tool']]['solid_geometry'].append(poly)
  3681. except Exception as e:
  3682. log.debug("Excellon geometry creation failed due of ERROR: %s" % str(e))
  3683. return "fail"
  3684. # drill_geometry = {}
  3685. # slot_geometry = {}
  3686. #
  3687. # def insertIntoDataStruct(dia, drill_geo, aDict):
  3688. # if not dia in aDict:
  3689. # aDict[dia] = [drill_geo]
  3690. # else:
  3691. # aDict[dia].append(drill_geo)
  3692. #
  3693. # for tool in self.tools:
  3694. # tooldia = self.tools[tool]['C']
  3695. # for drill in self.drills:
  3696. # if drill['tool'] == tool:
  3697. # poly = drill['point'].buffer(tooldia / 2.0)
  3698. # insertIntoDataStruct(tooldia, poly, drill_geometry)
  3699. #
  3700. # for tool in self.tools:
  3701. # slot_tooldia = self.tools[tool]['C']
  3702. # for slot in self.slots:
  3703. # if slot['tool'] == tool:
  3704. # start = slot['start']
  3705. # stop = slot['stop']
  3706. # lines_string = LineString([start, stop])
  3707. # poly = lines_string.buffer(slot_tooldia/2.0, self.geo_steps_per_circle)
  3708. # insertIntoDataStruct(slot_tooldia, poly, drill_geometry)
  3709. #
  3710. # self.solid_geometry = [drill_geometry, slot_geometry]
  3711. def bounds(self):
  3712. """
  3713. Returns coordinates of rectangular bounds
  3714. of Gerber geometry: (xmin, ymin, xmax, ymax).
  3715. """
  3716. # fixed issue of getting bounds only for one level lists of objects
  3717. # now it can get bounds for nested lists of objects
  3718. log.debug("Excellon() -> bounds()")
  3719. # if self.solid_geometry is None:
  3720. # log.debug("solid_geometry is None")
  3721. # return 0, 0, 0, 0
  3722. def bounds_rec(obj):
  3723. if type(obj) is list:
  3724. minx = Inf
  3725. miny = Inf
  3726. maxx = -Inf
  3727. maxy = -Inf
  3728. for k in obj:
  3729. if type(k) is dict:
  3730. for key in k:
  3731. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  3732. minx = min(minx, minx_)
  3733. miny = min(miny, miny_)
  3734. maxx = max(maxx, maxx_)
  3735. maxy = max(maxy, maxy_)
  3736. else:
  3737. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  3738. minx = min(minx, minx_)
  3739. miny = min(miny, miny_)
  3740. maxx = max(maxx, maxx_)
  3741. maxy = max(maxy, maxy_)
  3742. return minx, miny, maxx, maxy
  3743. else:
  3744. # it's a Shapely object, return it's bounds
  3745. return obj.bounds
  3746. minx_list = []
  3747. miny_list = []
  3748. maxx_list = []
  3749. maxy_list = []
  3750. for tool in self.tools:
  3751. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  3752. minx_list.append(minx)
  3753. miny_list.append(miny)
  3754. maxx_list.append(maxx)
  3755. maxy_list.append(maxy)
  3756. return (min(minx_list), min(miny_list), max(maxx_list), max(maxy_list))
  3757. def convert_units(self, units):
  3758. """
  3759. This function first convert to the the units found in the Excellon file but it converts tools that
  3760. are not there yet so it has no effect other than it signal that the units are the ones in the file.
  3761. On object creation, in new_object(), true conversion is done because this is done at the end of the
  3762. Excellon file parsing, the tools are inside and self.tools is really converted from the units found
  3763. inside the file to the FlatCAM units.
  3764. Kind of convolute way to make the conversion and it is based on the assumption that the Excellon file
  3765. will have detected the units before the tools are parsed and stored in self.tools
  3766. :param units:
  3767. :type str: IN or MM
  3768. :return:
  3769. """
  3770. factor = Geometry.convert_units(self, units)
  3771. # Tools
  3772. for tname in self.tools:
  3773. self.tools[tname]["C"] *= factor
  3774. self.create_geometry()
  3775. return factor
  3776. def scale(self, xfactor, yfactor=None, point=None):
  3777. """
  3778. Scales geometry on the XY plane in the object by a given factor.
  3779. Tool sizes, feedrates an Z-plane dimensions are untouched.
  3780. :param factor: Number by which to scale the object.
  3781. :type factor: float
  3782. :return: None
  3783. :rtype: NOne
  3784. """
  3785. if yfactor is None:
  3786. yfactor = xfactor
  3787. if point is None:
  3788. px = 0
  3789. py = 0
  3790. else:
  3791. px, py = point
  3792. def scale_geom(obj):
  3793. if type(obj) is list:
  3794. new_obj = []
  3795. for g in obj:
  3796. new_obj.append(scale_geom(g))
  3797. return new_obj
  3798. else:
  3799. return affinity.scale(obj, xfactor,
  3800. yfactor, origin=(px, py))
  3801. # Drills
  3802. for drill in self.drills:
  3803. drill['point'] = affinity.scale(drill['point'], xfactor, yfactor, origin=(px, py))
  3804. # scale solid_geometry
  3805. for tool in self.tools:
  3806. self.tools[tool]['solid_geometry'] = scale_geom(self.tools[tool]['solid_geometry'])
  3807. # Slots
  3808. for slot in self.slots:
  3809. slot['stop'] = affinity.scale(slot['stop'], xfactor, yfactor, origin=(px, py))
  3810. slot['start'] = affinity.scale(slot['start'], xfactor, yfactor, origin=(px, py))
  3811. self.create_geometry()
  3812. def offset(self, vect):
  3813. """
  3814. Offsets geometry on the XY plane in the object by a given vector.
  3815. :param vect: (x, y) offset vector.
  3816. :type vect: tuple
  3817. :return: None
  3818. """
  3819. dx, dy = vect
  3820. def offset_geom(obj):
  3821. if type(obj) is list:
  3822. new_obj = []
  3823. for g in obj:
  3824. new_obj.append(offset_geom(g))
  3825. return new_obj
  3826. else:
  3827. return affinity.translate(obj, xoff=dx, yoff=dy)
  3828. # Drills
  3829. for drill in self.drills:
  3830. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  3831. # offset solid_geometry
  3832. for tool in self.tools:
  3833. self.tools[tool]['solid_geometry'] = offset_geom(self.tools[tool]['solid_geometry'])
  3834. # Slots
  3835. for slot in self.slots:
  3836. slot['stop'] = affinity.translate(slot['stop'], xoff=dx, yoff=dy)
  3837. slot['start'] = affinity.translate(slot['start'],xoff=dx, yoff=dy)
  3838. # Recreate geometry
  3839. self.create_geometry()
  3840. def mirror(self, axis, point):
  3841. """
  3842. :param axis: "X" or "Y" indicates around which axis to mirror.
  3843. :type axis: str
  3844. :param point: [x, y] point belonging to the mirror axis.
  3845. :type point: list
  3846. :return: None
  3847. """
  3848. px, py = point
  3849. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  3850. def mirror_geom(obj):
  3851. if type(obj) is list:
  3852. new_obj = []
  3853. for g in obj:
  3854. new_obj.append(mirror_geom(g))
  3855. return new_obj
  3856. else:
  3857. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  3858. # Modify data
  3859. # Drills
  3860. for drill in self.drills:
  3861. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  3862. # mirror solid_geometry
  3863. for tool in self.tools:
  3864. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  3865. # Slots
  3866. for slot in self.slots:
  3867. slot['stop'] = affinity.scale(slot['stop'], xscale, yscale, origin=(px, py))
  3868. slot['start'] = affinity.scale(slot['start'], xscale, yscale, origin=(px, py))
  3869. # Recreate geometry
  3870. self.create_geometry()
  3871. def skew(self, angle_x=None, angle_y=None, point=None):
  3872. """
  3873. Shear/Skew the geometries of an object by angles along x and y dimensions.
  3874. Tool sizes, feedrates an Z-plane dimensions are untouched.
  3875. Parameters
  3876. ----------
  3877. xs, ys : float, float
  3878. The shear angle(s) for the x and y axes respectively. These can be
  3879. specified in either degrees (default) or radians by setting
  3880. use_radians=True.
  3881. See shapely manual for more information:
  3882. http://toblerity.org/shapely/manual.html#affine-transformations
  3883. """
  3884. if angle_x is None:
  3885. angle_x = 0.0
  3886. if angle_y is None:
  3887. angle_y = 0.0
  3888. def skew_geom(obj):
  3889. if type(obj) is list:
  3890. new_obj = []
  3891. for g in obj:
  3892. new_obj.append(skew_geom(g))
  3893. return new_obj
  3894. else:
  3895. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  3896. if point is None:
  3897. px, py = 0, 0
  3898. # Drills
  3899. for drill in self.drills:
  3900. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  3901. origin=(px, py))
  3902. # skew solid_geometry
  3903. for tool in self.tools:
  3904. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  3905. # Slots
  3906. for slot in self.slots:
  3907. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  3908. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  3909. else:
  3910. px, py = point
  3911. # Drills
  3912. for drill in self.drills:
  3913. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  3914. origin=(px, py))
  3915. # skew solid_geometry
  3916. for tool in self.tools:
  3917. self.tools[tool]['solid_geometry'] = skew_geom( self.tools[tool]['solid_geometry'])
  3918. # Slots
  3919. for slot in self.slots:
  3920. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  3921. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  3922. self.create_geometry()
  3923. def rotate(self, angle, point=None):
  3924. """
  3925. Rotate the geometry of an object by an angle around the 'point' coordinates
  3926. :param angle:
  3927. :param point: tuple of coordinates (x, y)
  3928. :return:
  3929. """
  3930. def rotate_geom(obj, origin=None):
  3931. if type(obj) is list:
  3932. new_obj = []
  3933. for g in obj:
  3934. new_obj.append(rotate_geom(g))
  3935. return new_obj
  3936. else:
  3937. if origin:
  3938. return affinity.rotate(obj, angle, origin=origin)
  3939. else:
  3940. return affinity.rotate(obj, angle, origin=(px, py))
  3941. if point is None:
  3942. # Drills
  3943. for drill in self.drills:
  3944. drill['point'] = affinity.rotate(drill['point'], angle, origin='center')
  3945. # rotate solid_geometry
  3946. for tool in self.tools:
  3947. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'], origin='center')
  3948. # Slots
  3949. for slot in self.slots:
  3950. slot['stop'] = affinity.rotate(slot['stop'], angle, origin='center')
  3951. slot['start'] = affinity.rotate(slot['start'], angle, origin='center')
  3952. else:
  3953. px, py = point
  3954. # Drills
  3955. for drill in self.drills:
  3956. drill['point'] = affinity.rotate(drill['point'], angle, origin=(px, py))
  3957. # rotate solid_geometry
  3958. for tool in self.tools:
  3959. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  3960. # Slots
  3961. for slot in self.slots:
  3962. slot['stop'] = affinity.rotate(slot['stop'], angle, origin=(px, py))
  3963. slot['start'] = affinity.rotate(slot['start'], angle, origin=(px, py))
  3964. self.create_geometry()
  3965. class AttrDict(dict):
  3966. def __init__(self, *args, **kwargs):
  3967. super(AttrDict, self).__init__(*args, **kwargs)
  3968. self.__dict__ = self
  3969. class CNCjob(Geometry):
  3970. """
  3971. Represents work to be done by a CNC machine.
  3972. *ATTRIBUTES*
  3973. * ``gcode_parsed`` (list): Each is a dictionary:
  3974. ===================== =========================================
  3975. Key Value
  3976. ===================== =========================================
  3977. geom (Shapely.LineString) Tool path (XY plane)
  3978. kind (string) "AB", A is "T" (travel) or
  3979. "C" (cut). B is "F" (fast) or "S" (slow).
  3980. ===================== =========================================
  3981. """
  3982. defaults = {
  3983. "global_zdownrate": None,
  3984. "pp_geometry_name":'default',
  3985. "pp_excellon_name":'default',
  3986. "excellon_optimization_type": "B",
  3987. "steps_per_circle": 64
  3988. }
  3989. def __init__(self,
  3990. units="in", kind="generic", tooldia=0.0,
  3991. z_cut=-0.002, z_move=0.1,
  3992. feedrate=3.0, feedrate_z=3.0, feedrate_rapid=3.0, feedrate_probe=3.0,
  3993. pp_geometry_name='default', pp_excellon_name='default',
  3994. depthpercut=0.1,z_pdepth=-0.02,
  3995. spindlespeed=None, dwell=True, dwelltime=1000,
  3996. toolchangez=0.787402, toolchange_xy=[0.0, 0.0],
  3997. endz=2.0,
  3998. segx=None,
  3999. segy=None,
  4000. steps_per_circle=None):
  4001. # Used when parsing G-code arcs
  4002. if steps_per_circle is None:
  4003. steps_per_circle = int(CNCjob.defaults["steps_per_circle"])
  4004. self.steps_per_circle = int(steps_per_circle)
  4005. Geometry.__init__(self, geo_steps_per_circle=int(steps_per_circle))
  4006. self.kind = kind
  4007. self.origin_kind = None
  4008. self.units = units
  4009. self.z_cut = z_cut
  4010. self.tool_offset = {}
  4011. self.z_move = z_move
  4012. self.feedrate = feedrate
  4013. self.z_feedrate = feedrate_z
  4014. self.feedrate_rapid = feedrate_rapid
  4015. self.tooldia = tooldia
  4016. self.z_toolchange = toolchangez
  4017. self.xy_toolchange = toolchange_xy
  4018. self.toolchange_xy_type = None
  4019. self.toolC = tooldia
  4020. self.z_end = endz
  4021. self.z_depthpercut = depthpercut
  4022. self.unitcode = {"IN": "G20", "MM": "G21"}
  4023. self.feedminutecode = "G94"
  4024. self.absolutecode = "G90"
  4025. self.gcode = ""
  4026. self.gcode_parsed = None
  4027. self.pp_geometry_name = pp_geometry_name
  4028. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  4029. self.pp_excellon_name = pp_excellon_name
  4030. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  4031. self.pp_solderpaste_name = None
  4032. # Controls if the move from Z_Toolchange to Z_Move is done fast with G0 or normally with G1
  4033. self.f_plunge = None
  4034. # Controls if the move from Z_Cutto Z_Move is done fast with G0 or G1 until zero and then G0 to Z_move
  4035. self.f_retract = None
  4036. # how much depth the probe can probe before error
  4037. self.z_pdepth = z_pdepth if z_pdepth else None
  4038. # the feedrate(speed) with which the probel travel while probing
  4039. self.feedrate_probe = feedrate_probe if feedrate_probe else None
  4040. self.spindlespeed = spindlespeed
  4041. self.dwell = dwell
  4042. self.dwelltime = dwelltime
  4043. self.segx = float(segx) if segx is not None else 0.0
  4044. self.segy = float(segy) if segy is not None else 0.0
  4045. self.input_geometry_bounds = None
  4046. self.oldx = None
  4047. self.oldy = None
  4048. self.tool = 0.0
  4049. # used for creating drill CCode geometry; will be updated in the generate_from_excellon_by_tool()
  4050. self.exc_drills = None
  4051. self.exc_tools = None
  4052. # search for toolchange parameters in the Toolchange Custom Code
  4053. self.re_toolchange_custom = re.compile(r'(%[a-zA-Z0-9\-_]+%)')
  4054. # search for toolchange code: M6
  4055. self.re_toolchange = re.compile(r'^\s*(M6)$')
  4056. # Attributes to be included in serialization
  4057. # Always append to it because it carries contents
  4058. # from Geometry.
  4059. self.ser_attrs += ['kind', 'z_cut', 'z_move', 'z_toolchange', 'feedrate', 'z_feedrate', 'feedrate_rapid',
  4060. 'tooldia', 'gcode', 'input_geometry_bounds', 'gcode_parsed', 'steps_per_circle',
  4061. 'z_depthpercut', 'spindlespeed', 'dwell', 'dwelltime']
  4062. @property
  4063. def postdata(self):
  4064. return self.__dict__
  4065. def convert_units(self, units):
  4066. factor = Geometry.convert_units(self, units)
  4067. log.debug("CNCjob.convert_units()")
  4068. self.z_cut = float(self.z_cut) * factor
  4069. self.z_move *= factor
  4070. self.feedrate *= factor
  4071. self.z_feedrate *= factor
  4072. self.feedrate_rapid *= factor
  4073. self.tooldia *= factor
  4074. self.z_toolchange *= factor
  4075. self.z_end *= factor
  4076. self.z_depthpercut = float(self.z_depthpercut) * factor
  4077. return factor
  4078. def doformat(self, fun, **kwargs):
  4079. return self.doformat2(fun, **kwargs) + "\n"
  4080. def doformat2(self, fun, **kwargs):
  4081. attributes = AttrDict()
  4082. attributes.update(self.postdata)
  4083. attributes.update(kwargs)
  4084. try:
  4085. returnvalue = fun(attributes)
  4086. return returnvalue
  4087. except Exception as e:
  4088. self.app.log.error('Exception occurred within a postprocessor: ' + traceback.format_exc())
  4089. return ''
  4090. def parse_custom_toolchange_code(self, data):
  4091. text = data
  4092. match_list = self.re_toolchange_custom.findall(text)
  4093. if match_list:
  4094. for match in match_list:
  4095. command = match.strip('%')
  4096. try:
  4097. value = getattr(self, command)
  4098. except AttributeError:
  4099. self.app.inform.emit(_("[ERROR] There is no such parameter: %s") % str(match))
  4100. log.debug("CNCJob.parse_custom_toolchange_code() --> AttributeError ")
  4101. return 'fail'
  4102. text = text.replace(match, str(value))
  4103. return text
  4104. def optimized_travelling_salesman(self, points, start=None):
  4105. """
  4106. As solving the problem in the brute force way is too slow,
  4107. this function implements a simple heuristic: always
  4108. go to the nearest city.
  4109. Even if this algorithm is extremely simple, it works pretty well
  4110. giving a solution only about 25% longer than the optimal one (cit. Wikipedia),
  4111. and runs very fast in O(N^2) time complexity.
  4112. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  4113. [[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],
  4114. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  4115. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  4116. [[0, 0], [6, 0], [10, 0]]
  4117. """
  4118. if start is None:
  4119. start = points[0]
  4120. must_visit = points
  4121. path = [start]
  4122. # must_visit.remove(start)
  4123. while must_visit:
  4124. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  4125. path.append(nearest)
  4126. must_visit.remove(nearest)
  4127. return path
  4128. def generate_from_excellon_by_tool(self, exobj, tools="all", drillz = 3.0,
  4129. toolchange=False, toolchangez=0.1, toolchangexy='',
  4130. endz=2.0, startz=None,
  4131. excellon_optimization_type='B'):
  4132. """
  4133. Creates gcode for this object from an Excellon object
  4134. for the specified tools.
  4135. :param exobj: Excellon object to process
  4136. :type exobj: Excellon
  4137. :param tools: Comma separated tool names
  4138. :type: tools: str
  4139. :param drillz: drill Z depth
  4140. :type drillz: float
  4141. :param toolchange: Use tool change sequence between tools.
  4142. :type toolchange: bool
  4143. :param toolchangez: Height at which to perform the tool change.
  4144. :type toolchangez: float
  4145. :param toolchangexy: Toolchange X,Y position
  4146. :type toolchangexy: String containing 2 floats separated by comma
  4147. :param startz: Z position just before starting the job
  4148. :type startz: float
  4149. :param endz: final Z position to move to at the end of the CNC job
  4150. :type endz: float
  4151. :param excellon_optimization_type: Single character that defines which drill re-ordering optimisation algorithm
  4152. is to be used: 'M' for meta-heuristic and 'B' for basic
  4153. :type excellon_optimization_type: string
  4154. :return: None
  4155. :rtype: None
  4156. """
  4157. # create a local copy of the exobj.drills so it can be used for creating drill CCode geometry
  4158. self.exc_drills = deepcopy(exobj.drills)
  4159. self.exc_tools = deepcopy(exobj.tools)
  4160. if drillz > 0:
  4161. self.app.inform.emit(_("[WARNING] The Cut Z parameter has positive value. "
  4162. "It is the depth value to drill into material.\n"
  4163. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4164. "therefore the app will convert the value to negative. "
  4165. "Check the resulting CNC code (Gcode etc)."))
  4166. self.z_cut = -drillz
  4167. elif drillz == 0:
  4168. self.app.inform.emit(_("[WARNING] The Cut Z parameter is zero. "
  4169. "There will be no cut, skipping %s file") % exobj.options['name'])
  4170. return 'fail'
  4171. else:
  4172. self.z_cut = drillz
  4173. self.z_toolchange = toolchangez
  4174. try:
  4175. if toolchangexy == '':
  4176. self.xy_toolchange = None
  4177. else:
  4178. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  4179. if len(self.xy_toolchange) < 2:
  4180. self.app.inform.emit(_("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4181. "in the format (x, y) \nbut now there is only one value, not two. "))
  4182. return 'fail'
  4183. except Exception as e:
  4184. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  4185. pass
  4186. self.startz = startz
  4187. self.z_end = endz
  4188. self.pp_excellon = self.app.postprocessors[self.pp_excellon_name]
  4189. p = self.pp_excellon
  4190. log.debug("Creating CNC Job from Excellon...")
  4191. # Tools
  4192. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  4193. # so we actually are sorting the tools by diameter
  4194. #sorted_tools = sorted(exobj.tools.items(), key=lambda t1: t1['C'])
  4195. sort = []
  4196. for k, v in list(exobj.tools.items()):
  4197. sort.append((k, v.get('C')))
  4198. sorted_tools = sorted(sort,key=lambda t1: t1[1])
  4199. if tools == "all":
  4200. tools = [i[0] for i in sorted_tools] # we get a array of ordered tools
  4201. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  4202. else:
  4203. selected_tools = [x.strip() for x in tools.split(",")] # we strip spaces and also separate the tools by ','
  4204. selected_tools = [t1 for t1 in selected_tools if t1 in selected_tools]
  4205. # Create a sorted list of selected tools from the sorted_tools list
  4206. tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  4207. log.debug("Tools selected and sorted are: %s" % str(tools))
  4208. # Points (Group by tool)
  4209. points = {}
  4210. for drill in exobj.drills:
  4211. if drill['tool'] in tools:
  4212. try:
  4213. points[drill['tool']].append(drill['point'])
  4214. except KeyError:
  4215. points[drill['tool']] = [drill['point']]
  4216. #log.debug("Found %d drills." % len(points))
  4217. self.gcode = []
  4218. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  4219. self.f_retract = self.app.defaults["excellon_f_retract"]
  4220. # Initialization
  4221. gcode = self.doformat(p.start_code)
  4222. gcode += self.doformat(p.feedrate_code)
  4223. if toolchange is False:
  4224. if self.xy_toolchange is not None:
  4225. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4226. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4227. else:
  4228. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  4229. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  4230. # Distance callback
  4231. class CreateDistanceCallback(object):
  4232. """Create callback to calculate distances between points."""
  4233. def __init__(self):
  4234. """Initialize distance array."""
  4235. locations = create_data_array()
  4236. size = len(locations)
  4237. self.matrix = {}
  4238. for from_node in range(size):
  4239. self.matrix[from_node] = {}
  4240. for to_node in range(size):
  4241. if from_node == to_node:
  4242. self.matrix[from_node][to_node] = 0
  4243. else:
  4244. x1 = locations[from_node][0]
  4245. y1 = locations[from_node][1]
  4246. x2 = locations[to_node][0]
  4247. y2 = locations[to_node][1]
  4248. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  4249. # def Distance(self, from_node, to_node):
  4250. # return int(self.matrix[from_node][to_node])
  4251. def Distance(self, from_index, to_index):
  4252. # Convert from routing variable Index to distance matrix NodeIndex.
  4253. from_node = manager.IndexToNode(from_index)
  4254. to_node = manager.IndexToNode(to_index)
  4255. return self.matrix[from_node][to_node]
  4256. # Create the data.
  4257. def create_data_array():
  4258. locations = []
  4259. for point in points[tool]:
  4260. locations.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  4261. return locations
  4262. if self.xy_toolchange is not None:
  4263. self.oldx = self.xy_toolchange[0]
  4264. self.oldy = self.xy_toolchange[1]
  4265. else:
  4266. self.oldx = 0.0
  4267. self.oldy = 0.0
  4268. measured_distance = 0
  4269. current_platform = platform.architecture()[0]
  4270. if current_platform == '64bit':
  4271. if excellon_optimization_type == 'M':
  4272. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  4273. if exobj.drills:
  4274. for tool in tools:
  4275. self.tool=tool
  4276. self.postdata['toolC'] = exobj.tools[tool]["C"]
  4277. self.tooldia = exobj.tools[tool]["C"]
  4278. ################################################
  4279. # Create the data.
  4280. node_list = []
  4281. locations = create_data_array()
  4282. tsp_size = len(locations)
  4283. num_routes = 1 # The number of routes, which is 1 in the TSP.
  4284. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  4285. depot = 0
  4286. # Create routing model.
  4287. if tsp_size > 0:
  4288. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  4289. routing = pywrapcp.RoutingModel(manager)
  4290. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  4291. search_parameters.local_search_metaheuristic = (
  4292. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  4293. # Set search time limit in milliseconds.
  4294. if float(self.app.defaults["excellon_search_time"]) != 0:
  4295. search_parameters.time_limit.seconds = int(
  4296. float(self.app.defaults["excellon_search_time"]))
  4297. else:
  4298. search_parameters.time_limit.seconds = 3
  4299. # Callback to the distance function. The callback takes two
  4300. # arguments (the from and to node indices) and returns the distance between them.
  4301. dist_between_locations = CreateDistanceCallback()
  4302. dist_callback = dist_between_locations.Distance
  4303. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  4304. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  4305. # Solve, returns a solution if any.
  4306. assignment = routing.SolveWithParameters(search_parameters)
  4307. if assignment:
  4308. # Solution cost.
  4309. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  4310. # Inspect solution.
  4311. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  4312. route_number = 0
  4313. node = routing.Start(route_number)
  4314. start_node = node
  4315. while not routing.IsEnd(node):
  4316. node_list.append(node)
  4317. node = assignment.Value(routing.NextVar(node))
  4318. else:
  4319. log.warning('No solution found.')
  4320. else:
  4321. log.warning('Specify an instance greater than 0.')
  4322. ################################################
  4323. # Only if tool has points.
  4324. if tool in points:
  4325. # Tool change sequence (optional)
  4326. if toolchange:
  4327. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  4328. gcode += self.doformat(p.spindle_code) # Spindle start
  4329. if self.dwell is True:
  4330. gcode += self.doformat(p.dwell_code) # Dwell time
  4331. else:
  4332. gcode += self.doformat(p.spindle_code)
  4333. if self.dwell is True:
  4334. gcode += self.doformat(p.dwell_code) # Dwell time
  4335. if self.units == 'MM':
  4336. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  4337. else:
  4338. current_tooldia = float('%.3f' % float(exobj.tools[tool]["C"]))
  4339. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  4340. # because the values for Z offset are created in build_ui()
  4341. try:
  4342. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  4343. except KeyError:
  4344. z_offset = 0
  4345. self.z_cut += z_offset
  4346. # Drillling!
  4347. for k in node_list:
  4348. locx = locations[k][0]
  4349. locy = locations[k][1]
  4350. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  4351. gcode += self.doformat(p.down_code, x=locx, y=locy)
  4352. if self.f_retract is False:
  4353. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  4354. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  4355. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  4356. self.oldx = locx
  4357. self.oldy = locy
  4358. else:
  4359. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  4360. "The loaded Excellon file has no drills ...")
  4361. self.app.inform.emit(_('[ERROR_NOTCL] The loaded Excellon file has no drills ...'))
  4362. return 'fail'
  4363. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  4364. elif excellon_optimization_type == 'B':
  4365. log.debug("Using OR-Tools Basic drill path optimization.")
  4366. if exobj.drills:
  4367. for tool in tools:
  4368. self.tool=tool
  4369. self.postdata['toolC']=exobj.tools[tool]["C"]
  4370. self.tooldia = exobj.tools[tool]["C"]
  4371. ################################################
  4372. node_list = []
  4373. locations = create_data_array()
  4374. tsp_size = len(locations)
  4375. num_routes = 1 # The number of routes, which is 1 in the TSP.
  4376. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  4377. depot = 0
  4378. # Create routing model.
  4379. if tsp_size > 0:
  4380. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  4381. routing = pywrapcp.RoutingModel(manager)
  4382. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  4383. # Callback to the distance function. The callback takes two
  4384. # arguments (the from and to node indices) and returns the distance between them.
  4385. dist_between_locations = CreateDistanceCallback()
  4386. dist_callback = dist_between_locations.Distance
  4387. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  4388. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  4389. # Solve, returns a solution if any.
  4390. assignment = routing.SolveWithParameters(search_parameters)
  4391. if assignment:
  4392. # Solution cost.
  4393. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  4394. # Inspect solution.
  4395. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  4396. route_number = 0
  4397. node = routing.Start(route_number)
  4398. start_node = node
  4399. while not routing.IsEnd(node):
  4400. node_list.append(node)
  4401. node = assignment.Value(routing.NextVar(node))
  4402. else:
  4403. log.warning('No solution found.')
  4404. else:
  4405. log.warning('Specify an instance greater than 0.')
  4406. ################################################
  4407. # Only if tool has points.
  4408. if tool in points:
  4409. # Tool change sequence (optional)
  4410. if toolchange:
  4411. gcode += self.doformat(p.toolchange_code,toolchangexy=(self.oldx, self.oldy))
  4412. gcode += self.doformat(p.spindle_code) # Spindle start)
  4413. if self.dwell is True:
  4414. gcode += self.doformat(p.dwell_code) # Dwell time
  4415. else:
  4416. gcode += self.doformat(p.spindle_code)
  4417. if self.dwell is True:
  4418. gcode += self.doformat(p.dwell_code) # Dwell time
  4419. if self.units == 'MM':
  4420. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  4421. else:
  4422. current_tooldia = float('%.3f' % float(exobj.tools[tool]["C"]))
  4423. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  4424. # because the values for Z offset are created in build_ui()
  4425. try:
  4426. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  4427. except KeyError:
  4428. z_offset = 0
  4429. self.z_cut += z_offset
  4430. # Drillling!
  4431. for k in node_list:
  4432. locx = locations[k][0]
  4433. locy = locations[k][1]
  4434. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  4435. gcode += self.doformat(p.down_code, x=locx, y=locy)
  4436. if self.f_retract is False:
  4437. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  4438. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  4439. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  4440. self.oldx = locx
  4441. self.oldy = locy
  4442. else:
  4443. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  4444. "The loaded Excellon file has no drills ...")
  4445. self.app.inform.emit(_('[ERROR_NOTCL] The loaded Excellon file has no drills ...'))
  4446. return 'fail'
  4447. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  4448. else:
  4449. self.app.inform.emit(_("[ERROR_NOTCL] Wrong optimization type selected."))
  4450. return 'fail'
  4451. else:
  4452. log.debug("Using Travelling Salesman drill path optimization.")
  4453. for tool in tools:
  4454. if exobj.drills:
  4455. self.tool = tool
  4456. self.postdata['toolC'] = exobj.tools[tool]["C"]
  4457. self.tooldia = exobj.tools[tool]["C"]
  4458. # Only if tool has points.
  4459. if tool in points:
  4460. # Tool change sequence (optional)
  4461. if toolchange:
  4462. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  4463. gcode += self.doformat(p.spindle_code) # Spindle start)
  4464. if self.dwell is True:
  4465. gcode += self.doformat(p.dwell_code) # Dwell time
  4466. else:
  4467. gcode += self.doformat(p.spindle_code)
  4468. if self.dwell is True:
  4469. gcode += self.doformat(p.dwell_code) # Dwell time
  4470. if self.units == 'MM':
  4471. current_tooldia = float('%.2f' % float(exobj.tools[tool]["C"]))
  4472. else:
  4473. current_tooldia = float('%.3f' % float(exobj.tools[tool]["C"]))
  4474. # TODO apply offset only when using the GUI, for TclCommand this will create an error
  4475. # because the values for Z offset are created in build_ui()
  4476. try:
  4477. z_offset = float(self.tool_offset[current_tooldia]) * (-1)
  4478. except KeyError:
  4479. z_offset = 0
  4480. self.z_cut += z_offset
  4481. # Drillling!
  4482. altPoints = []
  4483. for point in points[tool]:
  4484. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  4485. for point in self.optimized_travelling_salesman(altPoints):
  4486. gcode += self.doformat(p.rapid_code, x=point[0], y=point[1])
  4487. gcode += self.doformat(p.down_code, x=point[0], y=point[1])
  4488. if self.f_retract is False:
  4489. gcode += self.doformat(p.up_to_zero_code, x=point[0], y=point[1])
  4490. gcode += self.doformat(p.lift_code, x=point[0], y=point[1])
  4491. measured_distance += abs(distance_euclidian(point[0], point[1], self.oldx, self.oldy))
  4492. self.oldx = point[0]
  4493. self.oldy = point[1]
  4494. else:
  4495. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  4496. "The loaded Excellon file has no drills ...")
  4497. self.app.inform.emit(_('[ERROR_NOTCL] The loaded Excellon file has no drills ...'))
  4498. return 'fail'
  4499. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  4500. gcode += self.doformat(p.spindle_stop_code) # Spindle stop
  4501. gcode += self.doformat(p.end_code, x=0, y=0)
  4502. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  4503. log.debug("The total travel distance including travel to end position is: %s" %
  4504. str(measured_distance) + '\n')
  4505. self.travel_distance = measured_distance
  4506. self.gcode = gcode
  4507. return 'OK'
  4508. def generate_from_multitool_geometry(self, geometry, append=True,
  4509. tooldia=None, offset=0.0, tolerance=0, z_cut=1.0, z_move=2.0,
  4510. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  4511. spindlespeed=None, dwell=False, dwelltime=1.0,
  4512. multidepth=False, depthpercut=None,
  4513. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0", extracut=False,
  4514. startz=None, endz=2.0, pp_geometry_name=None, tool_no=1):
  4515. """
  4516. Algorithm to generate from multitool Geometry.
  4517. Algorithm description:
  4518. ----------------------
  4519. Uses RTree to find the nearest path to follow.
  4520. :param geometry:
  4521. :param append:
  4522. :param tooldia:
  4523. :param tolerance:
  4524. :param multidepth: If True, use multiple passes to reach
  4525. the desired depth.
  4526. :param depthpercut: Maximum depth in each pass.
  4527. :param extracut: Adds (or not) an extra cut at the end of each path
  4528. overlapping the first point in path to ensure complete copper removal
  4529. :return: GCode - string
  4530. """
  4531. log.debug("Generate_from_multitool_geometry()")
  4532. temp_solid_geometry = []
  4533. if offset != 0.0:
  4534. for it in geometry:
  4535. # if the geometry is a closed shape then create a Polygon out of it
  4536. if isinstance(it, LineString):
  4537. c = it.coords
  4538. if c[0] == c[-1]:
  4539. it = Polygon(it)
  4540. temp_solid_geometry.append(it.buffer(offset, join_style=2))
  4541. else:
  4542. temp_solid_geometry = geometry
  4543. ## Flatten the geometry. Only linear elements (no polygons) remain.
  4544. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4545. log.debug("%d paths" % len(flat_geometry))
  4546. self.tooldia = float(tooldia) if tooldia else None
  4547. self.z_cut = float(z_cut) if z_cut else None
  4548. self.z_move = float(z_move) if z_move else None
  4549. self.feedrate = float(feedrate) if feedrate else None
  4550. self.z_feedrate = float(feedrate_z) if feedrate_z else None
  4551. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  4552. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  4553. self.dwell = dwell
  4554. self.dwelltime = float(dwelltime) if dwelltime else None
  4555. self.startz = float(startz) if startz else None
  4556. self.z_end = float(endz) if endz else None
  4557. self.z_depthpercut = float(depthpercut) if depthpercut else None
  4558. self.multidepth = multidepth
  4559. self.z_toolchange = float(toolchangez) if toolchangez else None
  4560. # it servers in the postprocessor file
  4561. self.tool = tool_no
  4562. try:
  4563. if toolchangexy == '':
  4564. self.xy_toolchange = None
  4565. else:
  4566. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  4567. if len(self.xy_toolchange) < 2:
  4568. self.app.inform.emit(_("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4569. "in the format (x, y) \nbut now there is only one value, not two. "))
  4570. return 'fail'
  4571. except Exception as e:
  4572. log.debug("camlib.CNCJob.generate_from_multitool_geometry() --> %s" % str(e))
  4573. pass
  4574. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4575. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4576. if self.z_cut is None:
  4577. self.app.inform.emit(_("[ERROR_NOTCL] Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4578. "other parameters."))
  4579. return 'fail'
  4580. if self.z_cut > 0:
  4581. self.app.inform.emit(_("[WARNING] The Cut Z parameter has positive value. "
  4582. "It is the depth value to cut into material.\n"
  4583. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4584. "therefore the app will convert the value to negative."
  4585. "Check the resulting CNC code (Gcode etc)."))
  4586. self.z_cut = -self.z_cut
  4587. elif self.z_cut == 0:
  4588. self.app.inform.emit(_("[WARNING] The Cut Z parameter is zero. "
  4589. "There will be no cut, skipping %s file") % self.options['name'])
  4590. return 'fail'
  4591. if self.z_move is None:
  4592. self.app.inform.emit(_("[ERROR_NOTCL] Travel Z parameter is None or zero."))
  4593. return 'fail'
  4594. if self.z_move < 0:
  4595. self.app.inform.emit(_("[WARNING] The Travel Z parameter has negative value. "
  4596. "It is the height value to travel between cuts.\n"
  4597. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4598. "therefore the app will convert the value to positive."
  4599. "Check the resulting CNC code (Gcode etc)."))
  4600. self.z_move = -self.z_move
  4601. elif self.z_move == 0:
  4602. self.app.inform.emit(_("[WARNING] The Z Travel parameter is zero. "
  4603. "This is dangerous, skipping %s file") % self.options['name'])
  4604. return 'fail'
  4605. ## Index first and last points in paths
  4606. # What points to index.
  4607. def get_pts(o):
  4608. return [o.coords[0], o.coords[-1]]
  4609. # Create the indexed storage.
  4610. storage = FlatCAMRTreeStorage()
  4611. storage.get_points = get_pts
  4612. # Store the geometry
  4613. log.debug("Indexing geometry before generating G-Code...")
  4614. for shape in flat_geometry:
  4615. if shape is not None: # TODO: This shouldn't have happened.
  4616. storage.insert(shape)
  4617. # self.input_geometry_bounds = geometry.bounds()
  4618. if not append:
  4619. self.gcode = ""
  4620. # tell postprocessor the number of tool (for toolchange)
  4621. self.tool = tool_no
  4622. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  4623. # given under the name 'toolC'
  4624. self.postdata['toolC'] = self.tooldia
  4625. # Initial G-Code
  4626. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  4627. p = self.pp_geometry
  4628. self.gcode = self.doformat(p.start_code)
  4629. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4630. if toolchange is False:
  4631. self.gcode += self.doformat(p.lift_code, x=0, y=0) # Move (up) to travel height
  4632. self.gcode += self.doformat(p.startz_code, x=0, y=0)
  4633. if toolchange:
  4634. # if "line_xyz" in self.pp_geometry_name:
  4635. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4636. # else:
  4637. # self.gcode += self.doformat(p.toolchange_code)
  4638. self.gcode += self.doformat(p.toolchange_code)
  4639. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4640. if self.dwell is True:
  4641. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4642. else:
  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. ## Iterate over geometry paths getting the nearest each time.
  4647. log.debug("Starting G-Code...")
  4648. path_count = 0
  4649. current_pt = (0, 0)
  4650. pt, geo = storage.nearest(current_pt)
  4651. try:
  4652. while True:
  4653. path_count += 1
  4654. # Remove before modifying, otherwise deletion will fail.
  4655. storage.remove(geo)
  4656. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4657. # then reverse coordinates.
  4658. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4659. geo.coords = list(geo.coords)[::-1]
  4660. #---------- Single depth/pass --------
  4661. if not multidepth:
  4662. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance)
  4663. #--------- Multi-pass ---------
  4664. else:
  4665. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  4666. postproc=p, current_point=current_pt)
  4667. current_pt = geo.coords[-1]
  4668. pt, geo = storage.nearest(current_pt) # Next
  4669. except StopIteration: # Nothing found in storage.
  4670. pass
  4671. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4672. # Finish
  4673. self.gcode += self.doformat(p.spindle_stop_code)
  4674. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4675. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4676. return self.gcode
  4677. def generate_from_geometry_2(self, geometry, append=True,
  4678. tooldia=None, offset=0.0, tolerance=0,
  4679. z_cut=1.0, z_move=2.0,
  4680. feedrate=2.0, feedrate_z=2.0, feedrate_rapid=30,
  4681. spindlespeed=None, dwell=False, dwelltime=1.0,
  4682. multidepth=False, depthpercut=None,
  4683. toolchange=False, toolchangez=1.0, toolchangexy="0.0, 0.0",
  4684. extracut=False, startz=None, endz=2.0,
  4685. pp_geometry_name=None, tool_no=1):
  4686. """
  4687. Second algorithm to generate from Geometry.
  4688. Algorithm description:
  4689. ----------------------
  4690. Uses RTree to find the nearest path to follow.
  4691. :param geometry:
  4692. :param append:
  4693. :param tooldia:
  4694. :param tolerance:
  4695. :param multidepth: If True, use multiple passes to reach
  4696. the desired depth.
  4697. :param depthpercut: Maximum depth in each pass.
  4698. :param extracut: Adds (or not) an extra cut at the end of each path
  4699. overlapping the first point in path to ensure complete copper removal
  4700. :return: None
  4701. """
  4702. if not isinstance(geometry, Geometry):
  4703. self.app.inform.emit(_("[ERROR]Expected a Geometry, got %s") % type(geometry))
  4704. return 'fail'
  4705. log.debug("Generate_from_geometry_2()")
  4706. # if solid_geometry is empty raise an exception
  4707. if not geometry.solid_geometry:
  4708. self.app.inform.emit(_("[ERROR_NOTCL] Trying to generate a CNC Job "
  4709. "from a Geometry object without solid_geometry."))
  4710. temp_solid_geometry = []
  4711. def bounds_rec(obj):
  4712. if type(obj) is list:
  4713. minx = Inf
  4714. miny = Inf
  4715. maxx = -Inf
  4716. maxy = -Inf
  4717. for k in obj:
  4718. if type(k) is dict:
  4719. for key in k:
  4720. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  4721. minx = min(minx, minx_)
  4722. miny = min(miny, miny_)
  4723. maxx = max(maxx, maxx_)
  4724. maxy = max(maxy, maxy_)
  4725. else:
  4726. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  4727. minx = min(minx, minx_)
  4728. miny = min(miny, miny_)
  4729. maxx = max(maxx, maxx_)
  4730. maxy = max(maxy, maxy_)
  4731. return minx, miny, maxx, maxy
  4732. else:
  4733. # it's a Shapely object, return it's bounds
  4734. return obj.bounds
  4735. if offset != 0.0:
  4736. offset_for_use = offset
  4737. if offset <0:
  4738. a, b, c, d = bounds_rec(geometry.solid_geometry)
  4739. # if the offset is less than half of the total length or less than half of the total width of the
  4740. # solid geometry it's obvious we can't do the offset
  4741. if -offset > ((c - a) / 2) or -offset > ((d - b) / 2):
  4742. self.app.inform.emit(_("[ERROR_NOTCL] The Tool Offset value is too negative to use "
  4743. "for the current_geometry.\n"
  4744. "Raise the value (in module) and try again."))
  4745. return 'fail'
  4746. # hack: make offset smaller by 0.0000000001 which is insignificant difference but allow the job
  4747. # to continue
  4748. elif -offset == ((c - a) / 2) or -offset == ((d - b) / 2):
  4749. offset_for_use = offset - 0.0000000001
  4750. for it in geometry.solid_geometry:
  4751. # if the geometry is a closed shape then create a Polygon out of it
  4752. if isinstance(it, LineString):
  4753. c = it.coords
  4754. if c[0] == c[-1]:
  4755. it = Polygon(it)
  4756. temp_solid_geometry.append(it.buffer(offset_for_use, join_style=2))
  4757. else:
  4758. temp_solid_geometry = geometry.solid_geometry
  4759. ## Flatten the geometry. Only linear elements (no polygons) remain.
  4760. flat_geometry = self.flatten(temp_solid_geometry, pathonly=True)
  4761. log.debug("%d paths" % len(flat_geometry))
  4762. self.tooldia = float(tooldia) if tooldia else None
  4763. self.z_cut = float(z_cut) if z_cut else None
  4764. self.z_move = float(z_move) if z_move else None
  4765. self.feedrate = float(feedrate) if feedrate else None
  4766. self.z_feedrate = float(feedrate_z) if feedrate_z else None
  4767. self.feedrate_rapid = float(feedrate_rapid) if feedrate_rapid else None
  4768. self.spindlespeed = int(spindlespeed) if spindlespeed else None
  4769. self.dwell = dwell
  4770. self.dwelltime = float(dwelltime) if dwelltime else None
  4771. self.startz = float(startz) if startz else None
  4772. self.z_end = float(endz) if endz else None
  4773. self.z_depthpercut = float(depthpercut) if depthpercut else None
  4774. self.multidepth = multidepth
  4775. self.z_toolchange = float(toolchangez) if toolchangez else None
  4776. try:
  4777. if toolchangexy == '':
  4778. self.xy_toolchange = None
  4779. else:
  4780. self.xy_toolchange = [float(eval(a)) for a in toolchangexy.split(",")]
  4781. if len(self.xy_toolchange) < 2:
  4782. self.app.inform.emit(_("[ERROR]The Toolchange X,Y field in Edit -> Preferences has to be "
  4783. "in the format (x, y) \nbut now there is only one value, not two. "))
  4784. return 'fail'
  4785. except Exception as e:
  4786. log.debug("camlib.CNCJob.generate_from_geometry_2() --> %s" % str(e))
  4787. pass
  4788. self.pp_geometry_name = pp_geometry_name if pp_geometry_name else 'default'
  4789. self.f_plunge = self.app.defaults["geometry_f_plunge"]
  4790. if self.z_cut is None:
  4791. self.app.inform.emit(_("[ERROR_NOTCL] Cut_Z parameter is None or zero. Most likely a bad combinations of "
  4792. "other parameters."))
  4793. return 'fail'
  4794. if self.z_cut > 0:
  4795. self.app.inform.emit(_("[WARNING] The Cut Z parameter has positive value. "
  4796. "It is the depth value to cut into material.\n"
  4797. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  4798. "therefore the app will convert the value to negative."
  4799. "Check the resulting CNC code (Gcode etc)."))
  4800. self.z_cut = -self.z_cut
  4801. elif self.z_cut == 0:
  4802. self.app.inform.emit(_("[WARNING] The Cut Z parameter is zero. "
  4803. "There will be no cut, skipping %s file") % geometry.options['name'])
  4804. return 'fail'
  4805. if self.z_move is None:
  4806. self.app.inform.emit(_("[ERROR_NOTCL] Travel Z parameter is None or zero."))
  4807. return 'fail'
  4808. if self.z_move < 0:
  4809. self.app.inform.emit(_("[WARNING] The Travel Z parameter has negative value. "
  4810. "It is the height value to travel between cuts.\n"
  4811. "The Z Travel parameter needs to have a positive value, assuming it is a typo "
  4812. "therefore the app will convert the value to positive."
  4813. "Check the resulting CNC code (Gcode etc)."))
  4814. self.z_move = -self.z_move
  4815. elif self.z_move == 0:
  4816. self.app.inform.emit(_("[WARNING] The Z Travel parameter is zero. "
  4817. "This is dangerous, skipping %s file") % self.options['name'])
  4818. return 'fail'
  4819. ## Index first and last points in paths
  4820. # What points to index.
  4821. def get_pts(o):
  4822. return [o.coords[0], o.coords[-1]]
  4823. # Create the indexed storage.
  4824. storage = FlatCAMRTreeStorage()
  4825. storage.get_points = get_pts
  4826. # Store the geometry
  4827. log.debug("Indexing geometry before generating G-Code...")
  4828. for shape in flat_geometry:
  4829. if shape is not None: # TODO: This shouldn't have happened.
  4830. storage.insert(shape)
  4831. # self.input_geometry_bounds = geometry.bounds()
  4832. if not append:
  4833. self.gcode = ""
  4834. # tell postprocessor the number of tool (for toolchange)
  4835. self.tool = tool_no
  4836. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  4837. # given under the name 'toolC'
  4838. self.postdata['toolC'] = self.tooldia
  4839. # Initial G-Code
  4840. self.pp_geometry = self.app.postprocessors[self.pp_geometry_name]
  4841. p = self.pp_geometry
  4842. self.oldx = 0.0
  4843. self.oldy = 0.0
  4844. self.gcode = self.doformat(p.start_code)
  4845. self.gcode += self.doformat(p.feedrate_code) # sets the feed rate
  4846. if toolchange is False:
  4847. self.gcode += self.doformat(p.lift_code, x=self.oldx , y=self.oldy ) # Move (up) to travel height
  4848. self.gcode += self.doformat(p.startz_code, x=self.oldx , y=self.oldy )
  4849. if toolchange:
  4850. # if "line_xyz" in self.pp_geometry_name:
  4851. # self.gcode += self.doformat(p.toolchange_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  4852. # else:
  4853. # self.gcode += self.doformat(p.toolchange_code)
  4854. self.gcode += self.doformat(p.toolchange_code)
  4855. self.gcode += self.doformat(p.spindle_code) # Spindle start
  4856. if self.dwell is True:
  4857. self.gcode += self.doformat(p.dwell_code) # Dwell time
  4858. else:
  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. ## Iterate over geometry paths getting the nearest each time.
  4863. log.debug("Starting G-Code...")
  4864. path_count = 0
  4865. current_pt = (0, 0)
  4866. pt, geo = storage.nearest(current_pt)
  4867. try:
  4868. while True:
  4869. path_count += 1
  4870. # Remove before modifying, otherwise deletion will fail.
  4871. storage.remove(geo)
  4872. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4873. # then reverse coordinates.
  4874. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4875. geo.coords = list(geo.coords)[::-1]
  4876. #---------- Single depth/pass --------
  4877. if not multidepth:
  4878. self.gcode += self.create_gcode_single_pass(geo, extracut, tolerance)
  4879. #--------- Multi-pass ---------
  4880. else:
  4881. self.gcode += self.create_gcode_multi_pass(geo, extracut, tolerance,
  4882. postproc=p, current_point=current_pt)
  4883. current_pt = geo.coords[-1]
  4884. pt, geo = storage.nearest(current_pt) # Next
  4885. except StopIteration: # Nothing found in storage.
  4886. pass
  4887. log.debug("Finishing G-Code... %s paths traced." % path_count)
  4888. # Finish
  4889. self.gcode += self.doformat(p.spindle_stop_code)
  4890. self.gcode += self.doformat(p.lift_code, x=current_pt[0], y=current_pt[1])
  4891. self.gcode += self.doformat(p.end_code, x=0, y=0)
  4892. return self.gcode
  4893. def generate_gcode_from_solderpaste_geo(self, **kwargs):
  4894. """
  4895. Algorithm to generate from multitool Geometry.
  4896. Algorithm description:
  4897. ----------------------
  4898. Uses RTree to find the nearest path to follow.
  4899. :return: Gcode string
  4900. """
  4901. log.debug("Generate_from_solderpaste_geometry()")
  4902. ## Index first and last points in paths
  4903. # What points to index.
  4904. def get_pts(o):
  4905. return [o.coords[0], o.coords[-1]]
  4906. self.gcode = ""
  4907. if not kwargs:
  4908. log.debug("camlib.generate_from_solderpaste_geo() --> No tool in the solderpaste geometry.")
  4909. self.app.inform.emit(_("[ERROR_NOTCL] There is no tool data in the SolderPaste geometry."))
  4910. # this is the tool diameter, it is used as such to accommodate the postprocessor who need the tool diameter
  4911. # given under the name 'toolC'
  4912. self.postdata['z_start'] = kwargs['data']['tools_solderpaste_z_start']
  4913. self.postdata['z_dispense'] = kwargs['data']['tools_solderpaste_z_dispense']
  4914. self.postdata['z_stop'] = kwargs['data']['tools_solderpaste_z_stop']
  4915. self.postdata['z_travel'] = kwargs['data']['tools_solderpaste_z_travel']
  4916. self.postdata['z_toolchange'] = kwargs['data']['tools_solderpaste_z_toolchange']
  4917. self.postdata['xy_toolchange'] = kwargs['data']['tools_solderpaste_xy_toolchange']
  4918. self.postdata['frxy'] = kwargs['data']['tools_solderpaste_frxy']
  4919. self.postdata['frz'] = kwargs['data']['tools_solderpaste_frz']
  4920. self.postdata['frz_dispense'] = kwargs['data']['tools_solderpaste_frz_dispense']
  4921. self.postdata['speedfwd'] = kwargs['data']['tools_solderpaste_speedfwd']
  4922. self.postdata['dwellfwd'] = kwargs['data']['tools_solderpaste_dwellfwd']
  4923. self.postdata['speedrev'] = kwargs['data']['tools_solderpaste_speedrev']
  4924. self.postdata['dwellrev'] = kwargs['data']['tools_solderpaste_dwellrev']
  4925. self.postdata['pp_solderpaste_name'] = kwargs['data']['tools_solderpaste_pp']
  4926. self.postdata['toolC'] = kwargs['tooldia']
  4927. self.pp_solderpaste_name = kwargs['data']['tools_solderpaste_pp'] if kwargs['data']['tools_solderpaste_pp'] \
  4928. else self.app.defaults['tools_solderpaste_pp']
  4929. p = self.app.postprocessors[self.pp_solderpaste_name]
  4930. ## Flatten the geometry. Only linear elements (no polygons) remain.
  4931. flat_geometry = self.flatten(kwargs['solid_geometry'], pathonly=True)
  4932. log.debug("%d paths" % len(flat_geometry))
  4933. # Create the indexed storage.
  4934. storage = FlatCAMRTreeStorage()
  4935. storage.get_points = get_pts
  4936. # Store the geometry
  4937. log.debug("Indexing geometry before generating G-Code...")
  4938. for shape in flat_geometry:
  4939. if shape is not None:
  4940. storage.insert(shape)
  4941. # Initial G-Code
  4942. self.gcode = self.doformat(p.start_code)
  4943. self.gcode += self.doformat(p.spindle_off_code)
  4944. self.gcode += self.doformat(p.toolchange_code)
  4945. ## Iterate over geometry paths getting the nearest each time.
  4946. log.debug("Starting SolderPaste G-Code...")
  4947. path_count = 0
  4948. current_pt = (0, 0)
  4949. pt, geo = storage.nearest(current_pt)
  4950. try:
  4951. while True:
  4952. path_count += 1
  4953. # Remove before modifying, otherwise deletion will fail.
  4954. storage.remove(geo)
  4955. # If last point in geometry is the nearest but prefer the first one if last point == first point
  4956. # then reverse coordinates.
  4957. if pt != geo.coords[0] and pt == geo.coords[-1]:
  4958. geo.coords = list(geo.coords)[::-1]
  4959. self.gcode += self.create_soldepaste_gcode(geo, p=p)
  4960. current_pt = geo.coords[-1]
  4961. pt, geo = storage.nearest(current_pt) # Next
  4962. except StopIteration: # Nothing found in storage.
  4963. pass
  4964. log.debug("Finishing SolderPste G-Code... %s paths traced." % path_count)
  4965. # Finish
  4966. self.gcode += self.doformat(p.lift_code)
  4967. self.gcode += self.doformat(p.end_code)
  4968. return self.gcode
  4969. def create_soldepaste_gcode(self, geometry, p):
  4970. gcode = ''
  4971. path = geometry.coords
  4972. if type(geometry) == LineString or type(geometry) == LinearRing:
  4973. # Move fast to 1st point
  4974. gcode += self.doformat(p.rapid_code, x=path[0][0], y=path[0][1]) # Move to first point
  4975. # Move down to cutting depth
  4976. gcode += self.doformat(p.z_feedrate_code)
  4977. gcode += self.doformat(p.down_z_start_code)
  4978. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4979. gcode += self.doformat(p.dwell_fwd_code)
  4980. gcode += self.doformat(p.z_feedrate_dispense_code)
  4981. gcode += self.doformat(p.lift_z_dispense_code)
  4982. gcode += self.doformat(p.feedrate_xy_code)
  4983. # Cutting...
  4984. for pt in path[1:]:
  4985. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1]) # Linear motion to point
  4986. # Up to travelling height.
  4987. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  4988. gcode += self.doformat(p.spindle_rev_code)
  4989. gcode += self.doformat(p.down_z_stop_code)
  4990. gcode += self.doformat(p.spindle_off_code)
  4991. gcode += self.doformat(p.dwell_rev_code)
  4992. gcode += self.doformat(p.z_feedrate_code)
  4993. gcode += self.doformat(p.lift_code)
  4994. elif type(geometry) == Point:
  4995. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1]) # Move to first point
  4996. gcode += self.doformat(p.z_feedrate_dispense_code)
  4997. gcode += self.doformat(p.down_z_start_code)
  4998. gcode += self.doformat(p.spindle_fwd_code) # Start dispensing
  4999. gcode += self.doformat(p.dwell_fwd_code)
  5000. gcode += self.doformat(p.lift_z_dispense_code)
  5001. gcode += self.doformat(p.spindle_off_code) # Stop dispensing
  5002. gcode += self.doformat(p.spindle_rev_code)
  5003. gcode += self.doformat(p.spindle_off_code)
  5004. gcode += self.doformat(p.down_z_stop_code)
  5005. gcode += self.doformat(p.dwell_rev_code)
  5006. gcode += self.doformat(p.z_feedrate_code)
  5007. gcode += self.doformat(p.lift_code)
  5008. return gcode
  5009. def create_gcode_single_pass(self, geometry, extracut, tolerance):
  5010. # G-code. Note: self.linear2gcode() and self.point2gcode() will lower and raise the tool every time.
  5011. gcode_single_pass = ''
  5012. if type(geometry) == LineString or type(geometry) == LinearRing:
  5013. if extracut is False:
  5014. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance)
  5015. else:
  5016. if geometry.is_ring:
  5017. gcode_single_pass = self.linear2gcode_extra(geometry, tolerance=tolerance)
  5018. else:
  5019. gcode_single_pass = self.linear2gcode(geometry, tolerance=tolerance)
  5020. elif type(geometry) == Point:
  5021. gcode_single_pass = self.point2gcode(geometry)
  5022. else:
  5023. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5024. return
  5025. return gcode_single_pass
  5026. def create_gcode_multi_pass(self, geometry, extracut, tolerance, postproc, current_point):
  5027. gcode_multi_pass = ''
  5028. if isinstance(self.z_cut, Decimal):
  5029. z_cut = self.z_cut
  5030. else:
  5031. z_cut = Decimal(self.z_cut).quantize(Decimal('0.000000001'))
  5032. if self.z_depthpercut is None:
  5033. self.z_depthpercut = z_cut
  5034. elif not isinstance(self.z_depthpercut, Decimal):
  5035. self.z_depthpercut = Decimal(self.z_depthpercut).quantize(Decimal('0.000000001'))
  5036. depth = 0
  5037. reverse = False
  5038. while depth > z_cut:
  5039. # Increase depth. Limit to z_cut.
  5040. depth -= self.z_depthpercut
  5041. if depth < z_cut:
  5042. depth = z_cut
  5043. # Cut at specific depth and do not lift the tool.
  5044. # Note: linear2gcode() will use G00 to move to the first point in the path, but it should be already
  5045. # at the first point if the tool is down (in the material). So, an extra G00 should show up but
  5046. # is inconsequential.
  5047. if type(geometry) == LineString or type(geometry) == LinearRing:
  5048. if extracut is False:
  5049. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False)
  5050. else:
  5051. if geometry.is_ring:
  5052. gcode_multi_pass += self.linear2gcode_extra(geometry, tolerance=tolerance, z_cut=depth, up=False)
  5053. else:
  5054. gcode_multi_pass += self.linear2gcode(geometry, tolerance=tolerance, z_cut=depth, up=False)
  5055. # Ignore multi-pass for points.
  5056. elif type(geometry) == Point:
  5057. gcode_multi_pass += self.point2gcode(geometry)
  5058. break # Ignoring ...
  5059. else:
  5060. log.warning("G-code generation not implemented for %s" % (str(type(geometry))))
  5061. # Reverse coordinates if not a loop so we can continue cutting without returning to the beginning.
  5062. if type(geometry) == LineString:
  5063. geometry.coords = list(geometry.coords)[::-1]
  5064. reverse = True
  5065. # If geometry is reversed, revert.
  5066. if reverse:
  5067. if type(geometry) == LineString:
  5068. geometry.coords = list(geometry.coords)[::-1]
  5069. # Lift the tool
  5070. gcode_multi_pass += self.doformat(postproc.lift_code, x=current_point[0], y=current_point[1])
  5071. return gcode_multi_pass
  5072. def codes_split(self, gline):
  5073. """
  5074. Parses a line of G-Code such as "G01 X1234 Y987" into
  5075. a dictionary: {'G': 1.0, 'X': 1234.0, 'Y': 987.0}
  5076. :param gline: G-Code line string
  5077. :return: Dictionary with parsed line.
  5078. """
  5079. command = {}
  5080. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5081. match_z = re.search(r"^Z(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5082. if match_z:
  5083. command['G'] = 0
  5084. command['X'] = float(match_z.group(1).replace(" ", "")) * 0.025
  5085. command['Y'] = float(match_z.group(2).replace(" ", "")) * 0.025
  5086. command['Z'] = float(match_z.group(3).replace(" ", "")) * 0.025
  5087. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5088. match_pa = re.search(r"^PA(\s*-?\d+\.\d+?),(\s*\s*-?\d+\.\d+?)*;$", gline)
  5089. if match_pa:
  5090. command['G'] = 0
  5091. command['X'] = float(match_pa.group(1).replace(" ", ""))
  5092. command['Y'] = float(match_pa.group(2).replace(" ", ""))
  5093. match_pen = re.search(r"^(P[U|D])", gline)
  5094. if match_pen:
  5095. if match_pen.group(1) == 'PU':
  5096. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5097. # therefore the move is of kind T (travel)
  5098. command['Z'] = 1
  5099. else:
  5100. command['Z'] = 0
  5101. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name or \
  5102. (self.pp_solderpaste_name is not None and 'Paste' in self.pp_solderpaste_name):
  5103. match_lsr = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5104. if match_lsr:
  5105. command['X'] = float(match_lsr.group(1).replace(" ", ""))
  5106. command['Y'] = float(match_lsr.group(2).replace(" ", ""))
  5107. match_lsr_pos = re.search(r"^(M0[3|5])", gline)
  5108. if match_lsr_pos:
  5109. if match_lsr_pos.group(1) == 'M05':
  5110. # the value does not matter, only that it is positive so the gcode_parse() know it is > 0,
  5111. # therefore the move is of kind T (travel)
  5112. command['Z'] = 1
  5113. else:
  5114. command['Z'] = 0
  5115. elif self.pp_solderpaste_name is not None:
  5116. if 'Paste' in self.pp_solderpaste_name:
  5117. match_paste = re.search(r"X([\+-]?\d+.[\+-]?\d+)\s*Y([\+-]?\d+.[\+-]?\d+)", gline)
  5118. if match_paste:
  5119. command['X'] = float(match_paste.group(1).replace(" ", ""))
  5120. command['Y'] = float(match_paste.group(2).replace(" ", ""))
  5121. else:
  5122. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5123. while match:
  5124. command[match.group(1)] = float(match.group(2).replace(" ", ""))
  5125. gline = gline[match.end():]
  5126. match = re.search(r'^\s*([A-Z])\s*([\+\-\.\d\s]+)', gline)
  5127. return command
  5128. def gcode_parse(self):
  5129. """
  5130. G-Code parser (from self.gcode). Generates dictionary with
  5131. single-segment LineString's and "kind" indicating cut or travel,
  5132. fast or feedrate speed.
  5133. """
  5134. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5135. # Results go here
  5136. geometry = []
  5137. # Last known instruction
  5138. current = {'X': 0.0, 'Y': 0.0, 'Z': 0.0, 'G': 0}
  5139. # Current path: temporary storage until tool is
  5140. # lifted or lowered.
  5141. if self.toolchange_xy_type == "excellon":
  5142. if self.app.defaults["excellon_toolchangexy"] == '':
  5143. pos_xy = [0, 0]
  5144. else:
  5145. pos_xy = [float(eval(a)) for a in self.app.defaults["excellon_toolchangexy"].split(",")]
  5146. else:
  5147. if self.app.defaults["geometry_toolchangexy"] == '':
  5148. pos_xy = [0, 0]
  5149. else:
  5150. pos_xy = [float(eval(a)) for a in self.app.defaults["geometry_toolchangexy"].split(",")]
  5151. path = [pos_xy]
  5152. # path = [(0, 0)]
  5153. # Process every instruction
  5154. for line in StringIO(self.gcode):
  5155. if '%MO' in line or '%' in line or 'MOIN' in line or 'MOMM' in line:
  5156. return "fail"
  5157. gobj = self.codes_split(line)
  5158. ## Units
  5159. if 'G' in gobj and (gobj['G'] == 20.0 or gobj['G'] == 21.0):
  5160. self.units = {20.0: "IN", 21.0: "MM"}[gobj['G']]
  5161. continue
  5162. ## Changing height
  5163. if 'Z' in gobj:
  5164. if 'Roland' in self.pp_excellon_name or 'Roland' in self.pp_geometry_name:
  5165. pass
  5166. elif 'hpgl' in self.pp_excellon_name or 'hpgl' in self.pp_geometry_name:
  5167. pass
  5168. elif 'grbl_laser' in self.pp_excellon_name or 'grbl_laser' in self.pp_geometry_name:
  5169. pass
  5170. elif ('X' in gobj or 'Y' in gobj) and gobj['Z'] != current['Z']:
  5171. if self.pp_geometry_name == 'line_xyz' or self.pp_excellon_name == 'line_xyz':
  5172. pass
  5173. else:
  5174. log.warning("Non-orthogonal motion: From %s" % str(current))
  5175. log.warning(" To: %s" % str(gobj))
  5176. current['Z'] = gobj['Z']
  5177. # Store the path into geometry and reset path
  5178. if len(path) > 1:
  5179. geometry.append({"geom": LineString(path),
  5180. "kind": kind})
  5181. path = [path[-1]] # Start with the last point of last path.
  5182. # create the geometry for the holes created when drilling Excellon drills
  5183. if self.origin_kind == 'excellon':
  5184. if current['Z'] < 0:
  5185. current_drill_point_coords = (float('%.4f' % current['X']), float('%.4f' % current['Y']))
  5186. # find the drill diameter knowing the drill coordinates
  5187. for pt_dict in self.exc_drills:
  5188. point_in_dict_coords = (float('%.4f' % pt_dict['point'].x),
  5189. float('%.4f' % pt_dict['point'].y))
  5190. if point_in_dict_coords == current_drill_point_coords:
  5191. tool = pt_dict['tool']
  5192. dia = self.exc_tools[tool]['C']
  5193. kind = ['C', 'F']
  5194. geometry.append({"geom": Point(current_drill_point_coords).
  5195. buffer(dia/2).exterior,
  5196. "kind": kind})
  5197. break
  5198. if 'G' in gobj:
  5199. current['G'] = int(gobj['G'])
  5200. if 'X' in gobj or 'Y' in gobj:
  5201. # TODO: I think there is a problem here, current['X] (and the rest of current[...] are not initialized
  5202. if 'X' in gobj:
  5203. x = gobj['X']
  5204. # current['X'] = x
  5205. else:
  5206. x = current['X']
  5207. if 'Y' in gobj:
  5208. y = gobj['Y']
  5209. else:
  5210. y = current['Y']
  5211. kind = ["C", "F"] # T=travel, C=cut, F=fast, S=slow
  5212. if current['Z'] > 0:
  5213. kind[0] = 'T'
  5214. if current['G'] > 0:
  5215. kind[1] = 'S'
  5216. if current['G'] in [0, 1]: # line
  5217. path.append((x, y))
  5218. arcdir = [None, None, "cw", "ccw"]
  5219. if current['G'] in [2, 3]: # arc
  5220. center = [gobj['I'] + current['X'], gobj['J'] + current['Y']]
  5221. radius = sqrt(gobj['I']**2 + gobj['J']**2)
  5222. start = arctan2(-gobj['J'], -gobj['I'])
  5223. stop = arctan2(-center[1] + y, -center[0] + x)
  5224. path += arc(center, radius, start, stop,
  5225. arcdir[current['G']],
  5226. int(self.steps_per_circle / 4))
  5227. # Update current instruction
  5228. for code in gobj:
  5229. current[code] = gobj[code]
  5230. # There might not be a change in height at the
  5231. # end, therefore, see here too if there is
  5232. # a final path.
  5233. if len(path) > 1:
  5234. geometry.append({"geom": LineString(path),
  5235. "kind": kind})
  5236. self.gcode_parsed = geometry
  5237. return geometry
  5238. # def plot(self, tooldia=None, dpi=75, margin=0.1,
  5239. # color={"T": ["#F0E24D", "#B5AB3A"], "C": ["#5E6CFF", "#4650BD"]},
  5240. # alpha={"T": 0.3, "C": 1.0}):
  5241. # """
  5242. # Creates a Matplotlib figure with a plot of the
  5243. # G-code job.
  5244. # """
  5245. # if tooldia is None:
  5246. # tooldia = self.tooldia
  5247. #
  5248. # fig = Figure(dpi=dpi)
  5249. # ax = fig.add_subplot(111)
  5250. # ax.set_aspect(1)
  5251. # xmin, ymin, xmax, ymax = self.input_geometry_bounds
  5252. # ax.set_xlim(xmin-margin, xmax+margin)
  5253. # ax.set_ylim(ymin-margin, ymax+margin)
  5254. #
  5255. # if tooldia == 0:
  5256. # for geo in self.gcode_parsed:
  5257. # linespec = '--'
  5258. # linecolor = color[geo['kind'][0]][1]
  5259. # if geo['kind'][0] == 'C':
  5260. # linespec = 'k-'
  5261. # x, y = geo['geom'].coords.xy
  5262. # ax.plot(x, y, linespec, color=linecolor)
  5263. # else:
  5264. # for geo in self.gcode_parsed:
  5265. # poly = geo['geom'].buffer(tooldia/2.0)
  5266. # patch = PolygonPatch(poly, facecolor=color[geo['kind'][0]][0],
  5267. # edgecolor=color[geo['kind'][0]][1],
  5268. # alpha=alpha[geo['kind'][0]], zorder=2)
  5269. # ax.add_patch(patch)
  5270. #
  5271. # return fig
  5272. def plot2(self, tooldia=None, dpi=75, margin=0.1, gcode_parsed=None,
  5273. color={"T": ["#F0E24D4C", "#B5AB3A4C"], "C": ["#5E6CFFFF", "#4650BDFF"]},
  5274. alpha={"T": 0.3, "C": 1.0}, tool_tolerance=0.0005, obj=None, visible=False, kind='all'):
  5275. """
  5276. Plots the G-code job onto the given axes.
  5277. :param tooldia: Tool diameter.
  5278. :param dpi: Not used!
  5279. :param margin: Not used!
  5280. :param color: Color specification.
  5281. :param alpha: Transparency specification.
  5282. :param tool_tolerance: Tolerance when drawing the toolshape.
  5283. :return: None
  5284. """
  5285. gcode_parsed = gcode_parsed if gcode_parsed else self.gcode_parsed
  5286. path_num = 0
  5287. if tooldia is None:
  5288. tooldia = self.tooldia
  5289. if tooldia == 0:
  5290. for geo in gcode_parsed:
  5291. if kind == 'all':
  5292. obj.add_shape(shape=geo['geom'], color=color[geo['kind'][0]][1], visible=visible)
  5293. elif kind == 'travel':
  5294. if geo['kind'][0] == 'T':
  5295. obj.add_shape(shape=geo['geom'], color=color['T'][1], visible=visible)
  5296. elif kind == 'cut':
  5297. if geo['kind'][0] == 'C':
  5298. obj.add_shape(shape=geo['geom'], color=color['C'][1], visible=visible)
  5299. else:
  5300. text = []
  5301. pos = []
  5302. for geo in gcode_parsed:
  5303. path_num += 1
  5304. text.append(str(path_num))
  5305. pos.append(geo['geom'].coords[0])
  5306. # plot the geometry of Excellon objects
  5307. if self.origin_kind == 'excellon':
  5308. try:
  5309. poly = Polygon(geo['geom'])
  5310. except ValueError:
  5311. # if the geos are travel lines it will enter into Exception
  5312. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  5313. else:
  5314. # plot the geometry of any objects other than Excellon
  5315. poly = geo['geom'].buffer(tooldia / 2.0).simplify(tool_tolerance)
  5316. if kind == 'all':
  5317. obj.add_shape(shape=poly, color=color[geo['kind'][0]][1], face_color=color[geo['kind'][0]][0],
  5318. visible=visible, layer=1 if geo['kind'][0] == 'C' else 2)
  5319. elif kind == 'travel':
  5320. if geo['kind'][0] == 'T':
  5321. obj.add_shape(shape=poly, color=color['T'][1], face_color=color['T'][0],
  5322. visible=visible, layer=2)
  5323. elif kind == 'cut':
  5324. if geo['kind'][0] == 'C':
  5325. obj.add_shape(shape=poly, color=color['C'][1], face_color=color['C'][0],
  5326. visible=visible, layer=1)
  5327. obj.annotation.set(text=text, pos=pos, visible=obj.options['plot'])
  5328. def create_geometry(self):
  5329. # TODO: This takes forever. Too much data?
  5330. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5331. return self.solid_geometry
  5332. # code snippet added by Lei Zheng in a rejected pull request on FlatCAM https://bitbucket.org/realthunder/
  5333. def segment(self, coords):
  5334. """
  5335. break long linear lines to make it more auto level friendly
  5336. """
  5337. if len(coords) < 2 or self.segx <= 0 and self.segy <= 0:
  5338. return list(coords)
  5339. path = [coords[0]]
  5340. # break the line in either x or y dimension only
  5341. def linebreak_single(line, dim, dmax):
  5342. if dmax <= 0:
  5343. return None
  5344. if line[1][dim] > line[0][dim]:
  5345. sign = 1.0
  5346. d = line[1][dim] - line[0][dim]
  5347. else:
  5348. sign = -1.0
  5349. d = line[0][dim] - line[1][dim]
  5350. if d > dmax:
  5351. # make sure we don't make any new lines too short
  5352. if d > dmax * 2:
  5353. dd = dmax
  5354. else:
  5355. dd = d / 2
  5356. other = dim ^ 1
  5357. return (line[0][dim] + dd * sign, line[0][other] + \
  5358. dd * (line[1][other] - line[0][other]) / d)
  5359. return None
  5360. # recursively breaks down a given line until it is within the
  5361. # required step size
  5362. def linebreak(line):
  5363. pt_new = linebreak_single(line, 0, self.segx)
  5364. if pt_new is None:
  5365. pt_new2 = linebreak_single(line, 1, self.segy)
  5366. else:
  5367. pt_new2 = linebreak_single((line[0], pt_new), 1, self.segy)
  5368. if pt_new2 is not None:
  5369. pt_new = pt_new2[::-1]
  5370. if pt_new is None:
  5371. path.append(line[1])
  5372. else:
  5373. path.append(pt_new)
  5374. linebreak((pt_new, line[1]))
  5375. for pt in coords[1:]:
  5376. linebreak((path[-1], pt))
  5377. return path
  5378. def linear2gcode(self, linear, tolerance=0, down=True, up=True,
  5379. z_cut=None, z_move=None, zdownrate=None,
  5380. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False):
  5381. """
  5382. Generates G-code to cut along the linear feature.
  5383. :param linear: The path to cut along.
  5384. :type: Shapely.LinearRing or Shapely.Linear String
  5385. :param tolerance: All points in the simplified object will be within the
  5386. tolerance distance of the original geometry.
  5387. :type tolerance: float
  5388. :param feedrate: speed for cut on X - Y plane
  5389. :param feedrate_z: speed for cut on Z plane
  5390. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5391. :return: G-code to cut along the linear feature.
  5392. :rtype: str
  5393. """
  5394. if z_cut is None:
  5395. z_cut = self.z_cut
  5396. if z_move is None:
  5397. z_move = self.z_move
  5398. #
  5399. # if zdownrate is None:
  5400. # zdownrate = self.zdownrate
  5401. if feedrate is None:
  5402. feedrate = self.feedrate
  5403. if feedrate_z is None:
  5404. feedrate_z = self.z_feedrate
  5405. if feedrate_rapid is None:
  5406. feedrate_rapid = self.feedrate_rapid
  5407. # Simplify paths?
  5408. if tolerance > 0:
  5409. target_linear = linear.simplify(tolerance)
  5410. else:
  5411. target_linear = linear
  5412. gcode = ""
  5413. # path = list(target_linear.coords)
  5414. path = self.segment(target_linear.coords)
  5415. p = self.pp_geometry
  5416. # Move fast to 1st point
  5417. if not cont:
  5418. gcode += self.doformat(p.rapid_code, x=path[0][0], y=path[0][1]) # Move to first point
  5419. # Move down to cutting depth
  5420. if down:
  5421. # Different feedrate for vertical cut?
  5422. gcode += self.doformat(p.z_feedrate_code)
  5423. # gcode += self.doformat(p.feedrate_code)
  5424. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut)
  5425. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5426. # Cutting...
  5427. for pt in path[1:]:
  5428. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1], z=z_cut) # Linear motion to point
  5429. # Up to travelling height.
  5430. if up:
  5431. gcode += self.doformat(p.lift_code, x=pt[0], y=pt[1], z_move=z_move) # Stop cutting
  5432. return gcode
  5433. def linear2gcode_extra(self, linear, tolerance=0, down=True, up=True,
  5434. z_cut=None, z_move=None, zdownrate=None,
  5435. feedrate=None, feedrate_z=None, feedrate_rapid=None, cont=False):
  5436. """
  5437. Generates G-code to cut along the linear feature.
  5438. :param linear: The path to cut along.
  5439. :type: Shapely.LinearRing or Shapely.Linear String
  5440. :param tolerance: All points in the simplified object will be within the
  5441. tolerance distance of the original geometry.
  5442. :type tolerance: float
  5443. :param feedrate: speed for cut on X - Y plane
  5444. :param feedrate_z: speed for cut on Z plane
  5445. :param feedrate_rapid: speed to move between cuts; usually is G0 but some CNC require to specify it
  5446. :return: G-code to cut along the linear feature.
  5447. :rtype: str
  5448. """
  5449. if z_cut is None:
  5450. z_cut = self.z_cut
  5451. if z_move is None:
  5452. z_move = self.z_move
  5453. #
  5454. # if zdownrate is None:
  5455. # zdownrate = self.zdownrate
  5456. if feedrate is None:
  5457. feedrate = self.feedrate
  5458. if feedrate_z is None:
  5459. feedrate_z = self.z_feedrate
  5460. if feedrate_rapid is None:
  5461. feedrate_rapid = self.feedrate_rapid
  5462. # Simplify paths?
  5463. if tolerance > 0:
  5464. target_linear = linear.simplify(tolerance)
  5465. else:
  5466. target_linear = linear
  5467. gcode = ""
  5468. path = list(target_linear.coords)
  5469. p = self.pp_geometry
  5470. # Move fast to 1st point
  5471. if not cont:
  5472. gcode += self.doformat(p.rapid_code, x=path[0][0], y=path[0][1]) # Move to first point
  5473. # Move down to cutting depth
  5474. if down:
  5475. # Different feedrate for vertical cut?
  5476. if self.z_feedrate is not None:
  5477. gcode += self.doformat(p.z_feedrate_code)
  5478. # gcode += self.doformat(p.feedrate_code)
  5479. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut)
  5480. gcode += self.doformat(p.feedrate_code, feedrate=feedrate)
  5481. else:
  5482. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut=z_cut) # Start cutting
  5483. # Cutting...
  5484. for pt in path[1:]:
  5485. gcode += self.doformat(p.linear_code, x=pt[0], y=pt[1], z=z_cut) # Linear motion to point
  5486. # this line is added to create an extra cut over the first point in patch
  5487. # to make sure that we remove the copper leftovers
  5488. gcode += self.doformat(p.linear_code, x=path[1][0], y=path[1][1]) # Linear motion to the 1st point in the cut path
  5489. # Up to travelling height.
  5490. if up:
  5491. gcode += self.doformat(p.lift_code, x=path[1][0], y=path[1][1], z_move=z_move) # Stop cutting
  5492. return gcode
  5493. def point2gcode(self, point):
  5494. gcode = ""
  5495. path = list(point.coords)
  5496. p = self.pp_geometry
  5497. gcode += self.doformat(p.linear_code, x=path[0][0], y=path[0][1]) # Move to first point
  5498. if self.z_feedrate is not None:
  5499. gcode += self.doformat(p.z_feedrate_code)
  5500. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut = self.z_cut)
  5501. gcode += self.doformat(p.feedrate_code)
  5502. else:
  5503. gcode += self.doformat(p.down_code, x=path[0][0], y=path[0][1], z_cut = self.z_cut) # Start cutting
  5504. gcode += self.doformat(p.lift_code, x=path[0][0], y=path[0][1]) # Stop cutting
  5505. return gcode
  5506. def export_svg(self, scale_factor=0.00):
  5507. """
  5508. Exports the CNC Job as a SVG Element
  5509. :scale_factor: float
  5510. :return: SVG Element string
  5511. """
  5512. # scale_factor is a multiplication factor for the SVG stroke-width used within shapely's svg export
  5513. # If not specified then try and use the tool diameter
  5514. # This way what is on screen will match what is outputed for the svg
  5515. # This is quite a useful feature for svg's used with visicut
  5516. if scale_factor <= 0:
  5517. scale_factor = self.options['tooldia'] / 2
  5518. # If still 0 then default to 0.05
  5519. # This value appears to work for zooming, and getting the output svg line width
  5520. # to match that viewed on screen with FlatCam
  5521. if scale_factor == 0:
  5522. scale_factor = 0.01
  5523. # Separate the list of cuts and travels into 2 distinct lists
  5524. # This way we can add different formatting / colors to both
  5525. cuts = []
  5526. travels = []
  5527. for g in self.gcode_parsed:
  5528. if g['kind'][0] == 'C': cuts.append(g)
  5529. if g['kind'][0] == 'T': travels.append(g)
  5530. # Used to determine the overall board size
  5531. self.solid_geometry = cascaded_union([geo['geom'] for geo in self.gcode_parsed])
  5532. # Convert the cuts and travels into single geometry objects we can render as svg xml
  5533. if travels:
  5534. travelsgeom = cascaded_union([geo['geom'] for geo in travels])
  5535. if cuts:
  5536. cutsgeom = cascaded_union([geo['geom'] for geo in cuts])
  5537. # Render the SVG Xml
  5538. # The scale factor affects the size of the lines, and the stroke color adds different formatting for each set
  5539. # It's better to have the travels sitting underneath the cuts for visicut
  5540. svg_elem = ""
  5541. if travels:
  5542. svg_elem = travelsgeom.svg(scale_factor=scale_factor, stroke_color="#F0E24D")
  5543. if cuts:
  5544. svg_elem += cutsgeom.svg(scale_factor=scale_factor, stroke_color="#5E6CFF")
  5545. return svg_elem
  5546. def bounds(self):
  5547. """
  5548. Returns coordinates of rectangular bounds
  5549. of geometry: (xmin, ymin, xmax, ymax).
  5550. """
  5551. # fixed issue of getting bounds only for one level lists of objects
  5552. # now it can get bounds for nested lists of objects
  5553. def bounds_rec(obj):
  5554. if type(obj) is list:
  5555. minx = Inf
  5556. miny = Inf
  5557. maxx = -Inf
  5558. maxy = -Inf
  5559. for k in obj:
  5560. if type(k) is dict:
  5561. for key in k:
  5562. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  5563. minx = min(minx, minx_)
  5564. miny = min(miny, miny_)
  5565. maxx = max(maxx, maxx_)
  5566. maxy = max(maxy, maxy_)
  5567. else:
  5568. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5569. minx = min(minx, minx_)
  5570. miny = min(miny, miny_)
  5571. maxx = max(maxx, maxx_)
  5572. maxy = max(maxy, maxy_)
  5573. return minx, miny, maxx, maxy
  5574. else:
  5575. # it's a Shapely object, return it's bounds
  5576. return obj.bounds
  5577. if self.multitool is False:
  5578. log.debug("CNCJob->bounds()")
  5579. if self.solid_geometry is None:
  5580. log.debug("solid_geometry is None")
  5581. return 0, 0, 0, 0
  5582. bounds_coords = bounds_rec(self.solid_geometry)
  5583. else:
  5584. for k, v in self.cnc_tools.items():
  5585. minx = Inf
  5586. miny = Inf
  5587. maxx = -Inf
  5588. maxy = -Inf
  5589. try:
  5590. for k in v['solid_geometry']:
  5591. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  5592. minx = min(minx, minx_)
  5593. miny = min(miny, miny_)
  5594. maxx = max(maxx, maxx_)
  5595. maxy = max(maxy, maxy_)
  5596. except TypeError:
  5597. minx_, miny_, maxx_, maxy_ = bounds_rec(v['solid_geometry'])
  5598. minx = min(minx, minx_)
  5599. miny = min(miny, miny_)
  5600. maxx = max(maxx, maxx_)
  5601. maxy = max(maxy, maxy_)
  5602. bounds_coords = minx, miny, maxx, maxy
  5603. return bounds_coords
  5604. # TODO This function should be replaced at some point with a "real" function. Until then it's an ugly hack ...
  5605. def scale(self, xfactor, yfactor=None, point=None):
  5606. """
  5607. Scales all the geometry on the XY plane in the object by the
  5608. given factor. Tool sizes, feedrates, or Z-axis dimensions are
  5609. not altered.
  5610. :param factor: Number by which to scale the object.
  5611. :type factor: float
  5612. :param point: the (x,y) coords for the point of origin of scale
  5613. :type tuple of floats
  5614. :return: None
  5615. :rtype: None
  5616. """
  5617. if yfactor is None:
  5618. yfactor = xfactor
  5619. if point is None:
  5620. px = 0
  5621. py = 0
  5622. else:
  5623. px, py = point
  5624. def scale_g(g):
  5625. """
  5626. :param g: 'g' parameter it's a gcode string
  5627. :return: scaled gcode string
  5628. """
  5629. temp_gcode = ''
  5630. header_start = False
  5631. header_stop = False
  5632. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5633. lines = StringIO(g)
  5634. for line in lines:
  5635. # this changes the GCODE header ---- UGLY HACK
  5636. if "TOOL DIAMETER" in line or "Feedrate:" in line:
  5637. header_start = True
  5638. if "G20" in line or "G21" in line:
  5639. header_start = False
  5640. header_stop = True
  5641. if header_start is True:
  5642. header_stop = False
  5643. if "in" in line:
  5644. if units == 'MM':
  5645. line = line.replace("in", "mm")
  5646. if "mm" in line:
  5647. if units == 'IN':
  5648. line = line.replace("mm", "in")
  5649. # find any float number in header (even multiple on the same line) and convert it
  5650. numbers_in_header = re.findall(self.g_nr_re, line)
  5651. if numbers_in_header:
  5652. for nr in numbers_in_header:
  5653. new_nr = float(nr) * xfactor
  5654. # replace the updated string
  5655. line = line.replace(nr, ('%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_nr))
  5656. )
  5657. # this scales all the X and Y and Z and F values and also the Tool Dia in the toolchange message
  5658. if header_stop is True:
  5659. if "G20" in line:
  5660. if units == 'MM':
  5661. line = line.replace("G20", "G21")
  5662. if "G21" in line:
  5663. if units == 'IN':
  5664. line = line.replace("G21", "G20")
  5665. # find the X group
  5666. match_x = self.g_x_re.search(line)
  5667. if match_x:
  5668. if match_x.group(1) is not None:
  5669. new_x = float(match_x.group(1)[1:]) * xfactor
  5670. # replace the updated string
  5671. line = line.replace(
  5672. match_x.group(1),
  5673. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5674. )
  5675. # find the Y group
  5676. match_y = self.g_y_re.search(line)
  5677. if match_y:
  5678. if match_y.group(1) is not None:
  5679. new_y = float(match_y.group(1)[1:]) * yfactor
  5680. line = line.replace(
  5681. match_y.group(1),
  5682. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5683. )
  5684. # find the Z group
  5685. match_z = self.g_z_re.search(line)
  5686. if match_z:
  5687. if match_z.group(1) is not None:
  5688. new_z = float(match_z.group(1)[1:]) * xfactor
  5689. line = line.replace(
  5690. match_z.group(1),
  5691. 'Z%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_z)
  5692. )
  5693. # find the F group
  5694. match_f = self.g_f_re.search(line)
  5695. if match_f:
  5696. if match_f.group(1) is not None:
  5697. new_f = float(match_f.group(1)[1:]) * xfactor
  5698. line = line.replace(
  5699. match_f.group(1),
  5700. 'F%.*f' % (self.app.defaults["cncjob_fr_decimals"], new_f)
  5701. )
  5702. # find the T group (tool dia on toolchange)
  5703. match_t = self.g_t_re.search(line)
  5704. if match_t:
  5705. if match_t.group(1) is not None:
  5706. new_t = float(match_t.group(1)[1:]) * xfactor
  5707. line = line.replace(
  5708. match_t.group(1),
  5709. '= %.*f' % (self.app.defaults["cncjob_coords_decimals"], new_t)
  5710. )
  5711. temp_gcode += line
  5712. lines.close()
  5713. header_stop = False
  5714. return temp_gcode
  5715. if self.multitool is False:
  5716. # offset Gcode
  5717. self.gcode = scale_g(self.gcode)
  5718. # offset geometry
  5719. for g in self.gcode_parsed:
  5720. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5721. self.create_geometry()
  5722. else:
  5723. for k, v in self.cnc_tools.items():
  5724. # scale Gcode
  5725. v['gcode'] = scale_g(v['gcode'])
  5726. # scale gcode_parsed
  5727. for g in v['gcode_parsed']:
  5728. g['geom'] = affinity.scale(g['geom'], xfactor, yfactor, origin=(px, py))
  5729. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5730. self.create_geometry()
  5731. def offset(self, vect):
  5732. """
  5733. Offsets all the geometry on the XY plane in the object by the
  5734. given vector.
  5735. Offsets all the GCODE on the XY plane in the object by the
  5736. given vector.
  5737. g_offsetx_re, g_offsety_re, multitool, cnnc_tools are attributes of FlatCAMCNCJob class in camlib
  5738. :param vect: (x, y) offset vector.
  5739. :type vect: tuple
  5740. :return: None
  5741. """
  5742. dx, dy = vect
  5743. def offset_g(g):
  5744. """
  5745. :param g: 'g' parameter it's a gcode string
  5746. :return: offseted gcode string
  5747. """
  5748. temp_gcode = ''
  5749. lines = StringIO(g)
  5750. for line in lines:
  5751. # find the X group
  5752. match_x = self.g_x_re.search(line)
  5753. if match_x:
  5754. if match_x.group(1) is not None:
  5755. # get the coordinate and add X offset
  5756. new_x = float(match_x.group(1)[1:]) + dx
  5757. # replace the updated string
  5758. line = line.replace(
  5759. match_x.group(1),
  5760. 'X%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_x)
  5761. )
  5762. match_y = self.g_y_re.search(line)
  5763. if match_y:
  5764. if match_y.group(1) is not None:
  5765. new_y = float(match_y.group(1)[1:]) + dy
  5766. line = line.replace(
  5767. match_y.group(1),
  5768. 'Y%.*f' % (self.app.defaults["cncjob_coords_decimals"], new_y)
  5769. )
  5770. temp_gcode += line
  5771. lines.close()
  5772. return temp_gcode
  5773. if self.multitool is False:
  5774. # offset Gcode
  5775. self.gcode = offset_g(self.gcode)
  5776. # offset geometry
  5777. for g in self.gcode_parsed:
  5778. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5779. self.create_geometry()
  5780. else:
  5781. for k, v in self.cnc_tools.items():
  5782. # offset Gcode
  5783. v['gcode'] = offset_g(v['gcode'])
  5784. # offset gcode_parsed
  5785. for g in v['gcode_parsed']:
  5786. g['geom'] = affinity.translate(g['geom'], xoff=dx, yoff=dy)
  5787. v['solid_geometry'] = cascaded_union([geo['geom'] for geo in v['gcode_parsed']])
  5788. def mirror(self, axis, point):
  5789. """
  5790. Mirror the geometrys of an object by an given axis around the coordinates of the 'point'
  5791. :param angle:
  5792. :param point: tupple of coordinates (x,y)
  5793. :return:
  5794. """
  5795. px, py = point
  5796. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  5797. for g in self.gcode_parsed:
  5798. g['geom'] = affinity.scale(g['geom'], xscale, yscale, origin=(px, py))
  5799. self.create_geometry()
  5800. def skew(self, angle_x, angle_y, point):
  5801. """
  5802. Shear/Skew the geometries of an object by angles along x and y dimensions.
  5803. Parameters
  5804. ----------
  5805. angle_x, angle_y : float, float
  5806. The shear angle(s) for the x and y axes respectively. These can be
  5807. specified in either degrees (default) or radians by setting
  5808. use_radians=True.
  5809. point: tupple of coordinates (x,y)
  5810. See shapely manual for more information:
  5811. http://toblerity.org/shapely/manual.html#affine-transformations
  5812. """
  5813. px, py = point
  5814. for g in self.gcode_parsed:
  5815. g['geom'] = affinity.skew(g['geom'], angle_x, angle_y,
  5816. origin=(px, py))
  5817. self.create_geometry()
  5818. def rotate(self, angle, point):
  5819. """
  5820. Rotate the geometrys of an object by an given angle around the coordinates of the 'point'
  5821. :param angle:
  5822. :param point: tupple of coordinates (x,y)
  5823. :return:
  5824. """
  5825. px, py = point
  5826. for g in self.gcode_parsed:
  5827. g['geom'] = affinity.rotate(g['geom'], angle, origin=(px, py))
  5828. self.create_geometry()
  5829. def get_bounds(geometry_list):
  5830. xmin = Inf
  5831. ymin = Inf
  5832. xmax = -Inf
  5833. ymax = -Inf
  5834. for gs in geometry_list:
  5835. try:
  5836. gxmin, gymin, gxmax, gymax = gs.bounds()
  5837. xmin = min([xmin, gxmin])
  5838. ymin = min([ymin, gymin])
  5839. xmax = max([xmax, gxmax])
  5840. ymax = max([ymax, gymax])
  5841. except:
  5842. log.warning("DEVELOPMENT: Tried to get bounds of empty geometry.")
  5843. return [xmin, ymin, xmax, ymax]
  5844. def arc(center, radius, start, stop, direction, steps_per_circ):
  5845. """
  5846. Creates a list of point along the specified arc.
  5847. :param center: Coordinates of the center [x, y]
  5848. :type center: list
  5849. :param radius: Radius of the arc.
  5850. :type radius: float
  5851. :param start: Starting angle in radians
  5852. :type start: float
  5853. :param stop: End angle in radians
  5854. :type stop: float
  5855. :param direction: Orientation of the arc, "CW" or "CCW"
  5856. :type direction: string
  5857. :param steps_per_circ: Number of straight line segments to
  5858. represent a circle.
  5859. :type steps_per_circ: int
  5860. :return: The desired arc, as list of tuples
  5861. :rtype: list
  5862. """
  5863. # TODO: Resolution should be established by maximum error from the exact arc.
  5864. da_sign = {"cw": -1.0, "ccw": 1.0}
  5865. points = []
  5866. if direction == "ccw" and stop <= start:
  5867. stop += 2 * pi
  5868. if direction == "cw" and stop >= start:
  5869. stop -= 2 * pi
  5870. angle = abs(stop - start)
  5871. #angle = stop-start
  5872. steps = max([int(ceil(angle / (2 * pi) * steps_per_circ)), 2])
  5873. delta_angle = da_sign[direction] * angle * 1.0 / steps
  5874. for i in range(steps + 1):
  5875. theta = start + delta_angle * i
  5876. points.append((center[0] + radius * cos(theta), center[1] + radius * sin(theta)))
  5877. return points
  5878. def arc2(p1, p2, center, direction, steps_per_circ):
  5879. r = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  5880. start = arctan2(p1[1] - center[1], p1[0] - center[0])
  5881. stop = arctan2(p2[1] - center[1], p2[0] - center[0])
  5882. return arc(center, r, start, stop, direction, steps_per_circ)
  5883. def arc_angle(start, stop, direction):
  5884. if direction == "ccw" and stop <= start:
  5885. stop += 2 * pi
  5886. if direction == "cw" and stop >= start:
  5887. stop -= 2 * pi
  5888. angle = abs(stop - start)
  5889. return angle
  5890. # def find_polygon(poly, point):
  5891. # """
  5892. # Find an object that object.contains(Point(point)) in
  5893. # poly, which can can be iterable, contain iterable of, or
  5894. # be itself an implementer of .contains().
  5895. #
  5896. # :param poly: See description
  5897. # :return: Polygon containing point or None.
  5898. # """
  5899. #
  5900. # if poly is None:
  5901. # return None
  5902. #
  5903. # try:
  5904. # for sub_poly in poly:
  5905. # p = find_polygon(sub_poly, point)
  5906. # if p is not None:
  5907. # return p
  5908. # except TypeError:
  5909. # try:
  5910. # if poly.contains(Point(point)):
  5911. # return poly
  5912. # except AttributeError:
  5913. # return None
  5914. #
  5915. # return None
  5916. def to_dict(obj):
  5917. """
  5918. Makes the following types into serializable form:
  5919. * ApertureMacro
  5920. * BaseGeometry
  5921. :param obj: Shapely geometry.
  5922. :type obj: BaseGeometry
  5923. :return: Dictionary with serializable form if ``obj`` was
  5924. BaseGeometry or ApertureMacro, otherwise returns ``obj``.
  5925. """
  5926. if isinstance(obj, ApertureMacro):
  5927. return {
  5928. "__class__": "ApertureMacro",
  5929. "__inst__": obj.to_dict()
  5930. }
  5931. if isinstance(obj, BaseGeometry):
  5932. return {
  5933. "__class__": "Shply",
  5934. "__inst__": sdumps(obj)
  5935. }
  5936. return obj
  5937. def dict2obj(d):
  5938. """
  5939. Default deserializer.
  5940. :param d: Serializable dictionary representation of an object
  5941. to be reconstructed.
  5942. :return: Reconstructed object.
  5943. """
  5944. if '__class__' in d and '__inst__' in d:
  5945. if d['__class__'] == "Shply":
  5946. return sloads(d['__inst__'])
  5947. if d['__class__'] == "ApertureMacro":
  5948. am = ApertureMacro()
  5949. am.from_dict(d['__inst__'])
  5950. return am
  5951. return d
  5952. else:
  5953. return d
  5954. # def plotg(geo, solid_poly=False, color="black"):
  5955. # try:
  5956. # _ = iter(geo)
  5957. # except:
  5958. # geo = [geo]
  5959. #
  5960. # for g in geo:
  5961. # if type(g) == Polygon:
  5962. # if solid_poly:
  5963. # patch = PolygonPatch(g,
  5964. # facecolor="#BBF268",
  5965. # edgecolor="#006E20",
  5966. # alpha=0.75,
  5967. # zorder=2)
  5968. # ax = subplot(111)
  5969. # ax.add_patch(patch)
  5970. # else:
  5971. # x, y = g.exterior.coords.xy
  5972. # plot(x, y, color=color)
  5973. # for ints in g.interiors:
  5974. # x, y = ints.coords.xy
  5975. # plot(x, y, color=color)
  5976. # continue
  5977. #
  5978. # if type(g) == LineString or type(g) == LinearRing:
  5979. # x, y = g.coords.xy
  5980. # plot(x, y, color=color)
  5981. # continue
  5982. #
  5983. # if type(g) == Point:
  5984. # x, y = g.coords.xy
  5985. # plot(x, y, 'o')
  5986. # continue
  5987. #
  5988. # try:
  5989. # _ = iter(g)
  5990. # plotg(g, color=color)
  5991. # except:
  5992. # log.error("Cannot plot: " + str(type(g)))
  5993. # continue
  5994. def parse_gerber_number(strnumber, int_digits, frac_digits, zeros):
  5995. """
  5996. Parse a single number of Gerber coordinates.
  5997. :param strnumber: String containing a number in decimal digits
  5998. from a coordinate data block, possibly with a leading sign.
  5999. :type strnumber: str
  6000. :param int_digits: Number of digits used for the integer
  6001. part of the number
  6002. :type frac_digits: int
  6003. :param frac_digits: Number of digits used for the fractional
  6004. part of the number
  6005. :type frac_digits: int
  6006. :param zeros: If 'L', leading zeros are removed and trailing zeros are kept. Same situation for 'D' when
  6007. no zero suppression is done. If 'T', is in reverse.
  6008. :type zeros: str
  6009. :return: The number in floating point.
  6010. :rtype: float
  6011. """
  6012. ret_val = None
  6013. if zeros == 'L' or zeros == 'D':
  6014. ret_val = int(strnumber) * (10 ** (-frac_digits))
  6015. if zeros == 'T':
  6016. int_val = int(strnumber)
  6017. ret_val = (int_val * (10 ** ((int_digits + frac_digits) - len(strnumber)))) * (10 ** (-frac_digits))
  6018. return ret_val
  6019. # def alpha_shape(points, alpha):
  6020. # """
  6021. # Compute the alpha shape (concave hull) of a set of points.
  6022. #
  6023. # @param points: Iterable container of points.
  6024. # @param alpha: alpha value to influence the gooeyness of the border. Smaller
  6025. # numbers don't fall inward as much as larger numbers. Too large,
  6026. # and you lose everything!
  6027. # """
  6028. # if len(points) < 4:
  6029. # # When you have a triangle, there is no sense in computing an alpha
  6030. # # shape.
  6031. # return MultiPoint(list(points)).convex_hull
  6032. #
  6033. # def add_edge(edges, edge_points, coords, i, j):
  6034. # """Add a line between the i-th and j-th points, if not in the list already"""
  6035. # if (i, j) in edges or (j, i) in edges:
  6036. # # already added
  6037. # return
  6038. # edges.add( (i, j) )
  6039. # edge_points.append(coords[ [i, j] ])
  6040. #
  6041. # coords = np.array([point.coords[0] for point in points])
  6042. #
  6043. # tri = Delaunay(coords)
  6044. # edges = set()
  6045. # edge_points = []
  6046. # # loop over triangles:
  6047. # # ia, ib, ic = indices of corner points of the triangle
  6048. # for ia, ib, ic in tri.vertices:
  6049. # pa = coords[ia]
  6050. # pb = coords[ib]
  6051. # pc = coords[ic]
  6052. #
  6053. # # Lengths of sides of triangle
  6054. # a = math.sqrt((pa[0]-pb[0])**2 + (pa[1]-pb[1])**2)
  6055. # b = math.sqrt((pb[0]-pc[0])**2 + (pb[1]-pc[1])**2)
  6056. # c = math.sqrt((pc[0]-pa[0])**2 + (pc[1]-pa[1])**2)
  6057. #
  6058. # # Semiperimeter of triangle
  6059. # s = (a + b + c)/2.0
  6060. #
  6061. # # Area of triangle by Heron's formula
  6062. # area = math.sqrt(s*(s-a)*(s-b)*(s-c))
  6063. # circum_r = a*b*c/(4.0*area)
  6064. #
  6065. # # Here's the radius filter.
  6066. # #print circum_r
  6067. # if circum_r < 1.0/alpha:
  6068. # add_edge(edges, edge_points, coords, ia, ib)
  6069. # add_edge(edges, edge_points, coords, ib, ic)
  6070. # add_edge(edges, edge_points, coords, ic, ia)
  6071. #
  6072. # m = MultiLineString(edge_points)
  6073. # triangles = list(polygonize(m))
  6074. # return cascaded_union(triangles), edge_points
  6075. # def voronoi(P):
  6076. # """
  6077. # Returns a list of all edges of the voronoi diagram for the given input points.
  6078. # """
  6079. # delauny = Delaunay(P)
  6080. # triangles = delauny.points[delauny.vertices]
  6081. #
  6082. # circum_centers = np.array([triangle_csc(tri) for tri in triangles])
  6083. # long_lines_endpoints = []
  6084. #
  6085. # lineIndices = []
  6086. # for i, triangle in enumerate(triangles):
  6087. # circum_center = circum_centers[i]
  6088. # for j, neighbor in enumerate(delauny.neighbors[i]):
  6089. # if neighbor != -1:
  6090. # lineIndices.append((i, neighbor))
  6091. # else:
  6092. # ps = triangle[(j+1)%3] - triangle[(j-1)%3]
  6093. # ps = np.array((ps[1], -ps[0]))
  6094. #
  6095. # middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5
  6096. # di = middle - triangle[j]
  6097. #
  6098. # ps /= np.linalg.norm(ps)
  6099. # di /= np.linalg.norm(di)
  6100. #
  6101. # if np.dot(di, ps) < 0.0:
  6102. # ps *= -1000.0
  6103. # else:
  6104. # ps *= 1000.0
  6105. #
  6106. # long_lines_endpoints.append(circum_center + ps)
  6107. # lineIndices.append((i, len(circum_centers) + len(long_lines_endpoints)-1))
  6108. #
  6109. # vertices = np.vstack((circum_centers, long_lines_endpoints))
  6110. #
  6111. # # filter out any duplicate lines
  6112. # lineIndicesSorted = np.sort(lineIndices) # make (1,2) and (2,1) both (1,2)
  6113. # lineIndicesTupled = [tuple(row) for row in lineIndicesSorted]
  6114. # lineIndicesUnique = np.unique(lineIndicesTupled)
  6115. #
  6116. # return vertices, lineIndicesUnique
  6117. #
  6118. #
  6119. # def triangle_csc(pts):
  6120. # rows, cols = pts.shape
  6121. #
  6122. # A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],
  6123. # [np.ones((1, rows)), np.zeros((1, 1))]])
  6124. #
  6125. # b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))
  6126. # x = np.linalg.solve(A,b)
  6127. # bary_coords = x[:-1]
  6128. # return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)
  6129. #
  6130. #
  6131. # def voronoi_cell_lines(points, vertices, lineIndices):
  6132. # """
  6133. # Returns a mapping from a voronoi cell to its edges.
  6134. #
  6135. # :param points: shape (m,2)
  6136. # :param vertices: shape (n,2)
  6137. # :param lineIndices: shape (o,2)
  6138. # :rtype: dict point index -> list of shape (n,2) with vertex indices
  6139. # """
  6140. # kd = KDTree(points)
  6141. #
  6142. # cells = collections.defaultdict(list)
  6143. # for i1, i2 in lineIndices:
  6144. # v1, v2 = vertices[i1], vertices[i2]
  6145. # mid = (v1+v2)/2
  6146. # _, (p1Idx, p2Idx) = kd.query(mid, 2)
  6147. # cells[p1Idx].append((i1, i2))
  6148. # cells[p2Idx].append((i1, i2))
  6149. #
  6150. # return cells
  6151. #
  6152. #
  6153. # def voronoi_edges2polygons(cells):
  6154. # """
  6155. # Transforms cell edges into polygons.
  6156. #
  6157. # :param cells: as returned from voronoi_cell_lines
  6158. # :rtype: dict point index -> list of vertex indices which form a polygon
  6159. # """
  6160. #
  6161. # # first, close the outer cells
  6162. # for pIdx, lineIndices_ in cells.items():
  6163. # dangling_lines = []
  6164. # for i1, i2 in lineIndices_:
  6165. # p = (i1, i2)
  6166. # 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_)
  6167. # # connections = filter(lambda (i1_, i2_): (i1, i2) != (i1_, i2_) and (i1 == i1_ or i1 == i2_ or i2 == i1_ or i2 == i2_), lineIndices_)
  6168. # assert 1 <= len(connections) <= 2
  6169. # if len(connections) == 1:
  6170. # dangling_lines.append((i1, i2))
  6171. # assert len(dangling_lines) in [0, 2]
  6172. # if len(dangling_lines) == 2:
  6173. # (i11, i12), (i21, i22) = dangling_lines
  6174. # s = (i11, i12)
  6175. # t = (i21, i22)
  6176. #
  6177. # # determine which line ends are unconnected
  6178. # connected = filter(lambda k: k != s and (k[0] == s[0] or k[1] == s[0]), lineIndices_)
  6179. # # connected = filter(lambda (i1,i2): (i1,i2) != (i11,i12) and (i1 == i11 or i2 == i11), lineIndices_)
  6180. # i11Unconnected = len(connected) == 0
  6181. #
  6182. # connected = filter(lambda k: k != t and (k[0] == t[0] or k[1] == t[0]), lineIndices_)
  6183. # # connected = filter(lambda (i1,i2): (i1,i2) != (i21,i22) and (i1 == i21 or i2 == i21), lineIndices_)
  6184. # i21Unconnected = len(connected) == 0
  6185. #
  6186. # startIdx = i11 if i11Unconnected else i12
  6187. # endIdx = i21 if i21Unconnected else i22
  6188. #
  6189. # cells[pIdx].append((startIdx, endIdx))
  6190. #
  6191. # # then, form polygons by storing vertex indices in (counter-)clockwise order
  6192. # polys = dict()
  6193. # for pIdx, lineIndices_ in cells.items():
  6194. # # get a directed graph which contains both directions and arbitrarily follow one of both
  6195. # directedGraph = lineIndices_ + [(i2, i1) for (i1, i2) in lineIndices_]
  6196. # directedGraphMap = collections.defaultdict(list)
  6197. # for (i1, i2) in directedGraph:
  6198. # directedGraphMap[i1].append(i2)
  6199. # orderedEdges = []
  6200. # currentEdge = directedGraph[0]
  6201. # while len(orderedEdges) < len(lineIndices_):
  6202. # i1 = currentEdge[1]
  6203. # i2 = directedGraphMap[i1][0] if directedGraphMap[i1][0] != currentEdge[0] else directedGraphMap[i1][1]
  6204. # nextEdge = (i1, i2)
  6205. # orderedEdges.append(nextEdge)
  6206. # currentEdge = nextEdge
  6207. #
  6208. # polys[pIdx] = [i1 for (i1, i2) in orderedEdges]
  6209. #
  6210. # return polys
  6211. #
  6212. #
  6213. # def voronoi_polygons(points):
  6214. # """
  6215. # Returns the voronoi polygon for each input point.
  6216. #
  6217. # :param points: shape (n,2)
  6218. # :rtype: list of n polygons where each polygon is an array of vertices
  6219. # """
  6220. # vertices, lineIndices = voronoi(points)
  6221. # cells = voronoi_cell_lines(points, vertices, lineIndices)
  6222. # polys = voronoi_edges2polygons(cells)
  6223. # polylist = []
  6224. # for i in range(len(points)):
  6225. # poly = vertices[np.asarray(polys[i])]
  6226. # polylist.append(poly)
  6227. # return polylist
  6228. #
  6229. #
  6230. # class Zprofile:
  6231. # def __init__(self):
  6232. #
  6233. # # data contains lists of [x, y, z]
  6234. # self.data = []
  6235. #
  6236. # # Computed voronoi polygons (shapely)
  6237. # self.polygons = []
  6238. # pass
  6239. #
  6240. # # def plot_polygons(self):
  6241. # # axes = plt.subplot(1, 1, 1)
  6242. # #
  6243. # # plt.axis([-0.05, 1.05, -0.05, 1.05])
  6244. # #
  6245. # # for poly in self.polygons:
  6246. # # p = PolygonPatch(poly, facecolor=np.random.rand(3, 1), alpha=0.3)
  6247. # # axes.add_patch(p)
  6248. #
  6249. # def init_from_csv(self, filename):
  6250. # pass
  6251. #
  6252. # def init_from_string(self, zpstring):
  6253. # pass
  6254. #
  6255. # def init_from_list(self, zplist):
  6256. # self.data = zplist
  6257. #
  6258. # def generate_polygons(self):
  6259. # self.polygons = [Polygon(p) for p in voronoi_polygons(array([[x[0], x[1]] for x in self.data]))]
  6260. #
  6261. # def normalize(self, origin):
  6262. # pass
  6263. #
  6264. # def paste(self, path):
  6265. # """
  6266. # Return a list of dictionaries containing the parts of the original
  6267. # path and their z-axis offset.
  6268. # """
  6269. #
  6270. # # At most one region/polygon will contain the path
  6271. # containing = [i for i in range(len(self.polygons)) if self.polygons[i].contains(path)]
  6272. #
  6273. # if len(containing) > 0:
  6274. # return [{"path": path, "z": self.data[containing[0]][2]}]
  6275. #
  6276. # # All region indexes that intersect with the path
  6277. # crossing = [i for i in range(len(self.polygons)) if self.polygons[i].intersects(path)]
  6278. #
  6279. # return [{"path": path.intersection(self.polygons[i]),
  6280. # "z": self.data[i][2]} for i in crossing]
  6281. def autolist(obj):
  6282. try:
  6283. _ = iter(obj)
  6284. return obj
  6285. except TypeError:
  6286. return [obj]
  6287. def three_point_circle(p1, p2, p3):
  6288. """
  6289. Computes the center and radius of a circle from
  6290. 3 points on its circumference.
  6291. :param p1: Point 1
  6292. :param p2: Point 2
  6293. :param p3: Point 3
  6294. :return: center, radius
  6295. """
  6296. # Midpoints
  6297. a1 = (p1 + p2) / 2.0
  6298. a2 = (p2 + p3) / 2.0
  6299. # Normals
  6300. b1 = dot((p2 - p1), array([[0, -1], [1, 0]], dtype=float32))
  6301. b2 = dot((p3 - p2), array([[0, 1], [-1, 0]], dtype=float32))
  6302. # Params
  6303. try:
  6304. T = solve(transpose(array([-b1, b2])), a1 - a2)
  6305. except Exception as e:
  6306. log.debug("camlib.three_point_circle() --> %s" % str(e))
  6307. return
  6308. # Center
  6309. center = a1 + b1 * T[0]
  6310. # Radius
  6311. radius = np.linalg.norm(center - p1)
  6312. return center, radius, T[0]
  6313. def distance(pt1, pt2):
  6314. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  6315. def distance_euclidian(x1, y1, x2, y2):
  6316. return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  6317. class FlatCAMRTree(object):
  6318. """
  6319. Indexes geometry (Any object with "cooords" property containing
  6320. a list of tuples with x, y values). Objects are indexed by
  6321. all their points by default. To index by arbitrary points,
  6322. override self.points2obj.
  6323. """
  6324. def __init__(self):
  6325. # Python RTree Index
  6326. self.rti = rtindex.Index()
  6327. ## Track object-point relationship
  6328. # Each is list of points in object.
  6329. self.obj2points = []
  6330. # Index is index in rtree, value is index of
  6331. # object in obj2points.
  6332. self.points2obj = []
  6333. self.get_points = lambda go: go.coords
  6334. def grow_obj2points(self, idx):
  6335. """
  6336. Increases the size of self.obj2points to fit
  6337. idx + 1 items.
  6338. :param idx: Index to fit into list.
  6339. :return: None
  6340. """
  6341. if len(self.obj2points) > idx:
  6342. # len == 2, idx == 1, ok.
  6343. return
  6344. else:
  6345. # len == 2, idx == 2, need 1 more.
  6346. # range(2, 3)
  6347. for i in range(len(self.obj2points), idx + 1):
  6348. self.obj2points.append([])
  6349. def insert(self, objid, obj):
  6350. self.grow_obj2points(objid)
  6351. self.obj2points[objid] = []
  6352. for pt in self.get_points(obj):
  6353. self.rti.insert(len(self.points2obj), (pt[0], pt[1], pt[0], pt[1]), obj=objid)
  6354. self.obj2points[objid].append(len(self.points2obj))
  6355. self.points2obj.append(objid)
  6356. def remove_obj(self, objid, obj):
  6357. # Use all ptids to delete from index
  6358. for i, pt in enumerate(self.get_points(obj)):
  6359. self.rti.delete(self.obj2points[objid][i], (pt[0], pt[1], pt[0], pt[1]))
  6360. def nearest(self, pt):
  6361. """
  6362. Will raise StopIteration if no items are found.
  6363. :param pt:
  6364. :return:
  6365. """
  6366. return next(self.rti.nearest(pt, objects=True))
  6367. class FlatCAMRTreeStorage(FlatCAMRTree):
  6368. """
  6369. Just like FlatCAMRTree it indexes geometry, but also serves
  6370. as storage for the geometry.
  6371. """
  6372. def __init__(self):
  6373. # super(FlatCAMRTreeStorage, self).__init__()
  6374. super().__init__()
  6375. self.objects = []
  6376. # Optimization attempt!
  6377. self.indexes = {}
  6378. def insert(self, obj):
  6379. self.objects.append(obj)
  6380. idx = len(self.objects) - 1
  6381. # Note: Shapely objects are not hashable any more, althought
  6382. # there seem to be plans to re-introduce the feature in
  6383. # version 2.0. For now, we will index using the object's id,
  6384. # but it's important to remember that shapely geometry is
  6385. # mutable, ie. it can be modified to a totally different shape
  6386. # and continue to have the same id.
  6387. # self.indexes[obj] = idx
  6388. self.indexes[id(obj)] = idx
  6389. # super(FlatCAMRTreeStorage, self).insert(idx, obj)
  6390. super().insert(idx, obj)
  6391. #@profile
  6392. def remove(self, obj):
  6393. # See note about self.indexes in insert().
  6394. # objidx = self.indexes[obj]
  6395. objidx = self.indexes[id(obj)]
  6396. # Remove from list
  6397. self.objects[objidx] = None
  6398. # Remove from index
  6399. self.remove_obj(objidx, obj)
  6400. def get_objects(self):
  6401. return (o for o in self.objects if o is not None)
  6402. def nearest(self, pt):
  6403. """
  6404. Returns the nearest matching points and the object
  6405. it belongs to.
  6406. :param pt: Query point.
  6407. :return: (match_x, match_y), Object owner of
  6408. matching point.
  6409. :rtype: tuple
  6410. """
  6411. tidx = super(FlatCAMRTreeStorage, self).nearest(pt)
  6412. return (tidx.bbox[0], tidx.bbox[1]), self.objects[tidx.object]
  6413. # class myO:
  6414. # def __init__(self, coords):
  6415. # self.coords = coords
  6416. #
  6417. #
  6418. # def test_rti():
  6419. #
  6420. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6421. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6422. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6423. #
  6424. # os = [o1, o2]
  6425. #
  6426. # idx = FlatCAMRTree()
  6427. #
  6428. # for o in range(len(os)):
  6429. # idx.insert(o, os[o])
  6430. #
  6431. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6432. #
  6433. # idx.remove_obj(0, o1)
  6434. #
  6435. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6436. #
  6437. # idx.remove_obj(1, o2)
  6438. #
  6439. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6440. #
  6441. #
  6442. # def test_rtis():
  6443. #
  6444. # o1 = myO([(0, 0), (0, 1), (1, 1)])
  6445. # o2 = myO([(2, 0), (2, 1), (2, 1)])
  6446. # o3 = myO([(2, 0), (2, 1), (3, 1)])
  6447. #
  6448. # os = [o1, o2]
  6449. #
  6450. # idx = FlatCAMRTreeStorage()
  6451. #
  6452. # for o in range(len(os)):
  6453. # idx.insert(os[o])
  6454. #
  6455. # #os = None
  6456. # #o1 = None
  6457. # #o2 = None
  6458. #
  6459. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6460. #
  6461. # idx.remove(idx.nearest((2,0))[1])
  6462. #
  6463. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]
  6464. #
  6465. # idx.remove(idx.nearest((0,0))[1])
  6466. #
  6467. # print [x.bbox for x in idx.rti.nearest((0, 0), num_results=20, objects=True)]