예제 #1
0
    def setPosition(self, x, X, y, Y, z, Z, homed, spinning, mk):
        '''Update the tool position according to the given values.'''
        self.pos.translation = (x, y, z)

        if spinning:
            self.mat.diffuseColor = coin.SbColor(
                MachinekitPreferences.hudToolColorSpinning())
        else:
            self.mat.diffuseColor = coin.SbColor(
                MachinekitPreferences.hudToolColorStopped())
    def __init__(self, view, coneHeight=5):
        self.view = view
        self.tsze = coneHeight

        self.cam = coin.SoOrthographicCamera()
        self.cam.aspectRatio = 1
        self.cam.viewportMapping = coin.SoCamera.LEAVE_ALONE

        self.pos = coin.SoTranslation()

        self.mat = coin.SoMaterial()
        self.mat.diffuseColor = coin.SbColor(0.9, 0.0, 0.9)
        self.mat.transparency = 0

        self.fnt = coin.SoFont()

        self.txt = coin.SoText2()
        self.txt.string = 'setValues'
        self.txt.justification = coin.SoText2.LEFT

        self.sep = coin.SoSeparator()

        self.sep.addChild(self.cam)
        self.sep.addChild(self.pos)
        self.sep.addChild(self.mat)
        self.sep.addChild(self.fnt)
        self.sep.addChild(self.txt)

        self.tTrf = coin.SoTransform()
        self.tTrf.translation.setValue((0, -self.tsze / 2, 0))
        self.tTrf.center.setValue((0, self.tsze / 2, 0))
        self.tTrf.rotation.setValue(coin.SbVec3f((1, 0, 0)), -math.pi / 2)

        self.tPos = coin.SoTranslation()

        self.tMat = coin.SoMaterial()
        self.tMat.diffuseColor = coin.SbColor(0.4, 0.4, 0.4)
        self.tMat.transparency = 0.8

        self.tool = coin.SoCone()
        self.tool.height.setValue(self.tsze)
        self.tool.bottomRadius.setValue(self.tsze / 4)

        self.tSep = coin.SoSeparator()
        self.tSep.addChild(self.tPos)
        self.tSep.addChild(self.tTrf)
        self.tSep.addChild(self.tMat)
        self.tSep.addChild(self.tool)

        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)
예제 #3
0
 def setPosition(self, x, X, y, Y, z, Z, homed, spinning, mk):
     '''Update the DRO according to the given values.'''
     if homed:
         self.mat.diffuseColor = coin.SbColor(
             MachinekitPreferences.hudFontColorHomed())
     else:
         self.mat.diffuseColor = coin.SbColor(
             MachinekitPreferences.hudFontColorUnhomed())
     self.txt.string.setValues([
         self.axisFmt('X', x, X),
         self.axisFmt('Y', y, Y),
         self.axisFmt('Z', z, Z)
     ])
    def setPosition(self, x, X, y, Y, z, Z, homed=True, hot=False):
        if homed:
            self.mat.diffuseColor = coin.SbColor(0.0, 0.9, 0.0)
        else:
            self.mat.diffuseColor = coin.SbColor(0.9, 0.0, 0.9)
        self.txt.string.setValues([
            self.axisFmt('X', x, X),
            self.axisFmt('Y', y, Y),
            self.axisFmt('Z', z, Z)
        ])
        self.tPos.translation = (x, y, z)

        if hot:
            self.tMat.diffuseColor = coin.SbColor(0.9, 0.0, 0.0)
        else:
            self.tMat.diffuseColor = coin.SbColor(0.0, 0.0, 0.9)
예제 #5
0
    def attach(self, vobj):
        self.vobj = vobj
        self.obj = vobj.Object
        self.taskPanel = None

        # setup the axis display at the origin
        self.switch = coin.SoSwitch()
        self.sep = coin.SoSeparator()
        self.axs = coin.SoType.fromName('SoAxisCrossKit').createInstance()
        self.axs.set('xHead.transform', 'scaleFactor 2 3 2')
        self.axs.set('yHead.transform', 'scaleFactor 2 3 2')
        self.axs.set('zHead.transform', 'scaleFactor 2 3 2')
        self.sca = coin.SoType.fromName('SoShapeScale').createInstance()
        self.sca.setPart('shape', self.axs)
        self.sca.scaleFactor.setValue(0.5)
        self.mat = coin.SoMaterial()
        self.mat.diffuseColor = coin.SbColor(0.9, 0, 0.9)
        self.mat.transparency = 0.85
        self.sph = coin.SoSphere()
        self.scs = coin.SoType.fromName('SoShapeScale').createInstance()
        self.scs.setPart('shape', self.sph)
        self.scs.scaleFactor.setValue(10)
        self.sep.addChild(self.sca)
        self.sep.addChild(self.mat)
        self.sep.addChild(self.scs)
        self.switch.addChild(self.sep)
        vobj.RootNode.addChild(self.switch)
        self.showOriginAxis(False)
예제 #6
0
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.")
예제 #7
0
def viewer(scene=None, background=(1.0, 1.0, 1.0)):
    """viewer(scene=None,background=(1.0,1.0,1.0)): starts a standalone coin viewer with the contents of the given scene"""

    # Initialize Coin. This returns a main window to use
    from pivy import sogui
    win = sogui.SoGui.init()
    if win == None:
        print("Unable to create a SoGui window")
        return

    win.setBackgroundColor(
        coin.SbColor(background[0], background[1], background[2]))

    if not scene:
        # build a quick default scene
        mat = coin.SoMaterial()
        mat.diffuseColor = (1.0, 0.0, 0.0)
        # Make a scene containing a red cone
        scene = coin.SoSeparator()
        scene.addChild(mat)
        scene.addChild(coin.SoCone())

    # ref the scene so it doesn't get garbage-collected
    scene.ref()

    # Create a viewer in which to see our scene graph
    viewer = sogui.SoGuiExaminerViewer(win)

    # Put our scene into viewer, change the title
    viewer.setSceneGraph(scene)
    viewer.setTitle("Coin viewer")
    viewer.show()

    sogui.SoGui.show(win)  # Display main window
    sogui.SoGui.mainLoop()  # Main Coin event loop
예제 #8
0
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")
예제 #9
0
    def __init__(self, surf):
        # The control points for this surface
        self.pts = to1D(surf.getPoles(), surf.getWeights())
        # The knot vector
        try:
            self.Uknots = surf.UKnotSequence
        except:
            self.Uknots = [0.0] * len(surf.getPoles()) + [1.0] * len(
                surf.getPoles())
        print(str(self.Uknots))
        try:
            self.Vknots = surf.VKnotSequence
        except:
            self.Vknots = [0.0] * len(surf.getPoles()[0]) + [1.0] * len(
                surf.getPoles()[0])
        print(str(self.Vknots))
        #self.Vknots = surf.VKnotSequence
        self.surfaceNode = coin.SoSeparator()
        self.surfSep = coin.SoSeparator()

        # Define the Bezier surface including the control
        # points and a complexity.
        self.material = coin.SoMaterial()
        self.material.transparency.setValue(0.0)
        FreeCAD.Console.PrintMessage("transparency OK\n")
        self.complexity = coin.SoComplexity()
        #self.controlPts = coin.SoCoordinate3()
        self.surface = coin.SoNurbsSurface()
        self.complexity.value = 1.0
        #self.complexity.type  = self.complexity.SCREEN_SPACE
        self.material.ambientColor.setValue(coin.SbColor(0.3, 0, 0))
        #self.material.diffuseColor.setValue(coin.SbColor(0.8,1,0.8))
        self.material.specularColor.setValue(coin.SbColor(1, 1, 1))
        self.material.shininess.setValue(0.5)
        #self.material.transparency.setValue(0.5)
        #self.material.orderedRGBA = 0xcccccc88
        #self.controlPts.point.setValues(0, len(self.pts), self.pts)
        self.surface.numUControlPoints = len(surf.getPoles())
        self.surface.numVControlPoints = len(surf.getPoles()[0])
        self.surface.uKnotVector.setValues(0, len(self.Uknots), self.Uknots)
        self.surface.vKnotVector.setValues(0, len(self.Vknots), self.Vknots)
        self.surfSep.addChild(self.material)
        self.surfSep.addChild(self.complexity)
        #self.surfSep.addChild(self.controlPts)
        self.surfSep.addChild(self.surface)
        self.surfaceNode.addChild(self.surfSep)
예제 #10
0
def main():
    app = QtWidgets.QApplication(sys.argv)

    root = coin.SoSeparator()
    mat = coin.SoMaterial()
    mat.diffuseColor.setValue(coin.SbColor(0.8, 1, 0.8))
    mat.specularColor.setValue(coin.SbColor(1, 1, 1))
    mat.shininess.setValue(1.0)
    mat.transparency.setValue(0.9)
    root.addChild(mat)
    root.addChild(coin.SoSphere())
    root.addChild(coin.SoCube())

    viewer = quarter.QuarterWidget()
    viewer.setSceneGraph(root)

    viewer.setWindowTitle("minimal")
    viewer.show()
    sys.exit(app.exec_())
예제 #11
0
def main():
    app = QApplication(sys.argv)

    root = coin.SoSeparator()
    

    vert = coin.SoVertexShader()
    vert.sourceProgram = "vertex.glsl"
    
    frag = coin.SoFragmentShader()
    frag.sourceProgram = "frag.glsl"
    
    shaders = [vert,frag]
    pro = coin.SoShaderProgram()
    pro.shaderObject.setValues(0,len(shaders),shaders)
    
    
    mat = coin.SoMaterial()
    mat.diffuseColor.setValue(coin.SbColor(0.8, 0.8, 0.8))
    mat.specularColor.setValue(coin.SbColor(1, 1, 1))
    mat.shininess.setValue(1.0)
    mat.transparency.setValue(0.5)
    
    
    
    
    sphere = coin.SoSphere()
    sphere.radius = 1.2
    
    
    root.addChild(pro)
    root.addChild(sphere)
    root.addChild(mat)
    root.addChild(coin.SoCube())

    viewer = quarter.QuarterWidget()
    viewer.setSceneGraph(root)

    viewer.setWindowTitle("minimal")
    viewer.show()
    sys.exit(app.exec_())
예제 #12
0
파일: viewer.py 프로젝트: jthirp/pivy_jtp
    def __init__(self, *args, **kwrds):
        try:
            self.app = QtGui.QApplication([])
        except RuntimeError:
            self.app = QtGui.QApplication.instance()

        super(Viewer, self).__init__(*args, **kwrds)
        self.sg = coin.SoSeparator()
        self.sg += [coin.SoOrthographicCamera()]
        self.setSceneGraph(self.sg)
        self.setBackgroundColor(coin.SbColor(1,1,1))
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
예제 #13
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)
예제 #14
0
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)
예제 #15
0
def draw_label(text=[], prop: propertyValues=None):
    ''' Draw widgets label relative to the position with alignment'''
    if text=='' or prop ==None: 
        return     # Nothing to do here 
    try:
        delta=App.Vector(0,0,0)
        print (prop.vectors)

        p1=App.Vector(prop.vectors[0])  #You must cast the value or it will fail
        p2=App.Vector(prop.vectors[1])
        delta.x=p1.x+2
        delta.y=p1.y+2
        delta.z=p1.z
        (r,thi,phi)=calculateLineSpherical(prop.vectors)        #get spherical representation of the point(p2)
        _transPositionPOS=coin.SoTransform()
        #_transPositionX = coin.SoTransform()
        _transPositionY = coin.SoTransform()
        _transPositionZ = coin.SoTransform()
        _transPositionPOS.translation.setValue(delta)
        _transPositionY.translation.setValue(App.Vector(0,0,0))
        _transPositionZ.translation.setValue(App.Vector(0,0,0))
        print (delta)
        _transPositionY.rotation.setValue(coin.SbVec3f(1,0, 0),phi)
        _transPositionZ.rotation.setValue(coin.SbVec3f(0, 0, 1),thi)

        font = coin.SoFont()
        font.size = prop.fontsize  # Font size
        font.Name = prop.labelfont  # Font used
        _text3D = coin.SoAsciiText()  # Draw text in the 3D world
        _text3D.string.setValues([l.encode("utf8") for l in text if l])
        #_text3D.justification = coin.SoAsciiText.LEFT
        coinColor = coin.SoMaterial()  # Font color
        coinColor.diffuseColor.set1Value(0, coin.SbColor(*prop.labelcolor))
        _textNode = coin.SoSeparator()   # A Separator to separate the text from the drawing
        _textNode.addChild(_transPositionPOS)
        if phi!=0:
            _textNode.addChild(_transPositionY)
        if thi!=0:
            _textNode.addChild(_transPositionZ)
        
        
        _textNode.addChild(coinColor)
        _textNode.addChild(font)
        _textNode.addChild(_text3D)
        return _textNode  # Return the created SoSeparator that contains the text
    except Exception as err:
        App.Console.PrintError("'draw_label' Failed. "
                                   "{err}\n".format(err=str(err)))
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        print(exc_type, fname, exc_tb.tb_lineno)
예제 #16
0
    def __init__(self, view, coneHeight):
        self.view = view
        self.tsze = coneHeight

        self.trf = coin.SoTransform()
        self.pos = coin.SoTranslation()

        self.mat = coin.SoMaterial()
        self.mat.diffuseColor = coin.SbColor(0.4, 0.4, 0.4)
        self.mat.transparency = 0.8

        self.sep = coin.SoSeparator()
        self.sep.addChild(self.pos)
        self.sep.addChild(self.trf)
        self.sep.addChild(self.mat)
        self.tool = None
        self.setToolShape(None)
예제 #17
0
def main():
    app = QtWidgets.QApplication(sys.argv)
    viewer = quarter.QuarterWidget()
    # build a scene (sphere, cube)
    plane = coin.SbPlane(coin.SbVec3f(0, 0, 1), coin.SbVec3f(0, 0, 0))
    root = coin.SoSeparator()
    myCallback = coin.SoCallback()
    cap = CapPlane(plane, root)
    myCallback.setCallback(myCallbackRoutine, cap)
    root += myCallback, coin.SoSphere()

    viewer.setSceneGraph(root)
    viewer.setBackgroundColor(coin.SbColor(.5, .5, .5))
    viewer.setWindowTitle("GL stencil buffer")

    viewer.show()

    sys.exit(app.exec_())
예제 #18
0
def viewer(scene=None,background=(1.0,1.0,1.0),lightdir=None):

    """viewer(scene=None,background=(1.0,1.0,1.0),lightdir=None): starts
    a standalone coin viewer with the contents of the given scene. You can
    give a background color, and optionally a light direction as a (x,y,z)
    tuple. In this case, a directional light will be added and shadows will
    be turned on. This might not work with some 3D drivers."""

    # Initialize Coin. This returns a main window to use
    from pivy import coin
    from pivy import sogui

    win = sogui.SoGui.init()
    if win is None:
        print("Unable to create a SoGui window")
        return

    win.setBackgroundColor(coin.SbColor(background[0],background[1],background[2]))

    if not scene:
        # build a quick default scene
        mat = coin.SoMaterial()
        mat.diffuseColor = (1.0, 0.0, 0.0)
        # Make a scene containing a red cone
        scene = coin.SoSeparator()
        scene.addChild(mat)
        scene.addChild(coin.SoCone())

    if lightdir:
        scene = embedLight(scene,lightdir)

    # ref the scene so it doesn't get garbage-collected
    scene.ref()

    # Create a viewer in which to see our scene graph
    viewer = sogui.SoGuiExaminerViewer(win)

    # Put our scene into viewer, change the title
    viewer.setSceneGraph(scene)
    viewer.setTitle("Coin viewer")
    viewer.show()

    sogui.SoGui.show(win) # Display main window
    sogui.SoGui.mainLoop()     # Main Coin event loop
예제 #19
0
    def updatePreferences(self):
        '''Callback when preferences have changed to update the visuals accordingly.'''
        self.fsze = MachinekitPreferences.hudFontSize()
        self.fnt.name = MachinekitPreferences.hudFontName()
        self.fnt.size = self.fsze

        self.mat.diffuseColor = coin.SbColor(
            MachinekitPreferences.hudFontColorUnhomed())

        size = self.view.getSize()
        ypos = 1 - (2. / size[1]) * self.fsze
        xpos = -0.98  # there's probably a smarter way, but it seems to be OK

        self.pos.translation = (xpos, ypos, 0)

        self.showWorkCoordinates = MachinekitPreferences.hudShowWorkCoordinates(
        )
        self.showMachineCoordinates = MachinekitPreferences.hudShowMachineCoordinates(
        )
예제 #20
0
def simple_quad_mesh(points, num_u, num_v, colors=None):
    msh_sep = coin.SoSeparator()
    msh = coin.SoQuadMesh()
    vertexproperty = coin.SoVertexProperty()
    vertexproperty.vertex.setValues(0, len(points), points)
    msh.verticesPerRow = num_u
    msh.verticesPerColumn = num_v
    if colors:
        vertexproperty.materialBinding = coin.SoMaterialBinding.PER_VERTEX
        for i in range(len(colors)):
            vertexproperty.orderedRGBA.set1Value(
                i,
                coin.SbColor(colors[i]).getPackedValue())
    msh.vertexProperty = vertexproperty

    shape_hint = coin.SoShapeHints()
    shape_hint.vertexOrdering = coin.SoShapeHints.COUNTERCLOCKWISE
    shape_hint.creaseAngle = np.pi / 3
    msh_sep += [shape_hint, msh]
    return msh_sep
예제 #21
0
    def __init__(self, view):
        self.view = view

        self.pos = coin.SoTranslation()

        self.mat = coin.SoMaterial()
        self.mat.diffuseColor = coin.SbColor(
            MachinekitPreferences.hudFontColorUnhomed())
        self.mat.transparency = 0

        self.fnt = coin.SoFont()

        self.txt = coin.SoText2()
        self.txt.string = 'setValues'
        self.txt.justification = coin.SoText2.LEFT

        self.sep = coin.SoSeparator()

        self.sep.addChild(self.pos)
        self.sep.addChild(self.mat)
        self.sep.addChild(self.fnt)
        self.sep.addChild(self.txt)
예제 #22
0
    def set_color(self, **kwargs):
        """Set various color attributes.

        Keyword args:
            diffuse -- diffuse color
            emissive -- emissive color
            specular -- specular color
            ambient -- ambient color

        (see Coin SoMaterial documentation for more details)
        """
        for key, value in kwargs.items():
            color = coin.SbColor(value)
            if key == "diffuse":
                attribute = self.material.diffuseColor
            elif key == "emissive":
                attribute = self.material.emissiveColor
            elif key == "specular":
                attribute = self.material.specularColor
            elif key == "ambient":
                attribute = self.material.ambientColor
            else:
                raise KeyError("Unknown color attribute")
            attribute.setValue(color)
예제 #23
0
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)
예제 #24
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)
예제 #25
0
    def __init__(self):
        super(gridNode, self).__init__()

        self.vec = coin.SoTransformVec3f()
        #self.vec.matrix.connectFrom(cam.orientation)
        self.vec.vector = coin.SbVec3f(0, 0, -1)

        self.calc = coin.SoCalculator()
        self.calc.A.connectFrom(self.vec.direction)
        self.calc.expression.set1Value(0, "ta=0.5")  # maxviz
        self.calc.expression.set1Value(1, "tb=20.0")  # factor
        self.calc.expression.set1Value(2, "tA=vec3f(1,0,0)")  # plane normal
        self.calc.expression.set1Value(3, "tc=dot(A,tA)")
        self.calc.expression.set1Value(4, "td=fabs(tc)")
        self.calc.expression.set1Value(5, "oa=1.0-ta*pow(td,tb)")
        self.calc.expression.set1Value(6, "oA=vec3f(oa,0,0)")

        self.scaleEngine = coin.SoCalculator()
        #self.scaleEngine.a.connectFrom(cam.height)
        self.scaleEngine.expression.set1Value(0, "ta=floor(log10(a/10))")
        self.scaleEngine.expression.set1Value(1, "tb=pow(10,ta)")
        self.scaleEngine.expression.set1Value(2, "oA=vec3f(tb,tb,tb)")
        self.scaleEngine.expression.set1Value(3, "oa=0.01*a/tb")

        self.calc2 = coin.SoCalculator()
        self.calc2.a.connectFrom(self.scaleEngine.oa)
        self.calc2.b.connectFrom(self.calc.oa)
        self.calc2.expression.set1Value(0, "ta=pow(a,0.3)")
        self.calc2.expression.set1Value(1, "oa=(b>ta)?b:ta")

        self.material1 = coin.SoMaterial()
        self.material2 = coin.SoMaterial()
        self.material3 = coin.SoMaterial()
        self.material4 = coin.SoMaterial()
        self.coord = coin.SoCoordinate3()
        self.coord2 = coin.SoCoordinate3()
        self.line1 = coin.SoIndexedLineSet()
        self.line2 = coin.SoIndexedLineSet()
        self.lineSet = coin.SoIndexedLineSet()
        self.lineSet2 = coin.SoIndexedLineSet()

        self.miniscale = coin.SoScale()
        self.miniscale.scaleFactor = coin.SbVec3f(0.1, 0.1, 0.1)

        self.mainscale = coin.SoScale()
        self.mainscale.scaleFactor.connectFrom(self.scaleEngine.oA)

        self.addChild(self.mainscale)
        self.addChild(self.coord)
        self.addChild(self.material1)
        self.addChild(self.line1)
        self.addChild(self.material2)
        self.addChild(self.line2)
        self.addChild(self.material3)
        self.addChild(self.lineSet)
        self.addChild(self.miniscale)
        self.addChild(self.material4)
        self.addChild(self.coord2)
        self.addChild(self.lineSet2)

        self._vector1 = coin.SbVec3f(1, 0, 0)
        self._vector2 = coin.SbVec3f(0, 1, 0)
        self.normal = self._vector1.cross(self._vector2)

        self._mainDim = 100
        self._subDim = 10
        self._maxviz = 1.0
        self._factor = 1.0

        self._numGridLines = 4
        self.material1.diffuseColor = coin.SbColor(1, 0, 0)
        self.material2.diffuseColor = coin.SbColor(0, 1, 0)
        self.material3.diffuseColor = coin.SbColor(0.5, 0.5, 0.5)
        self.material4.diffuseColor = coin.SbColor(0.5, 0.5, 0.5)
        self.material3.transparency.connectFrom(self.calc.oa)
        self.material4.transparency.connectFrom(self.calc2.oa)
예제 #26
0
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
예제 #27
0
def mkshadow(sgg,lis):

	rGrp=FreeCAD.ParamGet('User parameter:BaseApp/Preferences/View')
	atr="HeadlightIntensity"
	v=rGrp.GetInt(atr)

	#set headlight on
	rGrp.SetInt(atr,100)

	# or off
	rGrp.SetInt(atr,0)

	# myCustomNode=Gui.ActiveDocument.ActiveView.getSceneGraph()


	sggs=sgg.getChildren()
	cs=[c.copy() for c in sggs]
	for i in range(len(cs)):
		sgg.removeChild(0)


	sotype=coin.SoType.fromName("ShadowGroup")
	sg=sotype.createInstance()
	sg.getTypeId().getName()
	sg.quality=1

	sgg.insertChild(sg,0)
	ss=sg


	ff=0.5

	if 0:
		l=coin.SoSpotLight()
		l.direction.setValue(coin.SbVec3f(-20,10,-300))
		l.color.setValue(coin.SbColor(ff*random.random(),ff*random.random(),ff*random.random()))
		l.location.setValue(coin.SbVec3f(0,0,300))
		l.cutOffAngle.setValue(0.4)
		l.dropOffRate.setValue(0.)
		ss.insertChild(l,0)

		l=coin.SoSpotLight()
		l.direction.setValue(coin.SbVec3f(0,0,-300))
		l.color.setValue(coin.SbColor(ff*random.random(),ff*random.random(),ff*random.random()))
		l.location.setValue(coin.SbVec3f(0,0,300))
		l.cutOffAngle.setValue(0.4)
		l.dropOffRate.setValue(0.)
		ss.insertChild(l,0)


		l=coin.SoSpotLight()
		l.direction.setValue(coin.SbVec3f(10,20,-300))
		l.color.setValue(coin.SbColor(1,0,0))
		l.color.setValue(coin.SbColor(ff*random.random(),ff*random.random(),ff*random.random()))
		l.location.setValue(coin.SbVec3f(50,10,300))
		l.cutOffAngle.setValue(.35)
		l.dropOffRate.setValue(0.)
		ss.insertChild(l,0)

	else:
		for lig in lis:
			ss.insertChild(lig,0)

	ll=len(cs)
	for i in range(len(cs)):
		sotype=coin.SoType.fromName("SoShadowStyle")
		inst=sotype.createInstance()
		print inst.getTypeId().getName() # => ShadowStyle
		inst.style=3
		ss.insertChild(inst,0)
		ss.addChild(cs[ll-1-i])


	Gui.SendMsgToActiveView("ViewFit")


	print "children von sg"
	ssc=sg.getChildren()
	for c in ssc:
		print c
예제 #28
0
	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()
예제 #29
0
 def colorForColorValue(val):
     v = [((val >> n) & 0xff) / 255. for n in [24, 16, 8, 0]]
     return coin.SbColor(v[0], v[1], v[2])
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