Example #1
0
def createMovingModel(center, radius):
    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.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,1.0))
        xform.addChild(positioned)
        model.addChild(xform)
    cessna = osgDB.readNodeFile("cessna.osgt")
    if cessna :
        bs = cessna.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(180.0),0.0,0.0,1.0))
        positioned.addChild(cessna)
        xform = osg.MatrixTransform()
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,2.0))
        xform.addChild(positioned)
        model.addChild(xform)
    return model
Example #2
0
def main(argv):


    
    arguments = osg.ArgumentParser(argv)
    
    node = osg.Group()

    if arguments.read("--MyUserDataContainer")  or  arguments.read("--mydc") :
        node.setUserDataContainer(MyNamespace.MyUserDataContainer)()
    
    i = 10
    node.setUserValue("Int value",i)

    testString = str("All seems fine")
    node.setUserValue("Status",testString)

    node.setUserValue("Height",float(1.4))

    drawable = osg.Geometry()
    drawable.setName("myDrawable")
    node.getOrCreateUserDataContainer().addUserObject(drawable)

    node.setUserValue("fred",12)
    node.setUserValue("john",1.1)
    node.setUserValue("david",1.9)
    node.setUserValue("char",char(65))
    node.setUserValue("matrixd",osg.Matrixd.translate(1.0,2.0,3.0))
    node.setUserValue("flag-on",True)
    node.setUserValue("flag-off",False)

    OSG_NOTICE, "Testing results for values set directly on scene graph"
    testResults(node)

        osgDB.writeNodeFile(*node, "results.osgt")

        from_osgt = osgDB.readNodeFile("results.osgt")
        if from_osgt.valid() :
            OSG_NOTICE, "Testing results for values from scene graph read from .osgt file"
            testResults(from_osgt)
    
        osgDB.writeNodeFile(*node, "results.osgb")

        from_osgb = osgDB.readNodeFile("results.osgb")
        if from_osgb.valid() :
            OSG_NOTICE, "Testing results for values from scene graph read from .osgb file"
            testResults(from_osgb)

        osgDB.writeNodeFile(*node, "results.osgx")

        from_osgx = osgDB.readNodeFile("results.osgx")
        if from_osgx.valid() :
            OSG_NOTICE, "Testing results for values from scene graph read from .osgx file"
            testResults(from_osgx)
Example #3
0
def main(argv):

    
    loadedModel = osg.Node()
    
    # load the scene.
    if argc>1 : loadedModel = osgDB.readNodeFile(argv[1])
    
    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not loadedModel : loadedModel = osgDB.readNodeFile("dumptruck.osgt")
    
    if  not loadedModel : 
        print argv[0], ": No data loaded."
        return 1
    
    # create the window to draw to.
    traits = osg.GraphicsContext.Traits()
    traits.x = 200
    traits.y = 200
    traits.width = 800
    traits.height = 600
    traits.windowDecoration = True
    traits.doubleBuffer = True
    traits.sharedContext = 0

    gc = osg.GraphicsContext.createGraphicsContext(traits)
    gw = dynamic_cast<osgViewer.GraphicsWindow*>(gc)
    if  not gw :
        osg.notify(osg.NOTICE), "Error: unable to create graphics window."
        return 1

    # create the view of the scene.
    viewer = osgViewer.Viewer()
    viewer.getCamera().setGraphicsContext(gc)
    viewer.getCamera().setViewport(0,0,800,600)
    viewer.setSceneData(loadedModel)
    
    # create a tracball manipulator to move the camera around in response to keyboard/mouse events
    viewer.setCameraManipulator( osgGA.TrackballManipulator )()

    statesetManipulator = osgGA.StateSetManipulator(viewer.getCamera().getStateSet())
    viewer.addEventHandler(statesetManipulator)

    # add the pick handler
    viewer.addEventHandler(PickHandler())

    viewer.realize()

    # main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
    while  not viewer.done() :
        viewer.frame()

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


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

    # load the nodes from the commandline arguments.
    loadedModel = osgDB.readNodeFiles(arguments)


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


    if  not loadedModel :
        osg.notify(osg.NOTICE), "Please specifiy a filename and the command line"
        return 1
  
    # decorate the scenegraph with a clip node.
    rootnode = decorate_with_clip_node(loadedModel)
      
    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(rootnode)
    
    viewer = osgViewer.Viewer()
     
    # set the scene to render
    viewer.setSceneData(rootnode)

    return viewer.run()
def main(argv):
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)
    # set the osgDB.Registy read file callback to catch all requests for reading files.
    osgDB.Registry.instance().setReadFileCallback(MyReadFileCallback())
    # initialize the viewer.
    viewer = osgViewer.Viewer()
    # load the nodes from the commandline arguments.
    rootnode = osgDB.readNodeFiles(arguments)
    # if not loaded assume no arguments passed in, try use default mode instead.
    if rootnode is None:
        rootnode = osgDB.readNodeFile("cow.osgt")
    if rootnode is None:
        osg.notify(osg.NOTICE), "Please specify a file on the command line"
        return 1
    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(rootnode)
    # insert all the callbacks
    icv = InsertCallbacksVisitor()
    # rootnode.accept(icv)
    cuc = CameraUpdateCallback() # TODO - crashes if I do create this persistent reference 
    viewer.getCamera().setUpdateCallback( cuc )
    ceu = CameraEventCallback() # TODO - crashes if I do create this persistent reference 
    viewer.getCamera().setEventCallback(ceu)
    # set the scene to render
    viewer.setSceneData(rootnode)
    return viewer.run()
Example #6
0
def main(argv):

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

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

    # load the nodes from the commandline arguments.
    loadedModel = osgDB.readNodeFiles(arguments)

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

    # create a room made of foor walls, a floor, a roof, and swinging light fitting.
    rootnode = createRoom(loadedModel)

    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(rootnode)

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


    # create the windows and run the threads.
    viewer.realize()

    viewer.getCamera().setCullingMode( viewer.getCamera().getCullingMode()  ~osg.CullStack.SMALL_FEATURE_CULLING)

    return viewer.run()
Example #7
0
def main(argv):


    
    arguments = osg.ArgumentParser(argv)
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] <file>")
    arguments.getApplicationUsage().addCommandLineOption("--testOcclusion","Test occlusion by other objects")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")

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

    # load outlined object
    modelFilename = arguments.argc() >  arguments[1] if (1) else  "dumptruck.osgt"
    outlineModel = osgDB.readNodeFile(modelFilename)
    if  not outlineModel :
        osg.notify(osg.FATAL), "Unable to load model '", modelFilename, "'\n"
        return -1

    # create scene
    root = osg.Group()

        # create outline effect
        outline = osgFX.Outline()
        root.addChild(outline)

        outline.setWidth(8)
        outline.setColor(osg.Vec4(1,1,0,1))
        outline.addChild(outlineModel)
def main(argv):

    
    viewer = osgViewer.Viewer()

    wm = osgWidget.WindowManager(
        viewer,
        1280.0,
        1024.0,
        MASK_2D,
        osgWidget.WindowManager.WM_PICK_DEBUG
    )

    menu = osgWidget.Box("menu", osgWidget.Box.HORIZONTAL)

    menu.addWidget(ColorLabelMenu("Pick me not "))
    menu.addWidget(ColorLabelMenu("No, wait, pick me not "))
    menu.addWidget(ColorLabelMenu("Don't pick them..."))
    menu.addWidget(ColorLabelMenu("Grarar not ? not "))

    wm.addChild(menu)
    
    menu.getBackground().setColor(1.0, 1.0, 1.0, 0.0)
    menu.resizePercent(100.0)

    model = osgDB.readNodeFile("osgcool.osgt")

    model.setNodeMask(MASK_3D)

    return osgWidget.createExample(viewer, wm, model)
Example #9
0
def main(argv):

    
    theme = "osgWidget/theme-1.png"
    if argc > 1 :
        theme = str(argv[1])

    viewer = osgViewer.Viewer()

    wm = osgWidget.WindowManager(
        viewer,
        1280.0,
        1024.0,
        MASK_2D,
        osgWidget.WindowManager.WM_PICK_DEBUG
    )

    frame = createErrorMessage(theme,
                                          "osgWidget/theme-8-shadow.png",
                                          "Error - Critical",
                                          LABEL1,
                                          "Ok",
                                          "fonts/Vera.ttf",
                                          20)
    # Add everything to the WindowManager.
    wm.addChild(frame)
    frame.resizeAdd(30, 30)

    alpha = AlphaSetterVisitor(.8)
    frame.accept(alpha)
    return osgWidget.createExample(viewer, wm, osgDB.readNodeFile("cow.osgt"))
Example #10
0
def main(argv):
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)
    # set the osgDB.Registy read file callback to catch all requests for reading files.
    osgDB.Registry.instance().setReadFileCallback(MyReadFileCallback())
    # initialize the viewer.
    viewer = osgViewer.Viewer()
    # load the nodes from the commandline arguments.
    rootnode = osgDB.readNodeFiles(arguments)
    # if not loaded assume no arguments passed in, try use default mode instead.
    if rootnode is None:
        rootnode = osgDB.readNodeFile("cow.osgt")
    if rootnode is None:
        osg.notify(osg.NOTICE), "Please specify a file on the command line"
        return 1
    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(rootnode)
    # insert all the callbacks
    icv = InsertCallbacksVisitor()
    # rootnode.accept(icv)
    cuc = CameraUpdateCallback(
    )  # TODO - crashes if I do create this persistent reference
    viewer.getCamera().setUpdateCallback(cuc)
    ceu = CameraEventCallback(
    )  # TODO - crashes if I do create this persistent reference
    viewer.getCamera().setEventCallback(ceu)
    # set the scene to render
    viewer.setSceneData(rootnode)
    return viewer.run()
Example #11
0
def main(argv):

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

    # load the nodes from the commandline arguments.
    loadedModel = osgDB.readNodeFiles(arguments)

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

    if not loadedModel:
        osg.notify(
            osg.NOTICE), "Please specifiy a filename and the command line"
        return 1

    # decorate the scenegraph with a clip node.
    rootnode = decorate_with_clip_node(loadedModel)

    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(rootnode)

    viewer = osgViewer.Viewer()

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

    return viewer.run()
def main(argv):

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

    # load the nodes from the commandline arguments.
    rootnode = osgDB.readNodeFiles(arguments)
    
    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not rootnode : rootnode = osgDB.readNodeFile("cessnafire.osgt")
    
    if  not rootnode :
        osg.notify(osg.NOTICE), "Please specify a model filename on the command line."
        return 1
    
    image = osgDB.readImageFile("Images/reflect.rgb")
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)

        texgen = osg.TexGen()
        texgen.setMode(osg.TexGen.SPHERE_MAP)

        texenv = osg.TexEnv()
        texenv.setMode(osg.TexEnv.BLEND)
        texenv.setColor(osg.Vec4(0.3,0.3,0.3,0.3))

        stateset = osg.StateSet()
        stateset.setTextureAttributeAndModes(1,texture,osg.StateAttribute.ON)
        stateset.setTextureAttributeAndModes(1,texgen,osg.StateAttribute.ON)
        stateset.setTextureAttribute(1,texenv)
        
        rootnode.setStateSet(stateset)
    else:
        osg.notify(osg.NOTICE), "unable to load reflect map, model will not be mutlitextured"

    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(rootnode)
     
    # add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData( rootnode )
    
    # create the windows and run the threads.
    viewer.realize()

    for(unsigned int contextID = 0 
        contextID<osg.DisplaySettings.instance().getMaxNumberOfGraphicsContexts()
        ++contextID)
        textExt = osg.Texture.getExtensions(contextID,False)
        if textExt :
            if  not textExt.isMultiTexturingSupported() :
                print "Warning: multi-texturing not supported by OpenGL drivers, unable to run application."
                return 1
Example #13
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().setDescription(arguments.getApplicationName()+" is the example which demonstrates use of convex planer occluders.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("-m","Mannually create occluders")

    # initialize the viewer.
    viewer = osgViewer.Viewer()

    manuallyCreateOccluders = False
    while arguments.read("-m") :  manuallyCreateOccluders = True 

    if manuallyCreateOccluders :
        viewer.addEventHandler(OccluderEventHandler(viewer))

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

    # load the nodes from the commandline arguments.
    loadedmodel = osgDB.readNodeFiles(arguments)

    # if not loaded assume no arguments passed in, try using default mode instead.
    if  not loadedmodel : loadedmodel = osgDB.readNodeFile("glider.osgt")

    if  not loadedmodel :
        osg.notify(osg.NOTICE), "Please specify a model filename on the command line."
        return 1

    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(loadedmodel)

    # add the occluders to the loaded model.
    rootnode = osg.Group()

    if manuallyCreateOccluders :
        rootnode = osg.Group()
        rootnode.addChild(loadedmodel)
    else:
        rootnode = createOccludersAroundModel(loadedmodel)


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

    return viewer.run()
def getShape(name):

    
    shape0 = osgDB.readNodeFile(name)
    if shape0 :
        finder = GeometryFinder()
        shape0.accept(finder)
        return finder._geom
    else:
        return NULL
Example #15
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()+" is an OpenSceneGraph example that shows how to use the accumulation buffer to achieve a simple motion blur effect.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("-P or --persistence","Set the motion blur persistence time")
    

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

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

    persistence = 0.25
    arguments.read("-P", persistence)  or  arguments.read("--persistence", persistence)

    # read the scene from the list of file specified commandline args.
    loadedModel = osgDB.readNodeFiles(arguments)
    
    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not loadedModel : loadedModel = osgDB.readNodeFile("cow.osgt")

    # if no model has been successfully loaded report failure.
    if  not loadedModel : 
        print arguments.getApplicationName(), ": No data loaded"
        return 1


    # set the display settings we can to request, OsgCameraGroup will read this.
    osg.DisplaySettings.instance().setMinimumNumAccumBits(8,8,8,8)

    # pass the loaded scene graph to the viewer.
    viewer.setSceneData(loadedModel)

    # create the windows and run the threads.
    viewer.realize()

    windows = osgViewer.Viewer.Windows()
    viewer.getWindows(windows)
    for(osgViewer.Viewer.Windows.iterator itr = windows.begin()
        not = windows.end()
        ++itr)
        (*itr).add(MotionBlurOperation(persistence))
Example #16
0
def main(argv):


    

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

    # load the images specified on command line
    loadedModel = osgDB.readNodeFiles(arguments)
  
    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not loadedModel : loadedModel = osgDB.readNodeFile("dumptruck.osgt")
    
    if  not loadedModel :
        osg.notify(osg.NOTICE), arguments.getApplicationUsage().getCommandLineUsage()
        return 0

    stateset = create1DTextureStateToDecorate(loadedModel)
    if  not stateset :
        print "Error: failed to create 1D texture state."
        return 1


    loadedModel.setStateSet(stateset)

    osg. Group *root = osg. Group()
    root . addChild( loadedModel )

    # The contour banded color texture is used in conjunction with TexGenNode
    # to create contoured models, either in object linear coords - like
    # contours on a map, or eye linear which contour the distance from
    # the eye. An app callback toggles between the two tex gen modes.
    texgenNode = osg.TexGenNode()
    texgenNode.setReferenceFrame( osg.TexGenNode.ABSOLUTE_RF )
    texgenNode.getTexGen().setMode( osg.TexGen.OBJECT_LINEAR )

    bs = loadedModel.getBound()
    zBase = bs.center().z()-bs.radius()
    zScale = 2.0/bs.radius()
    texgenNode.getTexGen().setPlane(osg.TexGen.S,osg.Plane(0.0,0.0,zScale,-zBase))

    texgenNode.setUpdateCallback(AnimateTexGenCallback())

    root . addChild( texgenNode )


    viewer.setSceneData( root )

    return viewer.run()
Example #17
0
    def _clicked(widget):

        
        text = gtk_label_get_label(
            GTK_LABEL(gtk_bin_get_child(GTK_BIN(widget)))
        )

        if not strncmp(text, "Close", 5) : gtk_main_quit()
    
        elif not strncmp(text, "Open File", 9) : 
            of = gtk_file_chooser_dialog_new(
                "Please select an OSG file...",
                GTK_WINDOW(gtk_widget_get_toplevel(getWidget())),
                GTK_FILE_CHOOSER_ACTION_OPEN,
                GTK_STOCK_CANCEL,
                GTK_RESPONSE_CANCEL,
                GTK_STOCK_OPEN,
                GTK_RESPONSE_ACCEPT,
                NULL
            )

            if gtk_dialog_run(GTK_DIALOG(of)) == GTK_RESPONSE_ACCEPT : 
                file = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(of))

                model = osgDB.readNodeFile(file)

                if model.valid() : 
                    setSceneData(model)
                
                    queueDraw()

                g_free(file)
            
            gtk_widget_destroy(of)

        # Assume we're wanting FPS toggling.
        else:
            if not _tid : 
                _tid = g_timeout_add(
                    15,
                    (GSourceFunc)(ExampleOSGGTKDrawingArea.timeout),
                    this
                )

                gtk_button_set_label(GTK_BUTTON(widget), "Toggle 60 FPS (off)")

            else:
                g_source_remove(_tid)
                gtk_button_set_label(GTK_BUTTON(widget), "Toggle 60 FPS (on)")

                _tid = 0

        return True
 def open(group):
 
     
     files = Files()
     readMasterFile(files)
     for(Files.iterator itr = files.begin()
         not = files.end()
         ++itr)
         model = osgDB.readNodeFile(*itr)
         if model :
             osg.notify(osg.NOTICE), "open: Loaded file ", *itr
             group.addChild(model)
             _existingFilenameNodeMap[*itr] = model
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 how to use glBlendEquation for mixing rendered scene and the frame-buffer.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
   
    # construct the viewer.
    viewer = osgViewer.Viewer()

    # load the nodes from the commandline arguments.
    loadedModel = osgDB.readNodeFiles(arguments)

    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not loadedModel : loadedModel = osgDB.readNodeFile("cessnafire.osgt")
  
    if  not loadedModel :
        print arguments.getApplicationName(), ": No data loaded"
        return 1

    root = osg.Group()
    root.addChild(loadedModel)
    
    
    stateset = osg.StateSet()
    stateset.setDataVariance(osg.Object.DYNAMIC)
    
    blendEquation = osg.BlendEquation(osg.BlendEquation.FUNC_ADD)
    blendEquation.setDataVariance(osg.Object.DYNAMIC)
    
    stateset.setAttributeAndModes(blendEquation,osg.StateAttribute.OVERRIDE|osg.StateAttribute.ON)
            
    #tell to sort the mesh before displaying it
    stateset.setRenderingHint(osg.StateSet.TRANSPARENT_BIN)           

    loadedModel.setStateSet(stateset)

    viewer.addEventHandler(TechniqueEventHandler(blendEquation))

    # add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData( root )
    
    return viewer.run()
Example #20
0
def main(argv):




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

    # load the nodes from the commandline arguments.
    loadedModel = osgDB.readNodeFiles(arguments)
    
    # if not loaded assume no arguments passed in, try use default mode instead.
    if  not loadedModel : loadedModel = osgDB.readNodeFile("glider.osgt")
    
    if  not loadedModel :
        osg.notify(osg.NOTICE), "Please specify model filename on the command line."
        return 1
  
    root = osg.Group()
    root.addChild(loadedModel)
    
    stateset = osg.StateSet()
    logicOp = osg.LogicOp(osg.LogicOp.OR_INVERTED)

    stateset.setAttributeAndModes(logicOp,osg.StateAttribute.OVERRIDE|osg.StateAttribute.ON)

    #tell to sort the mesh before displaying it
    stateset.setRenderingHint(osg.StateSet.TRANSPARENT_BIN)


    loadedModel.setStateSet(stateset)

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

    viewer.addEventHandler(TechniqueEventHandler(logicOp))
    
    # run optimization over the scene graph
    optimzer = osgUtil.Optimizer()
    optimzer.optimize(root)
     
    # add a viewport to the viewer and attach the scene graph.
    viewer.setSceneData( root )
    
    return viewer.run()
Example #21
0
def main(argv):

    
    arguments = osg.ArgumentParser( argc, argv )
    model = osgDB.readNodeFiles( arguments )
    if   not model  : model = osgDB.readNodeFile( "cow.osgt" )
    if   not model  : 
        print arguments.getApplicationName(), ": No data loaded"
        return 1
    
    viewer = CustomViewer()
    viewer.addEventHandler( JoystickHandler )()
    viewer.addEventHandler( osgViewer.StatsHandler )()
    viewer.addEventHandler( osgViewer.WindowSizeHandler )()
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
    viewer.setSceneData( model )
    viewer.setUpViewInWindow( 250, 50, 800, 600 )
    return viewer.run()
Example #22
0
def main(argv):
    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

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

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

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

    # if no model has been successfully loaded report failure.
    if  not loadedModel :
        print arguments.getApplicationName(), ": No data loaded"
        return 1


    # optimize the scene graph, remove redundant nodes and state etc.
    optimizer = osgUtil.Optimizer()
    optimizer.optimize(loadedModel)

    # add a transform with a callback to animate the loaded model.
    loadedModelTransform = osg.MatrixTransform()
    loadedModelTransform.addChild(loadedModel)

    nc = osg.AnimationPathCallback(loadedModelTransform.getBound().center(),osg.Vec3(0.0,0.0,1.0),osg.inDegrees(45.0))
    loadedModelTransform.setUpdateCallback(nc)


    # finally decorate the loaded model so that it has the required multipass/bin scene graph to do the reflection effect.
    rootNode = createMirroredScene(loadedModelTransform)

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

    # hint to tell viewer to request stencil buffer when setting up windows
    osg.DisplaySettings.instance().setMinimumNumStencilBits(8)

    #osgDB.writeNodeFile(*rootNode, "test.osgt")

    return viewer.run()
Example #23
0
 def handle(ea, aa):
     
     
     viewer = dynamic_cast<osgViewer.Viewer*>(aa)
     if  not viewer : return False
 
     if _filenames.empty() : return False
 
     switch(ea.getEventType())
         case(osgGA.GUIEventAdapter.KEYUP):
             if ea.getKey()==ord("l") :
                 model = osgDB.readNodeFile( _filenames[_position] )
                 ++_position
                 if _position>=_filenames.size() : _position = 0
                 
                 if model.valid() :
                     viewer.setSceneData(model)
                 
                 return True
Example #24
0
def main(argv):
    
    gtk_init(argc, argv)
    gtk_gl_init(argc, argv)

    da = ExampleOSGGTKDrawingArea()

    if da.createWidget(640, 480) : 
        if argc >= 2 : 
            model = osgDB.readNodeFile(argv[1])

            if model.valid() : da.setSceneData(model)

        window = gtk_window_new(GTK_WINDOW_TOPLEVEL)
        vbox1 = gtk_vbox_new(False, 3)
        vbox2 = gtk_vbox_new(False, 3)
        hbox = gtk_hbox_new(False, 3)
        label = gtk_label_new("")
        GtkWidget* buttons[] = 
            gtk_button_new_with_label("Open File"),
            gtk_button_new_with_label("Toggle 60 FPS (on)"),
            gtk_button_new_with_label("Close")
        

        gtk_label_set_use_markup(GTK_LABEL(label), True)
        gtk_label_set_label(GTK_LABEL(label), HELP_TEXT)

        for(unsigned int i = 0 i < sizeof(buttons) / sizeof(GtkWidget*) i++) 
            gtk_box_pack_start(
                GTK_BOX(vbox2),
                buttons[i],
                False,
                False,
                0
            )

            g_signal_connect(
                G_OBJECT(buttons[i]),
                "clicked",
                G_CALLBACK(ExampleOSGGTKDrawingArea.clicked),
                da
            )
Example #25
0
def main(argv):

    
    viewer = osgViewer.Viewer()

    wm = osgWidget.WindowManager(
        viewer,
        1280.0,
        1024.0,
        MASK_2D,
        osgWidget.WindowManager.WM_PICK_DEBUG
    )
    
    wm.setPointerFocusMode(osgWidget.WindowManager.PFM_SLOPPY)

    box1 = createBox("HBOX", osgWidget.Box.HORIZONTAL)
    box2 = createBox("VBOX", osgWidget.Box.VERTICAL)
    box3 = createBox("HBOX2", osgWidget.Box.HORIZONTAL)
    box4 = createBox("VBOX2", osgWidget.Box.VERTICAL)

    box1.getBackground().setColor(1.0, 0.0, 0.0, 0.8)
    box1.attachMoveCallback()

    box2.getBackground().setColor(0.0, 1.0, 0.0, 0.8)
    box2.attachMoveCallback()

    box3.getBackground().setColor(0.0, 0.0, 1.0, 0.8)
    box3.attachMoveCallback()

    wm.addChild(box1)
    wm.addChild(box2)
    wm.addChild(box3)
    wm.addChild(box4)

    box4.hide()

    model = osgDB.readNodeFile("spaceship.osgt")

    model.setNodeMask(MASK_3D)

    return osgWidget.createExample(viewer, wm, model)
def main(argv):

    
    viewer = osgViewer.Viewer()

    wm = osgWidget.WindowManager(
        viewer,
        1280.0,
        1024.0,
        MASK_2D,
        osgWidget.WindowManager.WM_PICK_DEBUG
    )
    
    canvas = osgWidget.Canvas("canvas")
    pOutline = osgWidget.Widget("pOutline", 512.0, 64.0)
    pMeter = osgWidget.Widget("pMeter", 0.0, 64.0)
    pLabel = osgWidget.Label("pLabel", "0% Done")

    pOutline.setImage("osgWidget/progress-outline.png", True)
    pOutline.setLayer(osgWidget.Widget.LAYER_MIDDLE, 2)
    
    pMeter.setImage("osgWidget/progress-meter.png")
    pMeter.setColor(0.7, 0.1, 0.1, 0.7)
    pMeter.setLayer(osgWidget.Widget.LAYER_MIDDLE, 1)

    pLabel.setFont("fonts/VeraMono.ttf")
    pLabel.setFontSize(20)
    pLabel.setFontColor(1.0, 1.0, 1.0, 1.0)
    pLabel.setSize(512.0, 64.0)
    pLabel.setLayer(osgWidget.Widget.LAYER_MIDDLE, 3)

    canvas.setOrigin(300.0, 300.0)
    canvas.addWidget(pMeter, 0.0, 0.0)
    canvas.addWidget(pOutline, 0.0, 0.0)
    canvas.addWidget(pLabel, 0.0, 0.0)
    canvas.getBackground().setColor(0.0, 0.0, 0.0, 0.0)
    canvas.setUpdateCallback(UpdateProgressNode())

    wm.addChild(canvas)

    return osgWidget.createExample(viewer, wm, osgDB.readNodeFile("cow.osgt"))
def main(argv):
    
    # construct the viewer.
    arguments = osg.ArgumentParser( argc, argv )
    viewer = osgViewer.Viewer( arguments )

    useSimpleExample = arguments.read("-s")  or  arguments.read("--simple") 

    model = NULL

    if arguments.argc()>1  and   not arguments.isOption(1)  : 
        filename = arguments[1]
        model = osgDB.readNodeFile( filename )
        if   not model  : 
            osg.notify( osg.NOTICE ), "Error, cannot read ", filename, ". Loading default earth model instead."

    if  model == NULL  :
        model = CreateGlobe( )

    node =  CreateSimpleHierarchy( model ) if (useSimpleExample) else 
        CreateAdvancedHierarchy( model )
Example #28
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 loaded assume no arguments passed in, try use default model instead.
    if  not scene : scene = osgDB.readNodeFile("dumptruck.osgt")
    
    if  not scene : 
            geode = osg.Geode()
            drawable = osg.ShapeDrawable(osg.Box(osg.Vec3(0,0,0), 100))
            drawable.setColor(osg.Vec4(0.5, 0.5, 0.5,1))
            geode.addDrawable(drawable)
            scene = geode


    # construct the viewer.
    viewer = osgViewer.Viewer()
    
    
    group = osg.Group()

    # add the HUD subgraph.    
    if scene.valid() : group.addChild(scene)
    
    viewer.setCameraManipulator(osgGA.MultiTouchTrackballManipulator())
    viewer.realize()
    
    gc = viewer.getCamera().getGraphicsContext()
    
    #ifdef __APPLE__
        # as multitouch is disabled by default, enable it now
        win = dynamic_cast<osgViewer.GraphicsWindowCocoa*>(gc)
        if win : win.setMultiTouchEnabled(True)
Example #29
0
def main(argv):

    
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)
    arguments.getApplicationUsage().addKeyboardMouseBinding("m", "Increase the number of depth peeling layers")
    arguments.getApplicationUsage().addKeyboardMouseBinding("n", "Decrease the number of depth peeling layers")
    arguments.getApplicationUsage().addKeyboardMouseBinding("l", "Toggle display of the individual or composed layer textures")
    arguments.getApplicationUsage().addKeyboardMouseBinding("p", "Increase the layer offset")
    arguments.getApplicationUsage().addKeyboardMouseBinding("o", "Decrease the layer offset")

    # Have the usual viewer
    viewer = osgViewer.Viewer(arguments)

    displaySettings = osg.DisplaySettings()
    viewer.setDisplaySettings(displaySettings)
   
    # Add the stats handler
    viewer.addEventHandler(osgViewer.StatsHandler)()
   
    # add the help handler
    viewer.addEventHandler(osgViewer.HelpHandler(arguments.getApplicationUsage()))

    # any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized()
   
    # read the dump truck, we will need it twice
    dt = osgDB.readNodeFile("dumptruck.osg")

    # display a solid version of the dump truck
    solidModel = osg.PositionAttitudeTransform()
    solidModel.setPosition(osg.Vec3f(7.0, -2.0, 7.0))
    solidModel.addChild(dt)

    # generate the 3D heatmap surface to display
    hm = Heatmap(30, 30, 10, 30, 30, 1.0, 0.25)
    float data[30][30]
    for (int x=0 x < 30 ++x)
        for (int y=0 y < 30 ++y)
            data[y][x] = (double)rand() / RAND_MAX
Example #30
0
def main(argv):
    # use an ArgumentParser object to manage the program arguments.
    viewer = osgViewer.Viewer()
#    viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded)

    # read the scene from the list of file specified commandline args.
    loadedModel = osgDB.readNodeFile("cessna.osg")
    if loadedModel == None:
        raise Exception('Could not load model file (is OSG_FILE_PATH set and correct?)')

    # create a transform to spin the model.
    loadedModelTransform = osg.MatrixTransform()
    loadedModelTransform.addChild(loadedModel)

    print loadedModelTransform.getBound()._center
#todo:    nc = osg.AnimationPathCallback(loadedModelTransform.getBound()._center,osg.Vec3(0.0,0.0,1.0),osg.inDegrees(45.0));
#    loadedModelTransform.setUpdateCallback(nc)

    rootNode = osg.Group()
    rootNode.stateSet.dataVariance = osg.Object.DYNAMIC
    rootNode.addChild(createMirroredScene(loadedModelTransform))

    viewer.addEventHandler(osgViewer.HelpHandler())
    viewer.addEventHandler(osgViewer.StatsHandler())
    viewer.addEventHandler(osgGA.StateSetManipulator(rootNode.stateSet))
    viewer.setSceneData(rootNode)
    print "set scene data"

    #hint to tell viewer to request stencil buffer when setting up windows
    # osg.DisplaySettings().setMinimumNumStencilBits(8)
    osg.DisplaySettings.instance().setMinimumNumStencilBits(8);

    osgDB.writeNodeFile(rootNode, "test_reflect.osg");

    viewer.run() #we need run, because that sets up a trackballmanipulator and so we have the correct "look" into the scene.
    return 0
Example #31
0
#   this list of conditions and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice, 
#   this list of conditions and the following disclaimer in the documentation 
#   and/or other materials provided with the distribution.
#   * Neither the name of the Howard Hughes Medical Institute nor the names of 
#   its contributors may be used to endorse or promote products derived from 
#   this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, ANY 
# IMPLIED WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR FITNESS FOR A 
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
# REASONABLE ROYALTIES; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# This is the "hello world" of OpenScenGraph.
# Creates a window containing a model of a cow

from osgpypp import osgDB, osgViewer

scene = osgDB.readNodeFile("cow.osg")
viewer = osgViewer.Viewer()
viewer.setSceneData(scene)
viewer.setUpViewInWindow(100, 100, 500, 500, 0)
viewer.run()

Example #32
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 #33
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()