Пример #1
0
def loadImages(image1, image2, texmatLeft, texmatRight, radius, height, length):

    
    imageLeft = osgDB.readImageFile(image1)
    imageRight = osgDB.readImageFile(image2)
    if imageLeft.valid()  and  imageRight.valid() :
	streamLeft = dynamic_cast<osg.ImageStream*>(imageLeft)
	if streamLeft : streamLeft.play()

	streamRight = dynamic_cast<osg.ImageStream*>(imageRight)
	if streamRight : streamRight.play()


	average_s = (imageLeft.s()+imageRight.s())*0.5
	average_t = (imageLeft.t()+imageRight.t())*0.5
	geodeLeft = createSectorForImage(imageLeft,texmatLeft,average_s,average_t, radius, height, length)
	geodeLeft.setNodeMask(0x01)

	geodeRight = createSectorForImage(imageRight,texmatRight,average_s,average_t, radius, height, length)
	geodeRight.setNodeMask(0x02)

	imageGroup = osg.Group()

	imageGroup.addChild(geodeLeft)
	imageGroup.addChild(geodeRight)
	return imageGroup
    else:
	print "Warning: Unable to load both image files, '", image1, "'  '", image2, "', required for stereo imaging."
	return 0
Пример #2
0
def createState():

    
    # read 4 2d images
    image_0 = osgDB.readImageFile("Images/lz.rgb")
    image_1 = osgDB.readImageFile("Images/reflect.rgb")
    image_2 = osgDB.readImageFile("Images/tank.rgb")
    image_3 = osgDB.readImageFile("Images/skymap.jpg")

    if  not image_0  or   not image_1  or   not image_2  or   not image_3 :
        print "Warning: could not open files."
        return osg.StateSet()

    if image_0.getPixelFormat() not =image_1.getPixelFormat()  or  image_0.getPixelFormat() not =image_2.getPixelFormat()  or  image_0.getPixelFormat() not =image_3.getPixelFormat() :
        print "Warning: image pixel formats not compatible."
        return osg.StateSet()
Пример #3
0
def build_world(root):

    

    terrainGeode = osg.Geode()
    # create terrain
        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 )

        size = 1000 # 10km
        scale = size/39.0 # 10km
        z_scale = scale*3.0

        grid = osg.HeightField()
        grid.allocate(38,39)
        grid.setXInterval(scale)
        grid.setYInterval(scale)

        for(unsigned int r=0r<39++r)
            for(unsigned int c=0c<38++c)
                grid.setHeight(c,r,z_scale*vertex[r+c*39][2])
Пример #4
0
def createBase(center, radius):

    

    geode = osg.Geode()
    
    # set up the texture of the base.
    stateset = osg.StateSet()
    image = osgDB.readImageFile("Images/lz.rgb")
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)
        stateset.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON)
    
    geode.setStateSet( stateset )


    grid = osg.HeightField()
    grid.allocate(38,39)
    grid.setOrigin(center+osg.Vec3(-radius,-radius,0.0))
    grid.setXInterval(radius*2.0/(float)(38-1))
    grid.setYInterval(radius*2.0/(float)(39-1))
    
    minHeight = FLT_MAX
    maxHeight = -FLT_MAX


    r = unsigned int()
    for(r=0r<39++r)
        for(unsigned int c=0c<38++c)
            h = vertex[r+c*39][2]
            if h>maxHeight : maxHeight=h
            if h<minHeight : minHeight=h
Пример #5
0
    def loadSlide(new_ndx):

        
        if new_ndx == _currentFile :
            return

        _currentFile = new_ndx
        if _currentFile < 0 :
            _currentFile = _files.size() - 1
        elif _currentFile >= static_cast<int>(_files.size()) :
            _currentFile = 0

        obj = osgDB.readRefObjectFile(_files[_currentFile], _options)
        tex = dynamic_cast<osg.Texture*>(obj)
        if  not tex : 
            stream = dynamic_cast<osg.ImageStream*>(obj)
            if  not stream :
                stream = dynamic_cast<osg.ImageStream*>(osgDB.readImageFile(_files[_currentFile], _options))

            if stream :
                tex = osg.Texture2D(stream)
                tex.setResizeNonPowerOfTwoHint(False)
        if tex : 
            stream = dynamic_cast<osg.ImageStream*>(tex.getImage(0))
            if stream :
                stream.play()
            v = ReplaceTextureVisitor(tex)
            _node.accept(v)
Пример #6
0
def createButtonOk(theme, text, fontSize):

    
    frame = osgWidget.Frame.createSimpleFrameFromTheme(
        "ButtonOK",
        osgDB.readImageFile(theme),
        300.0, 
        50.0,
        osgWidget.Frame.FRAME_TEXTURE
        )
    frame.getBackground().setColor(0.0, 0.0, 0.0, 0.0)

    label = createLabel(text, "fonts/Vera.ttf", fontSize, osgWidget.Color(0,0,0,1))

    box = osgWidget.Box("HBOX", osgWidget.Box.HORIZONTAL)
    box.addWidget(label)
    box.resize()
    colorBack = frame.getEmbeddedWindow().getColor()
    box.getBackground().setColor(colorBack)
    frame.getEmbeddedWindow().setWindow(box)
    box.setVisibilityMode(osgWidget.Window.VM_ENTIRE)
    box.setEventMask(osgWidget.EVENT_NONE)

    frame.resizeFrame(box.getWidth(), box.getHeight())
    frame.resizeAdd(0, 0)

    event = EventOK(frame)
    frame.setUpdateCallback(event)
    frame.addCallback(event)


    return frame.release()
Пример #7
0
def makeStateSet(size):

    
    set = osg.StateSet()

    #/ Setup cool blending
    set.setMode(GL_BLEND, osg.StateAttribute.ON)
    fn = osg.BlendFunc()
    fn.setFunction(osg.BlendFunc.SRC_ALPHA, osg.BlendFunc.DST_ALPHA)
    set.setAttributeAndModes(fn, osg.StateAttribute.ON)

    #/ Setup the point sprites
    sprite = osg.PointSprite()
    set.setTextureAttributeAndModes(0, sprite, osg.StateAttribute.ON)

    #/ Give some size to the points to be able to see the sprite
    point = osg.Point()
    point.setSize(size)
    set.setAttribute(point)

    #/ Disable depth test to avoid sort problems and Lighting
    set.setMode(GL_DEPTH_TEST, osg.StateAttribute.OFF)
    set.setMode(GL_LIGHTING, osg.StateAttribute.OFF)

    #/ The texture for the sprites
    tex = osg.Texture2D()
    tex.setImage(osgDB.readImageFile("Images/particle.rgb"))
    set.setTextureAttributeAndModes(0, tex, osg.StateAttribute.ON)

    return set
Пример #8
0
def createErrorMessage(themeMessage, themeButton, titleText, messageText, buttonText, font, fontSize):

    

    frame = osgWidget.Frame.createSimpleFrameFromTheme(
        "error",
        osgDB.readImageFile(themeMessage),
        300.0,
        50.0,
        osgWidget.Frame.FRAME_ALL
        )
    frame.getBackground().setColor(0.0, 0.0, 0.0, 0.0)

    labelText = createLabel(messageText, font, fontSize, osgWidget.Color(0,0,0,1))
    labelTitle = createLabel(titleText, font, fontSize+5, osgWidget.Color(0.4,0,0,1))

    box = osgWidget.Box("VBOX", osgWidget.Box.VERTICAL)

    buttonOK = createButtonOk(themeButton, buttonText, fontSize).embed()
    buttonOK.setColor(osgWidget.Color(0,0,0,0))
    buttonOK.setCanFill(False)

    box.addWidget(buttonOK)
    box.addWidget(labelText)
    box.addWidget(labelTitle)

    colorBack = frame.getEmbeddedWindow().getColor()
    box.getBackground().setColor(colorBack)

    frame.setWindow(box)

    box.resize()
    frame.resizeFrame(box.getWidth(), box.getHeight())
    return frame.release()
Пример #9
0
def createTeapot():


    
    geode = osg.Geode()

    # add the teapot to the geode.
    geode.addDrawable( Teapot )()

    # add a reflection map to the teapot.     
    image = osgDB.readImageFile("Images/reflect.rgb")
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)

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

        stateset = osg.StateSet()
        stateset.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON)
        stateset.setTextureAttributeAndModes(0,texgen,osg.StateAttribute.ON)
        
        geode.setStateSet(stateset)
   
    return geode
Пример #10
0
def main(argv):

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

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

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

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

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

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

    for(unsigned int contextID = 0 
        contextID<osg.DisplaySettings.instance().getMaxNumberOfGraphicsContexts()
        ++contextID)
        textExt = osg.Texture.getExtensions(contextID,False)
        if textExt :
            if  not textExt.isMultiTexturingSupported() :
                print "Warning: multi-texturing not supported by OpenGL drivers, unable to run application."
                return 1
Пример #11
0
def main(argv):

    
    viewer = osgViewer.Viewer()

    wm = osgWidget.WindowManager(
        viewer,
        1280.0,
        1024.0,
        MASK_2D,
        osgWidget.WindowManager.WM_PICK_DEBUG
        #osgWidget.WindowManager.WM_NO_INVERT_Y
    )
    
    frame = osgWidget.Frame.createSimpleFrameFromTheme(
        "frame",
        osgDB.readImageFile("osgWidget/theme.png"),
        40.0,
        40.0,
	osgWidget.Frame.FRAME_ALL
    )

    frame.getBackground().setColor(0.0, 0.0, 0.0, 0.0)

    # This is our Transformers box. :)
    box = osgWidget.Box("images", osgWidget.Box.VERTICAL)
    img1 = osgWidget.Widget("im1", 512.0, 512.0)
    img2 = osgWidget.Widget("im2", 512.0, 512.0)
    img3 = osgWidget.Widget("im3", 512.0, 512.0)
    img4 = osgWidget.Widget("im4", 512.0, 512.0)

    img1.setImage("osgWidget/scrolled1.jpg", True)
    img2.setImage("osgWidget/scrolled2.jpg", True)
    img3.setImage("osgWidget/scrolled3.jpg", True)
    img4.setImage("osgWidget/scrolled4.jpg", True)

    img1.setMinimumSize(10.0, 10.0)
    img2.setMinimumSize(10.0, 10.0)
    img3.setMinimumSize(10.0, 10.0)
    img4.setMinimumSize(10.0, 10.0)

    box.addWidget(img1)
    box.addWidget(img2)
    box.addWidget(img3)
    box.addWidget(img4)
    box.setEventMask(osgWidget.EVENT_NONE)

    #frame.getEmbeddedWindow().setWindow(box)
    frame.setWindow(box)
    frame.getEmbeddedWindow().setColor(1.0, 1.0, 1.0, 1.0)
    frame.resize(300.0, 300.0)
    frame.addCallback(osgWidget.Callback(scrollWindow, osgWidget.EVENT_MOUSE_SCROLL))
    frame.addCallback(osgWidget.Callback(changeTheme, osgWidget.EVENT_KEY_DOWN))

    wm.addChild(frame)

    return osgWidget.createExample(viewer, wm)
Пример #12
0
def createMirrorTexturedState(filename):
    dstate = osg.StateSet();
    dstate.setMode(osg.GL_CULL_FACE,osg.StateAttribute.OFF|osg.StateAttribute.PROTECTED);

    #// set up the texture.
    image = osgDB.readImageFile(filename);
    if (image):
        texture = osg.Texture2D();
        texture.setImage(image);
        dstate.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON|osg.StateAttribute.PROTECTED);

    return dstate;
Пример #13
0
def readCubeMap():


    
    cubemap = osg.TextureCubeMap()
    ##define CUBEMAP_FILENAME(face) "nvlobby_" #face ".png"
    ##define CUBEMAP_FILENAME(face) "Cubemap_axis/" #face ".png"
    #define CUBEMAP_FILENAME(face) "Cubemap_snow/" #face ".jpg"

    imagePosX = osgDB.readImageFile(CUBEMAP_FILENAME(posx))
    imageNegX = osgDB.readImageFile(CUBEMAP_FILENAME(negx))
    imagePosY = osgDB.readImageFile(CUBEMAP_FILENAME(posy))
    imageNegY = osgDB.readImageFile(CUBEMAP_FILENAME(negy))
    imagePosZ = osgDB.readImageFile(CUBEMAP_FILENAME(posz))
    imageNegZ = osgDB.readImageFile(CUBEMAP_FILENAME(negz))

    if imagePosX  and  imageNegX  and  imagePosY  and  imageNegY  and  imagePosZ  and  imageNegZ :
        cubemap.setImage(osg.TextureCubeMap.POSITIVE_X, imagePosX)
        cubemap.setImage(osg.TextureCubeMap.NEGATIVE_X, imageNegX)
        cubemap.setImage(osg.TextureCubeMap.POSITIVE_Y, imagePosY)
        cubemap.setImage(osg.TextureCubeMap.NEGATIVE_Y, imageNegY)
        cubemap.setImage(osg.TextureCubeMap.POSITIVE_Z, imagePosZ)
        cubemap.setImage(osg.TextureCubeMap.NEGATIVE_Z, imageNegZ)

        cubemap.setWrap(osg.Texture.WRAP_S, osg.Texture.CLAMP_TO_EDGE)
        cubemap.setWrap(osg.Texture.WRAP_T, osg.Texture.CLAMP_TO_EDGE)
        cubemap.setWrap(osg.Texture.WRAP_R, osg.Texture.CLAMP_TO_EDGE)

        cubemap.setFilter(osg.Texture.MIN_FILTER, osg.Texture.LINEAR_MIPMAP_LINEAR)
        cubemap.setFilter(osg.Texture.MAG_FILTER, osg.Texture.LINEAR)

    return cubemap
Пример #14
0
def createMirrorTexturedState(filename):


    
    dstate = osg.StateSet()
    dstate.setMode(GL_CULL_FACE,osg.StateAttribute.OFF|osg.StateAttribute.PROTECTED)

    # set up the texture.
    image = osgDB.readImageFile(filename.c_str())
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)
        dstate.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON|osg.StateAttribute.PROTECTED)

    return dstate
Пример #15
0
def createShapes():

    
    geode = osg.Geode()

    
    # ---------------------------------------
    # Set up a StateSet to texture the objects
    # ---------------------------------------
    stateset = osg.StateSet()

    image = osgDB.readImageFile( "Images/lz.rgb" )
    if image :
        texture = osg.Texture2D()
        texture.setImage(image)
        texture.setFilter(osg.Texture.MIN_FILTER, osg.Texture.LINEAR)
        stateset.setTextureAttributeAndModes(0,texture, osg.StateAttribute.ON)
    
    stateset.setMode(GL_LIGHTING, osg.StateAttribute.ON)
    
    geode.setStateSet( stateset )

    
    radius = 0.8
    height = 1.0
    
    hints = osg.TessellationHints()
    hints.setDetailRatio(0.5)
    
    geode.addDrawable(osg.ShapeDrawable(osg.Sphere(osg.Vec3(0.0,0.0,0.0),radius),hints))
    geode.addDrawable(osg.ShapeDrawable(osg.Box(osg.Vec3(2.0,0.0,0.0),2*radius),hints))
    geode.addDrawable(osg.ShapeDrawable(osg.Cone(osg.Vec3(4.0,0.0,0.0),radius,height),hints))
    geode.addDrawable(osg.ShapeDrawable(osg.Cylinder(osg.Vec3(6.0,0.0,0.0),radius,height),hints))
    geode.addDrawable(osg.ShapeDrawable(osg.Capsule(osg.Vec3(8.0,0.0,0.0),radius,height),hints))

    grid = osg.HeightField()
    grid.allocate(38,39)
    grid.setXInterval(0.28)
    grid.setYInterval(0.28)
    
    for(unsigned int r=0r<39++r)
        for(unsigned int c=0c<38++c)
            grid.setHeight(c,r,vertex[r+c*39][2])
Пример #16
0
def createBackground():


    

    # we'll create a texture mapped quad to sit behind the Geometry
    image = osgDB.readImageFile("Images/primitives.gif")
    if  not image : return NULL


    # create Geometry object to store all the vertices and lines primitive.
    polyGeom = osg.Geometry()

    # note, anticlockwise ordering.
    osg.Vec3 myCoords[] =
        osg.Vec3(-1.22908,0.0,1.0),
        osg.Vec3(-1.22908,0.0,-1.0),
        osg.Vec3(1.22908,0.0,-1.0),
        osg.Vec3(1.22908,0.0,1.0)
Пример #17
0
def createEarth():

    
    hints = osg.TessellationHints()
    hints.setDetailRatio(5.0)

    
    sd = osg.ShapeDrawable(osg.Sphere(osg.Vec3(0.0,0.0,0.0), osg.WGS_84_RADIUS_POLAR), hints)
    
    geode = osg.Geode()
    geode.addDrawable(sd)
    
    filename = osgDB.findDataFile("Images/land_shallow_topo_2048.jpg")
    geode.getOrCreateStateSet().setTextureAttributeAndModes(0, osg.Texture2D(osgDB.readImageFile(filename)))
    
    csn = osg.CoordinateSystemNode()
    csn.setEllipsoidModel(osg.EllipsoidModel())
    csn.addChild(geode)
    
    return csn
Пример #18
0
def SetObjectTextureState(geodeCurrent, texture):


    
    # retrieve or create a StateSet
    stateTexture = geodeCurrent.getOrCreateStateSet()

    # load texture.jpg as an image
    imgTexture = osgDB.readImageFile( texture )
    
    # if the image is successfully loaded
    if imgTexture :
        # create a two-dimensional texture object
        texCube = osg.Texture2D()

        # set the texture to the loaded image
        texCube.setImage(imgTexture)

        # set the texture to the state
        stateTexture.setTextureAttributeAndModes(0,texCube,osg.StateAttribute.ON)

        # set the state of the current geode
        geodeCurrent.setStateSet(stateTexture)
            "vec4 newZ = vec4( 0., 0., 1., 0. ) \n"
            "mat4 mV = mat4( newX, newY, newZ, pos ) \n"
            "gl_Position = ( gl_ModelViewProjectionMatrix * mV * gl_Vertex ) \n"
        " \n"

     vertexShader = osg.Shader()
    vertexShader.setType( osg.Shader.VERTEX )
    vertexShader.setShaderSource( vertexSource )

     program = osg.Program()
    program.addShader( vertexShader )

    ss.setAttribute( program,
        osg.StateAttribute.ON | osg.StateAttribute.PROTECTED )

     iLogo = osgDB.readImageFile( "Images/osg128.png" )
    if   not iLogo.valid()  :
        osg.notify( osg.ALWAYS ), "Can't open image file osg128.png"
        return( NULL )
    texLogo = osg.Texture2D( iLogo )
    texLogo.setFilter( osg.Texture2D.MIN_FILTER, osg.Texture2D.LINEAR )
    texLogo.setFilter( osg.Texture2D.MAG_FILTER, osg.Texture2D.LINEAR )

    ss.setTextureAttribute( 0, texLogo )

     texLogoUniform = osg.Uniform( "osgLogo", 0 )
    ss.addUniform( texLogoUniform )

    return( ss.release() )

Пример #20
0
root.addChild(pyramidGeode)

# Now for adding a texture. Here we'll declare a texture instance and set
# its data variance as 'DYNAMIC'. (If we don't declare the texture as dynamic,
# some of the osg's optimization routines could remove it.) The texture class
# encapsulates OpenGL texture modes (wrap, filiter, etc.) as well as an
# osg.Image. The code below shows how to read an osg.Image instance from a
# file and associate this image with a texture.

KLN89FaceTexture = osg.Texture2D()

# protect from being optimized away as static state:
KLN89FaceTexture.setDataVariance(osg.Object.DYNAMIC)

# load an image by reading a file:
klnFace = osgDB.readImageFile("KLN89FaceB.tga")
if klnFace is None:
    print " Couldn't find texture, quitting."
    sys.exit(-1)

# Assign the texture to the image we read from file:
KLN89FaceTexture.setImage(klnFace)

# Textures can be associated with rendering StateSets. The next step is to
# create a StateSet, associate and enable our texture with this state set and
# assign the StateSet to our geometry.

# Create a StateSet with default settings:
stateOne = osg.StateSet()

# Assign texture unit 0 of our StateSet to the texture
Пример #21
0
def main(argv):

    

    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)
    
    # set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage().setApplicationName(arguments.getApplicationName())
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" example provides an interactive viewer for visualising point clouds..")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")
    arguments.getApplicationUsage().addCommandLineOption("--sprites","Point sprites.")
    arguments.getApplicationUsage().addCommandLineOption("--points","Sets the polygon mode to GL_POINT for front and back faces.")


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

    shader = False
    while arguments.read("--shader") : shader = 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
    
    usePointSprites = False
    while arguments.read("--sprites") :  usePointSprites = True 

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

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

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

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

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


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

    stateset = loadedModel.getOrCreateStateSet()
    if usePointSprites :    
        #/ Setup cool blending
        fn = osg.BlendFunc()
        stateset.setAttributeAndModes(fn, osg.StateAttribute.ON)

        #/ Setup the point sprites
        sprite = osg.PointSprite()
        stateset.setTextureAttributeAndModes(0, sprite, osg.StateAttribute.ON)

        #/ The texture for the sprites
        tex = osg.Texture2D()
        tex.setImage(osgDB.readImageFile("Images/particle.rgb"))
        stateset.setTextureAttributeAndModes(0, tex, osg.StateAttribute.ON)

    if  forcePointMode  :
        #/ Set polygon mode to GL_POINT
        pm = osg.PolygonMode(
            osg.PolygonMode.FRONT_AND_BACK, osg.PolygonMode.POINT )
        stateset.setAttributeAndModes( pm, osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE)
    

    # register the handler for modifying the point size
    viewer.addEventHandler(KeyboardEventHandler(viewer.getCamera().getOrCreateStateSet()))


    if shader :
        stateset = loadedModel.getOrCreateStateSet()
    
        #################################/
        # vertex shader using just Vec4 coefficients
        char vertexShaderSource[] = 
            "void main(void) \n"
            " \n"
            "\n"
            "    gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex\n"
            "\n"



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

        vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource)
        program.addShader(vertex_shader)

#if 0
        #################################
        # fragment shader
        #
        char fragmentShaderSource[] = 
            "void main(void) \n"
            " \n"
            "    gl_FragColor = gl_Color \n"
            "\n"
                terrainTile.setElevationLayer(hfl)
                
                lastAppliedLayer = hfl
                
                osg.notify(osg.NOTICE), "created osgTerrain.HeightFieldLayer"
            else:
                osg.notify(osg.NOTICE), "failed to create osgTerrain.HeightFieldLayer"
            
            scale = 1.0
            offset = 0.0
            

        elif arguments.read(pos, "-d",filename)  or  arguments.read(pos, "--elevation-image",filename) :
            osg.notify(osg.NOTICE), "--elevation-image ", filename

            image = osgDB.readImageFile(filename)
            if image.valid() :
                imageLayer = osgTerrain.ImageLayer()
                imageLayer.setImage(image)
                imageLayer.setLocator(locator)
                imageLayer.setValidDataOperator(validDataOperator)
                imageLayer.setMagFilter(filter)
                
                if offset not =0.0  or  scale not =1.0 :
                    imageLayer.transform(offset,scale)
                
                terrainTile.setElevationLayer(imageLayer)
                
                lastAppliedLayer = imageLayer

                osg.notify(osg.NOTICE), "created Elevation osgTerrain.ImageLayer"
Пример #23
0
        ++citr)
        if  not ((*citr)._trees.empty()) :
            cellsNotEmpty.push_back(*citr)
    _cells.swap(cellsNotEmpty)



osg.Geode* ForestTechniqueManager.createTerrain( osg.Vec3 origin,  osg.Vec3 size)
    geode = osg.Geode()

    # ---------------------------------------
    # Set up a StateSet to texture the objects
    # ---------------------------------------
    stateset = osg.StateSet()

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

    geode.setStateSet( stateset )

    numColumns = 38
    numRows = 39
    r = unsigned int()
    c = unsigned int()

    # compute z range of z values of grid data so we can scale it.
    min_z = FLT_MAX
    max_z = -FLT_MAX
Пример #24
0
    bluemarble =  0 : osgDB: if (filename.empty()) else readNodeFile(filename.c_str())
    if bluemarble :
        bs = bluemarble.getBound()
        s = 1.2*bb.radius()/bs.radius()
        positioner = osg.MatrixTransform()
        positioner.setMatrix(osg.Matrix.translate(-bs.center())*osg.Matrix.scale(s,s,s)*osg.Matrix.translate(bb.center()))
        positioner.addChild(bluemarble)

        xform.addChild(positioner)
    else:

        geode = osg.Geode()

        stateset = geode.getOrCreateStateSet()

        image = osgDB.readImageFile("Images/land_shallow_topo_2048.jpg")
        if image :
            texture = osg.Texture2D()
            texture.setImage(image)
            texture.setMaxAnisotropy(8)
            stateset.setTextureAttributeAndModes(0,texture,osg.StateAttribute.ON)

        material = osg.Material()
        stateset.setAttribute(material)

        # the globe
        geode.addDrawable(osg.ShapeDrawable(osg.Sphere(bb.center(),bb.radius()*ratio)))

        xform.addChild(geode)

    return xform
Пример #25
0
        image = (*itr).readImage(dr._fileName,dr._resolutionX,dr._resolutionY,s,t)
        if image : return image
    return 0

osg.Image* ImageReaderWriter.readImage_DynamicSampling(DataReference dr, float s,float t)

    # record previous options.
    previousOptions = osgDB.Registry.instance().getOptions()

    options = osgDB.ImageOptions()
    options._destinationImageWindowMode = osgDB.ImageOptions.PIXEL_WINDOW
    options._destinationPixelWindow.set(0,0,dr._resolutionX,dr._resolutionY)

    osgDB.Registry.instance().setOptions(options)

    image = osgDB.readImageFile(dr._fileName)

    # restore previous options.
    osgDB.Registry.instance().setOptions(previousOptions)

    s =  options._sourcePixelWindow.windowWidth if (options.valid()) else 1.0
    t =  options._sourcePixelWindow.windowHeight if (options.valid()) else 1.0

    return image



osgDB.ReaderWriter.ReadResult ImageReaderWriter.local_readNode( str fileName,  Options*)
    itr = _dataReferences.find(fileName)
    if itr==_dataReferences.end() : return osgDB.ReaderWriter.ReadResult.FILE_NOT_HANDLED
Пример #26
0
    label = osgWidget.Label("", "")
    label.setFont(font)
    label.setFontSize(size)
    label.setFontColor(color)
    label.setColor(osgWidget.Color(0,0,0,0))
    label.setLabel(string)
    label.setCanFill(True)
    return label

osgWidget.Frame* MessageBox.createButtonOk( str theme, 
                                                  str text, 
                                                  str font, 
                                                 int fontSize)
    frame = osgWidget.Frame.createSimpleFrameFromTheme(
        "ButtonOK",
        osgDB.readImageFile(theme),
        300.0, 
        50.0,
        osgWidget.Frame.FRAME_TEXTURE
        )
    frame.getBackground().setColor(0.0, 0.0, 0.0, 0.0)

    label = createLabel(text, font, fontSize, osgWidget.Color(0,0,0,1))

    box = osgWidget.Box("HBOX", osgWidget.Box.HORIZONTAL)
    box.addWidget(label)
    box.resize()
    colorBack = frame.getEmbeddedWindow().getColor()
    box.getBackground().setColor(colorBack)
    frame.getEmbeddedWindow().setWindow(box)
    box.setVisibilityMode(osgWidget.Window.VM_ENTIRE)
Пример #27
0
    return g


# Create a 1x1 quad in XZ plane
g = osg.createTexturedQuadGeometry(osg.Vec3f(0, 0, 0), osg.Vec3f(1, 0, 0),
                                   osg.Vec3f(0, 0, 1), 0, 0, 1, 1)
g.getColorArray()[0] = osg.Vec4f(1, 1, 1,
                                 0.5)  # change color to semitransparent

# Add it to a geode
geode = osg.Geode()
geode.addDrawable(g)

# Add texture
i = osgDB.readImageFile("Images/osg256.png")
t = osg.Texture2D(i)
s = geode.stateSet
s.setTextureAttributeAndModes(0, t, osg.StateAttribute.Values.ON)

# Make sure blending is active and the geode is in the transparent (depth sorted) bin
s.setRenderingHint(osg.StateSet.TRANSPARENT_BIN)
s.setMode(osg.GL_BLEND, osg.StateAttribute.ON)

# Create viewer, add some standard handlers to it and run it
viewer = osgViewer.Viewer()
viewer.setUpViewInWindow(50, 50, 1024, 768)
viewer.addEventHandler(osgGA.StateSetManipulator(geode.stateSet))
viewer.addEventHandler(osgViewer.HelpHandler())
viewer.addEventHandler(osgViewer.StatsHandler())
viewer.setSceneData(geode)
Пример #28
0
def createLightPointsDatabase():

    
    start = osgSim.LightPoint()
    end = osgSim.LightPoint()

    start._position.set(-500.0,-500.0,0.0)
    start._color.set(1.0,0.0,0.0,1.0)
    
    end._position.set(500.0,-500.0,0.0)
    end._color.set(1.0,1.0,1.0,1.0)
    
    transform = osg.MatrixTransform()
    
    transform.setDataVariance(osg.Object.STATIC)
    transform.setMatrix(osg.Matrix.scale(0.1,0.1,0.1))

    start_delta = osg.Vec3(0.0,10.0,0.0)
    end_delta = osg.Vec3(0.0,10.0,1.0)

    noStepsX = 100
    noStepsY = 100

#     osgSim.BlinkSequence* bs = osgSim.BlinkSequence()
#     bs.addPulse(1.0,osg.Vec4(1.0,0.0,0.0,1.0))
#     bs.addPulse(0.5,osg.Vec4(0.0,0.0,0.0,0.0)) # off
#     bs.addPulse(1.5,osg.Vec4(1.0,1.0,0.0,1.0))
#     bs.addPulse(0.5,osg.Vec4(0.0,0.0,0.0,0.0)) # off
#     bs.addPulse(1.0,osg.Vec4(1.0,1.0,1.0,1.0))
#     bs.addPulse(0.5,osg.Vec4(0.0,0.0,0.0,0.0)) # off
    

#    osgSim.Sector* sector = osgSim.ConeSector(osg.Vec3(0.0,0.0,1.0),osg.inDegrees(45.0),osg.inDegrees(45.0))
#    osgSim.Sector* sector = osgSim.ElevationSector(-osg.inDegrees(45.0),osg.inDegrees(45.0),osg.inDegrees(45.0))
#    osgSim.Sector* sector = osgSim.AzimSector(-osg.inDegrees(45.0),osg.inDegrees(45.0),osg.inDegrees(90.0))
#     osgSim.Sector* sector = osgSim.AzimElevationSector(osg.inDegrees(180),osg.inDegrees(90), # azim range
#                                                                 osg.inDegrees(0.0),osg.inDegrees(90.0), # elevation range
#                                                                 osg.inDegrees(5.0))

    for(int i=0i<noStepsY++i)

#         osgSim.BlinkSequence* local_bs = osgSim.BlinkSequence(*bs)
#         local_bs.setSequenceGroup(osgSim.BlinkSequence.SequenceGroup((double)i*0.1))        
#         start._blinkSequence = local_bs

#        start._sector = sector

        lpn = osgSim.LightPointNode()

        #
        set = lpn.getOrCreateStateSet()

        if usePointSprites :
            lpn.setPointSprite()

            # Set point sprite texture in LightPointNode StateSet.
            tex = osg.Texture2D()
            tex.setImage(osgDB.readImageFile("Images/particle.rgb"))
            set.setTextureAttributeAndModes(0, tex, osg.StateAttribute.ON)

        #set.setMode(GL_BLEND, osg.StateAttribute.ON)
        #osg.BlendFunc *fn = osg.BlendFunc()
        #fn.setFunction(osg.BlendFunc.SRC_ALPHA, osg.BlendFunc.DST_ALPHA)
        #set.setAttributeAndModes(fn, osg.StateAttribute.ON)
        #

        addToLightPointNode(*lpn,start,end,noStepsX)
        
        start._position += start_delta
        end._position += end_delta
        
        transform.addChild(lpn)    
Пример #29
0
root.addChild(pyramidGeode)

# Now for adding a texture. Here we'll declare a texture instance and set 
# its data variance as 'DYNAMIC'. (If we don't declare the texture as dynamic, 
# some of the osg's optimization routines could remove it.) The texture class 
# encapsulates OpenGL texture modes (wrap, filiter, etc.) as well as an 
# osg.Image. The code below shows how to read an osg.Image instance from a 
# file and associate this image with a texture.

KLN89FaceTexture = osg.Texture2D()

# protect from being optimized away as static state:
KLN89FaceTexture.setDataVariance(osg.Object.DYNAMIC) 

# load an image by reading a file: 
klnFace = osgDB.readImageFile("KLN89FaceB.tga")
if klnFace is None:
    print " Couldn't find texture, quitting."
    sys.exit(-1)

# Assign the texture to the image we read from file: 
KLN89FaceTexture.setImage(klnFace)

# Textures can be associated with rendering StateSets. The next step is to 
# create a StateSet, associate and enable our texture with this state set and 
# assign the StateSet to our geometry.

# Create a StateSet with default settings: 
stateOne = osg.StateSet()

# Assign texture unit 0 of our StateSet to the texture 
Пример #30
0
def createModel():

    

    # create the root node which will hold the model.
    root = osg.Group()

    # add the drawable into a single goede to be shared...
    center = osg.Billboard()
    center.setMode(osg.Billboard.POINT_ROT_EYE)
    center.addDrawable(
        createSquare(osg.Vec3(-0.5,0.0,-0.5),osg.Vec3(1.0,0.0,0.0),osg.Vec3(0.0,0.0,1.0),osgDB.readImageFile("Images/reflect.rgb")),
        osg.Vec3(0.0,0.0,0.0))

    x_arrow = osg.Billboard()
    x_arrow.setMode(osg.Billboard.AXIAL_ROT)
    x_arrow.setAxis(osg.Vec3(1.0,0.0,0.0))
    x_arrow.setNormal(osg.Vec3(0.0,-1.0,0.0))
    x_arrow.addDrawable(
       createSquare(osg.Vec3(-0.5,0.0,-0.5),osg.Vec3(1.0,0.0,0.0),osg.Vec3(0.0,0.0,1.0),osgDB.readImageFile("Cubemap_axis/posx.png")),
       osg.Vec3(5.0,0.0,0.0))

    y_arrow = osg.Billboard()
    y_arrow.setMode(osg.Billboard.AXIAL_ROT)
    y_arrow.setAxis(osg.Vec3(0.0,1.0,0.0))
    y_arrow.setNormal(osg.Vec3(1.0,0.0,0.0))
    y_arrow.addDrawable(
        createSquare(osg.Vec3(0.0,-0.5,-0.5),osg.Vec3(0.0,1.0,0.0),osg.Vec3(0.0,0.0,1.0),osgDB.readImageFile("Cubemap_axis/posy.png")),
        osg.Vec3(0.0,5.0,0.0))

    z_arrow = osg.Billboard()
    z_arrow.setMode(osg.Billboard.AXIAL_ROT)
    z_arrow.setAxis(osg.Vec3(0.0,0.0,1.0))
    z_arrow.setNormal(osg.Vec3(0.0,-1.0,0.0))
    z_arrow.addDrawable(
        createSquare(osg.Vec3(-0.5,0.0,-0.5),osg.Vec3(1.0,0.0,0.0),osg.Vec3(0.0,0.0,1.0),osgDB.readImageFile("Cubemap_axis/posz.png")),
        osg.Vec3(0.0,0.0,5.0))



    axis = osg.Geode()
    axis.addDrawable(createAxis(osg.Vec3(0.0,0.0,0.0),osg.Vec3(5.0,0.0,0.0),osg.Vec3(0.0,5.0,0.0),osg.Vec3(0.0,0.0,5.0)))


    root.addChild(center)
    root.addChild(x_arrow)
    root.addChild(y_arrow)
    root.addChild(z_arrow)
    root.addChild(axis)

    return root
def main(argv):

    
    arguments = osg.ArgumentParser(argv)

    # construct the viewer.
    viewer = osgViewer.CompositeViewer(arguments)
    
    if arguments.argc()<=1 :
        print "Please supply an image filename on the commnand line."
        return 1
    
    filename = arguments[1]
    image = osgDB.readImageFile(filename)
    
    if  not image :
        print "Error: unable able to read image from ", filename
        return 1

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


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

    traits = osg.GraphicsContext.Traits()
    traits.x = 0
    traits.y = 0
    traits.width = width
    traits.height = height
    traits.windowDecoration = False
    traits.doubleBuffer = True
    
    gc = osg.GraphicsContext.createGraphicsContext(traits)
    if  not gc :
        print "Error: GraphicsWindow has not been created successfully."

    gc.setClearColor(osg.Vec4(0.0,0.0,0.0,1.0))
    gc.setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    trackball = osgGA.TrackballManipulator()
    
    typedef std.vector< osg.Node > Models
    
    models = Models()
    models.push_back(creatQuad("no compression", image, osg.Texture.USE_IMAGE_DATA_FORMAT, osg.Texture.LINEAR))
    models.push_back(creatQuad("ARB compression", image, osg.Texture.USE_ARB_COMPRESSION, osg.Texture.LINEAR))
    models.push_back(creatQuad("DXT1 compression", image, osg.Texture.USE_S3TC_DXT1_COMPRESSION, osg.Texture.LINEAR))
    models.push_back(creatQuad("DXT3 compression", image, osg.Texture.USE_S3TC_DXT3_COMPRESSION, osg.Texture.LINEAR))
    models.push_back(creatQuad("DXT5 compression", image, osg.Texture.USE_S3TC_DXT5_COMPRESSION, osg.Texture.LINEAR))
    
    numX = 1
    numY = 1

    # compute the number of views up and across that are need
        aspectRatio = float(width)/float(height)
        multiplier = sqrtf(float(models.size())/aspectRatio)
        multiplier_x = multiplier*aspectRatio
        multiplier_y = multiplier


        if multiplier_x/ceilf(multiplier_x) : > (multiplier_y/ceilf(multiplier_y)) :
            numX = int(ceilf(multiplier_x))
            numY = int(ceilf(float(models.size())/float(numX)))
    char fragmentShaderSource[] =
        "varying vec2 texCoord\n"
        "uniform sampler2D baseTexture\n"
        "void main(void)\n"
        "\n"
        "    gl_FragColor = texture2D(baseTexture, texCoord) \n"
        "\n"

    program = osg.Program()
    program.addShader(osg.Shader(osg.Shader.VERTEX, vertexShaderSource))
    program.addShader(osg.Shader(osg.Shader.FRAGMENT, fragmentShaderSource))

    stateset = geometry.getOrCreateStateSet()
    stateset.setAttribute(program)

    image = osgDB.readImageFile("Images/lz.rgb")
    texture = osg.Texture2D(image)
    texture.setFilter(osg.Texture.MIN_FILTER, osg.Texture.LINEAR)
    texture.setFilter(osg.Texture.MAG_FILTER, osg.Texture.LINEAR)
    stateset.setTextureAttribute(0, texture)

    baseTextureSampler = osg.Uniform("baseTexture",0)
    stateset.addUniform(baseTextureSampler)

    return group

int main(int argc, char *argv[])
    # use an ArgumentParser object to manage the program arguments.
    arguments = osg.ArgumentParser(argv)

    # construct the viewer.
Пример #33
0
    pos = osg.Vec3(0.0,0.0,0.0)
    topleft = pos
    bottomright = pos

    xyPlane = fullscreen
    
    useAudioSink = False
    while arguments.read("--audio") :  useAudioSink = True 
    
#if USE_SDL
    numAudioStreamsEnabled = 0
#endif

    for(int i=1i<arguments.argc()++i)
        if arguments.isString(i) :
            image = osgDB.readImageFile(arguments[i])
            imagestream = dynamic_cast<osg.ImageStream*>(image)
            if imagestream : 
                audioStreams = imagestream.getAudioStreams()
                if useAudioSink  and   not audioStreams.empty() :
                    audioStream = audioStreams[0]
                    osg.notify(osg.NOTICE), "AudioStream read [", audioStream.getName(), "]"
#if USE_SDL
                    if numAudioStreamsEnabled==0 :
                        audioStream.setAudioSink(SDLAudioSink(audioStream))
                        
                        ++numAudioStreamsEnabled
#endif


                imagestream.play()
Пример #34
0
Character.Character():
    _positionRatio(0.5),
    _numLives(3),
    _numCatches(0)


void Character.setCharacter( str filename,  str name,  osg.Vec3 origin,  osg.Vec3 width,  osg.Vec3 catchPos, float positionRatio)
    _origin = origin
    _width = width
    _positionRatio = positionRatio
    _numLives = 3
    _numCatches = 0

    _characterSize = _width.length()*0.2

    image = osgDB.readImageFile(filename)
    if image :
        pos = osg.Vec3(-0.5*_characterSize,0.0,0.0)
        width = osg.Vec3(_characterSize*((float)image.s())/(float)(image.t()),0.0,0.0)
        height = osg.Vec3(0.0,0.0,_characterSize)

        geometry = osg.createTexturedQuadGeometry(pos,width,height)
        stateset = geometry.getOrCreateStateSet()
        stateset.setTextureAttributeAndModes(0,osg.Texture2D(image),osg.StateAttribute.ON)
        stateset.setMode(GL_BLEND,osg.StateAttribute.ON)
        stateset.setRenderingHint(osg.StateSet.TRANSPARENT_BIN)

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

        _character = osg.PositionAttitudeTransform()
Пример #35
0
def main(argv):

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

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

    useTextureRectangle = True
    useShader = False

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

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

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

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

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


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

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

    geode = osg.Geode()

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

    if useShader :
        #useTextureRectangle = False

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

        static  char *shaderSourceTexture2D = 
            "uniform vec4 cutoff_color\n"
            "uniform sampler2D movie_texture\n"
            "void main(void)\n"
            "\n"
            "    vec4 texture_color = texture2D(movie_texture, gl_TexCoord[0].st) \n"
            "    if all(lessThanEqual(texture_color,cutoff_color)) : discard \n"
            "    gl_FragColor = texture_color\n"
            "\n"
    # Add primitive set
    g.addPrimitiveSet(osg.DrawArrays(osg.PrimitiveSet.QUADS, 0, 4))

    return g

# Create a 1x1 quad in XZ plane
g = osg.createTexturedQuadGeometry(osg.Vec3f(0,0,0), osg.Vec3f(1,0,0), osg.Vec3f(0,0,1), 0, 0, 1, 1)
g.getColorArray()[0] = osg.Vec4f(1,1,1,0.5)  # change color to semitransparent

# Add it to a geode
geode = osg.Geode()
geode.addDrawable(g)

# Add texture
i = osgDB.readImageFile("Images/osg256.png")
t = osg.Texture2D(i)
s = geode.stateSet
s.setTextureAttributeAndModes(0, t, osg.StateAttribute.Values.ON)

# Make sure blending is active and the geode is in the transparent (depth sorted) bin
s.setRenderingHint(osg.StateSet.TRANSPARENT_BIN)
s.setMode(osg.GL_BLEND, osg.StateAttribute.ON)

# Create viewer, add some standard handlers to it and run it
viewer = osgViewer.Viewer()
viewer.setUpViewInWindow(50, 50, 1024, 768);
viewer.addEventHandler(osgGA.StateSetManipulator(geode.stateSet))
viewer.addEventHandler(osgViewer.HelpHandler())
viewer.addEventHandler(osgViewer.StatsHandler())
viewer.setSceneData(geode)
Пример #37
0
        MarbleProgram.setName( "marble" )
        _programList.push_back( MarbleProgram )
        MarbleVertObj = osg.Shader( osg.Shader.VERTEX )
        MarbleFragObj = osg.Shader( osg.Shader.FRAGMENT )
        MarbleProgram.addShader( MarbleFragObj )
        MarbleProgram.addShader( MarbleVertObj )
        ss.setAttributeAndModes(MarbleProgram, osg.StateAttribute.ON)

        ss.addUniform( osg.Uniform("NoiseTex", TEXUNIT_NOISE) )
        ss.addUniform( osg.Uniform("SineTex", TEXUNIT_SINE) )

#ifdef INTERNAL_3DLABS #[
    # regular GL 1.x texturing for comparison.
    ss = ModelInstance()
    tex0 = osg.Texture2D()
    tex0.setImage( osgDB.readImageFile( "images/3dl-ge100.png" ) )
    ss.setTextureAttributeAndModes(0, tex0, osg.StateAttribute.ON)
#endif #]

    reloadShaderSource()

#ifdef INTERNAL_3DLABS #[
    # add logo overlays
    rootNode.addChild( osgDB.readNodeFile( "3dl_ogl.logo" ) )
#endif #]

    return rootNode

#####################################/
#####################################/
def main():
   viewer = osgViewer.Viewer()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   return 0
Пример #39
0
    moonPositioned = osg.MatrixTransform()
    moonPositioned.setMatrix(osg.Matrix.translate(osg.Vec3( 0.0, _RorbitMoon, 0.0 ) )*
                                 osg.Matrix.scale(1.0, 1.0, 1.0)*
                                 osg.Matrix.rotate(osg.inDegrees( tilt ),0.0,0.0,1.0))

    return moonPositioned
# end SolarSystem.createTranslationAndTilt


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

    sSpaceSphere = osg.ShapeDrawable( spaceSphere )

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

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

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

    geodeSpace.addDrawable( sSpaceSphere )

    return( geodeSpace )

# end SolarSystem.createSpace