def run(self): '''load the data''' filename = self.root.ids['bl'].text() #filename='/home/microelly2/FCB/b202_gmx_tracks/dgm1/dgm1_32356_5638_2_nw.xyz' try: ts = time.time() #\cond self.pts = import_xyz( self.root.ids['pclMode'].isChecked(), filename, self.root.ids['pclLabel'].text(), int(self.root.ids['ku'].text()), int(self.root.ids['kv'].text()), int(self.root.ids['lu'].text()), int(self.root.ids['lv'].text()), ) #\endcond te = time.time() say("load points time " + str(round(te - ts, 2))) say(("points", len(self.pts))) lu, lv = getShape(self.pts) self.root.ids['lu'].setText(str(lu)) self.root.ids['lv'].setText(str(lv)) self.update() self.root.ids['post'].show() self.root.ids['run'].hide() self.root.ids['main'].hide() self.root.ids['img1'].hide() self.root.ids['img2'].hide() except: sayexc()
def run(self): '''load the file and create a nurbs surface''' try: filename = self.root.ids['bl'].text() if filename.startswith('UserAppData'): filename = filename.replace('UserAppData', FreeCAD.ConfigGet("UserAppData")) ts = time.time() bs = import_image( filename, int(self.root.ids['border'].text()), int(self.root.ids['color'].text()), self.root.ids['inverse'].isChecked(), int(self.root.ids['kx'].text()), int(self.root.ids['ky'].text()), int(self.root.ids['kz'].text()), self.root.ids['gengrid'].isChecked(), self.root.ids['genblock'].isChecked(), self.root.ids['genpoles'].isChecked(), self.root.ids['pointsonly'].isChecked(), ) te = time.time() say("load image time " + str(round(te - ts, 2))) except: sayexc()
def create_grid(pu, du, dv, wb, eb, sb, nb, color=(1.0, 0.0, 0.0)): '''create_grid(pu,du,dv, wb, eb, sb, nb, color=(1.0,0.0,0.0)''' ts = time.time() sss = [] # u direction curves for iu in range(sb, dv - nb): pps = [] for iv in range(wb, du - eb): pps.append(pu[iu * du + iv]) tt = Part.BSplineCurve() tt.interpolate(pps) ss = tt.toShape() sss.append(ss) # v direction curves for iv in range(wb, du - eb): pps = [] for iu in range(sb, dv - nb): pps.append(pu[iu * du + iv]) tt = Part.BSplineCurve() tt.interpolate(pps) ss = tt.toShape() sss.append(ss) comp = Part.Compound(sss) Part.show(comp) App.ActiveDocument.ActiveObject.ViewObject.LineColor = color App.ActiveDocument.grids.addObject(App.ActiveDocument.ActiveObject) te = time.time() say(["create grid time ", round(te - ts, 5)]) return App.ActiveDocument.ActiveObject
def create_mgrid(pu, du, dv, wb, eb, sb, nb, color=(1.0, 0.0, 0.0)): '''create_grid(pu,du,dv, wb, eb, sb, nb, color=(1.0,0.0,0.0)''' ts = time.time() sss = [] # mesh generieren #+# #alles 0,0 bis 2000, 2000 # u direction curves for iu in range(sb, dv - nb): pps = [] for iv in range(wb, du - eb): pps.append(pu[iu * du + iv]) ss = Part.makePolygon(pps) sss.append(ss) # v direction curves for iv in range(wb, du - eb): pps = [] for iu in range(sb, dv - nb): pps.append(pu[iu * du + iv]) ss = Part.makePolygon(pps) sss.append(ss) comp = Part.Compound(sss) Part.show(comp) App.ActiveDocument.ActiveObject.ViewObject.LineColor = color App.ActiveDocument.grids.addObject(App.ActiveDocument.ActiveObject) te = time.time() say(["create grid time ", round(te - ts, 5)]) return App.ActiveDocument.ActiveObject
def muv(app, u=3, v=5, d=10, la=100, lb=100): '''generate a quadratic mesh on startposition u,v wit size d)''' st = time.time() tt = Part.BSplineSurface() wb, eb, sb, nb = 0, 0, 0, 0 if u >= 2: wb = 2 if u < la - 2 - d: eb = 2 if v >= 2: sb = 2 if v < la - 2 - d: nb = 2 uu = [] du = d + wb + eb + 1 dv = d + nb + sb + 1 u = u - wb v = v - sb pu = [] say(["(wb,eb,sb,nb,du,dv)", (wb, eb, sb, nb, du, dv)]) try: pts = app.pts except: pts = app for k in range(dv): pu += pts[u + v * la + la * k:u + v * la + du + la * k] uu.append(pts[u + v * la + la * k:u + v * la + du + la * k]) color = (1 - 0.5 * random.random(), 1 - 0.5 * random.random(), 1 - 0.5 * random.random()) App.ActiveDocument.ActiveObject.ViewObject.hide() App.ActiveDocument.ActiveObject.ViewObject.hide() #create bspline grid create_mgrid(pu, du, dv, wb, eb, sb, nb, color) Gui.updateGui()
def showMap(self): b=self.root.ids['b'].text() l=self.root.ids['l'].text() s=self.root.ids['s'].value() say([l,b,s]) import WebGui WebGui.openBrowser( "http://www.openstreetmap.org/#map=9/"+str(b)+'/'+str(l))
def showFrame(pts, u=0, v=0, d=10, lu=None, lv=None): '''showFrame(pts,u=0,v=0,d=10,lu=None,lv=None) creates a rectangle frame of size u * v on a rectangle grid point cloud with shape lu * lv if lu or lv is not set, the shape of the point clloud is calculated ''' say(("showframe u v to u+d v+d in lu,lv", u, v, d, lu, lv)) if lu == None or lv == None: lu, lv = getShape(pts) say((lu, lv, u, v, d)) assert (u + d < lu) assert (v + d < lv) try: ff = FreeCAD.ActiveDocument.frame except: ff = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "frame") ViewProvider(ff.ViewObject) iix = [ u + v * lu, u + v * lu + d, u + v * lu + d * lu + d, u + v * lu + d * lu ] a, b, c, d = pts[iix[0]], pts[iix[1]], pts[iix[2]], pts[iix[3]], sha = Part.makePolygon([a, b, c, d, a]) ff.Shape = sha ff.ViewObject.show()
def runValues(self): b=self.root.ids['b'].text() l=self.root.ids['l'].text() s=self.root.ids['s'].value() say([l,b,s]) import WebGui # WebGui.openBrowser( "http://www.openstreetmap.org/#map=19/"+str(b)+'/'+str(l)) import GeoDataWB.import_osm geodat.import_osm.import_osm(float(b),float(l),float(s)/10,self.root.ids['progb'],self.root.ids['status'])
def runbl(self): bl = self.root.ids['bl'].text() spli = bl.split(',') b = float(spli[0]) l = float(spli[1]) s = 15 say([l, b, s]) import_heights(float(b), float(l), float(s))
def createNurbs(self): '''create nurbs surface for selected frame''' u = self.root.ids['ud'].value() v = self.root.ids['vd'].value() d = self.root.ids['dd'].value() # lu,lv = getShape(self.pts) lu = int(self.root.ids['lu'].text()) lv = float(self.root.ids['lv'].text()) say(("create nurbs for subset", u, v, d, lu, lv)) suv(self, u, v, d, lu, lv)
def run(mx,my,dx,dy): ys=my-dy yn=my+dy xw=mx-dx xe=mx+dx dats=[] say(xw,ys,xe,yn) for ix in range(int(math.floor(xw)),int(math.floor(xe))+1): for iy in range(int(math.floor(ys)),int(math.floor(yn))+1): dat="Lat"+str(iy)+"Lon"+str(ix)+"Lat"+str(iy+1)+"Lon"+str(ix+1) say(dat) dats.append(dat) directory=FreeCAD.ConfigGet("UserAppData") + "geodat_SRTM/" if not os.path.isdir(directory): os.makedirs(directory) for dat in dats: getdata(directory,dat) fn=directory+"/"+dat+".osm" pts=runfile(fn,xw,xe,ys,yn,mx,my) # Get or create "Point_Groups". try: PointGroups = FreeCAD.ActiveDocument.Point_Groups except: PointGroups = FreeCAD.ActiveDocument.addObject("App::DocumentObjectGroup", 'Point_Groups') PointGroups.Label = "Point Groups" # Get or create "Points". try: FreeCAD.ActiveDocument.Points except: Points = FreeCAD.ActiveDocument.addObject('Points::Feature', "Points") PointGroups.addObject(Points) PointGroup = FreeCAD.ActiveDocument.addObject('Points::Feature', "Point_Group") PointGroup.Label = dat FreeCAD.ActiveDocument.Point_Groups.addObject(PointGroup) PointObject = PointGroup.Points.copy() PointObject.addPoints(pts) PointGroup.Points = PointObject FreeCAD.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") return pts
def getheight(b, l): source = "https://api.open-elevation.com/api/v1/lookup?locations=" + str( b) + ',' + str(l) say(source) print(source) import json from urllib import request response = request.urlopen(source) s = json.loads(response.read()) res = s['results'] for r in res: return round(r['elevation'] * 1000, 2)
def create_pcl(pu, color=(1.0, 0.0, 0.0)): '''create_pcl(pu,color=(1.0,0.0,0.0))''' say(len(pu)) p = Points.Points(pu) Points.show(p) App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = color App.ActiveDocument.ActiveObject.ViewObject.PointSize = 3 try: App.ActiveDocument.points except: points = App.ActiveDocument.addObject("App::DocumentObjectGroup", "points") App.ActiveDocument.points.addObject(App.ActiveDocument.ActiveObject) Gui.updateGui()
def import_heights(b, le, size): size = int(size) size = 30 lines = [] for ld in range(-size, size): say("run", ld) res = run(b, le, b, le + ld * 0.001, size) lines.append(res) ll = FreeCAD.activeDocument().addObject('Part::Loft', 'Loft') ll.Sections = lines for li in lines: li.ViewObject.Visibility = False inventortools.setcolorlights(ll) FreeCAD.activeDocument().recompute()
def getdata(directory,dat): zipfilename=directory + "/{}.osm.zip".format(dat) source="http://geoweb.hft-stuttgart.de/SRTM/srtm_as_osm/{}.osm.zip".format(dat) fn=directory+"/"+dat+".osm" if not os.path.exists(fn): if not os.path.exists(zipfilename): say("get "+ source) tg=urllib.request.urlretrieve(source,zipfilename) targetfile=tg[0] say("targetfile:"+targetfile) fh = open(targetfile, 'rb') else: fh = open(zipfilename, 'rb') zfile = zipfile.ZipFile(fh) zfile.extractall(directory) fh.close()
def getShape(pts): '''given a point cloud of a rectangle area get the shape of a appropriate array''' dists = {} ls = [] for i, p in enumerate(pts): if i > 0: pa = pts[i - 1] p1 = FreeCAD.Vector(p.x, p.y, 0) p2 = FreeCAD.Vector(pa.x, pa.y, 0) dist = (p1 - p2).Length dist = round(dist) ls.append(dist) try: dists[dist] += 1 except: dists[dist] = 1 say(dists.keys()) mm = np.mean(list(dists.keys())) tts = [] ia = -1 for i, d in enumerate(ls): if d > mm: tts.append(i - ia) ia = i say(tts) try: dx = int(np.mean(tts)) dy = len(pts) / dx say(("getshape shape: ", dx, dy)) return dx, dy except: return (len(pts), 1)
def run(b0=50.35, l0=11.17, b=50.35, le=11.17, size=40): tm.lat = b0 tm.lon = l0 baseheight = getheight(tm.lat, tm.lon) center = tm.fromGeographic(tm.lat, tm.lon) say("Base height ", baseheight) say("center point", center) for i in range(-size, size): source = "https://api.open-elevation.com/api/v1/lookup?locations=" bb = b + i * 0.001 ss = str(bb) + ',' + str(le) source += ss import json from urllib import request response = request.urlopen(source) s = json.loads(response.read()) res = s['results'] points = [] for r in res: c = tm.fromGeographic(r['latitude'], r['longitude']) v = FreeCAD.Vector(round((c[0] - center[0]), 2), round((c[1] - center[1]), 2), round(r['elevation'] * 1000, 2) - baseheight) points.append(v) Draft.makeWire(points, closed=False, face=False, support=None) FreeCAD.activeDocument().recompute() FreeCADGui.updateGui() return FreeCAD.activeDocument().ActiveObject
def update(self): '''update dialog values''' # lu,lv = getShape(self.pts) say("update") lu = int(self.root.ids['lu'].text()) lv = float(self.root.ids['lv'].text()) say("dd,ud,vd", self.root.ids['dd'].value(), self.root.ids['ud'].value(), self.root.ids['vd'].value()) dmax = min(lu - self.root.ids['ud'].value(), lv - self.root.ids['vd'].value(), 101) - 1 self.root.ids['dd'].setMaximum(dmax) if self.root.ids['dd'].value() > dmax: self.root.ids['dd'].setValue(dmax) say("dd,ud,vd", self.root.ids['dd'].value(), self.root.ids['ud'].value(), self.root.ids['vd'].value()) self.root.ids['vd'].setMaximum(lv - self.root.ids['dd'].value() - 1) self.root.ids['ud'].setMaximum(lu - self.root.ids['dd'].value() - 1)
def suv2(label, pts, u=3, v=5, d=10, la=100, lb=100): try: App.ActiveDocument.nurbs except: nurbs = App.ActiveDocument.addObject("App::DocumentObjectGroup", "nurbs") try: App.ActiveDocument.grids except: grids = App.ActiveDocument.addObject("App::DocumentObjectGroup", "grids") try: App.ActiveDocument.points except: points = nurbs = App.ActiveDocument.addObject( "App::DocumentObjectGroup", "points") st = time.time() tt = Part.BSplineSurface() wb, eb, sb, nb = 0, 0, 0, 0 if u >= 2: wb = 2 if u < la - 2 - d: eb = 2 if v >= 2: sb = 2 if v < la - 2 - d: nb = 2 uu = [] du = d + wb + eb dv = d + nb + sb u = u - wb v = v - sb pu = [] say(["(wb,eb,sb,nb,du,dv)", (wb, eb, sb, nb, du, dv)]) for k in range(dv): pu.append(pts[u + v * la + la * k:u + v * la + du + la * k]) uu.append(pts[u + v * la + la * k:u + v * la + du + la * k]) color = (1 - 0.5 * random.random(), 1 - 0.5 * random.random(), 1 - 0.5 * random.random()) try: App.ActiveDocument.ActiveObject.ViewObject.hide() except: pass # create point cloud create_pcl(pu, color) Gui.updateGui() try: App.ActiveDocument.ActiveObject.ViewObject.hide() except: pass #create bspline grid create_grid(pu, du, dv, wb, eb, sb, nb, color) Gui.updateGui() tt.interpolate(uu) uk = tt.getUKnots() vk = tt.getVKnots() tt.segment(uk[sb], uk[-1 - nb], vk[wb], vk[-1 - eb]) sha = tt.toShape() se = time.time() say(["running time for one shape ", round(se - st, 5)]) # alternative # Part.show(sha) App.ActiveDocument.ActiveObject.ViewObject.hide() a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "QuadNurbs") a.Label = label ViewProvider(a.ViewObject) a.Shape = sha se = time.time() say(["running time for show the shape ", round(se - st, 5)]) App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = color App.ActiveDocument.nurbs.addObject(App.ActiveDocument.ActiveObject) # return tt return a
def suv(app, u=3, v=5, d=10, la=100, lb=100): '''generate a quadratic bspline surface on startposition u,v wit size d)''' st = time.time() tt = Part.BSplineSurface() wb, eb, sb, nb = 0, 0, 0, 0 if u >= 2: wb = 2 if u < la - 2 - d: eb = 2 if v >= 2: sb = 2 if v < la - 2 - d: nb = 2 uu = [] du = d + wb + eb + 1 dv = d + nb + sb + 1 u = u - wb v = v - sb pu = [] say(["(wb,eb,sb,nb,du,dv)", (wb, eb, sb, nb, du, dv)]) say('u,v', u, v) try: pts = app.pts except: pts = app for k in range(dv): pu += pts[u + v * la + la * k:u + v * la + du + la * k] uu.append(pts[u + v * la + la * k:u + v * la + du + la * k]) say(k, u + v * la + la * k, u + v * la + du + la * k) say("uu") say(uu) color = (1 - 0.5 * random.random(), 1 - 0.5 * random.random(), 1 - 0.5 * random.random()) App.ActiveDocument.ActiveObject.ViewObject.hide() # create point cloud create_pcl(pu, color) Gui.updateGui() App.ActiveDocument.ActiveObject.ViewObject.hide() #create bspline grid create_grid(pu, du, dv, wb, eb, sb, nb, color) Gui.updateGui() tt.interpolate(uu) uk = tt.getUKnots() vk = tt.getVKnots() tt.segment(uk[sb], uk[-1 - nb], vk[wb], vk[-1 - eb]) sha = tt.toShape() se = time.time() say(["running time for one shape ", round(se - st, 5)]) App.ActiveDocument.ActiveObject.ViewObject.hide() a = FreeCAD.ActiveDocument.addObject("Part::FeaturePython", "mynurbs") ViewProvider(a.ViewObject) a.Shape = sha se = time.time() say(["running time for show the shape ", round(se - st, 5)]) App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = color App.ActiveDocument.nurbs.addObject(App.ActiveDocument.ActiveObject) Gui.ActiveDocument.update() # return the BSpline geometry return tt
def importHeights(): say("runit") mydialog() say("runit-done")
def showHelpBoxY(self): say("showHelpBox called")
def import_osm2(b, l, bk, progressbar, status, elevation): if progressbar: progressbar.setValue(0) if status: status.setText("get data from openstreetmap.org ...") FreeCADGui.updateGui() content = '' bk = 0.5 * bk dn = FreeCAD.ConfigGet("UserAppData") + "geodat3/" fn = dn + str(b) + '-' + str(l) + '-' + str(bk) import os if not os.path.isdir(dn): os.makedirs(dn) try: say("I try to read data from cache file ... ") say(fn) f = open(fn, "r") content = f.read() except: sayW("no cache file, so I connect to openstreetmap.org...") lk = bk b1 = b - bk / 1113 * 10 l1 = l - lk / 713 * 10 b2 = b + bk / 1113 * 10 l2 = l + lk / 713 * 10 source = 'http://api.openstreetmap.org/api/0.6/map?bbox=' + str( l1) + ',' + str(b1) + ',' + str(l2) + ',' + str(b2) say(source) import requests response = requests.get(source) data = response.text lines = response.text.split('\n') FreeCAD.t = response f = open(fn, "w") if response.status_code == 200: with open(fn, 'wb') as f: for chunk in response.iter_content(1024): f.write(chunk) f.close() if elevation: baseheight = getHeight(b, l) else: baseheight = 0 if debug: say("-------Data---------") say(content) if status: status.setText("parse data ...") FreeCADGui.updateGui() say("------------------------------") say(fn) tree = my_xmlparser.getData(fn) if debug: say(json.dumps(sd, indent=4)) if status: status.setText("transform data ...") FreeCADGui.updateGui() relations = tree.getiterator('relation') nodes = tree.getiterator('node') ways = tree.getiterator('way') bounds = tree.getiterator('bounds')[0] # center of the scene minlat = float(bounds.params['minlat']) minlon = float(bounds.params['minlon']) maxlat = float(bounds.params['maxlat']) maxlon = float(bounds.params['maxlon']) tm = TransverseMercator() tm.lat = 0.5 * (minlat + maxlat) tm.lon = 0.5 * (minlon + maxlon) center = tm.fromGeographic(tm.lat, tm.lon) corner = tm.fromGeographic(minlat, minlon) size = [center[0] - corner[0], center[1] - corner[1]] # map all points to xy-plane points = {} nodesbyid = {} for n in nodes: nodesbyid[n.params['id']] = n ll = tm.fromGeographic(float(n.params['lat']), float(n.params['lon'])) points[str(n.params['id'])] = FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0.0) if status: status.setText("create visualizations ...") FreeCADGui.updateGui() App.newDocument("OSM Map") say("Datei erzeugt") area = App.ActiveDocument.addObject("Part::Plane", "area") obj = FreeCAD.ActiveDocument.ActiveObject say("grundflaeche erzeugt") try: viewprovider = obj.ViewObject root = viewprovider.RootNode myLight = coin.SoDirectionalLight() myLight.color.setValue(coin.SbColor(0, 1, 0)) root.insertChild(myLight, 0) say("beleuchtung auf grundobjekt eingeschaltet") except: sayexc("Beleuchtung 272") cam = '''#Inventor V2.1 ascii OrthographicCamera { viewportMapping ADJUST_CAMERA orientation 0 0 -1.0001 0.001 nearDistance 0 farDistance 10000000000 aspectRatio 100 focalDistance 1 ''' x = 0 y = 0 height = 200 * bk * 10000 / 0.6 cam += '\nposition ' + str(x) + ' ' + str(y) + ' 999\n ' cam += '\nheight ' + str(height) + '\n}\n\n' FreeCADGui.activeDocument().activeView().setCamera(cam) FreeCADGui.activeDocument().activeView().viewAxonometric() say("Kamera gesetzt") area.Length = size[0] * 2 area.Width = size[1] * 2 area.Placement = FreeCAD.Placement( FreeCAD.Vector(-size[0], -size[1], 0.00), FreeCAD.Rotation(0.00, 0.00, 0.00, 1.00)) say("Area skaliert") wn = -1 coways = len(ways) starttime = time.time() refresh = 1000 for w in ways: wid = w.params['id'] building = False landuse = False highway = False wn += 1 nowtime = time.time() if wn != 0 and (nowtime - starttime) / wn > 0.5: say(("way ---- # " + str(wn) + "/" + str(coways) + " time per house: " + str(round( (nowtime - starttime) / wn, 2)))) if progressbar: progressbar.setValue(int(0 + 100.0 * wn / coways)) st = "" st2 = "" nr = "" h = 0 ci = "" for t in w.getiterator('tag'): try: if str(t.params['k']) == 'building': building = True if st == '': st = 'building' if str(t.params['k']) == 'landuse': landuse = True st = t.params['k'] nr = t.params['v'] if str(t.params['k']) == 'highway': highway = True st = t.params['k'] if str(t.params['k']) == 'addr:city': ci = t.params['v'] if str(t.params['k']) == 'name': nr = t.params['v'] if str(t.params['k']) == 'ref': nr = t.params['v'] + " /" if str(t.params['k']) == 'addr:street': st2 = " " + t.params['v'] if str(t.params['k']) == 'addr:housenumber': nr = str(t.params['v']) if str(t.params['k']) == 'building:levels': if h == 0: h = int(str(t.params['v'])) * 1000 * 3 if str(t.params['k']) == 'building:height': h = int(str(t.params['v'])) * 1000 except: sayErr( "unexpected error ######################################################" ) name = str(st) + st2 + " " + str(nr) if name == ' ': name = 'landuse xyz' if debug: say(("name ", name)) # Generate pointlist of the way polis = [] height = None llpoints = [] for n in w.getiterator('nd'): m = nodesbyid[n.params['ref']] llpoints.append( [n.params['ref'], m.params['lat'], m.params['lon']]) if elevation: say("get heights for " + str(len(llpoints))) heights = getHeights(llpoints) for n in w.getiterator('nd'): p = points[str(n.params['ref'])] if building and elevation: if not height: try: height = heights[m.params['lat'] + ' ' + m.params['lon']] * 1000 - baseheight except: sayErr("---no height available for " + m.params['lat'] + ' ' + m.params['lon']) height = 0 p.z = height polis.append(p) # Create 2D map pp = Part.makePolygon(polis) Part.show(pp) z = App.ActiveDocument.ActiveObject z.Label = "w_" + wid if name == ' ': g = App.ActiveDocument.addObject("Part::Extrusion", name) g.Base = z g.ViewObject.ShapeColor = (1.00, 1.00, 0.00) g.Dir = (0, 0, 10) g.Solid = True g.Label = 'way ex ' if building: g = App.ActiveDocument.addObject("Part::Extrusion", name) g.Base = z g.ViewObject.ShapeColor = (1.00, 1.00, 1.00) if h == 0: h = 10000 g.Dir = (0, 0, h) g.Solid = True g.Label = name obj = FreeCAD.ActiveDocument.ActiveObject inventortools.setcolors2(obj) if landuse: g = App.ActiveDocument.addObject("Part::Extrusion", name) g.Base = z if nr == 'residential': g.ViewObject.ShapeColor = (1.00, 0.60, 0.60) elif nr == 'meadow': g.ViewObject.ShapeColor = (0.00, 1.00, 0.00) elif nr == 'farmland': g.ViewObject.ShapeColor = (0.80, 0.80, 0.00) elif nr == 'forest': g.ViewObject.ShapeColor = (1.0, 0.40, 0.40) g.Dir = (0, 0, 0.1) g.Label = name g.Solid = True if highway: g = App.ActiveDocument.addObject("Part::Extrusion", "highway") g.Base = z g.ViewObject.LineColor = (0.00, 0.00, 1.00) g.ViewObject.LineWidth = 10 g.Dir = (0, 0, 0.2) g.Label = name refresh += 1 if os.path.exists("/tmp/stop"): sayErr("notbremse gezogen") FreeCAD.w = w raise Exception("Notbremse Manager main loop") if refresh > 3: FreeCADGui.updateGui() refresh = 0 FreeCADGui.updateGui() FreeCAD.activeDocument().recompute() if status: status.setText("import finished.") if progressbar: progressbar.setValue(100) organize() endtime = time.time() say(("running time ", int(endtime - starttime), " count ways ", coways)) return True
def import_latlon(filename,orig,hi): global sd # content=trackstring # fn='/home/microelly2/FCB/b202_gmx_tracks/im_haus.gpx' # filename='/home/microelly2/FCB/b202_gmx_tracks/neufang.gpx' f=open(filename,"r") c1=f.read() import re #content = re.sub('^\<\?[^\>]+\?\>', '', c1) tm=TransverseMercator() # outdoor inn ... tm.lat,tm.lon = 50.3736049,11.191643 if orig != 'auto': yy=orig.split(' ') say(yy) origin=(float(yy[0]),float(yy[1])) tm.lat=origin[0] tm.lon=origin[1] center=tm.fromGeographic(tm.lat,tm.lon) FreeCAD.c=c1 vals=np.array([float(c) for c in c1.split()]) #vals=vals.reshape(len(vals)/3,3) ''' points=[] points2=[] points0=[] px=[] py=[] pz=[] pt=[] startx=None starty=None starth=None FreeCAD.sd=sd seg=sd['gpx']['trk']['trkseg'] try: seg['trkpt'] ss=seg seg=[ss] except: pass ''' lats=[] lons=[] points=[] for v in vals: lats.append(float(v[0])) lons.append(float(v[1])) ll=tm.fromGeographic(float(v[0]),float(v[1])) points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(v[2])))) print (min(lats),max(lats)) print (min(lons),max(lons)) print ((max(lats)+min(lats))/2,(max(lons)+min(lons))/2) print ((max(lats)-min(lats))/2,(max(lons)-min(lons))/2) import Draft Draft.makeWire(points) return if orig == 'auto': tm.lat, tm.lon = (max(lats)+min(lats))/2,(max(lons)+min(lons))/2 print ("origin:") print(tm.lat,tm.lon) print ("----------") for s in seg: trkpts=s['trkpt'] n=trkpts[0] center=tm.fromGeographic(tm.lat,tm.lon) # print(trkpts) # for p in trkpts: # print(p) # map all points to xy-plane for n in trkpts: # print(n['@lat'],n['@lon']) lats.append(float(n['@lat'])) lons.append(float(n['@lon'])) ll=tm.fromGeographic(float(n['@lat']),float(n['@lon'])) h=n['ele'] # print(h) tim=n['time'] t2=re.sub('^.*T', '', tim) t3=re.sub('Z', '', t2) t4=t3.split(':') timx=int(t4[0])*3600+int(t4[1])*60+int(t4[2]) pt.append(timx) if starth == None: starth=float(h) starth=0 points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth))) points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0)) points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth))) points2.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth)+20000)) points0.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0)) px.append(ll[0]-center[0]) py.append(ll[1]-center[1]) pz.append(1000*(float(h)-starth)) # print(ll) if 1: import Draft if 0: #close path points.append(points[0]) Draft.makeWire(points0) Draft.makeWire(points) po=App.ActiveDocument.ActiveObject po.ViewObject.LineColor=(1.0,.0,0.0) po.MakeFace = False po.Placement.Base.z= float(hi) *1000 po.Label="My Track" Draft.makeWire(points2) po2=App.ActiveDocument.ActiveObject po2.ViewObject.LineColor=(.0,.0,1.0) po2.ViewObject.PointSize=5 po2.ViewObject.PointColor=(.0,1.0,1.0) po2.Placement.Base.z= float(hi)*1000 po2.Label="Track + 20m" App.activeDocument().recompute() Gui.SendMsgToActiveView("ViewFit") # break #------------------------------------------------ # data for postprocessing try: import numpyNode import mathplotlibNode t=mathplotlibNode.createMPL() t.Label="My Track raw Data" # hier werte bereitstellen t.countSources=4 t.source1Values=px t.source2Values=py t.source3Values=pz t.source4Values=pt t.source1Data="px" t.source2Data="py" t.source3Data="pz" t.source4Data="pt" t.useOut1=True t.useOut2=True t.useOut3=True t.useOut4=True # werte umrechnen t2=numpyNode.createNP() t2.Label="My Track data processed" t2.sourceObject=t t2.expression1="in1/np.max(np.abs(in1))" t2.label1 = "x relative" t2.expression2="in2/np.max(np.abs(in2))" t2.label2 = "y relative" t2.expression3="in3/np.max(np.abs(in3))" t2.label3 = "z relative" t2.expression4="-1+2*(in4-np.min(in4))/(np.max(in4)-np.min(in4))" t2.label4 = "time relative" # werte grafisch darstellen t3=mathplotlibNode.createMPL() t3.Label="My Track Data visualization" t3.record=False t3.useNumpy=True t3.sourceNumpy=t2 t3.useOut1=True t3.useOut2=True t3.useOut3=True t3.useOut4=True t4=numpyNode.createNP() t4.Label="My Track Data xy" t4.sourceObject=t t4.expression2="in2" t4.label2 = "path xy" t4.expressionTime="in1" t5=mathplotlibNode.createMPL() t5.Label="My Track Data xy Map" t5.record=False t5.useNumpy=True t5.sourceNumpy=t4 t5.useOut2=True FreeCAD.ActiveDocument.recompute() except: sayexc() print("!",orig,"!") return (str(tm.lat)+','+str(tm.lon)) return px,py
def import_image(filename=None, n=10, c=2, inverse=False, kx=10, ky=10, kz=60, gengrid=True, genblock=False, genpoles=False, pointsonly=False): '''import_image(filename=None,n=10,c=2,inverse=False,kx=10,ky=10,kz=60,gengrid=True,genblock=False,genpoles=False,pointsonly=False) ''' display_mathplot = False dataAsPoles = False if filename == None: filename = '/home/microelly2/Schreibtisch/test_nurbs3.png' img = mpimg.imread(filename) ojn = os.path.basename(filename) # grey scaled image and color channel select if len(img.shape) == 2: lum_img = img else: lum_img = img[:, :, c] lum_img = 0.33 * img[:, :, 0] + 0.33 * img[:, :, 1] + 0.34 * img[:, :, 2] (lu, lv) = lum_img.shape if display_mathplot: plt.imshow(lum_img) plt.show() #create a n points border uu2 = np.zeros((lu + 2 * n) * (lv + 2 * n)) uu2 = uu2.reshape(lu + 2 * n, lv + 2 * n) uu2[n:lu + n, n:lv + n] = lum_img lum_img = uu2 (lu, lv) = lum_img.shape bz = kz + 100 if inverse: kz = -kz pts = [] uu = [] for u in range(lu): ul = [] for v in range(lv): # p=FreeCAD.Vector(ky*v,-kx*u,bz-kz*lum_img[u,v]) r = 0.001 p = FreeCAD.Vector(ky * v + r * random.random(), -kx * u + r * random.random(), bz - kz * lum_img[u, v] + r * random.random()) ul.append(p) pts.append(p) uu.append(ul) # show the points p = Points.Points(pts) Points.show(p) App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (1.0, .0, 1.0) App.ActiveDocument.ActiveObject.Label = "Points " + str(lv) + " " + str( lu) + " _" say((("u, v, points"), u, v, len(pts))) Gui.updateGui() if pointsonly: return tt = Part.BSplineSurface() if dataAsPoles: pols = uu else: tt.interpolate(uu) # flatten the border pols = tt.getPoles() pols2 = np.array(pols) lup, lvp, la = pols2.shape zz = bz bord = n - 2 for u in range(lup): for v in range(bord): op = pols[u][v] nup = FreeCAD.Vector(op.x, op.y, zz) pols[u][v] = nup op = pols[u][-1 - v] nup = FreeCAD.Vector(op.x, op.y, zz) pols[u][-1 - v] = nup for u in range(bord): for v in range(lvp): op = pols[u][v] nup = FreeCAD.Vector(op.x, op.y, zz) pols[u][v] = nup op = pols[-1 - u][v] nup = FreeCAD.Vector(op.x, op.y, zz) pols[-1 - u][v] = nup bs = Part.BSplineSurface() knot_v2 = tt.getVKnots() knot_u2 = tt.getUKnots() mult_u = tt.getUMultiplicities() mult_v = tt.getVMultiplicities() ws = tt.getWeights() bs.buildFromPolesMultsKnots(pols, mult_u, mult_v, knot_u2, knot_v2, False, False, 3, 3, ws) if 1: sha = bs.toShape() # show the poles if genpoles: pols = bs.getPoles() ps = [] for l in pols: for po in l: ps.append(po) p = Points.Points(ps) Points.show(p) App.ActiveDocument.ActiveObject.ViewObject.ShapeColor = (1.0, 1.0, .0) App.ActiveDocument.ActiveObject.Label = 'Poles ' + str(lv) + " " + str( lu) + " _" Gui.updateGui() # the nurbs grid if gengrid: jj = [] rr = lv for i in range(rr + 1): v = bs.vIso((0.0 + i) / rr).toShape() jj.append(v.Edge1) rr = lu for i in range(rr + 1): v = bs.uIso((0.0 + i) / rr).toShape() jj.append(v.Edge1) com = Part.makeCompound(jj) ttt = App.ActiveDocument.addObject('Part::Feature', 'Nurbsgrid ' + str(n) + ' ' + ojn) ttt.ViewObject.DisplayMode = "Wireframe" # ttt.ViewObject.hide() ttt.Shape = com ttt.Placement.Base.z = 10 Gui.updateGui() return #create the solid a = FreeCAD.Vector(0, 0, -bz) b = FreeCAD.Vector(0, -kx * (lu - 1), -bz) c = FreeCAD.Vector(ky * (lv - 1), -kx * (lu - 1), -bz) d = FreeCAD.Vector(ky * (lv - 1), 0, -bz) ad = FreeCAD.Vector(0, 0, bz) bd = FreeCAD.Vector(0, -kx * (lu - 1), bz) cd = FreeCAD.Vector(ky * (lv - 1), -kx * (lu - 1), bz) dd = FreeCAD.Vector(ky * (lv - 1), 0, bz) # for nonlinear borders - experimental if 0: u0e = bs.uIso(0).toShape() p = Part.makePolygon([ad, a, d, dd], True) ll = p.Edges + [u0e.Edge1] f4 = Part.makeFilledFace(Part.__sortEdges__(ll)) Part.show(f4) v0e = bs.vIso(0).toShape() p = Part.makePolygon([bd, b, a, ad], True) ll = p.Edges + [v0e.Edge1] f1 = Part.makeFilledFace(Part.__sortEdges__(ll)) #Part.show(v0e) #Part.show(p) Part.show(f1) u1e = bs.uIso(1).toShape() p = Part.makePolygon([bd, b, c, cd], True) ll = p.Edges + [u1e.Edge1] f2 = Part.makeFilledFace(Part.__sortEdges__(ll)) # f2=Part.Face(Part.__sortEdges__(ll)) #Part.show(u1e) #Part.show(p) Part.show(f2) v1e = bs.vIso(1).toShape() p = Part.makePolygon([dd, d, c, cd], True) ll = p.Edges + [v1e.Edge1] f3 = Part.makeFilledFace(Part.__sortEdges__(ll)) #Part.show(v1e) #Part.show(p) Part.show(f3) p = Part.makePolygon([a, b, c, d], True) f0 = Part.makeFilledFace(p.Edges) Part.show(f0) if 1: nb = App.ActiveDocument.addObject('Part::Spline', 'Nurbs ' + str(n) + ' ' + ojn) nb.Shape = sha.Face1 if genblock: fln = sha.Face1 f0 = Part.Face(Part.makePolygon([a, b, c, d], True)) f1 = Part.Face(Part.makePolygon([ad, bd, b, a], True)) f2 = Part.Face(Part.makePolygon([b, bd, cd, c], True)) f3 = Part.Face(Part.makePolygon([cd, dd, d, c], True)) f4 = Part.Face(Part.makePolygon([ad, a, d, dd], True)) fls = [f0, f1, f2, f3, f4, fln] sh = Part.Shell(fls) sol = Part.Solid(sh) ttt = App.ActiveDocument.addObject('Part::Feature', 'Nurbsblock ' + str(n) + ' ' + ojn) ttt.Shape = sol # ttt.ViewObject.hide() print(lu, lv) return bs
def import_xyz(mode, filename="/tmp/test.xyz", label='', ku=20, kv=10, lu=0, lv=0): '''import_xyz(mode,filename="/tmp/test.xyz",label='',ku=20, kv=10,lu=0,lv=0) import the point cloud from the file ''' print("Import mode=", mode) if mode: if lu > 0 and lv > 0: sayErr("read Points001") try: App.ActiveDocument.nurbs except: nurbs = App.ActiveDocument.addObject("App::DocumentObjectGroup", "nurbs") try: App.ActiveDocument.grids except: grids = App.ActiveDocument.addObject("App::DocumentObjectGroup", "grids") # Get or create "Point_Groups". try: PointGroups = FreeCAD.ActiveDocument.Point_Groups except: PointGroups = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", 'Point_Groups') PointGroups.Label = "Point Groups" # Get or create "Points". try: FreeCAD.ActiveDocument.Points except: Points = FreeCAD.ActiveDocument.addObject('Points::Feature', "Points") PointGroups.addObject(Points) objs = App.ActiveDocument.getObjectsByLabel(label) if len(objs) != 1: sayexc("no point cloud with this label found: >" + label + "<") pts = objs[0].Points.Points say(("len pts, lu, lv, lu*lv", len(pts), lu, lv, lu * lv)) assert (len(pts) == lu * lv) return pts say("iport") try: App.ActiveDocument.Points say("use existing Points") return App.ActiveDocument.Points.Points.Points except: try: App.ActiveDocument.nurbs except: nurbs = App.ActiveDocument.addObject("App::DocumentObjectGroup", "nurbs") try: App.ActiveDocument.grids except: grids = App.ActiveDocument.addObject("App::DocumentObjectGroup", "grids") # Get or create "Point_Groups". try: PointGroups = FreeCAD.ActiveDocument.Point_Groups except: PointGroups = FreeCAD.ActiveDocument.addObject( "App::DocumentObjectGroup", 'Point_Groups') PointGroups.Label = "Point Groups" # Get or create "Points". try: FreeCAD.ActiveDocument.Points except: Points = FreeCAD.ActiveDocument.addObject('Points::Feature', "Points") PointGroups.addObject(Points) fn = filename if fn.startswith('UserAppData'): fn = fn.replace('UserAppData', FreeCAD.ConfigGet("UserAppData")) f = open(fn) lines = f.readlines() say("readlines", len(lines)) ''' # utm coords 32356000.00 5638000.00 # height scale factor hfac=3 ''' pts = [] Gui.updateGui() for i, l in enumerate(lines): p = l.split() hfac = 3 try: #pts.append(FreeCAD.Vector(float(p[0])-32356000.00,float(p[1])-5638000.00,hfac*float(p[2]))) pts.append( FreeCAD.Vector(float(p[0]), float(p[1]), hfac * float(p[2]))) except: sayErr(("error line ", i, p, l)) if i % 1000 == 0: Gui.updateGui() # if i >100: break if ku > 1 and kv > 1: pts = reduceGrid(pts, ku, kv) head, tail = os.path.split(fn) PointGroup = FreeCAD.ActiveDocument.addObject('Points::Feature', "Point_Group") PointGroup.Label = tail[:-4] FreeCAD.ActiveDocument.Point_Groups.addObject(PointGroup) PointObject = PointGroup.Points.copy() PointObject.addPoints(pts) PointGroup.Points = PointObject App.ActiveDocument.ActiveObject.ViewObject.hide() PointGroup.ViewObject.ShapeColor = (1.0, .0, 0.0) PointGroup.ViewObject.PointSize = 3.0 FreeCAD.ActiveDocument.recompute() Gui.SendMsgToActiveView("ViewFit") return pts