示例#1
0
class KeyboardEventHandler (osgGA.GUIEventHandler) :

    KeyboardEventHandler()
    


    static void rotate(float angle,osg.MatrixTransform *joint)
        zRot = osg.Matrix()
        zRot.makeRotate(angle, 0.0,0.0,1.0)
        joint.setMatrix(zRot*joint.getMatrix())
示例#2
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)"
示例#3
0
    def drawImplementation(renderInfo, drawable):

        
        state = *renderInfo.getState()

        if  not _firstTime :
            _previousModelViewMatrix = _currentModelViewMatrix
            _currentModelViewMatrix = state.getModelViewMatrix()
            _inverseModelViewMatrix.invert(_currentModelViewMatrix)

            T = osg.Matrix(_previousModelViewMatrix*_inverseModelViewMatrix)

            geometry = dynamic_cast<osg.Geometry*>(const_cast<osg.Drawable*>(drawable))
            vertices = dynamic_cast<osg.Vec3Array*>(geometry.getVertexArray())
            for(unsigned int i=0i+1<vertices.size()i+=2)
                (*vertices)[i+1] = (*vertices)[i]*T
示例#4
0
def buildEndEffector():

    
    mt = osg.MatrixTransform()
    m = osg.Matrix()
    length = 17.0
    m.makeTranslate(0,0,length/2)
    mt.setMatrix(m)
    geode_3 = osg.Geode()
    shape1 = osg.ShapeDrawable(osg.Box(osg.Vec3(-EndEffector, 0.0, 0.0), .5, 1.5, length), hints)
    shape2 = osg.ShapeDrawable(osg.Box(osg.Vec3( EndEffector, 0.0, 0.0), .5, 1.5, length), hints)
    shape1.setColor(osg.Vec4(0.8, 0.8, 0.4, 1.0))
    shape2.setColor(osg.Vec4(0.8, 0.8, 0.4, 1.0))
    geode_3.addDrawable(shape1)
    geode_3.addDrawable(shape2)
    mt.addChild(geode_3)
    return mt
示例#5
0
def main(argv):


    
    if argc<=1 :
        readConfFile("osg.conf")                                                                          # read ConfigFile        1
    else:
        readConfFile(argv[1])                                                                          # read ConfigFile        1
    
    # construct the viewer.
    viewer = osgViewer.Viewer()

    updateText = osgText.Text()
    updateText.setDataVariance(osg.Object.DYNAMIC)

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

    root = osg.Group()

    root.addChild( setupGraph() )

    # add the HUD subgraph.    
    root.addChild(createHUD(updateText))
   
    # add model to viewer.
    viewer.setSceneData( root )

    lookAt = osg.Matrix()
    lookAt.makeLookAt(osg.Vec3(0.0, -4.0, 0.0), centerScope, osg.Vec3(0.0, 0.0, 1.0))

    viewer.getCamera().setViewMatrix(lookAt)
        
    viewer.realize()

    while   not viewer.done()  :
        # fire off the cull and draw traversals of the scene.
        viewer.frame()        

    return 0
示例#6
0
class GameEventHandler (osgGA.GUIEventHandler) :

    GameEventHandler()
    
    META_Object(osgStereImageApp,GameEventHandler)

    handle = virtual bool( osgGA.GUIEventAdapter ea,osgGA.GUIActionAdapter)
    
    virtual void getUsage(osg.ApplicationUsage usage) 
    
    getCameraPosition = osg.Matrix()
    
    def compileGLObjects(state):
    
        
        compile = osgUtil.GLObjectsVisitor()
        compile.setState(state)
    
        for(ObjectMap.iterator itr = s_objectMap.begin()
            not = s_objectMap.end()
            ++itr)
            itr.second.accept(compile)
示例#7
0
         else              # behind layers peeling passes
            camera.addChild(transparentNodePeel)
            # set depth (shadow) texture for depth peeling and add a cull callback
            camera.getOrCreateStateSet().setTextureAttributeAndModes(_texUnit, prevDepthTexture)
            camera.addCullCallback(ccb)
        _root.addChild(camera)

    # create the composite camera that blends the peeled layers into the final scene
    _compositeCamera = osg.Camera()
    _compositeCamera.setDataVariance(osg.Object.DYNAMIC)
    _compositeCamera.setInheritanceMask(osg.Camera.READ_BUFFER | osg.Camera.DRAW_BUFFER)
    _compositeCamera.setRenderOrder(osg.Camera.POST_RENDER, _numPasses)
    _compositeCamera.setComputeNearFarMode(osg.Camera.COMPUTE_NEAR_FAR_USING_PRIMITIVES)
    _compositeCamera.setClearMask(0)
    _compositeCamera.setReferenceFrame(osg.Transform.ABSOLUTE_RF)
    _compositeCamera.setViewMatrix(osg.Matrix())
    _compositeCamera.setProjectionMatrix(osg.Matrix.ortho2D(0, 1, 0, 1))
    _compositeCamera.setCullCallback(CullCallback(0, _texWidth, _texHeight, 0))
    stateSet = _compositeCamera.getOrCreateStateSet()
    stateSet.setRenderBinDetails(100, "TraversalOrderBin", osg.StateSet.OVERRIDE_RENDERBIN_DETAILS)
    _root.addChild(_compositeCamera)

    # solid geometry is blended first, transparency layers are blended in back to front order.
    # this order is achieved by rendering using a TraversalOrderBin (see camera stateset).
    for (unsigned int i = _numPasses i > 0 --i) 
        geode = createQuad(i%_numPasses, numTiles)
        stateSet = geode.getOrCreateStateSet()
        stateSet.setTextureAttributeAndModes(0, _colorTextures[i%_numPasses], osg.StateAttribute.ON)
        stateSet.setAttribute(osg.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg.StateAttribute.ON)
        stateSet.setMode(GL_BLEND, osg.StateAttribute.ON)
        stateSet.setMode(GL_LIGHTING, osg.StateAttribute.OFF)
示例#8
0
            position = bs.center()

            typedef std.pair<osg.Vec3, osg.Vec3> ImageData
             ImageData id[] =
                ImageData( osg.Vec3( 1,  0,  0), osg.Vec3( 0, -1,  0) ), # +X
                ImageData( osg.Vec3(-1,  0,  0), osg.Vec3( 0, -1,  0) ), # -X
                ImageData( osg.Vec3( 0,  1,  0), osg.Vec3( 0,  0,  1) ), # +Y
                ImageData( osg.Vec3( 0, -1,  0), osg.Vec3( 0,  0, -1) ), # -Y
                ImageData( osg.Vec3( 0,  0,  1), osg.Vec3( 0, -1,  0) ), # +Z
                ImageData( osg.Vec3( 0,  0, -1), osg.Vec3( 0, -1,  0) )  # -Z
            

            for(unsigned int i=0 
                i<6  and  i<_Cameras.size()
                ++i)
                localOffset = osg.Matrix()
                localOffset.makeLookAt(position,position+id[i].first,id[i].second)
                
                viewMatrix = worldToLocal*localOffset
            
                _Cameras[i].setReferenceFrame(osg.Camera.ABSOLUTE_RF)
                _Cameras[i].setProjectionMatrixAsFrustum(-1.0,1.0,-1.0,1.0,1.0,10000.0)
                _Cameras[i].setViewMatrix(viewMatrix)
    
        virtual ~UpdateCameraAndTexGenCallback() 
        
        _reflectorNodePath = osg.NodePath()        
        _Cameras = CameraList()


class TexMatCullCallback (osg.NodeCallback) :
示例#9
0
        mt =  0 : dynamic_cast<osg: if (nodePath.empty()) else MatrixTransform*>(nodePath.back())
        if mt :
            csn = 0

            # find coordinate system node from our parental chain
            i = unsigned int()
            for(i=0 i<nodePath.size()  and  csn==0 ++i)
                csn = dynamic_cast<osg.CoordinateSystemNode*>(nodePath[i])
            
            if csn :


                ellipsoid = csn.getEllipsoidModel()
                if ellipsoid :
                    inheritedMatrix = osg.Matrix()
                    for(i+=1 i<nodePath.size()-1 ++i)
                        transform = nodePath[i].asTransform()
                        if transform : transform.computeLocalToWorldMatrix(inheritedMatrix, nv)
                    
                    matrix = osg.Matrixd(inheritedMatrix)

                    #osg.Matrixd matrix
                    ellipsoid.computeLocalToWorldTransformFromLatLongHeight(_latitude,_longitude,_height,matrix)
                    matrix.preMultRotate(_rotation)
                    
                    mt.setMatrix(matrix)

            
        traverse(node,nv)
    
示例#10
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)
示例#11
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 osg.AnimationPath and UpdateCallbacks for adding animation to your scenes.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("-o <filename>","Object to be loaded")
    
    if  arguments.read( "-h" )  or  arguments.read( "--help" )  :
        print "Argumentlist:"
        print "\t-o <filename> sets object to be loaded and sliced"
        print "\t--slices <unsigned int> sets number of slices through the object"
        print "\t--near <double> sets start for near clipping plane"
        print "\t--far <double> sets start for far clipping plane"
        
        return 1
    
    outputName = str("volume_tex.dds")
    while  arguments.read( "-o", outputName )  :  


    numberSlices = 128
    while  arguments.read( "--slices", numberSlices)  :  

    nearClip = 0.0
    farClip = 0.0
    while  arguments.read( "--near",nearClip )  :  
    while  arguments.read( "--far", farClip)  :  

    
    # load the scene.
    loadedModel = osgDB.readNodeFiles( arguments )
    if  not loadedModel : 
        print "No data loaded."
        return 1

    bs = loadedModel.getBound()
    sp = SliceProcessor( (double)bs.radius(), numberSlices )
    if nearClip not =0.0 : sp._nearPlane = nearClip
    if farClip not =0.0 : sp._farPlane = farClip

    # 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
    


    traits = osg.GraphicsContext.Traits()
    traits.x = 100
    traits.y = 100
    traits.width = numberSlices
    traits.height = numberSlices
    traits.alpha = 8
    traits.windowDecoration = True
    traits.doubleBuffer = True
    traits.sharedContext = 0
    traits.pbuffer = False

    gc = osg.GraphicsContext.createGraphicsContext(traits)
    if  not gc  or   not gc.valid() :
        osg.notify(osg.NOTICE), "Error: unable to create graphics window"
        return 1
    
    gc.realize()
    gc.makeCurrent()

    # create the view of the scene.
    sceneView = osgUtil.SceneView()
    sceneView.setDefaults()
    sceneView.setSceneData(loadedModel)

    # initialize the view to look at the center of the scene graph
    viewMatrix = osg.Matrix()
    # distance from viewport to object's center is set to be 2x bs.radius()
    viewMatrix.makeLookAt(bs.center()-osg.Vec3(0.0,2.0*bs.radius(),0.0),bs.center(),osg.Vec3(0.0,0.0,1.0))
    
    # turn off autocompution of near and far clipping planes
    sceneView.setComputeNearFarMode(osgUtil.CullVisitor.DO_NOT_COMPUTE_NEAR_FAR)

    # set the clear color of the background to make sure that the alpha is 0.0.
    sceneView.setClearColor(osg.Vec4(0.0,0.0,0.0,0.0))

    # record the timer tick at the start of rendering.     
    start_tick = osg.Timer.instance().tick()
    
    print "radius: ", bs.radius()
    
    frameNum = 0
    double tmpNear, tmpFar
    baseImageName = str("shot_")
    tmpImageName = str()
    
    tmpImage = osg.Image()
    
    # main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.)
    for( unsigned int i = 0  i < sp._sliceNumber  and  gc.isRealized()  ++i )
        # set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly
        frameStamp = osg.FrameStamp()
        frameStamp.setReferenceTime(osg.Timer.instance().delta_s(start_tick,osg.Timer.instance().tick()))
        frameStamp.setFrameNumber(frameNum++)
        
        # pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp
        sceneView.setFrameStamp(frameStamp)
        
        # update the viewport dimensions, incase the window has been resized.
        sceneView.setViewport(0,0,traits.width,traits.height)
        
        
        # set the view
        sceneView.setViewMatrix(viewMatrix)
        
        # set Projection Matrix
        tmpNear = sp._nearPlane+i*sp._sliceDelta
        tmpFar = sp._farPlane+(i*sp._sliceDelta)+sp._nearFarOffset
        sceneView.setProjectionMatrixAsOrtho(-(bs.radius()+bs.radius()/2), bs.radius()+bs.radius()/2,-bs.radius(), bs.radius(), tmpNear, tmpFar)

        # do the update traversal the scene graph - such as updating animations
        sceneView.update()
        
        # do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins
        sceneView.cull()
        
        # draw the rendering bins.
        sceneView.draw()
                
        # Swap Buffers
        gc.swapBuffers()
        
        print "before readPixels: _r = ", sp._image.r()
        
        tmpImage.readPixels(static_cast<int>(sceneView.getViewport().x()),
                             static_cast<int>(sceneView.getViewport().y()),
                             static_cast<int>(sceneView.getViewport().width()),
                             static_cast<int>(sceneView.getViewport().height()),
                             GL_RGBA,GL_UNSIGNED_BYTE)
        
#        print "vor copySubImage: _r = ", sp._image.r()
        sp._image.copySubImage( 0, 0, i, tmpImage )

        #
#        o = std.ostringstream()
#        o, baseImageName, i, ".rgba"
#        tmpImageName = o.str()
#        osgDB.writeImageFile( *(sp._image), tmpImageName )
#        print "Wrote image to file: ", tmpImageName
#        
    osgDB.writeImageFile( *(sp._image), outputName)

    return 0



if __name__ == "__main__":
    main(sys.argv)
示例#12
0
            case(osgGA.GUIEventAdapter.DRAG):
            case(osgGA.GUIEventAdapter.MOVE):
                px = (ea.getXnormalized()+1.0)*0.5

                if _numberOfPlayers>=1 : _players[0].moveTo(px)

                return True

            default:
                return False
    return False    

void GameEventHandler.getUsage(osg.ApplicationUsage) 

osg.Matrix GameEventHandler.getCameraPosition()
    cameraPosition = osg.Matrix()
    center = _origin+(_width+_height)*0.5
    
    distance = _height.length()/(2.0*tanf(_fovy*0.5))
    
    cameraPosition.makeLookAt(center-osg.Vec3(0.0,distance,0.0),center,osg.Vec3(0.0,0.0,1.0))
    return cameraPosition

osg.Node* GameEventHandler.createScene()
    _gameSwitch = osg.Switch()
    
    # create a dummy catchable to load all the particule textures to reduce 
    # latency later on..
    _dummyCatchable = CatchableObject()
    _dummyCatchable.setObject("Catch/a.png","a",osg.Vec3(0.0,0.0,0.0),1.0,osg.Vec3(0.0,0.0,0.0))
    _dummyCatchable.explode()
示例#13
0
        if _referenceFrame==RELATIVE_RF :
            matrix.postMult(inverse)
        else # absolute
            matrix = inverse
        return True

    def getMatrix():

         return _pageOffset*osg.Matrix.rotate(-_rotation,0.0,0.0,1.0) 
    def getInverseMatrix():
         return osg.Matrix.inverse(getMatrix()) 

    Page(Album* album, unsigned int pageNo,  str frontFileName,  str backFileName, float width, float height)

    _rotation = float()
    _pageOffset = osg.Matrix()

    _targetRotation = float()
    _targetTime = float()
    _lastTimeTraverse = float()

    _switch = osg.Switch()




class Album (osg.Referenced) :

    Album(osg.ArgumentParser ap, float width, float height)

    def getScene():
示例#14
0
    # 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)

    viewer.setFusionDistance(osgUtil.SceneView.USE_FUSION_DISTANCE_VALUE,radius)

    # set up the SlideEventHandler.
    if onDisk : seh.set(fileList,rootNode,offsetX,offsetY,texmatLeft,texmatRight,radius,height,length,timeDelayBetweenSlides,autoSteppingActive)
    else seh.set(rootNode,offsetX,offsetY,texmatLeft,texmatRight,timeDelayBetweenSlides,autoSteppingActive)

    homePosition = osg.Matrix()
    homePosition.makeLookAt(osg.Vec3(0.0,0.0,0.0),osg.Vec3(0.0,1.0,0.0),osg.Vec3(0.0,0.0,1.0))

    while   not viewer.done()  :
        viewer.getCamera().setViewMatrix(homePosition)

        # fire off the cull and draw traversals of the scene.
        viewer.frame()


    return 0



if __name__ == "__main__":
    main(sys.argv)
        anim.addChannel(channel)
    manager.registerAnimation(anim)
    manager.buildTargetReference()

    # let's start  not 
    manager.playAnimation(anim)

    # we will use local data from the skeleton
    rootTransform = osg.MatrixTransform()
    rootTransform.setMatrix(osg.Matrix.rotate(osg.PI_2,osg.Vec3(1.0,0.0,0.0)))
    right0.addChild(createAxis())
    right0.setDataVariance(osg.Object.DYNAMIC)
    right1.addChild(createAxis())
    right1.setDataVariance(osg.Object.DYNAMIC)
    trueroot = osg.MatrixTransform()
    trueroot.setMatrix(osg.Matrix(root.getMatrixInBoneSpace().ptr()))
    trueroot.addChild(createAxis())
    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)
示例#16
0

struct EventOK : public osgWidget.Callback, osg.NodeCallback
    typedef osgAnimation.OutCubicMotion WidgetMotion
#    typedef osgAnimation.OutQuartMotion WidgetMotion
    _motionOver = WidgetMotion()
    _motionLeave = WidgetMotion()
    
    _lastUpdate = double()
    _defaultColor = osgWidget.Color()
    _overColor = osgWidget.Color()
    _over = bool()
    _frame = osgWidget.Frame()
    _width = float()
    _height = float()
    _matrix = osg.Matrix()
    EventOK(osgWidget.Frame* frame) : osgWidget.Callback(osgWidget.EVENT_ALL), _frame(frame) 
        _motionOver = WidgetMotion(0.0, 0.4)
        _motionLeave = WidgetMotion(0.0, 0.5)
        _defaultColor = _frame.getEmbeddedWindow().getColor()
        _overColor = osgWidget.Color(229.0/255.0,
                                      103.0/255.0,
                                      17.0/255,
                                      _defaultColor[3])
        _over  = False

    bool operator()(osgWidget.Event ev)
        if ev.type == osgWidget.EVENT_MOUSE_ENTER :
            _over = True
            _width = _frame.getWidth()
            _height = _frame.getHeight()
示例#17
0
def createModel(shader, textureFileName, terrainFileName, dynamic, useVBO):

    
    geode = osg.Geode()
    
    geom = osg.Geometry()
    geode.addDrawable(geom)
    
    # dimensions for ~one million triangles :-)
    num_x = 708
    num_y = 708

    # set up state
    
        stateset = geom.getOrCreateStateSet()

        program = osg.Program()
        stateset.setAttribute(program)

        if shader=="simple" :
            vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_simple)
            program.addShader(vertex_shader)

            coeff = osg.Uniform("coeff",osg.Vec4(1.0,-1.0,-1.0,1.0))
            
            stateset.addUniform(coeff)

            if dynamic :
                coeff.setUpdateCallback(UniformVarying)()
                coeff.setDataVariance(osg.Object.DYNAMIC)
                stateset.setDataVariance(osg.Object.DYNAMIC)
            
        elif shader=="matrix" :
            vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_matrix)
            program.addShader(vertex_shader)

            origin = osg.Uniform("origin",osg.Vec4(0.0,0.0,0.0,1.0))
            stateset.addUniform(origin)

            coeffMatrix = osg.Uniform("coeffMatrix",
                osg.Matrix(1.0,0.0,1.0,0.0,
                            0.0,0.0,-1.0,0.0,
                            0.0,1.0,-1.0,0.0,
                            0.0,0.0,1.0,0.0))

            stateset.addUniform(coeffMatrix)
        elif shader=="texture" :
            vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_texture)
            program.addShader(vertex_shader)

            image = 0

            if terrainFileName.empty() :
                image = osg.Image()
                tx = 38
                ty = 39
                image.allocateImage(tx,ty,1,GL_LUMINANCE,GL_FLOAT,1)
                for(unsigned int r=0r<ty++r)
                    for(unsigned int c=0c<tx++c)
                        *((float*)image.data(c,r)) = vertex[r+c*39][2]*0.1

                num_x = tx
                num_y = tx