Example #1
0
def create3DText(center, radius):
    

    geode = osg.Geode()

####################################################
#    
# Examples of how to set up axis/orientation alignments
#

    characterSize = radius*0.2
    characterDepth = characterSize*0.2
    
    pos = osg.Vec3(center.x()-radius*.5,center.y()-radius*.5,center.z()-radius*.5)

    text1 = osgText.Text3D()
    text1.setFont("fonts/arial.ttf")
    text1.setCharacterSize(characterSize)
    text1.setCharacterDepth(characterDepth)
    text1.setPosition(pos)
    text1.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text1.setAxisAlignment(osgText.Text3D.XY_PLANE)
    text1.setText("XY_PLANE")
    geode.addDrawable(text1)

    text2 = osgText.Text3D()
    text2.setFont("fonts/times.ttf")
    text2.setCharacterSize(characterSize)
    text2.setCharacterDepth(characterDepth)
    text2.setPosition(pos)
    text2.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text2.setAxisAlignment(osgText.Text3D.YZ_PLANE)
    text2.setText("YZ_PLANE")
    geode.addDrawable(text2)

    text3 = osgText.Text3D()
    text3.setFont("fonts/dirtydoz.ttf")
    text3.setCharacterSize(characterSize)
    text3.setCharacterDepth(characterDepth)
    text3.setPosition(pos)
    text3.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text3.setAxisAlignment(osgText.Text3D.XZ_PLANE)
    text3.setText("XZ_PLANE")
    geode.addDrawable(text3)

    style = osgText.Style()
    bevel = osgText.Bevel()
    bevel.roundedBevel2(0.25)
    style.setBevel(bevel)
    style.setWidthRatio(0.4)

    text7 = osgText.Text3D()
    text7.setFont("fonts/times.ttf")
    text7.setStyle(style)
    text7.setCharacterSize(characterSize)
    text7.setCharacterDepth(characterSize*0.2)
    text7.setPosition(center - osg.Vec3(0.0, 0.0, 0.6))
    text7.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text7.setAxisAlignment(osgText.Text3D.SCREEN)
    text7.setCharacterSizeMode(osgText.Text3D.OBJECT_COORDS)
    text7.setText("CharacterSizeMode OBJECT_COORDS (default)")
    geode.addDrawable(text7)

    shape = osg.ShapeDrawable(osg.Sphere(center,characterSize*0.2))
    shape.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.ON)
    geode.addDrawable(shape)

    rootNode = osg.Group()
    rootNode.addChild(geode)

    front = osg.Material()
    front.setAlpha(osg.Material.FRONT_AND_BACK,1)
    front.setAmbient(osg.Material.FRONT_AND_BACK,osg.Vec4(0.2,0.2,0.2,1.0))
    front.setDiffuse(osg.Material.FRONT_AND_BACK,osg.Vec4(.0,.0,1.0,1.0))
    rootNode.getOrCreateStateSet().setAttributeAndModes(front)
    
    
    return rootNode    
Example #2
0
def createHUDText():

    

    rootNode = osg.Group()

    font = osgText.Font(osgQt.QFontImplementation(QFont("Arial")))

    geode = osg.Geode()
    rootNode.addChild(geode)

    windowHeight = 1024.0
    windowWidth = 1280.0
    margin = 50.0


####################################################
#    
# Examples of how to set up different text layout
#

    layoutColor = osg.Vec4(1.0,1.0,0.0,1.0)
    layoutCharacterSize = 20.0    
    
        text = osgText.Text()
        text.setFont(font)
        text.setColor(layoutColor)
        text.setCharacterSize(layoutCharacterSize)
        text.setPosition(osg.Vec3(margin,windowHeight-margin,0.0))

        # the default layout is left to right, typically used in languages
        # originating from europe such as English, French, German, Spanish etc..
        text.setLayout(osgText.Text.LEFT_TO_RIGHT)

        text.setText("text.setLayout(osgText.Text.LEFT_TO_RIGHT)")
        geode.addDrawable(text)

        text = osgText.Text()
        text.setFont(font)
        text.setColor(layoutColor)
        text.setCharacterSize(layoutCharacterSize)
        text.setPosition(osg.Vec3(windowWidth-margin,windowHeight-margin,0.0))

        # right to left layouts would be used for hebrew or arabic fonts.
        text.setLayout(osgText.Text.RIGHT_TO_LEFT)
        text.setAlignment(osgText.Text.RIGHT_BASE_LINE)

        text.setText("text.setLayout(osgText.Text.RIGHT_TO_LEFT)")
        geode.addDrawable(text)

        text = osgText.Text()
        text.setFont(font)
        text.setColor(layoutColor)
        text.setPosition(osg.Vec3(margin,windowHeight-margin,0.0))
        text.setCharacterSize(layoutCharacterSize)

        # vertical font layout would be used for asian fonts.
        text.setLayout(osgText.Text.VERTICAL)

        text.setText("text.setLayout(osgText.Text.VERTICAL)")
        geode.addDrawable(text)
Example #3
0
def createDemoScene(fixedSizeInScreen):

    
 
    root = osg.Group()

    geode_1 = osg.Geode()
    transform_1 = osg.MatrixTransform()

    geode_2 = osg.Geode()
    transform_2 = osg.MatrixTransform()

    geode_3 = osg.Geode()
    transform_3 = osg.MatrixTransform()

    geode_4 = osg.Geode()
    transform_4 = osg.MatrixTransform()

    geode_5 = osg.Geode()
    transform_5 = osg.MatrixTransform()

    geode_6 = osg.Geode()
    transform_6 = osg.MatrixTransform()

    geode_7 = osg.Geode()
    transform_7 = osg.MatrixTransform()

 



    radius = 0.8
    height = 1.0
    hints = osg.TessellationHints()
    hints.setDetailRatio(2.0)
    shape = osg.ShapeDrawable()

    shape = osg.ShapeDrawable(osg.Box(osg.Vec3(0.0, 0.0, -2.0), 10, 10.0, 0.1), hints)
    shape.setColor(osg.Vec4(0.5, 0.5, 0.7, 1.0))
    geode_1.addDrawable(shape)

    shape = osg.ShapeDrawable(osg.Cylinder(osg.Vec3(0.0, 0.0, 0.0), radius * 2,radius), hints)
    shape.setColor(osg.Vec4(0.8, 0.8, 0.8, 1.0))
    geode_2.addDrawable(shape)

    shape = osg.ShapeDrawable(osg.Cylinder(osg.Vec3(-3.0, 0.0, 0.0), radius,radius), hints)
    shape.setColor(osg.Vec4(0.6, 0.8, 0.8, 1.0))
    geode_3.addDrawable(shape)

    shape = osg.ShapeDrawable(osg.Cone(osg.Vec3(3.0, 0.0, 0.0), 2 * radius,radius), hints)
    shape.setColor(osg.Vec4(0.4, 0.9, 0.3, 1.0))
    geode_4.addDrawable(shape)

    shape = osg.ShapeDrawable(osg.Cone(osg.Vec3(0.0, -3.0, 0.0), radius, height), hints)
    shape.setColor(osg.Vec4(0.2, 0.5, 0.7, 1.0))
    geode_5.addDrawable(shape)

    shape = osg.ShapeDrawable(osg.Cylinder(osg.Vec3(0.0, 3.0, 0.0), radius, height), hints)
    shape.setColor(osg.Vec4(1.0, 0.3, 0.3, 1.0))
    geode_6.addDrawable(shape)

    shape = osg.ShapeDrawable(osg.Cone(osg.Vec3(0.0, 0.0, 3.0), 2.0, 2.0), hints)
    shape.setColor(osg.Vec4(0.8, 0.8, 0.4, 1.0))
    geode_7.addDrawable(shape)






    # material
    matirial = osg.Material()
    matirial.setColorMode(osg.Material.DIFFUSE)
    matirial.setAmbient(osg.Material.FRONT_AND_BACK, osg.Vec4(0, 0, 0, 1))
    matirial.setSpecular(osg.Material.FRONT_AND_BACK, osg.Vec4(1, 1, 1, 1))
    matirial.setShininess(osg.Material.FRONT_AND_BACK, 64.0)
    root.getOrCreateStateSet().setAttributeAndModes(matirial, osg.StateAttribute.ON)

    transform_1.addChild(addDraggerToScene(geode_1,"TabBoxDragger",fixedSizeInScreen))
    transform_2.addChild(addDraggerToScene(geode_2,"TabPlaneDragger",fixedSizeInScreen))
    transform_3.addChild(addDraggerToScene(geode_3,"TabBoxTrackballDragger",fixedSizeInScreen))
    transform_4.addChild(addDraggerToScene(geode_4,"TrackballDragger",fixedSizeInScreen))
    transform_5.addChild(addDraggerToScene(geode_5,"Translate1DDragger",fixedSizeInScreen))
    transform_6.addChild(addDraggerToScene(geode_6,"Translate2DDragger",fixedSizeInScreen))
    transform_7.addChild(addDraggerToScene(geode_7,"TranslateAxisDragger",fixedSizeInScreen))

    root.addChild(transform_1)
    root.addChild(transform_2)
    root.addChild(transform_3)
    root.addChild(transform_4)
    root.addChild(transform_5)
    root.addChild(transform_6)
    root.addChild(transform_7)

 
 
    return root
Example #4
0
def main(argv):

    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    # read the scene from the list of file specified commandline args.
    scene = osgDB.readNodeFiles(arguments)

    if  not scene  and  arguments.read("--relative-camera-scene") :
        # Create a test scene with a camera that has a relative reference frame.
        group = osg.Group()

        sphere = osg.Geode()
        sphere.setName("Sphere")
        sphere.addDrawable(osg.ShapeDrawable(osg.Sphere()))

        cube = osg.Geode()
        cube.setName("Cube")
        cube.addDrawable(osg.ShapeDrawable(osg.Box()))

        camera = osg.Camera()
        camera.setRenderOrder(osg.Camera.POST_RENDER)
        camera.setClearMask(GL_DEPTH_BUFFER_BIT)
        camera.setReferenceFrame(osg.Transform.RELATIVE_RF)
        camera.setViewMatrix(osg.Matrix.translate(-2, 0, 0))

        xform = osg.MatrixTransform(osg.Matrix.translate(1, 1, 1))
        xform.addChild(camera)

        group.addChild(sphere)
        group.addChild(xform)
        camera.addChild(cube)

        scene = group

    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not scene : scene = osgDB.readNodeFile("fountain.osgt")

    group = dynamic_cast<osg.Group*>(scene)
    if  not group :
        group = osg.Group()
        group.addChild(scene)

    updateText = osgText.Text()

    # add the HUD subgraph.
    group.addChild(createHUD(updateText))

    if arguments.read("--CompositeViewer") :
        view = osgViewer.View()
        # add the handler for doing the picking
        view.addEventHandler(PickHandler(updateText))

        # set the scene to render
        view.setSceneData(group)

        view.setUpViewAcrossAllScreens()

        viewer = osgViewer.CompositeViewer()
        viewer.addView(view)

        return viewer.run()

    else:
        viewer = osgViewer.Viewer()


        # add all the camera manipulators
            keyswitchManipulator = osgGA.KeySwitchMatrixManipulator()

            keyswitchManipulator.addMatrixManipulator( ord("1"), "Trackball", osgGA.TrackballManipulator() )
            keyswitchManipulator.addMatrixManipulator( ord("2"), "Flight", osgGA.FlightManipulator() )
            keyswitchManipulator.addMatrixManipulator( ord("3"), "Drive", osgGA.DriveManipulator() )

            num = keyswitchManipulator.getNumMatrixManipulators()
            keyswitchManipulator.addMatrixManipulator( ord("4"), "Terrain", osgGA.TerrainManipulator() )

            pathfile = str()
            keyForAnimationPath = ord("5")
            while arguments.read("-p",pathfile) :
                apm = osgGA.AnimationPathManipulator(pathfile)
                if apm  or   not apm.valid() :
                    num = keyswitchManipulator.getNumMatrixManipulators()
                    keyswitchManipulator.addMatrixManipulator( keyForAnimationPath, "Path", apm )
                    ++keyForAnimationPath

            keyswitchManipulator.selectMatrixManipulator(num)

            viewer.setCameraManipulator( keyswitchManipulator )

        # add the handler for doing the picking
        viewer.addEventHandler(PickHandler(updateText))

        # set the scene to render
        viewer.setSceneData(group)

        return viewer.run()
Example #5
0
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_TOP,"text.setAlignment(\nosgText.Text.RIGHT_TOP)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_CENTER,"text.setAlignment(\nosgText.Text.RIGHT_CENTER)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_BOTTOM,"text.setAlignment(\nosgText.Text.RIGHT_BOTTOM)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.LEFT_BASE_LINE,"text.setAlignment(\nosgText.Text.LEFT_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.CENTER_BASE_LINE,"text.setAlignment(\nosgText.Text.CENTER_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_BASE_LINE,"text.setAlignment(\nosgText.Text.RIGHT_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.LEFT_BOTTOM_BASE_LINE,"text.setAlignment(\nosgText.Text.LEFT_BOTTOM_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.CENTER_BOTTOM_BASE_LINE,"text.setAlignment(\nosgText.Text.CENTER_BOTTOM_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_BOTTOM_BASE_LINE,"text.setAlignment(\nosgText.Text.RIGHT_BOTTOM_BASE_LINE)"))


    sequence = osg.Sequence()
        for(AlignmentList.iterator itr=alignmentList.begin()
            not = alignmentList.end()
            ++itr)
            alignmentGeode = osg.Geode()
            sequence.addChild(alignmentGeode)
            sequence.setTime(sequence.getNumChildren(), 1.0)

            text = osgText.Text()
            text.setFont(font)
            text.setColor(alignmentSizeColor)
            text.setCharacterSize(alignmentCharacterSize)
            text.setPosition(cursor)
            text.setDrawMode(osgText.Text.TEXT|osgText.Text.ALIGNMENT|osgText.Text.BOUNDINGBOX)
            
            text.setAlignment(itr.first)
            text.setText(itr.second)
            
            alignmentGeode.addDrawable(text)
def setDomeCorrection(viewer, arguments):

    

    wsi = osg.GraphicsContext.getWindowingSystemInterface()
    if  not wsi :
        osg.notify(osg.NOTICE), "Error, no WindowSystemInterface available, cannot create windows."
        return

    unsigned int width, height
    wsi.getScreenResolution(osg.GraphicsContext.ScreenIdentifier(0), width, height)

    while arguments.read("--width",width) : 
    while arguments.read("--height",height) : 

    traits = osg.GraphicsContext.Traits()
    traits.x = 0
    traits.y = 0
    traits.width = width
    traits.height = height
    traits.windowDecoration = False
    traits.doubleBuffer = True
    traits.sharedContext = 0



    gc = osg.GraphicsContext.createGraphicsContext(traits)
    if  not gc :
        osg.notify(osg.NOTICE), "GraphicsWindow has not been created successfully."
        return

    tex_width = 512
    tex_height = 512

    camera_width = tex_width
    camera_height = tex_height

    texture = osg.TextureCubeMap()

    texture.setTextureSize(tex_width, tex_height)
    texture.setInternalFormat(GL_RGB)
    texture.setFilter(osg.Texture.MIN_FILTER,osg.Texture.LINEAR)
    texture.setFilter(osg.Texture.MAG_FILTER,osg.Texture.LINEAR)

#if 0
    renderTargetImplementation = osg.Camera.SEPERATE_WINDOW
    buffer = GL_FRONT
#else:
    renderTargetImplementation = osg.Camera.FRAME_BUFFER_OBJECT
    buffer = GL_FRONT
#endif

    # front face
        camera = osg.Camera()
        camera.setName("Front face camera")
        camera.setGraphicsContext(gc)
        camera.setViewport(osg.Viewport(0,0,camera_width, camera_height))
        camera.setDrawBuffer(buffer)
        camera.setReadBuffer(buffer)
        camera.setAllowEventFocus(False)
        # tell the camera to use OpenGL frame buffer object where supported.
        camera.setRenderTargetImplementation(renderTargetImplementation)

        # attach the texture and use it as the color buffer.
        camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.POSITIVE_Y)

        viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd())


    # top face
        camera = osg.Camera()
        camera.setName("Top face camera")
        camera.setGraphicsContext(gc)
        camera.setViewport(osg.Viewport(0,0,camera_width, camera_height))
        buffer =  GL_BACK if (traits.doubleBuffer) else  GL_FRONT
        camera.setDrawBuffer(buffer)
        camera.setReadBuffer(buffer)
        camera.setAllowEventFocus(False)

        # tell the camera to use OpenGL frame buffer object where supported.
        camera.setRenderTargetImplementation(renderTargetImplementation)

        # attach the texture and use it as the color buffer.
        camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.POSITIVE_Z)

        viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(-90.0), 1.0,0.0,0.0))

    # left face
        camera = osg.Camera()
        camera.setName("Left face camera")
        camera.setGraphicsContext(gc)
        camera.setViewport(osg.Viewport(0,0,camera_width, camera_height))
        camera.setDrawBuffer(buffer)
        camera.setReadBuffer(buffer)
        camera.setAllowEventFocus(False)

        # tell the camera to use OpenGL frame buffer object where supported.
        camera.setRenderTargetImplementation(renderTargetImplementation)

        # attach the texture and use it as the color buffer.
        camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.NEGATIVE_X)

        viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(-90.0), 0.0,1.0,0.0) * osg.Matrixd.rotate(osg.inDegrees(-90.0), 0.0,0.0,1.0))

    # right face
        camera = osg.Camera()
        camera.setName("Right face camera")
        camera.setGraphicsContext(gc)
        camera.setViewport(osg.Viewport(0,0,camera_width, camera_height))
        camera.setDrawBuffer(buffer)
        camera.setReadBuffer(buffer)
        camera.setAllowEventFocus(False)

        # tell the camera to use OpenGL frame buffer object where supported.
        camera.setRenderTargetImplementation(renderTargetImplementation)

        # attach the texture and use it as the color buffer.
        camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.POSITIVE_X)

        viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(90.0), 0.0,1.0,0.0 ) * osg.Matrixd.rotate(osg.inDegrees(90.0), 0.0,0.0,1.0))

    # bottom face
        camera = osg.Camera()
        camera.setGraphicsContext(gc)
        camera.setName("Bottom face camera")
        camera.setViewport(osg.Viewport(0,0,camera_width, camera_height))
        camera.setDrawBuffer(buffer)
        camera.setReadBuffer(buffer)
        camera.setAllowEventFocus(False)

        # tell the camera to use OpenGL frame buffer object where supported.
        camera.setRenderTargetImplementation(renderTargetImplementation)

        # attach the texture and use it as the color buffer.
        camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.NEGATIVE_Z)

        viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(90.0), 1.0,0.0,0.0) * osg.Matrixd.rotate(osg.inDegrees(180.0), 0.0,0.0,1.0))

    # back face
        camera = osg.Camera()
        camera.setName("Back face camera")
        camera.setGraphicsContext(gc)
        camera.setViewport(osg.Viewport(0,0,camera_width, camera_height))
        camera.setDrawBuffer(buffer)
        camera.setReadBuffer(buffer)
        camera.setAllowEventFocus(False)

        # tell the camera to use OpenGL frame buffer object where supported.
        camera.setRenderTargetImplementation(renderTargetImplementation)

        # attach the texture and use it as the color buffer.
        camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.NEGATIVE_Y)

        viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(180.0), 1.0,0.0,0.0))

    viewer.getCamera().setProjectionMatrixAsPerspective(90.0, 1.0, 1, 1000.0)



    # distortion correction set up.
        geode = osg.Geode()
        geode.addDrawable(createDomeDistortionMesh(osg.Vec3(0.0,0.0,0.0), osg.Vec3(width,0.0,0.0), osg.Vec3(0.0,height,0.0), arguments))

        # we need to add the texture to the mesh, we do so by creating a
        # StateSet to contain the Texture StateAttribute.
        stateset = geode.getOrCreateStateSet()
        stateset.setTextureAttributeAndModes(0, texture,osg.StateAttribute.ON)
        stateset.setMode(GL_LIGHTING,osg.StateAttribute.OFF)

        camera = osg.Camera()
        camera.setGraphicsContext(gc)
        camera.setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT )
        camera.setClearColor( osg.Vec4(0.1,0.1,1.0,1.0) )
        camera.setViewport(osg.Viewport(0, 0, width, height))
        buffer =  GL_BACK if (traits.doubleBuffer) else  GL_FRONT
        camera.setDrawBuffer(buffer)
        camera.setReadBuffer(buffer)
        camera.setReferenceFrame(osg.Camera.ABSOLUTE_RF)
        camera.setAllowEventFocus(False)
        #camera.setInheritanceMask(camera.getInheritanceMask()  ~osg.CullSettings.CLEAR_COLOR  ~osg.CullSettings.COMPUTE_NEAR_FAR_MODE)
        #camera.setComputeNearFarMode(osg.CullSettings.DO_NOT_COMPUTE_NEAR_FAR)

        camera.setProjectionMatrixAsOrtho2D(0,width,0,height)
        camera.setViewMatrix(osg.Matrix.identity())

        # add subgraph to render
        camera.addChild(geode)

        camera.setName("DistortionCorrectionCamera")

        viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd(), False)

    viewer.getCamera().setNearFarRatio(0.0001)
Example #7
0
def createHUD():


    
    # create a camera to set up the projection and model view matrices, and the subgraph to draw in the HUD
    camera = osg.Camera()

    # set the projection matrix
    camera.setProjectionMatrix(osg.Matrix.ortho2D(0,1280,0,1024))

    # set the view matrix
    camera.setReferenceFrame(osg.Transform.ABSOLUTE_RF)
    camera.setViewMatrix(osg.Matrix.identity())

    # only clear the depth buffer
    camera.setClearMask(GL_DEPTH_BUFFER_BIT)

    # draw subgraph after main camera view.
    camera.setRenderOrder(osg.Camera.POST_RENDER)

    # we don't want the camera to grab event focus from the viewers main camera(s).
    camera.setAllowEventFocus(False)



    # add to this camera a subgraph to render

        geode = osg.Geode()

        timesFont = str("fonts/arial.ttf")

        # turn lighting off for the text and disable depth test to ensure it's always ontop.
        stateset = geode.getOrCreateStateSet()
        stateset.setMode(GL_LIGHTING,osg.StateAttribute.OFF)

        position = osg.Vec3(150.0,800.0,0.0)
        delta = osg.Vec3(0.0,-120.0,0.0)

            text = osgText.Text()
            geode.addDrawable( text )

            text.setFont(timesFont)
            text.setPosition(position)
            text.setText("Head Up Displays are simple :-)")

            position += delta


            text = osgText.Text()
            geode.addDrawable( text )

            text.setFont(timesFont)
            text.setPosition(position)
            text.setText("All you need to do is create your text in a subgraph.")

            position += delta


            text = osgText.Text()
            geode.addDrawable( text )

            text.setFont(timesFont)
            text.setPosition(position)
            text.setText("Then place an osg.Camera above the subgraph\n"
                          "to create an orthographic projection.\n")

            position += delta

            text = osgText.Text()
            geode.addDrawable( text )

            text.setFont(timesFont)
            text.setPosition(position)
            text.setText("Set the Camera's ReferenceFrame to ABSOLUTE_RF to ensure\n"
                          "it remains independent from any external model view matrices.")

            position += delta

            text = osgText.Text()
            geode.addDrawable( text )

            text.setFont(timesFont)
            text.setPosition(position)
            text.setText("And set the Camera's clear mask to just clear the depth buffer.")

            position += delta

            text = osgText.Text()
            geode.addDrawable( text )

            text.setFont(timesFont)
            text.setPosition(position)
            text.setText("And finally set the Camera's RenderOrder to POST_RENDER\n"
                          "to make sure it's drawn last.")

            position += delta


            bb = osg.BoundingBox()
            for(unsigned int i=0i<geode.getNumDrawables()++i)
                bb.expandBy(geode.getDrawable(i).getBound())
#*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#*  THE SOFTWARE.
#

#include "Frame.h"

#include <osgText/Text>

namespace osgfxbrowser 

Frame.Frame()
:    osg.Geode(),
    bgcolor_(0.5, 0.5, 0.5, 1.0),
    rect_(0, 0, 100, 100),
    caption_("Frame")

Frame.Frame( Frame copy,  osg.CopyOp copyop)
:    osg.Geode(copy, copyop),
    bgcolor_(copy.bgcolor_),
    rect_(copy.rect_),
    caption_(copy.caption_)

void Frame.rebuild()
    zPos = -0.1

    removeDrawables(0, getNumDrawables())
    addDrawable(build_quad(rect_, bgcolor_))
Example #9
0
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_TOP,"text.setAlignment(\nosgText.Text.RIGHT_TOP)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_CENTER,"text.setAlignment(\nosgText.Text.RIGHT_CENTER)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_BOTTOM,"text.setAlignment(\nosgText.Text.RIGHT_BOTTOM)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.LEFT_BASE_LINE,"text.setAlignment(\nosgText.Text.LEFT_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.CENTER_BASE_LINE,"text.setAlignment(\nosgText.Text.CENTER_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_BASE_LINE,"text.setAlignment(\nosgText.Text.RIGHT_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.LEFT_BOTTOM_BASE_LINE,"text.setAlignment(\nosgText.Text.LEFT_BOTTOM_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.CENTER_BOTTOM_BASE_LINE,"text.setAlignment(\nosgText.Text.CENTER_BOTTOM_BASE_LINE)"))
    alignmentList.push_back(AlignmentPair(osgText.Text.RIGHT_BOTTOM_BASE_LINE,"text.setAlignment(\nosgText.Text.RIGHT_BOTTOM_BASE_LINE)"))


    sequence = osg.Sequence()
        for(AlignmentList.iterator itr=alignmentList.begin()
            not = alignmentList.end()
            ++itr)
            alignmentGeode = osg.Geode()
            sequence.addChild(alignmentGeode)
            sequence.setTime(sequence.getNumChildren(), 1.0)

            text = osgText.Text()
            text.setFont(font)
            text.setColor(alignmentSizeColor)
            text.setCharacterSize(alignmentCharacterSize)
            text.setPosition(cursor)
            text.setDrawMode(osgText.Text.TEXT|osgText.Text.ALIGNMENT|osgText.Text.BOUNDINGBOX)
            
            text.setAlignment(itr.first)
            text.setText(itr.second)
            
            alignmentGeode.addDrawable(text)
def main(argv):

    
    arguments = osg.ArgumentParser( argc, argv )
    
    textureFile = str("Images/smoke.rgb")
    while  arguments.read("--texture", textureFile)  : 
    
    pointSize = 20.0
    while  arguments.read("--point", pointSize)  : 
    
    visibilityDistance = -1.0
    while  arguments.read("--visibility", visibilityDistance)  : 
    
    customShape = False
    while  arguments.read("--enable-custom")  :  customShape = True 
    
    useShaders = True
    while  arguments.read("--disable-shaders")  :  useShaders = False 
    
    #**
#    Customize particle template and system attributes
#    **
    ps = osgParticle.ParticleSystem()
    
    ps.getDefaultParticleTemplate().setLifeTime( 5.0 )
    
    if  customShape  :
        # osgParticle now supports making use of customized drawables. The draw() method will be executed
        # and display lists will be called for each particle. It is always a huge consumption of memory, and
        # hardly to use shaders to render them, so please be careful using this feature.
        ps.getDefaultParticleTemplate().setShape( osgParticle.Particle.USER )
        ps.getDefaultParticleTemplate().setDrawable( osg.ShapeDrawable(osg.Box(osg.Vec3(), 1.0)) )
        useShaders = False
    else:
        # The shader only supports rendering points at present.
        ps.getDefaultParticleTemplate().setShape( osgParticle.Particle.POINT )
    
    # Set the visibility distance of particles, due to their Z-value in the eye coordinates.
    # Particles that are out of the distance (or behind the eye) will not be rendered.
    ps.setVisibilityDistance( visibilityDistance )
    
    if  useShaders  :
        # Set using local GLSL shaders to render particles.
        # At present, this is slightly efficient than ordinary methods. The bottlenack here seems to be the cull
        # traversal time. Operators go through the particle list again and again...
        ps.setDefaultAttributesUsingShaders( textureFile, True, 0 )
    else:
        # The default methods uses glBegin()/glEnd() pairs. Fortunately the GLBeginEndAdapter does improve the
        # process, which mimics the immediate mode with glDrawArrays().
        ps.setDefaultAttributes( textureFile, True, False, 0 )
        
        # Without the help of shaders, we have to sort particles to make the visibility distance work. Sorting is
        # also useful in rendering transparent particles in back-to-front order.
        if  visibilityDistance>0.0  :
            ps.setSortMode( osgParticle.ParticleSystem.SORT_BACK_TO_FRONT )
    
    # At last, to make the point sprite work, we have to set the points size and the sprite attribute.
    stateset = ps.getOrCreateStateSet()
    stateset.setAttribute( osg.Point(pointSize) )
    stateset.setTextureAttributeAndModes( 0, osg.PointSprite, osg.StateAttribute.ON )()
    
    #**
#    Construct other particle system elements, including the emitter and program
#    **
    emitter = osgParticle.ModularEmitter()
    emitter.setParticleSystem( ps )
    
    program = osgParticle.ModularProgram()
    program.setParticleSystem( ps )
    
    createFountainEffect( emitter, program )
    
    #**
#    Add the entire particle system to the scene graph
#    **
    parent = osg.MatrixTransform()
    parent.addChild( emitter )
    parent.addChild( program )
    
    # The updater can receive particle systems as child drawables now. The addParticleSystem() method
    # is still usable, with which we should define another geode to contain a particle system.
    updater = osgParticle.ParticleSystemUpdater()
    #updater.addDrawable( ps )
    
    root = osg.Group()
    root.addChild( parent )
    root.addChild( updater )
    
    # FIXME 2010.9.19: the updater can't be a drawable otehrwise the ParticleEffect will not work properly. why?
    updater.addParticleSystem( ps )
    
    geode = osg.Geode()
    geode.addDrawable( ps )
    root.addChild( geode )
    
    #**
#    Start the viewer
#    **
    viewer = osgViewer.Viewer()
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
    viewer.addEventHandler( osgViewer.StatsHandler )()
    viewer.addEventHandler( osgViewer.WindowSizeHandler )()
    viewer.setSceneData( root )
    viewer.setCameraManipulator( osgGA.TrackballManipulator )()
    
    # A floating error of delta-time should be explained here:
    # The particles emitter, program and updater all use a 'dt' to compute the time value in every frame.
    # Because the 'dt' is a double value, it is not suitable to keep three copies of it seperately, which
    # is the previous implementation. The small error makes some opeartors unable to work correctly, e.g.
    # the BounceOperator.
    # Now we make use of the getDeltaTime() of ParticleSystem to maintain and dispatch the delta time. But..
    # it is not the best solution so far, since there are still very few particles acting unexpectedly.
    return viewer.run()
    
    # FIXME 2010.9.19: At present, getDeltaTime() is not used and the implementations in the updater and processors still
    # use a (t - _t0) as the delta time, which is of course causing floating errors. ParticleEffect will not work if we
    # replace the delta time with getDeltaTime()... Need to find a solution.


if __name__ == "__main__":
    main(sys.argv)
Example #11
0
      colours = osg.Vec4Array(1)
      (*colours)[0] = osg.Vec4d(1.0,0.0,0.0,1.0)
      axes.setColorArray(colours, osg.Array.BIND_OVERALL)
      coords = osg.Vec3Array(6)
      (*coords)[0].set(osg.Vec3d(0.0, 0.0, 0.0))
      (*coords)[1].set(osg.Vec3d(0.5, 0.0, 0.0))
      (*coords)[2].set(osg.Vec3d(0.0, 0.0, 0.0))
      (*coords)[3].set(osg.Vec3d(0.0, 0.5, 0.0))
      (*coords)[4].set(osg.Vec3d(0.0, 0.0, 0.0))
      (*coords)[5].set(osg.Vec3d(0.0, 0.0, 0.5))
      axes.setVertexArray(coords)
      axes.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.OFF)
      axes.addPrimitiveSet(osg.DrawArrays(osg.PrimitiveSet.LINES,0,6))

    # Earth orbit
    earthOrbitGeode = osg.Geode()
    earthOrbitGeode.addDrawable(unitCircle)
    earthOrbitGeode.addDrawable(axes)
    earthOrbitGeode.setName("EarthOrbitGeode")

    earthOrbitPAT = osg.PositionAttitudeTransform()
    earthOrbitPAT.setScale(osg.Vec3d(AU,AU,AU))
    earthOrbitPAT.setPosition(osg.Vec3d(0.0, AU, 0.0))
    earthOrbitPAT.addChild(earthOrbitGeode)
    earthOrbitPAT.setName("EarthOrbitPAT")

    scene = osg.Group()
    scene.setName("SceneGroup")
    scene.addChild(earth_geode)
    scene.addChild(pat)
    scene.addChild(earthOrbitPAT)
Example #12
0
class IntersectionUpdateCallback (osg.NodeCallback) :
virtual void operator()(osg.Node* #node, osg.NodeVisitor* nv)
            if  not root_  or   not terrain_  or   not ss_  or   not intersectionGroup_ :
                osg.notify(osg.NOTICE), "IntersectionUpdateCallback not set up correctly."
                return

            #traverse(node,nv)
            frameCount_++
            if frameCount_ > 200 :
                # first we need find the transformation matrix that takes
                # the terrain into the coordinate frame of the sphere segment.
                terrainLocalToWorld = osg.Matrixd()
                terrain_worldMatrices = terrain_.getWorldMatrices(root_)
                if terrain_worldMatrices.empty() : terrainLocalToWorld.makeIdentity()
                elif terrain_worldMatrices.size()==1 : terrainLocalToWorld = terrain_worldMatrices.front()
                else:
                    osg.notify(osg.NOTICE), "IntersectionUpdateCallback: warning cannot interestect with multiple terrain instances, just uses first one."
                    terrainLocalToWorld = terrain_worldMatrices.front()

                # sphere segment is easier as this callback is attached to the node, so the node visitor has the unique path to it already.
                ssWorldToLocal = osg.computeWorldToLocal(nv.getNodePath())

                # now we can compute the terrain to ss transform
                possie = terrainLocalToWorld*ssWorldToLocal

                lines = ss_.computeIntersection(possie, terrain_)
                if  not lines.empty() :
                    if intersectionGroup_.valid() :
                        # now we need to place the intersections which are in the SphereSegmenet's coordinate frame into
                        # to the final position.
                        mt = osg.MatrixTransform()
                        mt.setMatrix(osg.computeLocalToWorld(nv.getNodePath()))
                        intersectionGroup_.addChild(mt)

                        # print "matrix = ", mt.getMatrix()

                        geode = osg.Geode()
                        mt.addChild(geode)

                        geode.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.OFF)

                        for(osgSim.SphereSegment.LineList.iterator itr=lines.begin()
                           not = lines.end()
                           ++itr)
                            geom = osg.Geometry()
                            geode.addDrawable(geom)

                            vertices = itr
                            geom.setVertexArray(vertices)
                            geom.addPrimitiveSet(osg.DrawArrays(GL_LINE_STRIP, 0, vertices.getNumElements()))
                else:
                       osg.notify(osg.NOTICE), "No intersections found"


                frameCount_ = 0
    root_ = osg.observer_ptr<osg.Group>()
    terrain_ = osg.observer_ptr<osg.Geode>()
    ss_ = osg.observer_ptr<osgSim.SphereSegment>()
    intersectionGroup_ = osg.observer_ptr<osg.Group>()
    frameCount_ = unsigned()


class RotateUpdateCallback (osg.NodeCallback) :
    RotateUpdateCallback()  i=0
        virtual void operator()(osg.Node* node, osg.NodeVisitor* nv)
            ss = dynamic_cast<osgSim.SphereSegment *>(node)
            if ss :
                ss.setArea(osg.Vec3(cos(i/(2*osg.PI)),sin(i/(2*osg.PI)),0), osg.PI_2, osg.PI_2)

                i += 0.1

    i = float()


def createMovingModel(center, radius, terrainGeode, root, createMovingRadar):

    
    animationLength = 10.0

    animationPath = createAnimationPath(center,radius,animationLength)

    model = osg.Group()

    glider = osgDB.readNodeFile("glider.osgt")
    if glider :
        bs = glider.getBound()

        size = radius/bs.radius()*0.3
        positioned = osg.MatrixTransform()
        positioned.setDataVariance(osg.Object.STATIC)
        positioned.setMatrix(osg.Matrix.translate(-bs.center())*
                                     osg.Matrix.scale(size,size,size)*
                                     osg.Matrix.rotate(osg.inDegrees(-90.0),0.0,0.0,1.0))

        positioned.addChild(glider)

        xform = osg.PositionAttitudeTransform()
        xform.getOrCreateStateSet().setMode(GL_NORMALIZE, osg.StateAttribute.ON)
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,1.0))
        xform.addChild(positioned)
        model.addChild(xform)

    if createMovingRadar :
        # The IntersectionUpdateCallback has to have a safe place to put all its generated geometry into,
        # and this group can't be in the parental chain of the callback otherwise we will end up invalidating
        # traversal iterators.
        intersectionGroup = osg.Group()
        root.addChild(intersectionGroup)

        xform = osg.PositionAttitudeTransform()
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,1.0))

        ss = osgSim.SphereSegment(osg.Vec3d(0.0,0.0,0.0),
                                700.0, # radius
                                osg.DegreesToRadians(135.0),
                                osg.DegreesToRadians(240.0),
                                osg.DegreesToRadians(-60.0),
                                osg.DegreesToRadians(-40.0),
                                60)

        iuc = IntersectionUpdateCallback()
        iuc.frameCount_ = 0
        iuc.root_ = root
        iuc.terrain_ = terrainGeode
        iuc.ss_ = ss
        iuc.intersectionGroup_ = intersectionGroup
        ss.setUpdateCallback(iuc)
        ss.setAllColors(osg.Vec4(1.0,1.0,1.0,0.5))
        ss.setSideColor(osg.Vec4(0.5,1.0,1.0,0.1))
        xform.addChild(ss)
        model.addChild(xform)

    cessna = osgDB.readNodeFile("cessna.osgt")
    if cessna :
        bs = cessna.getBound()

        text = osgText.Text()
        size = radius/bs.radius()*0.3

        text.setPosition(bs.center())
        text.setText("Cessna")
        text.setAlignment(osgText.Text.CENTER_CENTER)
        text.setAxisAlignment(osgText.Text.SCREEN)
        text.setCharacterSize(40.0)
        text.setCharacterSizeMode(osgText.Text.OBJECT_COORDS)

        geode = osg.Geode()
        geode.addDrawable(text)

        lod = osg.LOD()
        lod.setRangeMode(osg.LOD.PIXEL_SIZE_ON_SCREEN)
        lod.setRadius(cessna.getBound().radius())
        lod.addChild(geode,0.0,100.0)
        lod.addChild(cessna,100.0,10000.0)


        positioned = osg.MatrixTransform()
        positioned.getOrCreateStateSet().setMode(GL_NORMALIZE, osg.StateAttribute.ON)
        positioned.setDataVariance(osg.Object.STATIC)
        positioned.setMatrix(osg.Matrix.translate(-bs.center())*
                                     osg.Matrix.scale(size,size,size)*
                                     osg.Matrix.rotate(osg.inDegrees(180.0),0.0,0.0,1.0))

        #positioned.addChild(cessna)
        positioned.addChild(lod)

        xform = osg.MatrixTransform()
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,2.0))
        xform.addChild(positioned)

        model.addChild(xform)

    return model

def createOverlay(center, radius):

    
    group = osg.Group()

    # create a grid of lines.
        geom = osg.Geometry()

        num_rows = 10

        left = center+osg.Vec3(-radius,-radius,0.0)
        right = center+osg.Vec3(radius,-radius,0.0)
        delta_row = osg.Vec3(0.0,2.0*radius/float(num_rows-1),0.0)

        top = center+osg.Vec3(-radius,radius,0.0)
        bottom = center+osg.Vec3(-radius,-radius,0.0)
        delta_column = osg.Vec3(2.0*radius/float(num_rows-1),0.0,0.0)

        vertices = osg.Vec3Array()
        for(unsigned int i=0 i<num_rows ++i)
            vertices.push_back(left)
            vertices.push_back(right)
            left += delta_row
            right += delta_row

            vertices.push_back(top)
            vertices.push_back(bottom)
            top += delta_column
            bottom += delta_column

        geom.setVertexArray(vertices)

        color = *(osg.Vec4ubArray(1))
        color[0].set(0,0,0,255)
        geom.setColorArray(color, osg.Array.BIND_OVERALL)

        geom.addPrimitiveSet(osg.DrawArrays(GL_LINES,0,vertices.getNumElements()))

        geom.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.OFF)

        geode = osg.Geode()
        geode.addDrawable(geom)
        group.addChild(geode)

    return group

def computeTerrainIntersection(subgraph, x, y):

    
    bs = subgraph.getBound()
    zMax = bs.center().z()+bs.radius()
    zMin = bs.center().z()-bs.radius()

    intersector = osgUtil.LineSegmentIntersector(osg.Vec3(x,y,zMin),osg.Vec3(x,y,zMax))

    iv = osgUtil.IntersectionVisitor(intersector)

    subgraph.accept(iv)

    if intersector.containsIntersections() :
        return intersector.getFirstIntersection().getWorldIntersectPoint()

    return osg.Vec3(x,y,0.0)


#######################################
# MAIN SCENE GRAPH BUILDING FUNCTION
#######################################

def build_world(root, testCase, useOverlay, technique):

    

    # create terrain
    terrainGeode = 0
        terrainGeode = osg.Geode()

        stateset = osg.StateSet()
        image = osgDB.readImageFile("Images/lz.rgb")
        if image :
            texture = osg.Texture2D()
            texture.setImage(image)
            stateset.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON)

        terrainGeode.setStateSet( stateset )


            numColumns = 38
            numRows = 39
            unsigned int r, c

            origin = osg.Vec3(0.0,0.0,0.0)
            size = osg.Vec3(1000.0,1000.0,250.0)

            geometry = osg.Geometry()

            v = *(osg.Vec3Array(numColumns*numRows))
            tc = *(osg.Vec2Array(numColumns*numRows))
            color = *(osg.Vec4ubArray(1))

            color[0].set(255,255,255,255)

            rowCoordDelta = size.y()/(float)(numRows-1)
            columnCoordDelta = size.x()/(float)(numColumns-1)

            rowTexDelta = 1.0/(float)(numRows-1)
            columnTexDelta = 1.0/(float)(numColumns-1)

            # compute z range of z values of grid data so we can scale it.
            min_z = FLT_MAX
            max_z = -FLT_MAX
            for(r=0r<numRows++r)
                for(c=0c<numColumns++c)
                    min_z = osg.minimum(min_z,vertex[r+c*numRows][2])
                    max_z = osg.maximum(max_z,vertex[r+c*numRows][2])

            scale_z = size.z()/(max_z-min_z)

            pos = origin
            tex = osg.Vec2(0.0,0.0)
            vi = 0
            for(r=0r<numRows++r)
                pos.x() = origin.x()
                tex.x() = 0.0
                for(c=0c<numColumns++c)
                    v[vi].set(pos.x(),pos.y(),pos.z()+(vertex[r+c*numRows][2]-min_z)*scale_z)
                    tc[vi] = tex
                    pos.x()+=columnCoordDelta
                    tex.x()+=columnTexDelta
                    ++vi
                pos.y() += rowCoordDelta
                tex.y() += rowTexDelta

            geometry.setVertexArray(v)
            geometry.setTexCoordArray(0, tc)
            geometry.setColorArray(color, osg.Array.BIND_OVERALL)

            for(r=0r<numRows-1++r)
                drawElements = *(osg.DrawElementsUShort(GL_QUAD_STRIP,2*numColumns))
                geometry.addPrimitiveSet(drawElements)
                ei = 0
                for(c=0c<numColumns++c)
                    drawElements[ei++] = (r+1)*numColumns+c
                    drawElements[ei++] = (r)*numColumns+c

            smoother = osgUtil.SmoothingVisitor()
            smoother.smooth(*geometry)

            terrainGeode.addDrawable(geometry)



    # create sphere segment
    ss = 0

        terrainToSS = osg.Matrix()

        switch(testCase)
            case(0):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(135.0),
                                osg.DegreesToRadians(240.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                root.addChild(ss)
                break
            case(1):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(45.0),
                                osg.DegreesToRadians(240.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                root.addChild(ss)
                break
            case(2):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(5.0),
                                osg.DegreesToRadians(355.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                root.addChild(ss)
                break
            case(3):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(0.0),
                                osg.DegreesToRadians(360.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                root.addChild(ss)
                break
            case(4):
                ss = osgSim.SphereSegment(osg.Vec3d(0.0,0.0,0.0),
                                700.0, # radius
                                osg.DegreesToRadians(135.0),
                                osg.DegreesToRadians(240.0),
                                osg.DegreesToRadians(-60.0),
                                osg.DegreesToRadians(-40.0),
                                60)

                mt = osg.MatrixTransform()

                mt.setMatrix(osg.Matrix(-0.851781, 0.156428, -0.5, 0,
                                          -0.180627, -0.983552, -6.93889e-18, 0,
                                          -0.491776, 0.0903136, 0.866025, 0,
                                          598.217, 481.957, 100, 1))
                mt.addChild(ss)

                terrainToSS.invert(mt.getMatrix())

                root.addChild(mt)
                break
            case(5):
                ss = osgSim.SphereSegment(osg.Vec3d(0.0,0.0,0.0),
                                700.0, # radius
                                osg.DegreesToRadians(35.0),
                                osg.DegreesToRadians(135.0),
                                osg.DegreesToRadians(-60.0),
                                osg.DegreesToRadians(-40.0),
                                60)

                mt = osg.MatrixTransform()

                mt.setMatrix(osg.Matrix(-0.851781, 0.156428, -0.5, 0,
                                          -0.180627, -0.983552, -6.93889e-18, 0,
                                          -0.491776, 0.0903136, 0.866025, 0,
                                          598.217, 481.957, 100, 1))
                mt.addChild(ss)

                terrainToSS.invert(mt.getMatrix())

                root.addChild(mt)
                break
            case(6):
                ss = osgSim.SphereSegment(osg.Vec3d(0.0,0.0,0.0),
                                700.0, # radius
                                osg.DegreesToRadians(-45.0),
                                osg.DegreesToRadians(45.0),
                                osg.DegreesToRadians(-60.0),
                                osg.DegreesToRadians(-40.0),
                                60)

                mt = osg.MatrixTransform()

                mt.setMatrix(osg.Matrix(-0.851781, 0.156428, -0.5, 0,
                                          -0.180627, -0.983552, -6.93889e-18, 0,
                                          -0.491776, 0.0903136, 0.866025, 0,
                                          598.217, 481.957, 100, 1))
                mt.addChild(ss)

                terrainToSS.invert(mt.getMatrix())

                root.addChild(mt)
                break
            case(7):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(-240.0),
                                osg.DegreesToRadians(-135.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                ss.setUpdateCallback(RotateUpdateCallback())
                root.addChild(ss)
                break
        

        if ss.valid() :
            ss.setAllColors(osg.Vec4(1.0,1.0,1.0,0.5))
            ss.setSideColor(osg.Vec4(0.0,1.0,1.0,0.1))

            if  not ss.getParents().empty() :
                ss.getParent(0).addChild(ss.computeIntersectionSubgraph(terrainToSS, terrainGeode))



    if useOverlay :
        overlayNode = osgSim.OverlayNode(technique)
        overlayNode.getOrCreateStateSet().setTextureAttribute(1, osg.TexEnv(osg.TexEnv.DECAL))

        bs = terrainGeode.getBound()
        overlaySubgraph = createOverlay(bs.center(), bs.radius()*0.5)
        overlaySubgraph.addChild(ss)
        overlayNode.setOverlaySubgraph(overlaySubgraph)
        overlayNode.setOverlayTextureSizeHint(1024)
        overlayNode.setOverlayBaseHeight(0.0)
        overlayNode.addChild(terrainGeode)

        root.addChild(overlayNode)
    else:
      root.addChild(terrainGeode)

    # create particle effects
        position = computeTerrainIntersection(terrainGeode,100.0,100.0)

        explosion = osgParticle.ExplosionEffect(position, 10.0)
        smoke = osgParticle.SmokeEffect(position, 10.0)
        fire = osgParticle.FireEffect(position, 10.0)

        root.addChild(explosion)
        root.addChild(smoke)
        root.addChild(fire)

    # create particle effects
        position = computeTerrainIntersection(terrainGeode,200.0,100.0)

        explosion = osgParticle.ExplosionEffect(position, 1.0)
        smoke = osgParticle.SmokeEffect(position, 1.0)
        fire = osgParticle.FireEffect(position, 1.0)

        root.addChild(explosion)
        root.addChild(smoke)
        root.addChild(fire)


    createMovingRadar = True

    # create the moving models.
        root.addChild(createMovingModel(osg.Vec3(500.0,500.0,500.0),100.0, terrainGeode, root, createMovingRadar))


#######################################
# main()
#######################################


def main(argv):


    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    # set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")


    # construct the viewer.
    viewer = osgViewer.Viewer(arguments)

    # if user request help write it out to cout.
    testCase = 0
    while arguments.read("-t", testCase) : 

    useOverlay = False
    technique = osgSim.OverlayNode.OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY
    while arguments.read("--object") :  useOverlay = True technique = osgSim.OverlayNode.OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY 
    while arguments.read("--ortho")  or  arguments.read("--orthographic") :  useOverlay = True technique = osgSim.OverlayNode.VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY 
    while arguments.read("--persp")  or  arguments.read("--perspective") :  useOverlay = True technique = osgSim.OverlayNode.VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY 


    # if user request help write it out to cout.
    if arguments.read("-h")  or  arguments.read("--help") :
        arguments.getApplicationUsage().write(std.cout)
        return 1

    # any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized()

    # report any errors if they have occurred when parsing the program arguments.
    if arguments.errors() :
        arguments.writeErrorMessages(std.cout)
        return 1

    root = osg.Group()
    build_world(root, testCase, useOverlay, technique)

    # add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData(root)

    return viewer.run()


if __name__ == "__main__":
    main(sys.argv)
Example #13
0
def main(argv):

    

    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    arguments.getApplicationUsage().addCommandLineOption("--zeroconf","uses zeroconf to advertise the osc-plugin and to discover it")
    arguments.getApplicationUsage().addCommandLineOption("--sender","create a view which sends its events via osc")
    arguments.getApplicationUsage().addCommandLineOption("--recevier","create a view which receive its events via osc")



    # read the scene from the list of file specified commandline args.
    scene = osgDB.readNodeFiles(arguments)

    if  not scene :
        print argv[0], ": requires filename argument."
        return 1

    use_zeroconf = bool(False)
    use_sender = bool(False)
    use_receiver = bool(False)
    if arguments.find("--zeroconf") > 0 :  use_zeroconf = True 
    if arguments.find("--sender") > 0 :  use_sender = True 
    if arguments.find("--receiver") > 0 :  use_receiver = True 
    # construct the viewer.
    viewer = osgViewer.CompositeViewer(arguments)

    # receiver view
    if use_receiver : 
        traits = osg.GraphicsContext.Traits()
        traits.x = 600
        traits.y = 100
        traits.width = 400
        traits.height = 400
        traits.windowDecoration = True
        traits.doubleBuffer = True
        traits.sharedContext = 0
        traits.windowName = "Receiver / view two"

        gc = osg.GraphicsContext.createGraphicsContext(traits)

        view = osgViewer.View()
        view.setName("View two")
        viewer.addView(view)

        group = osg.Group()
        group.addChild(scene)
        geode = osg.Geode()
        group.addChild(geode)

        text = osgText.Text()
        geode.addDrawable( text )

        text.setFont("Arial.ttf")
        text.setText("Waiting for data")
        text.setPosition(osg.Vec3(-50,0,30))
        text.setAxisAlignment(osgText.TextBase.SCREEN)
        text.setDataVariance(osg.Object.DYNAMIC)
        text.setCharacterSize(2.0)
        view.setSceneData(group)
        view.getCamera().setName("Cam two")
        view.getCamera().setViewport(osg.Viewport(0,0, traits.width, traits.height))
        view.getCamera().setGraphicsContext(gc)

        view.addEventHandler( osgViewer.StatsHandler )()
        view.addEventHandler( UserEventHandler(text) )

        device = osgDB.readFile<osgGA.Device>("0.0.0.0:9000.receiver.osc")
        if device.valid()  and  (device.getCapabilities()  osgGA.Device.RECEIVE_EVENTS) :
            view.addDevice(device)

            # add a zeroconf device, advertising the osc-device
            if use_zeroconf :
                zeroconf_device = osgDB.readFile<osgGA.Device>("_osc._udp:9000.advertise.zeroconf")
                if zeroconf_device :
                    view.addDevice(zeroconf_device)
        else:
            OSG_WARN, "could not open osc-device, receiving will not work"
Example #14
0
def main(argv):


    
    arguments = osg.ArgumentParser(argv)

    viewer = osgViewer.Viewer(arguments)

    fontFile = str("arial.ttf")
    while arguments.read("-f",fontFile) : 

    font = osgText.readFontFile(fontFile)
    if  not font : return 1
    OSG_NOTICE, "Read font ", fontFile, " font=", font

    word = str("This is a test.")()
    while arguments.read("-w",word) : 

    style = osgText.Style()

    thickness = 0.1
    while arguments.read("--thickness",thickness) : 
    style.setThicknessRatio(thickness)

    # set up any bevel if required
    r = float()
    bevel = osgText.Bevel()
    while arguments.read("--rounded",r) :  bevel = osgText.Bevel() bevel.roundedBevel2(r) 
    while arguments.read("--rounded") :  bevel = osgText.Bevel() bevel.roundedBevel2(0.25) 
    while arguments.read("--flat",r) :  bevel = osgText.Bevel() bevel.flatBevel(r) 
    while arguments.read("--flat") :  bevel = osgText.Bevel() bevel.flatBevel(0.25) 
    while arguments.read("--bevel-thickness",r) :  if bevel.valid() : bevel.setBevelThickness(r) 

    style.setBevel(bevel)

    # set up outline.
    while arguments.read("--outline",r) :  style.setOutlineRatio(r) 


    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
    viewer.addEventHandler(osgViewer.StatsHandler)()

#if 1
    group = osg.Group()

    characterSize = 1.0
    while arguments.read("--size",characterSize) : 

    if arguments.read("--2d") :
        text2D = osgText.Text()
        text2D.setFont(font)
        text2D.setCharacterSize(characterSize)
        text2D.setFontResolution(256,256)
        text2D.setDrawMode(osgText.Text.TEXT | osgText.Text.BOUNDINGBOX)
        text2D.setAxisAlignment(osgText.Text.XZ_PLANE)
        text2D.setText(word)
        geode = osg.Geode()
        geode.addDrawable(text2D)
        group.addChild(geode)

    if arguments.read("--TextNode") :
        # experimental text node
        text = osgText.TextNode()
        text.setFont(font)
        text.setStyle(style)
        text.setTextTechnique(osgText.TextTechnique)()
        text.setText(word)
        text.update()

        group.addChild(text)
    elif  not arguments.read("--no-3d") :
        text3D = osgText.Text3D()
        text3D.setFont(font)
        text3D.setStyle(style)
        text3D.setCharacterSize(characterSize)
        text3D.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
        text3D.setAxisAlignment(osgText.Text3D.XZ_PLANE)
        text3D.setText(word)

        geode = osg.Geode()
        geode.addDrawable(text3D)
        group.addChild(geode)

        color = osg.Vec4(1.0, 1.0, 1.0, 1.0)
        while arguments.read("--color",color.r(),color.g(),color.b(),color.a()) :
            OSG_NOTICE, "--color ", color
            text3D.setColor(color)

        imageFilename = str()
        while arguments.read("--image",imageFilename) :
            OSG_NOTICE, "--image ", imageFilename
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                OSG_NOTICE, "  loaded image ", imageFilename
                stateset = text3D.getOrCreateStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        while arguments.read("--wall-color",color.r(),color.g(),color.b(),color.a()) :
            stateset = text3D.getOrCreateWallStateSet()
            material = osg.Material()
            material.setDiffuse(osg.Material.FRONT_AND_BACK, color)
            stateset.setAttribute(material)

        while arguments.read("--wall-image",imageFilename) :
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                stateset = text3D.getOrCreateWallStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        while arguments.read("--back-color",color.r(),color.g(),color.b(),color.a()) :
            stateset = text3D.getOrCreateBackStateSet()
            material = osg.Material()
            material.setDiffuse(osg.Material.FRONT_AND_BACK, color)
            stateset.setAttribute(material)

        while arguments.read("--back-image",imageFilename) :
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                stateset = text3D.getOrCreateBackStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        if arguments.read("--size-quad") :
            geode.addDrawable( osg.createTexturedQuadGeometry(osg.Vec3(0.0,characterSize*thickness,0.0),osg.Vec3(characterSize,0.0,0.0),osg.Vec3(0.0,0.0,characterSize), 0.0, 0.0, 1.0, 1.0) )

    
    viewer.setSceneData(group)

#endif

    return viewer.run()

# Translated from file 'osgtext3D_orig.cpp'

# OpenSceneGraph example, osgtext.
#*
#*  Permission is hereby granted, free of charge, to any person obtaining a copy
#*  of this software and associated documentation files (the "Software"), to deal
#*  in the Software without restriction, including without limitation the rights
#*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#*  copies of the Software, and to permit persons to whom the Software is
#*  furnished to do so, subject to the following conditions:
#*
#*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#*  THE SOFTWARE.
#


#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>

#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgText/Text3D>

#include <iostream>
#include <sstream>



# create text which sits in 3D space such as would be inserted into a normal model
def create3DText(center, radius):
    

    geode = osg.Geode()

####################################################
#    
# Examples of how to set up axis/orientation alignments
#

    characterSize = radius*0.2
    characterDepth = characterSize*0.2
    
    pos = osg.Vec3(center.x()-radius*.5,center.y()-radius*.5,center.z()-radius*.5)

    text1 = osgText.Text3D()
    text1.setFont("fonts/arial.ttf")
    text1.setCharacterSize(characterSize)
    text1.setCharacterDepth(characterDepth)
    text1.setPosition(pos)
    text1.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text1.setAxisAlignment(osgText.Text3D.XY_PLANE)
    text1.setText("XY_PLANE")
    geode.addDrawable(text1)

    text2 = osgText.Text3D()
    text2.setFont("fonts/times.ttf")
    text2.setCharacterSize(characterSize)
    text2.setCharacterDepth(characterDepth)
    text2.setPosition(pos)
    text2.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text2.setAxisAlignment(osgText.Text3D.YZ_PLANE)
    text2.setText("YZ_PLANE")
    geode.addDrawable(text2)

    text3 = osgText.Text3D()
    text3.setFont("fonts/dirtydoz.ttf")
    text3.setCharacterSize(characterSize)
    text3.setCharacterDepth(characterDepth)
    text3.setPosition(pos)
    text3.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text3.setAxisAlignment(osgText.Text3D.XZ_PLANE)
    text3.setText("XZ_PLANE")
    geode.addDrawable(text3)

    style = osgText.Style()
    bevel = osgText.Bevel()
    bevel.roundedBevel2(0.25)
    style.setBevel(bevel)
    style.setWidthRatio(0.4)

    text7 = osgText.Text3D()
    text7.setFont("fonts/times.ttf")
    text7.setStyle(style)
    text7.setCharacterSize(characterSize)
    text7.setCharacterDepth(characterSize*0.2)
    text7.setPosition(center - osg.Vec3(0.0, 0.0, 0.6))
    text7.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text7.setAxisAlignment(osgText.Text3D.SCREEN)
    text7.setCharacterSizeMode(osgText.Text3D.OBJECT_COORDS)
    text7.setText("CharacterSizeMode OBJECT_COORDS (default)")
    geode.addDrawable(text7)

    shape = osg.ShapeDrawable(osg.Sphere(center,characterSize*0.2))
    shape.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.ON)
    geode.addDrawable(shape)

    rootNode = osg.Group()
    rootNode.addChild(geode)

    front = osg.Material()
    front.setAlpha(osg.Material.FRONT_AND_BACK,1)
    front.setAmbient(osg.Material.FRONT_AND_BACK,osg.Vec4(0.2,0.2,0.2,1.0))
    front.setDiffuse(osg.Material.FRONT_AND_BACK,osg.Vec4(.0,.0,1.0,1.0))
    rootNode.getOrCreateStateSet().setAttributeAndModes(front)
    
    
    return rootNode    

int main_orig(int, char**)
    viewer = osgViewer.Viewer()

    center = osg.Vec3(0.0,0.0,0.0)
    radius = 1.0
    
    root = osg.Group()
    root.addChild(create3DText(center, radius))

    viewer.setSceneData(root)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    viewer.addEventHandler(osgViewer.ThreadingHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()
    viewer.addEventHandler(osgViewer.StatsHandler)()


    viewer.run()
    
    return 0



# Translated from file 'osgtext3D_test.cpp'


#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>

#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgText/Text3D>

#include <iostream>
#include <sstream>



def test_create3DText(center, radius):



    

    geode = osg.Geode()

    characterSize = radius*0.2
    characterDepth = characterSize*0.2
    
    pos = osg.Vec3(center.x()-radius*.5,center.y()-radius*.5,center.z()-radius*.5)
#define SHOW_INTESECTION_CEASH
#ifdef SHOW_INTESECTION_CEASH
    text3 = osgText.Text3D()
    text3.setFont("fonts/dirtydoz.ttf")
    text3.setCharacterSize(characterSize)
    text3.setCharacterDepth(characterDepth)
    text3.setPosition(pos)
    text3.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text3.setAxisAlignment(osgText.Text3D.XZ_PLANE)
    text3.setText("CRAS H") #intersection crash
    geode.addDrawable(text3)
#else:
    text7 = osgText.Text3D()
    text7.setFont("fonts/times.ttf")
    text7.setCharacterSize(characterSize)
    text7.setCharacterDepth(characterSize*2.2)
    text7.setPosition(center - osg.Vec3(0.0, 0.0, 0.6))
    text7.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text7.setAxisAlignment(osgText.Text3D.SCREEN)
    text7.setCharacterSizeMode(osgText.Text3D.OBJECT_COORDS)
    text7.setText("ABCDE") #wrong intersection
    geode.addDrawable(text7)
#endif

    shape = osg.ShapeDrawable(osg.Sphere(center,characterSize*0.2))
    shape.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.ON)
    geode.addDrawable(shape)

    rootNode = osg.Group()
    rootNode.addChild(geode)

#define SHOW_WRONG_NORMAL
#ifdef SHOW_WRONG_NORMAL
    front = osg.Material() #
    front.setAlpha(osg.Material.FRONT_AND_BACK,1)
    front.setAmbient(osg.Material.FRONT_AND_BACK,osg.Vec4(0.2,0.2,0.2,1.0))
    front.setDiffuse(osg.Material.FRONT_AND_BACK,osg.Vec4(.0,.0,1.0,1.0))
    rootNode.getOrCreateStateSet().setAttributeAndModes(front)
#else:
    stateset = osg.StateSet() #Show wireframe
    polymode = osg.PolygonMode()
    polymode.setMode(osg.PolygonMode.FRONT_AND_BACK,osg.PolygonMode.LINE)
    stateset.setAttributeAndModes(polymode,osg.StateAttribute.OVERRIDE|osg.StateAttribute.ON)
    rootNode.setStateSet(stateset)
#endif
    
    
    return rootNode    

#####################################
#include <osg/PositionAttitudeTransform>
#include <osg/ShapeDrawable>
class CInputHandler (osgGA.GUIEventHandler) :
  CInputHandler( osg.PositionAttitudeTransform* pPatSphere )
    m_rPatSphere = pPatSphere
  def handle(ea, aa, pObject, pNodeVisitor):
      
    pViewer = dynamic_cast<osgViewer.Viewer*>(aa)
    if   not pViewer  :
      return False

    if  ea.getEventType()==osgGA.GUIEventAdapter.PUSH  :
      cams = osgViewer.ViewerBase.Cameras()
      pViewer.getCameras( cams )

      x = ea.getXnormalized()
      y = ea.getYnormalized()

      picker = osgUtil.LineSegmentIntersector( osgUtil.Intersector.PROJECTION, x, y )
      iv = osgUtil.IntersectionVisitor( picker )
      cams[0].accept( iv )

      if  picker.containsIntersections()  :
        intersection = picker.getFirstIntersection()
        v = intersection.getWorldIntersectPoint()
        m_rPatSphere.setPosition( v )

      return True # return True, event handled

    return False
  m_rPatSphere = osg.PositionAttitudeTransform()

#####################################
int main_test(int, char**)
    viewer = osgViewer.Viewer()
    viewer.setUpViewInWindow(99,99,666,666, 0)
    rPat = osg.PositionAttitudeTransform()
    # add the handler to the viewer
    viewer.addEventHandler( CInputHandler(rPat) )
    # create a group to contain our scene and sphere
    pGroup = osg.Group()
    # create sphere
    pGeodeSphere = osg.Geode()
    pGeodeSphere.addDrawable( osg.ShapeDrawable( osg.Sphere(osg.Vec3(0.0,0.0,0.0),0.01) ) )
    rPat.addChild( pGeodeSphere )
    pGroup.addChild( rPat )

    center = osg.Vec3(0.0,0.0,0.0)
    radius = 1.0

    root = osg.Group()
    root.addChild(test_create3DText(center, radius))

    #viewer.setSceneData(root)
    pGroup.addChild(root)
    viewer.setSceneData(pGroup)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    viewer.addEventHandler(osgViewer.ThreadingHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()
    viewer.addEventHandler(osgViewer.StatsHandler)()

    return viewer.run()



# Translated from file 'TextNode.cpp'

# -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
# *
# * This library is open source and may be redistributed and/or modified under
# * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
# * (at your option) any later version.  The full license is in LICENSE file
# * included with this distribution, and on the openscenegraph.org website.
# *
# * This library is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# * OpenSceneGraph Public License for more details.
#

#include "TextNode.h"
#include "../../src/osgText/GlyphGeometry.h"

#include <osg/PositionAttitudeTransform>
#include <osg/Geode>
#include <osgUtil/SmoothingVisitor>

#include <osg/io_utils>

using namespace osgText

############################################/
#
# Layout
#
Layout.Layout()

Layout.Layout( Layout layout,  osg.CopyOp copyop):
    osg.Object(layout,copyop)
Example #15
0
    # create marker for point light.
    marker = osg.Geometry()
    vertices = osg.Vec3Array()
    vertices.push_back(osg.Vec3(0.0,0.0,0.0))
    marker.setVertexArray(vertices)
    marker.addPrimitiveSet(osg.DrawArrays(GL_POINTS,0,1))

    stateset = osg.StateSet()
    point = osg.Point()
    point.setSize(4.0)
    stateset.setAttribute(point)

    marker.setStateSet(stateset)

    markerGeode = osg.Geode()
    markerGeode.addDrawable(marker)

    mt.addChild(lightS2)
    mt.addChild(markerGeode)

    lightGroup.addChild(mt)

    return lightGroup

def createWall(v1, v2, v3, stateset):

    

   # create a drawable for occluder.
    geom = osg.Geometry()
Example #16
0
def main(argv):


    
    arguments = osg.ArgumentParser(argv)

    # construct the viewer.
    viewer = osgViewer.Viewer(arguments)
    
    typedef std.list< osg.OperationThread > Threads

    operationThreads = Threads()
    updateOperation = UpdateTextOperation()

    numThreads = 0
    if arguments.read("--mt", numThreads)  or  arguments.read("--mt") :
        # construct a multi-threaded text updating test.
        if numThreads==0 : numThreads = 1
        
        # create a group to add everything into.
        mainGroup = osg.Group()
        
        center = osg.Vec3(0.5,0.5,0.5)
        diameter = 1.0
        
        loadedModel = osgDB.readNodeFiles(arguments)
        if loadedModel.valid() :
            mainGroup.addChild(loadedModel)
            
            center = loadedModel.getBound().center()
            diameter = loadedModel.getBound().radius() * 2.0
        
        for(unsigned int i=0 i<numThreads ++i)
            textGroup = osg.Group()
            mainGroup.addChild(textGroup)

            # create the background thread
            operationThread = osg.OperationThread()
            
            operationThreads.push_back(operationThread)

            # create the operation that will run in the background and
            # sync once per frame with the main viewer loop.
            updateOperation = UpdateTextOperation(center, diameter, textGroup)

            # add the operation to the operation thread and start it.
            operationThread.add(updateOperation)
            operationThread.startThread()

            # add the operation to the viewer to sync once per frame.
            viewer.addUpdateOperation(updateOperation)


            # add a unit cube for the text to appear within.
            geode = osg.Geode()
            geode.getOrCreateStateSet().setAttribute(osg.PolygonMode(osg.PolygonMode.FRONT_AND_BACK,osg.PolygonMode.LINE))
            geode.addDrawable(osg.ShapeDrawable(osg.Box(center,diameter)))

            mainGroup.addChild(geode)
                
        viewer.setSceneData(mainGroup)        
Example #17
0
def createRoom(loadedModel):


    
    # default scale for this model.
    bs = osg.BoundingSphere(osg.Vec3(0.0,0.0,0.0),1.0)

    root = osg.Group()

    if loadedModel :
        loaded_bs = loadedModel.getBound()

        pat = osg.PositionAttitudeTransform()
        pat.setPivotPoint(loaded_bs.center())

        pat.setUpdateCallback(ModelTransformCallback(loaded_bs))
        pat.addChild(loadedModel)

        bs = pat.getBound()

        root.addChild(pat)


    bs.radius()*=1.5

    # create a bounding box, which we'll use to size the room.
    bb = osg.BoundingBox()
    bb.expandBy(bs)


    # create statesets.
    rootStateSet = osg.StateSet()
    root.setStateSet(rootStateSet)

    wall = osg.StateSet()
    wall.setMode(GL_CULL_FACE,osg.StateAttribute.ON)

    floor = osg.StateSet()
    floor.setMode(GL_CULL_FACE,osg.StateAttribute.ON)

    roof = osg.StateSet()
    roof.setMode(GL_CULL_FACE,osg.StateAttribute.ON)

    geode = osg.Geode()

    # create front side.
    geode.addDrawable(createWall(bb.corner(0),
                                  bb.corner(4),
                                  bb.corner(1),
                                  wall))

    # right side
    geode.addDrawable(createWall(bb.corner(1),
                                  bb.corner(5),
                                  bb.corner(3),
                                  wall))

    # left side
    geode.addDrawable(createWall(bb.corner(2),
                                  bb.corner(6),
                                  bb.corner(0),
                                  wall))
    # back side
    geode.addDrawable(createWall(bb.corner(3),
                                  bb.corner(7),
                                  bb.corner(2),
                                  wall))

    # floor
    geode.addDrawable(createWall(bb.corner(0),
                                  bb.corner(1),
                                  bb.corner(2),
                                  floor))

    # roof
    geode.addDrawable(createWall(bb.corner(6),
                                  bb.corner(7),
                                  bb.corner(4),
                                  roof))

    root.addChild(geode)

    root.addChild(createLights(bb,rootStateSet))

    return root
def createPyramid():
   pyramidGeode = osg.Geode()
   pyramidGeometry = osg.Geometry()
   pyramidGeode.addDrawable(pyramidGeometry) 
   pyramidVertices = osg.Vec3Array()
   pyramidVertices.append( osg.Vec3(0, 0, 0) ) # front left 
   pyramidVertices.append( osg.Vec3(2, 0, 0) ) # front right 
   pyramidVertices.append( osg.Vec3(2, 2, 0) ) # back right 
   pyramidVertices.append( osg.Vec3( 0,2, 0) ) # back left 
   pyramidVertices.append( osg.Vec3( 1, 1,2) ) # peak
   # Associate this set of vertices with the geometry associated with the 
   # geode we added to the scene.
   pyramidGeometry.setVertexArray( pyramidVertices )
   pyramidBase = osg.DrawElementsUInt(osg.PrimitiveSet.QUADS, 3)
   pyramidBase.append(3)
   pyramidBase.append(2)
   pyramidBase.append(1)
   pyramidBase.append(0)
   pyramidGeometry.addPrimitiveSet(pyramidBase)

   pyramidFaceOne = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
   pyramidFaceOne.append(0)
   pyramidFaceOne.append(1)
   pyramidFaceOne.append(4)
   pyramidGeometry.addPrimitiveSet(pyramidFaceOne)

   pyramidFaceTwo = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
   pyramidFaceTwo.append(1)
   pyramidFaceTwo.append(2)
   pyramidFaceTwo.append(4)
   pyramidGeometry.addPrimitiveSet(pyramidFaceTwo)

   pyramidFaceThree = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
   pyramidFaceThree.append(2)
   pyramidFaceThree.append(3)
   pyramidFaceThree.append(4)
   pyramidGeometry.addPrimitiveSet(pyramidFaceThree)

   pyramidFaceFour = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
   pyramidFaceFour.append(3)
   pyramidFaceFour.append(0)
   pyramidFaceFour.append(4)
   pyramidGeometry.addPrimitiveSet(pyramidFaceFour)

   colors = osg.Vec4Array()
   colors.append(osg.Vec4(1.0, 0.0, 0.0, 1.0) ) #index 0 red
   colors.append(osg.Vec4(0.0, 1.0, 0.0, 1.0) ) #index 1 green
   colors.append(osg.Vec4(0.0, 0.0, 1.0, 1.0) ) #index 2 blue
   colors.append(osg.Vec4(1.0, 1.0, 1.0, 1.0) ) #index 3 white

   colorIndexArray = osg.UIntArray()
   colorIndexArray.append(0) # vertex 0 assigned color array element 0
   colorIndexArray.append(1) # vertex 1 assigned color array element 1
   colorIndexArray.append(2) # vertex 2 assigned color array element 2
   colorIndexArray.append(3) # vertex 3 assigned color array element 3
   colorIndexArray.append(0) # vertex 4 assigned color array element 0

   pyramidGeometry.setColorArray(colors)
   pyramidGeometry.setColorIndices(colorIndexArray)
   pyramidGeometry.setColorBinding(osg.Geometry.BIND_PER_VERTEX)

   texcoords = osg.Vec2Array(5)
   texcoords[0].set(0.00,0.0)
   texcoords[1].set(0.25,0.0)
   texcoords[2].set(0.50,0.0)
   texcoords[3].set(0.75,0.0)
   texcoords[4].set(0.50,1.0)

   pyramidGeometry.setTexCoordArray(0,texcoords)
   return pyramidGeode
Example #19
0
        enum Operation  SIN 
        AnimateCallback(Operation op) : _operation(op) 
        virtual void operator() ( osg.Uniform* uniform, osg.NodeVisitor* nv )
            angle = 2.0 * nv.getFrameStamp().getSimulationTime()
            sine = sinf( angle )            # -1 . 1
            switch(_operation) 
                case SIN : uniform.set( sine ) break
        _operation = Operation()


int main(int, char **)
    # construct the viewer.
    viewer = osgViewer.Viewer()

    # use a geode with a Box ShapeDrawable
    basicModel = osg.Geode()
    basicModel.addDrawable(osg.ShapeDrawable(osg.Box(osg.Vec3(0.0,0.0,0.0),1.0)))

    # create the "blocky" shader, a simple animation test
    ss = basicModel.getOrCreateStateSet()
    program = osg.Program()
    program.setName( "blocky" )
    program.addShader( osg.Shader( osg.Shader.VERTEX, blockyVertSource ) )
    program.addShader( osg.Shader( osg.Shader.FRAGMENT, blockyFragSource ) )
    ss.setAttributeAndModes(program, osg.StateAttribute.ON)

    # attach some animated Uniform variable to the state set
    SineUniform = osg.Uniform( "Sine", 0.0 )
    ss.addUniform( SineUniform )
    SineUniform.setUpdateCallback(AnimateCallback(AnimateCallback.SIN))
def main():
   viewer = osgViewer.Viewer()

   # Declare a group to act as root node of a scene:
   root = osg.Group()

   # Declare a box class (derived from shape class) instance
   # This constructor takes an osg.Vec3 to define the center
   #  and a float to define the height, width and depth.
   #  (an overloaded constructor allows you to specify unique
   #   height, width and height values.)
   unitCube = osg.Box( osg.Vec3(0,0,0), 1.0)
   unitCube.setDataVariance(osg.Object.DYNAMIC)

   # Declare an instance of the shape drawable class and initialize 
   #  it with the unitCube shape we created above.
   #  This class is derived from 'drawable' so instances of this
   #  class can be added to Geode instances.
   unitCubeDrawable = osg.ShapeDrawable(unitCube)

   # Declare a instance of the geode class: 
   basicShapesGeode = osg.Geode()

   # Add the unit cube drawable to the geode:
   basicShapesGeode.addDrawable(unitCubeDrawable)

   # Add the goede to the scene:
   root.addChild(basicShapesGeode)

   unitSphere = osg.Sphere( osg.Vec3(0,0,0), 1.0)
   unitSphereDrawable = osg.ShapeDrawable(unitSphere)
   unitSphereDrawable.setColor( osg.Vec4(0.1, 0.1, 0.1, 0.1) )

   unitSphereXForm = osg.PositionAttitudeTransform()
   unitSphereXForm.setPosition(osg.Vec3(3.0,0,0))

   unitSphereGeode = osg.Geode()
   root.addChild(unitSphereXForm)
   unitSphereXForm.addChild(unitSphereGeode)
   unitSphereGeode.addDrawable(unitSphereDrawable)

   pyramidGeode = createPyramid()
   
   pyramidXForm = osg.PositionAttitudeTransform()
   pyramidXForm.setPosition(osg.Vec3(0,-3.0,0))
   root.addChild(pyramidXForm)
   pyramidXForm.addChild(pyramidGeode)

   KLN89FaceTexture = osg.Texture2D()
   # protect from being optimized away as static state:
   KLN89FaceTexture.setDataVariance(osg.Object.DYNAMIC) 
   klnFace = osgDB.readImageFile("../NPS_Data/Textures/KLN89FaceB.tga")
   if klnFace is None:
      print " couldn't find texture, quitting."
      sys.exit(-1)
   
   KLN89FaceTexture.setImage(klnFace)

   # Declare a state set for 'BLEND' texture mode
   blendStateSet = osg.StateSet()

   # Declare a TexEnv instance, set the mode to 'BLEND'
   blendTexEnv = osg.TexEnv()
   blendTexEnv.setMode(osg.TexEnv.BLEND)

   # Turn the attribute of texture 0 'ON'
   blendStateSet.setTextureAttributeAndModes(0,KLN89FaceTexture,osg.StateAttribute.ON)
   # Set the texture texture environment for texture 0 to the 
   #  texture envirnoment we declared above:
   blendStateSet.setTextureAttribute(0,blendTexEnv)

   decalStateSet = osg.StateSet()
   decalTexEnv = osg.TexEnv()
   decalTexEnv.setMode(osg.TexEnv.DECAL)

   decalStateSet.setTextureAttributeAndModes(0,KLN89FaceTexture,osg.StateAttribute.ON)
   decalStateSet.setTextureAttribute(0,decalTexEnv)

   root.setStateSet(blendStateSet)
   unitSphereGeode.setStateSet(decalStateSet)

   # OSG1 viewer.setUpViewer(osgProducer.Viewer.STANDARD_SETTINGS)
   viewer.setSceneData( root )
   viewer.setCameraManipulator(osgGA.TrackballManipulator())
   viewer.realize()

   while not viewer.done():
      viewer.frame()

   return 0
Example #21
0
def createMirroredScene(model):

    

    # calculate where to place the mirror according to the
    # loaded models bounding sphere.
    bs = model.getBound()

    width_factor = 1.5
    height_factor = 0.3

    xMin = bs.center().x()-bs.radius()*width_factor
    xMax = bs.center().x()+bs.radius()*width_factor
    yMin = bs.center().y()-bs.radius()*width_factor
    yMax = bs.center().y()+bs.radius()*width_factor

    z = bs.center().z()-bs.radius()*height_factor


    # create a textured, transparent node at the appropriate place.
    mirror = createMirrorSurface(xMin,xMax,yMin,yMax,z)


    rootNode = osg.MatrixTransform()
    rootNode.setMatrix(osg.Matrix.rotate(osg.inDegrees(45.0),1.0,0.0,0.0))

    # make sure that the global color mask exists.
    rootColorMask = osg.ColorMask()
    rootColorMask.setMask(True,True,True,True)

    # set up depth to be inherited by the rest of the scene unless
    # overrideen. this is overridden in bin 3.
    rootDepth = osg.Depth()
    rootDepth.setFunction(osg.Depth.LESS)
    rootDepth.setRange(0.0,1.0)

    rootStateSet = osg.StateSet()
    rootStateSet.setAttribute(rootColorMask)
    rootStateSet.setAttribute(rootDepth)

    rootNode.setStateSet(rootStateSet)


    # bin1  - set up the stencil values and depth for mirror.

        # set up the stencil ops so that the stencil buffer get set at
        # the mirror plane
        stencil = osg.Stencil()
        stencil.setFunction(osg.Stencil.ALWAYS,1,~0u)
        stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.REPLACE)

        # switch off the writing to the color bit planes.
        colorMask = osg.ColorMask()
        colorMask.setMask(False,False,False,False)

        statesetBin1 = osg.StateSet()
        statesetBin1.setRenderBinDetails(1,"RenderBin")
        statesetBin1.setMode(GL_CULL_FACE,osg.StateAttribute.OFF)
        statesetBin1.setAttributeAndModes(stencil,osg.StateAttribute.ON)
        statesetBin1.setAttribute(colorMask)

        # set up the mirror geode.
        geode = osg.Geode()
        geode.addDrawable(mirror)
        geode.setStateSet(statesetBin1)

        rootNode.addChild(geode)


    # bin one - draw scene without mirror or reflection, unset
    # stencil values where scene is infront of mirror and hence
    # occludes the mirror.
        stencil = osg.Stencil()
        stencil.setFunction(osg.Stencil.ALWAYS,0,~0u)
        stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.REPLACE)

        statesetBin2 = osg.StateSet()
        statesetBin2.setRenderBinDetails(2,"RenderBin")
        statesetBin2.setAttributeAndModes(stencil,osg.StateAttribute.ON)


        groupBin2 = osg.Group()
        groupBin2.setStateSet(statesetBin2)
        groupBin2.addChild(model)

        rootNode.addChild(groupBin2)

    # bin3  - set up the depth to the furthest depth value

        # set up the stencil ops so that only operator on this mirrors stencil value.
        stencil = osg.Stencil()
        stencil.setFunction(osg.Stencil.EQUAL,1,~0u)
        stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.KEEP)

        # switch off the writing to the color bit planes.
        colorMask = osg.ColorMask()
        colorMask.setMask(False,False,False,False)

        # set up depth so all writing to depth goes to maximum depth.
        depth = osg.Depth()
        depth.setFunction(osg.Depth.ALWAYS)
        depth.setRange(1.0,1.0)

        statesetBin3 = osg.StateSet()
        statesetBin3.setRenderBinDetails(3,"RenderBin")
        statesetBin3.setMode(GL_CULL_FACE,osg.StateAttribute.OFF)
        statesetBin3.setAttributeAndModes(stencil,osg.StateAttribute.ON)
        statesetBin3.setAttribute(colorMask)
        statesetBin3.setAttribute(depth)

        # set up the mirror geode.
        geode = osg.Geode()
        geode.addDrawable(mirror)
        geode.setStateSet(statesetBin3)

        rootNode.addChild(geode)


    # bin4  - draw the reflection.

        # now create the 'reflection' of the loaded model by applying
        # create a Transform which flips the loaded model about the z axis
        # relative to the mirror node, the loadedModel is added to the
        # Transform so now appears twice in the scene, but is shared so there
        # is negligable memory overhead.  Also use an osg.StateSet
        # attached to the Transform to override the face culling on the subgraph
        # to prevert an 'inside' out view of the reflected model.
        # set up the stencil ops so that only operator on this mirrors stencil value.



        # this clip plane removes any of the scene which when mirror would
        # poke through the mirror.  However, this clip plane should really
        # flip sides once the eye point goes to the back of the mirror...
        clipplane = osg.ClipPlane()
        clipplane.setClipPlane(0.0,0.0,-1.0,z)
        clipplane.setClipPlaneNum(0)

        clipNode = osg.ClipNode()
        clipNode.addClipPlane(clipplane)


        dstate = clipNode.getOrCreateStateSet()
        dstate.setRenderBinDetails(4,"RenderBin")
        dstate.setMode(GL_CULL_FACE,osg.StateAttribute.OVERRIDE|osg.StateAttribute.OFF)

        stencil = osg.Stencil()
        stencil.setFunction(osg.Stencil.EQUAL,1,~0u)
        stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.KEEP)
        dstate.setAttributeAndModes(stencil,osg.StateAttribute.ON)

        reverseMatrix = osg.MatrixTransform()
        reverseMatrix.setStateSet(dstate)
        reverseMatrix.preMult(osg.Matrix.translate(0.0,0.0,-z)*
                     osg.Matrix.scale(1.0,1.0,-1.0)*
                     osg.Matrix.translate(0.0,0.0,z))

        reverseMatrix.addChild(model)

        clipNode.addChild(reverseMatrix)

        rootNode.addChild(clipNode)



    # bin5  - draw the textured mirror and blend it with the reflection.

        # set up depth so all writing to depth goes to maximum depth.
        depth = osg.Depth()
        depth.setFunction(osg.Depth.ALWAYS)

        stencil = osg.Stencil()
        stencil.setFunction(osg.Stencil.EQUAL,1,~0u)
        stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.ZERO)

        # set up additive blending.
        trans = osg.BlendFunc()
        trans.setFunction(osg.BlendFunc.ONE,osg.BlendFunc.ONE)

        statesetBin5 = createMirrorTexturedState("Images/tank.rgb")

        statesetBin5.setRenderBinDetails(5,"RenderBin")
        statesetBin5.setMode(GL_CULL_FACE,osg.StateAttribute.OFF)
        statesetBin5.setAttributeAndModes(stencil,osg.StateAttribute.ON)
        statesetBin5.setAttributeAndModes(trans,osg.StateAttribute.ON)
        statesetBin5.setAttribute(depth)

        # set up the mirror geode.
        geode = osg.Geode()
        geode.addDrawable(mirror)
        geode.setStateSet(statesetBin5)

        rootNode.addChild(geode)
Example #22
0

osg.Geode* SolarSystem.createSpace(  str name,  str textureName )
    spaceSphere = osg.Sphere( osg.Vec3( 0.0, 0.0, 0.0 ), _radiusSpace )

    sSpaceSphere = osg.ShapeDrawable( spaceSphere )

    if   not textureName.empty()  :
        image = osgDB.readImageFile( textureName )
        if  image  :
            sSpaceSphere.getOrCreateStateSet().setTextureAttributeAndModes( 0, osg.Texture2D( image ), osg.StateAttribute.ON )

            # reset the object color to white to allow the texture to set the colour.
            sSpaceSphere.setColor( osg.Vec4(1.0,1.0,1.0,1.0) )

    geodeSpace = osg.Geode()
    geodeSpace.setName( name )

    geodeSpace.addDrawable( sSpaceSphere )

    return( geodeSpace )

# end SolarSystem.createSpace


osg.Geode* SolarSystem.createPlanet( double radius,  str name,  osg.Vec4 color ,  str textureName)
    # create a container that makes the sphere drawable
    sPlanetSphere = osg.Geometry()

        # set the single colour so bind overall
        colours = osg.Vec4Array(1)
Example #23
0
def main(argv):


    
    # Qt requires that we construct the global QApplication before creating any widgets.
    app = QApplication(argc, argv)

    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    # True = run osgViewer in a separate thread than Qt
    # False = interleave osgViewer and Qt in the main thread
    useFrameLoopThread = False
    if arguments.read("--no-frame-thread") : useFrameLoopThread = False
    if arguments.read("--frame-thread") : useFrameLoopThread = True

    # True = use QWidgetImage
    # False = use QWebViewImage
    useWidgetImage = False
    if arguments.read("--useWidgetImage") : useWidgetImage = True

    # True = use QWebView in a QWidgetImage to compare to QWebViewImage
    # False = make an interesting widget
    useBrowser = False
    if arguments.read("--useBrowser") : useBrowser = True

    # True = use a QLabel for text
    # False = use a QTextEdit for text
    # (only applies if useWidgetImage == True and useBrowser == False)
    useLabel = False
    if arguments.read("--useLabel") : useLabel = True

    # True = make a Qt window with the same content to compare to 
    # QWebViewImage/QWidgetImage
    # False = use QWebViewImage/QWidgetImage (depending on useWidgetImage)
    sanityCheck = False
    if arguments.read("--sanityCheck") : sanityCheck = True

    # Add n floating windows inside the QGraphicsScene.
    numFloatingWindows = 0
    while arguments.read("--numFloatingWindows", numFloatingWindows) :

    # True = Qt widgets will be displayed on a quad inside the 3D scene
    # False = Qt widgets will be an overlay over the scene (like a HUD)
    inScene = True
    if arguments.read("--fullscreen") :  inScene = False 


    root = osg.Group()

    if  not useWidgetImage :
        #-------------------------------------------------------------------
        # QWebViewImage test
        #-------------------------------------------------------------------
        # Note: When the last few issues with QWidgetImage are fixed, 
        # QWebViewImage and this if  :  section can be removed since 
        # QWidgetImage can display a QWebView just like QWebViewImage. Use 
        # --useWidgetImage --useBrowser to see that in action.

        if  not sanityCheck :
            image = osgQt.QWebViewImage()

            if arguments.argc()>1 : image.navigateTo((arguments[1]))
            else image.navigateTo("http:#www.youtube.com/")

            hints = osgWidget.GeometryHints(osg.Vec3(0.0,0.0,0.0),
                                           osg.Vec3(1.0,0.0,0.0),
                                           osg.Vec3(0.0,0.0,1.0),
                                           osg.Vec4(1.0,1.0,1.0,1.0),
                                           osgWidget.GeometryHints.RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO)

            browser = osgWidget.Browser()
            browser.assign(image, hints)

            root.addChild(browser)
        else:
            # Sanity check, do the same thing as QGraphicsViewAdapter but in 
            # a separate Qt window.
            webPage = QWebPage()
            webPage.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
            webPage.settings().setAttribute(QWebSettings.PluginsEnabled, True)

            webView = QWebView()
            webView.setPage(webPage)

            if arguments.argc()>1 : webView.load(QUrl(arguments[1]))
            else webView.load(QUrl("http:#www.youtube.com/"))

            graphicsScene = QGraphicsScene()
            graphicsScene.addWidget(webView)

            graphicsView = QGraphicsView()
            graphicsView.setScene(graphicsScene)

            mainWindow = QMainWindow()
            #mainWindow.setLayout(QVBoxLayout)()
            mainWindow.setCentralWidget(graphicsView)
            mainWindow.setGeometry(50, 50, 1024, 768)
            mainWindow.show()
            mainWindow.raise()
    else:
        #-------------------------------------------------------------------
        # QWidgetImage test
        #-------------------------------------------------------------------
        # QWidgetImage still has some issues, some examples are:
        # 
        # 1. Editing in the QTextEdit doesn't work. Also when started with 
        #    --useBrowser, editing in the search field on YouTube doesn't 
        #    work. But that same search field when using QWebViewImage 
        #    works... And editing in the text field in the pop-up getInteger 
        #    dialog works too. All these cases use QGraphicsViewAdapter 
        #    under the hood, so why do some work and others don't?
        #
        #    a) osgQtBrowser --useWidgetImage [--fullscreen] (optional)
        #    b) Try to click in the QTextEdit and type, or to select text
        #       and drag-and-drop it somewhere else in the QTextEdit. These
        #       don't work.
        #    c) osgQtBrowser --useWidgetImage --sanityCheck
        #    d) Try the operations in b), they all work.
        #    e) osgQtBrowser --useWidgetImage --useBrowser [--fullscreen]
        #    f) Try to click in the search field and type, it doesn't work.
        #    g) osgQtBrowser
        #    h) Try the operation in f), it works.
        #
        # 2. Operations on floating windows (--numFloatingWindows 1 or more). 
        #    Moving by dragging the titlebar, clicking the close button, 
        #    resizing them, none of these work. I wonder if it's because the 
        #    OS manages those functions (they're functions of the window 
        #    decorations) so we need to do something special for that? But 
        #    in --sanityCheck mode they work.
        #
        #    a) osgQtBrowser --useWidgetImage --numFloatingWindows 1 [--fullscreen]
        #    b) Try to drag the floating window, click the close button, or
        #       drag its sides to resize it. None of these work.
        #    c) osgQtBrowser --useWidgetImage --numFloatingWindows 1 --sanityCheck
        #    d) Try the operations in b), all they work.
        #    e) osgQtBrowser --useWidgetImage [--fullscreen]
        #    f) Click the button so that the getInteger() dialog is 
        #       displayed, then try to move that dialog or close it with the 
        #       close button, these don't work.
        #    g) osgQtBrowser --useWidgetImage --sanityCheck
        #    h) Try the operation in f), it works.
        #
        # 3. (Minor) The QGraphicsView's scrollbars don't appear when 
        #    using QWidgetImage or QWebViewImage. QGraphicsView is a 
        #    QAbstractScrollArea and it should display scrollbars as soon as
        #    the scene is too large to fit the view.
        #
        #    a) osgQtBrowser --useWidgetImage --fullscreen
        #    b) Resize the OSG window so it's smaller than the QTextEdit.
        #       Scrollbars should appear but don't.
        #    c) osgQtBrowser --useWidgetImage --sanityCheck
        #    d) Try the operation in b), scrollbars appear. Even if you have 
        #       floating windows (by clicking the button or by adding 
        #       --numFloatingWindows 1) and move them outside the view, 
        #       scrollbars appear too. You can't test that case in OSG for 
        #       now because of problem 2 above, but that's pretty cool.
        #
        # 4. (Minor) In sanity check mode, the widget added to the 
        #    QGraphicsView is centered. With QGraphicsViewAdapter, it is not.
        #
        #    a) osgQtBrowser --useWidgetImage [--fullscreen]
        #    b) The QTextEdit and button are not in the center of the image
        #       generated by the QGraphicsViewAdapter.
        #    c) osgQtBrowser --useWidgetImage --sanityCheck
        #    d) The QTextEdit and button are in the center of the 
        #       QGraphicsView.


        widget = 0
        if useBrowser :
            webPage = QWebPage()
            webPage.settings().setAttribute(QWebSettings.JavascriptEnabled, True)
            webPage.settings().setAttribute(QWebSettings.PluginsEnabled, True)

            webView = QWebView()
            webView.setPage(webPage)

            if arguments.argc()>1 : webView.load(QUrl(arguments[1]))
            else webView.load(QUrl("http:#www.youtube.com/"))

            widget = webView
        else:
            widget = QWidget()
            widget.setLayout(QVBoxLayout)()

            text = QString("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque velit turpis, euismod ac ultrices et, molestie non nisi. Nullam egestas dignissim enim, quis placerat nulla suscipit sed. Donec molestie elementum risus sit amet sodales. Nunc consectetur congue neque, at viverra massa pharetra fringilla. Integer vitae mi sem. Donec dapibus semper elit nec sollicitudin. Vivamus egestas ultricies felis, in mollis mi facilisis quis. Nam suscipit bibendum eros sed cursus. Suspendisse mollis suscipit hendrerit. Etiam magna eros, convallis non congue vel, faucibus ac augue. Integer ante ante, porta in ornare ullamcorper, congue nec nibh. Etiam congue enim vitae enim sollicitudin fringilla. Mauris mattis, urna in fringilla dapibus, ipsum sem feugiat purus, ac hendrerit felis arcu sed sapien. Integer id velit quam, sit amet dignissim tortor. Sed mi tortor, placerat ac luctus id, tincidunt et urna. Nulla sed nunc ante.Sed ut sodales enim. Ut sollicitudin ultricies magna, vel ultricies ante venenatis id. Cras luctus mi in lectus rhoncus malesuada. Sed ac sollicitudin nisi. Nunc venenatis congue quam, et suscipit diam consectetur id. Donec vel enim ac enim elementum bibendum ut quis augue. Nulla posuere suscipit dolor, id convallis tortor congue eu. Vivamus sagittis consectetur dictum. Duis a ante quis dui varius fermentum. In hac habitasse platea dictumst. Nam dapibus dolor eu felis eleifend in scelerisque dolor ultrices. Donec arcu lectus, fringilla ut interdum non, tristique id dolor. Morbi sagittis sagittis volutpat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis venenatis ultrices euismod.Nam sit amet convallis libero. Integer lectus urna, eleifend et sollicitudin non, porttitor vel erat. Vestibulum pulvinar egestas leo, a porttitor turpis ullamcorper et. Vestibulum in ornare turpis. Ut nec libero a sem mattis iaculis quis id purus. Praesent ante neque, dictum vitae pretium vel, iaculis luctus dui. Etiam luctus tellus vel nunc suscipit a ullamcorper nisl semper. Nunc dapibus, eros in sodales dignissim, orci lectus egestas felis, sit amet vehicula tortor dolor eu quam. Vivamus pellentesque convallis quam aliquet pellentesque. Phasellus facilisis arcu ac orci fringilla aliquet. Donec sed euismod augue. Duis eget orci sit amet neque tempor fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae In hac habitasse platea dictumst. Duis sollicitudin, lacus ac pellentesque lacinia, lacus magna pulvinar purus, pulvinar porttitor est nibh quis augue.Duis eleifend, massa sit amet mattis fringilla, elit turpis venenatis libero, sed convallis turpis diam sit amet ligula. Morbi non dictum turpis. Integer porttitor condimentum elit, sit amet sagittis nibh ultrices sit amet. Mauris ac arcu augue, id aliquet mauris. Donec ultricies urna id enim accumsan at pharetra dui adipiscing. Nunc luctus rutrum molestie. Curabitur libero ipsum, viverra at pulvinar ut, porttitor et neque. Aliquam sit amet dolor et purus sagittis adipiscing. Nam sit amet hendrerit sem. Etiam varius, ligula non ultricies dignissim, sapien dui commodo urna, eu vehicula enim nunc molestie augue. Fusce euismod, erat vitae pharetra tempor, quam eros tincidunt lorem, ut iaculis ligula erat vitae nibh. Aenean eu ultricies dolor. Curabitur suscipit viverra bibendum.Sed egestas adipiscing mi in egestas. Proin in neque in nibh blandit consequat nec quis tortor. Vestibulum sed interdum justo. Sed volutpat velit vitae elit pulvinar aliquam egestas elit rutrum. Proin lorem nibh, bibendum vitae sollicitudin condimentum, pulvinar ut turpis. Maecenas iaculis, mauris in consequat ultrices, ante erat blandit mi, vel fermentum lorem turpis eget sem. Integer ultrices tristique erat sit amet volutpat. In sit amet diam et nunc congue pellentesque at in dolor. Mauris eget orci orci. Integer posuere augue ornare tortor tempus elementum. Quisque iaculis, nunc ac cursus fringilla, magna elit cursus eros, id feugiat diam eros et tellus. Etiam consectetur ultrices erat quis rhoncus. Mauris eu lacinia neque. Curabitur suscipit feugiat tellus in dictum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed aliquam tempus ante a tempor. Praesent viverra erat quis sapien pretium rutrum. Praesent dictum scelerisque venenatis.Proin bibendum lectus eget nisl lacinia porta. Morbi eu erat in sapien malesuada vulputate. Cras non elit quam. Ut dictum urna quis nisl feugiat ac sollicitudin libero luctus. Donec leo mauris, varius at luctus eget, placerat quis arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae Etiam tristique, mauris ut lacinia elementum, mauris erat consequat massa, ac gravida nisi tellus vitae purus. Curabitur consectetur ultricies commodo. Cras pulvinar orci nec enim adipiscing tristique. Ut ornare orci id est fringilla sit amet blandit libero pellentesque. Vestibulum tincidunt sapien ut enim venenatis vestibulum ultricies ipsum tristique. Mauris tempus eleifend varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vitae dui ac quam gravida semper. In ac enim ac ligula rutrum porttitor.Integer dictum sagittis leo, at convallis sapien facilisis eget. Etiam cursus bibendum tortor, faucibus aliquam lectus ullamcorper sed. Nulla pulvinar posuere quam, ut sagittis ligula tincidunt ut. Nulla convallis velit ut enim condimentum pulvinar. Quisque gravida accumsan scelerisque. Proin pellentesque nisi cursus tortor aliquet dapibus. Duis vel eros orci. Sed eget purus ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ullamcorper porta congue. Nunc id velit ut neque malesuada consequat in eu nisi. Nulla facilisi. Quisque pellentesque magna vitae nisl euismod ac accumsan tellus feugiat.Nulla facilisi. Integer quis orci lectus, non aliquam nisi. Vivamus varius porta est, ac porttitor orci blandit mattis. Sed dapibus facilisis dapibus. Duis tincidunt leo ac tortor faucibus hendrerit. Morbi sit amet sapien risus, vel luctus enim. Aliquam sagittis nunc id purus aliquam lobortis. Duis posuere viverra dui, sit amet convallis sem vulputate at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pellentesque, lectus id imperdiet commodo, diam diam faucibus lectus, sit amet vestibulum tortor lacus viverra eros.Maecenas nec augue lectus. Duis nec arcu eget lorem tempus sollicitudin suscipit vitae arcu. Nullam vitae mauris lectus. Vivamus id risus neque, dignissim vehicula diam. Cras rhoncus velit sed velit iaculis ac dignissim turpis luctus. Suspendisse potenti. Sed vitae ligula a ligula ornare rutrum sit amet ut quam. Duis tincidunt, nibh vitae iaculis adipiscing, dolor orci cursus arcu, vel congue tortor quam eget arcu. Suspendisse tellus felis, blandit ac accumsan vitae, fringilla id lorem. Duis tempor lorem mollis est congue ut imperdiet velit laoreet. Nullam interdum cursus mollis. Pellentesque non mauris accumsan elit laoreet viverra ut at risus. Proin rutrum sollicitudin sem, vitae ultricies augue sagittis vel. Cras quis vehicula neque. Aliquam erat volutpat. Aliquam erat volutpat. Praesent non est erat, accumsan rutrum lacus. Pellentesque tristique molestie aliquet. Cras ullamcorper facilisis faucibus. In non lorem quis velit lobortis pulvinar.Phasellus non sem ipsum. Praesent ut libero quis turpis viverra semper. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In hac habitasse platea dictumst. Donec at velit tellus. Fusce commodo pharetra tincidunt. Proin lacus enim, fringilla a fermentum ut, vestibulum ut nibh. Duis commodo dolor vel felis vehicula at egestas neque bibendum. Phasellus malesuada dictum ante in aliquam. Curabitur interdum semper urna, nec placerat justo gravida in. Praesent quis mauris massa. Pellentesque porttitor lacinia tincidunt. Phasellus egestas viverra elit vel blandit. Sed dapibus nisi et lectus pharetra dignissim. Mauris hendrerit lectus nec purus dapibus condimentum. Sed ac eros nulla. Aenean semper sapien a nibh aliquam lobortis. Aliquam elementum euismod sapien, in dapibus leo dictum et. Pellentesque augue neque, ultricies non viverra eu, tincidunt ac arcu. Morbi ut porttitor lectus.")

            if useLabel :
                label = QLabel(text)
                label.setWordWrap(True)
                label.setTextInteractionFlags(Qt.TextEditorInteraction)

                palette = label.palette()
                palette.setColor(QPalette.Highlight, Qt.darkBlue)
                palette.setColor(QPalette.HighlightedText, Qt.white)
                label.setPalette(palette)

                scrollArea = QScrollArea()
                scrollArea.setWidget(label)

                widget.layout().addWidget(scrollArea)
            else:
                textEdit = QTextEdit(text)
                textEdit.setReadOnly(False)
                textEdit.setTextInteractionFlags(Qt.TextEditable)

                palette = textEdit.palette()
                palette.setColor(QPalette.Highlight, Qt.darkBlue)
                palette.setColor(QPalette.HighlightedText, Qt.white)
                textEdit.setPalette(palette)

                widget.layout().addWidget(textEdit)

            button = MyPushButton("Button")
            widget.layout().addWidget(button)

            widget.setGeometry(0, 0, 800, 600)

        graphicsScene = 0

        if  not sanityCheck :
            widgetImage = osgQt.QWidgetImage(widget)
#if QT_VERSION >= QT_VERSION_CHECK(4, 5, 0) :
            widgetImage.getQWidget().setAttribute(Qt.WA_TranslucentBackground)
#endif
            widgetImage.getQGraphicsViewAdapter().setBackgroundColor(QColor(0, 0, 0, 0))
            #widgetImage.getQGraphicsViewAdapter().resize(800, 600)
            graphicsScene = widgetImage.getQGraphicsViewAdapter().getQGraphicsScene()

            camera = 0        # Will stay NULL in the inScene case.
            quad = osg.createTexturedQuadGeometry(osg.Vec3(0,0,0), osg.Vec3(1,0,0), osg.Vec3(0,1,0), 1, 1)
            geode = osg.Geode()
            geode.addDrawable(quad)

            mt = osg.MatrixTransform()

            texture = osg.Texture2D(widgetImage)
            texture.setResizeNonPowerOfTwoHint(False)
            texture.setFilter(osg.Texture.MIN_FILTER,osg.Texture.LINEAR)
            texture.setWrap(osg.Texture.WRAP_S, osg.Texture.CLAMP_TO_EDGE)
            texture.setWrap(osg.Texture.WRAP_T, osg.Texture.CLAMP_TO_EDGE)
            mt.getOrCreateStateSet().setTextureAttributeAndModes(0, texture, osg.StateAttribute.ON)

            handler = osgViewer.InteractiveImageHandler*() 
            if inScene :
                mt.setMatrix(osg.Matrix.rotate(osg.Vec3(0,1,0), osg.Vec3(0,0,1)))
                mt.addChild(geode)

                handler = osgViewer.InteractiveImageHandler(widgetImage)
            else    # fullscreen
                # The HUD camera's viewport needs to follow the size of the 
                # window. MyInteractiveImageHandler will make sure of this.
                # As for the quad and the camera's projection, setting the 
                # projection resize policy to FIXED takes care of them, so
                # they can stay the same: (0,1,0,1) with a quad that fits.

                # Set the HUD camera's projection and viewport to match the screen.
                camera = osg.Camera()
                camera.setProjectionResizePolicy(osg.Camera.FIXED)
                camera.setProjectionMatrix(osg.Matrix.ortho2D(0,1,0,1))
                camera.setReferenceFrame(osg.Transform.ABSOLUTE_RF)
                camera.setViewMatrix(osg.Matrix.identity())
                camera.setClearMask(GL_DEPTH_BUFFER_BIT)
                camera.setRenderOrder(osg.Camera.POST_RENDER)
                camera.addChild(geode)
                camera.setViewport(0, 0, 1024, 768)

                mt.addChild(camera)

                handler = osgViewer.InteractiveImageHandler(widgetImage, texture, camera)

            mt.getOrCreateStateSet().setMode(GL_LIGHTING, osg.StateAttribute.OFF)
            mt.getOrCreateStateSet().setMode(GL_BLEND, osg.StateAttribute.ON)
            mt.getOrCreateStateSet().setRenderingHint(osg.StateSet.TRANSPARENT_BIN)
            mt.getOrCreateStateSet().setAttribute(osg.Program)()

            overlay = osg.Group()
            overlay.addChild(mt)

            root.addChild(overlay)
            
            quad.setEventCallback(handler)
            quad.setCullCallback(handler)
        else:
            # Sanity check, do the same thing as QWidgetImage and 
            # QGraphicsViewAdapter but in a separate Qt window.

            graphicsScene = QGraphicsScene()
            graphicsScene.addWidget(widget)

            graphicsView = QGraphicsView()
            graphicsView.setScene(graphicsScene)

            mainWindow = QMainWindow()
            mainWindow.setCentralWidget(graphicsView)
            mainWindow.setGeometry(50, 50, 1024, 768)
            mainWindow.show()
            mainWindow.raise()

        # Add numFloatingWindows windows to the graphicsScene.
        for (unsigned int i = 0 i < (unsigned int)numFloatingWindows ++i)
            window = QWidget(0, Qt.Window)
            window.setWindowTitle(QString("Window %1").arg(i))
            window.setLayout(QVBoxLayout)()
            window.layout().addWidget(QLabel(QString("This window %1").arg(i)))
            window.layout().addWidget(MyPushButton(QString("Button in window %1").arg(i)))
            window.setGeometry(100, 100, 300, 300)

            proxy = QGraphicsProxyWidget(0, Qt.Window)
            proxy.setWidget(window)
            proxy.setFlag(QGraphicsItem.ItemIsMovable, True)

            graphicsScene.addItem(proxy)


    root.addChild(osgDB.readNodeFile("cow.osg.(15,0,5).trans.(0.1,0.1,0.1).scale"))

    viewer = osgViewer.Viewer(arguments)
    viewer.setSceneData(root)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler(osgGA.StateSetManipulator(root.getOrCreateStateSet()))
    viewer.addEventHandler(osgViewer.StatsHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()

    viewer.setUpViewInWindow(50, 50, 1024, 768)
    viewer.getEventQueue().windowResize(0, 0, 1024, 768)

    if useFrameLoopThread :
        # create a thread to run the viewer's frame loop
        viewerThread = ViewerFrameThread(viewer, True)
        viewerThread.startThread()

        # now start the standard Qt event loop, then exists when the viewerThead sends the QApplication.exit() signal.
        return QApplication.exec()

    else:
        # run the frame loop, interleaving Qt and the main OSG frame loop
        while  not viewer.done() :
            # process Qt events - this handles both events and paints the browser image
            QCoreApplication.processEvents(QEventLoop.AllEvents, 100)

            viewer.frame()

        return 0
Example #24
0
def main(argv):

    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    # set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage().setApplicationName(arguments.getApplicationName())
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" example demonstrates the use of ImageStream for rendering movies as textures.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("--texture2D","Use Texture2D rather than TextureRectangle.")
    arguments.getApplicationUsage().addCommandLineOption("--shader","Use shaders to post process the video.")
    arguments.getApplicationUsage().addCommandLineOption("--interactive","Use camera manipulator to allow movement around movie.")
    arguments.getApplicationUsage().addCommandLineOption("--flip","Flip the movie so top becomes bottom.")
#if defined(WIN32)  or  defined(__APPLE__)
    arguments.getApplicationUsage().addCommandLineOption("--devices","Print the Video input capability via QuickTime and exit.")
#endif

    useTextureRectangle = True
    useShader = False

    # construct the viewer.
    viewer = osgViewer.Viewer(arguments)

    if arguments.argc()<=1 :
        arguments.getApplicationUsage().write(std.cout,osg.ApplicationUsage.COMMAND_LINE_OPTION)
        return 1

#if defined(WIN32)  or  defined(__APPLE__)
    # if user requests devices video capability.
    if arguments.read("-devices")  or  arguments.read("--devices") :
        # Force load QuickTime plugin, probe video capability, exit
        osgDB.readImageFile("devices.live")
        return 1
#endif

    while arguments.read("--texture2D") : useTextureRectangle=False
    while arguments.read("--shader") : useShader=True

    mouseTracking = False
    while arguments.read("--mouse") : mouseTracking=True


    # if user request help write it out to cout.
    if arguments.read("-h")  or  arguments.read("--help") :
        arguments.getApplicationUsage().write(std.cout)
        return 1

    fullscreen = not arguments.read("--interactive")
    flip = arguments.read("--flip")

    geode = osg.Geode()

    stateset = geode.getOrCreateStateSet()
    stateset.setMode(GL_LIGHTING,osg.StateAttribute.OFF)

    if useShader :
        #useTextureRectangle = False

        static  char *shaderSourceTextureRec = 
            "uniform vec4 cutoff_color\n"
            "uniform samplerRect movie_texture\n"
            "void main(void)\n"
            "\n"
            "    vec4 texture_color = textureRect(movie_texture, gl_TexCoord[0].st) \n"
            "    if all(lessThanEqual(texture_color,cutoff_color)) : discard \n"
            "    gl_FragColor = texture_color\n"
            "\n"
        

        static  char *shaderSourceTexture2D = 
            "uniform vec4 cutoff_color\n"
            "uniform sampler2D movie_texture\n"
            "void main(void)\n"
            "\n"
            "    vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0].st) \n"
            "    if all(lessThanEqual(texture_color,cutoff_color)) : discard \n"
            "    gl_FragColor = texture_color\n"
            "\n"
Example #25
0
def create3DText(center, radius):
    

    geode = osg.Geode()

####################################################
#    
# Examples of how to set up axis/orientation alignments
#

    characterSize = radius*0.2
    
    pos = osg.Vec3(center.x()-radius*.5,center.y()-radius*.5,center.z()-radius*.5)

    text1 = osgText.Text()
    text1.setFont(osgText.Font(osgQt.QFontImplementation(QFont("Times"))))
    text1.setCharacterSize(characterSize)
    text1.setPosition(pos)
    text1.setAxisAlignment(osgText.Text.XY_PLANE)
    text1.setText("XY_PLANE")
    geode.addDrawable(text1)

    text2 = osgText.Text()
    text2.setFont(osgText.Font(osgQt.QFontImplementation(QFont("Times"))))
    text2.setCharacterSize(characterSize)
    text2.setPosition(pos)
    text2.setAxisAlignment(osgText.Text.YZ_PLANE)
    text2.setText("YZ_PLANE")
    geode.addDrawable(text2)

    text3 = osgText.Text()
    text3.setFont(osgText.Font(osgQt.QFontImplementation(QFont("Times"))))
    text3.setCharacterSize(characterSize)
    text3.setPosition(pos)
    text3.setAxisAlignment(osgText.Text.XZ_PLANE)
    text3.setText("XZ_PLANE")
    geode.addDrawable(text3)


    text4 = osgText.Text()
    text4.setFont(osgText.Font(osgQt.QFontImplementation(QFont("Times"))))
    text4.setCharacterSize(characterSize)
    text4.setPosition(center)
    text4.setAxisAlignment(osgText.Text.SCREEN)

    characterSizeModeColor = osg.Vec4(1.0,0.0,0.5,1.0)

    text5 = osgText.Text()
    text5.setColor(characterSizeModeColor)
    text5.setFont(osgText.Font(osgQt.QFontImplementation(QFont("Times"))))
    #text5.setCharacterSize(characterSize)
    text5.setCharacterSize(32.0) # medium
    text5.setPosition(center - osg.Vec3(0.0, 0.0, 0.2))
    text5.setAxisAlignment(osgText.Text.SCREEN)
    text5.setCharacterSizeMode(osgText.Text.SCREEN_COORDS)
    text5.setText("CharacterSizeMode SCREEN_COORDS(size 32.0)")
    geode.addDrawable(text5)

    text6 = osgText.Text()
    text6.setColor(characterSizeModeColor)
    text6.setFont(osgText.Font(osgQt.QFontImplementation(QFont("Times"))))
    text6.setCharacterSize(characterSize)
    text6.setPosition(center - osg.Vec3(0.0, 0.0, 0.4))
    text6.setAxisAlignment(osgText.Text.SCREEN)
    text6.setCharacterSizeMode(osgText.Text.OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT)
    text6.setText("CharacterSizeMode OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT")
    geode.addDrawable(text6)

    text7 = osgText.Text()
    text7.setColor(characterSizeModeColor)
    text7.setFont(osgText.Font(osgQt.QFontImplementation(QFont("Times"))))
    text7.setCharacterSize(characterSize)
    text7.setPosition(center - osg.Vec3(0.0, 0.0, 0.6))
    text7.setAxisAlignment(osgText.Text.SCREEN)
    text7.setCharacterSizeMode(osgText.Text.OBJECT_COORDS)
    text7.setText("CharacterSizeMode OBJECT_COORDS (default)")
    geode.addDrawable(text7)

#if 1
    # reproduce outline bounding box compute problem with backdrop on.
    text4.setBackdropType(osgText.Text.OUTLINE)
    text4.setDrawMode(osgText.Text.TEXT | osgText.Text.BOUNDINGBOX)
#endif

    text4.setText("SCREEN")
    geode.addDrawable(text4)

    shape = osg.ShapeDrawable(osg.Sphere(center,characterSize*0.2))
    shape.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.ON)
    geode.addDrawable(shape)

    rootNode = osg.Group()
    rootNode.addChild(geode)

    return rootNode    
            #print out the first three values
            data = (float*)_image.data(0, 0)
            fprintf(stderr,"Float pixel data: r %e g %e b %e\n", data[0], data[1], data[2])

    _image = osg.Image*()


#define NUM_TEXTURES 4

# The quad geometry is used by the render to texture camera to generate multiple textures.
def createRTTQuad(tex_width, tex_height, useHDR):
    
    top_group = osg.Group()

    quad_geode = osg.Geode()

    quad_coords = osg.Vec3Array() # vertex coords
    # counter-clockwise
    quad_coords.push_back(osg.Vec3d(0, 0, -1))
    quad_coords.push_back(osg.Vec3d(1, 0, -1))
    quad_coords.push_back(osg.Vec3d(1, 1, -1))
    quad_coords.push_back(osg.Vec3d(0, 1, -1))

    quad_tcoords = osg.Vec2Array() # texture coords
    quad_tcoords.push_back(osg.Vec2(0, 0))
    quad_tcoords.push_back(osg.Vec2(tex_width, 0))
    quad_tcoords.push_back(osg.Vec2(tex_width, tex_height))
    quad_tcoords.push_back(osg.Vec2(0, tex_height))

    quad_geom = osg.Geometry()
Example #27
0
            # just add ascii characters right now...
            _inputText.getText().push_back(key)
            _inputText.update()
        elif key==osgGA.GUIEventAdapter.KEY_Return :
            _inputText.getText().push_back('\n')
            _inputText.update()
        elif key==osgGA.GUIEventAdapter.KEY_BackSpace  or  key==osgGA.GUIEventAdapter.KEY_Delete : 
            if  not _inputText.getText().empty() :
                _inputText.getText().pop_back()
                _inputText.update()
        
    

osg.Switch* KeyboardModel.addKey(osg.Vec3 pos, int key, str text,float width, float height)

    geodeUp = osg.Geode()
        textUp = osgText.Text()
        textUp.setFont("fonts/arial.ttf")
        textUp.setColor(osg.Vec4(1.0,1.0,1.0,1.0))
        textUp.setCharacterSize(height)
        textUp.setPosition(pos)
        textUp.setDrawMode(osgText.Text.TEXT#|osgText.Text.BOUNDINGBOX)
        textUp.setAlignment(osgText.Text.LEFT_CENTER)
        textUp.setAxisAlignment(osgText.Text.XZ_PLANE)
        textUp.setText(text)
        
        geodeUp.addDrawable(textUp)
    
    geodeDown = osg.Geode()
        textDown = osgText.Text()
        textDown.setFont("fonts/arial.ttf")
Example #28
0
def createPyramid():
    pyramidGeode = osg.Geode()
    pyramidGeometry = osg.Geometry()
    pyramidGeode.addDrawable(pyramidGeometry)

    # Specify the vertices:
    pyramidVertices = osg.Vec3Array()
    pyramidVertices.append(osg.Vec3(0, 0, 0))  # front left
    pyramidVertices.append(osg.Vec3(2, 0, 0))  # front right
    pyramidVertices.append(osg.Vec3(2, 2, 0))  # back right
    pyramidVertices.append(osg.Vec3(0, 2, 0))  # back left
    pyramidVertices.append(osg.Vec3(1, 1, 2))  # peak

    # Associate this set of vertices with the geometry associated with the
    # geode we added to the scene.
    pyramidGeometry.setVertexArray(pyramidVertices)

    # Create a QUAD primitive for the base by specifying the
    # vertices from our vertex list that make up this QUAD:
    pyramidBase = osg.DrawElementsUInt(osg.PrimitiveSet.QUADS, 0)
    pyramidBase.append(3)
    pyramidBase.append(2)
    pyramidBase.append(1)
    pyramidBase.append(0)

    # Add this primitive to the geometry:
    # pyramidGeometry.addPrimitiveSet(pyramidBase)
    # code to create other faces goes here!
    pyramidGeometry.addPrimitiveSet(pyramidBase)
    # Repeat the same for each of the four sides. Again, vertices are specified in counter-clockwise order.
    pyramidFaceOne = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
    pyramidFaceOne.append(0)
    pyramidFaceOne.append(1)
    pyramidFaceOne.append(4)
    pyramidGeometry.addPrimitiveSet(pyramidFaceOne)

    pyramidFaceTwo = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
    pyramidFaceTwo.append(1)
    pyramidFaceTwo.append(2)
    pyramidFaceTwo.append(4)
    pyramidGeometry.addPrimitiveSet(pyramidFaceTwo)

    pyramidFaceThree = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
    pyramidFaceThree.append(2)
    pyramidFaceThree.append(3)
    pyramidFaceThree.append(4)
    pyramidGeometry.addPrimitiveSet(pyramidFaceThree)

    pyramidFaceFour = osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLES, 0)
    pyramidFaceFour.append(3)
    pyramidFaceFour.append(0)
    pyramidFaceFour.append(4)
    pyramidGeometry.addPrimitiveSet(pyramidFaceFour)

    colors = osg.Vec4Array()
    colors.append(osg.Vec4(1.0, 0.0, 0.0, 1.0))  #index 0 red
    colors.append(osg.Vec4(0.0, 1.0, 0.0, 1.0))  #index 1 green
    colors.append(osg.Vec4(0.0, 0.0, 1.0, 1.0))  #index 2 blue
    colors.append(osg.Vec4(1.0, 1.0, 1.0, 1.0))  #index 3 white
    colors.append(osg.Vec4(1.0, 0.0, 0.0, 1.0))  #index 4 red

    pyramidGeometry.setColorArray(colors)
    pyramidGeometry.setColorBinding(osg.Geometry.BIND_PER_VERTEX)

    # Since the mapping from vertices to texture coordinates is 1:1,
    # we don't need to use an index array to map vertices to texture
    # coordinates. We can do it directly with the 'setTexCoordArray'
    # method of the Geometry class.
    # This method takes a variable that is an array of two dimensional
    # vectors (osg.Vec2). This variable needs to have the same
    # number of elements as our Geometry has vertices. Each array element
    # defines the texture coordinate for the cooresponding vertex in the
    # vertex array.
    texcoords = osg.Vec2Array(5)
    texcoords[0].set(0.00, 0.0)  # tex coord for vertex 0
    texcoords[1].set(0.25, 0.0)  # tex coord for vertex 1
    texcoords[2].set(0.50, 0.0)  # ""
    texcoords[3].set(0.75, 0.0)  # ""
    texcoords[4].set(0.50, 1.0)  # ""
    pyramidGeometry.setTexCoordArray(0, texcoords)

    return pyramidGeode
Example #29
0
    # we need to add the texture to the Drawable, we do so by creating a
    # StateSet to contain the Texture2D StateAttribute.
    stateset = osg.StateSet()

    # set up the texture.
    texture = osg.Texture2D()
    texture.setImage(image)

    stateset.setTextureAttributeAndModes(0, texture,osg.StateAttribute.ON)

    polyGeom.setStateSet(stateset)


    # create the Geode (Geometry Node) to contain all our osg.Geometry objects.
    geode = osg.Geode()

    # add the points geometry to the geode.
    geode.addDrawable(polyGeom)

    #return geode

    # create a transform to move the background back and forward with.

    transform = osg.MatrixTransform()
    transform.setUpdateCallback(MyTransformCallback(1.0))
    transform.addChild(geode)

    return transform

int main(int, char **)
def createRectangle(bb, filename):


    
    top_left = osg.Vec3(bb.xMin(),bb.yMax(),bb.zMax())
    bottom_left = osg.Vec3(bb.xMin(),bb.yMax(),bb.zMin())
    bottom_right = osg.Vec3(bb.xMax(),bb.yMax(),bb.zMin())
    top_right = osg.Vec3(bb.xMax(),bb.yMax(),bb.zMax())

    # create geometry
    geom = osg.Geometry()

    vertices = osg.Vec3Array(4)
    (*vertices)[0] = top_left
    (*vertices)[1] = bottom_left
    (*vertices)[2] = bottom_right
    (*vertices)[3] = top_right
    geom.setVertexArray(vertices)

    texcoords = osg.Vec2Array(4)
    (*texcoords)[0].set(0.0, 0.0)
    (*texcoords)[1].set(1.0, 0.0)
    (*texcoords)[2].set(1.0, 1.0)
    (*texcoords)[3].set(0.0, 1.0)
    geom.setTexCoordArray(0,texcoords)

    normals = osg.Vec3Array(1)
    (*normals)[0].set(0.0,-1.0,0.0)
    geom.setNormalArray(normals, osg.Array.BIND_OVERALL)

    colors = osg.Vec4Array(1)
    (*colors)[0].set(1.0,1.0,1.0,1.0)
    geom.setColorArray(colors, osg.Array.BIND_OVERALL)

    geom.addPrimitiveSet(osg.DrawArrays(GL_QUADS, 0, 4))

    # disable display list so our modified tex coordinates show up
    geom.setUseDisplayList(False)

    # load image
    img = osgDB.readImageFile(filename)

    # setup texture
    texture = osg.TextureRectangle(img)

    texmat = osg.TexMat()
    texmat.setScaleByTextureRectangleSize(True)

    # setup state
    state = geom.getOrCreateStateSet()
    state.setTextureAttributeAndModes(0, texture, osg.StateAttribute.ON)
    state.setTextureAttributeAndModes(0, texmat, osg.StateAttribute.ON)

    # turn off lighting
    state.setMode(GL_LIGHTING, osg.StateAttribute.OFF)

    # install 'update' callback
    geode = osg.Geode()
    geode.addDrawable(geom)
    geode.setUpdateCallback(TexturePanCallback(texmat))

    return geode