camlib.py 316 KB

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