def createMovingModel(center, radius):
    animationLength = 10.0
    animationPath = createAnimationPath(center,radius,animationLength)
    model = osg.Group()
    glider = osgDB.readNodeFile("glider.osgt")
    if glider :
        bs = glider.getBound()
        size = radius/bs.radius()*0.3
        positioned = osg.MatrixTransform()
        positioned.setDataVariance(osg.Object.STATIC)
        positioned.setMatrix(osg.Matrix.translate(-bs.center())*
                                     osg.Matrix.scale(size,size,size)*
                                     osg.Matrix.rotate(osg.inDegrees(-90.0),0.0,0.0,1.0))
        positioned.addChild(glider)
        xform = osg.PositionAttitudeTransform()
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,1.0))
        xform.addChild(positioned)
        model.addChild(xform)
    cessna = osgDB.readNodeFile("cessna.osgt")
    if cessna :
        bs = cessna.getBound()
        size = radius/bs.radius()*0.3
        positioned = osg.MatrixTransform()
        positioned.setDataVariance(osg.Object.STATIC)
        positioned.setMatrix(osg.Matrix.translate(-bs.center())*
                                     osg.Matrix.scale(size,size,size)*
                                     osg.Matrix.rotate(osg.inDegrees(180.0),0.0,0.0,1.0))
        positioned.addChild(cessna)
        xform = osg.MatrixTransform()
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,2.0))
        xform.addChild(positioned)
        model.addChild(xform)
    return model
Beispiel #2
0
class CatchableObject (osg.Referenced) :
        CatchableObject()

        setObject = void( str filename,  str name,  osg.Vec3 center, float size,  osg.Vec3 direction)

        anyInside = bool( osg.Vec3 lower_left,  osg.Vec3 top_right)

        centerInside = bool( osg.Vec3 center, float radius)
        
        explode = void()
        
        def dangerous():
        
             return _dangerous 

        def stop():

             _stopped = True 
        
        def stopped():
        
             return _stopped 
        
        def setTimeToRemove(time):
        
             _timeToRemove=time 
        
        def getTimeToRemove():
        
             return _timeToRemove 
        
        def needToRemove(time):
        
             return  _timeToRemove>=0.0  and  time>_timeToRemove 
        
        _object = osg.PositionAttitudeTransform()
        _velocity = osg.Vec3()
        _mass = float()
        _radius = float()

        _stopped = bool()
        _dangerous = bool()

        _timeToRemove = double()

        static void setUpCatchablesMap( FileList fileList)
    
        # update position and velocity
        update = void(double dt)

        #/ Set the viscosity of the fluid.
        inline void setFluidViscosity(float v)
            _viscosity = v
            _viscosityCoefficient = 6 * osg.PI * _viscosity
def getPATransformation(object, position, scale, pivot):


    
    tmpTrans = osg.PositionAttitudeTransform()
    tmpTrans.addChild( object )
    
    tmpTrans.setPosition( position )
    tmpTrans.setScale( scale )
    tmpTrans.setPivotPoint( pivot )
    
    return tmpTrans
Beispiel #4
0
class Character (osg.Referenced) :
    Character()
    
    setCharacter = void( str filename,  str name,  osg.Vec3 orgin,  osg.Vec3 width,  osg.Vec3 catchPos, float positionRatio)
    
    setLives = void( str filename,  osg.Vec3 orgin,  osg.Vec3 delta, unsigned int numLives)
    
    setCatches = void( str filename,  osg.Vec3 orgin,  osg.Vec3 delta, unsigned int numLives)

    moveLeft = void()
    moveRight = void()
    moveTo = void(float positionRatio)

    reset = void()

    resetCatches = void()

    addCatch = bool()
    
    looseLife = bool()

    def getCurrentCenterOfBasket():

         return _character.getPosition()+_centerBasket 
    def getCurrentRadiusOfBasket():
         return _radiusBasket 

    def getLowerLeft():

         return _character.getPosition() 
    def getUpperRight():
         return _character.getPosition() 

    _origin = osg.Vec3()
    _width = osg.Vec3()

    _positionRatio = float()
    _character = osg.PositionAttitudeTransform()

    _numLives = unsigned int()
    _livesSwitch = osg.Switch()

    _numCatches = unsigned int()
    _catchSwitch = osg.Switch()
    
    _objectsGroup = osg.Group()
    
    _centerBasket = osg.Vec3()
    _radiusBasket = float()
Beispiel #5
0
def createScene():

    
    # Create the Earth, in blue
    earth_sd = osg.ShapeDrawable()
    earth_sphere = osg.Sphere()
    earth_sphere.setName("EarthSphere")
    earth_sphere.setRadius(r_earth)
    earth_sd.setShape(earth_sphere)
    earth_sd.setColor(osg.Vec4(0, 0, 1.0, 1.0))

    earth_geode = osg.Geode()
    earth_geode.setName("EarthGeode")
    earth_geode.addDrawable(earth_sd)

    # Create the Sun, in yellow
    sun_sd = osg.ShapeDrawable()
    sun_sphere = osg.Sphere()
    sun_sphere.setName("SunSphere")
    sun_sphere.setRadius(r_sun)
    sun_sd.setShape(sun_sphere)
    sun_sd.setColor(osg.Vec4(1.0, 0.0, 0.0, 1.0))

    sun_geode = osg.Geode()
    sun_geode.setName("SunGeode")
    sun_geode.addDrawable(sun_sd)

    # Move the sun behind the earth
    pat = osg.PositionAttitudeTransform()
    pat.setPosition(osg.Vec3d(0.0, AU, 0.0))
    pat.addChild(sun_geode)

    unitCircle = osg.Geometry()
      colours = osg.Vec4Array(1)
      (*colours)[0] = osg.Vec4d(1.0,1.0,1.0,1.0)
      unitCircle.setColorArray(colours, osg.Array.BIND_OVERALL)
      n_points = 1024
      coords = osg.Vec3Array(n_points)
      dx = 2.0*osg.PI/n_points
      double s,c
      for (unsigned int j=0 j<n_points ++j) 
Beispiel #6
0
def main(argv):

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

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

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

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

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

    # generate the 3D heatmap surface to display
    hm = Heatmap(30, 30, 10, 30, 30, 1.0, 0.25)
    float data[30][30]
    for (int x=0 x < 30 ++x)
        for (int y=0 y < 30 ++y)
            data[y][x] = (double)rand() / RAND_MAX
Beispiel #7
0
def createReflector():

    
  pat = osg.PositionAttitudeTransform()
  pat.setPosition(osg.Vec3(0.0,0.0,0.0))
  pat.setAttitude(osg.Quat(osg.inDegrees(0.0),osg.Vec3(0.0,0.0,1.0)))
  
  geode_1 = Geode()
  pat.addChild(geode_1)

  radius = 0.8
  hints = TessellationHints()
  hints.setDetailRatio(2.0)
  shape = ShapeDrawable(Sphere(Vec3(0.0, 0.0, 0.0), radius * 1.5), hints)
  shape.setColor(Vec4(0.8, 0.8, 0.8, 1.0))
  geode_1.addDrawable(shape)
  
  nodeList = osg.NodePath()
  nodeList.push_back(pat)
  nodeList.push_back(geode_1)
  
  return nodeList
def main(argv):

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

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

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

    # create scene
    root = osg.Group()

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

    outline.setWidth(8)
    outline.setColor(osg.Vec4(1, 1, 0, 1))
    outline.addChild(outlineModel)

    if testOcclusion:
        # load occluder
        occludedModelFilename = "cow.osgt"
        occludedModel = osgDB.readNodeFile(occludedModelFilename)
        if not occludedModel:
            osg.notify(
                osg.FATAL
            ), "Unable to load model '", occludedModelFilename, "'\n"
            return -1

        # occluder offset
        bsphere = outlineModel.getBound()
        occluderOffset = osg.Vec3(0, 1, 0) * bsphere.radius() * 1.2

        # occluder behind outlined model
        modelTransform0 = osg.PositionAttitudeTransform()
        modelTransform0.setPosition(bsphere.center() + occluderOffset)
        modelTransform0.addChild(occludedModel)
        root.addChild(modelTransform0)

        # occluder in front of outlined model
        modelTransform1 = osg.PositionAttitudeTransform()
        modelTransform1.setPosition(bsphere.center() - occluderOffset)
        modelTransform1.addChild(occludedModel)
        root.addChild(modelTransform1)

    # must have stencil buffer...
    osg.DisplaySettings.instance().setMinimumNumStencilBits(1)

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

    # must clear stencil buffer...
    clearMask = viewer.getCamera().getClearMask()
    viewer.getCamera().setClearMask(clearMask | GL_STENCIL_BUFFER_BIT)
    viewer.getCamera().setClearStencil(0)

    return viewer.run()
static osg.Geode*
CreateModel()
    geode = osg.Geode()
    geode.addDrawable(osg.ShapeDrawable(osg.Sphere(osg.Vec3(0.0,0.0,0.0),1.0)))
    geode.addDrawable(osg.ShapeDrawable(osg.Cone(osg.Vec3(2.2,0.0,-0.4),0.9,1.8)))
    geode.addDrawable(osg.ShapeDrawable(osg.Cylinder(osg.Vec3(4.4,0.0,0.0),1.0,1.4)))
    return geode

# Add a reference to the masterModel at the specified translation, and
# return its StateSet so we can easily attach StateAttributes.
static osg.StateSet*
ModelInstance()
    static float zvalue = 0.0
    static osg.Node* masterModel = CreateModel()

    xform = osg.PositionAttitudeTransform()
    xform.setPosition(osg.Vec3( 0.0, -1.0, zvalue ))
    zvalue = zvalue + 2.2
    xform.addChild(masterModel)
    rootNode.addChild(xform)
    return xform.getOrCreateStateSet()

# load source from a file.
static void
LoadShaderSource( osg.Shader* shader,  str fileName )
    fqFileName = osgDB.findDataFile(fileName)
    if  fqFileName.length()  not = 0  :
        shader.loadShaderSourceFromFile( fqFileName.c_str() )
    else:
        osg.notify(osg.WARN), "File \"", fileName, "\" not found."
Beispiel #10
0
    # display a solid version of the dump truck
    solidModel = osg.PositionAttitudeTransform()
    solidModel.setPosition(osg.Vec3f(7.0, -2.0, 7.0))
    solidModel.addChild(dt)

    # generate the 3D heatmap surface to display
    hm = Heatmap(30, 30, 10, 30, 30, 1.0, 0.25)
    float data[30][30]
    for (int x=0 x < 30 ++x)
        for (int y=0 y < 30 ++y)
            data[y][x] = (double)rand() / RAND_MAX
    hm.setData((float*)data, 10.0, 1.0, 0.25)

    # add a transparent version of the truck to the scene also
    transparentTruck = osg.PositionAttitudeTransform()
    transparentTruck.setPosition(osg.Vec3f(7.0, -25.0, 7.0))

    # set the states of the truck so that it actually appears transparently and nicely lit.
    state = transparentTruck.getOrCreateStateSet()
    state.setMode(GL_BLEND, osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE)
    state.setAttribute(osg.BlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA), osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE)
    material = osg.Material()
    material.setAmbient(osg.Material.FRONT_AND_BACK,osg.Vec4(0.2,0.2,0.2,0.3))
    material.setDiffuse(osg.Material.FRONT_AND_BACK,osg.Vec4(0.8,0.8,0.8,0.3))
    state.setAttribute(material,osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE)
    lm = osg.LightModel()
    lm.setTwoSided(True)
    state.setAttribute(lm, osg.StateAttribute.ON | osg.StateAttribute.OVERRIDE)
    (transparentTruck).addChild(dt)
Beispiel #11
0
    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()
        _character.setName(name)
        _character.addChild(geode)
        
        moveTo(positionRatio)

        _centerBasket = width*catchPos.x() + height*catchPos.y() + pos
        _radiusBasket = width.length()*catchPos.z()

    

void Character.setLives( str filename,  osg.Vec3 origin,  osg.Vec3 delta, unsigned int numLives)
    characterSize = delta.length()

    _numLives = numLives
    _livesSwitch = osg.Switch()
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
Beispiel #13
0
def main(argv):


    
    arguments = osg.ArgumentParser(argv)

    viewer = osgViewer.Viewer(arguments)

    fontFile = str("arial.ttf")
    while arguments.read("-f",fontFile) : 

    font = osgText.readFontFile(fontFile)
    if  not font : return 1
    OSG_NOTICE, "Read font ", fontFile, " font=", font

    word = str("This is a test.")()
    while arguments.read("-w",word) : 

    style = osgText.Style()

    thickness = 0.1
    while arguments.read("--thickness",thickness) : 
    style.setThicknessRatio(thickness)

    # set up any bevel if required
    r = float()
    bevel = osgText.Bevel()
    while arguments.read("--rounded",r) :  bevel = osgText.Bevel() bevel.roundedBevel2(r) 
    while arguments.read("--rounded") :  bevel = osgText.Bevel() bevel.roundedBevel2(0.25) 
    while arguments.read("--flat",r) :  bevel = osgText.Bevel() bevel.flatBevel(r) 
    while arguments.read("--flat") :  bevel = osgText.Bevel() bevel.flatBevel(0.25) 
    while arguments.read("--bevel-thickness",r) :  if bevel.valid() : bevel.setBevelThickness(r) 

    style.setBevel(bevel)

    # set up outline.
    while arguments.read("--outline",r) :  style.setOutlineRatio(r) 


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

#if 1
    group = osg.Group()

    characterSize = 1.0
    while arguments.read("--size",characterSize) : 

    if arguments.read("--2d") :
        text2D = osgText.Text()
        text2D.setFont(font)
        text2D.setCharacterSize(characterSize)
        text2D.setFontResolution(256,256)
        text2D.setDrawMode(osgText.Text.TEXT | osgText.Text.BOUNDINGBOX)
        text2D.setAxisAlignment(osgText.Text.XZ_PLANE)
        text2D.setText(word)
        geode = osg.Geode()
        geode.addDrawable(text2D)
        group.addChild(geode)

    if arguments.read("--TextNode") :
        # experimental text node
        text = osgText.TextNode()
        text.setFont(font)
        text.setStyle(style)
        text.setTextTechnique(osgText.TextTechnique)()
        text.setText(word)
        text.update()

        group.addChild(text)
    elif  not arguments.read("--no-3d") :
        text3D = osgText.Text3D()
        text3D.setFont(font)
        text3D.setStyle(style)
        text3D.setCharacterSize(characterSize)
        text3D.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
        text3D.setAxisAlignment(osgText.Text3D.XZ_PLANE)
        text3D.setText(word)

        geode = osg.Geode()
        geode.addDrawable(text3D)
        group.addChild(geode)

        color = osg.Vec4(1.0, 1.0, 1.0, 1.0)
        while arguments.read("--color",color.r(),color.g(),color.b(),color.a()) :
            OSG_NOTICE, "--color ", color
            text3D.setColor(color)

        imageFilename = str()
        while arguments.read("--image",imageFilename) :
            OSG_NOTICE, "--image ", imageFilename
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                OSG_NOTICE, "  loaded image ", imageFilename
                stateset = text3D.getOrCreateStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        while arguments.read("--wall-color",color.r(),color.g(),color.b(),color.a()) :
            stateset = text3D.getOrCreateWallStateSet()
            material = osg.Material()
            material.setDiffuse(osg.Material.FRONT_AND_BACK, color)
            stateset.setAttribute(material)

        while arguments.read("--wall-image",imageFilename) :
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                stateset = text3D.getOrCreateWallStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        while arguments.read("--back-color",color.r(),color.g(),color.b(),color.a()) :
            stateset = text3D.getOrCreateBackStateSet()
            material = osg.Material()
            material.setDiffuse(osg.Material.FRONT_AND_BACK, color)
            stateset.setAttribute(material)

        while arguments.read("--back-image",imageFilename) :
            image = osgDB.readImageFile(imageFilename)
            if image.valid() :
                stateset = text3D.getOrCreateBackStateSet()
                stateset.setTextureAttributeAndModes(0, osg.Texture2D(image), osg.StateAttribute.ON)

        if arguments.read("--size-quad") :
            geode.addDrawable( osg.createTexturedQuadGeometry(osg.Vec3(0.0,characterSize*thickness,0.0),osg.Vec3(characterSize,0.0,0.0),osg.Vec3(0.0,0.0,characterSize), 0.0, 0.0, 1.0, 1.0) )

    
    viewer.setSceneData(group)

#endif

    return viewer.run()

# Translated from file 'osgtext3D_orig.cpp'

# OpenSceneGraph example, osgtext.
#*
#*  Permission is hereby granted, free of charge, to any person obtaining a copy
#*  of this software and associated documentation files (the "Software"), to deal
#*  in the Software without restriction, including without limitation the rights
#*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#*  copies of the Software, and to permit persons to whom the Software is
#*  furnished to do so, subject to the following conditions:
#*
#*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#*  THE SOFTWARE.
#


#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>

#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgText/Text3D>

#include <iostream>
#include <sstream>



# create text which sits in 3D space such as would be inserted into a normal model
def create3DText(center, radius):
    

    geode = osg.Geode()

####################################################
#    
# Examples of how to set up axis/orientation alignments
#

    characterSize = radius*0.2
    characterDepth = characterSize*0.2
    
    pos = osg.Vec3(center.x()-radius*.5,center.y()-radius*.5,center.z()-radius*.5)

    text1 = osgText.Text3D()
    text1.setFont("fonts/arial.ttf")
    text1.setCharacterSize(characterSize)
    text1.setCharacterDepth(characterDepth)
    text1.setPosition(pos)
    text1.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text1.setAxisAlignment(osgText.Text3D.XY_PLANE)
    text1.setText("XY_PLANE")
    geode.addDrawable(text1)

    text2 = osgText.Text3D()
    text2.setFont("fonts/times.ttf")
    text2.setCharacterSize(characterSize)
    text2.setCharacterDepth(characterDepth)
    text2.setPosition(pos)
    text2.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text2.setAxisAlignment(osgText.Text3D.YZ_PLANE)
    text2.setText("YZ_PLANE")
    geode.addDrawable(text2)

    text3 = osgText.Text3D()
    text3.setFont("fonts/dirtydoz.ttf")
    text3.setCharacterSize(characterSize)
    text3.setCharacterDepth(characterDepth)
    text3.setPosition(pos)
    text3.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text3.setAxisAlignment(osgText.Text3D.XZ_PLANE)
    text3.setText("XZ_PLANE")
    geode.addDrawable(text3)

    style = osgText.Style()
    bevel = osgText.Bevel()
    bevel.roundedBevel2(0.25)
    style.setBevel(bevel)
    style.setWidthRatio(0.4)

    text7 = osgText.Text3D()
    text7.setFont("fonts/times.ttf")
    text7.setStyle(style)
    text7.setCharacterSize(characterSize)
    text7.setCharacterDepth(characterSize*0.2)
    text7.setPosition(center - osg.Vec3(0.0, 0.0, 0.6))
    text7.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text7.setAxisAlignment(osgText.Text3D.SCREEN)
    text7.setCharacterSizeMode(osgText.Text3D.OBJECT_COORDS)
    text7.setText("CharacterSizeMode OBJECT_COORDS (default)")
    geode.addDrawable(text7)

    shape = osg.ShapeDrawable(osg.Sphere(center,characterSize*0.2))
    shape.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.ON)
    geode.addDrawable(shape)

    rootNode = osg.Group()
    rootNode.addChild(geode)

    front = osg.Material()
    front.setAlpha(osg.Material.FRONT_AND_BACK,1)
    front.setAmbient(osg.Material.FRONT_AND_BACK,osg.Vec4(0.2,0.2,0.2,1.0))
    front.setDiffuse(osg.Material.FRONT_AND_BACK,osg.Vec4(.0,.0,1.0,1.0))
    rootNode.getOrCreateStateSet().setAttributeAndModes(front)
    
    
    return rootNode    

int main_orig(int, char**)
    viewer = osgViewer.Viewer()

    center = osg.Vec3(0.0,0.0,0.0)
    radius = 1.0
    
    root = osg.Group()
    root.addChild(create3DText(center, radius))

    viewer.setSceneData(root)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    viewer.addEventHandler(osgViewer.ThreadingHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()
    viewer.addEventHandler(osgViewer.StatsHandler)()


    viewer.run()
    
    return 0



# Translated from file 'osgtext3D_test.cpp'


#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgDB/ReadFile>

#include <osgGA/TrackballManipulator>
#include <osgGA/StateSetManipulator>

#include <osg/Geode>
#include <osg/Geometry>
#include <osg/Material>
#include <osg/Shape>
#include <osg/ShapeDrawable>
#include <osgText/Text3D>

#include <iostream>
#include <sstream>



def test_create3DText(center, radius):



    

    geode = osg.Geode()

    characterSize = radius*0.2
    characterDepth = characterSize*0.2
    
    pos = osg.Vec3(center.x()-radius*.5,center.y()-radius*.5,center.z()-radius*.5)
#define SHOW_INTESECTION_CEASH
#ifdef SHOW_INTESECTION_CEASH
    text3 = osgText.Text3D()
    text3.setFont("fonts/dirtydoz.ttf")
    text3.setCharacterSize(characterSize)
    text3.setCharacterDepth(characterDepth)
    text3.setPosition(pos)
    text3.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text3.setAxisAlignment(osgText.Text3D.XZ_PLANE)
    text3.setText("CRAS H") #intersection crash
    geode.addDrawable(text3)
#else:
    text7 = osgText.Text3D()
    text7.setFont("fonts/times.ttf")
    text7.setCharacterSize(characterSize)
    text7.setCharacterDepth(characterSize*2.2)
    text7.setPosition(center - osg.Vec3(0.0, 0.0, 0.6))
    text7.setDrawMode(osgText.Text3D.TEXT | osgText.Text3D.BOUNDINGBOX)
    text7.setAxisAlignment(osgText.Text3D.SCREEN)
    text7.setCharacterSizeMode(osgText.Text3D.OBJECT_COORDS)
    text7.setText("ABCDE") #wrong intersection
    geode.addDrawable(text7)
#endif

    shape = osg.ShapeDrawable(osg.Sphere(center,characterSize*0.2))
    shape.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.ON)
    geode.addDrawable(shape)

    rootNode = osg.Group()
    rootNode.addChild(geode)

#define SHOW_WRONG_NORMAL
#ifdef SHOW_WRONG_NORMAL
    front = osg.Material() #
    front.setAlpha(osg.Material.FRONT_AND_BACK,1)
    front.setAmbient(osg.Material.FRONT_AND_BACK,osg.Vec4(0.2,0.2,0.2,1.0))
    front.setDiffuse(osg.Material.FRONT_AND_BACK,osg.Vec4(.0,.0,1.0,1.0))
    rootNode.getOrCreateStateSet().setAttributeAndModes(front)
#else:
    stateset = osg.StateSet() #Show wireframe
    polymode = osg.PolygonMode()
    polymode.setMode(osg.PolygonMode.FRONT_AND_BACK,osg.PolygonMode.LINE)
    stateset.setAttributeAndModes(polymode,osg.StateAttribute.OVERRIDE|osg.StateAttribute.ON)
    rootNode.setStateSet(stateset)
#endif
    
    
    return rootNode    

#####################################
#include <osg/PositionAttitudeTransform>
#include <osg/ShapeDrawable>
class CInputHandler (osgGA.GUIEventHandler) :
  CInputHandler( osg.PositionAttitudeTransform* pPatSphere )
    m_rPatSphere = pPatSphere
  def handle(ea, aa, pObject, pNodeVisitor):
      
    pViewer = dynamic_cast<osgViewer.Viewer*>(aa)
    if   not pViewer  :
      return False

    if  ea.getEventType()==osgGA.GUIEventAdapter.PUSH  :
      cams = osgViewer.ViewerBase.Cameras()
      pViewer.getCameras( cams )

      x = ea.getXnormalized()
      y = ea.getYnormalized()

      picker = osgUtil.LineSegmentIntersector( osgUtil.Intersector.PROJECTION, x, y )
      iv = osgUtil.IntersectionVisitor( picker )
      cams[0].accept( iv )

      if  picker.containsIntersections()  :
        intersection = picker.getFirstIntersection()
        v = intersection.getWorldIntersectPoint()
        m_rPatSphere.setPosition( v )

      return True # return True, event handled

    return False
  m_rPatSphere = osg.PositionAttitudeTransform()

#####################################
int main_test(int, char**)
    viewer = osgViewer.Viewer()
    viewer.setUpViewInWindow(99,99,666,666, 0)
    rPat = osg.PositionAttitudeTransform()
    # add the handler to the viewer
    viewer.addEventHandler( CInputHandler(rPat) )
    # create a group to contain our scene and sphere
    pGroup = osg.Group()
    # create sphere
    pGeodeSphere = osg.Geode()
    pGeodeSphere.addDrawable( osg.ShapeDrawable( osg.Sphere(osg.Vec3(0.0,0.0,0.0),0.01) ) )
    rPat.addChild( pGeodeSphere )
    pGroup.addChild( rPat )

    center = osg.Vec3(0.0,0.0,0.0)
    radius = 1.0

    root = osg.Group()
    root.addChild(test_create3DText(center, radius))

    #viewer.setSceneData(root)
    pGroup.addChild(root)
    viewer.setSceneData(pGroup)
    viewer.setCameraManipulator(osgGA.TrackballManipulator())
    viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) )

    viewer.addEventHandler(osgViewer.ThreadingHandler)()
    viewer.addEventHandler(osgViewer.WindowSizeHandler)()
    viewer.addEventHandler(osgViewer.StatsHandler)()

    return viewer.run()



# Translated from file 'TextNode.cpp'

# -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield
# *
# * This library is open source and may be redistributed and/or modified under
# * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
# * (at your option) any later version.  The full license is in LICENSE file
# * included with this distribution, and on the openscenegraph.org website.
# *
# * This library is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# * OpenSceneGraph Public License for more details.
#

#include "TextNode.h"
#include "../../src/osgText/GlyphGeometry.h"

#include <osg/PositionAttitudeTransform>
#include <osg/Geode>
#include <osgUtil/SmoothingVisitor>

#include <osg/io_utils>

using namespace osgText

############################################/
#
# Layout
#
Layout.Layout()

Layout.Layout( Layout layout,  osg.CopyOp copyop):
    osg.Object(layout,copyop)
Beispiel #14
0
def createRoom(loadedModel):


    
    # default scale for this model.
    bs = osg.BoundingSphere(osg.Vec3(0.0,0.0,0.0),1.0)

    root = osg.Group()

    if loadedModel :
        loaded_bs = loadedModel.getBound()

        pat = osg.PositionAttitudeTransform()
        pat.setPivotPoint(loaded_bs.center())

        pat.setUpdateCallback(ModelTransformCallback(loaded_bs))
        pat.addChild(loadedModel)

        bs = pat.getBound()

        root.addChild(pat)


    bs.radius()*=1.5

    # create a bounding box, which we'll use to size the room.
    bb = osg.BoundingBox()
    bb.expandBy(bs)


    # create statesets.
    rootStateSet = osg.StateSet()
    root.setStateSet(rootStateSet)

    wall = osg.StateSet()
    wall.setMode(GL_CULL_FACE,osg.StateAttribute.ON)

    floor = osg.StateSet()
    floor.setMode(GL_CULL_FACE,osg.StateAttribute.ON)

    roof = osg.StateSet()
    roof.setMode(GL_CULL_FACE,osg.StateAttribute.ON)

    geode = osg.Geode()

    # create front side.
    geode.addDrawable(createWall(bb.corner(0),
                                  bb.corner(4),
                                  bb.corner(1),
                                  wall))

    # right side
    geode.addDrawable(createWall(bb.corner(1),
                                  bb.corner(5),
                                  bb.corner(3),
                                  wall))

    # left side
    geode.addDrawable(createWall(bb.corner(2),
                                  bb.corner(6),
                                  bb.corner(0),
                                  wall))
    # back side
    geode.addDrawable(createWall(bb.corner(3),
                                  bb.corner(7),
                                  bb.corner(2),
                                  wall))

    # floor
    geode.addDrawable(createWall(bb.corner(0),
                                  bb.corner(1),
                                  bb.corner(2),
                                  floor))

    # roof
    geode.addDrawable(createWall(bb.corner(6),
                                  bb.corner(7),
                                  bb.corner(4),
                                  roof))

    root.addChild(geode)

    root.addChild(createLights(bb,rootStateSet))

    return root
Beispiel #15
0
      (*coords)[1].set(osg.Vec3d(0.5, 0.0, 0.0))
      (*coords)[2].set(osg.Vec3d(0.0, 0.0, 0.0))
      (*coords)[3].set(osg.Vec3d(0.0, 0.5, 0.0))
      (*coords)[4].set(osg.Vec3d(0.0, 0.0, 0.0))
      (*coords)[5].set(osg.Vec3d(0.0, 0.0, 0.5))
      axes.setVertexArray(coords)
      axes.getOrCreateStateSet().setMode(GL_LIGHTING,osg.StateAttribute.OFF)
      axes.addPrimitiveSet(osg.DrawArrays(osg.PrimitiveSet.LINES,0,6))

    # Earth orbit
    earthOrbitGeode = osg.Geode()
    earthOrbitGeode.addDrawable(unitCircle)
    earthOrbitGeode.addDrawable(axes)
    earthOrbitGeode.setName("EarthOrbitGeode")

    earthOrbitPAT = osg.PositionAttitudeTransform()
    earthOrbitPAT.setScale(osg.Vec3d(AU,AU,AU))
    earthOrbitPAT.setPosition(osg.Vec3d(0.0, AU, 0.0))
    earthOrbitPAT.addChild(earthOrbitGeode)
    earthOrbitPAT.setName("EarthOrbitPAT")

    scene = osg.Group()
    scene.setName("SceneGroup")
    scene.addChild(earth_geode)
    scene.addChild(pat)
    scene.addChild(earthOrbitPAT)

    return scene

def main(argv):
Beispiel #16
0
class IntersectionUpdateCallback (osg.NodeCallback) :
virtual void operator()(osg.Node* #node, osg.NodeVisitor* nv)
            if  not root_  or   not terrain_  or   not ss_  or   not intersectionGroup_ :
                osg.notify(osg.NOTICE), "IntersectionUpdateCallback not set up correctly."
                return

            #traverse(node,nv)
            frameCount_++
            if frameCount_ > 200 :
                # first we need find the transformation matrix that takes
                # the terrain into the coordinate frame of the sphere segment.
                terrainLocalToWorld = osg.Matrixd()
                terrain_worldMatrices = terrain_.getWorldMatrices(root_)
                if terrain_worldMatrices.empty() : terrainLocalToWorld.makeIdentity()
                elif terrain_worldMatrices.size()==1 : terrainLocalToWorld = terrain_worldMatrices.front()
                else:
                    osg.notify(osg.NOTICE), "IntersectionUpdateCallback: warning cannot interestect with multiple terrain instances, just uses first one."
                    terrainLocalToWorld = terrain_worldMatrices.front()

                # sphere segment is easier as this callback is attached to the node, so the node visitor has the unique path to it already.
                ssWorldToLocal = osg.computeWorldToLocal(nv.getNodePath())

                # now we can compute the terrain to ss transform
                possie = terrainLocalToWorld*ssWorldToLocal

                lines = ss_.computeIntersection(possie, terrain_)
                if  not lines.empty() :
                    if intersectionGroup_.valid() :
                        # now we need to place the intersections which are in the SphereSegmenet's coordinate frame into
                        # to the final position.
                        mt = osg.MatrixTransform()
                        mt.setMatrix(osg.computeLocalToWorld(nv.getNodePath()))
                        intersectionGroup_.addChild(mt)

                        # print "matrix = ", mt.getMatrix()

                        geode = osg.Geode()
                        mt.addChild(geode)

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

                        for(osgSim.SphereSegment.LineList.iterator itr=lines.begin()
                           not = lines.end()
                           ++itr)
                            geom = osg.Geometry()
                            geode.addDrawable(geom)

                            vertices = itr
                            geom.setVertexArray(vertices)
                            geom.addPrimitiveSet(osg.DrawArrays(GL_LINE_STRIP, 0, vertices.getNumElements()))
                else:
                       osg.notify(osg.NOTICE), "No intersections found"


                frameCount_ = 0
    root_ = osg.observer_ptr<osg.Group>()
    terrain_ = osg.observer_ptr<osg.Geode>()
    ss_ = osg.observer_ptr<osgSim.SphereSegment>()
    intersectionGroup_ = osg.observer_ptr<osg.Group>()
    frameCount_ = unsigned()


class RotateUpdateCallback (osg.NodeCallback) :
    RotateUpdateCallback()  i=0
        virtual void operator()(osg.Node* node, osg.NodeVisitor* nv)
            ss = dynamic_cast<osgSim.SphereSegment *>(node)
            if ss :
                ss.setArea(osg.Vec3(cos(i/(2*osg.PI)),sin(i/(2*osg.PI)),0), osg.PI_2, osg.PI_2)

                i += 0.1

    i = float()


def createMovingModel(center, radius, terrainGeode, root, createMovingRadar):

    
    animationLength = 10.0

    animationPath = createAnimationPath(center,radius,animationLength)

    model = osg.Group()

    glider = osgDB.readNodeFile("glider.osgt")
    if glider :
        bs = glider.getBound()

        size = radius/bs.radius()*0.3
        positioned = osg.MatrixTransform()
        positioned.setDataVariance(osg.Object.STATIC)
        positioned.setMatrix(osg.Matrix.translate(-bs.center())*
                                     osg.Matrix.scale(size,size,size)*
                                     osg.Matrix.rotate(osg.inDegrees(-90.0),0.0,0.0,1.0))

        positioned.addChild(glider)

        xform = osg.PositionAttitudeTransform()
        xform.getOrCreateStateSet().setMode(GL_NORMALIZE, osg.StateAttribute.ON)
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,1.0))
        xform.addChild(positioned)
        model.addChild(xform)

    if createMovingRadar :
        # The IntersectionUpdateCallback has to have a safe place to put all its generated geometry into,
        # and this group can't be in the parental chain of the callback otherwise we will end up invalidating
        # traversal iterators.
        intersectionGroup = osg.Group()
        root.addChild(intersectionGroup)

        xform = osg.PositionAttitudeTransform()
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,1.0))

        ss = osgSim.SphereSegment(osg.Vec3d(0.0,0.0,0.0),
                                700.0, # radius
                                osg.DegreesToRadians(135.0),
                                osg.DegreesToRadians(240.0),
                                osg.DegreesToRadians(-60.0),
                                osg.DegreesToRadians(-40.0),
                                60)

        iuc = IntersectionUpdateCallback()
        iuc.frameCount_ = 0
        iuc.root_ = root
        iuc.terrain_ = terrainGeode
        iuc.ss_ = ss
        iuc.intersectionGroup_ = intersectionGroup
        ss.setUpdateCallback(iuc)
        ss.setAllColors(osg.Vec4(1.0,1.0,1.0,0.5))
        ss.setSideColor(osg.Vec4(0.5,1.0,1.0,0.1))
        xform.addChild(ss)
        model.addChild(xform)

    cessna = osgDB.readNodeFile("cessna.osgt")
    if cessna :
        bs = cessna.getBound()

        text = osgText.Text()
        size = radius/bs.radius()*0.3

        text.setPosition(bs.center())
        text.setText("Cessna")
        text.setAlignment(osgText.Text.CENTER_CENTER)
        text.setAxisAlignment(osgText.Text.SCREEN)
        text.setCharacterSize(40.0)
        text.setCharacterSizeMode(osgText.Text.OBJECT_COORDS)

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

        lod = osg.LOD()
        lod.setRangeMode(osg.LOD.PIXEL_SIZE_ON_SCREEN)
        lod.setRadius(cessna.getBound().radius())
        lod.addChild(geode,0.0,100.0)
        lod.addChild(cessna,100.0,10000.0)


        positioned = osg.MatrixTransform()
        positioned.getOrCreateStateSet().setMode(GL_NORMALIZE, osg.StateAttribute.ON)
        positioned.setDataVariance(osg.Object.STATIC)
        positioned.setMatrix(osg.Matrix.translate(-bs.center())*
                                     osg.Matrix.scale(size,size,size)*
                                     osg.Matrix.rotate(osg.inDegrees(180.0),0.0,0.0,1.0))

        #positioned.addChild(cessna)
        positioned.addChild(lod)

        xform = osg.MatrixTransform()
        xform.setUpdateCallback(osg.AnimationPathCallback(animationPath,0.0,2.0))
        xform.addChild(positioned)

        model.addChild(xform)

    return model

def createOverlay(center, radius):

    
    group = osg.Group()

    # create a grid of lines.
        geom = osg.Geometry()

        num_rows = 10

        left = center+osg.Vec3(-radius,-radius,0.0)
        right = center+osg.Vec3(radius,-radius,0.0)
        delta_row = osg.Vec3(0.0,2.0*radius/float(num_rows-1),0.0)

        top = center+osg.Vec3(-radius,radius,0.0)
        bottom = center+osg.Vec3(-radius,-radius,0.0)
        delta_column = osg.Vec3(2.0*radius/float(num_rows-1),0.0,0.0)

        vertices = osg.Vec3Array()
        for(unsigned int i=0 i<num_rows ++i)
            vertices.push_back(left)
            vertices.push_back(right)
            left += delta_row
            right += delta_row

            vertices.push_back(top)
            vertices.push_back(bottom)
            top += delta_column
            bottom += delta_column

        geom.setVertexArray(vertices)

        color = *(osg.Vec4ubArray(1))
        color[0].set(0,0,0,255)
        geom.setColorArray(color, osg.Array.BIND_OVERALL)

        geom.addPrimitiveSet(osg.DrawArrays(GL_LINES,0,vertices.getNumElements()))

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

        geode = osg.Geode()
        geode.addDrawable(geom)
        group.addChild(geode)

    return group

def computeTerrainIntersection(subgraph, x, y):

    
    bs = subgraph.getBound()
    zMax = bs.center().z()+bs.radius()
    zMin = bs.center().z()-bs.radius()

    intersector = osgUtil.LineSegmentIntersector(osg.Vec3(x,y,zMin),osg.Vec3(x,y,zMax))

    iv = osgUtil.IntersectionVisitor(intersector)

    subgraph.accept(iv)

    if intersector.containsIntersections() :
        return intersector.getFirstIntersection().getWorldIntersectPoint()

    return osg.Vec3(x,y,0.0)


#######################################
# MAIN SCENE GRAPH BUILDING FUNCTION
#######################################

def build_world(root, testCase, useOverlay, technique):

    

    # create terrain
    terrainGeode = 0
        terrainGeode = osg.Geode()

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

        terrainGeode.setStateSet( stateset )


            numColumns = 38
            numRows = 39
            unsigned int r, c

            origin = osg.Vec3(0.0,0.0,0.0)
            size = osg.Vec3(1000.0,1000.0,250.0)

            geometry = osg.Geometry()

            v = *(osg.Vec3Array(numColumns*numRows))
            tc = *(osg.Vec2Array(numColumns*numRows))
            color = *(osg.Vec4ubArray(1))

            color[0].set(255,255,255,255)

            rowCoordDelta = size.y()/(float)(numRows-1)
            columnCoordDelta = size.x()/(float)(numColumns-1)

            rowTexDelta = 1.0/(float)(numRows-1)
            columnTexDelta = 1.0/(float)(numColumns-1)

            # compute z range of z values of grid data so we can scale it.
            min_z = FLT_MAX
            max_z = -FLT_MAX
            for(r=0r<numRows++r)
                for(c=0c<numColumns++c)
                    min_z = osg.minimum(min_z,vertex[r+c*numRows][2])
                    max_z = osg.maximum(max_z,vertex[r+c*numRows][2])

            scale_z = size.z()/(max_z-min_z)

            pos = origin
            tex = osg.Vec2(0.0,0.0)
            vi = 0
            for(r=0r<numRows++r)
                pos.x() = origin.x()
                tex.x() = 0.0
                for(c=0c<numColumns++c)
                    v[vi].set(pos.x(),pos.y(),pos.z()+(vertex[r+c*numRows][2]-min_z)*scale_z)
                    tc[vi] = tex
                    pos.x()+=columnCoordDelta
                    tex.x()+=columnTexDelta
                    ++vi
                pos.y() += rowCoordDelta
                tex.y() += rowTexDelta

            geometry.setVertexArray(v)
            geometry.setTexCoordArray(0, tc)
            geometry.setColorArray(color, osg.Array.BIND_OVERALL)

            for(r=0r<numRows-1++r)
                drawElements = *(osg.DrawElementsUShort(GL_QUAD_STRIP,2*numColumns))
                geometry.addPrimitiveSet(drawElements)
                ei = 0
                for(c=0c<numColumns++c)
                    drawElements[ei++] = (r+1)*numColumns+c
                    drawElements[ei++] = (r)*numColumns+c

            smoother = osgUtil.SmoothingVisitor()
            smoother.smooth(*geometry)

            terrainGeode.addDrawable(geometry)



    # create sphere segment
    ss = 0

        terrainToSS = osg.Matrix()

        switch(testCase)
            case(0):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(135.0),
                                osg.DegreesToRadians(240.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                root.addChild(ss)
                break
            case(1):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(45.0),
                                osg.DegreesToRadians(240.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                root.addChild(ss)
                break
            case(2):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(5.0),
                                osg.DegreesToRadians(355.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                root.addChild(ss)
                break
            case(3):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(0.0),
                                osg.DegreesToRadians(360.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                root.addChild(ss)
                break
            case(4):
                ss = osgSim.SphereSegment(osg.Vec3d(0.0,0.0,0.0),
                                700.0, # radius
                                osg.DegreesToRadians(135.0),
                                osg.DegreesToRadians(240.0),
                                osg.DegreesToRadians(-60.0),
                                osg.DegreesToRadians(-40.0),
                                60)

                mt = osg.MatrixTransform()

                mt.setMatrix(osg.Matrix(-0.851781, 0.156428, -0.5, 0,
                                          -0.180627, -0.983552, -6.93889e-18, 0,
                                          -0.491776, 0.0903136, 0.866025, 0,
                                          598.217, 481.957, 100, 1))
                mt.addChild(ss)

                terrainToSS.invert(mt.getMatrix())

                root.addChild(mt)
                break
            case(5):
                ss = osgSim.SphereSegment(osg.Vec3d(0.0,0.0,0.0),
                                700.0, # radius
                                osg.DegreesToRadians(35.0),
                                osg.DegreesToRadians(135.0),
                                osg.DegreesToRadians(-60.0),
                                osg.DegreesToRadians(-40.0),
                                60)

                mt = osg.MatrixTransform()

                mt.setMatrix(osg.Matrix(-0.851781, 0.156428, -0.5, 0,
                                          -0.180627, -0.983552, -6.93889e-18, 0,
                                          -0.491776, 0.0903136, 0.866025, 0,
                                          598.217, 481.957, 100, 1))
                mt.addChild(ss)

                terrainToSS.invert(mt.getMatrix())

                root.addChild(mt)
                break
            case(6):
                ss = osgSim.SphereSegment(osg.Vec3d(0.0,0.0,0.0),
                                700.0, # radius
                                osg.DegreesToRadians(-45.0),
                                osg.DegreesToRadians(45.0),
                                osg.DegreesToRadians(-60.0),
                                osg.DegreesToRadians(-40.0),
                                60)

                mt = osg.MatrixTransform()

                mt.setMatrix(osg.Matrix(-0.851781, 0.156428, -0.5, 0,
                                          -0.180627, -0.983552, -6.93889e-18, 0,
                                          -0.491776, 0.0903136, 0.866025, 0,
                                          598.217, 481.957, 100, 1))
                mt.addChild(ss)

                terrainToSS.invert(mt.getMatrix())

                root.addChild(mt)
                break
            case(7):
                ss = osgSim.SphereSegment(
                                computeTerrainIntersection(terrainGeode,550.0,780.0), # center
                                510.0, # radius
                                osg.DegreesToRadians(-240.0),
                                osg.DegreesToRadians(-135.0),
                                osg.DegreesToRadians(-10.0),
                                osg.DegreesToRadians(30.0),
                                60)
                ss.setUpdateCallback(RotateUpdateCallback())
                root.addChild(ss)
                break
        

        if ss.valid() :
            ss.setAllColors(osg.Vec4(1.0,1.0,1.0,0.5))
            ss.setSideColor(osg.Vec4(0.0,1.0,1.0,0.1))

            if  not ss.getParents().empty() :
                ss.getParent(0).addChild(ss.computeIntersectionSubgraph(terrainToSS, terrainGeode))



    if useOverlay :
        overlayNode = osgSim.OverlayNode(technique)
        overlayNode.getOrCreateStateSet().setTextureAttribute(1, osg.TexEnv(osg.TexEnv.DECAL))

        bs = terrainGeode.getBound()
        overlaySubgraph = createOverlay(bs.center(), bs.radius()*0.5)
        overlaySubgraph.addChild(ss)
        overlayNode.setOverlaySubgraph(overlaySubgraph)
        overlayNode.setOverlayTextureSizeHint(1024)
        overlayNode.setOverlayBaseHeight(0.0)
        overlayNode.addChild(terrainGeode)

        root.addChild(overlayNode)
    else:
      root.addChild(terrainGeode)

    # create particle effects
        position = computeTerrainIntersection(terrainGeode,100.0,100.0)

        explosion = osgParticle.ExplosionEffect(position, 10.0)
        smoke = osgParticle.SmokeEffect(position, 10.0)
        fire = osgParticle.FireEffect(position, 10.0)

        root.addChild(explosion)
        root.addChild(smoke)
        root.addChild(fire)

    # create particle effects
        position = computeTerrainIntersection(terrainGeode,200.0,100.0)

        explosion = osgParticle.ExplosionEffect(position, 1.0)
        smoke = osgParticle.SmokeEffect(position, 1.0)
        fire = osgParticle.FireEffect(position, 1.0)

        root.addChild(explosion)
        root.addChild(smoke)
        root.addChild(fire)


    createMovingRadar = True

    # create the moving models.
        root.addChild(createMovingModel(osg.Vec3(500.0,500.0,500.0),100.0, terrainGeode, root, createMovingRadar))


#######################################
# main()
#######################################


def main(argv):


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

    # set up the usage document, in case we need to print out how to use this program.
    arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" is the example which demonstrates use of particle systems.")
    arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] image_file_left_eye image_file_right_eye")
    arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information")


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

    # if user request help write it out to cout.
    testCase = 0
    while arguments.read("-t", testCase) : 

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


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

    # any option left unread are converted into errors to write out later.
    arguments.reportRemainingOptionsAsUnrecognized()

    # report any errors if they have occurred when parsing the program arguments.
    if arguments.errors() :
        arguments.writeErrorMessages(std.cout)
        return 1

    root = osg.Group()
    build_world(root, testCase, useOverlay, technique)

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

    return viewer.run()


if __name__ == "__main__":
    main(sys.argv)
Beispiel #17
0
            vertex_shader.addCodeInjection(0,"gl_Position = ftransform()\n")
            sa.addShader(vertex_shader)

            fragment_shader = osg.Shader(osg.Shader.FRAGMENT)
            fragment_shader.addCodeInjection(-1,"varying vec4 color\n")
            fragment_shader.addCodeInjection(-1,"varying vec4 texcoord\n")
            fragment_shader.addCodeInjection(-1,"uniform sampler2D baseTexture \n")
            fragment_shader.addCodeInjection(0,"gl_FragColor = color * texture2DProj( baseTexture, texcoord )\n")

            sa.addShader(fragment_shader)

        sa.addUniform(osg.Uniform("baseTexture",0))


    # inherit the ShaderComponents entirely from above
        pat = osg.PositionAttitudeTransform()
        pat.setPosition(position)
        pat.addChild(node)

        position.x() += spacing

        group.addChild(pat)


        pat = osg.PositionAttitudeTransform()
        pat.setPosition(position)
        pat.addChild(node)

        position.x() += spacing

        stateset = pat.getOrCreateStateSet()
Beispiel #18
0
        outline.addChild(outlineModel)

    if testOcclusion :
        # load occluder
        occludedModelFilename = "cow.osgt"
        occludedModel = osgDB.readNodeFile(occludedModelFilename)
        if  not occludedModel :
            osg.notify(osg.FATAL), "Unable to load model '", occludedModelFilename, "'\n"
            return -1

        # occluder offset
        bsphere = outlineModel.getBound()
        occluderOffset = osg.Vec3(0,1,0) * bsphere.radius() * 1.2

        # occluder behind outlined model
        modelTransform0 = osg.PositionAttitudeTransform()
        modelTransform0.setPosition(bsphere.center() + occluderOffset)
        modelTransform0.addChild(occludedModel)
        root.addChild(modelTransform0)

        # occluder in front of outlined model
        modelTransform1 = osg.PositionAttitudeTransform()
        modelTransform1.setPosition(bsphere.center() - occluderOffset)
        modelTransform1.addChild(occludedModel)
        root.addChild(modelTransform1)

    # must have stencil buffer...
    osg.DisplaySettings.instance().setMinimumNumStencilBits(1)

    # construct the viewer
    viewer = osgViewer.Viewer()
colors.append(osg.Vec4(0.0, 1.0, 0.0, 1.0))  # index 1 green
colors.append(osg.Vec4(0.0, 0.0, 1.0, 1.0))  # index 2 blue
colors.append(osg.Vec4(1.0, 1.0, 1.0, 1.0))  # index 3 white
colors.append(osg.Vec4(1.0, 0.0, 0.0, 1.0))  # index 4 red
# Declare the variable that will match vertex array elements to color array
# elements. This vector should have the same number of elements as the number
# of vertices. This vector serves as a link between vertex arrays and color
# arrays. The next step is to associate the array of colors with the geometr
# and set the binding mode to BIND_PER_VERTEX.
pyramidGeometry.setColorArray(colors)
pyramidGeometry.setColorBinding(osg.Geometry.BIND_PER_VERTEX)
# Now that we have created a geometry node and added it to the scene we can
# reuse this geometry. For example, if we wanted to put a second pyramid 15
# units to the right of the first one, we could add this geode as the child
# of a transform node in our scene graph.
#  Declare and initialize a transform node.
pyramidTwoXForm = osg.PositionAttitudeTransform()
#  Use the 'addChild' method of the osg.Group class to
#  add the transform as a child of the root node and the
#  pyramid node as a child of the transform.
root.addChild(pyramidTwoXForm)
pyramidTwoXForm.addChild(pyramidGeode)
#  Declare and initialize a Vec3 instance to change the
#  position of the tank model in the scene
pyramidTwoPosition = osg.Vec3(15, 0, 0)
pyramidTwoXForm.setPosition(pyramidTwoPosition)
# The final step is to set up and enter a simulation loop.
viewer = osgViewer.Viewer()
viewer.setSceneData(root)
viewer.run()