camlib.py 344 KB

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