Пример #1
0
    def handle(ea, aa):

        
        viewer = dynamic_cast<osgViewer.Viewer*>(aa)
        if  not viewer : return False

        switch(ea.getEventType())
            case(osgGA.GUIEventAdapter.KEYUP):
                if ea.getKey()==ord("s") :
                    saveSelectedModel(viewer.getSceneData())
                elif ea.getKey()==ord("o") :
                    osg.notify(osg.NOTICE), "Saved model to file 'saved_model.osgt'"
                    osgDB.writeNodeFile(*(viewer.getSceneData()), "saved_model.osgt")
                elif ea.getKey()==ord("p") :
                    _usePolytopeIntersector =  not _usePolytopeIntersector
                    if _usePolytopeIntersector :
                        osg.notify(osg.NOTICE), "Using PolytopeIntersector"
                     else:
                        osg.notify(osg.NOTICE), "Using LineSegmentIntersector"
                elif ea.getKey()==ord("c") :
                    _useWindowCoordinates =  not _useWindowCoordinates
                    if _useWindowCoordinates :
                        osg.notify(osg.NOTICE), "Using window coordinates for picking"
                     else:
                        osg.notify(osg.NOTICE), "Using projection coordiates for picking"
                elif ea.getKey()==osgGA.GUIEventAdapter.KEY_Delete  or  ea.getKey()==osgGA.GUIEventAdapter.KEY_BackSpace :
                    osg.notify(osg.NOTICE), "Delete"
                    dsnv = DeleteSelectedNodesVisitor()
                    viewer.getSceneData().accept(dsnv)
                    dsnv.pruneSelectedNodes()
                return False
Пример #2
0
    def apply(plod):
    
        

        # go through all the named children and write them out to disk.
        for(unsigned int i=0i<plod.getNumChildren()++i)
            child = plod.getChild(i)
            filename = plod.getFileName(i)
            if  not filename.empty() :
                osg.notify(osg.NOTICE), "Writing out ", filename
                osgDB.writeNodeFile(*child,filename)
Пример #3
0
    def saveSelectedModel(scene):

        
        if  not scene : return
    
        cmtsv = CreateModelToSaveVisitor()
        scene.accept(cmtsv)
        
        if cmtsv._group.getNumChildren()>0 :
            print "Writing selected compoents to 'selected_model.osgt'"
            osgDB.writeNodeFile(*cmtsv._group, "selected_model.osgt")
Пример #4
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
Пример #5
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)
            return 1

        if runShaderGen :
            # convert fixed function pipeline to shaders
            sgv = osgUtil.ShaderGenVisitor()
            loadedModel.accept(sgv)

        if runConvertToVertexAttributes :
            # find any conventional vertex, colour, normal and tex coords arrays and convert to vertex attributes
            ctvaa = ConvertToVertexAttibArrays()
            loadedModel.accept(ctvaa)

    if  not loadedModel : return 1

    if  not outputFileName.empty() :
        osgDB.writeNodeFile(*loadedModel, outputFileName)
        return 0

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

    viewer.setCameraManipulator(osgGA.TrackballManipulator())

    # add the stats handler
    viewer.addEventHandler(osgViewer.StatsHandler)()

    viewer.realize()


    if runConvertToVertexAttributes :
        # switch on the uniforms that track the modelview and projection matrices
Пример #7
0
    sunLight.addChild( aroundSunRotationJupiter )
#
#*********************************************
#**  end Jupiter and Transformations
#*********************************************
#

#
#    # add space, but don't light it, as its not illuminated by our sun
#    space = solarSystem.createSpace( "Space", solarSystem._mapSpace )
#    space.getOrCreateStateSet().setMode(GL_LIGHTING, osg.StateAttribute.OFF)
#    root.addChild( space )
#

    if  not writeFileName.empty() :
        osgDB.writeNodeFile(*root, writeFileName)
        print "Written solar system to \"", writeFileName, "\""
        return 0


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

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


    # set up tracker manipulators, once for each astral body
        fnnv = FindNamedNodeVisitor("Moon")
        root.accept(fnnv)
Пример #8
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()+" creates a hierarchy of files for paging which can be later loaded by viewers.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("-o","set the output file (defaults to output.ive)")
    arguments.getApplicationUsage().addCommandLineOption("--makeAllChildrenPaged","Force all children of LOD to be written out as external PagedLOD children")

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

    outputfile = str("output.ive")
    while arguments.read("-o",outputfile) : 
    
    
    makeAllChildrenPaged = False
    while arguments.read("--makeAllChildrenPaged") :  makeAllChildrenPaged = True 

    # 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
    
#     if arguments.argc()<=1 :
#     
#         arguments.getApplicationUsage().write(std.cout,osg.ApplicationUsage.COMMAND_LINE_OPTION)
#         return 1
#     


    model = osgDB.readNodeFiles(arguments)
    
    if  not model :
        osg.notify(osg.NOTICE), "No model loaded."
        return 1
    
    basename = str( osgDB.getNameLessExtension(outputfile) )
    ext = ord(".")+ osgDB.getFileExtension(outputfile)
    
    converter = ConvertToPageLODVistor(basename,ext, makeAllChildrenPaged)
    model.accept(converter)
    converter.convert()
    
    nameNodes = NameVistor()
    model.accept(nameNodes)

    #CheckVisitor checkNodes
    #model.accept(checkNodes)

    if model.valid() :
        osgDB.writeNodeFile(*model,outputfile)
        
        woplsv = WriteOutPagedLODSubgraphsVistor()
        model.accept(woplsv)

    return 0


if __name__ == "__main__":
    main(sys.argv)
Пример #9
0
                    ddv = DebugDisplayVisitor( _debug )
                    _node.accept( ddv )
                    return True
                elif ea.getKey()==osgGA.GUIEventAdapter.KEY_F8 :
                    # F8 -- Gether stats and display
                    sv = StatisticsVisitor()
                    _node.accept( sv )
                    print "osgOQ: Stats: numOQNs ", sv.getNumOQNs(), ", numPased ", sv.getNumPassed()
                    return True
                elif ea.getKey()==osgGA.GUIEventAdapter.KEY_F9 :
                    # F9 -- Remove all OcclusionQueryNodes
                    roqv = RemoveOcclusionQueryVisitor()
                    _node.accept( roqv )
                    return True
                elif ea.getKey()==ord("o") :
                    if osgDB.writeNodeFile( _node, "saved_model.osgt" ) :
                        osg.notify( osg.ALWAYS ), "osgOQ: Wrote scene graph to \"saved_model.osgt\""
                    else:
                        osg.notify( osg.ALWAYS ), "osgOQ: Wrote failed for \"saved_model.osgt\""
                    return True
                return False
            default:
                break
        return False

    _node = osg.Node()

    bool _enable, _debug


# Create a cube with one side missing. This makes a great simple occluder.
Пример #10
0
def main(argv):

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

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

    # load the nodes from the commandline arguments.
    rootnode = osgDB.readNodeFiles(arguments)
    if  not rootnode :
        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(rootnode)
    
# -------------    Start of copy specific code -------------------------------------------------------
    
    # do a deep copy, using MyCopyOp to reveal whats going on under the good,
    # in your own code you'd typically just use the basic osg.CopyOp something like
    mycopy = dynamic_cast<osg.Node*>(rootnode.clone(osg.CopyOp.DEEP_COPY_ALL))
    print "Doing a deep copy of scene graph"

    # note, we need the dyanmic_cast because MS Visual Studio can't handle covarient
    # return types, so that clone has return just Object*.  bahh hum bug
    deep_copy = dynamic_cast<osg.Node*>(rootnode.clone(MyCopyOp(osg.CopyOp.DEEP_COPY_ALL)))
    
    print "----------------------------------------------------------------"

    # do a graph preserving deep copy.
    print "Doing a graph preserving deep copy of scene graph nodes"
    graph_copy = dynamic_cast<osg.Node*>(rootnode.clone(GraphCopyOp(osg.CopyOp.DEEP_COPY_NODES)))


    # do a shallow copy.
    print "Doing a shallow copy of scene graph"
    shallow_copy = dynamic_cast<osg.Node*>(rootnode.clone(MyCopyOp(osg.CopyOp.SHALLOW_COPY)))


    # write out the various scene graphs so that they can be browsed, either
    # in an editor or using a graphics diff tool gdiff/xdiff/xxdiff.
    print std.endl, "Writing out the original scene graph as 'original.osgt'"
    osgDB.writeNodeFile(*rootnode,"original.osgt")

    print std.endl, "Writing out the graph preserving scene graph as 'graph_copy.osgt'"
    osgDB.writeNodeFile(*graph_copy,"graph_copy.osgt")

    print "Writing out the deep copied scene graph as 'deep_copy.osgt'"
    osgDB.writeNodeFile(*deep_copy,"deep_copy.osgt")

    print "Writing out the shallow copied scene graph as 'shallow_copy.osgt'"
    osgDB.writeNodeFile(*shallow_copy,"shallow_copy.osgt")


    # You can use a bit mask to control which parts of the scene graph are shallow copied
    # vs deep copied.  The options are (from include/osg/CopyOp) :
    # enum Options 
    #        SHALLOW_COPY = 0,
    #        DEEP_COPY_OBJECTS = 1,
    #        DEEP_COPY_NODES = 2,
    #        DEEP_COPY_DRAWABLES = 4,
    #        DEEP_COPY_STATESETS = 8,
    #        DEEP_COPY_STATEATTRIBUTES = 16,
    #        DEEP_COPY_TEXTURES = 32,
    #        DEEP_COPY_IMAGES = 64,
    #        DEEP_COPY_ALL = 0xffffffff
    # 
    # 
    # These options you can use together such as :
    #    osg.Node* mycopy = dynamic_cast<osg.Node*>(rootnode.clone(osg.CopyOp.DEEP_COPY_NODES | DEEP_COPY_DRAWABLES))
    # Which shares state but creates copies of all nodes and drawables (which contain the geometry).
    # 
    # You may also want to subclass from CopyOp to provide finer grained control of what gets shared (shallow copy) vs
    # cloned (deep copy).
    


# -------------    End of copy specific code -------------------------------------------------------
     
    # set the scene to render
    viewer.setSceneData(rootnode)

    # viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded)

    return viewer.run()
Пример #11
0
            camera.setViewMatrix(osg.Matrix.identity())
            camera.setClearMask(GL_DEPTH_BUFFER_BIT)
            camera.addChild(createHUDText())
            camera.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.OFF)

            group.addChild(camera)

        if True :
            group.addChild(create3DText(center,radius))

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

    filename = str()
    if arguments.read("-o",filename) :
        osgDB.writeNodeFile(*viewer.getSceneData(),filename)
        return 0

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

    viewer.run()
    
    if  not operationThreads.empty() :
        for(Threads.iterator itr = operationThreads.begin()
            not = operationThreads.end()
            ++itr)
            (*itr).cancel()

    return 0
Пример #12
0
    virtual void operator () (osg.Object* object)
        osg.notify(osg.NOTICE), "LoadAndCompileOperation ", _filename

        _modelReadyToMerge = False
        _loadedModel = osgDB.readNodeFile(_filename)

        if _loadedModel.valid() :
            if _sceneGraphProcessor.valid() :
                _loadedModel = _sceneGraphProcessor.process(_loadedModel)

        if _loadedModel.valid() :
            if  not _outputFilename.empty() :
                OSG_NOTICE, "Writing out file ", _outputFilename
                
                osgDB.writeNodeFile(*_loadedModel, _outputFilename)

            if _incrementalCompileOperation.valid() :
                OSG_NOTICE, "Registering with ICO ", _outputFilename

                compileSet = osgUtil.IncrementalCompileOperation.CompileSet(_loadedModel)

                compileSet._compileCompletedCallback = this

                _incrementalCompileOperation.add(compileSet)
            else:
                _modelReadyToMerge = True

        osg.notify(osg.NOTICE), "done LoadAndCompileOperation ", _filename

    def compileCompleted(compileSet):
Пример #13
0
def main(argv):

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

    if argc<2 : 
        print argv[0], ": requires filename argument."
        return 1

    viewer = osgViewer.Viewer(arguments)
    
    outputfile = str("output.osgt")
    while arguments.read("-o",outputfile) : 

    while arguments.read("-s") :  viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded) 
    while arguments.read("-g") :  viewer.setThreadingModel(osgViewer.Viewer.CullDrawThreadPerContext) 
    while arguments.read("-d") :  viewer.setThreadingModel(osgViewer.Viewer.DrawThreadPerContext) 
    while arguments.read("-c") :  viewer.setThreadingModel(osgViewer.Viewer.CullThreadPerCameraDrawThreadPerContext) 
    
    singleWindowSideBySideCameras(viewer)

    viewer.setCameraManipulator( osgGA.TrackballManipulator() )
    viewer.addEventHandler(osgViewer.StatsHandler)()
    viewer.addEventHandler(osgViewer.ThreadingHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler())
    viewer.addEventHandler(osgViewer.LODScaleHandler())
    viewer.addEventHandler(osgGA.StateSetManipulator())

    visit = SwitchDOFVisitor()
    viewer.addEventHandler(visit)
    
    loadedModel = osg.Node()
    # load the scene.
    loadedModel = osgDB.readNodeFiles(arguments)

    if  not loadedModel : 
        print argv[0], ": No data loaded."
        return 1

    group = osg.Group()
    
    group1 = osg.Group()
    group1.addChild(loadedModel)
    group1.setNodeMask(1)

    # Uncomment these lines if you like to compare the loaded model to the resulting model in a merge/diff tool
    #osgDB.writeNodeFile(*loadedModel, "dummy1.osgt")

    osgDB.writeNodeFile(*loadedModel, outputfile)
    convertedModel = osgDB.readNodeFile(outputfile)

    #osgDB.writeNodeFile(*convertedModel, "dummy2.osgt")

    group2 = osg.Group()
    group2.addChild(convertedModel)
    group2.setNodeMask(2)

    # Activate DOF animations and collect switches
    loadedModel.accept(*visit)
    convertedModel.accept(*visit)

    group.addChild(group1)
    group.addChild(group2)

    viewer.setSceneData(group)

    viewer.setThreadingModel(osgViewer.Viewer.DrawThreadPerContext)
    viewer.realize()

    viewer.run()

    return 0



if __name__ == "__main__":
    main(sys.argv)
Пример #14
0
    scene.addUpdateCallback(bam)
    
    geode = osg.Geode()
    geode.addDrawable(morph)
    geode.addUpdateCallback(osgAnimation.UpdateMorph("MorphNodeCallback"))
    scene.addChild(geode)

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

    # let's run  not 
    viewer.setSceneData( scene )
    viewer.realize()

    bam.playAnimation(animation)


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

    osgDB.writeNodeFile(*scene, "morph_scene.osg")

    return 0




if __name__ == "__main__":
    main(sys.argv)
    trueroot.addChild(skelroot)
    trueroot.setDataVariance(osg.Object.DYNAMIC)
    rootTransform.addChild(trueroot)
    scene.addChild(rootTransform)

    geom = createTesselatedBox(4, 4.0)
    geode = osg.Geode()
    geode.addDrawable(geom)
    skelroot.addChild(geode)
    src = dynamic_cast<osg.Vec3Array*>(geom.getSourceGeometry().getVertexArray())
    geom.getOrCreateStateSet().setMode(GL_LIGHTING, False)
    geom.setDataVariance(osg.Object.DYNAMIC)

    initVertexMap(root, right0, right1, geom, src)

    # let's run  not 
    viewer.setSceneData( scene )
    viewer.realize()

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

    osgDB.writeNodeFile(*scene, "skinning.osg")
    return 0




if __name__ == "__main__":
    main(sys.argv)
Пример #16
0
                view = dynamic_cast<osgViewer.View*>(aa)
                intersections = osgUtil.LineSegmentIntersector.Intersections()
                if view  and  view.computeIntersections(ea, intersections) :
                    hit = *(intersections.begin())
                    if hit.matrix.valid() : addPoint(hit.localIntersectionPoint * (*hit.matrix))
                    addPoint = else(hit.localIntersectionPoint)

                return True
            elif ea.getKey()==ord("e") :
                endOccluder()
                return True
            elif ea.getKey()==ord("O") :
                if _occluders.valid() :

                    if osgDB.writeNodeFile(*_occluders,"saved_occluders.osgt") :
                        print "saved occluders to 'saved_occluders.osgt'"
                else:
                    print "no occluders to save"
                return True
            return False

        default:
            return False

void OccluderEventHandler.addPoint( osg.Vec3 pos)
    print "add point ", pos

    if  not _convexPlanarOccluder.valid() : _convexPlanarOccluder = osg.ConvexPlanarOccluder()

    occluder = _convexPlanarOccluder.getOccluder()