示例#1
0
    def test_quat(self):
        "Adapted from examples/osgunittests/osgunittests.cpp"
        q1 = osg.Quat()
        q1.makeRotate(osg.DegreesToRadians(30.0), 0.0, 0.0, 1.0)

        q2 = osg.Quat()
        q2.makeRotate(osg.DegreesToRadians(133.0), 0.0, 1.0, 1.0)

        q1_2 = q1 * q2
        q2_1 = q2 * q1

        m1 = osg.Matrix.rotate(q1)
        m2 = osg.Matrix.rotate(q2)

        m1_2 = m1 * m2
        m2_1 = m2 * m1

        qm1_2 = osg.Quat()
        qm1_2.set(m1_2)

        qm2_1 = osg.Quat()
        qm2_1.set(m2_1)

        print "q1*q2 = ", q1_2
        print "q2*q1 = ", q2_1
        print "m1*m2 = ", qm1_2
        print "m2*m1 = ", qm2_1

        testQuatRotate(osg.Vec3d(1.0, 0.0, 0.0), osg.Vec3d(0.0, 1.0, 0.0))
        testQuatRotate(osg.Vec3d(0.0, 1.0, 0.0), osg.Vec3d(1.0, 0.0, 0.0))
        testQuatRotate(osg.Vec3d(0.0, 0.0, 1.0), osg.Vec3d(0.0, 1.0, 0.0))
        testQuatRotate(osg.Vec3d(1.0, 1.0, 1.0), osg.Vec3d(1.0, 0.0, 0.0))
        testQuatRotate(osg.Vec3d(1.0, 0.0, 0.0), osg.Vec3d(1.0, 0.0, 0.0))
        testQuatRotate(osg.Vec3d(1.0, 0.0, 0.0), osg.Vec3d(-1.0, 0.0, 0.0))
        testQuatRotate(osg.Vec3d(-1.0, 0.0, 0.0), osg.Vec3d(1.0, 0.0, 0.0))
        testQuatRotate(osg.Vec3d(0.0, 1.0, 0.0), osg.Vec3d(0.0, -1.0, 0.0))
        testQuatRotate(osg.Vec3d(0.0, -1.0, 0.0), osg.Vec3d(0.0, 1.0, 0.0))
        testQuatRotate(osg.Vec3d(0.0, 0.0, 1.0), osg.Vec3d(0.0, 0.0, -1.0))
        testQuatRotate(osg.Vec3d(0.0, 0.0, -1.0), osg.Vec3d(0.0, 0.0, 1.0))

        # Test a range of rotations
        testGetQuatFromMatrix(quat_scale)

        # This is a specific test case for a matrix containing scale and rotation
        matrix = osg.Matrix(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0,
                            0.5, 0.0, 1.0, 1.0, 1.0, 1.0)

        quat = osg.Quat()
        matrix.get(quat)

        print "Matrix = ", matrix, "rotation = ", quat, ", expected quat = (0,0,0,1)"
示例#2
0
class ModelPositionCallback (osg.NodeCallback) :

    ModelPositionCallback(double speed):
        _latitude(0.0),
        _longitude(0.0),
        _height(100000.0),
        _speed(speed)
        _rotation.makeRotate(osg.DegreesToRadians(90.0),0.0,0.0,1.0)
示例#3
0
def createText(ellipsoid, latitude, longitude, height, str):

    
    double X,Y,Z
    ellipsoid.convertLatLongHeightToXYZ( osg.DegreesToRadians(latitude), osg.DegreesToRadians(longitude), height, X, Y, Z)


    text = osgText.FadeText()

    normal = ellipsoid.computeLocalUpVector( X, Y, Z)
    text.setCullCallback(osg.ClusterCullingCallback(osg.Vec3(X,Y,Z), normal, 0.0))

    text.setText(str)
    text.setFont("fonts/arial.ttf")
    text.setPosition(osg.Vec3(X,Y,Z))
    text.setCharacterSize(300000.0)
    text.setCharacterSizeMode(osgText.Text.OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT)
    text.setAutoRotateToScreen(True)
    
    return text
示例#4
0
def main(argv):
    
    arguments = osg.ArgumentParser( argc, argv )
    usage = arguments.getApplicationUsage()
    usage.setDescription( arguments.getApplicationName() +
                           " is the example which demonstrates how to render high-resolution images (posters).")
    usage.setCommandLineUsage( arguments.getApplicationName() + " [options] scene_file" )
    usage.addCommandLineOption( "-h or --help", "Display this information." )
    usage.addCommandLineOption( "--color <r> <g> <b>", "The background color." )
    usage.addCommandLineOption( "--ext <ext>", "The output tiles' extension (Default: bmp)." )
    usage.addCommandLineOption( "--poster <filename>", "The output poster's name (Default: poster.bmp)." )
    usage.addCommandLineOption( "--tilesize <w> <h>", "Size of each image tile (Default: 640 480)." )
    usage.addCommandLineOption( "--finalsize <w> <h>", "Size of the poster (Default: 6400 4800)." )
    usage.addCommandLineOption( "--enable-output-poster", "Output the final poster file (Default)." )
    usage.addCommandLineOption( "--disable-output-poster", "Don't output the final poster file." )
    #usage.addCommandLineOption( "--enable-output-tiles", "Output all tile files." )
    #usage.addCommandLineOption( "--disable-output-tiles", "Don't output all tile files (Default)." )
    usage.addCommandLineOption( "--use-fb", "Use Frame Buffer for rendering tiles (Default, recommended).")
    usage.addCommandLineOption( "--use-fbo", "Use Frame Buffer Object for rendering tiles.")
    usage.addCommandLineOption( "--use-pbuffer","Use Pixel Buffer for rendering tiles.")
    usage.addCommandLineOption( "--use-pbuffer-rtt","Use Pixel Buffer RTT for rendering tiles.")
    usage.addCommandLineOption( "--inactive", "Inactive capturing mode." )
    usage.addCommandLineOption( "--camera-eye <x> <y> <z>", "Set eye position in inactive mode." )
    usage.addCommandLineOption( "--camera-latlongheight <lat> <lon> <h>", "Set eye position on earth in inactive mode." )
    usage.addCommandLineOption( "--camera-hpr <h> <p> <r>", "Set eye rotation in inactive mode." )
    
    if  arguments.read("-h")  or  arguments.read("--help")  :
        usage.write( std.cout )
        return 1
    
    # Poster arguments
    activeMode = True
    outputPoster = True
    #bool outputTiles = False
    tileWidth = 640, tileHeight = 480
    posterWidth = 640*2, posterHeight = 480*2
    posterName = "poster.bmp", extName = "bmp"
    bgColor = osg.Vec4(0.2, 0.2, 0.6, 1.0)
    renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT
    
    while  arguments.read("--inactive")  :  activeMode = False 
    while  arguments.read("--color", bgColor.r(), bgColor.g(), bgColor.b())  : 
    while  arguments.read("--tilesize", tileWidth, tileHeight)  : 
    while  arguments.read("--finalsize", posterWidth, posterHeight)  : 
    while  arguments.read("--poster", posterName)  : 
    while  arguments.read("--ext", extName)  : 
    while  arguments.read("--enable-output-poster")  :  outputPoster = True 
    while  arguments.read("--disable-output-poster")  :  outputPoster = False 
    #while  arguments.read("--enable-output-tiles")  :  outputTiles = True 
    #while  arguments.read("--disable-output-tiles")  :  outputTiles = False 
    while  arguments.read("--use-fbo") :  renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT 
    while  arguments.read("--use-pbuffer") :  renderImplementation = osg.Camera.PIXEL_BUFFER 
    while  arguments.read("--use-pbuffer-rtt") :  renderImplementation = osg.Camera.PIXEL_BUFFER_RTT 
    while  arguments.read("--use-fb") :  renderImplementation = osg.Camera.FRAME_BUFFER 
    
    # Camera settings for inactive screenshot
    useLatLongHeight = True
    eye = osg.Vec3d()
    latLongHeight = osg.Vec3d( 50.0, 10.0, 2000.0 )
    hpr = osg.Vec3d( 0.0, 0.0, 0.0 )
    if  arguments.read("--camera-eye", eye.x(), eye.y(), eye.z())  :
        useLatLongHeight = False
        activeMode = False
    elif  arguments.read("--camera-latlongheight", latLongHeight.x(), latLongHeight.y(), latLongHeight.z())  :
        activeMode = False
        latLongHeight.x() = osg.DegreesToRadians( latLongHeight.x() )
        latLongHeight.y() = osg.DegreesToRadians( latLongHeight.y() )
    if  arguments.read("--camera-hpr", hpr.x(), hpr.y(), hpr.z())  :
        activeMode = False
        hpr.x() = osg.DegreesToRadians( hpr.x() )
        hpr.y() = osg.DegreesToRadians( hpr.y() )
        hpr.z() = osg.DegreesToRadians( hpr.z() )
    
    # Construct scene graph
    scene = osgDB.readNodeFiles( arguments )
    if   not scene  : scene = osgDB.readNodeFile( "cow.osgt" )
    if   not scene  :
        print arguments.getApplicationName(), ": No data loaded"
        return 1
    
    # Create camera for rendering tiles offscreen. FrameBuffer is recommended because it requires less memory.
    camera = osg.Camera()
    camera.setClearColor( bgColor )
    camera.setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT )
    camera.setReferenceFrame( osg.Transform.ABSOLUTE_RF )
    camera.setRenderOrder( osg.Camera.PRE_RENDER )
    camera.setRenderTargetImplementation( renderImplementation )
    camera.setViewport( 0, 0, tileWidth, tileHeight )
    camera.addChild( scene )
    
    # Set the printer
    printer = PosterPrinter()
    printer.setTileSize( tileWidth, tileHeight )
    printer.setPosterSize( posterWidth, posterHeight )
    printer.setCamera( camera )
    
    posterImage = 0
    if  outputPoster  :
        posterImage = osg.Image()
        posterImage.allocateImage( posterWidth, posterHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE )
        printer.setFinalPoster( posterImage )
        printer.setOutputPosterName( posterName )
    
#if 0
    # While recording sub-images of the poster, the scene will always be traversed twice, from its two
    # parent node: root and camera. Sometimes this may not be so comfortable.
    # To prevent this behaviour, we can use a switch node to enable one parent and disable the other.
    # However, the solution also needs to be used with care, as the window will go blank while taking
    # snapshots and recover later.
    root = osg.Switch()
    root.addChild( scene, True )
    root.addChild( camera, False )
#else:
    root = osg.Group()
    root.addChild( scene )
    root.addChild( camera )
#endif
    
    viewer = osgViewer.Viewer()
    viewer.setSceneData( root )
    viewer.getDatabasePager().setDoPreCompile( False )
    
    if  renderImplementation==osg.Camera.FRAME_BUFFER  :
        # FRAME_BUFFER requires the window resolution equal or greater than the to-be-copied size
        viewer.setUpViewInWindow( 100, 100, tileWidth, tileHeight )
    else:
        # We want to see the console output, so just render in a window
        viewer.setUpViewInWindow( 100, 100, 800, 600 )
    
    if  activeMode  :
        viewer.addEventHandler( PrintPosterHandler(printer) )
        viewer.addEventHandler( osgViewer.StatsHandler )()
        viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
        viewer.setCameraManipulator( osgGA.TrackballManipulator )()
        viewer.run()
    else:
        camera = viewer.getCamera()
        if   not useLatLongHeight  : computeViewMatrix( camera, eye, hpr )
        computeViewMatrixOnEarth = else( camera, scene, latLongHeight, hpr )
        
        renderer = CustomRenderer( camera )
        camera.setRenderer( renderer )
        viewer.setThreadingModel( osgViewer.Viewer.SingleThreaded )
        
        # Realize and initiate the first PagedLOD request
        viewer.realize()
        viewer.frame()
        
        printer.init( camera )
        while   not printer.done()  :
            viewer.advance()
            
            # Keep updating and culling until full level of detail is reached
            renderer.setCullOnly( True )
            while  viewer.getDatabasePager().getRequestsInProgress()  :
                viewer.updateTraversal()
                viewer.renderingTraversals()
            
            renderer.setCullOnly( False )
            printer.frame( viewer.getFrameStamp(), viewer.getSceneData() )
            viewer.renderingTraversals()
    return 0

# Translated from file 'PosterPrinter.cpp'

#include <osg/ClusterCullingCallback>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <string.h>
#include <iostream>
#include <sstream>
#include "PosterPrinter.h"

# PagedLoadingCallback: Callback for loading paged nodes while doing intersecting test 
class PagedLoadingCallback (osgUtil.IntersectionVisitor.ReadCallback) :
def readNodeFile(filename):
    
        return osgDB.readNodeFile( filename )

static PagedLoadingCallback g_pagedLoadingCallback = PagedLoadingCallback()

# LodCullingCallback: Callback for culling LODs and selecting the highest level 
class LodCullingCallback (osg.NodeCallback) :
    virtual void operator()( osg.Node* node, osg.NodeVisitor* nv )
        lod = static_cast<osg.LOD*>(node)
        if  lod  and  lod.getNumChildren()>0  :
            lod.getChild(lod.getNumChildren()-1).accept(*nv)

static LodCullingCallback g_lodCullingCallback = LodCullingCallback()

# PagedCullingCallback: Callback for culling paged nodes and selecting the highest level 
class PagedCullingCallback (osg.NodeCallback) :
    virtual void operator()( osg.Node* node, osg.NodeVisitor* nv )
        pagedLOD = static_cast<osg.PagedLOD*>(node)
        if  pagedLOD  and  pagedLOD.getNumChildren()>0  :
            numChildren = pagedLOD.getNumChildren()
            updateTimeStamp = nv.getVisitorType()==osg.NodeVisitor.CULL_VISITOR
            if  nv.getFrameStamp()  and  updateTimeStamp  :
                timeStamp =  nv.getFrameStamp().getReferenceTime() if (nv.getFrameStamp()) else 0.0
                frameNumber =  nv.getFrameStamp().getFrameNumber() if (nv.getFrameStamp()) else 0
                
                pagedLOD.setFrameNumberOfLastTraversal( frameNumber )
                pagedLOD.setTimeStamp( numChildren-1, timeStamp )
                pagedLOD.setFrameNumber( numChildren-1, frameNumber )
                pagedLOD.getChild(numChildren-1).accept(*nv)
            
            # Request for child
            if   not pagedLOD.getDisableExternalChildrenPaging()  and 
                 nv.getDatabaseRequestHandler()  and 
                 numChildren<pagedLOD.getNumRanges()  :
                if  pagedLOD.getDatabasePath().empty()  :
                    nv.getDatabaseRequestHandler().requestNodeFile(
                        pagedLOD.getFileName(numChildren), nv.getNodePath(),
                        1.0, nv.getFrameStamp(),
                        pagedLOD.getDatabaseRequest(numChildren), pagedLOD.getDatabaseOptions() )
                else:
                    nv.getDatabaseRequestHandler().requestNodeFile(
                        pagedLOD.getDatabasePath()+pagedLOD.getFileName(numChildren), nv.getNodePath(),
                        1.0, nv.getFrameStamp(),
                        pagedLOD.getDatabaseRequest(numChildren), pagedLOD.getDatabaseOptions() )
        #node.traverse(*nv)

static PagedCullingCallback g_pagedCullingCallback = PagedCullingCallback()

# PosterVisitor: A visitor for adding culling callbacks to newly allocated paged nodes 
PosterVisitor.PosterVisitor()
:   osg.NodeVisitor(osg.NodeVisitor.TRAVERSE_ALL_CHILDREN),
    _appliedCount(0), _needToApplyCount(0),
    _addingCallbacks(True)

void PosterVisitor.apply( osg.LOD node )
    #if   not hasCullCallback(node.getCullCallback(), g_lodCullingCallback)  :
#    
#        if   not node.getName().empty()  :
#        
#            itr = _pagedNodeNames.find( node.getName() )
#            if  itr not =_pagedNodeNames.end()  :
#            
#                insertCullCallback( node, g_lodCullingCallback )
#                _appliedCount++
#            
#        
#    
#    def if _addingCallbacks .
#        
#        node.removeCullCallback( g_lodCullingCallback )
#        _appliedCount--
#    
    traverse( node )

void PosterVisitor.apply( osg.PagedLOD node )
    if   not hasCullCallback(node.getCullCallback(), g_pagedCullingCallback)  :
        for ( unsigned int i=0 i<node.getNumFileNames() ++i )
            if  node.getFileName(i).empty()  : continue
            
            itr = _pagedNodeNames.find( node.getFileName(i) )
            if  itr not =_pagedNodeNames.end()  :
                node.addCullCallback( g_pagedCullingCallback )
                _appliedCount++
            break
        cubemap.setFilter(osg.Texture.MAG_FILTER, osg.Texture.LINEAR)

    return cubemap


# Update texture matrix for cubemaps
class TexMatCallback (osg.NodeCallback) :

    TexMatCallback(osg.TexMat tm) :
        _texMat(tm)

    virtual void operator()(osg.Node* node, osg.NodeVisitor* nv)
        cv = dynamic_cast<osgUtil.CullVisitor*>(nv)
        if cv :
            MV = *(cv.getModelViewMatrix())
            R = osg.Matrix.rotate( osg.DegreesToRadians(112.0), 0.0,0.0,1.0)*
                                  osg.Matrix.rotate( osg.DegreesToRadians(90.0), 1.0,0.0,0.0)

            q = MV.getRotate()
            C = osg.Matrix.rotate( q.inverse() )

            _texMat.setMatrix( C*R )

        traverse(node,nv)

    _texMat = osg.TexMat()



class MoveEarthySkyWithEyePointTransform (osg.Transform) :
    #* Get the transformation matrix which moves from local coords to world coords.
示例#6
0
def main(argv):


    
    # use an ArgumentParser object to manage the program arguments.
    arguments = 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 using of GL_ARB_shadow extension implemented in osg.Texture class")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName())
    arguments.getApplicationUsage().addCommandLineOption("-h or --help", "Display this information")
    arguments.getApplicationUsage().addCommandLineOption("--fbo","Use Frame Buffer Object for render to texture, where supported.")
    arguments.getApplicationUsage().addCommandLineOption("--fb","Use FrameBuffer for render to texture.")
    arguments.getApplicationUsage().addCommandLineOption("--pbuffer","Use Pixel Buffer for render to texture, where supported.")
    arguments.getApplicationUsage().addCommandLineOption("--window","Use a separate Window for render to texture.")
    arguments.getApplicationUsage().addCommandLineOption("--width","Set the width of the render to texture")
    arguments.getApplicationUsage().addCommandLineOption("--height","Set the height of the render to texture")

    # 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
    
    tex_width = 256
    tex_height = 256
    while arguments.read("--width", tex_width) : 
    while arguments.read("--height", tex_height) : 

    renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT
    
    while arguments.read("--fbo") :  renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT 
    while arguments.read("--pbuffer") :  renderImplementation = osg.Camera.PIXEL_BUFFER 
    while arguments.read("--fb") :  renderImplementation = osg.Camera.FRAME_BUFFER 
    while arguments.read("--window") :  renderImplementation = osg.Camera.SEPERATE_WINDOW 
    

    # 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

    scene = MatrixTransform()
    scene.setMatrix(osg.Matrix.rotate(osg.DegreesToRadians(125.0),1.0,0.0,0.0))

    reflectedSubgraph = _create_scene()    
    if  not reflectedSubgraph.valid() : return 1

    reflectedScene = createShadowedScene(reflectedSubgraph, createReflector(), 0, viewer.getCamera().getClearColor(),
                                                        tex_width, tex_height, renderImplementation)

    scene.addChild(reflectedScene)

    viewer.setSceneData(scene)

    return viewer.run()


if __name__ == "__main__":
    main(sys.argv)
示例#7
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 node tracker.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName())
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    

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

    # add the state manipulator
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )
    
    # add the thread model handler
    viewer.addEventHandler(osgViewer.ThreadingHandler)()

    # add the window size toggle handler
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()
        
    # add the stats handler
    viewer.addEventHandler(osgViewer.StatsHandler)()
        
    # add the record camera path  handler
    viewer.addEventHandler(osgViewer.RecordCameraPathHandler)()

    # add the help handler
    viewer.addEventHandler(osgViewer.HelpHandler(arguments.getApplicationUsage()))

    # set the near far ration computation up.
    viewer.getCamera().setComputeNearFarMode(osg.CullSettings.COMPUTE_NEAR_FAR_USING_PRIMITIVES)
    viewer.getCamera().setNearFarRatio(0.000003)


    speed = 1.0
    while arguments.read("-f")  or  arguments.read("--fixed") : speed = 0.0


    rotation = osg.Quat()
    vec4 = osg.Vec4()
    while arguments.read("--rotate-model",vec4[0],vec4[1],vec4[2],vec4[3]) :
        local_rotate = osg.Quat()
        local_rotate.makeRotate(osg.DegreesToRadians(vec4[0]),vec4[1],vec4[2],vec4[3])
        
        rotation = rotation * local_rotate

    nc = 0
    flightpath_filename = str()
    while arguments.read("--flight-path",flightpath_filename) :
        fin = osgDB.ifstream(flightpath_filename.c_str())
        if fin :
            path = osg.AnimationPath()
            path.read(fin)
            nc = osg.AnimationPathCallback(path)
    
    trackerMode = osgGA.NodeTrackerManipulator.NODE_CENTER_AND_ROTATION
    mode = str()
    while arguments.read("--tracker-mode",mode) :
        if mode=="NODE_CENTER_AND_ROTATION" : trackerMode = osgGA.NodeTrackerManipulator.NODE_CENTER_AND_ROTATION
        elif mode=="NODE_CENTER_AND_AZIM" : trackerMode = osgGA.NodeTrackerManipulator.NODE_CENTER_AND_AZIM
        elif mode=="NODE_CENTER" : trackerMode = osgGA.NodeTrackerManipulator.NODE_CENTER
        else:
            print "Unrecognized --tracker-mode option ", mode, ", valid options are:"
            print "    NODE_CENTER_AND_ROTATION"
            print "    NODE_CENTER_AND_AZIM"
            print "    NODE_CENTER"
            return 1
    
    
    rotationMode = osgGA.NodeTrackerManipulator.TRACKBALL
    while arguments.read("--rotation-mode",mode) :
        if mode=="TRACKBALL" : rotationMode = osgGA.NodeTrackerManipulator.TRACKBALL
        elif mode=="ELEVATION_AZIM" : rotationMode = osgGA.NodeTrackerManipulator.ELEVATION_AZIM
        else:
            print "Unrecognized --rotation-mode option ", mode, ", valid options are:"
            print "    TRACKBALL"
            print "    ELEVATION_AZIM"
            return 1

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

    overlayTextureUnit = 1
    while arguments.read("--unit", overlayTextureUnit) : 
    
    pathfile = str()
    while arguments.read("-p",pathfile) : 

    addFireEffect = arguments.read("--fire")

    # if user request help write it out to cout.
    if arguments.read("-h")  or  arguments.read("--help") :
        arguments.getApplicationUsage().write(std.cout)
        return 1
    
    
    tm = osgGA.NodeTrackerManipulator()
    
    overlayFilename = str()
    while arguments.read("--overlay", overlayFilename) : 

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

    if  not root : root = createEarth()

    if  not root : return 0


    if  not overlayFilename.empty() :
        #osg.Object *pObj = osgDB.readObjectFile("alaska_clean.shp")
        #osg.Geode shapefile = dynamic_cast<osg.Geode*> (pObj)
        #
        #ConvertLatLon2EllipsoidCoordinates latlon2em
        #shapefile.accept(latlon2em)

        shapefile = osgDB.readNodeFile(overlayFilename)
        
        if  not shapefile :
            osg.notify(osg.NOTICE), "File `", overlayFilename, "` not found"
            return 1

        csn = dynamic_cast<osg.CoordinateSystemNode*>(root)
        if csn :

            overlayNode = osgSim.OverlayNode(technique)
            overlayNode.getOrCreateStateSet().setTextureAttribute(1, osg.TexEnv(osg.TexEnv.DECAL))
            overlayNode.setOverlaySubgraph(shapefile)
            overlayNode.setOverlayTextureSizeHint(1024)
            overlayNode.setOverlayTextureUnit(overlayTextureUnit)

            # insert the OverlayNode between the coordinate system node and its children.
            for(unsigned int i=0 i<csn.getNumChildren() ++i)
                overlayNode.addChild( csn.getChild(i) )

            csn.removeChildren(0, csn.getNumChildren())
            csn.addChild(overlayNode)

            viewer.setSceneData(csn)
        else:
            overlayNode = osgSim.OverlayNode(technique)
            overlayNode.getOrCreateStateSet().setTextureAttribute(1, osg.TexEnv(osg.TexEnv.DECAL))
            overlayNode.setOverlaySubgraph(shapefile)
            overlayNode.setOverlayTextureSizeHint(1024)
            overlayNode.addChild(root)

            viewer.setSceneData(overlayNode)
    else:
    

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

        csn = dynamic_cast<osg.CoordinateSystemNode*>(root)
        if csn :

            overlayNode = osgSim.OverlayNode()
            if useOverlay :
                overlayNode = osgSim.OverlayNode(technique)

                # insert the OverlayNode between the coordinate system node and its children.
                for(unsigned int i=0 i<csn.getNumChildren() ++i)
                    overlayNode.addChild( csn.getChild(i) )

                csn.removeChildren(0, csn.getNumChildren())
                csn.addChild(overlayNode)

                # tell the overlay node to continously update its overlay texture
                # as we know we'll be tracking a moving target.
                overlayNode.setContinuousUpdate(True)


            cessna = osgDB.readNodeFile("cessna.osgt")
            if cessna :
                s = 200000.0 / cessna.getBound().radius()

                scaler = osg.MatrixTransform()
                scaler.addChild(cessna)
                scaler.setMatrix(osg.Matrixd.scale(s,s,s)*osg.Matrixd.rotate(rotation))
                scaler.getOrCreateStateSet().setMode(GL_RESCALE_NORMAL,osg.StateAttribute.ON)
                
                if addFireEffect :
                    center = cessna.getBound().center()
                    
                    fire = osgParticle.FireEffect(center, 10.0)
                    scaler.addChild(fire)
                

                if False :
                    ss = osgSim.SphereSegment(
                                        osg.Vec3(0.0,0.0,0.0), # center
                                        19.9, # radius
                                        osg.DegreesToRadians(135.0),
                                        osg.DegreesToRadians(240.0),
                                        osg.DegreesToRadians(-10.0),
                                        osg.DegreesToRadians(30.0),
                                        60)

                    scaler.addChild(ss)

                mt = osg.MatrixTransform()
                mt.addChild(scaler)


                if  not nc : nc = ModelPositionCallback(speed)

                mt.setUpdateCallback(nc)

                csn.addChild(mt)

                # if we are using an overaly node, use the cessna subgraph as the overlay subgraph
                if overlayNode.valid() :
                    overlayNode.setOverlaySubgraph(mt)

                tm = osgGA.NodeTrackerManipulator()
                tm.setTrackerMode(trackerMode)
                tm.setRotationMode(rotationMode)
                tm.setTrackNode(scaler)
            else:
                 print "Failed to read cessna.osgt"


    # set up camera manipulators.
        keyswitchManipulator = osgGA.KeySwitchMatrixManipulator()

        if tm.valid() : keyswitchManipulator.addMatrixManipulator( ord("0"), "NodeTracker", tm )

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

        if  not pathfile.empty() :
            apm = osgGA.AnimationPathManipulator(pathfile)
            if apm  or   not apm.valid() : 
                num = keyswitchManipulator.getNumMatrixManipulators()
                keyswitchManipulator.addMatrixManipulator( ord("5"), "Path", apm )
                keyswitchManipulator.selectMatrixManipulator(num)

        viewer.setCameraManipulator( keyswitchManipulator )

    # viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded)

    return viewer.run()


if __name__ == "__main__":
    main(sys.argv)
        _texmat(texmat),
        _phaseS(35.0),
        _phaseT(18.0),
        _phaseScale(5.0),
        _delay(delay),
        _prevTime(0.0)

    virtual void operator()(osg.Node*, osg.NodeVisitor* nv)
        if  not _texmat :
            return

        if nv.getFrameStamp() : 
            currTime = nv.getFrameStamp().getSimulationTime()
            if currTime - _prevTime > _delay : 

                rad = osg.DegreesToRadians(currTime)

                # zoom scale (0.2 - 1.0)
                scale = sin(rad * _phaseScale) * 0.4 + 0.6
                scaleR = 1.0 - scale

                # calculate texture coordinates
                float s, t()
                s = ((sin(rad * _phaseS) + 1) * 0.5) * (scaleR)
                t = ((sin(rad * _phaseT) + 1) * 0.5) * (scaleR)


                _texmat.setMatrix(osg.Matrix.translate(s,t,1.0)*osg.Matrix.scale(scale,scale,1.0))

                # record time
                _prevTime = currTime
示例#9
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 node masks to create stereo images.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye")
    arguments.getApplicationUsage().addCommandLineOption("-d <float>","Time delay in seconds between the display of successive image pairs when in auto advance mode.")
    arguments.getApplicationUsage().addCommandLineOption("-a","Enter auto advance of image pairs on start up.")
    arguments.getApplicationUsage().addCommandLineOption("-x <float>","Horizontal offset of left and right images.")
    arguments.getApplicationUsage().addCommandLineOption("-y <float>","Vertical offset of left and right images.")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")

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


    # register the handler to add keyboard and mouse handling.
    seh = GameEventHandler()
    viewer.addEventHandler(seh)

    while arguments.read("--boy") : seh.addPlayer(GameEventHandler.PLAYER_BOY)
    while arguments.read("--girl") : seh.addPlayer(GameEventHandler.PLAYER_GIRL)
    
    
    # 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
    
    
    # enable the image cache so we don't need to keep loading the particle files
    options = osgDB.ReaderWriter.Options()
    options.setObjectCacheHint(osgDB.ReaderWriter.Options.CACHE_IMAGES)
    osgDB.Registry.instance().setOptions(options)


    # creat the scene from the file list.
    rootNode = seh.createScene()

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

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

    # for some reason osgcatch is hanging on exit inside the TextureObject clean up code when the it's
    # run as multi-threaded view, switching to SingleThreaded cures this.
    viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded)

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

    viewer.setRealizeOperation(CompileStateCallback(seh))

    double fovy, aspectRatio, zNear, zFar
    viewer.getCamera().getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar)
    seh.setFOVY(osg.DegreesToRadians(fovy))    

    # todo for osgViewer - create default set up.
    viewer.setUpViewAcrossAllScreens()

    viewer.realize()

    # switch off the cursor
    windows = osgViewer.Viewer.Windows()
    viewer.getWindows(windows)
    for(osgViewer.Viewer.Windows.iterator itr = windows.begin()
        not = windows.end()
        ++itr)
        (*itr).useCursor(False)
示例#10
0
    _benignCatachables.push_back("Catch/a.png")
    _benignCatachables.push_back("Catch/b.png")
    _benignCatachables.push_back("Catch/c.png")
    _benignCatachables.push_back("Catch/m.png")
    _benignCatachables.push_back("Catch/n.png")
    _benignCatachables.push_back("Catch/s.png")
    _benignCatachables.push_back("Catch/t.png")
    _benignCatachables.push_back("Catch/u.png")
    _benignCatachables.push_back("Catch/ball.png")
    
    CatchableObject.setUpCatchablesMap(_benignCatachables)
    
    _currentScore = 0
    
    setFOVY(osg.DegreesToRadians(60.0))


bool GameEventHandler.handle( osgGA.GUIEventAdapter ea,osgGA.GUIActionAdapter)
    if _currentIndex==_welcomeIndex :
        # welcome screen
        switch(ea.getEventType())
            case(osgGA.GUIEventAdapter.KEYDOWN):
                _currentIndex = _gameIndex
                _gameSwitch.setSingleChildOn(_currentIndex)
                resetGame()
                return True
            default:
                return False
        
    elif _currentIndex==_lostIndex :
    
    _rotationCenter = _center
    _rotationAxis = osg.Vec3d(0.0, 0.0, 1.0)
    _rotationSpeed = 0.0


void CameraProperty.update(osgViewer.View* view)
    camera = view.getCamera()
    fs = view.getFrameStamp()

    matrix = osg.Matrixd()
    matrix.makeLookAt(_eye, _center, _up)

    if _rotationSpeed not =0.0 :
        matrix.preMult(osg.Matrixd.translate(-_rotationCenter) *
                    osg.Matrix.rotate(osg.DegreesToRadians(_rotationSpeed*fs.getSimulationTime()), _rotationAxis) *
                    osg.Matrixd.translate(_rotationCenter))
    
    camera.setViewMatrix( matrix )

    # set the fusion distance up so that the left and right eye images are co-incedent on the image plane at the center of ration.
    view.setFusionDistance(osgUtil.SceneView.USE_FUSION_DISTANCE_VALUE,(_center-_eye).length())
    # view.setFusionDistance(osgUtil.SceneView.PROPORTIONAL_TO_SCREEN_DISTANCE, 1.0)


############################################/
#
# Serialization support
#
REGISTER_OBJECT_WRAPPER( gsc_CameraProperty,
                         gsc.CameraProperty,
示例#12
0
    width = style.getThicknessRatio()
    creaseAngle = 30.0
    smooth = True

    if bevel :
        thickness = bevel.getBevelThickness()

        glyphGeometry = osgText.computeGlyphGeometry(glyph, thickness, width)
        textGeometry = osgText.computeTextGeometry(glyphGeometry, *bevel, width)
        shellGeometry =  osgText.computeShellGeometry(glyphGeometry, *bevel, width) if (outline) else  0
        if textGeometry.valid() : geode.addDrawable(textGeometry)
        if shellGeometry.valid() : geode.addDrawable(shellGeometry)

        # create the normals
        if smooth  and  textGeometry.valid() :
            osgUtil.SmoothingVisitor.smooth(*textGeometry, osg.DegreesToRadians(creaseAngle))
    else:
        textGeometry = osgText.computeTextGeometry(glyph, width)
        if textGeometry.valid() : geode.addDrawable(textGeometry)

        # create the normals
        if smooth  and  textGeometry.valid() :
            osgUtil.SmoothingVisitor.smooth(*textGeometry, osg.DegreesToRadians(creaseAngle))

    transform.addChild(geode)

    _textNode.addChild(transform)

    transform.getOrCreateStateSet().setMode(GL_NORMALIZE, osg.StateAttribute.ON)

示例#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 node masks to create stereo images.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] image_file [image_file]")
    arguments.getApplicationUsage().addCommandLineOption("-d <float>","Time delay in seconds between the display of successive image pairs when in auto advance mode.")
    arguments.getApplicationUsage().addCommandLineOption("-a","Enter auto advance of image pairs on start up.")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("--create <filename>","Create an photo archive of specified files")


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

    viewer.setThreadingModel(osgViewer.Viewer.SingleThreaded)

    # register the handler to add keyboard and mouse handling.
    seh = SlideEventHandler()
    viewer.addEventHandler(seh)

    # read any time delay argument.
    timeDelayBetweenSlides = 5.0
    while arguments.read("-d",timeDelayBetweenSlides) : 

    autoSteppingActive = False
    while arguments.read("-a") : autoSteppingActive = 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

    archiveName = str()
    while arguments.read("--create",archiveName) : 

    # 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


    if  not archiveName.empty() :
        # archive name set to create
        fileNameList = PhotoArchive.FileNameList()
        for(int i=1i<arguments.argc()++i)
            if arguments.isString(i) : fileNameList.push_back(str(arguments[i]))

        PhotoArchive.buildArchive(archiveName,fileNameList)

        return 0


    # now the windows have been realized we switch off the cursor to prevent it
    # distracting the people seeing the stereo images.
    double fovy, aspectRatio, zNear, zFar
    viewer.getCamera().getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar)

    fovy = osg.DegreesToRadians(fovy)
    fovx = atan(tan(fovy*0.5)*aspectRatio)*2.0

    radius = 1.0
    width = 2*radius*tan(fovx*0.5)
    height = 2*radius*tan(fovy*0.5)

    album = Album(arguments,width,height)

    # creat the scene from the file list.
    rootNode = album.getScene()

    if  not rootNode : return 0


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

    # set the scene to render
    viewer.setSceneData(album.getScene())

    # set up the SlideEventHandler.
    seh.set(album,timeDelayBetweenSlides,autoSteppingActive)

    viewer.realize()

    # switch off the cursor
    windows = osgViewer.Viewer.Windows()
    viewer.getWindows(windows)
    for(osgViewer.Viewer.Windows.iterator itr = windows.begin()
        not = windows.end()
        ++itr)
        (*itr).useCursor(False)


    return viewer.run()
示例#14
0
        if arguments.isString(pos) : fileList.push_back(arguments[pos])

    if fileList.empty() :
        fileList.push_back("Images/dog_left_eye.jpg")
         fileList.push_back("Images/dog_right_eye.jpg")
    elif fileList.size()<2 :
        arguments.getApplicationUsage().write(std.cout,osg.ApplicationUsage.COMMAND_LINE_OPTION)
        return 1

    # now the windows have been realized we switch off the cursor to prevent it
    # distracting the people seeing the stereo images.
    double fovy, aspectRatio, zNear, zFar
    viewer.getCamera().getProjectionMatrixAsPerspective(fovy, aspectRatio, zNear, zFar)

    radius = 1.0
    height = 2*radius*tan(osg.DegreesToRadians(fovy)*0.5)
    length = osg.PI*radius  # half a cylinder.

    # use a texture matrix to control the placement of the image.
    texmatLeft = osg.TexMat()
    texmatRight = osg.TexMat()

    # creat the scene from the file list.
    rootNode = osg.Switch()
    if  not onDisk :  rootNode = createScene(fileList,texmatLeft,texmatRight,radius,height,length)
    rootNode = osg.Switch()

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


示例#15
0
def testGetQuatFromMatrix(scale):
    # Options

    # acceptable error range
    eps = 1e-6

    # scale matrix
    # To not test with scale, use 1,1,1
    # Not sure if 0's or negative values are acceptable
    scalemat = osg.Matrixd()
    scalemat.makeScale(scale)

    # range of rotations
    if True:
        # wide range
        rol1start = 0.0
        rol1stop = 360.0
        rol1step = 20.0

        pit1start = 0.0
        pit1stop = 90.0
        pit1step = 20.0

        yaw1start = 0.0
        yaw1stop = 360.0
        yaw1step = 20.0

        rol2start = 0.0
        rol2stop = 360.0
        rol2step = 20.0

        pit2start = 0.0
        pit2stop = 90.0
        pit2step = 20.0

        yaw2start = 0.0
        yaw2stop = 360.0
        yaw2step = 20.0
    else:
        # focussed range
        rol1start = 0.0
        rol1stop = 0.0
        rol1step = 0.1

        pit1start = 0.0
        pit1stop = 5.0
        pit1step = 5.0

        yaw1start = 89.0
        yaw1stop = 91.0
        yaw1step = 0.0

        rol2start = 0.0
        rol2stop = 0.0
        rol2step = 0.0

        pit2start = 0.0
        pit2stop = 0.0
        pit2step = 0.1

        yaw2start = 89.0
        yaw2stop = 91.0
        yaw2step = 0.1
    #endif

    print "Starting testGetQuatFromMatrix, it can take a while ..."

    tstart = osg.Timer.instance().tick()
    count = 0
    for rol1 in arange(rol1start, rol1stop + 1, rol1step):
        # for (double pit1 = pit1start pit1 <= pit1stop pit1 += pit1step)
        for pit1 in arange(pit1start, pit1stop + 1, pit1step):
            # for (double yaw1 = yaw1start yaw1 <= yaw1stop yaw1 += yaw1step)
            for yaw1 in arange(yaw1start, yaw1stop + 1, yaw1step):
                # for (double rol2 = rol2start rol2 <= rol2stop rol2 += rol2step)
                for rol2 in arange(rol2start, rol2stop + 1, rol2step):
                    # for (double pit2 = pit2start pit2 <= pit2stop pit2 += pit2step)
                    for pit2 in arange(pit2start, pit2stop, pit2step):
                        # for (double yaw2 = yaw2start yaw2 <= yaw2stop yaw2 += yaw2step)
                        for yaw2 in arange(yaw2start, yaw2stop + 1, yaw2step):

                            count += 1
                            # create two quats based on the roll, pitch and yaw values
                            rot_quat1 = osg.Quat(osg.DegreesToRadians(rol1),
                                                 osg.Vec3d(1, 0, 0),
                                                 osg.DegreesToRadians(pit1),
                                                 osg.Vec3d(0, 1, 0),
                                                 osg.DegreesToRadians(yaw1),
                                                 osg.Vec3d(0, 0, 1))

                            rot_quat2 = osg.Quat(osg.DegreesToRadians(rol2),
                                                 osg.Vec3d(1, 0, 0),
                                                 osg.DegreesToRadians(pit2),
                                                 osg.Vec3d(0, 1, 0),
                                                 osg.DegreesToRadians(yaw2),
                                                 osg.Vec3d(0, 0, 1))

                            # create an output quat using quaternion math
                            out_quat1 = rot_quat2 * rot_quat1

                            # create two matrices based on the input quats
                            # osg.Matrixd mat1,mat2
                            mat1 = osg.Matrixd()
                            mat2 = osg.Matrixd()
                            mat1.makeRotate(rot_quat1)
                            mat2.makeRotate(rot_quat2)

                            # create an output quat by matrix multiplication and getRotate
                            out_mat = mat2 * mat1
                            # add matrix scale for even more nastiness
                            out_mat = out_mat * scalemat
                            out_quat2 = out_mat.getRotate()

                            # If the quaternion W is <0, then we should reflect
                            # to get it into the positive W.
                            # Unfortunately, when W is very small (close to 0), the sign
                            # does not really make sense because of precision problems
                            # and the reflection might not work.
                            if out_quat1.w() < 0:
                                out_quat1 = out_quat1 * -1.0
                            if out_quat2.w() < 0:
                                out_quat2 = out_quat2 * -1.0

                            # if the output quat length is not one
                            # or if the components do not match,
                            # something is amiss

                            componentsOK = False
                            if (((abs(out_quat1.x() - out_quat2.x())) < eps)
                                    and
                                ((abs(out_quat1.y() - out_quat2.y())) < eps)
                                    and
                                ((abs(out_quat1.z() - out_quat2.z())) < eps)
                                    and
                                ((abs(out_quat1.w() - out_quat2.w())) < eps)):

                                componentsOK = True

                            # We should also test for q = -q which is valid, so reflect
                            # one quat.
                            out_quat2 = out_quat2 * -1.0
                            if (((abs(out_quat1.x() - out_quat2.x())) < eps)
                                    and
                                ((abs(out_quat1.y() - out_quat2.y())) < eps)
                                    and
                                ((abs(out_quat1.z() - out_quat2.z())) < eps)
                                    and
                                ((abs(out_quat1.w() - out_quat2.w())) < eps)):
                                componentsOK = True

                            lengthOK = False
                            if (abs(1.0 - out_quat2.length()) < eps):
                                lengthOK = True

                            if (not lengthOK) or (not componentsOK):
                                print[
                                    "testGetQuatFromMatrix problem at: \n",
                                    " r1=", rol1, " p1=", pit1, " y1=", yaw1,
                                    " r2=", rol2, " p2=", pit2, " y2=", yaw2
                                ]
                                print "quats:        ", out_quat1, " length: ", out_quat1.length(
                                ), "\n"
                                print "mats and get: ", out_quat2, " length: ", out_quat2.length(
                                ), "\n\n"

    tstop = osg.Timer.instance().tick()
    duration = osg.Timer.instance().delta_s(tstart, tstop)
    print "Time for testGetQuatFromMatrix with ", count, " iterations: ", duration
示例#16
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)
示例#17
0
            camera.setReadBuffer(buffer)
            viewer.setCamera(camera)
        else:
            osg.notify(osg.NOTICE), "Pixel buffer has not been created successfully."

    # Read camera settings for screenshot
    lat = 50
    lon = 10
    alt = 2000
    heading = 0
    incline = 45
    roll = 0
    camera_specified = False
    if arguments.read("--camera", lat, lon, alt, heading, incline, roll) :
        camera_specified=True
        lat = osg.DegreesToRadians(lat)
        lon = osg.DegreesToRadians(lon)
        heading = osg.DegreesToRadians(heading)
        incline = osg.DegreesToRadians(incline)
        roll = osg.DegreesToRadians(roll)

    # load the data
    loadedModel = osgDB.readNodeFiles(arguments)
    if  not loadedModel : 
        print arguments.getApplicationName(), ": No data loaded"
        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.