def allocate(): if _depth>1 : image = osg.Image() image.allocateImage(_width, _height, _depth, GL_RGBA, GL_UNSIGNED_BYTE) texture = osg.Texture3D() texture.setImage(image) texture.setResizeNonPowerOfTwoHint(False) return StateAttributeObject(texture) if _height>1 : image = osg.Image() image.allocateImage(_width, _height, 1, GL_RGBA, GL_UNSIGNED_BYTE) texture = osg.Texture2D() texture.setImage(image) texture.setResizeNonPowerOfTwoHint(False) return StateAttributeObject(texture) if _width>1 : image = osg.Image() image.allocateImage(_width, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE) texture = osg.Texture1D() texture.setImage(image) texture.setResizeNonPowerOfTwoHint(False) return StateAttributeObject(texture) else: throw "Invalid texture size of 0,0,0"
def create1DTextureStateToDecorate(loadedModel): image = osg.Image() noPixels = 1024 # allocate the image data, noPixels x 1 x 1 with 4 rgba floats - equivalent to a Vec4 not image.allocateImage(noPixels,1,1,GL_RGBA,GL_FLOAT) image.setInternalTextureFormat(GL_RGBA) typedef std.vector<osg.Vec4> ColorBands colorbands = ColorBands() colorbands.push_back(osg.Vec4(0.0,0.0,0.0,1.0)) colorbands.push_back(osg.Vec4(1.0,0.0,0.0,1.0)) colorbands.push_back(osg.Vec4(1.0,1.0,0.0,1.0)) colorbands.push_back(osg.Vec4(0.0,1.0,0.0,1.0)) colorbands.push_back(osg.Vec4(0.0,1.0,1.0,1.0)) colorbands.push_back(osg.Vec4(0.0,0.0,1.0,1.0)) colorbands.push_back(osg.Vec4(1.0,0.0,1.0,1.0)) colorbands.push_back(osg.Vec4(1.0,1.0,1.0,1.0)) nobands = colorbands.size() delta = nobands/(float)noPixels pos = 0.0 # fill in the image data. dataPtr = (osg.Vec4*)image.data() for(int i=0i<noPixels++i,pos+=delta) #float p = floorf(pos) #float r = pos-p #osg.Vec4 color = colorbands[(int)p]*(1.0-r) #if p+1<colorbands.size() : color += colorbands[(int)p+1]*r color = colorbands[(int)pos] *dataPtr++ = color
def createBillboardImage(centerColour, size, power): backgroundColour = centerColour backgroundColour[3] = 0.0 image = osg.Image() image.allocateImage(size,size,1, GL_RGBA,GL_UNSIGNED_BYTE) mid = (float(size)-1)*0.5 div = 2.0/float(size) for(unsigned int r=0r<size++r) ptr = image.data(0,r,0) for(unsigned int c=0c<size++c) dx = (float(c) - mid)*div dy = (float(r) - mid)*div r = powf(1.0-sqrtf(dx*dx+dy*dy),power) if r<0.0 : r=0.0 color = centerColour*r+backgroundColour*(1.0-r) # color.set(1.0,1.0,1.0,0.5) *ptr++ = (unsigned char)((color[0])*255.0) *ptr++ = (unsigned char)((color[1])*255.0) *ptr++ = (unsigned char)((color[2])*255.0) *ptr++ = (unsigned char)((color[3])*255.0)
class Heatmap (osg.Geode) : Heatmap(float width, float depth, float maxheight, unsigned int K, unsigned int N, float maximum, float transparency) ~Heatmap() setData = void(float *buffer, float maxheight, float maximum, float transparency) m_K = unsigned int() m_N = unsigned int() *m_data = float() m_img2 = osg.Image() m_tex2 = osg.Texture2D() colorimg = osg.Image() colortex = osg.Texture1D() *maximumUniform = osg.Uniform() *maxheightUniform = osg.Uniform() *transparencyUniform = osg.Uniform()
class SliceProcessor : SliceProcessor() : _sliceNumber(128), _sliceDelta(0.1), _nearPlane(0.0), _farPlane(MIN_NEARFAROFFSET) # SliceProcessor( double objectRadius, unsigned int numberSlices) : _sliceNumber(numberSlices) _sliceDelta = (objectRadius*2) / _sliceNumber _nearPlane = objectRadius # note: distance from viewpoint is going to be set 2x radius _farPlane = _nearPlane+MIN_NEARFAROFFSET _image = osg.Image() if _sliceDelta > MIN_NEARFAROFFSET : _nearFarOffset = MIN_NEARFAROFFSET else: _nearFarOffset = _sliceDelta _image.allocateImage( _sliceNumber, _sliceNumber,_sliceNumber, GL_RGBA, GL_UNSIGNED_BYTE )
class SnapImage (osg.Camera.DrawCallback) : SnapImage( str filename): _filename(filename), _snapImage(False) _image = osg.Image()
osg.Node* ForestTechniqueManager.createTextureBufferGraph(Cell* cell, osg.Geometry* templateGeometry) needGroup = not (cell._cells.empty()) needTrees = not (cell._trees.empty()) geode = 0 group = 0 if needTrees : geometry = (osg.Geometry*)templateGeometry.clone( osg.CopyOp.DEEP_COPY_PRIMITIVES ) primSet = dynamic_cast<osg.DrawArrays*>( geometry.getPrimitiveSet(0) ) primSet.setNumInstances( cell._trees.size() ) geode = osg.Geode() geode.addDrawable(geometry) treeParamsImage = osg.Image() treeParamsImage.allocateImage( 3*cell._trees.size(), 1, 1, GL_RGBA, GL_FLOAT ) i = 0 for(TreeList.iterator itr=cell._trees.begin() not = cell._trees.end() ++itr,++i) ptr = (osg.Vec4f*)treeParamsImage.data(3*i) tree = **itr ptr[0] = osg.Vec4f(tree._position.x(),tree._position.y(),tree._position.z(),1.0) ptr[1] = osg.Vec4f((float)tree._color.r()/255.0,(float)tree._color.g()/255.0, (float)tree._color.b()/255.0, 1.0) ptr[2] = osg.Vec4f(tree._width, tree._height, 1.0, 1.0) tbo = osg.TextureBuffer() tbo.setImage( treeParamsImage ) tbo.setInternalFormat(GL_RGBA32F_ARB) geometry.getOrCreateStateSet().setTextureAttribute(1, tbo)
# attach the textures to use for (int i=0 i<NUM_TEXTURES i++) if useMultiSample : camera.attach(osg.Camera.BufferComponent(osg.Camera.COLOR_BUFFER0+i), textureRect[i], 0, 0, False, 4, 4) else: camera.attach(osg.Camera.BufferComponent(osg.Camera.COLOR_BUFFER0+i), textureRect[i]) # we can also read back any of the targets as an image, modify this image and push it back if useImage : # which texture to get the image from tex_to_get = 0 image = osg.Image() if useHDR : image.allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_FLOAT) else: image.allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE) # attach the image so its copied on each frame. camera.attach(osg.Camera.BufferComponent(osg.Camera.COLOR_BUFFER0 + tex_to_get), image) camera.setPostDrawCallback(MyCameraPostDrawCallback(image)) # push back the image to the texture textureRect[tex_to_get].setImage(0, image) # add the subgraph to render camera.addChild(cam_subgraph)
base2 = (y/2) * (O*K+O*K+1) + O*K + O*K+1 i = 0 for (unsigned int x=0 x < O*K x++) indices[i++] = base+x indices[i++] = base2+x indices[i++] = base+O*K meshGeom.addPrimitiveSet(osg.DrawElementsUInt(osg.PrimitiveSet.TRIANGLE_STRIP, i, indices)) delete[] indices # create vertex and fragment shader program = osg.Program() program.setName( "mesh" ) program.addBindAttribLocation("xypos", 6) program.addShader( osg.Shader( osg.Shader.VERTEX, VertexShader ) ) program.addShader( osg.Shader( osg.Shader.FRAGMENT, DepthPeeling.PeelingShader ) ) program.addShader( osg.Shader( osg.Shader.FRAGMENT, FragmentShader ) ) # create a 1D texture for color lookups colorimg = osg.Image() colorimg.allocateImage(5, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE) data = colorimg.data() *data++ = 0 *data++ = 0 *data++ = 255 *data++ = 0 # fully transparent blue *data++ = 0 *data++ = 255 *data++ = 255 *data++ = 255 # turquoise *data++ = 0 *data++ = 255 *data++ = 0 *data++ = 255 # green *data++ = 255 *data++ = 255 *data++ = 0 *data++ = 255 # yellow *data++ = 255 *data++ = 0 *data++ = 0 *data++ = 255 # red colortex = osg.Texture1D(colorimg) colortex.setFilter(osg.Texture.MIN_FILTER, osg.Texture.LINEAR) colortex.setFilter(osg.Texture.MAG_FILTER, osg.Texture.LINEAR) colortex.setWrap(osg.Texture.WRAP_S, osg.Texture.CLAMP_TO_EDGE) colortex.setResizeNonPowerOfTwoHint(False) # create a 2D texture for data lookups m_img2 = osg.Image()
class PosterPrinter (osg.Referenced) : typedef std.pair<unsigned int, unsigned int> TilePosition typedef std.map< TilePosition, osg.Image > TileImages PosterPrinter() #* Set to output each sub-image-tile to disk def setOutputTiles(b): _outputTiles = b def getOutputTiles(): return _outputTiles #* Set the output sub-image-tile extension, e.g. bmp def setOutputTileExtension(ext): _outputTileExt = ext def getOutputTileExtension(): return _outputTileExt #* Set the output poster name, e.g. output.bmp def setOutputPosterName(name): _outputPosterName = name def getOutputPosterName(): return _outputPosterName #* Set the size of each sub-image-tile, e.g. 640x480 def setTileSize(w, h): _tileSize.set(w, h) def getTileSize(): return _tileSize #* Set the final size of the high-res poster, e.g. 6400x4800 def setPosterSize(w, h): _posterSize.set(w, h) def getPosterSize(): return _posterSize #* Set the capturing camera def setCamera(camera): _camera = camera def getCamera(): return _camera #* Set the final poster image, should be already allocated def setFinalPoster(image): _finalPoster = image def getFinalPoster(): return _finalPoster def getPosterVisitor(): return _visitor def getPosterVisitor(): return _visitor def done(): return not _isRunning and not _isFinishing init = void( osg.Camera* camera ) init = void( osg.Matrixd view, osg.Matrixd proj ) frame = void( osg.FrameStamp* fs, osg.Node* node ) virtual ~PosterPrinter() addCullCallbacks = bool( osg.FrameStamp* fs, osg.Node* node ) removeCullCallbacks = void( osg.Node* node ) bindCameraToImage = void( osg.Camera* camera, int row, int col ) recordImages = void() _outputTiles = bool() _outputTileExt = str() _outputPosterName = str() _tileSize = osg.Vec2() _posterSize = osg.Vec2() _isRunning = bool() _isFinishing = bool() _lastBindingFrame = unsigned int() _tileRows = int() _tileColumns = int() _currentRow = int() _currentColumn = int() _intersector = PosterIntersector() _visitor = PosterVisitor() _currentViewMatrix = osg.Matrixd() _currentProjectionMatrix = osg.Matrixd() _camera = osg.Camera() _finalPoster = osg.Image() _images = TileImages()
def main(argv): arguments = osg.ArgumentParser( argc, argv ) usage = arguments.getApplicationUsage() usage.setDescription( arguments.getApplicationName() + " is the example which demonstrates how to render high-resolution images (posters).") usage.setCommandLineUsage( arguments.getApplicationName() + " [options] scene_file" ) usage.addCommandLineOption( "-h or --help", "Display this information." ) usage.addCommandLineOption( "--color <r> <g> <b>", "The background color." ) usage.addCommandLineOption( "--ext <ext>", "The output tiles' extension (Default: bmp)." ) usage.addCommandLineOption( "--poster <filename>", "The output poster's name (Default: poster.bmp)." ) usage.addCommandLineOption( "--tilesize <w> <h>", "Size of each image tile (Default: 640 480)." ) usage.addCommandLineOption( "--finalsize <w> <h>", "Size of the poster (Default: 6400 4800)." ) usage.addCommandLineOption( "--enable-output-poster", "Output the final poster file (Default)." ) usage.addCommandLineOption( "--disable-output-poster", "Don't output the final poster file." ) #usage.addCommandLineOption( "--enable-output-tiles", "Output all tile files." ) #usage.addCommandLineOption( "--disable-output-tiles", "Don't output all tile files (Default)." ) usage.addCommandLineOption( "--use-fb", "Use Frame Buffer for rendering tiles (Default, recommended).") usage.addCommandLineOption( "--use-fbo", "Use Frame Buffer Object for rendering tiles.") usage.addCommandLineOption( "--use-pbuffer","Use Pixel Buffer for rendering tiles.") usage.addCommandLineOption( "--use-pbuffer-rtt","Use Pixel Buffer RTT for rendering tiles.") usage.addCommandLineOption( "--inactive", "Inactive capturing mode." ) usage.addCommandLineOption( "--camera-eye <x> <y> <z>", "Set eye position in inactive mode." ) usage.addCommandLineOption( "--camera-latlongheight <lat> <lon> <h>", "Set eye position on earth in inactive mode." ) usage.addCommandLineOption( "--camera-hpr <h> <p> <r>", "Set eye rotation in inactive mode." ) if arguments.read("-h") or arguments.read("--help") : usage.write( std.cout ) return 1 # Poster arguments activeMode = True outputPoster = True #bool outputTiles = False tileWidth = 640, tileHeight = 480 posterWidth = 640*2, posterHeight = 480*2 posterName = "poster.bmp", extName = "bmp" bgColor = osg.Vec4(0.2, 0.2, 0.6, 1.0) renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT while arguments.read("--inactive") : activeMode = False while arguments.read("--color", bgColor.r(), bgColor.g(), bgColor.b()) : while arguments.read("--tilesize", tileWidth, tileHeight) : while arguments.read("--finalsize", posterWidth, posterHeight) : while arguments.read("--poster", posterName) : while arguments.read("--ext", extName) : while arguments.read("--enable-output-poster") : outputPoster = True while arguments.read("--disable-output-poster") : outputPoster = False #while arguments.read("--enable-output-tiles") : outputTiles = True #while arguments.read("--disable-output-tiles") : outputTiles = False while arguments.read("--use-fbo") : renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT while arguments.read("--use-pbuffer") : renderImplementation = osg.Camera.PIXEL_BUFFER while arguments.read("--use-pbuffer-rtt") : renderImplementation = osg.Camera.PIXEL_BUFFER_RTT while arguments.read("--use-fb") : renderImplementation = osg.Camera.FRAME_BUFFER # Camera settings for inactive screenshot useLatLongHeight = True eye = osg.Vec3d() latLongHeight = osg.Vec3d( 50.0, 10.0, 2000.0 ) hpr = osg.Vec3d( 0.0, 0.0, 0.0 ) if arguments.read("--camera-eye", eye.x(), eye.y(), eye.z()) : useLatLongHeight = False activeMode = False elif arguments.read("--camera-latlongheight", latLongHeight.x(), latLongHeight.y(), latLongHeight.z()) : activeMode = False latLongHeight.x() = osg.DegreesToRadians( latLongHeight.x() ) latLongHeight.y() = osg.DegreesToRadians( latLongHeight.y() ) if arguments.read("--camera-hpr", hpr.x(), hpr.y(), hpr.z()) : activeMode = False hpr.x() = osg.DegreesToRadians( hpr.x() ) hpr.y() = osg.DegreesToRadians( hpr.y() ) hpr.z() = osg.DegreesToRadians( hpr.z() ) # Construct scene graph scene = osgDB.readNodeFiles( arguments ) if not scene : scene = osgDB.readNodeFile( "cow.osgt" ) if not scene : print arguments.getApplicationName(), ": No data loaded" return 1 # Create camera for rendering tiles offscreen. FrameBuffer is recommended because it requires less memory. camera = osg.Camera() camera.setClearColor( bgColor ) camera.setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) camera.setReferenceFrame( osg.Transform.ABSOLUTE_RF ) camera.setRenderOrder( osg.Camera.PRE_RENDER ) camera.setRenderTargetImplementation( renderImplementation ) camera.setViewport( 0, 0, tileWidth, tileHeight ) camera.addChild( scene ) # Set the printer printer = PosterPrinter() printer.setTileSize( tileWidth, tileHeight ) printer.setPosterSize( posterWidth, posterHeight ) printer.setCamera( camera ) posterImage = 0 if outputPoster : posterImage = osg.Image() posterImage.allocateImage( posterWidth, posterHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE ) printer.setFinalPoster( posterImage ) printer.setOutputPosterName( posterName ) #if 0 # While recording sub-images of the poster, the scene will always be traversed twice, from its two # parent node: root and camera. Sometimes this may not be so comfortable. # To prevent this behaviour, we can use a switch node to enable one parent and disable the other. # However, the solution also needs to be used with care, as the window will go blank while taking # snapshots and recover later. root = osg.Switch() root.addChild( scene, True ) root.addChild( camera, False ) #else: root = osg.Group() root.addChild( scene ) root.addChild( camera ) #endif viewer = osgViewer.Viewer() viewer.setSceneData( root ) viewer.getDatabasePager().setDoPreCompile( False ) if renderImplementation==osg.Camera.FRAME_BUFFER : # FRAME_BUFFER requires the window resolution equal or greater than the to-be-copied size viewer.setUpViewInWindow( 100, 100, tileWidth, tileHeight ) else: # We want to see the console output, so just render in a window viewer.setUpViewInWindow( 100, 100, 800, 600 ) if activeMode : viewer.addEventHandler( PrintPosterHandler(printer) ) viewer.addEventHandler( osgViewer.StatsHandler )() viewer.addEventHandler( osgGA.StateSetManipulator(viewer.getCamera().getOrCreateStateSet()) ) viewer.setCameraManipulator( osgGA.TrackballManipulator )() viewer.run() else: camera = viewer.getCamera() if not useLatLongHeight : computeViewMatrix( camera, eye, hpr ) computeViewMatrixOnEarth = else( camera, scene, latLongHeight, hpr ) renderer = CustomRenderer( camera ) camera.setRenderer( renderer ) viewer.setThreadingModel( osgViewer.Viewer.SingleThreaded ) # Realize and initiate the first PagedLOD request viewer.realize() viewer.frame() printer.init( camera ) while not printer.done() : viewer.advance() # Keep updating and culling until full level of detail is reached renderer.setCullOnly( True ) while viewer.getDatabasePager().getRequestsInProgress() : viewer.updateTraversal() viewer.renderingTraversals() renderer.setCullOnly( False ) printer.frame( viewer.getFrameStamp(), viewer.getSceneData() ) viewer.renderingTraversals() return 0 # Translated from file 'PosterPrinter.cpp' #include <osg/ClusterCullingCallback> #include <osgDB/ReadFile> #include <osgDB/WriteFile> #include <string.h> #include <iostream> #include <sstream> #include "PosterPrinter.h" # PagedLoadingCallback: Callback for loading paged nodes while doing intersecting test class PagedLoadingCallback (osgUtil.IntersectionVisitor.ReadCallback) : def readNodeFile(filename): return osgDB.readNodeFile( filename ) static PagedLoadingCallback g_pagedLoadingCallback = PagedLoadingCallback() # LodCullingCallback: Callback for culling LODs and selecting the highest level class LodCullingCallback (osg.NodeCallback) : virtual void operator()( osg.Node* node, osg.NodeVisitor* nv ) lod = static_cast<osg.LOD*>(node) if lod and lod.getNumChildren()>0 : lod.getChild(lod.getNumChildren()-1).accept(*nv) static LodCullingCallback g_lodCullingCallback = LodCullingCallback() # PagedCullingCallback: Callback for culling paged nodes and selecting the highest level class PagedCullingCallback (osg.NodeCallback) : virtual void operator()( osg.Node* node, osg.NodeVisitor* nv ) pagedLOD = static_cast<osg.PagedLOD*>(node) if pagedLOD and pagedLOD.getNumChildren()>0 : numChildren = pagedLOD.getNumChildren() updateTimeStamp = nv.getVisitorType()==osg.NodeVisitor.CULL_VISITOR if nv.getFrameStamp() and updateTimeStamp : timeStamp = nv.getFrameStamp().getReferenceTime() if (nv.getFrameStamp()) else 0.0 frameNumber = nv.getFrameStamp().getFrameNumber() if (nv.getFrameStamp()) else 0 pagedLOD.setFrameNumberOfLastTraversal( frameNumber ) pagedLOD.setTimeStamp( numChildren-1, timeStamp ) pagedLOD.setFrameNumber( numChildren-1, frameNumber ) pagedLOD.getChild(numChildren-1).accept(*nv) # Request for child if not pagedLOD.getDisableExternalChildrenPaging() and nv.getDatabaseRequestHandler() and numChildren<pagedLOD.getNumRanges() : if pagedLOD.getDatabasePath().empty() : nv.getDatabaseRequestHandler().requestNodeFile( pagedLOD.getFileName(numChildren), nv.getNodePath(), 1.0, nv.getFrameStamp(), pagedLOD.getDatabaseRequest(numChildren), pagedLOD.getDatabaseOptions() ) else: nv.getDatabaseRequestHandler().requestNodeFile( pagedLOD.getDatabasePath()+pagedLOD.getFileName(numChildren), nv.getNodePath(), 1.0, nv.getFrameStamp(), pagedLOD.getDatabaseRequest(numChildren), pagedLOD.getDatabaseOptions() ) #node.traverse(*nv) static PagedCullingCallback g_pagedCullingCallback = PagedCullingCallback() # PosterVisitor: A visitor for adding culling callbacks to newly allocated paged nodes PosterVisitor.PosterVisitor() : osg.NodeVisitor(osg.NodeVisitor.TRAVERSE_ALL_CHILDREN), _appliedCount(0), _needToApplyCount(0), _addingCallbacks(True) void PosterVisitor.apply( osg.LOD node ) #if not hasCullCallback(node.getCullCallback(), g_lodCullingCallback) : # # if not node.getName().empty() : # # itr = _pagedNodeNames.find( node.getName() ) # if itr not =_pagedNodeNames.end() : # # insertCullCallback( node, g_lodCullingCallback ) # _appliedCount++ # # # # def if _addingCallbacks . # # node.removeCullCallback( g_lodCullingCallback ) # _appliedCount-- # traverse( node ) void PosterVisitor.apply( osg.PagedLOD node ) if not hasCullCallback(node.getCullCallback(), g_pagedCullingCallback) : for ( unsigned int i=0 i<node.getNumFileNames() ++i ) if node.getFileName(i).empty() : continue itr = _pagedNodeNames.find( node.getFileName(i) ) if itr not =_pagedNodeNames.end() : node.addCullCallback( g_pagedCullingCallback ) _appliedCount++ break
if image_0.getPixelFormat() not =image_1.getPixelFormat() or image_0.getPixelFormat() not =image_2.getPixelFormat() or image_0.getPixelFormat() not =image_3.getPixelFormat() : print "Warning: image pixel formats not compatible." return osg.StateSet() textureSize = 256 # scale them all to the same size. image_0.scaleImage(textureSize,textureSize,1) image_1.scaleImage(textureSize,textureSize,1) image_2.scaleImage(textureSize,textureSize,1) image_3.scaleImage(textureSize,textureSize,1) # then allocated a 3d image to use for texturing. image_3d = osg.Image() image_3d.allocateImage(textureSize,textureSize,4, image_0.getPixelFormat(),image_0.getDataType()) # copy the 2d images into the 3d image. image_3d.copySubImage(0,0,0,image_0) image_3d.copySubImage(0,0,1,image_1) image_3d.copySubImage(0,0,2,image_2) image_3d.copySubImage(0,0,3,image_3) image_3d.setInternalTextureFormat(image_0.getInternalTextureFormat()) # set up the 3d texture itself, # note, well set the filtering up so that mip mapping is disabled, # gluBuild3DMipsmaps doesn't do a very good job of handled the # inbalanced dimensions of the 256x256x4 texture.
class WindowCaptureCallback (osg.Camera.DrawCallback) : WindowCaptureCallback(GLenum readBuffer, str name): _readBuffer(readBuffer), _fileName(name) _image = osg.Image()
def main(argv): # use an ArgumentParser object to manage the program arguments. arguments = osg.ArgumentParser(argv) # set up the usage document, in case we need to print out how to use this program. arguments.getApplicationUsage().setDescription(arguments.getApplicationName()+" is the example which demonstrates use of osg.AnimationPath and UpdateCallbacks for adding animation to your scenes.") arguments.getApplicationUsage().setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...") arguments.getApplicationUsage().addCommandLineOption("-h or --help","Display this information") arguments.getApplicationUsage().addCommandLineOption("-o <filename>","Object to be loaded") if arguments.read( "-h" ) or arguments.read( "--help" ) : print "Argumentlist:" print "\t-o <filename> sets object to be loaded and sliced" print "\t--slices <unsigned int> sets number of slices through the object" print "\t--near <double> sets start for near clipping plane" print "\t--far <double> sets start for far clipping plane" return 1 outputName = str("volume_tex.dds") while arguments.read( "-o", outputName ) : numberSlices = 128 while arguments.read( "--slices", numberSlices) : nearClip = 0.0 farClip = 0.0 while arguments.read( "--near",nearClip ) : while arguments.read( "--far", farClip) : # load the scene. loadedModel = osgDB.readNodeFiles( arguments ) if not loadedModel : print "No data loaded." return 1 bs = loadedModel.getBound() sp = SliceProcessor( (double)bs.radius(), numberSlices ) if nearClip not =0.0 : sp._nearPlane = nearClip if farClip not =0.0 : sp._farPlane = farClip # any option left unread are converted into errors to write out later. arguments.reportRemainingOptionsAsUnrecognized() # report any errors if they have occurred when parsing the program arguments. if arguments.errors() : arguments.writeErrorMessages(std.cout) return 1 traits = osg.GraphicsContext.Traits() traits.x = 100 traits.y = 100 traits.width = numberSlices traits.height = numberSlices traits.alpha = 8 traits.windowDecoration = True traits.doubleBuffer = True traits.sharedContext = 0 traits.pbuffer = False gc = osg.GraphicsContext.createGraphicsContext(traits) if not gc or not gc.valid() : osg.notify(osg.NOTICE), "Error: unable to create graphics window" return 1 gc.realize() gc.makeCurrent() # create the view of the scene. sceneView = osgUtil.SceneView() sceneView.setDefaults() sceneView.setSceneData(loadedModel) # initialize the view to look at the center of the scene graph viewMatrix = osg.Matrix() # distance from viewport to object's center is set to be 2x bs.radius() viewMatrix.makeLookAt(bs.center()-osg.Vec3(0.0,2.0*bs.radius(),0.0),bs.center(),osg.Vec3(0.0,0.0,1.0)) # turn off autocompution of near and far clipping planes sceneView.setComputeNearFarMode(osgUtil.CullVisitor.DO_NOT_COMPUTE_NEAR_FAR) # set the clear color of the background to make sure that the alpha is 0.0. sceneView.setClearColor(osg.Vec4(0.0,0.0,0.0,0.0)) # record the timer tick at the start of rendering. start_tick = osg.Timer.instance().tick() print "radius: ", bs.radius() frameNum = 0 double tmpNear, tmpFar baseImageName = str("shot_") tmpImageName = str() tmpImage = osg.Image() # main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.) for( unsigned int i = 0 i < sp._sliceNumber and gc.isRealized() ++i ) # set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly frameStamp = osg.FrameStamp() frameStamp.setReferenceTime(osg.Timer.instance().delta_s(start_tick,osg.Timer.instance().tick())) frameStamp.setFrameNumber(frameNum++) # pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp sceneView.setFrameStamp(frameStamp) # update the viewport dimensions, incase the window has been resized. sceneView.setViewport(0,0,traits.width,traits.height) # set the view sceneView.setViewMatrix(viewMatrix) # set Projection Matrix tmpNear = sp._nearPlane+i*sp._sliceDelta tmpFar = sp._farPlane+(i*sp._sliceDelta)+sp._nearFarOffset sceneView.setProjectionMatrixAsOrtho(-(bs.radius()+bs.radius()/2), bs.radius()+bs.radius()/2,-bs.radius(), bs.radius(), tmpNear, tmpFar) # do the update traversal the scene graph - such as updating animations sceneView.update() # do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins sceneView.cull() # draw the rendering bins. sceneView.draw() # Swap Buffers gc.swapBuffers() print "before readPixels: _r = ", sp._image.r() tmpImage.readPixels(static_cast<int>(sceneView.getViewport().x()), static_cast<int>(sceneView.getViewport().y()), static_cast<int>(sceneView.getViewport().width()), static_cast<int>(sceneView.getViewport().height()), GL_RGBA,GL_UNSIGNED_BYTE) # print "vor copySubImage: _r = ", sp._image.r() sp._image.copySubImage( 0, 0, i, tmpImage ) # # o = std.ostringstream() # o, baseImageName, i, ".rgba" # tmpImageName = o.str() # osgDB.writeImageFile( *(sp._image), tmpImageName ) # print "Wrote image to file: ", tmpImageName # osgDB.writeImageFile( *(sp._image), outputName) return 0 if __name__ == "__main__": main(sys.argv)
def createModel(shader, textureFileName, terrainFileName, dynamic, useVBO): geode = osg.Geode() geom = osg.Geometry() geode.addDrawable(geom) # dimensions for ~one million triangles :-) num_x = 708 num_y = 708 # set up state stateset = geom.getOrCreateStateSet() program = osg.Program() stateset.setAttribute(program) if shader=="simple" : vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_simple) program.addShader(vertex_shader) coeff = osg.Uniform("coeff",osg.Vec4(1.0,-1.0,-1.0,1.0)) stateset.addUniform(coeff) if dynamic : coeff.setUpdateCallback(UniformVarying)() coeff.setDataVariance(osg.Object.DYNAMIC) stateset.setDataVariance(osg.Object.DYNAMIC) elif shader=="matrix" : vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_matrix) program.addShader(vertex_shader) origin = osg.Uniform("origin",osg.Vec4(0.0,0.0,0.0,1.0)) stateset.addUniform(origin) coeffMatrix = osg.Uniform("coeffMatrix", osg.Matrix(1.0,0.0,1.0,0.0, 0.0,0.0,-1.0,0.0, 0.0,1.0,-1.0,0.0, 0.0,0.0,1.0,0.0)) stateset.addUniform(coeffMatrix) elif shader=="texture" : vertex_shader = osg.Shader(osg.Shader.VERTEX, vertexShaderSource_texture) program.addShader(vertex_shader) image = 0 if terrainFileName.empty() : image = osg.Image() tx = 38 ty = 39 image.allocateImage(tx,ty,1,GL_LUMINANCE,GL_FLOAT,1) for(unsigned int r=0r<ty++r) for(unsigned int c=0c<tx++c) *((float*)image.data(c,r)) = vertex[r+c*39][2]*0.1 num_x = tx num_y = tx