def startDragPanOrPick(self, eventAdaptor, viewer): eventWasHandled = False if viewer.getSceneData(): # TODO: This is a major hack. The intersection code below always picks the composite dragger, even if it isn't being rendered. So we remove the inactive dragger while picking. # TODO: Figure out how to make the intersection code honor the LOD and get rid of the DraggerCullCallback class. if self._display.draggerLOD is not None: if self._display.activeDragger == self._display.simpleDragger: self._display.draggerLOD.removeChild( self._display.compositeDragger) if self._display.activeDragger == self._display.compositeDragger: self._display.draggerLOD.removeChild( self._display.simpleDragger) x, y = eventAdaptor.getX(), eventAdaptor.getY() if self.usePolytopeIntersector(): picker = osgUtil.PolytopeIntersector( osgUtil.Intersector.WINDOW, x - 2.0, y - 2.0, x + 2.0, y + 2.0) else: picker = osgUtil.LineSegmentIntersector( osgUtil.Intersector.WINDOW, x, y) intersectionVisitor = osgUtil.IntersectionVisitor(picker) intersectionVisitor.setTraversalMode( osg.NodeVisitor.TRAVERSE_ACTIVE_CHILDREN) viewer.getCamera().accept(intersectionVisitor) if picker.containsIntersections(): # Add all intersections from the first dragger hit onward to the pointer info. This allows dragging of nested regions. self.pointerInfo.setCamera(viewer.getCamera()) self.pointerInfo.setMousePosition(eventAdaptor.getX(), eventAdaptor.getY()) intersections = picker.getIntersections() for i in range(0, len(intersections)): intersection = intersections[i] for j in range(0, len(intersection.nodePath)): node = intersection.nodePath[j] if self.dragger is None: self.dragger = osgManipulator.NodeToDragger(node) if self.dragger is not None: localPoint = intersection.localIntersectionPoint # have to do stupid conversion from Vec3d to Vec3 if self.usePolytopeIntersector(): self.pointerInfo.addIntersection( intersection.nodePath, osg.Vec3(localPoint.x(), localPoint.y(), localPoint.z())) else: self.pointerInfo.addIntersection( intersection.nodePath, osg.Vec3d(localPoint.x(), localPoint.y(), localPoint.z())) if self.dragger is not None: self.dragger.handle(self.pointerInfo, eventAdaptor, viewer) eventWasHandled = True if self._display.draggerLOD is not None: if self._display.activeDragger == self._display.simpleDragger: self._display.draggerLOD.addChild( self._display.compositeDragger) if self._display.activeDragger == self._display.compositeDragger: self._display.draggerLOD.addChild( self._display.simpleDragger) return eventWasHandled
def createObjectFromImageList(pNode, pImageList, pBaseUrl=""): """ uses the image list to create a set of objects """ box_geometry = osg.Box() box_drawable = osg.ShapeDrawable(box_geometry) # create a random function for floating points frandom = lambda x, y: random.randrange(x, y, int=types.FloatType) print "Opening %d from %d images" % (maxphotos, len(pImageList)) for imgfile in [str(x) for x in pImageList[:maxphotos]]: print "osgDB.readImageFile loading:", imgfile image = osgDB.readImageFile(imgfile) #check if the image is there, and not too small (icons and such) if image and image.s() > 100.0 and image.t() > 100.0: t = osg.TextureRectangle() texmat = osg.TexMat() texmat.setScaleByTextureRectangleSize(True) t.setImage(image) stateset = osg.StateSet() stateset.setTextureAttributeAndModes(0, t, 1) stateset.setTextureAttributeAndModes(0, texmat, osg.StateAttribute.ON) lbox_geode = osg.Geode() lbox_geode.addDrawable(box_drawable) lbox_geode.setStateSet(stateset) lbox_node = osg.PositionAttitudeTransform() lbox_node.addChild(lbox_geode) rscale = frandom(5, 10) lbox_node.setScale( osg.Vec3d(image.s() / rscale, 0.5, image.t() / rscale)) #set vertical q = osg.Quat() q.makeRotate(frandom(0, 2 * math.pi), 0, 0, 1) lbox_node.setAttitude(q) lbox_node.setPosition( osg.Vec3d(frandom(-50, 50), frandom(-50, 50), frandom(-100, 100))) pNode.addChild(lbox_node)
def resetCamera(self, viewer): camera = viewer.getCamera() camera.setComputeNearFarMode(False) # camera = osg.Camera() camera.setViewport(osg.Viewport(0, 0, self.width(), self.height())) # camera.setReferenceFrame(osg.Transform.ABSOLUTE_RF) CAMERA_ANGLE = 45.0 CAMERA_Z_TRANSLATE = 2.4142135623730949 #1.0 / math.tan(math.radians(CAMERA_ANGLE / 2.0)) cameraPosition = [0.0, 0.0, CAMERA_Z_TRANSLATE] camera.setProjectionMatrixAsPerspective( CAMERA_ANGLE, float(self.width()) / float(self.height()), 0.1, 100.0) eye = osg.Vec3d(cameraPosition[0], cameraPosition[1], cameraPosition[2]) center = osg.Vec3d(0, 0, 0) up = osg.Vec3d(0, 1, 0) camera.setViewMatrixAsLookAt(eye, center, up) camera.getOrCreateStateSet().setAttributeAndModes( osg.BlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA)) camera.getOrCreateStateSet().setMode(GL.GL_DEPTH_TEST, False) camera.getOrCreateStateSet().setMode(GL.GL_DEPTH_WRITEMASK, False) camera.getOrCreateStateSet().setMode(GL.GL_LIGHTING, False) material = osg.Material() color = osg.Vec4(1.0, 1.0, 1.0, 1.0) material.setDiffuse(osg.Material.FRONT_AND_BACK, color) material.setAmbient(osg.Material.FRONT_AND_BACK, color) camera.getOrCreateStateSet().setAttributeAndModes(material) camera.setClearColor(osg.Vec4(0, 0, 0, 0)) camera.setClearMask(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) camera.setCullMask(VISIBLE_CULL_MASK) if not self.gw: raise Exception("GraphicsWindow not yet created") self.camera = camera # viewer.getCamera().setViewport(osg.Viewport(0,0, self.width(), self.height())) # viewer.getCamera().addChild(camera) camera.setGraphicsContext(self.gw)
def camera_build(self): texture = self.texture_build() camera = osg.Camera() camera.setViewport(osg.Viewport(0, 0, self.width(), self.height())) camera.setReferenceFrame(osg.Transform.ABSOLUTE_RF) camera.setRenderOrder(osg.Camera.PRE_RENDER) camera.setRenderTargetImplementation(osg.Camera.FRAME_BUFFER_OBJECT) camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, 0, False, 0, 0) CAMERA_ANGLE = 45.0 CAMERA_Z_TRANSLATE = 2.4142135623730949 #1.0 / math.tan(math.radians(CAMERA_ANGLE / 2.0)) cameraPosition = [0.0, 0.0, CAMERA_Z_TRANSLATE] camera.setProjectionMatrixAsPerspective( CAMERA_ANGLE, float(self.width()) / float(self.height()), 0.1, 10000.0) eye = osg.Vec3d(cameraPosition[0], cameraPosition[1], cameraPosition[2]) center = osg.Vec3d(0, 0, 0) up = osg.Vec3d(0, 1, 0) camera.setViewMatrixAsLookAt(eye, center, up) camera.getOrCreateStateSet().setAttributeAndModes( osg.BlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA)) camera.getOrCreateStateSet().setMode(GL.GL_DEPTH_TEST, False) camera.getOrCreateStateSet().setMode(GL.GL_DEPTH_WRITEMASK, False) camera.getOrCreateStateSet().setMode(GL.GL_LIGHTING, False) material = osg.Material() color = osg.Vec4(1.0, 1.0, 1.0, 1.0) material.setDiffuse(osg.Material.FRONT_AND_BACK, color) material.setAmbient(osg.Material.FRONT_AND_BACK, color) camera.getOrCreateStateSet().setAttributeAndModes(material) camera.setClearColor(osg.Vec4(0, 0, 0, 0)) camera.setClearMask(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) return camera, texture
#load the model loadedModel = osgDB.readNodeFile("cow.osg") root = osg.Group() #create some dynamic transformation nodes dynamicTransform1 = osg.PositionAttitudeTransform() dynamicTransform2 = osg.PositionAttitudeTransform() dynamicTransform3 = osg.PositionAttitudeTransform() dynamicTransform4 = osg.PositionAttitudeTransform() #add the loaded model to the transform nodes dynamicTransform1.addChild(loadedModel) dynamicTransform1.setPosition(osg.Vec3d(-10, 0, -10)) dynamicTransform2.addChild(loadedModel) dynamicTransform2.setPosition(osg.Vec3d(-10, 0, 10)) dynamicTransform3.addChild(loadedModel) dynamicTransform3.setPosition(osg.Vec3d(10, 0, -10)) dynamicTransform4.addChild(loadedModel) dynamicTransform4.setPosition(osg.Vec3d(10, 0, 10)) #add the transform nodes to the scene root root.addChild(dynamicTransform1.__disown__()) root.addChild(dynamicTransform2.__disown__()) root.addChild(dynamicTransform3.__disown__()) root.addChild(dynamicTransform4.__disown__()) #to prevent direct destruction you can create a variable for the callback #rotcb = RotateCB()
def createPreRenderSubGraph(subgraph, tex_width, tex_height, renderImplementation, \ useImage, useTextureRectangle, useHDR, \ samples, colorSamples): if not subgraph: return 0 # create a group to contain the flag and the pre rendering camera. parent = osg.Group() #texture to render to and to use for rendering of flag. texture = 0 if (useTextureRectangle): textureRect = osg.TextureRectangle() textureRect.setTextureSize(tex_width, tex_height) textureRect.setInternalFormat(osg.GL_RGBA) textureRect.setFilter(osg.Texture2D.MIN_FILTER, osg.Texture2D.LINEAR) textureRect.setFilter(osg.Texture2D.MAG_FILTER, osg.Texture2D.LINEAR) texture = textureRect else: texture2D = osg.Texture2D() texture2D.setTextureSize(tex_width, tex_height) texture2D.setInternalFormat(osg.GL_RGBA) texture2D.setFilter(osg.Texture2D.MIN_FILTER, osg.Texture2D.LINEAR) texture2D.setFilter(osg.Texture2D.MAG_FILTER, osg.Texture2D.LINEAR) texture = texture2D if useHDR: texture.setInternalFormat(osg.GL_RGBA16F_ARB) texture.setSourceFormat(osg.GL_RGBA) texture.setSourceType(osg.GL_FLOAT) #first create the geometry of the flag of which to view. if True: # create the to visualize. polyGeom = osg.Geometry() polyGeom.setName("PolyGeom") polyGeom.setDataVariance(osg.Object.DYNAMIC) polyGeom.setSupportsDisplayList(False) origin = osg.Vec3(0.0, 0.0, 0.0) xAxis = osg.Vec3(1.0, 0.0, 0.0) yAxis = osg.Vec3(0.0, 0.0, 1.0) zAxis = osg.Vec3(0.0, -1.0, 0.0) height = 100.0 width = 200.0 noSteps = 20 vertices = osg.Vec3Array() bottom = osg.Vec3(origin[0], origin[1], origin[2]) top = osg.Vec3(origin[0], origin[1], origin[2]) top[2] += height dv = xAxis * (width / (float(noSteps - 1))) texcoords = osg.Vec2Array() # note, when we use TextureRectangle we have to scale the tex coords up to compensate. bottom_texcoord = osg.Vec2(0.0, 0.0) if useTextureRectangle: ltex_height = tex_height ltex_width = tex_width else: ltex_height = 1.0 ltex_width = 1.0 top_texcoord = osg.Vec2(0.0, ltex_height) dv_texcoord = osg.Vec2(ltex_width / float((noSteps - 1)), 0.0) for i in range(noSteps): vertices.push_back(top) vertices.push_back(bottom) top += dv bottom += dv texcoords.push_back(top_texcoord) texcoords.push_back(bottom_texcoord) top_texcoord += dv_texcoord bottom_texcoord += dv_texcoord # pass the created vertex array to the points geometry object. polyGeom.setVertexArray(vertices) polyGeom.setTexCoordArray(0, texcoords) colors = osg.Vec4Array() colors.push_back(osg.Vec4(1.0, 1.0, 1.0, 1.0)) polyGeom.setColorArray(colors) polyGeom.setColorBinding(osg.Geometry.BIND_OVERALL) polyGeom.addPrimitiveSet( osg.DrawArrays(osg.PrimitiveSet.QUAD_STRIP, 0, vertices.size())) # new we need to add the texture to the Drawable, we do so by creating a # StateSet to contain the Texture StateAttribute. stateset = osg.StateSet() stateset.setTextureAttributeAndModes(0, texture, osg.StateAttribute.ON) polyGeom.setStateSet(stateset) #changes to the geometry polyGeom.setUpdateCallback( MyGeometryCallback(origin, xAxis, yAxis, zAxis, 1.0, 1.0 / width, 0.2).__disown__()) geode = osg.Geode() geode.addDrawable(polyGeom) parent.addChild(geode) # then create the camera node to do the render to texture if True: camera = osg.Camera() # set up the background color and clear mask. camera.setClearColor(osg.Vec4(0.1, 0.1, 0.3, 1.0)) camera.setClearMask(osg.GL_COLOR_BUFFER_BIT | osg.GL_DEPTH_BUFFER_BIT) bs = subgraph.getBound() if not bs.valid(): return subgraph znear = 1.0 * bs.radius() zfar = 3.0 * bs.radius() # 2:1 aspect ratio as per flag geometry below. proj_top = 0.25 * znear proj_right = 0.5 * znear znear *= 0.9 zfar *= 1.1 # set up projection. camera.setProjectionMatrixAsFrustum(-proj_right, proj_right, -proj_top, proj_top, znear, zfar) # set view camera.setReferenceFrame(osg.Transform.ABSOLUTE_RF) camera.setViewMatrixAsLookAt(osg.Vec3d(bs.center())-osg.Vec3d(0.0,2.0,0.0)*bs.radius(), \ osg.Vec3d(bs.center()),\ osg.Vec3d(0.0,0.0,1.0)) # set viewport camera.setViewport(0, 0, tex_width, tex_height) # set the camera to render before the main camera. camera.setRenderOrder(osg.Camera.PRE_RENDER) # tell the camera to use OpenGL frame buffer object where supported. camera.setRenderTargetImplementation(renderImplementation) if useImage: image = osg.Image() #image.allocateImage(tex_width, tex_height, 1, GL_RGBA, GL_UNSIGNED_BYTE); image.allocateImage(tex_width, tex_height, 1, osg.GL_RGBA, osg.GL_FLOAT) # attach the image so its copied on each frame. camera.attach(osg.Camera.COLOR_BUFFER, image, samples, colorSamples) camera.setPostDrawCallback(MyCameraPostDrawCallback(image)) # Rather than attach the texture directly to illustrate the texture's ability to # detect an image update and to subload the image onto the texture. You needn't # do this when using an Image for copying to, as a separate camera.attach(..) # would suffice as well, but we'll do it the long way round here just for demonstration # purposes (long way round meaning we'll need to copy image to main memory, then # copy it back to the graphics card to the texture in one frame). # The long way round allows us to manually modify the copied image via the callback # and then let this modified image by reloaded back. texture.setImage(0, image) else: # attach the texture and use it as the color buffer. camera.attach(osg.Camera.COLOR_BUFFER, texture, 0, 0, False, samples, colorSamples) # add subgraph to render camera.addChild(subgraph) parent.addChild(camera) return parent
def main(): # use an ArgumentParser object to manage the program arguments. #arguments = osg.ArgumentParser() #construct the viewer. viewer = osgViewer.Viewer() #need to use singlethreaded mode viewer.setThreadingModel(viewer.SingleThreaded) # add the stats viewer.addEventHandler(osgViewer.StatsHandler()) # add the record camera path handler viewer.addEventHandler(osgViewer.RecordCameraPathHandler()) #add the threading handler viewer.addEventHandler(osgViewer.ThreadingHandler()) #if user request help write it out to cout. #if (arguments.read("-h") or arguments.read("--help")): # arguments.getApplicationUsage().write(sys.stdout) # return 1 tex_width = 1024 tex_height = 512 samples = 0 colorSamples = 0 renderImplementation = osg.Camera.FRAME_BUFFER_OBJECT useImage = False useTextureRectangle = False useHDR = False # if not loaded assume no arguments passed in, try use default mode instead. loadedModel = osgDB.readNodeFile("cessna.osg") # create a transform to spin the model. loadedModelTransform = osg.MatrixTransform() loadedModelTransform.addChild(loadedModel) nc = osg.AnimationPathCallback( osg.Vec3d(loadedModelTransform.getBound().center()), osg.Vec3d(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.ive") # add model to the viewer. viewer.setSceneData(rootNode) viewer.run()