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
def main(argv): overlay = False arguments = osg.ArgumentParser(argv) while arguments.read("--overlay") : overlay = True technique = osgSim.OverlayNode.OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY while arguments.read("--object") : technique = osgSim.OverlayNode.OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY overlay=True while arguments.read("--ortho") or arguments.read("--orthographic") : technique = osgSim.OverlayNode.VIEW_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY overlay=True while arguments.read("--persp") or arguments.read("--perspective") : technique = osgSim.OverlayNode.VIEW_DEPENDENT_WITH_PERSPECTIVE_OVERLAY overlay=True # initialize the viewer. viewer = osgViewer.Viewer() # load the nodes from the commandline arguments. model = createModel(overlay, technique) if not model: return 1 # tilt the scene so the default eye position is looking down on the model. rootnode = osg.MatrixTransform() rootnode.setMatrix(osg.Matrix.rotate(osg.inDegrees(30.0),1.0,0.0,0.0)) rootnode.addChild(model) # run optimization over the scene graph optimzer = osgUtil.Optimizer() optimzer.optimize(rootnode) # set the scene to render viewer.setSceneData(rootnode) viewer.setCameraManipulator(osgGA.TrackballManipulator()) # viewer.setUpViewOnSingleScreen(1) # normal viewer usage. return viewer.run()
def createAnimationPath(center, radius, looptime): # set up the animation path animationPath = osg.AnimationPath() animationPath.setLoopMode(osg.AnimationPath.LOOP) numSamples = 40 yaw = 0.0 yaw_delta = 2.0*osg.PI/(numSamples-1.0) roll = osg.inDegrees(30.0) time = 0.0 time_delta = looptime/float(numSamples) for i in range(numSamples): position = center+osg.Vec3(math.sin(yaw)*radius,math.cos(yaw)*radius,0.0) rotation = osg.Quat(roll,osg.Vec3(0.0,1.0,0.0))*osg.Quat(-(yaw+osg.inDegrees(90.0)),osg.Vec3(0.0,0.0,1.0)) animationPath.insert(time,osg.AnimationPath.ControlPoint(position,rotation)) yaw += yaw_delta time += time_delta return animationPath
def createAnimationPath(center, radius, looptime): # set up the animation path animationPath = osg.AnimationPath() animationPath.setLoopMode(osg.AnimationPath.LOOP) numSamples = 40 yaw = 0.0 yaw_delta = 2.0*osg.PI/((float)numSamples-1.0) roll = osg.inDegrees(30.0) time = 0.0 time_delta = looptime/(double)numSamples for(int i=0i<numSamples++i) position = osg.Vec3(center+osg.Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0)) rotation = osg.Quat(osg.Quat(roll,osg.Vec3(0.0,1.0,0.0))*osg.Quat(-(yaw+osg.inDegrees(90.0)),osg.Vec3(0.0,0.0,1.0))) animationPath.insert(time,osg.AnimationPath.ControlPoint(position,rotation)) yaw += yaw_delta time += time_delta
def createAnimationPath(center, radius, looptime): # set up the animation path animationPath = osg.AnimationPath() animationPath.setLoopMode(osg.AnimationPath.LOOP) numSamples = 1000 yaw = 0.0 yaw_delta = -2.0*osg.PI/((float)numSamples-1.0) roll = osg.inDegrees(30.0) time = 0.0 time_delta = looptime/(double)numSamples for(int i=0i<numSamples++i) position = osg.Vec3(center+osg.Vec3(sinf(yaw)*radius,cosf(yaw)*radius,0.0)) rotation = osg.Quat(osg.Quat(roll,osg.Vec3(0.0,1.0,0.0))*osg.Quat(-(yaw+osg.inDegrees(90.0)),osg.Vec3(0.0,0.0,1.0))) animationPath.insert(time,osg.AnimationPath.ControlPoint(position,rotation)) yaw += yaw_delta time += time_delta
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 setDomeCorrection(viewer, arguments): wsi = osg.GraphicsContext.getWindowingSystemInterface() if not wsi : osg.notify(osg.NOTICE), "Error, no WindowSystemInterface available, cannot create windows." return unsigned int width, height wsi.getScreenResolution(osg.GraphicsContext.ScreenIdentifier(0), width, height) while arguments.read("--width",width) : while arguments.read("--height",height) : traits = osg.GraphicsContext.Traits() traits.x = 0 traits.y = 0 traits.width = width traits.height = height traits.windowDecoration = False traits.doubleBuffer = True traits.sharedContext = 0 gc = osg.GraphicsContext.createGraphicsContext(traits) if not gc : osg.notify(osg.NOTICE), "GraphicsWindow has not been created successfully." return tex_width = 512 tex_height = 512 camera_width = tex_width camera_height = tex_height texture = osg.TextureCubeMap() texture.setTextureSize(tex_width, tex_height) texture.setInternalFormat(GL_RGB) texture.setFilter(osg.Texture.MIN_FILTER,osg.Texture.LINEAR) texture.setFilter(osg.Texture.MAG_FILTER,osg.Texture.LINEAR) #if 0 renderTargetImplementation = osg.Camera.SEPERATE_WINDOW buffer = GL_FRONT #else: renderTargetImplementation = osg.Camera.FRAME_BUFFER_OBJECT buffer = GL_FRONT #endif # front face camera = osg.Camera() camera.setName("Front face camera") camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(0,0,camera_width, camera_height)) camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) camera.setAllowEventFocus(False) # tell the camera to use OpenGL frame buffer object where supported. camera.setRenderTargetImplementation(renderTargetImplementation) # attach the texture and use it as the color buffer. camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.POSITIVE_Y) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd()) # top face camera = osg.Camera() camera.setName("Top face camera") camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(0,0,camera_width, camera_height)) buffer = GL_BACK if (traits.doubleBuffer) else GL_FRONT camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) camera.setAllowEventFocus(False) # tell the camera to use OpenGL frame buffer object where supported. camera.setRenderTargetImplementation(renderTargetImplementation) # attach the texture and use it as the color buffer. camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.POSITIVE_Z) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(-90.0), 1.0,0.0,0.0)) # left face camera = osg.Camera() camera.setName("Left face camera") camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(0,0,camera_width, camera_height)) camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) camera.setAllowEventFocus(False) # tell the camera to use OpenGL frame buffer object where supported. camera.setRenderTargetImplementation(renderTargetImplementation) # attach the texture and use it as the color buffer. camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.NEGATIVE_X) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(-90.0), 0.0,1.0,0.0) * osg.Matrixd.rotate(osg.inDegrees(-90.0), 0.0,0.0,1.0)) # right face camera = osg.Camera() camera.setName("Right face camera") camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(0,0,camera_width, camera_height)) camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) camera.setAllowEventFocus(False) # tell the camera to use OpenGL frame buffer object where supported. camera.setRenderTargetImplementation(renderTargetImplementation) # attach the texture and use it as the color buffer. camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.POSITIVE_X) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(90.0), 0.0,1.0,0.0 ) * osg.Matrixd.rotate(osg.inDegrees(90.0), 0.0,0.0,1.0)) # bottom face camera = osg.Camera() camera.setGraphicsContext(gc) camera.setName("Bottom face camera") camera.setViewport(osg.Viewport(0,0,camera_width, camera_height)) camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) camera.setAllowEventFocus(False) # tell the camera to use OpenGL frame buffer object where supported. camera.setRenderTargetImplementation(renderTargetImplementation) # attach the texture and use it as the color buffer. camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.NEGATIVE_Z) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(90.0), 1.0,0.0,0.0) * osg.Matrixd.rotate(osg.inDegrees(180.0), 0.0,0.0,1.0)) # back face camera = osg.Camera() camera.setName("Back face camera") camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(0,0,camera_width, camera_height)) camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) camera.setAllowEventFocus(False) # tell the camera to use OpenGL frame buffer object where supported. camera.setRenderTargetImplementation(renderTargetImplementation) # attach the texture and use it as the color buffer. camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, osg.TextureCubeMap.NEGATIVE_Y) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(180.0), 1.0,0.0,0.0)) viewer.getCamera().setProjectionMatrixAsPerspective(90.0, 1.0, 1, 1000.0) # distortion correction set up. geode = osg.Geode() geode.addDrawable(createDomeDistortionMesh(osg.Vec3(0.0,0.0,0.0), osg.Vec3(width,0.0,0.0), osg.Vec3(0.0,height,0.0), arguments)) # we need to add the texture to the mesh, we do so by creating a # StateSet to contain the Texture StateAttribute. stateset = geode.getOrCreateStateSet() stateset.setTextureAttributeAndModes(0, texture,osg.StateAttribute.ON) stateset.setMode(GL_LIGHTING,osg.StateAttribute.OFF) camera = osg.Camera() camera.setGraphicsContext(gc) camera.setClearMask(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT ) camera.setClearColor( osg.Vec4(0.1,0.1,1.0,1.0) ) camera.setViewport(osg.Viewport(0, 0, width, height)) buffer = GL_BACK if (traits.doubleBuffer) else GL_FRONT camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) camera.setReferenceFrame(osg.Camera.ABSOLUTE_RF) camera.setAllowEventFocus(False) #camera.setInheritanceMask(camera.getInheritanceMask() ~osg.CullSettings.CLEAR_COLOR ~osg.CullSettings.COMPUTE_NEAR_FAR_MODE) #camera.setComputeNearFarMode(osg.CullSettings.DO_NOT_COMPUTE_NEAR_FAR) camera.setProjectionMatrixAsOrtho2D(0,width,0,height) camera.setViewMatrix(osg.Matrix.identity()) # add subgraph to render camera.addChild(geode) camera.setName("DistortionCorrectionCamera") viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd(), False) viewer.getCamera().setNearFarRatio(0.0001)
def setDomeFaces(viewer, arguments): wsi = osg.GraphicsContext.getWindowingSystemInterface() if not wsi : osg.notify(osg.NOTICE), "Error, no WindowSystemInterface available, cannot create windows." return unsigned int width, height wsi.getScreenResolution(osg.GraphicsContext.ScreenIdentifier(0), width, height) while arguments.read("--width",width) : while arguments.read("--height",height) : traits = osg.GraphicsContext.Traits() traits.x = 0 traits.y = 0 traits.width = width traits.height = height traits.windowDecoration = True traits.doubleBuffer = True traits.sharedContext = 0 gc = osg.GraphicsContext.createGraphicsContext(traits) if not gc : osg.notify(osg.NOTICE), "GraphicsWindow has not been created successfully." return center_x = width/2 center_y = height/2 camera_width = 256 camera_height = 256 # front face camera = osg.Camera() camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(center_x-camera_width/2, center_y, camera_width, camera_height)) buffer = GL_BACK if (traits.doubleBuffer) else GL_FRONT camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd()) # top face camera = osg.Camera() camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(center_x-camera_width/2, center_y+camera_height, camera_width, camera_height)) buffer = GL_BACK if (traits.doubleBuffer) else GL_FRONT camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(-90.0), 1.0,0.0,0.0)) # left face camera = osg.Camera() camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(center_x-camera_width*3/2, center_y, camera_width, camera_height)) buffer = GL_BACK if (traits.doubleBuffer) else GL_FRONT camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(-90.0), 0.0,1.0,0.0)) # right face camera = osg.Camera() camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(center_x+camera_width/2, center_y, camera_width, camera_height)) buffer = GL_BACK if (traits.doubleBuffer) else GL_FRONT camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(90.0), 0.0,1.0,0.0)) # bottom face camera = osg.Camera() camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(center_x-camera_width/2, center_y-camera_height, camera_width, camera_height)) buffer = GL_BACK if (traits.doubleBuffer) else GL_FRONT camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(90.0), 1.0,0.0,0.0)) # back face camera = osg.Camera() camera.setGraphicsContext(gc) camera.setViewport(osg.Viewport(center_x-camera_width/2, center_y-2*camera_height, camera_width, camera_height)) buffer = GL_BACK if (traits.doubleBuffer) else GL_FRONT camera.setDrawBuffer(buffer) camera.setReadBuffer(buffer) viewer.addSlave(camera, osg.Matrixd(), osg.Matrixd.rotate(osg.inDegrees(-180.0), 1.0,0.0,0.0)) viewer.getCamera().setProjectionMatrixAsPerspective(90.0, 1.0, 1, 1000.0) viewer.assignSceneDataToCameras() def createDomeDistortionMesh(origin, widthVector, heightVector, arguments): sphere_radius = 1.0 if arguments.read("--radius", sphere_radius) : collar_radius = 0.45 if arguments.read("--collar", collar_radius) : center = osg.Vec3d(0.0,0.0,0.0) eye = osg.Vec3d(0.0,0.0,0.0) distance = sqrt(sphere_radius*sphere_radius - collar_radius*collar_radius) if arguments.read("--distance", distance) : centerProjection = False projector = eye - osg.Vec3d(0.0,0.0, distance) osg.notify(osg.NOTICE), "Projector position = ", projector osg.notify(osg.NOTICE), "distance = ", distance # create the quad to visualize. geometry = osg.Geometry() geometry.setSupportsDisplayList(False) xAxis = osg.Vec3(widthVector) width = widthVector.length() xAxis /= width yAxis = osg.Vec3(heightVector) height = heightVector.length() yAxis /= height noSteps = 50 vertices = osg.Vec3Array() texcoords = osg.Vec3Array() colors = osg.Vec4Array() bottom = origin dx = xAxis*(width/((float)(noSteps-1))) dy = yAxis*(height/((float)(noSteps-1))) screenCenter = origin + widthVector*0.5 + heightVector*0.5 screenRadius = heightVector.length() * 0.5 int i,j if centerProjection : for(i=0i<noSteps++i) cursor = bottom+dy*(float)i for(j=0j<noSteps++j) delta = osg.Vec2(cursor.x() - screenCenter.x(), cursor.y() - screenCenter.y()) theta = atan2(-delta.y(), delta.x()) phi = osg.PI_2 * delta.length() / screenRadius if phi > osg.PI_2 : phi = osg.PI_2 phi *= 2.0 # osg.notify(osg.NOTICE), "theta = ", theta, "phi=", phi texcoord = osg.Vec3(sin(phi) * cos(theta), sin(phi) * sin(theta), cos(phi)) vertices.push_back(cursor) colors.push_back(osg.Vec4(1.0,1.0,1.0,1.0)) texcoords.push_back(texcoord) cursor += dx # osg.notify(osg.NOTICE) else:
def decorate_with_clip_node(subgraph): rootnode = osg.Group() # create wireframe view of the model so the user can see # what parts are being culled away. stateset = osg.StateSet() #osg.Material* material = osg.Material() polymode = osg.PolygonMode() polymode.setMode(osg.PolygonMode.FRONT_AND_BACK, osg.PolygonMode.LINE) stateset.setAttributeAndModes( polymode, osg.StateAttribute.OVERRIDE | osg.StateAttribute.ON) wireframe_subgraph = osg.Group() wireframe_subgraph.setStateSet(stateset) wireframe_subgraph.addChild(subgraph) rootnode.addChild(wireframe_subgraph) # # # simple approach to adding a clipnode above a subrgaph. # # # create clipped part. # clipped_subgraph = osg.ClipNode() # # bs = subgraph.getBound() # bs.radius()*= 0.4 # # bb = osg.BoundingBox() # bb.expandBy(bs) # # # clipped_subgraph.createClipBox(bb) # clipped_subgraph.addChild(subgraph) # rootnode.addChild(clipped_subgraph) # # more complex approach to managing ClipNode, allowing # ClipNode node to be transformed independantly from the subgraph # that it is clipping. transform = osg.MatrixTransform() nc = osg.AnimationPathCallback(subgraph.getBound().center(), osg.Vec3(0.0, 0.0, 1.0), osg.inDegrees(45.0)) transform.setUpdateCallback(nc) clipnode = osg.ClipNode() bs = subgraph.getBound() bs.radius() *= 0.4 bb = osg.BoundingBox() bb.expandBy(bs) clipnode.createClipBox(bb) clipnode.setCullingActive(False) transform.addChild(clipnode) rootnode.addChild(transform) # create clipped part. clipped_subgraph = osg.Group() clipped_subgraph.setStateSet(clipnode.getStateSet()) clipped_subgraph.addChild(subgraph) rootnode.addChild(clipped_subgraph) return rootnode
def decorate_with_clip_node(subgraph): rootnode = osg.Group() # create wireframe view of the model so the user can see # what parts are being culled away. stateset = osg.StateSet() #osg.Material* material = osg.Material() polymode = osg.PolygonMode() polymode.setMode(osg.PolygonMode.FRONT_AND_BACK,osg.PolygonMode.LINE) stateset.setAttributeAndModes(polymode,osg.StateAttribute.OVERRIDE|osg.StateAttribute.ON) wireframe_subgraph = osg.Group() wireframe_subgraph.setStateSet(stateset) wireframe_subgraph.addChild(subgraph) rootnode.addChild(wireframe_subgraph) # # # simple approach to adding a clipnode above a subrgaph. # # # create clipped part. # clipped_subgraph = osg.ClipNode() # # bs = subgraph.getBound() # bs.radius()*= 0.4 # # bb = osg.BoundingBox() # bb.expandBy(bs) # # # clipped_subgraph.createClipBox(bb) # clipped_subgraph.addChild(subgraph) # rootnode.addChild(clipped_subgraph) # # more complex approach to managing ClipNode, allowing # ClipNode node to be transformed independantly from the subgraph # that it is clipping. transform = osg.MatrixTransform() nc = osg.AnimationPathCallback(subgraph.getBound().center(),osg.Vec3(0.0,0.0,1.0),osg.inDegrees(45.0)) transform.setUpdateCallback(nc) clipnode = osg.ClipNode() bs = subgraph.getBound() bs.radius()*= 0.4 bb = osg.BoundingBox() bb.expandBy(bs) clipnode.createClipBox(bb) clipnode.setCullingActive(False) transform.addChild(clipnode) rootnode.addChild(transform) # create clipped part. clipped_subgraph = osg.Group() clipped_subgraph.setStateSet(clipnode.getStateSet()) clipped_subgraph.addChild(subgraph) rootnode.addChild(clipped_subgraph) return rootnode
center = osg.Vec3( 0.0, 0.0, 0.0 ) animationLength = 10.0 animationPath = createAnimationPath( center, orbit, animationLength ) rotation = osg.MatrixTransform() rotation.setUpdateCallback( osg.AnimationPathCallback( animationPath, 0.0, speed ) ) return rotation # end SolarSystem.createEarthRotation osg.MatrixTransform* SolarSystem.createTranslationAndTilt( double #translation, double tilt ) 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 )
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)
def createLogo(filename, label, subscript): bb = osg.BoundingBox(osg.Vec3(0.0,0.0,0.0),osg.Vec3(100.0,100.0,100.0)) chordRatio = 0.5 sphereRatio = 0.6 # create a group to hold the whole model. logo_group = osg.Group() osg.Quat r1,r2 r1.makeRotate(-osg.inDegrees(45.0),0.0,0.0,1.0) r2.makeRotate(osg.inDegrees(45.0),1.0,0.0,0.0) xform = MyBillboardTransform() xform.setPivotPoint(bb.center()) xform.setPosition(bb.center()) xform.setAttitude(r1*r2) # # create a transform to orientate the box and globe. # osg.MatrixTransform* xform = osg.MatrixTransform() # xform.setDataVariance(osg.Object.STATIC) # xform.setMatrix(osg.Matrix.translate(-bb.center())* # osg.Matrix.rotate(-osg.inDegrees(45.0),0.0,0.0,1.0)* # osg.Matrix.rotate(osg.inDegrees(45.0),1.0,0.0,0.0)* # osg.Matrix.translate(bb.center())) # add the box and globe to it. #xform.addChild(createBox(bb,chordRatio)) #xform.addChild(createBoxNo5(bb,chordRatio)) xform.addChild(createBoxNo5No2(bb,chordRatio)) # add the transform to the group. logo_group.addChild(xform) logo_group.addChild(createGlobe(bb,sphereRatio,filename)) # add the text to the group. #group.addChild(createTextBelow(bb)) logo_group.addChild(createTextLeft(bb, label, subscript)) # create the backdrop to render the shadow to. corner = osg.Vec3(-900.0,150.0,-100.0) top = osg.Vec3(0.0,0.0,300.0) top += corner right = osg.Vec3(1100.0,0.0,0.0) right += corner # osg.Group* backdrop = osg.Group() # backdrop.addChild(createBackdrop(corner,top,right)) backdrop = osg.ClearNode() backdrop.setClearColor(osg.Vec4(1.0,1.0,1.0,0.0)) #osg.Vec3 lightPosition(-500.0,-2500.0,500.0) #osg.Node* scene = createShadowedScene(logo_group,backdrop,lightPosition,0.0,0) scene = osg.Group() stateset = scene.getOrCreateStateSet() stateset.setMode(GL_LIGHTING,osg.StateAttribute.OVERRIDE|osg.StateAttribute.OFF) scene.addChild(logo_group) scene.addChild(backdrop) return scene
subscriptText = osgText.Text() subscriptText.setFont(font) subscriptText.setText(subscript) subscriptText.setAlignment(osgText.Text.RIGHT_CENTER) subscriptText.setAxisAlignment(osgText.Text.XZ_PLANE) subscriptText.setPosition(bb.center()-osg.Vec3((bb.xMax()-bb.xMin())*4.3,-(bb.yMax()-bb.yMin())*0.5,(bb.zMax()-bb.zMin())*0.6)) subscriptText.setColor(osg.Vec4(0.0,0.0,0.0,1.0)) # black geode.addDrawable( subscriptText ) return geode osg. Node* createGlobe( osg.BoundingBox bb,float ratio, str filename) xform = osg.MatrixTransform() xform.setUpdateCallback(osg.AnimationPathCallback(bb.center(),osg.Vec3(0.0,0.0,1.0),osg.inDegrees(10.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()
# load the nodes from the commandline arguments. loadedModel = osgDB.readNodeFiles(arguments) # if not loaded assume no arguments passed in, try use default mode instead. if not loadedModel : loadedModel = osgDB.readNodeFile("cessna.osgt") if not loadedModel : return 1 # create a transform to spin the model. loadedModelTransform = osg.MatrixTransform() loadedModelTransform.addChild(loadedModel) nc = osg.AnimationPathCallback(loadedModelTransform.getBound().center(),osg.Vec3(0.0,0.0,1.0),osg.inDegrees(45.0)) loadedModelTransform.setUpdateCallback(nc) rootNode = osg.Group() rootNode.addChild(createPreRenderSubGraph(loadedModelTransform,tex_width,tex_height, renderImplementation, useImage, useTextureRectangle, useHDR, samples, colorSamples)) #osgDB.writeNodeFile(*rootNode, "test.osgb") # add model to the viewer. viewer.setSceneData( rootNode ) return viewer.run() if __name__ == "__main__": main(sys.argv)
def createMirroredScene(model): # calculate where to place the mirror according to the # loaded models bounding sphere. bs = model.getBound() width_factor = 1.5 height_factor = 0.3 xMin = bs.center().x()-bs.radius()*width_factor xMax = bs.center().x()+bs.radius()*width_factor yMin = bs.center().y()-bs.radius()*width_factor yMax = bs.center().y()+bs.radius()*width_factor z = bs.center().z()-bs.radius()*height_factor # create a textured, transparent node at the appropriate place. mirror = createMirrorSurface(xMin,xMax,yMin,yMax,z) rootNode = osg.MatrixTransform() rootNode.setMatrix(osg.Matrix.rotate(osg.inDegrees(45.0),1.0,0.0,0.0)) # make sure that the global color mask exists. rootColorMask = osg.ColorMask() rootColorMask.setMask(True,True,True,True) # set up depth to be inherited by the rest of the scene unless # overrideen. this is overridden in bin 3. rootDepth = osg.Depth() rootDepth.setFunction(osg.Depth.LESS) rootDepth.setRange(0.0,1.0) rootStateSet = osg.StateSet() rootStateSet.setAttribute(rootColorMask) rootStateSet.setAttribute(rootDepth) rootNode.setStateSet(rootStateSet) # bin1 - set up the stencil values and depth for mirror. # set up the stencil ops so that the stencil buffer get set at # the mirror plane stencil = osg.Stencil() stencil.setFunction(osg.Stencil.ALWAYS,1,~0u) stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.REPLACE) # switch off the writing to the color bit planes. colorMask = osg.ColorMask() colorMask.setMask(False,False,False,False) statesetBin1 = osg.StateSet() statesetBin1.setRenderBinDetails(1,"RenderBin") statesetBin1.setMode(GL_CULL_FACE,osg.StateAttribute.OFF) statesetBin1.setAttributeAndModes(stencil,osg.StateAttribute.ON) statesetBin1.setAttribute(colorMask) # set up the mirror geode. geode = osg.Geode() geode.addDrawable(mirror) geode.setStateSet(statesetBin1) rootNode.addChild(geode) # bin one - draw scene without mirror or reflection, unset # stencil values where scene is infront of mirror and hence # occludes the mirror. stencil = osg.Stencil() stencil.setFunction(osg.Stencil.ALWAYS,0,~0u) stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.REPLACE) statesetBin2 = osg.StateSet() statesetBin2.setRenderBinDetails(2,"RenderBin") statesetBin2.setAttributeAndModes(stencil,osg.StateAttribute.ON) groupBin2 = osg.Group() groupBin2.setStateSet(statesetBin2) groupBin2.addChild(model) rootNode.addChild(groupBin2) # bin3 - set up the depth to the furthest depth value # set up the stencil ops so that only operator on this mirrors stencil value. stencil = osg.Stencil() stencil.setFunction(osg.Stencil.EQUAL,1,~0u) stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.KEEP) # switch off the writing to the color bit planes. colorMask = osg.ColorMask() colorMask.setMask(False,False,False,False) # set up depth so all writing to depth goes to maximum depth. depth = osg.Depth() depth.setFunction(osg.Depth.ALWAYS) depth.setRange(1.0,1.0) statesetBin3 = osg.StateSet() statesetBin3.setRenderBinDetails(3,"RenderBin") statesetBin3.setMode(GL_CULL_FACE,osg.StateAttribute.OFF) statesetBin3.setAttributeAndModes(stencil,osg.StateAttribute.ON) statesetBin3.setAttribute(colorMask) statesetBin3.setAttribute(depth) # set up the mirror geode. geode = osg.Geode() geode.addDrawable(mirror) geode.setStateSet(statesetBin3) rootNode.addChild(geode) # bin4 - draw the reflection. # now create the 'reflection' of the loaded model by applying # create a Transform which flips the loaded model about the z axis # relative to the mirror node, the loadedModel is added to the # Transform so now appears twice in the scene, but is shared so there # is negligable memory overhead. Also use an osg.StateSet # attached to the Transform to override the face culling on the subgraph # to prevert an 'inside' out view of the reflected model. # set up the stencil ops so that only operator on this mirrors stencil value. # this clip plane removes any of the scene which when mirror would # poke through the mirror. However, this clip plane should really # flip sides once the eye point goes to the back of the mirror... clipplane = osg.ClipPlane() clipplane.setClipPlane(0.0,0.0,-1.0,z) clipplane.setClipPlaneNum(0) clipNode = osg.ClipNode() clipNode.addClipPlane(clipplane) dstate = clipNode.getOrCreateStateSet() dstate.setRenderBinDetails(4,"RenderBin") dstate.setMode(GL_CULL_FACE,osg.StateAttribute.OVERRIDE|osg.StateAttribute.OFF) stencil = osg.Stencil() stencil.setFunction(osg.Stencil.EQUAL,1,~0u) stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.KEEP) dstate.setAttributeAndModes(stencil,osg.StateAttribute.ON) reverseMatrix = osg.MatrixTransform() reverseMatrix.setStateSet(dstate) reverseMatrix.preMult(osg.Matrix.translate(0.0,0.0,-z)* osg.Matrix.scale(1.0,1.0,-1.0)* osg.Matrix.translate(0.0,0.0,z)) reverseMatrix.addChild(model) clipNode.addChild(reverseMatrix) rootNode.addChild(clipNode) # bin5 - draw the textured mirror and blend it with the reflection. # set up depth so all writing to depth goes to maximum depth. depth = osg.Depth() depth.setFunction(osg.Depth.ALWAYS) stencil = osg.Stencil() stencil.setFunction(osg.Stencil.EQUAL,1,~0u) stencil.setOperation(osg.Stencil.KEEP, osg.Stencil.KEEP, osg.Stencil.ZERO) # set up additive blending. trans = osg.BlendFunc() trans.setFunction(osg.BlendFunc.ONE,osg.BlendFunc.ONE) statesetBin5 = createMirrorTexturedState("Images/tank.rgb") statesetBin5.setRenderBinDetails(5,"RenderBin") statesetBin5.setMode(GL_CULL_FACE,osg.StateAttribute.OFF) statesetBin5.setAttributeAndModes(stencil,osg.StateAttribute.ON) statesetBin5.setAttributeAndModes(trans,osg.StateAttribute.ON) statesetBin5.setAttribute(depth) # set up the mirror geode. geode = osg.Geode() geode.addDrawable(mirror) geode.setStateSet(statesetBin5) rootNode.addChild(geode)
def main(argv): # use an ArgumentParser object to manage the program arguments. arguments = osg.ArgumentParser(argv) # construct the viewer. viewer = osgViewer.Viewer() # read the scene from the list of file specified commandline args. loadedModel = osgDB.readNodeFiles(arguments) # if not loaded assume no arguments passed in, try use default mode instead. if not loadedModel : loadedModel = osgDB.readNodeFile("cessna.osgt") # 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) # add a transform with a callback to animate the loaded model. loadedModelTransform = osg.MatrixTransform() loadedModelTransform.addChild(loadedModel) nc = osg.AnimationPathCallback(loadedModelTransform.getBound().center(),osg.Vec3(0.0,0.0,1.0),osg.inDegrees(45.0)) loadedModelTransform.setUpdateCallback(nc) # finally decorate the loaded model so that it has the required multipass/bin scene graph to do the reflection effect. rootNode = createMirroredScene(loadedModelTransform) # set the scene to render viewer.setSceneData(rootNode) # hint to tell viewer to request stencil buffer when setting up windows osg.DisplaySettings.instance().setMinimumNumStencilBits(8) #osgDB.writeNodeFile(*rootNode, "test.osgt") return viewer.run()
static TextTechnique s_defaultTextTechnique = TextTechnique() return s_defaultTextTechnique void TextTechnique.start() OSG_NOTICE, "TextTechnique.start()" void TextTechnique.addCharacter( osg.Vec3 position, osg.Vec3 size, Glyph* glyph, Style* style) OSG_NOTICE, "TextTechnique.addCharacter 2D(", position, ", ", size, ", ", glyph, ", ", style, ")" void TextTechnique.addCharacter( osg.Vec3 position, osg.Vec3 size, Glyph3D* glyph, Style* style) OSG_NOTICE, "TextTechnique.addCharacter 3D(", position, ", ", size, ", ", glyph, ", ", style, ")" transform = osg.PositionAttitudeTransform() transform.setPosition(position) transform.setAttitude(osg.Quat(osg.inDegrees(90.0),osg.Vec3d(1.0,0.0,0.0))) transform.setScale(size) geode = osg.Geode() bevel = style.getBevel() if (style) else 0 outline = style.getOutlineRatio()>0.0 if (style) else False width = style.getThicknessRatio() creaseAngle = 30.0 smooth = True if bevel : thickness = bevel.getBevelThickness() glyphGeometry = osgText.computeGlyphGeometry(glyph, thickness, width) textGeometry = osgText.computeTextGeometry(glyphGeometry, *bevel, width)