def Activated(self): from pivy import sogui from pivy import coin global myRenderArea if myRenderArea == None: root = coin.SoSeparator() myCamera = coin.SoPerspectiveCamera() myMaterial = coin.SoMaterial() root.addChild(myCamera) root.addChild(coin.SoDirectionalLight()) #myMaterial.diffuseColor = (1.0, 0.0, 0.0) # Red root.addChild(myMaterial) root.addChild(coin.SoCone()) # Create a renderArea in which to see our scene graph. # The render area will appear within the main window. myRenderArea = sogui.SoGuiRenderArea(FreeCADGui.getMainWindow()) # Make myCamera see everything. myCamera.viewAll(root, myRenderArea.getViewportRegion()) # Put our scene in myRenderArea, change the title myRenderArea.setSceneGraph(root) myRenderArea.setTitle("Hello Cone") myRenderArea.show()
def set_cam(area, bk): # does this makes a difference ? from pivy import coin try: root = area.ViewObject.RootNode myLight = coin.SoDirectionalLight() myLight.color.setValue(coin.SbColor(0, 1, 0)) root.insertChild(myLight, 0) say("Lighting on base area activated.") except Exception: sayexc("Lighting 272") mycam = """#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 cam_height = 200 * bk * 10000 / 0.6 mycam += "\nposition " + str(x) + " " + str(y) + " 999\n " mycam += "\nheight " + str(cam_height) + "\n}\n\n" area.ViewObject.Document.activeView().setCamera(mycam) say("Camera was set.")
def __init__(self, view, coneHeight=5): self.view = view self.dro = DRO(view) self.tsk = TaskProgress(view) # Camera used for the DRO to maintain the same size independent of 3d zoom level self.cam = coin.SoOrthographicCamera() self.cam.aspectRatio = 1 self.cam.viewportMapping = coin.SoCamera.LEAVE_ALONE # Here's the thing, there is no need for a light in order to display text. But for # the faces a light is required otherwise they'll always be black - and one can spend # hours to try and make them a different color. self.lgt = coin.SoDirectionalLight() self.sep = coin.SoSeparator() self.sep.addChild(self.cam) self.sep.addChild(self.lgt) self.sep.addChild(self.dro.sep) self.sep.addChild(self.tsk.sep) self.tool = Tool(view, coneHeight) self.viewer = self.view.getViewer() self.render = self.viewer.getSoRenderManager() self.sup = None self.updatePreferences() self.setPosition(0, 0, 0, 0, 0, 0, False, False, None)
def render(outputfile,scene=None,camera=None,zoom=False,width=400,height=300,background=(1.0,1.0,1.0)): """render(outputfile,scene=None,camera=None,zoom=False,width=400,height=300,background=(1.0,1.0,1.0)): Renders a PNG image of given width and height and background color from the given coin scene, using the given coin camera (ortho or perspective). If zoom is True the camera will be resized to fit all objects. The outputfile must be a file path to save a png image.""" # On Linux, the X server must have indirect rendering enabled in order to be able to do offline # PNG rendering. Unfortunately, this is turned off by default on most recent distros. The easiest # way I found is to edit (or create if inexistant) /etc/X11/xorg.conf and add this: # # Section "ServerFlags" # Option "AllowIndirectGLX" "on" # Option "IndirectGLX" "on" # EndSection # # But there are other ways, google of GLX indirect rendering if isinstance(camera,str): camera = getCoinCamera(camera) print("Starting offline renderer") # build an offline scene root separator root = coin.SoSeparator() # add one light (mandatory) light = coin.SoDirectionalLight() root.addChild(light) if not camera: # create a default camera if none was given camera = coin.SoPerspectiveCamera() cameraRotation = coin.SbRotation.identity() cameraRotation *= coin.SbRotation(coin.SbVec3f(1,0,0),-0.4) cameraRotation *= coin.SbRotation(coin.SbVec3f(0,1,0), 0.4) camera.orientation = cameraRotation # make sure all objects get in the view later zoom = True root.addChild(camera) if scene: root.addChild(scene) else: # no scene was given, add a simple cube cube = coin.SoCube() root.addChild(cube) vpRegion = coin.SbViewportRegion(width,height) if zoom: camera.viewAll(root,vpRegion) print("Creating viewport") offscreenRenderer = coin.SoOffscreenRenderer(vpRegion) offscreenRenderer.setBackgroundColor(coin.SbColor(background[0],background[1],background[2])) print("Ready to render") # ref ensures that the node will not be garbage-collected during rendering root.ref() ok = offscreenRenderer.render(root) root.unref() if ok: offscreenRenderer.writeToFile(outputfile,"PNG") print("Rendering",outputfile,"done") else: print("Error rendering image")
def setcolors2(obj): ''' unterschiedliches licht aus allen richtungen ''' viewprovider = obj.ViewObject root=viewprovider.RootNode l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,1,0)) l.color.setValue(coin.SbColor(0,0,1)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(1,0,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,-1,0)) l.color.setValue(coin.SbColor(1,0,1)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(-1,0,0)) l.color.setValue(coin.SbColor(0,1,1)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,0,1)) l.color.setValue(coin.SbColor(1,0,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,0,-1)) l.color.setValue(coin.SbColor(1,1,0)) root.insertChild(l, 0)
def setcolors2(obj): viewprovider = obj.ViewObject root=viewprovider.RootNode l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,1,0)) l.color.setValue(coin.SbColor(0,0,1)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(1,0,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,-1,0)) l.color.setValue(coin.SbColor(1,0,1)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(-1,0,0)) l.color.setValue(coin.SbColor(0,1,1)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,0,1)) l.color.setValue(coin.SbColor(1,0,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,0,-1)) l.color.setValue(coin.SbColor(1,1,0)) root.insertChild(l, 0)
def makeSnapshotWithoutGui(): from pivy import coin # create a test geometry and create an IV representation as string box = Part.makeCone(10, 8, 10) iv = box.writeInventor() # load it into a buffer inp = coin.SoInput() try: inp.setBuffer(iv) except Exception: tempPath = tempfile.gettempdir() fileName = tempPath + os.sep + "cone.iv" file = open(fileName, "w") file.write(iv) file.close() inp.openFile(fileName) # and create a scenegraph data = coin.SoDB.readAll(inp) base = coin.SoBaseColor() base.rgb.setValue(0.6, 0.7, 1.0) data.insertChild(base, 0) # add light and camera so that the rendered geometry is visible root = coin.SoSeparator() light = coin.SoDirectionalLight() cam = coin.SoOrthographicCamera() root.addChild(cam) root.addChild(light) root.addChild(data) # do the rendering now axo = coin.SbRotation(-0.353553, -0.146447, -0.353553, -0.853553) viewport = coin.SbViewportRegion(400, 400) cam.orientation.setValue(axo) cam.viewAll(root, viewport) off = coin.SoOffscreenRenderer(viewport) root.ref() off.render(root) root.unref() # export the image, PS is always available off.writeToPostScript("crystal.ps") # Other formats are only available if simage package is installed if off.isWriteSupported("PNG"): print("Save as PNG") off.writeToFile("crystal.png", "PNG")
def make_snapshot(input_file, output_file, size=48): from pivy import coin ext = os.path.splitext(input_file)[1][1:] mod = FreeCAD.getImportType(ext) if len(mod) == 0: print("Cannot load file {}".format(input_file)) return # use the first listed module module = importlib.import_module(mod[0]) module.open(input_file) doc = FreeCAD.ActiveDocument if doc is None: print("No active document") return init_gui() nodes = [FreeCADGui.subgraphFromObject(obj) for obj in doc.Objects] # add light and camera so that the rendered geometry is visible root = coin.SoSeparator() light = coin.SoDirectionalLight() cam = coin.SoOrthographicCamera() root.addChild(cam) root.addChild(light) for node in nodes: root.addChild(node) # do the rendering now axo = coin.SbRotation(-0.353553, -0.146447, -0.353553, -0.853553) width = size height = size viewport = coin.SbViewportRegion(width, height) cam.orientation.setValue(axo) cam.viewAll(root, viewport) off = FreeCADGui.SoQtOffscreenRenderer(width, height) off.setBackgroundColor(1, 1, 1) root.ref() # A QGuiApplication is needed to create an OpenGL context if QtGui.QGuiApplication.instance() is None: app = QtGui.QGuiApplication(sys.argv) off.render(root) off.writeToImage(output_file) root.unref()
def attach(self, vobj): """Respond to created/restored object event (callback). Args: vobj -- Related ViewProviderDocumentObject """ # pylint: disable=attribute-defined-outside-init self.fpo = vobj.Object SunskyLight.set_properties(self.fpo) # Here we create coin representation, which is a directional light, self.coin = SimpleNamespace() scene = Gui.ActiveDocument.ActiveView.getSceneGraph() # Create pointlight in scenegraph self.coin.light = coin.SoDirectionalLight() scene.insertChild(self.coin.light, 0) # Insert frontwise vobj.addDisplayMode(self.coin.light, "Shaded")
def geom(self, resolution=None, fluxmap=None, trans=False, vmin=None, vmax=None): """ Method to draw the geometry of the scene to a Coin3D scenegraph. """ """ ls2 = coin.SoPointLight() self.r.addChild(ls2) ls2.position = (0,0,1) ls2.color=(1,1,1) """ ls3 = coin.SoDirectionalLight() self.r.addChild(ls3) ls3.direction = (0, 0, 1) ls3.color = (1, 1, 1) self.r.addChild( self.sim._asm.get_scene_graph(resolution, fluxmap, trans, vmin, vmax))
def main(): myWindow = SoGui.init(sys.argv[0]) if myWindow == None: sys.exit(1) # add a new marker type: utils.addMarkerFromSvg("test.svg", "CUSTOM_MARKER", 50) root = coin.SoSeparator() color = coin.SoMaterial() color.diffuseColor = (1., 0., 0.) marker = coin.SoMarkerSet() marker.markerIndex = coin.SoMarkerSet.CUSTOM_MARKER data = coin.SoCoordinate3() data.point.setValue(0, 0, 0) data.point.setValues(0, 1, [[0., 0., 0.]]) myCamera = coin.SoPerspectiveCamera() root.addChild(myCamera) root.addChild(coin.SoDirectionalLight()) root.addChild(color) root.addChild(data) root.addChild(marker) root.addChild(data) root.addChild(marker) myRenderArea = SoGuiRenderArea(myWindow) myCamera.viewAll(root, myRenderArea.getViewportRegion()) myRenderArea.setSceneGraph(root) myRenderArea.setTitle("Hello Cone") myRenderArea.show() SoGui.show(myWindow) SoGui.mainLoop()
def setcolorlights(obj): ''' lichter auf objekte legen ''' # obj = ll obj.ViewObject.ShapeColor = (1.00,1.00,1.00) obj.ViewObject.LineColor = (1.00,1.00,.00) obj.ViewObject.LineWidth = 1.00 viewprovider = obj.ViewObject root=viewprovider.RootNode #myLight = coin.SoDirectionalLight() #root.insertChild(myLight, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,1,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(1,0,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,-1,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(-1,0,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,0,1)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,0,-1)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0)
def setcolorlights(obj): ''' monochromes licht auf objekt legen ''' obj.ViewObject.ShapeColor = (1.00,1.00,1.00) obj.ViewObject.LineColor = (1.00,1.00,.00) obj.ViewObject.LineWidth = 1.00 viewprovider = obj.ViewObject root=viewprovider.RootNode l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,1,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(1,0,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,-1,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(-1,0,0)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,0,1)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0) l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0,0,-1)) l.color.setValue(coin.SbColor(0,1,0)) root.insertChild(l, 0)
def import_osm2(b, l, bk, progressbar, status, elevation): dialog = False debug = False 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() # say(content) # raise Exception("to debug:force load from internet") 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") # f.write(response.text) if response.status_code == 200: with open(fn, 'wb') as f: for chunk in response.iter_content(1024): f.write(chunk) f.close() # print("huhu");return if 0: try: say("read--") response = urllib.request.urlopen(source) #import ssl #ssl._create_default_https_context = ssl._create_unverified_context #response = urllib.request.urlopen(source) # import requests # response = requests.get(source) say(response) say("2huu") first = True content = '' f = open(fn, "w") l = 0 z = 0 ct = 0 say("2wkkw") #say(response.text) # lines=response.text.split('\n') # say(len(lines)) say("ll") # for line in lines: for line in response: print("Y", line) if status: if z > 5000: status.setText("read data ..." + str(l)) z = 0 FreeCADGui.updateGui() l += 1 z += 1 if first: first = False else: content += line f.write(line) f.close() if status: status.setText("FILE CLOSED ..." + str(l)) FreeCADGui.updateGui() response.close() except: sayErr("Fehler beim Lesen") if status: status.setText("got data from openstreetmap.org ...") FreeCADGui.updateGui() sayW("Beeenden - im zweiten versuch daten auswerten") return False 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) # fn='/home/thomas/.FreeCAD//geodat3/50.340722-11.232647-0.015' say(fn) tree = geodat.my_xmlparser.getData(fn) # for element in tree.getiterator('node'): # say(element.params) # say("ways") # for element in tree.getiterator('way'): # say(element.params) # say("relations") # for element in tree.getiterator('relation'): # say(element.params) if 0: try: sd = parse(content) except: sayexc("Problem parsing data - abort") status.setText( "Problem parsing data - aborted, for details see Report view") return 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) # say(points) # say("abbruch3 -hier daten uebernehmen !!");return # hack to catch deutsche umlaute def beaustring(string): res = '' for tk in zz: try: res += str(tk) except: if ord(tk) == 223: res += 'ß' elif ord(tk) == 246: res += 'ö' elif ord(tk) == 196: res += 'Ä' elif ord(tk) == 228: res += 'ä' elif ord(tk) == 242: res += 'ü' else: sayErr(["error sign", tk, ord(tk), string]) res += "#" return res 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 = 1000000 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'] # say(w.params) # say("way content") # for c in w.content: # say(c) building = False landuse = False highway = False wn += 1 # nur teile testen #if wn <2000: continue 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 debug: say(t) # say(t.params['k']) # say(t.params['v']) 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': zz = t.params['v'] nr = beaustring(zz) if str(t.params['k']) == 'ref': zz = t.params['v'] nr = beaustring(zz) + " /" if str(t.params['k']) == 'addr:street': zz = t.params['v'] st2 = " " + beaustring(zz) 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) + " " + str(nr) name = str(st) + st2 + " " + str(nr) if name == ' ': name = 'landuse xyz' if debug: say(("name ", name)) #say(name,zz,nr,ci) #generate pointlist of the way polis = [] height = None llpoints = [] # say("get nodes",w) for n in w.getiterator('nd'): # say(n.params) 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 avaiable 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, .60, .60) elif nr == 'meadow': g.ViewObject.ShapeColor = (0.00, 1.00, 0.00) elif nr == 'farmland': g.ViewObject.ShapeColor = (.80, .80, .00) elif nr == 'forest': g.ViewObject.ShapeColor = (1.0, .40, .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, .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() # FreeCADGui.SendMsgToActiveView("ViewFit") refresh = 0 FreeCAD.activeDocument().recompute() 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_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 Exception: 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) response = urllib.request.urlopen(source) FreeCAD.t = response f = open(fn, "w") if response.getcode == 200: with open(fn, 'wb') as f: for chunk in response.readlines(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() 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 Exception: 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 Exception: 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 Exception: 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
f.write(iv) name = f.name f.close() inp.openFile(name) print('1') # and create a scenegraph data = coin.SoDB.readAll(inp) base = coin.SoBaseColor() base.rgb.setValue(0.6, 0.7, 1.0) data.insertChild(base, 0) print('2') # add light and camera so that the rendered geometry is visible root = coin.SoSeparator() light = coin.SoDirectionalLight() cam = coin.SoOrthographicCamera() root.addChild(cam) root.addChild(light) root.addChild(data) print('3') # do the rendering now axo = coin.SbRotation(-0.353553, -0.146447, -0.353553, -0.853553) viewport = coin.SbViewportRegion(600, 600) cam.orientation.setValue(axo) cam.viewAll(root, viewport) off = coin.SoOffscreenRenderer(viewport) root.ref() off.render(root) root.unref()
def onChanged(self, fp, prop): if not fp.On: return print ("on changed .....",fp.Label,prop) if fp == None: return if not fp.ViewObject.Visibility: return try: self.v except: return AxisAngle=[ (FreeCAD.Vector(1,1,1),120), (FreeCAD.Vector(1,1,1),-120), (FreeCAD.Vector(1,0,1),45), (FreeCAD.Vector(1,0,1),60), (FreeCAD.Vector(1,0,1),30), (FreeCAD.Vector(1,0,0),90), (FreeCAD.Vector(1,0,0),-90), (FreeCAD.Vector(-1,0,0),90), (FreeCAD.Vector(-1,0,0),-90), ] if prop=="Shape" or prop=="Group": dpms=[fp.A_DisplayMode,fp.B_DisplayMode,fp.C_DisplayMode,fp.D_DisplayMode] vals=[fp.A_OrientationMode,fp.B_OrientationMode,fp.C_OrientationMode,fp.D_OrientationMode] for ix in [0]: objs=fp.objs view=self.v.getViewer(ix) val=vals[ix] marker = coin.SoSeparator() for objx in objs+[fp.obja]: print "run ",objx.Label node= objx.ViewObject.RootNode if fp.DisplayMode: nodeA=node.copy() clds=nodeA.getChildren() s2=clds[2] s2.whichChild.setValue(0) else: nodeA=node if fp.A_DisplayMode==0: nodeA=node else: nodeA=node.copy() clds=nodeA.getChildren() s2=clds[2] s2.whichChild.setValue(dpms[ix]) marker.addChild(nodeA) c=view.getSoRenderManager().getCamera() if val <> 0: c.orientation=FreeCAD.Rotation( AxisAngle[val-1][0],AxisAngle[val-1][1]).Q else: c.orientation=FreeCAD.Rotation( fp.A_Axis,fp.A_Angle).Q sg=view.getSceneGraph() sg.removeChild(1) sg.removeChild(0) # hier die lichter einfuegen lis=[] for ob in fp.Group: #break print ("!!",ob,ob.Label,ob.on) try: ob.mode except: continue print ("verarbeitung",ob.mode,ob.on) if ob.on and ob.ViewObject.Visibility: if ob.mode=="DirectionalLight": continue # ignore dirlights l=coin.SoDirectionalLight() #marker.insertChild(l,0) #lis += [l] if ob.mode=="SpotLight": l=coin.SoSpotLight() l.cutOffAngle.setValue(0.4) l.dropOffRate.setValue(0.) l.location.setValue(coin.SbVec3f(ob.location.x,ob.location.y,ob.location.z,)) l.direction.setValue(coin.SbVec3f(ob.direction.x,ob.direction.y,ob.direction.z,)) l.color.setValue(coin.SbColor(ob.color[0],ob.color[1],ob.color[2])) #marker.insertChild(l,0) lis += [l] sg.addChild(marker) print "makeshadow ..........!" mkshadow(marker,lis) print "------------------done-----------------" for ob in fp.Group: try: ob.mode except: continue print ("verarbeitung",ob.mode,ob.on) if ob.on and ob.ViewObject.Visibility: if ob.mode=="DirectionalLight": l=coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(-1,1,0)) l.color.setValue(coin.SbColor(1,0,0)) l.direction.setValue(coin.SbVec3f(ob.direction.x,ob.direction.y,ob.direction.z,)) l.color.setValue(coin.SbColor(ob.color[0],ob.color[1],ob.color[2])) marker.insertChild(l,0) if ob.mode=="PointLight": l=coin.SoPointLight() l.location.setValue(coin.SbVec3f(ob.location.x,ob.location.y,ob.location.z,)) l.color.setValue(coin.SbColor(ob.color[0],ob.color[1],ob.color[2])) marker.insertChild(l,0) return if prop.endswith("DisplayMode"): w=getattr(fp,prop) if w<0: setattr(fp,prop,0) if w>3: setattr(fp,prop,3) #updatencontenth2(self.v,fp.obja,fp.objb,fp.objs,fp,False) return if prop.endswith("OrientationMode"): val=getattr(fp,prop) if val>=len(AxisAngle)or val<0: setattr(fp,prop,val%len(AxisAngle)) val=getattr(fp,prop) if val<>0: if prop=="A_OrientationMode": fp.A_Axis=AxisAngle[val-1][0] fp.A_Angle=AxisAngle[val-1][1] if prop=="B_OrientationMode": fp.B_Axis=AxisAngle[val-1][0] fp.B_Angle=AxisAngle[val-1][1] if prop=="C_OrientationMode": fp.C_Axis=AxisAngle[val-1][0] fp.C_Angle=AxisAngle[val-1][1] if prop=="D_OrientationMode": fp.D_Axis=AxisAngle[val-1][0] fp.D_Angle=AxisAngle[val-1][1] return if prop.startswith("A_"): c=self.v.getViewer(0).getSoRenderManager().getCamera() c.orientation=FreeCAD.Rotation(fp.A_Axis,fp.A_Angle).Q view=self.v.getViewer(0) reg=view.getSoRenderManager().getViewportRegion() marker=view.getSoRenderManager().getSceneGraph() c.viewAll(marker,reg) if prop.startswith("B_"): c=self.v.getViewer(1).getSoRenderManager().getCamera() c.orientation=FreeCAD.Rotation(fp.B_Axis,fp.B_Angle).Q view=self.v.getViewer(1) reg=view.getSoRenderManager().getViewportRegion() marker=view.getSoRenderManager().getSceneGraph() c.viewAll(marker,reg) if prop.startswith("C_"): c=self.v.getViewer(2).getSoRenderManager().getCamera() c.orientation=FreeCAD.Rotation(fp.C_Axis,fp.C_Angle).Q view=self.v.getViewer(2) reg=view.getSoRenderManager().getViewportRegion() marker=view.getSoRenderManager().getSceneGraph() c.viewAll(marker,reg) if prop.startswith("D_"): c=self.v.getViewer(3).getSoRenderManager().getCamera() c.orientation=FreeCAD.Rotation(fp.D_Axis,fp.D_Angle).Q view=self.v.getViewer(3) reg=view.getSoRenderManager().getViewportRegion() marker=view.getSoRenderManager().getSceneGraph() c.viewAll(marker,reg) if fp.fitAll: self.v.fitAll()
def createLightInstance(self): return coin.SoDirectionalLight()
def import_osm2(b,l,bk,progressbar,status,elevation): dialog=False debug=False 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") + "/geodat/" fn=dn+str(b)+'-'+str(l)+'-'+str(bk) import os if not os.path.isdir(dn): print "create " + dn os.makedirs(dn) try: print "I try to read data from cache file ..." print fn f=open(fn,"r") content=f.read() print "successful read" # print content except: print "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) print source try: response = urllib2.urlopen(source) first=True content='' f=open(fn,"w") l=0 z=0 ct=0 for line in response: if status: if z>5000: status.setText("read data ..." + str(l)) z=0 FreeCADGui.updateGui() l+=1 z+=1 if first: first=False else: content += line f.write(line) f.close() if status: status.setText("FILE CLOSED ..." + str(l)) FreeCADGui.updateGui() response.close() except: print "Fehler beim Lesen" if status: status.setText("got data from openstreetmap.org ...") FreeCADGui.updateGui() print "Beeenden - im zweiten versuch daten auswerten" return False if elevation: baseheight=getHeight(b,l) else: baseheight=0 if debug: print "-------Data---------" print content print "--------------------" if status: status.setText("parse data ...") FreeCADGui.updateGui() try: sd=parse(content) except: sayexc("Problem parsing data - abort") status.setText("Problem parsing data - aborted, for details see Report view") return if debug: print(json.dumps(sd, indent=4)) if status: status.setText("transform data ...") FreeCADGui.updateGui() bounds=sd['osm']['bounds'] nodes=sd['osm']['node'] ways=sd['osm']['way'] try: relations=sd['osm']['relation'] except: relations=[] # center of the scene bounds=sd['osm']['bounds'] minlat=float(bounds['@minlat']) minlon=float(bounds['@minlon']) maxlat=float(bounds['@maxlat']) maxlon=float(bounds['@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['@id']]=n ll=tm.fromGeographic(float(n['@lat']),float(n['@lon'])) points[str(n['@id'])]=FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0.0) # hack to catch deutsche umlaute def beaustring(string): res='' for tk in zz: try: res += str(tk) except: if ord(tk)==223: res += 'ß' elif ord(tk)==246: res += 'ö' elif ord(tk)==196: res += 'Ä' elif ord(tk)==228: res += 'ä' elif ord(tk)==242: res += 'ü' else: print ["error sign",tk,ord(tk),string] res +="#" return res 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=1000000 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: # print w wid=w['@id'] # print wid building=False landuse=False highway=False wn += 1 # nur teile testen #if wn <2000: continue nowtime=time.time() if wn<>0 and (nowtime-starttime)/wn > 0.5: print "way ---- # " + str(wn) + "/" + str(coways) + " time per house: " + str(round((nowtime-starttime)/wn,2)) if progressbar: progressbar.setValue(int(0+100.0*wn/coways)) if debug: print "w=", w if debug: print "tags ..." st="" nr="" h=0 try: w['tag'] except: print "no tags found." continue for t in w['tag']: if t.__class__.__name__ == 'OrderedDict': try: if debug: print t if str(t['@k'])=='building': building=True st='building' if str(t['@k'])=='landuse': landuse=True st=w['tag']['@k'] nr=w['tag']['@v'] if str(t['@k'])=='highway': highway=True st=t['@k'] if str(t['@k'])=='name': zz=t['@v'] nr=beaustring(zz) if str(t['@k'])=='ref': zz=t['@v'] nr=beaustring(zz)+" /" if str(t['@k'])=='addr:street': zz=w['tag'][1]['@v'] st=beaustring(zz) if str(t['@k'])=='addr:housenumber': nr=str(t['@v']) if str(t['@k'])=='building:levels': if h==0: h=int(str(t['@v']))*1000*3 if str(t['@k'])=='building:height': h=int(str(t['@v']))*1000 except: print "unexpected error ################################################################" else: if debug: print [w['tag']['@k'],w['tag']['@v']] if str(w['tag']['@k'])=='building': building=True st='building' if str(w['tag']['@k'])=='building:levels': if h==0: h=int(str(w['tag']['@v']))*1000*3 if str(w['tag']['@k'])=='building:height': h=int(str(w['tag']['@v']))*1000 if str(w['tag']['@k'])=='landuse': landuse=True st=w['tag']['@k'] nr=w['tag']['@v'] if str(w['tag']['@k'])=='highway': highway=True st=w['tag']['@k'] nr=w['tag']['@v'] name=str(st) + " " + str(nr) if name==' ': name='landuse xyz' if debug: print "name ",name #generate pointlist of the way polis=[] height=None llpoints=[] for n in w['nd']: m=nodesbyid[n['@ref']] llpoints.append([n['@ref'],m['@lat'],m['@lon']]) if elevation: print "get heights for " + str(len(llpoints)) heights=getHeights(llpoints) for n in w['nd']: p=points[str(n['@ref'])] if building and elevation: if not height: try: height=heights[m['@lat']+' '+m['@lon']]*1000 - baseheight except: print "---no height avaiable for " + m['@lat']+' '+m['@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,.60,.60) elif nr == 'meadow': g.ViewObject.ShapeColor = (0.00,1.00,0.00) elif nr == 'farmland': g.ViewObject.ShapeColor = (.80,.80,.00) elif nr == 'forest': g.ViewObject.ShapeColor = (1.0,.40,.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,.00,1.00) g.ViewObject.LineWidth = 10 g.Dir = (0,0,0.2) g.Label=name refresh += 1 if os.path.exists("/tmp/stop"): print("notbremse gezogen") FreeCAD.w=w raise Exception("Notbremse Manager main loop") if refresh >3: FreeCADGui.updateGui() # FreeCADGui.SendMsgToActiveView("ViewFit") refresh=0 FreeCAD.activeDocument().recompute() FreeCADGui.updateGui() FreeCAD.activeDocument().recompute() if status: status.setText("import finished.") if progressbar: progressbar.setValue(100) organize() endtime=time.time() print "running time ", int(endtime-starttime), " count ways ", coways return True
def navi(): '''navigator startup''' mw = QtGui.QApplication #widget.setCursor(QtCore.Qt.SizeAllCursor) #cursor ausblenden #mw.setOverrideCursor(QtCore.Qt.BlankCursor) # FreeCADGui.activateWorkbench("NoneWorkbench") mw.setOverrideCursor(QtCore.Qt.PointingHandCursor) ef = EventFilter() ef.laenge = 0.0 ef.breite = 0.0 ef.campos = FreeCAD.Vector(0, 0, 20000) # ef.output.hide() ef.mouseMode = False ef.firstCall = True ef.mode = "turn" ef.navi = myNavigatorWidget(ef) ef.speed = 100 ef.direction = 0.5 * math.pi ef.roll = 0 #-------------- # get a jpg filename # jpgfilename = QtGui.QFileDialog.getOpenFileName(QtGui.qApp.activeWindow(),'Open image file','*.jpg') fn = '/home/microelly2/FCB/b175_camera_controller/winter.jpg' fn = os.path.dirname(__file__) + "/../pics/winter.jpg" sg = FreeCADGui.ActiveDocument.ActiveView.getSceneGraph() col = coin.SoBaseColor() #col.rgb=(1,0,0) trans = coin.SoTranslation() trans.translation.setValue([0, 0, 0]) myCustomNode = coin.SoSeparator() #myCustomNode.addChild(col) if 0 or False: cub = coin.SoCylinder() cub.radius.setValue(3000) cub.height.setValue(4000) cub.parts.set("SIDES") s = coin.SoRotationXYZ() s.angle.setValue(1.5708) s.axis.setValue(0) myCustomNode.addChild(s) s = coin.SoRotationXYZ() s.angle.setValue(math.pi) s.axis.setValue(1) myCustomNode.addChild(s) else: cub = coin.SoSphere() cub.radius.setValue(10000000) s = coin.SoRotationXYZ() s.angle.setValue(1.5708) s.axis.setValue(0) myCustomNode.addChild(s) s = coin.SoRotationXYZ() s.angle.setValue(math.pi) s.axis.setValue(1) myCustomNode.addChild(s) if False: l = coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0, 1, 0)) l.color.setValue(coin.SbColor(0, 0, 1)) myCustomNode.addChild(l) l = coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0, -1, 0)) l.color.setValue(coin.SbColor(0, 1, 1)) myCustomNode.addChild(l) l = coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0, 0, 1)) l.color.setValue(coin.SbColor(1, 0, 0)) myCustomNode.addChild(l) l = coin.SoDirectionalLight() l.direction.setValue(coin.SbVec3f(0, 0, -1)) l.color.setValue(coin.SbColor(0.6, 0.6, 1)) myCustomNode.addChild(l) l = coin.SoSpotLight() l.direction.setValue(coin.SbVec3f(1, 0, 1)) l.color.setValue(coin.SbColor(0, 1, 0)) l.location.setValue(coin.SbVec3f(0, 0, 0)) # l.cutOffAngle.setValue(0.01) # l.dropOffRate.setValue(1) myCustomNode.addChild(l) #myCustomNode.addChild(trans) myCustomNode.addChild(cub) sg.addChild(myCustomNode) tex = coin.SoTexture2() tex.filename = fn myCustomNode.insertChild(tex, 0) #--------------- ef.background = myCustomNode ef.tex = tex FreeCAD.eventfilter = ef mw.installEventFilter(ef) FreeCAD.eventfilter.on_key_press = on_keypress2 FreeCAD.eventfilter.on_move = on_move3 FreeCAD.eventfilter.on_clicks = on_clicks3 FreeCAD.eventfilter.on_windowslist = on_windowslist2 on_keypress2(FreeCAD.eventfilter, 'O') view = FreeCADGui.activeDocument().activeView() FreeCADGui.ActiveDocument.ActiveView.setAnimationEnabled(False) mgr = view.getViewer().getSoRenderManager() mgr.setAutoClipping(0) FreeCAD.ActiveDocument.recompute() FreeCADGui.updateGui() return ef
def __init__(self, *args, **kwargs): """ Constructs a QuarterWidget. QuarterWidget(QWidget parent = None, QGLWidget sharewidget = None, Qt.WindowFlags f = 0, scxml = "coin:scxml/navigation/examiner.xml") QuarterWidget(QGLContext context, QWidget parent = None, QGLWidget sharewidget = None, Qt.WindowFlags f = 0, scxml = "coin:scxml/navigation/examiner.xml") QuarterWidget(QGLFormat format, QWidget parent = None, QGLWidget sharewidget = None, Qt.WindowFlags f = 0, scxml = "coin:scxml/navigation/examiner.xml") """ params = ["parent", "sharewidget"] values = { "parent": None, "sharewidget": None, "f": 0, "scxml": "coin:scxml/navigation/examiner.xml" } values.update(kwargs) if len(args) > 0 and isinstance( args[0], QtOpenGL.QGLContext) or "context" in kwargs: params.insert(0, "context") elif len(args) > 0 and isinstance( args[0], QtOpenGL.QGLFormat) or "format" in kwargs: params.insert(0, "format") if len(args) > len(params): values["f"] = args[len(params)] if len(args) > len(params) + 1: values["scxml"] = args[len(params) + 1] for i in range(len(args), len(params)): args += (values[params[i]], ) QtOpenGL.QGLWidget.__init__(self, *args[:len(params)]) if values["f"]: self.setWindowFlags(values["f"]) # initialize Sensormanager and ImageReader instances only once if not QuarterWidget._sensormanager: QuarterWidget._sensormanager = SensorManager() if not QuarterWidget._imagereader: QuarterWidget._imagereader = ImageReader() self.cachecontext_list = [] self.cachecontext = self.findCacheContext(self, values["sharewidget"]) self.statecursormap = {} self.scene = None self.contextmenu = None self.contextmenuenabled = True self.sorendermanager = coin.SoRenderManager() self.soeventmanager = coin.SoEventManager() # Mind the order of initialization as the XML state machine uses # callbacks which depends on other state being initialized self.eventmanager = EventManager(self) self.devicemanager = DeviceManager(self) statemachine = coin.ScXML.readFile(values["scxml"]) if statemachine and statemachine.isOfType( coin.SoScXMLStateMachine.getClassTypeId()): sostatemachine = coin.cast(statemachine, "SoScXMLStateMachine") statemachine.addStateChangeCallback(statechangeCB, self) self.soeventmanager.addSoScXMLStateMachine(sostatemachine) sostatemachine.initialize() else: raise "could not initialize statemachine, given file not found?" self.headlight = coin.SoDirectionalLight() self.sorendermanager.setAutoClipping( coin.SoRenderManager.VARIABLE_NEAR_PLANE) self.sorendermanager.setRenderCallback(renderCB, self) self.sorendermanager.setBackgroundColor(coin.SbColor4f(0, 0, 0, 0)) self.sorendermanager.activate() self.sorendermanager.addPreRenderCallback(prerenderCB, self) self.sorendermanager.addPostRenderCallback(postrenderCB, self) self.soeventmanager.setNavigationState( coin.SoEventManager.MIXED_NAVIGATION) self.devicemanager.registerDevice(MouseHandler()) self.devicemanager.registerDevice(KeyboardHandler()) self.eventmanager.registerEventHandler(DragDropHandler()) # set up a cache context for the default SoGLRenderAction self.sorendermanager.getGLRenderAction().setCacheContext( self.getCacheContextId()) self.setStateCursor("interact", QtCore.Qt.ArrowCursor) self.setStateCursor("idle", QtCore.Qt.OpenHandCursor) self.setStateCursor("rotate", QtCore.Qt.ClosedHandCursor) self.setStateCursor("pan", QtCore.Qt.SizeAllCursor) self.setStateCursor("zoom", QtCore.Qt.SizeVerCursor) self.setStateCursor("seek", QtCore.Qt.CrossCursor) self.setStateCursor("spin", QtCore.Qt.OpenHandCursor) self.setMouseTracking(True) self.setFocusPolicy(QtCore.Qt.StrongFocus)