void PhongMaterial::prepareLocalChunks(void) { if(_materialChunk != NullFC) return; _materialChunk = MaterialChunk::create(); addRefCP(_materialChunk); _blendChunk = BlendChunk::create(); addRefCP(_blendChunk); beginEditCP(_blendChunk); _blendChunk->setSrcFactor (GL_SRC_ALPHA); _blendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA); endEditCP (_blendChunk); // phong shading without a fragment shader looks quite black ;-) // all cards with a fragment shader should also have a vertex shader. // calling hasCommonExtension() here is not a good idea as this works // only for a initialized window, I added a check to hasCommonExtension() // so this won't crash anymore. if(Window::hasCommonExtension(_arbFragmentProgram)) { _vpChunk = VertexProgramChunk::create(); addRefCP(_vpChunk); beginEditCP(_vpChunk); _vpChunk->setProgram(_phong_vp_prg); endEditCP(_vpChunk); _fpChunk = FragmentProgramChunk::create(); addRefCP(_fpChunk); createFragmentProgram(); } }
void FaceSpatializeIndexed<BasicTraits>::CategoryRaw::addData (OpenSGFaceBase<OpenSGTraits>* node, const FaceIterator& face) { GeoPositions3f::StoredFieldType* p = m_coord->getFieldPtr(); GeoNormals3f::StoredFieldType* n = m_normal->getFieldPtr(); //GeoIndicesUI32::StoredFieldType* i = m_index->getFieldPtr(); // find offset of positions and normals in the new geometry u32 i, k; m_offsetIt = m_offset.find(face.getGeometry()); if (m_offsetIt == m_offset.end()) { // insert new offsets entry into map HashMapPair offsetPair = m_offset.insert(HashMap::value_type(face.getGeometry(), quad())); m_offsetIt = offsetPair.first; m_offsetIt->second.position = m_coord->size(); GeoPositionsPtr faceP = m_original.getPositions(); addRefCP(faceP); for (k=0; k<faceP->getSize(); ++k) { p->addValue(faceP->getValue(k)); } if (m_hasNormal) { m_offsetIt->second.normal = m_normal->size(); GeoNormalsPtr faceN = m_original.getNormals(); addRefCP(faceN); for (k=0; k<faceN->getSize(); ++k) { n->addValue(faceN->getValue(k)); } subRefCP(faceN); } subRefCP(faceP); } // insert indices if (face.getLength() == 3) { for (k=0; k<3; ++k) { m_index->insertValue(face.getPositionIndex(k)+m_offsetIt->second.position, m_quadOffset++); i = 1; if (m_hasNormal) { m_index->insertValue(face.getNormalIndex(k)+m_offsetIt->second.normal, m_quadOffset++); ++i; } for (; i<m_indexStride; ++i) { m_index->insertValue(0, m_quadOffset++); } } } else { for (k=0; k<4; ++k) { m_index->addValue(face.getPositionIndex(k)+m_offsetIt->second.position); i = 1; if (m_hasNormal) { m_index->addValue(face.getNormalIndex(k)+m_offsetIt->second.normal); ++i; } for (; i<m_indexStride; ++i) { m_index->addValue(0); } } } }
OSG_USING_NAMESPACE /*! \class osg::MaterialPool */ /*-------------------------------------------------------------------------*/ /* Sync */ void MaterialPool::changed(BitVector whichField, UInt32 origin) { if(origin & ChangedOrigin::Abstract) { MFMaterialPtr::iterator matIt = _mfMaterials.begin(); MFMaterialPtr::iterator matEnd = _mfMaterials.end (); while(matIt != matEnd) { addRefCP(*matIt); ++matIt; } } if(whichField & MaterialsFieldMask) { sync(); } Inherited::changed(whichField, origin); }
OSG_USING_NAMESPACE CScalarUnstructuredGrid::CScalarUnstructuredGrid(){ m_pXCutActor = vtkOsgActor::New(); m_pYCutActor = vtkOsgActor::New(); m_pZCutActor = vtkOsgActor::New(); m_pContourActor = vtkOsgActor::New(); //m_pvtkGridReader = vtkUnstructuredGridReader::New(); //m_pvtkGrid = NULL; m_pvtkDataSet = NULL; m_pvtkDataReader = NULL; m_pvtkXMLReader = NULL; m_pvtkXCutPlane = NULL; m_pvtkYCutPlane = NULL; m_pvtkZCutPlane = NULL; m_pvtkContourFilter = NULL; m_pvtkLookupTable = vtkLookupTable2D::New(); m_pvtkXSectionLookupTable = vtkLookupTable2D::New(); m_pvtkYSectionLookupTable = vtkLookupTable2D::New(); m_pvtkZSectionLookupTable = vtkLookupTable2D::New(); m_posgRoot = makeCoredNode<Group>(); addRefCP(m_posgRoot); }
void SimpleTexturedMaterial::prepareLocalChunks(void) { if(_textureChunk == NullFC) { _textureChunk = TextureChunk::create(); addRefCP(_textureChunk); } if(_texGenChunk == NullFC) { _texGenChunk = TexGenChunk::create(); addRefCP(_texGenChunk); } }
OSG_USING_NAMESPACE int main (int argc, char *argv[]) { osgInit(argc, argv); FieldContainerFactory::the()->setThrowInvalidPointerException(true); #ifdef OSG_INVALID_PTR_CHECK try { NodePtr planeNode1 = makePlane(2,2, 1,1); NodePtr planeNode2 = planeNode1; addRefCP(planeNode1); subRefCP(planeNode1); if(planeNode1 == NullFC) { printf("planeNode1 == NullFC\n"); } // now call subRefCP on a NullFC pointer! subRefCP(planeNode1); // now call subRefCP on a invalid pointer! subRefCP(planeNode2); NodePtr planeNode3 = makePlane(2,2, 1,1); NodePtr planeNode4 = planeNode3; addRefCP(planeNode3); subRefCP(planeNode3); NodeCorePtr core1 = planeNode4->getCore(); NodeCorePtr core2 = planeNode3->getCore(); } catch(InvalidPointerException &e) { printf("error: '%s'\n", e.what()); } #endif return 0; }
void MultiPassMaterial::addMaterial(MaterialPtr mat) { if(mat == NullFC) return; _mfMaterials.push_back(mat); addRefCP(mat); }
//! Add a clip object void DVRClipObjects::add(DVRClipGeometryPtr obj) { if(obj == NullFC) return; addRefCP(obj); _mfClipObjects.push_back(obj); }
void FaceSpatialize<BasicTraits>::CategoryRaw::addData (OpenSGFaceBase<OpenSGTraits>* node, const FaceIterator& face) { GeoPositions3f::StoredFieldType* p = m_coord->getFieldPtr(); GeoNormals3f::StoredFieldType* n = m_normal->getFieldPtr(); //GeoIndicesUI32::StoredFieldType* i = m_index->getFieldPtr(); GeoPositionsPtr faceP = node->getPositions(); addRefCP(faceP); u32 k; for (k=0; k<faceP->getSize(); ++k) { p->addValue(faceP->getValue(k)); if (face.getLength()==3) { m_index->insertValue(p->size()-1, m_quadOffset++); } else { m_index->addValue(p->size()-1); } } if (!m_hasNormal) { #if 1 Vec3f p0(faceP->getValue(0)); Vec3f p1(faceP->getValue(1)); Vec3f p2(faceP->getValue(2)); p2 -= p1; p0 -= p1; if (m_ccw) { p0.crossThis(p2); p0.normalize(); n->addValue(p0); } else { p2.crossThis(p0); p2.normalize(); n->addValue(p2); } #endif } else { // per-vertex normals or per-face normals GeoNormalsPtr faceN = node->getNormals(); addRefCP(faceN); for (k=0; k<faceN->getSize(); ++k) { n->addValue(faceN->getValue(k)); } subRefCP(faceN); } subRefCP(faceP); }
void MaterialPool::add(const MaterialPtr &mat) { if(mat == NullFC) return; if(_mats.count(mat) > 0) return; addRefCP(mat); _mats.insert(mat); _mfMaterials.push_back(mat); }
void MultiPassMaterial::changed(BitVector whichField, UInt32 origin) { if(origin & ChangedOrigin::Abstract) { MFMaterialPtr::iterator matIt = _mfMaterials.begin(); MFMaterialPtr::iterator matEnd = _mfMaterials.end (); while(matIt != matEnd) { addRefCP(*matIt); ++matIt; } } Inherited::changed(whichField, origin); }
OSG_USING_NAMESPACE CParticleEmitter::CParticleEmitter( CParticleSystem *i_pParent, CParticleType *i_pParticleType ) : m_pParent( i_pParent ), m_pParticleType( i_pParticleType ), m_rEmissionRemainder( 0.0f ), m_nextMovement( 0.0f, 0.0f, 0.0f ) { // set timeline defaults (which are not 0) m_emissionDirection.SetDefaultValue( Vec3f( 0.0f, 1.0f, 0.0f ) ); m_emissionRate.SetDefaultValue( 10.0f ); m_lifeTime.SetDefaultValue( 2.0f ); m_size.SetDefaultValue( 1.0f ); m_velocity.SetDefaultValue( 1.0f ); m_color.SetDefaultValue( Vec3f( 1.0f, 0.0f, 1.0f ) ); m_pDrawableParticles = Particles::create(); beginEditCP( m_pDrawableParticles ); { m_pDrawableParticles->setMode( Particles::ViewerQuads ); m_pDrawableParticles->setDrawOrder( m_pParticleType->bGetAdditive() ? Particles::Any : Particles::BackToFront ); m_pDrawableParticles->setDynamic( true ); m_pDrawableParticles->setMaterial( m_pParticleType->pGetMaterial() ); m_pDrawableParticles->setPositions( GeoPositions3f::create() ); m_pDrawableParticles->setColors( GeoColors3f::create() ); } endEditCP( m_pDrawableParticles ); m_pNode = Node::create(); addRefCP( m_pNode ); beginEditCP( m_pNode ); { m_pNode->setCore( m_pDrawableParticles ); m_pNode->updateVolume(); // set volume static to prevent constant update Volume &v = m_pNode->getVolume( false ).getInstance(); v.setEmpty(); v.extendBy( Pnt3f( 0, 0, 0 ) ); v.extendBy( Pnt3f( 1, 1, 1 ) ); v.setStatic(); ((DynamicVolume&)m_pNode->getVolume()).instanceChanged(); } endEditCP( m_pNode ); }
void ScanParseSkel::beginImage(Int32 width, Int32 height, Int32 components) { if (_image == NullFC) { _image = Image::create(); addRefCP(_image); } UInt32 pixelFormat; switch (components) { case 1: pixelFormat = Image::OSG_L_PF; break; case 2: pixelFormat = Image::OSG_LA_PF; break; case 3: pixelFormat = Image::OSG_RGB_PF; break; case 4: pixelFormat = Image::OSG_RGBA_PF; break; default: pixelFormat = Image::OSG_INVALID_PF; break; } _image->set(pixelFormat, width, height); _imageDataPtr = _image->editData(); _pLexer->expectImageInts(width * height); }
Action::ResultE SplitGraphOp::traverseLeave(NodePtr& node, Action::ResultE res) { std::vector<NodePtr>::iterator it = node->editMFChildren()->getValues().begin(); std::vector<NodePtr>::iterator en = node->editMFChildren()->getValues().end (); std::vector<NodePtr> toAdd; std::vector<NodePtr> toSub; for ( ; it != en; ++it ) { bool special=isInExcludeList(*it); bool leaf=isLeaf(*it); if (!special && leaf) { if (splitNode(*it, toAdd)) toSub.push_back(*it); } } it = toAdd.begin(); en = toAdd.end (); for ( ; it != en; ++it ) { beginEditCP(node, Node::ChildrenFieldMask); node->addChild(*it); endEditCP (node, Node::ChildrenFieldMask); } it = toSub.begin(); en = toSub.end (); for ( ; it != en; ++it ) { beginEditCP(node, Node::ChildrenFieldMask); addRefCP(*it); node->subChild(*it); endEditCP (node, Node::ChildrenFieldMask); } return res; }
/*! Set up new Transform (Group) Node for starting block. */ DXFResult DXFBlock::beginEntity(void) { DXFResult state; state = Inherited::beginEntity(); // clear DXFBlocks data _layerName = ""; _blockName = ""; _basePoint.setNull(); _blockNodeP = Node::create(); // TODO: check for success! != // NullFC! TransformPtr trfCore = Transform::create(); beginEditCP(_blockNodeP); _blockNodeP->setCore(trfCore); addRefCP(_blockNodeP); return state; }
OSG_USING_NAMESPACE OpenSGEnvironmentSceneGraphAttachment::OpenSGEnvironmentSceneGraphAttachment() { envGroupeNode = Node::create(); envTransNode = Node::create(); envTransCore = Transform::create(); #if OSG_MAJOR_VERSION >= 2 envGroupeNode->setCore(Group::create()); Matrix4f temp; temp.setIdentity(); envTransCore->setMatrix(temp); envTransNode->setCore(envTransCore); envTransNode->addChild(envGroupeNode); #else //OpenSG1: beginEditCP(envGroupeNode, Node::CoreFieldMask); envGroupeNode->setCore(Group::create()); endEditCP(envGroupeNode, Node::CoreFieldMask); Matrix4f temp; temp.setIdentity(); beginEditCP(envTransCore); envTransCore->setMatrix(temp); endEditCP(envTransCore); beginEditCP(envTransNode, Node::CoreFieldMask | Node::ChildrenFieldMask); envTransNode->setCore(envTransCore); envTransNode->addChild(envGroupeNode); endEditCP(envTransNode, Node::CoreFieldMask | Node::ChildrenFieldMask); addRefCP(envTransNode); #endif } // OpenSGEnvironmentSceneGraphAttachment
virtual void redraw( void ) { static bool first=true; static RenderNode rn; int i; double tbalance; GeoLoadManager::ResultT region; if (_internalRoot == NullFC) { initialize(); showAll(); } _cart->getSFMatrix()->setValue(_navigator.getMatrix()); updateHighlight(); _win->activate(); _win->frameInit(); if(first) { loadManager=new GeoLoadManager(useFaceDistribution); first=false; rn.determinePerformance(_win); } if(_win->getPort().size() < (serverCount+1)) { ViewportPtr vp,ovp=_win->getPort(0); addRefCP(ovp); addRefCP(ovp); TileCameraDecoratorPtr deco; for(int i=_win->getPort().size()-1;i<serverCount;i++) { cout << "Add new" << endl; loadManager->addRenderNode(rn,i); if(simulateRendering) { beginEditCP(_win); deco=TileCameraDecorator::create(); beginEditCP(deco); deco->setFullWidth ( _win->getWidth() ); deco->setFullHeight( _win->getHeight() ); deco->setDecoratee( ovp->getCamera() ); vp=Viewport::create(); beginEditCP(vp); vp->setRoot ( ovp->getRoot() ); /* SkyBackgroundPtr sky = SkyBackground::create(); beginEditCP(sky); sky->setSphereRes(16); sky->getMFSkyColor()->addValue(Color3f(0, 0, .2)); sky->getMFSkyAngle()->addValue(Pi / 2); sky->getMFSkyColor()->addValue(Color3f(.6, .6, 1)); sky->getMFGroundColor()->addValue(Color3f(0, .3, 1)); sky->getMFGroundAngle()->addValue(Pi / 2); sky->getMFGroundColor()->addValue(Color3f(1, .3, 0)); endEditCP(sky); vp->setBackground( sky ); */ vp->setBackground( ovp->getBackground() ); vp->getMFForegrounds()->setValues( ovp->getForegrounds() ); vp->setCamera(deco); _win->addPort(vp); endEditCP(_win); endEditCP(vp); endEditCP(deco); } } } tbalance = -getSystemTime(); loadManager->update(_win->getPort()[0]->getRoot()); loadManager->balance(_win->getPort()[0],false,region); tbalance += getSystemTime(); if(simulateRendering) { ViewportPtr vp; TileCameraDecoratorPtr deco; for(i=0;i<region.size();i+=4) { #if 1 cout << "Region: " << i << " "; cout << region[i+0] << " "; cout << region[i+1] << " "; cout << region[i+2] << " "; cout << region[i+3] << endl; if(region[i+0] >= region[i+2]) { cout << "!!!" << endl; region[i+2]++; } if(region[i+1] >= region[i+3]) { cout << "!!!" << endl; region[i+3]++; } #endif vp=_win->getPort()[i/4+1]; deco=TileCameraDecoratorPtr::dcast(vp->getCamera()); beginEditCP(deco); beginEditCP(vp); vp->setSize(region[i+0], region[i+1], region[i+2], region[i+3]); deco->setSize(region[i+0]/(float)_win->getWidth(), region[i+1]/(float)_win->getHeight(), region[i+2]/(float)_win->getWidth(), region[i+3]/(float)_win->getHeight()); endEditCP(deco); endEditCP(vp); } } Time t,tmin,tmax; for(i=0;i<_win->getPort().size();++i) { t=-getSystemTime(); _action->setWindow( _win.getCPtr() ); _win->getPort(i)->render( _action ); glFlush(); t+=getSystemTime(); if(i==0) continue; if(i==1) { tmin=tmax=t; } else { if(t<tmin) tmin=t; if(t>tmax) tmax=t; } } if(!cache) printf("speed %5d %10.6f %10.6f %10.6f\n",_win->getPort().size()-1, tmin, tmax, tbalance); glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_SCISSOR_TEST); glViewport(0,0, _win->getWidth(), _win->getHeight()); if(viewVolume) loadManager->drawVolumes(_win); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0,_win->getWidth(), 0,_win->getHeight()); glDisable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); for(i=0;i<region.size();i+=4) { #if 0 cout << "Region: "; cout << region[i+0] << " "; cout << region[i+1] << " "; cout << region[i+2] << " "; cout << region[i+3] << endl; #endif glBegin(GL_LINE_LOOP); glColor3f(1, 1, 0); glVertex3f(region[i+0],region[i+1],0); glVertex3f(region[i+2],region[i+1],0); glVertex3f(region[i+2],region[i+3],0); glVertex3f(region[i+0],region[i+3],0); glEnd(); } glDisable(GL_COLOR_MATERIAL); glEnable(GL_DEPTH_TEST); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glPopAttrib(); if(doSave) { Int32 w,h; w=_win->getPort(0)->getPixelWidth(); h=_win->getPort(0)->getPixelHeight(); Image image(Image::OSG_RGB_PF, w,h,1, 1,1,0.0, NULL,true); ImageFileType *imgTransType=ImageFileHandler::the().getFileType("JPEG"); char filename[256]; if(imgTransType==NULL) { cerr << "Unknown image trans type" << endl; return; } sprintf(filename,"%s_%d.jpg",dumpImage,dumpImageNr++); // read buffer data into image glPixelStorei(GL_PACK_ALIGNMENT,1); glReadPixels(0,0,w,h, GL_RGB,GL_UNSIGNED_BYTE, image.getData()); imgTransType->write(image,filename); } _win->swap(); _win->frameExit(); }
// setup state for shading with fragment program void DVRIsoShader::activate_FragmentProgramShading(DVRVolume *volume, DrawActionBase *action) { // Initialize the fragment program if(m_pFragProg == NullFC) { FDEBUG(("Initializing fragment program ")); m_pFragProg = FragmentProgramChunk::create(); addRefCP( m_pFragProg ); FDEBUG((" - DONE\n")); // Load the appropriate program switch(m_shadingMode) { case SM_FRAGMENT_PROGRAM_3D: // SLOG << "Loading ... isoFragProg3D.asm" << std::endl; beginEditCP(m_pFragProg); { m_pFragProg->setProgram(_fragProg3D); // m_pFragProg->read( "isoFragProg3D.asm" ); } endEditCP (m_pFragProg); break; case SM_FRAGMENT_PROGRAM_2D: // SLOG << "Loading ... isoFragProg2D.asm" << std::endl; beginEditCP(m_pFragProg); { m_pFragProg->setProgram(_fragProg2D); // m_pFragProg->read( "isoFragProg2D.asm" ); } endEditCP(m_pFragProg); break; default: FFATAL(("Texture mode for fragment programs not supported " "by DVRSimpleLUTShader")); return; // break; } } // get parameters from isosurface attachment if available Real32 isoValue; UInt32 alphaMode; bool doSpecular; DVRIsoSurfacePtr isoParam = DVRVOLUME_PARAMETER(volume, DVRIsoSurface); if(isoParam != NullFC) { isoValue = isoParam->getIsoValue (); alphaMode = isoParam->getAlphaMode (); doSpecular = isoParam->getSpecularLighting(); } else { isoValue = 1.0; alphaMode = GL_GREATER; doSpecular = false; } unsigned int maxDiffuseLights = 6; // Hard-coded in the fragment program unsigned int maxSpecularLights = 6; // Set light parameters DirLightList diffuseLights; DirLightList specularLights; Color4f ambientLight; getLightSources(diffuseLights, specularLights, ambientLight); beginEditCP(m_pFragProg, ProgramChunk::ParamValuesFieldMask); { m_pFragProg->setParameter(static_cast<short int>(0), cToV(ambientLight)); // ambient color // Diffuse lights unsigned int i; DirLightList::iterator l = diffuseLights.begin(); for(i = 0; i < maxDiffuseLights && l != diffuseLights.end(); i++) { Vec3f tmp; Slicer::rotateToLocal(action,l->dir,tmp); tmp.normalize(); // diffuse direction m_pFragProg->setParameter(1 + 2 * i, Vec4f(tmp)); // diffuse color m_pFragProg->setParameter(1 + 2 * i + 1, cToV(l->color)); ++l; } for(; i < maxDiffuseLights; i++) { // diffuse direction m_pFragProg->setParameter(1 + 2 * i, Vec4f(0, 0, 0, 0)); // diffuse color m_pFragProg->setParameter(1 + 2 * i + 1, Vec4f(0, 0, 0, 0)); } // Specular lights unsigned int firstSpecId = 1 + 2 * maxDiffuseLights; i = 0; if(doSpecular) { // get and classify the slicing direction Vec3f viewDir; Slicer::getSlicingDirection(action, &viewDir); viewDir.normalize(); DirLightList::iterator ls = specularLights.begin(); for(i = 0; i < maxSpecularLights && ls != specularLights.end(); i++) { Vec3f tmp; Slicer::rotateToLocal(action,ls->dir,tmp); tmp.normalize(); // calc halfway tmp += viewDir; tmp.normalize(); // halfway vector m_pFragProg->setParameter(firstSpecId + 2 * i, Vec4f(tmp)); // specular color m_pFragProg->setParameter(firstSpecId + 2 * i + 1, cToV(ls->color)); ++ls; } } for(; i < maxSpecularLights; i++) { // specular direction m_pFragProg->setParameter(firstSpecId + 2 * i, Vec4f(0, 0, 0, 0)); // specular color m_pFragProg->setParameter(firstSpecId + 2 * i + 1, Vec4f(0, 0, 0, 0)); } } endEditCP(m_pFragProg, ProgramChunk::ParamValuesFieldMask); glPushAttrib(GL_ENABLE_BIT); // activate fragment program chunk m_pFragProg->activate(action); // no blending and lighting glDisable(GL_BLEND ); glDisable(GL_LIGHTING); // Enable Alpha Test for isosurface glEnable (GL_ALPHA_TEST ); glAlphaFunc(alphaMode, isoValue); }
// Initialize GLUT & OpenSG and set up the scene int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // Set up Window TutorialWindowEventProducer = createDefaultWindowEventProducer(); WindowPtr MainWindow = TutorialWindowEventProducer->initWindow(); TutorialWindowEventProducer->setDisplayCallback(display); TutorialWindowEventProducer->setReshapeCallback(reshape); //Add Window Listener TutorialKeyListener TheKeyListener; TutorialWindowEventProducer->addKeyListener(&TheKeyListener); TutorialMouseListener TheTutorialMouseListener; TutorialMouseMotionListener TheTutorialMouseMotionListener; TutorialWindowEventProducer->addMouseListener(&TheTutorialMouseListener); TutorialWindowEventProducer->addMouseMotionListener(&TheTutorialMouseMotionListener); // Create the SimpleSceneManager helper mgr = new SimpleSceneManager; // Tell the Manager what to manage mgr->setWindow(TutorialWindowEventProducer->getWindow()); Path FBOFilePath; if(argc < 2) { FWARNING(("No FBO file given!\n")); FBOFilePath = Path("./Data/01LoadFBO.xml"); } else { FBOFilePath = Path(std::string(argv[1])); } std::cout << "Loading xml File: " << FBOFilePath << std::endl; FCFileType::FCPtrStore NewContainers; NewContainers = FCFileHandler::the()->read(FBOFilePath); FCFileType::FCPtrStore::iterator Itor; for(Itor = NewContainers.begin() ; Itor != NewContainers.end() ; ++Itor) { if( (*Itor)->getType() == FBOViewport::getClassType()) { TheFBOViewport = FBOViewport::Ptr::dcast(*Itor); } } ChunkMaterialPtr BoxMaterial = ChunkMaterial::create(); GeometryPtr BoxGeoCore = makeBoxGeo(1.0,1.0,1.0,2,2,2); beginEditCP(BoxGeoCore, Geometry::MaterialFieldMask); BoxGeoCore->setMaterial(BoxMaterial); endEditCP(BoxGeoCore, Geometry::MaterialFieldMask); NodePtr BoxGeoNode = Node::create(); beginEditCP(BoxGeoNode, Node::CoreFieldMask); BoxGeoNode->setCore(BoxGeoCore); endEditCP(BoxGeoNode, Node::CoreFieldMask); NodePtr SceneNode = Node::create(); beginEditCP(SceneNode, Node::CoreFieldMask | Node::ChildrenFieldMask); SceneNode->setCore(Group::create()); SceneNode->addChild(BoxGeoNode); endEditCP(SceneNode, Node::CoreFieldMask | Node::ChildrenFieldMask); // tell the manager what to manage mgr->setRoot (SceneNode); // show the whole scene mgr->showAll(); if(TheFBOViewport != NullFC) { //Add the texture chunk of the FBO to the Material for the box beginEditCP(BoxMaterial, ChunkMaterial::ChunksFieldMask); BoxMaterial->addChunk(TheFBOViewport->editTextures(0)); endEditCP(BoxMaterial, ChunkMaterial::ChunksFieldMask); //Add The FBO Viewport the the Window beginEditCP(TheFBOViewport, FBOViewport::ParentFieldMask); TheFBOViewport->setParent(TutorialWindowEventProducer->getWindow()); endEditCP(TheFBOViewport, FBOViewport::ParentFieldMask); beginEditCP(TutorialWindowEventProducer->getWindow()); ViewportPtr vp = TutorialWindowEventProducer->getWindow()->getPort(0); addRefCP(vp); TutorialWindowEventProducer->getWindow()->subPort(0); //Put the FBO Vieport in front, so it is rendered first TutorialWindowEventProducer->getWindow()->addPort(TheFBOViewport); TutorialWindowEventProducer->getWindow()->addPort(vp ); endEditCP (TutorialWindowEventProducer->getWindow()); } Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f); Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5); TutorialWindowEventProducer->openWindow(WinPos, WinSize, "07LoadFBO"); //Main Loop TutorialWindowEventProducer->mainLoop(); osgExit(); return 0; }
virtual void initialize(void) { // Check necessary stuff if(_win == NullFC) { FWARNING(("SceneManager::initialize: window not set, " "ignoring!\n")); return; } // the rendering action _ownAction = RenderAction::create(); _action = _ownAction; // the camera and light beacon NodePtr cartN = Node::create(); _cart = Transform::create(); beginEditCP(cartN); cartN->setCore(_cart); endEditCP(cartN); // the headlight _internalRoot = Node::create(); _headlight = DirectionalLight::create(); addRefCP(_internalRoot); beginEditCP(_internalRoot); _internalRoot->setCore(_headlight); _internalRoot->addChild(cartN); endEditCP(_internalRoot); beginEditCP(_headlight); _headlight->setAmbient (.3, .3, .3, 1); _headlight->setDiffuse ( 1, 1, 1, 1); _headlight->setSpecular ( 1, 1, 1, 1); _headlight->setDirection( 0, 0, 1); _headlight->setBeacon (cartN); endEditCP(_headlight); // the camera _camera = PerspectiveCamera::create(); addRefCP(_camera); beginEditCP(PerspectiveCameraPtr::dcast(_camera)); PerspectiveCameraPtr::dcast(_camera)->setBeacon(cartN); PerspectiveCameraPtr::dcast(_camera)->setFov (deg2rad(60.f)); PerspectiveCameraPtr::dcast(_camera)->setNear (0.1f); PerspectiveCameraPtr::dcast(_camera)->setFar (10000.f); endEditCP(PerspectiveCameraPtr::dcast(_camera)); // need a viewport? if(_win->getPort().size() == 0) { SolidBackgroundPtr bg = SolidBackground::create(); beginEditCP(bg); bg->setColor(Color3f(0, 0, 0)); endEditCP(bg); ViewportPtr vp = Viewport::create(); beginEditCP(vp); vp->setCamera (_camera); vp->setRoot (_internalRoot); vp->setSize (0,0, 1,1); vp->setBackground (bg); endEditCP(vp); beginEditCP(_win); _win->addPort(vp); endEditCP(_win); } }
void SpaceNavigatorSSM::mouseButtonPress(UInt16 button, Int16 x, Int16 y) { switch (button) { case MouseLeft: // test if an object is picked if(_objectPicking) { Line ray = calcViewRay(x, y); IntersectAction *iAct = IntersectAction::create(); iAct->setLine(ray); iAct->apply(this->getRoot()); // we have a hit if(iAct->didHit()) { _pickedObjectNode = iAct->getHitObject(); #ifdef SPACENAVIGATOR_DEBUG_OUTPUT std::cout << "SpaceNavigatorSSM: Object transformation mode active ( " << getName(_pickedObjectNode) << " )" << std::endl; #endif // SPACENAVIGATOR_DEBUG_OUTPUT // go up in the graph to the next transformation while(!_pickedObjectNode->getCore()->getType().isDerivedFrom(Transform::getClassType())) { if(_pickedObjectNode->getParent() != this->getRoot()) _pickedObjectNode = _pickedObjectNode->getParent(); else { // insert a new transformation node NodePtr pickedObject = iAct->getHitObject(); TransformPtr newTransform = Transform::create(); Matrix m; m.setIdentity(); beginEditCP(newTransform, Transform::MatrixFieldMask); newTransform->setMatrix(m); endEditCP(newTransform, Transform::MatrixFieldMask); NodePtr newTransformNode = Node::create(); beginEditCP(newTransformNode, Node::CoreFieldMask); newTransformNode->setCore(newTransform); endEditCP(newTransformNode, Node::CoreFieldMask); NodePtr pickedObjectParent = pickedObject->getParent(); // add reference because reCount would be 0 and then it will // be deleted addRefCP(pickedObject); beginEditCP(pickedObjectParent); pickedObjectParent->replaceChildBy(pickedObject, newTransformNode); endEditCP(pickedObjectParent); beginEditCP(newTransformNode); newTransformNode->addChild(pickedObject); endEditCP(newTransformNode); // sub the reference which was added before subRefCP(pickedObject); _pickedObjectNode = newTransformNode; } } // a transformation was found and the objects bounding box is showed this->setHighlight(_pickedObjectNode); } } _navigator.buttonPress(Navigator::LEFT_MOUSE,x,y); break; case MouseMiddle: _navigator.buttonPress(Navigator::MIDDLE_MOUSE,x,y); break; case MouseRight: // release picked object and switch off bounding box rendering if(_objectPicking) { _pickedObjectNode = NullFC; this->setHighlight(NullFC); #ifdef SPACENAVIGATOR_DEBUG_OUTPUT std::cout << "SpaceNavigatorSSM: Camera transformation mode active" << std::endl; #endif // SPACENAVIGATOR_DEBUG_OUTPUT } _navigator.buttonPress(Navigator::RIGHT_MOUSE,x,y); break; case MouseUp: _navigator.buttonPress(Navigator::UP_MOUSE,x,y); break; case MouseDown: _navigator.buttonPress(Navigator::DOWN_MOUSE,x,y); break; } _mousebuttons |= 1 << button; _lastx = x; _lasty = y; }
int main(int argc, char **argv) { osgInit(argc,argv); // GLUT init glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); int id=glutCreateWindow("OpenSG"); glutReshapeFunc(reshape); glutDisplayFunc(display); glutIdleFunc(display); glutMouseFunc(mouse); glutMotionFunc(motion); glutKeyboardFunc(keyboard); GLUTWindowPtr gwin=GLUTWindow::create(); gwin->setId(id); gwin->init(); // create the scene // NodePtr scene = makeTorus(.5, 2, 16, 16); NodePtr scene = makeBox(1,1,1, 1,1,1); // create the SimpleSceneManager helper mgr = new SimpleSceneManager; // tell the manager what to manage mgr->setWindow(gwin ); mgr->setRoot (scene); // Create the textured material UChar8 imgdata[] = { 255,0,0,128, 0,255,0,128, 0,0,255,255, 255,255,255,255 }; ImagePtr img = Image::create(); beginEditCP(img); if(argc > 1) img->read(argv[1]); else img->set( Image::OSG_RGBA_PF, 2, 2, 1, 1, 1, 0, imgdata ); endEditCP(img); addRefCP(img); SimpleTexturedMaterialPtr mat = SimpleTexturedMaterial::create(); beginEditCP(mat); mat->setLit(false); mat->setDiffuse(Color3f(0,1,0)); mat->setImage(img); mat->setMinFilter(GL_NEAREST); mat->setMagFilter(GL_NEAREST); mat->setEnvMode(GL_REPLACE); endEditCP(mat); // Add the polygon foregrounds Pnt2f pos[][4] = { { Vec2f(.4,.4), Vec2f(.6,.4), Vec2f(.6,.6), Vec2f(.4,.6) }, { Vec2f(0,0), Vec2f(1,0), Vec2f(1,.1), Vec2f(0,.1) }, { Vec2f(1,-100), Vec2f(-2,-100), Vec2f(-2,-2), Vec2f(1,-2) }, { Vec2f(-1000,-1000), Vec2f(0,0), Vec2f(0,0), Vec2f(0,0) } }; bool normx[] = { true, true, false }; bool normy[] = { true, true, false }; for(UInt16 ind = 0; pos[ind][0][0] != -1000; ++ind) { PolygonForegroundPtr pg = PolygonForeground::create(); beginEditCP(pg); pg->setMaterial(mat); pg->editMFTexCoords()->push_back(Vec3f( 0.,0.,0.)); pg->editMFPositions()->push_back(pos[ind][0]); pg->editMFTexCoords()->push_back(Vec3f( 1.,0.,0.)); pg->editMFPositions()->push_back(pos[ind][1]); pg->editMFTexCoords()->push_back(Vec3f( 1.,1.,0.)); pg->editMFPositions()->push_back(pos[ind][2]); pg->editMFTexCoords()->push_back(Vec3f( 0.,1.,0.)); pg->editMFPositions()->push_back(pos[ind][3]); pg->setNormalizedX(normx[ind]); pg->setNormalizedY(normy[ind]); endEditCP(pg); // take the viewport ViewportPtr vp = gwin->getPort(0); beginEditCP(vp); vp->editMFForegrounds()->push_back(pg); endEditCP (vp); } // Create the edgeblend foreground const int blendpixel = 50; UChar8 ebimgdata[] = { 0,0,0,0, 0,0,0,255 }; ImagePtr ebimg = Image::create(); beginEditCP(ebimg); ebimg->set( Image::OSG_RGBA_PF, 2, 1, 1, 1, 1, 0, ebimgdata ); endEditCP(ebimg); addRefCP(ebimg); TextureChunkPtr tc = TextureChunk::create(); beginEditCP(tc); tc->setImage(ebimg); tc->setMinFilter(GL_NEAREST); tc->setMagFilter(GL_LINEAR); tc->setEnvMode(GL_REPLACE); tc->setWrapS(GL_CLAMP); endEditCP(tc); BlendChunkPtr bl = BlendChunk::create(); beginEditCP(bl); bl->setSrcFactor(GL_SRC_ALPHA); bl->setDestFactor(GL_ONE_MINUS_SRC_ALPHA); endEditCP(bl); ChunkMaterialPtr ebmat = ChunkMaterial::create(); beginEditCP(ebmat); ebmat->addChunk(tc); ebmat->addChunk(bl); endEditCP(ebmat); PolygonForegroundPtr ebpg = PolygonForeground::create(); beginEditCP(ebpg); ebpg->setMaterial(ebmat); ebpg->editMFTexCoords()->push_back(Vec3f( 0.25,0.,0.)); ebpg->editMFTexCoords()->push_back(Vec3f( 0.75,0.,0.)); ebpg->editMFTexCoords()->push_back(Vec3f( 0.75,1.,0.)); ebpg->editMFTexCoords()->push_back(Vec3f( 0.25,1.,0.)); ebpg->editMFPositions()->push_back(Pnt2f(-blendpixel-1, 0)); ebpg->editMFPositions()->push_back(Pnt2f( -1, 0)); ebpg->editMFPositions()->push_back(Pnt2f( -1, 1)); ebpg->editMFPositions()->push_back(Pnt2f(-blendpixel-1, 1)); ebpg->setNormalizedX(false); ebpg->setNormalizedY(true); endEditCP(ebpg); // take the viewport ViewportPtr vp = gwin->getPort(0); beginEditCP(vp); vp->editMFForegrounds()->push_back(ebpg); endEditCP (vp); // show the whole scene mgr->showAll(); // GLUT main loop glutMainLoop(); return 0; }
PCSSShadowMap::PCSSShadowMap(ShadowViewport *source) : TreeRenderer(source), _tiledeco(NullFC), _colorMap(NullFC), _shadowFactorMap(NullFC), _colorMapImage(NullFC), _shadowFactorMapImage(NullFC), _shadowCmat(NullFC), _shadowSHL(NullFC), _combineSHL(NullFC), _combineDepth(NullFC), _pf(NullFC), _firstRun(1), _width(1), _height(1), _widthHeightPOT(0), _fb(0), _fb2(0), _rb_depth(0), _initTexturesDone(false) { if(_shadowVP->getParent() != NullFC) { _width = _shadowVP->getPixelWidth(); _height = _shadowVP->getPixelHeight(); } if(_width == 0) _width = 1; if(_height == 0) _height = 1; if(_width > _height) _widthHeightPOT = osgnextpower2(_width - 1); else _widthHeightPOT = osgnextpower2(_height - 1); _tiledeco = NullFC; //Prepare Color Map grabbing _colorMap = TextureChunk::create(); _colorMapImage = Image::create(); beginEditCP(_colorMap); _colorMap->setImage(_colorMapImage); _colorMap->setInternalFormat(COLORMAP_FORMAT); _colorMap->setExternalFormat(COLORMAP_FORMAT); _colorMap->setMinFilter(GL_NEAREST); _colorMap->setMagFilter(GL_NEAREST); _colorMap->setWrapS(GL_REPEAT); _colorMap->setWrapT(GL_REPEAT); _colorMap->setTarget(GL_TEXTURE_2D); endEditCP(_colorMap); if(_useNPOTTextures) { beginEditCP(_colorMapImage); _colorMapImage->set(COLORMAP_FORMAT, _width, _height); endEditCP(_colorMapImage); } else { beginEditCP(_colorMapImage); _colorMapImage->set(COLORMAP_FORMAT, _widthHeightPOT, _widthHeightPOT); endEditCP(_colorMapImage); } //Prepare Shadow Factor Map grabbing _shadowFactorMap = TextureChunk::create(); _shadowFactorMapImage = Image::create(); beginEditCP(_shadowFactorMap); _shadowFactorMap->setImage(_shadowFactorMapImage); _shadowFactorMap->setInternalFormat(GL_RGB); _shadowFactorMap->setExternalFormat(GL_RGB); _shadowFactorMap->setMinFilter(GL_LINEAR); _shadowFactorMap->setMagFilter(GL_LINEAR); _shadowFactorMap->setWrapS(GL_REPEAT); _shadowFactorMap->setWrapT(GL_REPEAT); _shadowFactorMap->setTarget(GL_TEXTURE_2D); endEditCP(_shadowFactorMap); if(_useNPOTTextures) { beginEditCP(_shadowFactorMapImage); _shadowFactorMapImage->set(GL_RGB, _width, _height); endEditCP(_shadowFactorMapImage); } else { beginEditCP(_shadowFactorMapImage); _shadowFactorMapImage->set(GL_RGB, _widthHeightPOT, _widthHeightPOT); endEditCP(_shadowFactorMapImage); } //SHL Chunk 1 _shadowSHL = SHLChunk::create(); beginEditCP(_shadowSHL); //_shadowSHL->readVertexProgram("PCSS_Shadow.vert"); //_shadowSHL->readFragmentProgram("PCSS_Shadow.frag"); _shadowSHL->setVertexProgram(_pcss_shadow_vp); _shadowSHL->setFragmentProgram(_pcss_shadow_fp); endEditCP(_shadowSHL); //SHL Chunk 2 _combineSHL = SHLChunk::create(); beginEditCP(_combineSHL); //_combineSHL->readVertexProgram("PCSS_Shadow_combine.vert"); //_combineSHL->readFragmentProgram("PCSS_Shadow_combine.frag"); _combineSHL->setVertexProgram(_shadow_combine_vp); _combineSHL->setFragmentProgram(_shadow_combine_fp); endEditCP(_combineSHL); _combineDepth = DepthChunk::create(); beginEditCP(_combineDepth); _combineDepth->setReadOnly(true); endEditCP(_combineDepth); //Shadow Shader _shadowCmat = ChunkMaterial::create(); //Combine Shader _combineCmat = ChunkMaterial::create(); beginEditCP(_combineCmat); _combineCmat->addChunk(_combineSHL); _combineCmat->addChunk(_colorMap); _combineCmat->addChunk(_shadowFactorMap); _combineCmat->addChunk(_combineDepth); endEditCP(_combineCmat); _pf = PolygonForeground::create(); beginEditCP(_pf); // ref counting is not supported in the polygon foreground! _pf->setMaterial(_combineCmat); _pf->editMFTexCoords()->push_back(Vec3f(0.0f, 0.0f, 0.0f)); _pf->editMFPositions()->push_back(Pnt2f(0.0f, 0.0f)); _pf->editMFTexCoords()->push_back(Vec3f(1.0f, 0.0f, 0.0f)); _pf->editMFPositions()->push_back(Pnt2f(1.0f, 0.0f)); _pf->editMFTexCoords()->push_back(Vec3f(1.0f, 1.0f, 0.0f)); _pf->editMFPositions()->push_back(Pnt2f(1.0f, 1.0f)); _pf->editMFTexCoords()->push_back(Vec3f(0.0f, 1.0f, 0.0f)); _pf->editMFPositions()->push_back(Pnt2f(0.0f, 1.0f)); _pf->setNormalizedX(true); _pf->setNormalizedY(true); endEditCP(_pf); addRefCP(_colorMap); addRefCP(_shadowFactorMap); addRefCP(_shadowSHL); addRefCP(_shadowCmat); addRefCP(_combineSHL); addRefCP(_combineDepth); addRefCP(_combineCmat); addRefCP(_pf); }
void PhongMaterial::rebuildState(void) { if(_pState != NullFC) { _pState->clearChunks(); } else { _pState = State::create(); addRefCP(_pState); } prepareLocalChunks(); Color3f v3; Color4f v4; float alpha = 1.f - getTransparency(); beginEditCP(_materialChunk); v3 = getAmbient(); v4.setValuesRGBA(v3[0], v3[1], v3[2], alpha); _materialChunk->setAmbient(v4); v3 = getDiffuse(); v4.setValuesRGBA(v3[0], v3[1], v3[2], alpha); _materialChunk->setDiffuse(v4); v3 = getSpecular(); v4.setValuesRGBA(v3[0], v3[1], v3[2], alpha); _materialChunk->setSpecular(v4); _materialChunk->setShininess(getShininess()); v3 = getEmission(); v4.setValuesRGBA(v3[0], v3[1], v3[2], alpha); _materialChunk->setEmission(v4); _materialChunk->setLit(getLit()); _materialChunk->setColorMaterial(getColorMaterial()); endEditCP(_materialChunk); _pState->addChunk(_materialChunk); if(isTransparent()) _pState->addChunk(_blendChunk); if(_vpChunk != NullFC) _pState->addChunk(_vpChunk); createFragmentProgram(); if(_fpChunk != NullFC) _pState->addChunk(_fpChunk); for(MFStateChunkPtr::iterator i = _mfChunks.begin(); i != _mfChunks.end(); ++i) { _pState->addChunk(*i); } }
// Initialize GLUT & OpenSG and set up the scene int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // GLUT init int winid = setupGLUT(&argc, argv); gwin = GLUTWindow::create(); // create root rootNode = makeCoredNode<Group>(); NodePtr scene = makeCoredNode<Group>(); // create lights TransformPtr point1_trans; NodePtr point1 = makeCoredNode<PointLight>(&_point1_core); NodePtr point1_beacon = makeCoredNode<Transform>(&point1_trans); beginEditCP(point1_trans); point1_trans->editMatrix().setTranslate(0.0, 0.0, 25.0); endEditCP(point1_trans); beginEditCP(_point1_core); _point1_core->setAmbient(0.15,0.15,0.15,1); _point1_core->setDiffuse(0.4,0.4,0.4,1); _point1_core->setSpecular(0.0,0.0,0.0,1); _point1_core->setBeacon(point1_beacon); _point1_core->setOn(true); endEditCP(_point1_core); TransformPtr point2_trans; NodePtr point2 = makeCoredNode<PointLight>(&_point2_core); NodePtr point2_beacon = makeCoredNode<Transform>(&point2_trans); beginEditCP(point2_trans); point2_trans->editMatrix().setTranslate(5.0, 5.0, 20.0); endEditCP(point2_trans); beginEditCP(_point2_core); _point2_core->setAmbient(0.15,0.15,0.15,1); _point2_core->setDiffuse(0.4,0.4,0.4,1); _point2_core->setSpecular(0.0,0.0,0.0,1); _point2_core->setBeacon(point2_beacon); _point2_core->setOn(true); endEditCP(_point2_core); beginEditCP(point1); point1->addChild(point2); endEditCP(point1); beginEditCP(point2); point2->addChild(scene); endEditCP(point2); // create scene // bottom NodePtr plane = makePlane(25.0, 25.0, 128, 128); int size = imageWinWidth*imageWinHeight*256; ImagePtr plane_img = Image::create(); beginEditCP(plane_img); plane_img->set(Image::OSG_RGBA_PF, imageWinWidth, imageWinHeight, 1, 1, 1, 0, NULL); endEditCP(plane_img); TextureChunkPtr plane_tex = TextureChunk::create(); beginEditCP(plane_tex); plane_tex->setImage(plane_img); plane_tex->setMinFilter(GL_LINEAR); plane_tex->setMagFilter(GL_LINEAR); plane_tex->setTarget(GL_TEXTURE_2D); plane_tex->setInternalFormat(GL_RGBA16F_ARB); endEditCP(plane_tex); SHLChunkPtr shl = SHLChunk::create(); beginEditCP(shl); shl->setVertexProgram(_vp_program); shl->setFragmentProgram(_fp_program); shl->setUniformParameter("tex0", 0); endEditCP(shl); SimpleMaterialPtr plane_mat = SimpleMaterial::create(); beginEditCP(plane_mat); plane_mat->setAmbient(Color3f(0.3,0.3,0.3)); plane_mat->setDiffuse(Color3f(1.0,1.0,1.0)); plane_mat->addChunk(plane_tex); plane_mat->addChunk(shl); endEditCP(plane_mat); GeometryPtr plane_geo = GeometryPtr::dcast(plane->getCore()); beginEditCP(plane_geo); plane_geo->setMaterial(plane_mat); beginEditCP(plane_geo); // box box_trans_node = makeCoredNode<Transform>(&_box_trans); beginEditCP(_box_trans); _box_trans->editMatrix().setTranslate(0.0, 0.0, 12.0); endEditCP(_box_trans); NodePtr box = makeBox(4.0, 4.0, 0.8, 10, 10 , 10); beginEditCP(box_trans_node); box_trans_node->addChild(box); endEditCP(box_trans_node); PolygonChunkPtr pchunk = osg::PolygonChunk::create(); beginEditCP(pchunk); pchunk->setCullFace(GL_BACK); endEditCP(pchunk); SimpleMaterialPtr box_mat = SimpleMaterial::create(); beginEditCP(box_mat); box_mat->setAmbient(Color3f(0.0,0.0,0.0)); box_mat->setDiffuse(Color3f(0.0,0.0,1.0)); box_mat->addChunk(pchunk); endEditCP(box_mat); GeometryPtr box_geo = GeometryPtr::dcast(box->getCore()); beginEditCP(box_geo); box_geo->setMaterial(box_mat); beginEditCP(box_geo); // cylinder1 NodePtr cylinder1_trans_node = makeCoredNode<Transform>(&_cylinder1_trans); beginEditCP(_cylinder1_trans); _cylinder1_trans->editMatrix().setTranslate(0.0, 0.0, 5.0); endEditCP(_cylinder1_trans); NodePtr cylinder1 = OSG::makeCylinder(10.0, 0.4, 32, true, true ,true); beginEditCP(cylinder1_trans_node); cylinder1_trans_node->addChild(cylinder1); endEditCP(cylinder1_trans_node); SimpleMaterialPtr cylinder1_mat = SimpleMaterial::create(); beginEditCP(cylinder1_mat); cylinder1_mat->setAmbient(Color3f(0.0,0.0,0.0)); cylinder1_mat->setDiffuse(Color3f(1.0,0.0,0.0)); cylinder1_mat->addChunk(pchunk); endEditCP(cylinder1_mat); GeometryPtr cylinder1_geo = GeometryPtr::dcast(cylinder1->getCore()); beginEditCP(cylinder1_geo); cylinder1_geo->setMaterial(cylinder1_mat); beginEditCP(cylinder1_geo); // cylinder2 NodePtr cylinder2_trans_node = makeCoredNode<Transform>(&_cylinder2_trans); beginEditCP(_cylinder2_trans); _cylinder2_trans->editMatrix().setTranslate(0.0, 0.0, 8.0); endEditCP(_cylinder2_trans); NodePtr cylinder2 = OSG::makeCylinder(10.0, 0.4, 32, true, true ,true); beginEditCP(cylinder2_trans_node); cylinder2_trans_node->addChild(cylinder2); endEditCP(cylinder2_trans_node); SimpleMaterialPtr cylinder2_mat = SimpleMaterial::create(); beginEditCP(cylinder2_mat); cylinder2_mat->setAmbient(Color3f(0.0,0.0,0.0)); cylinder2_mat->setDiffuse(Color3f(0.0,1.0,0.0)); cylinder2_mat->addChunk(pchunk); endEditCP(cylinder2_mat); GeometryPtr cylinder2_geo = GeometryPtr::dcast(cylinder2->getCore()); beginEditCP(cylinder2_geo); cylinder2_geo->setMaterial(cylinder2_mat); beginEditCP(cylinder2_geo); // scene beginEditCP(scene); scene->addChild(plane); scene->addChild(box_trans_node); scene->addChild(cylinder1_trans_node); scene->addChild(cylinder2_trans_node); endEditCP(scene); vp = ShadowViewport::create(); GradientBackgroundPtr gbg = GradientBackground::create(); SolidBackgroundPtr sbg = SolidBackground::create(); UChar8 imgdata[] = { 255,0,0, 0,255,0, 0,0,255, 255,255,0 }; ImagePtr img1 = Image::create(); img1->set(Image::OSG_RGB_PF, 2, 2, 1, 1, 1, 0, imgdata); TextureChunkPtr tcPtr = TextureChunk::create(); beginEditCP(tcPtr); tcPtr->setImage(img1); endEditCP(tcPtr); TextureBackgroundPtr bkg = TextureBackground::create(); beginEditCP(bkg); bkg->setTexture(tcPtr); endEditCP(bkg); beginEditCP(sbg); sbg->setColor(Color3f(0.2,0.4,0.6)); endEditCP(sbg); beginEditCP(gbg); gbg->addLine(Color3f(0.7, 0.7, 0.8), 0); gbg->addLine(Color3f(0.1, 0.1, 0.3), 1); endEditCP(gbg); beginEditCP(rootNode); rootNode->addChild(point1); rootNode->addChild(point1_beacon); rootNode->addChild(point2_beacon); endEditCP(rootNode); //FBOViewportPtr fbo_vp = FBOViewport::create(); addRefCP(fbo_vp); // the Camera for the map cam = PerspectiveCamera::create(); beginEditCP(cam); cam->setFov(osgdegree2rad(90)); cam->setAspect(1); cam->setNear(0.001); cam->setFar(10000); cam->setBeacon(box_trans_node); endEditCP(cam); beginEditCP(fbo_vp); fbo_vp->setBackground(bkg); fbo_vp->setRoot(rootNode); fbo_vp->setCamera(cam); fbo_vp->setSize(0,0,imageWinWidth-1, imageWinHeight-1); fbo_vp->setStorageWidth(imageWinWidth); fbo_vp->setStorageHeight(imageWinHeight); fbo_vp->setDirty(true); fbo_vp->editMFTextures ()->push_back(plane_tex); fbo_vp->editMFExcludeNodes()->push_back(plane); fbo_vp->setFboOn(true); endEditCP(fbo_vp); // normal shadow viewport beginEditCP(vp); vp->setBackground(gbg); vp->setRoot(rootNode); vp->setSize(0,0,1,1); endEditCP(vp); beginEditCP(gwin); //Window gwin->setId(winid); gwin->addPort(vp); gwin->init(); endEditCP(gwin); Vec3f min,max; rootNode->updateVolume(); rootNode->getVolume().getBounds( min, max ); // create the SimpleSceneManager helper mgr = new SimpleSceneManager; mgr->setWindow(gwin); mgr->setRoot(rootNode); //Viewport beginEditCP(vp); vp->setCamera(mgr->getCamera()); endEditCP(vp); mgr->turnHeadlightOff(); mgr->showAll(); // GLUT main loop glutMainLoop(); return 0; }
void PCSSShadowMap::createShadowMaps(RenderActionBase *action) { if(_tiledeco == NullFC) { _tiledeco = TileCameraDecorator::create(); addRefCP(_tiledeco); } //Checking for the smallest Window-Dimension UInt32 minSize = _shadowVP->getPixelWidth(); if(_shadowVP->getPixelHeight() < minSize) minSize = _shadowVP->getPixelHeight(); //Checking for biggest PowerOf2 that fits in smallest Window-Dimension UInt32 _mapRenderSize = osgnextpower2(minSize + 1) / 2; if(_mapRenderSize == 0) _mapRenderSize = 128; Real32 vpTop, vpBottom, vpLeft, vpRight; //------Setting up Window to fit size of ShadowMap---------------- // Saving original Viewport-Dimensions vpTop = _shadowVP->getTop(); vpBottom = _shadowVP->getBottom(); vpLeft = _shadowVP->getLeft(); vpRight = _shadowVP->getRight(); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glShadeModel(GL_FLAT); glDisable(GL_LIGHTING); glDepthMask(GL_TRUE); // disable all lights more speed std::vector<bool> lightStates; for(UInt32 i = 0;i < _shadowVP->_lights.size();++i) { // store old states. lightStates.push_back(_shadowVP->_lights[i].second->getOn()); _shadowVP->_lights[i].second->setOn(false); } // deactivate exclude nodes: for(UInt32 i = 0;i < _shadowVP->getMFExcludeNodes()->getSize();++i) { NodePtr exnode = _shadowVP->getExcludeNodes(i); if(exnode != NullFC) exnode->setTravMask(0); } for(UInt32 i = 0;i < _shadowVP->_lights.size();++i) { if(_shadowVP->_lightStates[i] != 0) { if(_shadowVP->getGlobalShadowIntensity() != 0.0 || _shadowVP->_lights[i].second->getShadowIntensity() != 0.0) { if(_mapRenderSize > _shadowVP->getMapSize()) _mapRenderSize = _shadowVP->getMapSize(); _shadowVP->setVPSize(0, 0, _mapRenderSize - 1, _mapRenderSize - 1); // we use a tiledecorator to create shadow maps with // a higher resolutions than the viewport or the screen. beginEditCP(_tiledeco); _tiledeco->setDecoratee(_shadowVP->_lightCameras[i]); _tiledeco->setFullSize(_shadowVP->getMapSize(), _shadowVP->getMapSize()); endEditCP(_tiledeco); action->setCamera(getCPtr(_tiledeco)); Real32 step = (1.0 / Real32(_shadowVP->getMapSize())) * Real32(_mapRenderSize); UInt32 ypos = 0; for(Real32 y = 0;y < 1.0;y += step) { UInt32 xpos = 0; for(Real32 x = 0;x < 1.0;x += step) { beginEditCP(_tiledeco); _tiledeco->setSize(x, y, x + step, y + step); endEditCP(_tiledeco); glClear(GL_DEPTH_BUFFER_BIT); glPolygonOffset(_shadowVP->getOffFactor(), _shadowVP->getOffBias()); glEnable(GL_POLYGON_OFFSET_FILL); _shadowVP->renderLight(action, getCPtr(_unlitMat), i); action->getWindow()->validateGLObject( _shadowVP->_texChunks[i]->getGLId()); glDisable(GL_POLYGON_OFFSET_FILL); //----------Shadow-Texture-Parameters and Indices------------- glBindTexture(GL_TEXTURE_2D, action->getWindow()->getGLObjectId( _shadowVP->_texChunks[i]->getGLId())); if(glGetError() != GL_NO_ERROR) SWARNING << "Error on binding Texture!" << endLog; glCopyTexSubImage2D(GL_TEXTURE_2D, 0, xpos, ypos, 0, 0, _mapRenderSize, _mapRenderSize); if(glGetError() != GL_NO_ERROR) SWARNING << "Error on copying Texture!" << endLog; glBindTexture(GL_TEXTURE_2D, 0); if(glGetError() != GL_NO_ERROR) SWARNING << "Error on releasing Texture!" << endLog; if(glGetError() != GL_NO_ERROR) SWARNING << "Error while Texture-Creation!" << endLog; xpos += _mapRenderSize; } ypos += _mapRenderSize; } } } } // enable all lights. for(UInt32 i = 0;i < _shadowVP->_lights.size();++i) { // restore old states. _shadowVP->_lights[i].second->setOn(lightStates[i]); } // activate exclude nodes: for(UInt32 i = 0;i < _shadowVP->getMFExcludeNodes()->getSize();++i) { NodePtr exnode = _shadowVP->getExcludeNodes(i); if(exnode != NullFC) exnode->setTravMask(_shadowVP->_excludeNodeTravMask[i]); } //-------Restoring old states of Window and Viewport---------- beginEditCP(_shadowVP->getCamera(), _shadowVP->LeftFieldMask | _shadowVP->RightFieldMask | _shadowVP->BottomFieldMask | _shadowVP->TopFieldMask); { _shadowVP->setSize(vpLeft, vpBottom, vpRight, vpTop); } endEditCP(_shadowVP->getCamera(), _shadowVP->LeftFieldMask | _shadowVP->RightFieldMask | _shadowVP->BottomFieldMask | _shadowVP->TopFieldMask); action->setCamera(getCPtr(_shadowVP->getCamera())); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glShadeModel(GL_SMOOTH); glEnable(GL_LIGHTING); }
int main(int argc, char **argv) { // enableFPE(); #ifdef __sgi signal(SIGSEGV, (void (*)(int))sighand); signal(SIGTRAP, (void (*)(int))sighand); signal(SIGBUS, (void (*)(int))sighand); #endif // OSG init osgInit(argc,argv); if (argc > 1 && ! strcmp(argv[1],"-bench")) { runBench = true; argc--; argv++; glutInitWindowPosition(0,0); glutInitWindowSize(600,600); } if (argc > 1 && ! strcmp(argv[1],"-test")) { testSet = true; doMotion = false; argc--; argv++; } // GLUT init int winid = setupGLUT(&argc, argv); // the connection between GLUT and OpenSG GLUTWindowPtr gwin= GLUTWindow::create(); gwin->setId(winid); gwin->init(); // create the scene NodePtr scene = Node::create(); NodePtr pnode = Node::create(); ComponentTransformPtr trans = ComponentTransform::create(); beginEditCP(scene); scene->setCore(trans); scene->addChild(pnode); endEditCP(scene); beginEditCP(trans); trans->setTranslation(Vec3f(2,0,0)); trans->setRotation(Quaternion(Vec3f(0,1,0),Pi/2)); trans->setScale(Vec3f(2,2,2)); endEditCP(trans); particles = Particles::create(); beginEditCP(pnode); pnode->setCore(particles); endEditCP(pnode); numParticles = 100; if (argc > 1) { numParticles=atoi(argv[1]); } beginEditCP(particles); pnts=GeoPositions3f::create(); secpnts=GeoPositions3f::create(); addRefCP(pnts); addRefCP(secpnts); GeoColors3fPtr cols = GeoColors3f::create(); GeoNormals3fPtr norms = GeoNormals3f::create(); MFPnt3f* p=pnts->editFieldPtr(); MFPnt3f* sp=secpnts->editFieldPtr(); MFVec3f *size=particles->editMFSizes(); indices = particles->editMFIndices(); velocities=new Vec3f [numParticles]; beginEditCP(pnts); beginEditCP(secpnts); beginEditCP(cols); if(!testSet) { for(UInt32 i=0; i < numParticles; ++i) { Pnt3f pnt(osgrand(),osgrand(),osgrand()); indices->push_back(i); p->push_back(pnt); sp->push_back(pnt); velocities[i].setValues(osgrand()/30.f/2, osgrand()/30.f/2, osgrand()/30.f/2); cols->editFieldPtr()->push_back( Color3f(osgrand()/2.f + .5f,osgrand()/2.f + .5f,osgrand()/2.f + .5f) ); size->push_back( Vec3f(osgrand()/20.f+0.05,osgrand()/20.f+0.05,osgrand()/20.f+0.05)); } } else { Pnt3f tpos[] = { Pnt3f(.5,.5,.5), Pnt3f (.5,.5,.7), Pnt3f(.5,.5,.9), Pnt3f(.7,.5,.5), Pnt3f(.5,.7,.5), Pnt3f (-1000,-1000,-1000) }; Pnt3f tsecpos[] = { Pnt3f(0,0,0), Pnt3f(0,0,0), Pnt3f(0,0,0), Pnt3f(0,0,0), Pnt3f(0,0,0) }; Vec3f tvel[] = { Vec3f(0,0,0), Vec3f(0,0,0), Vec3f(0,0,0), Vec3f(0,0,0), Vec3f(0,0,0) }; Color3f tcol[] = { Color3f(1,0,0), Color3f(0,1,0), Color3f(0,0,1), Color3f(1,1,0), Color3f(1,0,1), Color3f(0,1,1), Color3f(1,1,1) }; Vec3f tsize[] = { Vec3f(.1,0,0), Vec3f(.1,0,0), Vec3f(.1,0,0), Vec3f(.1,0,0), Vec3f(.1,0,0) }; for(UInt32 i=0; tpos[i][0] > -1000; ++i) { indices->push_back(i); p->push_back(tpos[i]); sp->push_back(tsecpos[i]); velocities[i].setValue(tvel[i]); cols->editFieldPtr()->push_back(tcol[i]); size->push_back(tsize[i]); } } endEditCP(pnts); endEditCP(secpnts); endEditCP(cols); beginEditCP(norms); norms->push_back(Vec3f(0,1,0)); endEditCP(norms); particles->setPositions( pnts ); particles->setSecPositions( secpnts ); particles->setColors( cols ); particles->setNormals( norms ); endEditCP(particles); // set volume static to prevent constant update beginEditCP(pnode, Node::VolumeFieldMask); #ifndef OSG_2_PREP Volume &v = pnode->editVolume(false).getInstance(); #else Volume &v = pnode->editVolume(false); #endif v.setEmpty(); v.extendBy(Pnt3f(0,0,0)); v.extendBy(Pnt3f(1,1,1)); v.setStatic(); #ifndef OSG_2_PREP pnode->editVolume(false).instanceChanged(); #endif endEditCP (pnode, Node::VolumeFieldMask); SimpleTexturedMaterialPtr tm; tm = SimpleTexturedMaterial::create(); UChar8 imgdata[] = { 255,255,255, 255,0,0, 255,0,255, 255,0,0, 255,0,0, 255,255,255 }; ImagePtr pImage = Image::create(); if (argc > 2) { pImage->read(argv[2]); } else { pImage->set(Image::OSG_RGB_PF, 3, 2, 1, 1, 1, 0, imgdata); } beginEditCP(tm); tm->setDiffuse( Color3f( 1,1,1 ) ); tm->setLit( false ); tm->setImage( pImage ); tm->setEnvMode( GL_MODULATE ); BlendChunkPtr bl=BlendChunk::create(); beginEditCP(bl); bl->setSrcFactor(GL_SRC_ALPHA); //bl->setDestFactor(GL_ONE_MINUS_SRC_ALPHA); bl->setDestFactor(GL_ONE); #if 0 bl->setAlphaFunc(GL_EQUAL); bl->setAlphaValue(1); #endif endEditCP(bl); tm->addChunk(bl); endEditCP(tm); particles->setMaterial( tm ); #if 0 // write it, just for testing std::ofstream out("test.osg"); OSGWriter w(out); w.write(scene); #endif // create the SimpleSceneManager helper mgr = new SimpleSceneManager; // tell the manager what to manage mgr->setWindow(gwin ); mgr->setRoot (scene); // show the whole scene mgr->showAll(); //mgr->setHighlight(scene); // GLUT main loop glutMainLoop(); return 0; }
void NFIOBase::chargeFieldPtr(const fcInfo &info) { FieldContainerType &fcType = info._fc->getType(); Field *field = info._field; if(!info.isMultiField()) { FieldContainerPtr fc = NullFC; UInt32 id = info._id; if(id != 0) { fcMap::iterator it = _fcMap.find(id); if(it == _fcMap.end()) { FWARNING(("NFIOBase::chargeFieldPtr: couldn't find " "FieldContainer with id %u\n", id)); return; } fc = (*it).second; if(fc == NullFC) return; } beginEditCP(info._fc, info._mask); if(fc != NullFC && fcType.isNode() && info._mask == Node::CoreFieldMask) { NodePtr node = NodePtr::dcast(info._fc); node->setCore(NodeCorePtr::dcast(fc)); } else { addRefCP(fc); // increment ref count static_cast<SFFieldContainerPtr *>(field)->setValue(fc); } endEditCP(info._fc, info._mask); } else { if(info._ids.empty()) return; NodePtr node = NodePtr::dcast(info._fc); //fcType == Node::getClassType() AttachmentContainerPtr attContainer = AttachmentContainerPtr::dcast(info._fc); bool attachment = false; if(attContainer != NullFC && info._mask == AttachmentContainer::AttachmentsFieldMask) { attachment = true; } beginEditCP(info._fc, info._mask); bool has_ids_binding = (info._ids.size() == info._ids_binding.size()); for(UInt32 i=0;i<info._ids.size();++i) { UInt32 id = info._ids[i]; FieldContainerPtr fc = NullFC; if(id != 0) { fcMap::iterator it = _fcMap.find(id); if(it == _fcMap.end()) { FWARNING(("NFIOBase::chargeFieldPtr: couldn't find " "FieldContainer with id %u\n", id)); continue; } fc = (*it).second; if(fc == NullFC) continue; } if(node != NullFC && info._mask == Node::ChildrenFieldMask) { node->addChild(NodePtr::dcast(fc)); } else if(attachment) { AttachmentPtr pAtt = AttachmentPtr::dcast(fc); if(has_ids_binding) attContainer->addAttachment(pAtt, info._ids_binding[i]); else attContainer->addAttachment(pAtt); } else { addRefCP(fc); // increment ref count static_cast<MFFieldContainerPtr *>(field)->push_back(fc); } } endEditCP(info._fc, info._mask); } }
// Initialize GLUT & OpenSG and set up the scene int main(int argc, char **argv) { // OSG init osgInit(argc,argv); // GLUT init int winid = setupGLUT(&argc, argv); // the connection between GLUT and OpenSG GLUTWindowPtr gwin= GLUTWindow::create(); gwin->setId(winid); gwin->init(); // create the scene first = Node::create (); beginEditCP(first); first->setCore(Group::create()); unsigned i; for (i=0; i<numFirst; ++i) { first->addChild(makePerturbedAll(4, 1.0f)); //makeTransformedCube(1.0f,1.0f,1.0f,1,1,1, Color3f(1,0,0))); } endEditCP(first); second = Node::create (); beginEditCP(second); second->setCore(Group::create()); for (i=0; i<numSecond; ++i) { second->addChild(makePerturbedAll(4, 1.0f, 0.0f)); //makeTransformedCube(1.0f,1.0f,1.0f,1,1,1, Color3f(0,1,0))); } endEditCP(second); for (i=0; i<numFirst; ++i) { TransformPtr trf = TransformPtr::dcast(first->getChild(i)->getCore()); beginEditCP(trf); randomTransform(trf->getMatrix()); endEditCP(trf); } for (i=0; i<numSecond; ++i) { TransformPtr trf = TransformPtr::dcast(second->getChild(i)->getCore()); beginEditCP(trf); randomTransform(trf->getMatrix()); endEditCP(trf); } scene = Node::create (); beginEditCP(scene); scene->setCore(Group::create()); scene->addChild(first); scene->addChild(second); endEditCP(scene); addRefCP(scene); SLOG << "scene created" << std::endl; // create the SimpleSceneManager helper mgr = new SimpleSceneManager; // tell the manager what to manage mgr->setWindow(gwin ); mgr->setRoot (scene); // show the whole scene mgr->showAll(); // prepare for collision detection // * fill cache OSGCache::the().setHierarchy(NULL); OSGCache::the().apply(scene); SLOG << "cache filled." << std::endl; // * build hierarchy OSGCache::the().setHierarchy(&hier); OSGCache::the().apply(scene); SLOG << "adapters created.." << std::endl; // * create double traverser for collision detection traverser = new Traverser(); traverser->setUseCoherency(false); // do not use generalized front cache for frame coherency traverser->getDataTyped().setStopFirst(false); #ifndef GV_WITH_RAPID SWARNING << "For RAPID support you have to define GV_WITH_RAPID (see Kernel/OSGGVBase.h)" << std::endl; #endif // * create all traverser all = new AllTraverser<OpenSGTraits>(); all->setDoubleTraverser(traverser); // GLUT main loop Profiler::the().Reset(); glutMainLoop(); return 0; }