camlib.py 315 KB

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