camlib.py 296 KB

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