Exemplo n.º 1
0
static void mainThread(void)
{
    // do some animation in the main thread.
    static Real64 t = 0.0;

    if(OSG::getSystemTime() - t > 2.0)
    {
        // create a wave in the center of the plane.
        startWave(-1, -1, 0.1);
        t = OSG::getSystemTime();
    }

    calcWave();
    updateGeometry(_geo);
    calcVertexNormals(_geo);
}
Exemplo n.º 2
0
GeometryRefPtr buildTerrain(Vec2f Dimensions, UInt32 XSubdivisions, UInt32 YSubdivisions)
{
    GeoUInt8PropertyRefPtr type = GeoUInt8Property::create();        
    type->addValue(GL_TRIANGLES);

    GeoPnt3fPropertyRefPtr  pnts  = GeoPnt3fProperty ::create();
    GeoVec3fPropertyRefPtr  norms = GeoVec3fProperty ::create();
    Real32 ZScale(8.0);
    for(UInt32 i(0) ; i<XSubdivisions ; ++i)
    {
        for(UInt32 j(0) ; j<YSubdivisions ; ++j)
        {
            Real32 Theta(5*3.14159*(static_cast<Real32>(i)/static_cast<Real32>(XSubdivisions))),
                   ThetaNext(5*3.14159*(static_cast<Real32>(i+1)/static_cast<Real32>(XSubdivisions)));
            // the points of the Tris
            pnts->addValue(Pnt3f(-Dimensions.x()/2.0+i*(Dimensions.x()/static_cast<Real32>(XSubdivisions)),  Dimensions.y()/2.0-j*(Dimensions.y()/static_cast<Real32>(YSubdivisions)),  ZScale*osgCos(Theta)));
            norms->addValue(Vec3f( 0.0,0.0,1.0));
            pnts->addValue(Pnt3f(-Dimensions.x()/2.0+i*(Dimensions.x()/static_cast<Real32>(XSubdivisions)),  Dimensions.y()/2.0-(j+1)*(Dimensions.y()/static_cast<Real32>(YSubdivisions)),  ZScale*osgCos(Theta)));
            norms->addValue(Vec3f( 0.0,0.0,1.0));
            pnts->addValue(Pnt3f(-Dimensions.x()/2.0+(i+1)*(Dimensions.x()/static_cast<Real32>(XSubdivisions)),  Dimensions.y()/2.0-j*(Dimensions.y()/static_cast<Real32>(YSubdivisions)),  ZScale*osgCos(ThetaNext)));
            norms->addValue(Vec3f( 0.0,0.0,1.0));

            pnts->addValue(Pnt3f(-Dimensions.x()/2.0+i*(Dimensions.x()/static_cast<Real32>(XSubdivisions)),  Dimensions.y()/2.0-(j+1)*(Dimensions.y()/static_cast<Real32>(YSubdivisions)),  ZScale*osgCos(Theta)));
            norms->addValue(Vec3f( 0.0,0.0,1.0));
            pnts->addValue(Pnt3f(-Dimensions.x()/2.0+(i+1)*(Dimensions.x()/static_cast<Real32>(XSubdivisions)),  Dimensions.y()/2.0-(j+1)*(Dimensions.y()/static_cast<Real32>(YSubdivisions)),  ZScale*osgCos(ThetaNext)));
            norms->addValue(Vec3f( 0.0,0.0,1.0));
            pnts->addValue(Pnt3f(-Dimensions.x()/2.0+(i+1)*(Dimensions.x()/static_cast<Real32>(XSubdivisions)),  Dimensions.y()/2.0-j*(Dimensions.y()/static_cast<Real32>(YSubdivisions)),  ZScale*osgCos(ThetaNext)));
            norms->addValue(Vec3f( 0.0,0.0,1.0));
        }
    }


    GeoUInt32PropertyUnrecPtr lens = GeoUInt32Property::create();    
    lens->addValue(pnts->size());

    GeometryRefPtr Terrain = Geometry::create();
    Terrain->setTypes    (type);
    Terrain->setLengths  (lens);
    Terrain->setPositions(pnts);
    Terrain->setNormals(norms);

    calcVertexNormals(Terrain);

    return Terrain;
}
Exemplo n.º 3
0
Arquivo: a.c Projeto: mlang03/School
//This function controls camera movement while a button is held.
void up(int x, int y){
    if (left_down){
        float xdiff = (px - x)*0.05;
        float ydiff = (py - y)*0.1;
        cx_angle += xdiff;
        c_distance += ydiff;
        px = x;
        py = y;
        glutPostRedisplay();
    }
    if (right_down){
        float ydiff = (py - y)*0.00025;
        scale += ydiff;
        py = y;
        calcSurfaceNormals();
        calcVertexNormals();
        glutPostRedisplay();
    }
}
Exemplo n.º 4
0
Arquivo: a.c Projeto: mlang03/School
/*  Main Loop
 *  Open window with initial window size, title bar, 
 *  RGBA display mode, and handle input events.
 */
int main(int argc, char** argv)
{
   srand(time(NULL));
   glutInit(&argc, argv);
   glutInitDisplayMode (GLUT_SINGLE | GLUT_RGBA | GLUT_DEPTH);
   glutInitWindowSize (1024, 768);
   glutCreateWindow (argv[0]);
   init();
   loadHeightMap(argc,argv);
   calcSurfaceNormals();
   calcVertexNormals();
   calcVertexColour(0);
   glutReshapeFunc(reshape);
   glutDisplayFunc(display);
   glutKeyboardFunc (keyboard);
   glutMouseFunc (mouse);
   glutMotionFunc(up);
   glutMainLoop();
   return 0; 
}
Exemplo n.º 5
0
//----------------------------
// Function name: read
//----------------------------
//
//Parameters:
//p: Scene &image, const char *fileName
//GlobalVars:
//g:
//Returns:
//r:bool
// Caution
//c:
//Assumations:
//a:
//Describtions:
//d: read the image from the given file
//SeeAlso:
//s:
//
//------------------------------
NodeTransitPtr OBJSceneFileType::read(      std::istream &is,
                                      const Char8        *,
                                            Resolver        ) const
{
    NodeUnrecPtr rootPtr, nodePtr;
    std::string elem;
    std::map<std::string, DataElem>::const_iterator elemI;
    Vec3f vec3r;
    Pnt3f pnt3r;
    Vec2f vec2r;
    Real32 x,y,z;
    GeoPnt3fPropertyUnrecPtr coordPtr    = GeoPnt3fProperty::create();
    GeoVec2fPropertyUnrecPtr texCoordPtr = GeoVec2fProperty::create();
    GeoVec3fPropertyUnrecPtr normalPtr   = GeoVec3fProperty::create();
    GeometryUnrecPtr geoPtr;
    GeoIntegralPropertyUnrecPtr posIndexPtr, texIndexPtr, normalIndexPtr;
    GeoIntegralPropertyUnrecPtr lensPtr;
    GeoIntegralPropertyUnrecPtr typePtr;
    DataElem dataElem;
    DataElem lastDataElem;
    Char8 strBuf[8192], *token, *nextToken;
    Int32 strBufSize = sizeof(strBuf)/sizeof(Char8);
    Int32 index, posIndex = 0, indexType;
    Int32 i,j,n,primCount[3];
    std::list<Mesh> meshList;
    std::map<std::string, SimpleTexturedMaterialUnrecPtr> mtlMap;
    std::map<std::string, SimpleTexturedMaterialUnrecPtr>::iterator mtlI;
    Mesh emptyMesh;
    Face emptyFace;
    TiePoint  emptyTie;
    Int32 indexMask, meshIndexMask;
    std::list<Face>::iterator faceI;
    std::list<Mesh>::iterator meshI;
    bool isSingleIndex;

    // create the first mesh entry
    meshList.push_back(emptyMesh);
    meshI = meshList.begin();

    if(is)
    {
        primCount[0] = 0;
        primCount[1] = 0;
        primCount[2] = 0;

        for(is >> elem; is.eof() == false; is >> elem)
        {
            if(elem[0] == '#' || elem[0] == '$')
            {
                is.ignore(INT_MAX, '\n');
            }
            else
            {
                SceneFileHandler::the()->updateReadProgress();

                elemI = _dataElemMap.find(elem);
                dataElem = ((elemI == _dataElemMap.end()) ?
                        UNKNOWN_DE : elemI->second );
                switch (dataElem)
                {
                    case OBJECT_DE:
                    case GROUP_DE:
                    case SMOOTHING_GROUP_DE:
                        is.ignore(INT_MAX, '\n');
                    break;
                    case VERTEX_DE:
                        primCount[0]++;
                        is >> x >> y >> z;
                        pnt3r.setValues(x,y,z);
                        coordPtr->addValue(pnt3r);
                    break;
                    case VERTEX_TEXTURECOORD_DE:
                        primCount[1]++;
                        is >> x >> y;
                        vec2r.setValues(x,y);
                        texCoordPtr->addValue(vec2r);
                    break;
                    case VERTEX_NORMAL_DE:
                        primCount[2]++;
                        is >> x >> y >> z;
                        vec3r.setValues(x,y,z);
                        normalPtr->addValue(vec3r);
                    break;
                    case LIB_MTL_DE:
                        is >> elem;
                        readMTL ( elem.c_str(), mtlMap );
                        is.ignore(INT_MAX, '\n');
                    break;
                    case USE_MTL_DE:
                        is >> elem;
                        if (meshI->faceList.empty() == false)
                        {
                            meshList.push_front(emptyMesh);
                            meshI = meshList.begin();
                        }
                        mtlI = mtlMap.find(elem);
                        if (mtlI == mtlMap.end())
                        {
                            FFATAL (("Unkown mtl %s\n", elem.c_str()));
                        }
                        else
                        {
                            meshI->mtlPtr = mtlI->second;
                        }
                    break;
                    case FACE_DE:
                        meshI->faceList.push_front(emptyFace);
                        faceI = meshI->faceList.begin();
                        is.get(strBuf,strBufSize);
                        token = strBuf;
                        indexType = 0;
                        while(token && *token)
                        {
                            // some tools use line continuation for long
                            // face definitions - these use a \ at the line
                            // end
                            if(*token == '\\')
                            {
                                is.ignore(1, '\n');
                                is.get(strBuf,strBufSize);
                                token = strBuf;
                                indexType = 0;
                                continue;
                            }
                            for (; *token == '/'; token++)
                                indexType++;
                            for (; isspace(*token); token++)
                                indexType = 0;
                            index = strtol(token, &nextToken, 10);
                            if (token == nextToken)
                                break;
                            if (indexType == 0)
                                faceI->tieVec.push_back(emptyTie);
                            if (index >= 0)
                                index--;
                            else
                                index =  primCount[indexType] + index;
                            faceI->tieVec.back().index[indexType] = index;
                            token = nextToken;
                        }
                    break;

                    case UNKNOWN_DE:
                    default:
                        // don't warn about 3rd tex coord
                        if(lastDataElem != VERTEX_TEXTURECOORD_DE)
                        {
                            FWARNING (( "Unkown obj data elem: %s\n", 
                                        elem.c_str()));
                        }
                        is.ignore(INT_MAX, '\n');
                    break;
                }

                lastDataElem = dataElem;
            }
        }

#if 0
        std::cerr << "------------------------------------------------" << std::endl;
        i = 0;
        for (meshI = meshList.begin(); meshI != meshList.end(); meshI++)
        {
            std::cerr << "Mesh " << i << " faceCount :"
                      << meshI->faceList.size() << std::endl;
            j = 0 ;
            for ( faceI = meshI->faceList.begin(); faceI != meshI->faceList.end();
                  faceI++)
            std::cerr << "MESH " <<  i << "face: " << j++ << "tie num: "
                      << faceI->tieVec.size() << std::endl;
            i++;
        }
        std::cerr << "------------------------------------------------" << std::endl;
#endif

        // create Geometry objects
        for (meshI = meshList.begin(); meshI != meshList.end(); meshI++)
        {
            geoPtr   = Geometry::create();
            posIndexPtr = NULL;
            texIndexPtr = NULL;
            normalIndexPtr = NULL;
            lensPtr  = GeoUInt32Property::create();
            typePtr  = GeoUInt8Property ::create();

            // create and check mesh index mask
            meshIndexMask = 0;
            isSingleIndex = true;
            if ( meshI->faceList.empty() == false)
            {
                for ( faceI = meshI->faceList.begin();
                  faceI != meshI->faceList.end(); faceI++)
                {
                    indexMask = 0;
                    n = UInt32(faceI->tieVec.size());
                    for (i = 0; i < n; i++)
                    {
                        for (j = 0; j < 3; j++)
                        {
                            if ((index = (faceI->tieVec[i].index[j])) >= 0)
                            {
                                indexMask |= (1 << j);
                                if (j)
                                    isSingleIndex &= (posIndex == index);
                                else
                                    posIndex = index;
                            }
                        }
                    }
                    if (meshIndexMask == 0)
                    {
                        meshIndexMask = indexMask;
                    }
                    else if (meshIndexMask != indexMask)
                    {
                        // consider this real-world example:
                       // [...]
                       // f 1603//1747 1679//1744 1678//1743
                       // s 1
                       // f 9/1/10 5/2/9 1680/3/1748 1681/4/174
                       // [...]
                       // Some faces contain texture coords and others do not.
                       // The old version did just skip this geometry.
                       // This version should continue if there's at least
                       // the vertex index
                       // I've seen the change in the maskIndex only after a smooth group,
                       // so it's perhaps smarter to not ignore the smooth group further up in this code
                       if( !(indexMask & 1) )
                       {
                         // if there are vertex indices there's no reason to get in here
                          FFATAL (( "IndexMask unmatch, can not create geo\n"));
                          meshIndexMask = 0;
                          break;
                       }
                       else
                       {
                         // consider the minimum similarities of mesh masks
                         meshIndexMask &= indexMask;
                       }
                    }
                }
            }
            else
            {
                FWARNING (("Mesh with empty faceList\n"));
            }

            // fill the geo properties
            if (meshIndexMask)
            {
                geoPtr->setPositions ( coordPtr );
                posIndexPtr = GeoUInt32Property::create();
                if(!isSingleIndex)
                    geoPtr->setIndex(posIndexPtr, Geometry::PositionsIndex);
                geoPtr->setLengths   ( lensPtr );
                geoPtr->setTypes     ( typePtr );

                if ( (meshIndexMask & 2) && texCoordPtr->size() > 0 )
                {
                    geoPtr->setTexCoords ( texCoordPtr );
                    texIndexPtr = GeoUInt32Property::create();
                    if(!isSingleIndex)
                        geoPtr->setIndex(texIndexPtr, Geometry::TexCoordsIndex);
                }
                else
                {
                    geoPtr->setTexCoords ( NULL );
                }

                if ( (meshIndexMask & 4) && normalPtr->size() > 0 )
                {
                    geoPtr->setNormals   ( normalPtr );
                    normalIndexPtr = GeoUInt32Property::create();
                    if(!isSingleIndex)
                        geoPtr->setIndex(normalIndexPtr, Geometry::NormalsIndex);
                }
                else
                {
                    geoPtr->setNormals   ( NULL );
                }

                if (meshI->mtlPtr == NULL)
                {
                    meshI->mtlPtr = SimpleTexturedMaterial::create();
                    meshI->mtlPtr->setDiffuse( Color3f( .8f, .8f, .8f ) );
                    meshI->mtlPtr->setSpecular( Color3f( 1.f, 1.f, 1.f ) );
                    meshI->mtlPtr->setShininess( 20.f );
                }
                geoPtr->setMaterial  ( meshI->mtlPtr );

                for ( faceI = meshI->faceList.begin();
                      faceI != meshI->faceList.end(); faceI++)
                {
                    n = UInt32(faceI->tieVec.size());

                    // add the lens entry
                    lensPtr->push_back(n);

                    // add the type entry
                    typePtr->push_back(GL_POLYGON);

                    // create the index values
                    for (i = 0; i < n; i++)
                    {
                        if (isSingleIndex)
                        {
                            posIndexPtr->push_back(faceI->tieVec[i].index[0]);
                        }
                        else
                        {
                            posIndexPtr->push_back(faceI->tieVec[i].index[0]);
                            if(texIndexPtr != NULL)
                                texIndexPtr->push_back(faceI->tieVec[i].index[1]);
                            if(normalIndexPtr != NULL)
                                normalIndexPtr->push_back(faceI->tieVec[i].index[2]);
                        }
                    }
                }

                if(isSingleIndex)
                {
                    geoPtr->setIndex(posIndexPtr, Geometry::PositionsIndex);
                    geoPtr->setIndex(posIndexPtr, Geometry::NormalsIndex  );
                    geoPtr->setIndex(posIndexPtr, Geometry::TexCoordsIndex);
                }

                // need to port the geometry functions ...
                createSharedIndex( geoPtr );

                // check if we have normals
                // need to port the geometry functions ...

                if(geoPtr->getNormals() == NULL)
                    calcVertexNormals(geoPtr);

                // create and link the node
                nodePtr = Node::create();
                nodePtr->setCore( geoPtr );

                if (meshList.size() > 1)
                {
                    if (rootPtr == NULL)
                    {
                        rootPtr = Node::create();

                        GroupUnrecPtr tmpPtr = Group::create();

                        rootPtr->setCore ( tmpPtr );
                        rootPtr->addChild(nodePtr);
                    }
                    else
                    {
                        rootPtr->addChild(nodePtr);
                    }
                }
                else
                {
                    rootPtr = nodePtr;
                }
            }
        }
    }

    SceneFileHandler::the()->updateReadProgress(100);

    commitChanges();

    return NodeTransitPtr(rootPtr);
}
Exemplo n.º 6
0
void OpenSGLatticeGeometry::updateGeometry(const bool all)
{
    showAll = all;
    calcNumOfPoints(all);

    // set number of points for each OPEN_GL type for lattice
    beginEditCP(numOfPointsPerType, GeoPLengthsUI32::GeoPropDataFieldMask);
        numOfPointsPerType->setValue(numOfLatticePoints, 0);
        numOfPointsPerType->setValue(numOfLatticeLinePoints, 1);
    endEditCP(numOfPointsPerType, GeoPLengthsUI32::GeoPropDataFieldMask);

    cellDivisions = lattice.getCellDivisions();
    const Lattice::Vector3d& cellPoints = lattice.getCellPoints();

    // create all used vertices for the lattice (gl_points)
    beginEditCP(latticePoints, GeoPositions3f::GeoPropDataFieldMask);
        latticePoints->clear();

        // vertices for gl_points
        for (int h = 0; h <= cellDivisions[0]; h+=step)
            for (int w = 0; w <= cellDivisions[1]; w+=step)
                for (int l = 0; l <= cellDivisions[2]; l+=step)
                    latticePoints->addValue(Pnt3f(cellPoints[h][w][l][0],
                                                  cellPoints[h][w][l][1],
                                                  cellPoints[h][w][l][2]));

        // vertices for gl_lines
        for (int h = 0; h < cellDivisions[0]; h+=step)
            for (int w = 0; w <= cellDivisions[1]; w+=step)
                for (int l = 0; l <= cellDivisions[2]; l+=step)
                {
                    latticePoints->addValue(Pnt3f(cellPoints[h][w][l][0],
                                                  cellPoints[h][w][l][1],
                                                  cellPoints[h][w][l][2]));
                    latticePoints->addValue(Pnt3f(cellPoints[h + step][w][l][0],
                                                  cellPoints[h + step][w][l][1],
                                                  cellPoints[h + step][w][l][2])
                                                  );
                }
        for (int h = 0; h <= cellDivisions[0]; h+=step)
            for (int w = 0; w < cellDivisions[1]; w+=step)
                for (int l = 0; l <= cellDivisions[2]; l+=step)
                {
                    latticePoints->addValue(Pnt3f(cellPoints[h][w][l][0],
                                                  cellPoints[h][w][l][1],
                                                  cellPoints[h][w][l][2]));
                    latticePoints->addValue(Pnt3f(cellPoints[h][w + step][l][0],
                                                  cellPoints[h][w + step][l][1],
                                                  cellPoints[h][w + step][l][2])
                                                  );
                }
        for (int h = 0; h <= cellDivisions[0]; h+=step)
            for (int w = 0; w <= cellDivisions[1]; w+=step)
                for (int l = 0; l < cellDivisions[2]; l+=step)
                {
                    latticePoints->addValue(Pnt3f(cellPoints[h][w][l][0],
                                                  cellPoints[h][w][l][1],
                                                  cellPoints[h][w][l][2]));
                    latticePoints->addValue(Pnt3f(cellPoints[h][w][l + step][0],
                                                  cellPoints[h][w][l + step][1],
                                                  cellPoints[h][w][l + step][2])
                                            );
                }
    endEditCP(latticePoints, GeoPositions3f::GeoPropDataFieldMask);

    // create all indices for lattice <-> vertex assignment
    beginEditCP(latticeIndices, GeoIndicesUI32::GeoPropDataFieldMask);
        latticeIndices->clear();
        for (size_t i = 0; i < numOfLatticePoints; ++i)
            latticeIndices->addValue(i);
        for (size_t i = 0; i < numOfLatticeLinePoints; ++i)
            latticeIndices->addValue(numOfLatticePoints + i);
    endEditCP(latticeIndices, GeoIndicesUI32::GeoPropDataFieldMask);

    // assign vertices, colors, indices to geometry
#if OSG_MAJOR_VERSION >= 2
	beginEditCP(latticeGeo);
#else
	beginEditCP(latticeGeo, Geometry::TypesFieldMask |
                            Geometry::LengthsFieldMask |
                            Geometry::PositionsFieldMask |
                            Geometry::IndicesFieldMask |
                            Geometry::ColorsFieldMask);	
#endif
        latticeGeo->setTypes(latticeTypes);
        latticeGeo->setLengths(numOfPointsPerType);
        latticeGeo->setIndices(latticeIndices);
        latticeGeo->setPositions(latticePoints);
        latticeGeo->setColors(latticeColors);
        calcVertexNormals(latticeGeo);
#if OSG_MAJOR_VERSION >= 2
	 endEditCP(latticeGeo);
#else
	 endEditCP(latticeGeo, Geometry::TypesFieldMask |
                          Geometry::LengthsFieldMask |
                          Geometry::PositionsFieldMask |
                          Geometry::IndicesFieldMask |
                          Geometry::ColorsFieldMask);
#endif
   

    changeColor();
}
Exemplo n.º 7
0
bool vtkOsgConverter::WriteAnActor()
{
	vtkMapper* actorMapper = _actor->GetMapper();
	// see if the actor has a mapper. it could be an assembly
	if (actorMapper == NULL)
		return false;
	// dont export when not visible
	if (_actor->GetVisibility() == 0)
		return false;

	vtkDataObject* inputDO = actorMapper->GetInputDataObject(0, 0);
	if (inputDO == NULL)
		return false;

	// Get PolyData. Convert if necessary becasue we only want polydata
	vtkSmartPointer<vtkPolyData> pd;
	if(inputDO->IsA("vtkCompositeDataSet"))
	{
		vtkCompositeDataGeometryFilter* gf = vtkCompositeDataGeometryFilter::New();
		gf->SetInput(inputDO);
		gf->Update();
		pd = gf->GetOutput();
		gf->Delete();
	}
	else if(inputDO->GetDataObjectType() != VTK_POLY_DATA)
	{
		vtkGeometryFilter* gf = vtkGeometryFilter::New();
		gf->SetInput(inputDO);
		gf->Update();
		pd = gf->GetOutput();
		gf->Delete();
	}
	else
		pd = static_cast<vtkPolyData*>(inputDO);

	// Get the color range from actors lookup table
	double range[2];
	vtkLookupTable* actorLut = static_cast<vtkLookupTable*>(actorMapper->GetLookupTable());
	actorLut->GetTableRange(range);

	// Copy mapper to a new one
	vtkPolyDataMapper* pm = vtkPolyDataMapper::New();
	// Convert cell data to point data
	// NOTE: Comment this out to export a mesh
	if (actorMapper->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_DATA ||
		actorMapper->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)
	{
		vtkCellDataToPointData* cellDataToPointData = vtkCellDataToPointData::New();
		cellDataToPointData->PassCellDataOff();
		cellDataToPointData->SetInput(pd);
		cellDataToPointData->Update();
		pd = cellDataToPointData->GetPolyDataOutput();
		cellDataToPointData->Delete();

		pm->SetScalarMode(VTK_SCALAR_MODE_USE_POINT_DATA);
	}
	else
		pm->SetScalarMode(actorMapper->GetScalarMode());

	pm->SetInput(pd);
	pm->SetScalarVisibility(actorMapper->GetScalarVisibility());

	vtkLookupTable* lut = NULL;
	// ParaView OpenSG Exporter
	if (dynamic_cast<vtkDiscretizableColorTransferFunction*>(actorMapper->GetLookupTable()))
		lut = actorLut;
	// Clone the lut in OGS because otherwise the original lut gets destroyed
	else
	{
		lut = vtkLookupTable::New();
		lut->DeepCopy(actorLut);
		lut->Build();
	}
	pm->SetLookupTable(lut);
	pm->SetScalarRange(range);
	pm->Update();

	if(pm->GetScalarMode() == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA ||
	   pm->GetScalarMode() == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA )
	{
		if(actorMapper->GetArrayAccessMode() == VTK_GET_ARRAY_BY_ID )
			pm->ColorByArrayComponent(actorMapper->GetArrayId(),
			                          actorMapper->GetArrayComponent());
		else
			pm->ColorByArrayComponent(actorMapper->GetArrayName(),
			                          actorMapper->GetArrayComponent());
	}


	vtkPointData* pntData = pd->GetPointData();
	bool hasTexCoords = false;
	vtkUnsignedCharArray* vtkColors = pm->MapScalars(1.0);

	// ARRAY SIZES
	vtkIdType m_iNumPoints = pd->GetNumberOfPoints();
	if (m_iNumPoints == 0)
		return false;
	vtkIdType m_iNumGLPoints = pd->GetVerts()->GetNumberOfCells();
	vtkIdType m_iNumGLLineStrips = pd->GetLines()->GetNumberOfCells();
	vtkIdType m_iNumGLPolygons = pd->GetPolys()->GetNumberOfCells();
	vtkIdType m_iNumGLTriStrips = pd->GetStrips()->GetNumberOfCells();
	vtkIdType m_iNumGLPrimitives = m_iNumGLPoints + m_iNumGLLineStrips + m_iNumGLPolygons +
	                               m_iNumGLTriStrips;
	bool lit = !(m_iNumGLPolygons == 0 && m_iNumGLTriStrips == 0);

	if (_verbose)
	{
		std::cout << "Array sizes:" << std::endl;
		std::cout << "  number of vertices: " << m_iNumPoints << std::endl;
		std::cout << "  number of GL_POINTS: " << m_iNumGLPoints << std::endl;
		std::cout << "  number of GL_LINE_STRIPS: " << m_iNumGLLineStrips << std::endl;
		std::cout << "  number of GL_POLYGON's: " << m_iNumGLPolygons << std::endl;
		std::cout << "  number of GL_TRIANGLE_STRIPS: " << m_iNumGLTriStrips << std::endl;
		std::cout << "  number of primitives: " << m_iNumGLPrimitives << std::endl;
	}

	// NORMALS
	vtkDataArray* vtkNormals = NULL;
	int m_iNormalType = NOT_GIVEN;
	if (_actor->GetProperty()->GetInterpolation() == VTK_FLAT)
	{
		vtkNormals = pd->GetCellData()->GetNormals();
		if (vtkNormals != NULL)
			m_iNormalType = PER_CELL;
	}
	else
	{
		vtkNormals = pntData->GetNormals();
		if (vtkNormals != NULL)
			m_iNormalType = PER_VERTEX;
	}
	if (_verbose)
	{
		std::cout << "Normals:" << std::endl;
		if (m_iNormalType != NOT_GIVEN)
		{
			std::cout << "  number of normals: " << vtkNormals->GetNumberOfTuples() <<
			std::endl;
			std::cout << "  normals are given: ";
			std::cout <<
			((m_iNormalType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl;
		}
		else
			std::cout << "  no normals are given" << std::endl;
	}

	// COLORS
	int m_iColorType = NOT_GIVEN;
	if(pm->GetScalarVisibility())
	{
		int iScalarMode = pm->GetScalarMode();
		if(vtkColors == NULL)
		{
			m_iColorType = NOT_GIVEN;
			std::cout << "WARNING: MapScalars(1.0) did not return array!" << std::endl;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_DATA)
			m_iColorType = PER_CELL;
		else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_DATA)
			m_iColorType = PER_VERTEX;
		else if(iScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA)
		{
			std::cout <<
			"WARNING TO BE REMOVED: Can not process colours with scalar mode using cell field data!"
			          << std::endl;
			m_iColorType = PER_CELL;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA)
		{
			std::cout <<
			"WARNING TO BE REMOVED: Can not process colours with scalar mode using point field data!"
			          << std::endl;
			m_iColorType = PER_VERTEX;
		}
		else if(iScalarMode == VTK_SCALAR_MODE_DEFAULT)
		{
			//Bummer, we do not know what it is. may be we can make a guess
			int numColors = vtkColors->GetNumberOfTuples();
			if (numColors == 0)
			{
				m_iColorType = NOT_GIVEN;
				std::cout << "WARNING: No colors found!" << std::endl;
			}
			else if (numColors == m_iNumPoints)
				m_iColorType = PER_VERTEX;
			else if (numColors == m_iNumGLPrimitives)
				m_iColorType = PER_CELL;
			else
			{
				m_iColorType = NOT_GIVEN;
				std::cout <<
				"WARNING: Number of colors do not match number of points / cells!"
				          << std::endl;
			}
		}
	}
	if (_verbose)
	{
		std::cout << "Colors:" << std::endl;
		if (m_iColorType != NOT_GIVEN)
		{
			std::cout << "  number of colors: " << vtkColors->GetNumberOfTuples() <<
			std::endl;
			std::cout << "  colors are given: " <<
			((m_iColorType == PER_VERTEX) ? "per vertex" : "per cell") << std::endl;
		}
		else
			std::cout << "  no colors are given" << std::endl;
	}

	// TEXCOORDS
	vtkDataArray* vtkTexCoords = pntData->GetTCoords();
	if (_verbose)
	{
		std::cout << "Tex-coords:" << std::endl;
		if (vtkTexCoords)
		{
			std::cout << "  Number of tex-coords: " <<
			vtkTexCoords->GetNumberOfTuples() << std::endl;
			hasTexCoords = true;
		}
		else
			std::cout << "  No tex-coords where given" << std::endl;
	}

	// TRANSFORMATION
	double scaling[3];
	double translation[3];
	// double rotation[3];

	_actor->GetPosition(translation);
	_actor->GetScale(scaling);
	//_actor->GetRotation(rotation[0], rotation[1], rotation[2]);

	if (_verbose)
		std::cout << "set scaling: " << scaling[0] << " " << scaling[1] << " " <<
		scaling[2] << std::endl;

	osg::Matrix m;
	m.setIdentity();
	m.setTranslate(translation[0], translation[1], translation[2]);
	m.setScale(scaling[0], scaling[1], scaling[2]);
	// TODO QUATERNION m.setRotate(rotation[0], rotation[1], rotation[2])
	beginEditCP(_osgTransform);
	_osgTransform->setMatrix(m);
	endEditCP(_osgTransform);

	//pm->Update();

	// Get the converted OpenSG node
	NodePtr osgGeomNode = Node::create();
	GeometryPtr osgGeometry = Geometry::create();
	beginEditCP(osgGeomNode);
	osgGeomNode->setCore(osgGeometry);
	endEditCP(osgGeomNode);

	bool osgConversionSuccess = false;

	GeoPTypesPtr osgTypes = GeoPTypesUI8::create();
	GeoPLengthsPtr osgLengths = GeoPLengthsUI32::create();
	GeoIndicesUI32Ptr osgIndices = GeoIndicesUI32::create();
	GeoPositions3fPtr osgPoints = GeoPositions3f::create();
	GeoNormals3fPtr osgNormals = GeoNormals3f::create();
	GeoColors3fPtr osgColors = GeoColors3f::create();
	GeoTexCoords2dPtr osgTexCoords = GeoTexCoords2d::create();

	//Rendering with OpenSG simple indexed geometry
	if (((m_iNormalType == PER_VERTEX) || (m_iNormalType == NOT_GIVEN)) &&
		((m_iColorType == PER_VERTEX) || (m_iColorType == NOT_GIVEN)))
	{
		if (_verbose)
			std::cout << "Start ProcessGeometryNormalsAndColorsPerVertex()" << std::endl;

		//getting the vertices:
		beginEditCP(osgPoints);
		{
			for (int i = 0; i < m_iNumPoints; i++)
			{
				double* aVertex = pd->GetPoint(i);
				osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2]));
			}
		} endEditCP(osgPoints);

		//possibly getting the normals
		if (m_iNormalType == PER_VERTEX)
		{
			vtkIdType iNumNormals = vtkNormals->GetNumberOfTuples();
			beginEditCP(osgNormals);
			{
				double* aNormal;
				for (int i = 0; i < iNumNormals; i++)
				{
					aNormal = vtkNormals->GetTuple(i);
					osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
				}
			} endEditCP(osgNormals);
			if (iNumNormals != m_iNumPoints)
			{
				std::cout <<
				"WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of normals"
				          << std::endl;
				std::cout << "should equal the number of vertices (points)!" <<	std::endl << std::endl;
			}
		}

		//possibly getting the colors
		if (m_iColorType == PER_VERTEX)
		{
			vtkIdType iNumColors = vtkColors->GetNumberOfTuples();
			beginEditCP(osgColors);
			{
				unsigned char aColor[4];
				for (int i = 0; i < iNumColors; i++)
				{
					vtkColors->GetTupleValue(i, aColor);
					float r = ((float) aColor[0]) / 255.0f;
					float g = ((float) aColor[1]) / 255.0f;
					float b = ((float) aColor[2]) / 255.0f;
					osgColors->addValue(Color3f(r, g, b));
				}
			} endEditCP(osgColors);
			if (iNumColors != m_iNumPoints)
			{
				std::cout <<
				"WARNING: CVtkActorToOpenSG::ProcessGeometryNormalsAndColorsPerVertex() number of colors"
				          << std::endl;
				std::cout << "should equal the number of vertices (points)!" << std::endl << std::endl;
			}
		}

		//possibly getting the texture coordinates. These are alwary per vertex
		if (vtkTexCoords != NULL)
		{
			int numTuples = vtkTexCoords->GetNumberOfTuples();
			for (int i = 0; i < numTuples; i++)
			{
				double texCoords[3];
				vtkTexCoords->GetTuple(i, texCoords);
				osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1]));
			}
		}

		//getting the cells
		beginEditCP(osgTypes);
		beginEditCP(osgLengths);
		beginEditCP(osgIndices);
		{
			vtkCellArray* pCells;
			vtkIdType npts, * pts;
			int prim;

			prim = 0;
			pCells = pd->GetVerts();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_POINTS);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetLines();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_LINE_STRIP);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetPolys();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
				     prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_POLYGON);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}

			prim = 0;
			pCells = pd->GetStrips();
			if (pCells->GetNumberOfCells() > 0)
				for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts); prim++)
				{
					osgLengths->addValue(npts);
					osgTypes->addValue(GL_TRIANGLE_STRIP);
					for (int i = 0; i < npts; i++)
						osgIndices->addValue(pts[i]);
				}
		} endEditCP(osgIndices);
		endEditCP(osgLengths);
		endEditCP(osgTypes);

		ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords);
		beginEditCP(osgGeometry);
		{
			osgGeometry->setPositions(osgPoints);
			osgGeometry->setTypes(osgTypes);
			osgGeometry->setLengths(osgLengths);
			osgGeometry->setIndices(osgIndices);
			osgGeometry->setMaterial(material);

			if (m_iNormalType == PER_VERTEX)
				osgGeometry->setNormals(osgNormals);
			if (m_iColorType == PER_VERTEX)
				osgGeometry->setColors(osgColors);
			if (osgTexCoords->getSize() > 0)
				osgGeometry->setTexCoords(osgTexCoords);
		} endEditCP(osgGeometry);

		osgConversionSuccess = true;

		if (_verbose)
			std::cout << "    End ProcessGeometryNormalsAndColorsPerVertex()" <<
			std::endl;
	}
	else
	{
		//Rendering with OpenSG non indexed geometry by copying a lot of attribute data
		if (_verbose)
			std::cout <<
			"Start ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" <<
			std::endl;
		int gl_primitive_type = -1;
		if(m_iNumGLPolygons > 0)
		{
			if(m_iNumGLPolygons != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_POLYGON;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POLYGON, pd, osgGeometry);
		}
		else if(m_iNumGLLineStrips > 0)
		{
			if (m_iNumGLLineStrips != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_LINE_STRIP;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_LINE_STRIP, pd osgGeometry);
		}
		else if(m_iNumGLTriStrips > 0)
		{
			if (m_iNumGLTriStrips != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_TRIANGLE_STRIP;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_TRIANGLE_STRIP, pd osgGeometry);
		}
		else if (m_iNumGLPoints > 0)
		{
			if (m_iNumGLPoints != m_iNumGLPrimitives)
				std::cout << "WARNING: vtkActor contains different kind of primitives" << std::endl;
			gl_primitive_type = GL_POINTS;
			//osgConversionSuccess = this->ProcessGeometryNonIndexedCopyAttributes(GL_POINTS, pd osgGeometry);
		}
		if(gl_primitive_type != -1)
		{
			vtkCellArray* pCells;
			if (gl_primitive_type == GL_POINTS)
				pCells = pd->GetVerts();
			else if (gl_primitive_type == GL_LINE_STRIP)
				pCells = pd->GetLines();
			else if (gl_primitive_type == GL_POLYGON)
				pCells = pd->GetPolys();
			else if (gl_primitive_type == GL_TRIANGLE_STRIP)
				pCells = pd->GetStrips();
			else
			{
				std::cout <<
				"CVtkActorToOpenSG::ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)"
				<< std::endl << " was called with non implemented gl_primitive_type!" << std::endl;
			}

			beginEditCP(osgTypes);
			beginEditCP(osgLengths);
			beginEditCP(osgPoints);
			beginEditCP(osgColors);
			beginEditCP(osgNormals);
			{
				int prim = 0;
				if (pCells->GetNumberOfCells() > 0)
				{
					vtkIdType npts, * pts;
					for (pCells->InitTraversal(); pCells->GetNextCell(npts, pts);
					     prim++)
					{
						osgLengths->addValue(npts);
						osgTypes->addValue(GL_POLYGON);
						for (int i = 0; i < npts; i++)
						{
							double* aVertex;
							double* aNormal;
							unsigned char aColor[4];

							aVertex = pd->GetPoint(pts[i]);
							osgPoints->addValue(Vec3f(aVertex[0], aVertex[1], aVertex[2]));

							if (m_iNormalType == PER_VERTEX)
							{
								aNormal =
								        vtkNormals->GetTuple(pts[i]);
								osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
							}
							else if (m_iNormalType == PER_CELL)
							{
								aNormal = vtkNormals->GetTuple(prim);
								osgNormals->addValue(Vec3f(aNormal[0], aNormal[1], aNormal[2]));
							}

							if (m_iColorType == PER_VERTEX)
							{
								vtkColors->GetTupleValue(pts[i], aColor);
								float r = ((float) aColor[0]) /	 255.0f;
								float g = ((float) aColor[1]) / 255.0f;
								float b = ((float) aColor[2]) / 255.0f;
								osgColors->addValue(Color3f(r, g, b));
							}
							else if (m_iColorType == PER_CELL)
							{
								vtkColors->GetTupleValue(prim,
								                         aColor);
								float r = ((float) aColor[0]) /	255.0f;
								float g = ((float) aColor[1]) / 255.0f;
								float b = ((float) aColor[2]) / 255.0f;
								osgColors->addValue(Color3f(r, g, b));
							}
						}
					}
				}
			} endEditCP(osgTypes);
			endEditCP(osgLengths);
			endEditCP(osgPoints);
			endEditCP(osgColors);
			endEditCP(osgNormals);

			//possibly getting the texture coordinates. These are always per vertex
			vtkPoints* points = pd->GetPoints();
			if ((vtkTexCoords != NULL) && (points != NULL))
			{
				int numPoints = points->GetNumberOfPoints();
				int numTexCoords = vtkTexCoords->GetNumberOfTuples();
				if (numPoints == numTexCoords)
				{
					beginEditCP(osgTexCoords);
					{
						int numTuples = vtkTexCoords->GetNumberOfTuples();
						for (int i = 0; i < numTuples; i++)
						{
							double texCoords[3];
							vtkTexCoords->GetTuple(i, texCoords);
							osgTexCoords->addValue(Vec2f(texCoords[0], texCoords[1]));
						}
					} endEditCP(osgTexCoords);
				}
			}

			ChunkMaterialPtr material = CreateMaterial(lit, hasTexCoords);
			//GeometryPtr geo = Geometry::create();
			beginEditCP(osgGeometry);
			{
				osgGeometry->setPositions(osgPoints);
				osgGeometry->setTypes(osgTypes);
				osgGeometry->setLengths(osgLengths);
				osgGeometry->setMaterial(material);

				if (m_iNormalType != NOT_GIVEN)
					osgGeometry->setNormals(osgNormals);
				if (m_iColorType != NOT_GIVEN)
					osgGeometry->setColors(osgColors);
				if (osgTexCoords->getSize() > 0)
					osgGeometry->setTexCoords(osgTexCoords);
				//geo->setMaterial(getDefaultMaterial());
			} endEditCP(osgGeometry);

			osgConversionSuccess = true;
		}
		if (_verbose)
			std::cout <<
			"    End ProcessGeometryNonIndexedCopyAttributes(int gl_primitive_type)" <<
			std::endl;
	}

	if(!osgConversionSuccess)
	{
		std::cout << "OpenSG converter was not able to convert this actor." << std::endl;
		return false;
	}

	if(m_iNormalType == NOT_GIVEN)
	{
		//GeometryPtr newGeometryPtr = GeometryPtr::dcast(newNodePtr->getCore());
		if((osgGeometry != NullFC) && (m_iColorType == PER_VERTEX))
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per vertex!"
			          << std::endl;
			calcVertexNormals(osgGeometry);
		}
		else if ((osgGeometry != NullFC) && (m_iColorType == PER_CELL))
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per face!"
			          << std::endl;
			calcFaceNormals(osgGeometry);
		}
		else if (osgGeometry != NullFC)
		{
			std::cout <<
			"WARNING: Normals are missing in the vtk layer, calculating normals per vertex!"
			          << std::endl;
			calcVertexNormals(osgGeometry);
		}
	}

	std::cout << "Conversion finished." << std::endl;

	// Add node to root
	beginEditCP(_osgRoot);
	_osgRoot->addChild(osgGeomNode);
	endEditCP(_osgRoot);

	pm->Delete();

	return true;
}
Exemplo n.º 8
0
FBOViewportPtr createSceneFBO(void)
{
    //Create Camera Beacon
    Matrix CameraMat;
    CameraMat.setTranslate(0.0f,0.0f,4.0f);
    TransformPtr CameraBeconCore = Transform::create();
    beginEditCP(CameraBeconCore, Transform::MatrixFieldMask);
        CameraBeconCore->setMatrix(CameraMat);
    endEditCP(CameraBeconCore, Transform::MatrixFieldMask);

    NodePtr CameraBeconNode = Node::create();
    beginEditCP(CameraBeconNode, Node::CoreFieldMask);
        CameraBeconNode->setCore(CameraBeconCore);
    endEditCP(CameraBeconNode, Node::CoreFieldMask);

    //Create Camera
    PerspectiveCameraPtr TheCamera = PerspectiveCamera::create();
    beginEditCP(TheCamera);
        TheCamera->setFov(deg2rad(60.0f));
        TheCamera->setAspect(1.0f);
        TheCamera->setNear(0.1f);
        TheCamera->setFar(100.0f);
        TheCamera->setBeacon(CameraBeconNode);
    endEditCP(TheCamera);
    
    //Make the Material
    BlinnMaterialPtr TheMaterial = BlinnMaterial::create();
    beginEditCP(TheMaterial);
        TheMaterial->setDiffuse(0.8);
        TheMaterial->setColor(Color3f(1.0,1.0,1.0));
        TheMaterial->setAmbientColor(Color3f(1.0,1.0,1.0));
        TheMaterial->setNumLights(1);
    endEditCP(TheMaterial);

										
    // Make Torus Node (creates Torus in background of scene)
    NodePtr TorusGeometryNode = makeTorus(.5, 2, 24, 48);

    beginEditCP(TorusGeometryNode->getCore());
        GeometryPtr::dcast(TorusGeometryNode->getCore())->setMaterial(TheMaterial);
    endEditCP(TorusGeometryNode->getCore());
    calcVertexNormals(GeometryPtr::dcast(TorusGeometryNode->getCore()));
    calcVertexTangents(GeometryPtr::dcast(TorusGeometryNode->getCore()),0,Geometry::TexCoords7FieldId, Geometry::TexCoords6FieldId);

    RootTransformCore = Transform::create();

    NodePtr TorusTransformNode = Node::create();
    beginEditCP(TorusTransformNode, Node::CoreFieldMask);
        TorusTransformNode->setCore(RootTransformCore);
        TorusTransformNode->addChild(TorusGeometryNode);
    endEditCP(TorusTransformNode, Node::CoreFieldMask);

    //Create Light Beacon
    Matrix LightMat;
    LightMat.setTranslate(0.0f,10.0f,1.0f);
    TransformPtr LightBeconCore = Transform::create();
    beginEditCP(LightBeconCore, Transform::MatrixFieldMask);
        LightBeconCore->setMatrix(LightMat);
    endEditCP(LightBeconCore, Transform::MatrixFieldMask);

    NodePtr LightBeconNode = Node::create();
    beginEditCP(LightBeconNode, Node::CoreFieldMask);
        LightBeconNode->setCore(LightBeconCore);
    endEditCP(LightBeconNode, Node::CoreFieldMask);

    //Create Light
    TheLight = PointLight::create();
    beginEditCP(TheLight);
        TheLight->setBeacon(LightBeconNode);
    endEditCP(TheLight);

    NodePtr LightNode = Node::create();
    beginEditCP(LightNode, Node::CoreFieldMask);
        LightNode->setCore(TheLight);
        LightNode->addChild(TorusTransformNode);
    endEditCP(LightNode, Node::CoreFieldMask);


    //Create Root

    NodePtr TheRoot = Node::create();
    beginEditCP(TheRoot);
        TheRoot->setCore(Group::create());
        TheRoot->addChild(CameraBeconNode);
        TheRoot->addChild(LightNode);
        TheRoot->addChild(LightBeconNode);
    endEditCP(TheRoot);

    //Create Background
    SolidBackgroundPtr TheBackground = SolidBackground::create();
    TheBackground->setColor(Color3f(1.0,0.0,0.0));

    //DepthClearBackgroundPtr TheBackground = DepthClearBackground::create();

    //Create the Image
    ImagePtr TheColorImage = Image::create();
    TheColorImage->set(Image::OSG_RGB_PF,2,2,1,1,1,0.0f,0,Image::OSG_FLOAT16_IMAGEDATA);

    //Create the texture
    TextureChunkPtr TheColorTextureChunk = TextureChunk::create();
    beginEditCP(TheColorTextureChunk);
        TheColorTextureChunk->setImage(TheColorImage);

        TheColorTextureChunk->setMinFilter(GL_NEAREST);
        TheColorTextureChunk->setMagFilter(GL_NEAREST);

        TheColorTextureChunk->setWrapS(GL_CLAMP_TO_EDGE);
        TheColorTextureChunk->setWrapR(GL_CLAMP_TO_EDGE);

        TheColorTextureChunk->setScale(false);
        TheColorTextureChunk->setNPOTMatrixScale(true);
        
        TheColorTextureChunk->setEnvMode(GL_REPLACE);
        TheColorTextureChunk->setInternalFormat(GL_RGB16F);

    endEditCP(TheColorTextureChunk);


    //Create FBO
    FBOViewportPtr TheFBO = FBOViewport::create();
    beginEditCP(TheFBO);
        TheFBO->setBackground(TheBackground);
        TheFBO->setRoot(TheRoot);
        TheFBO->setCamera(TheCamera);

        TheFBO->setEnabled(true);
        TheFBO->getTextures().push_back(TheColorTextureChunk);

        TheFBO->setStorageWidth(TheColorTextureChunk->getImage()->getWidth());
        TheFBO->setStorageHeight(TheColorTextureChunk->getImage()->getHeight());
        
        TheFBO->setSize(0,0,TheColorTextureChunk->getImage()->getWidth()-1, TheColorTextureChunk->getImage()->getHeight()-1);
    endEditCP(TheFBO);
    return TheFBO;
}
Exemplo n.º 9
0
/***************************************************************************\
*                              Field Set	                               *
\***************************************************************************/
void PhysicsTriMeshGeom::setGeometryNode(NodePtr& node)
{
    PhysicsTriMeshGeomPtr tmpPtr(*this);

    GeometryPtr geo = GeometryPtr::dcast(node->getCore());
    if(geo!=NullFC)
    {
        calcVertexNormals(geo, deg2rad( 30));
        separateProperties(geo);
        createSingleIndex(geo);

        GeoPositions3f::StoredFieldType* positions =
            GeoPositions3fPtr::dcast( geo->getPositions())->getFieldPtr();
        GeoIndicesUI32::StoredFieldType* indices =
            GeoIndicesUI32Ptr::dcast( geo->getIndices())->getFieldPtr();
        GeoNormals3f::StoredFieldType* normals =
            GeoNormals3fPtr::dcast( geo->getNormals())->getFieldPtr();

        GeoPTypesPtr geoTypes = geo->getTypes();
        bool triangles = false;
        //has to be some triangle soup!
        for( Int32 i=0; i < geoTypes->size(); ++i) {
            switch( geoTypes->getValue(i)) {
            case GL_TRIANGLES:
                triangles=true;
                break;
            case GL_TRIANGLE_STRIP:
                triangles=true;
                break;
            case GL_TRIANGLE_FAN:
                triangles=true;
                break;
            }
        }

        UInt32 vertexCount =
            GeoPositions3fPtr::dcast(geo->getPositions())->getSize();
        UInt32 vertexStride = 3*sizeof(Real32);
        UInt32 indexCount =
            GeoIndicesUI32Ptr::dcast(geo->getIndices())->getSize();
        UInt32 indexStride = 3*sizeof(UInt32);

        //pass the pointers to ODE
        if(tmpPtr->data)
            dGeomTriMeshDataDestroy(tmpPtr->data);
        tmpPtr->data = dGeomTriMeshDataCreate();
        if(triangles)
        {
            dGeomTriMeshDataBuildSingle(tmpPtr->data, (Real32*)&positions->front(),
                                        vertexStride, vertexCount, (Int32*)&indices->front(), indexCount,
                                        indexStride/* just can't use this, (Real32*)&normals->front()*/);
            tmpPtr->setData(tmpPtr->data);

            /* use this method if you build with single precision
            dGeomTriMeshDataBuildSingle1(tmpPtr->data, (Real32*)&positions->front(),
                vertexStride, vertexCount, (Int32*)&indices->front(), indexCount,
                indexStride, (Real32*)&normals->front());
            tmpPtr->setData(tmpPtr->data);
            */

        }
        else
        {
            FWARNING(("No triangle mesh given to ODE! Convert to triangles first!\n"));
            tmpPtr->setData(tmpPtr->data);
        }
    }
    tmpPtr->geoNode=node;
    PhysicsTriMeshGeomBase::setGeometryNode(node);
}
Exemplo n.º 10
0
// 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());

    //Make a SphereNode for the point light
    LambertMaterialPtr TheLightMat = LambertMaterial::create();
    beginEditCP(TheLightMat, LambertMaterial::IncandescenceFieldMask);
        TheLightMat->setIncandescence(Color3f(1.0,1.0,1.0));
    endEditCP(TheLightMat, LambertMaterial::IncandescenceFieldMask);

    GeometryPtr LightSphereGeo = makeSphereGeo(2,2.0);
    beginEditCP(LightSphereGeo, Geometry::MaterialFieldMask);
        LightSphereGeo->setMaterial(TheLightMat);
    endEditCP  (LightSphereGeo, Geometry::MaterialFieldMask);

    NodePtr LightSphereNode = Node::create();
    beginEditCP(LightSphereNode, Node::CoreFieldMask);
		LightSphereNode->setCore(LightSphereGeo);
    endEditCP  (LightSphereNode, Node::CoreFieldMask);

    //Create the beacon for the Point Light
    Matrix ThePointLightMat;
    ThePointLightMat.setTranslate(Vec3f(0.0,100.0,0.0));
    
    ThePointLightBeaconTransform = Transform::create();
    beginEditCP(ThePointLightBeaconTransform);
        ThePointLightBeaconTransform->setMatrix(ThePointLightMat);
    endEditCP(ThePointLightBeaconTransform);

    NodePtr ThePointLightBeaconNode = Node::create();
    beginEditCP(ThePointLightBeaconNode);
        ThePointLightBeaconNode->setCore(ThePointLightBeaconTransform);
        ThePointLightBeaconNode->addChild(LightSphereNode);
    endEditCP(ThePointLightBeaconNode);

    //Set the light properties desired
    PointLightPtr ThePointLight = PointLight::create();
    beginEditCP(ThePointLight);
        ThePointLight->setAmbient(0.3,0.3,0.3,0.3);
        ThePointLight->setDiffuse(1.0,1.0,1.0,1.0);
        ThePointLight->setSpecular(1.0,1.0,1.0,1.0);
        ThePointLight->setBeacon(ThePointLightBeaconNode);
    endEditCP(ThePointLight);

    NodePtr ThePointLightNode = Node::create();
    beginEditCP(ThePointLightNode);
        ThePointLightNode->setCore(ThePointLight);
    endEditCP(ThePointLightNode);
    
    //Set the light properties desired
    SpotLightPtr TheSpotLight = SpotLight::create();
    beginEditCP(TheSpotLight);
        TheSpotLight->setAmbient(0.3,0.3,0.3,0.3);
        TheSpotLight->setDiffuse(1.0,1.0,1.0,1.0);
        TheSpotLight->setSpecular(1.0,1.0,1.0,1.0);
        TheSpotLight->setBeacon(ThePointLightBeaconNode);
        TheSpotLight->setDirection(Vec3f(0.0,-1.0,0.0));
        TheSpotLight->setSpotExponent(5.0);
        TheSpotLight->setSpotCutOff(1.1);
    endEditCP(TheSpotLight);

    NodePtr TheSpotLightNode = Node::create();
    beginEditCP(TheSpotLightNode);
        TheSpotLightNode->setCore(TheSpotLight);
    endEditCP(TheSpotLightNode);

	//Load in the Heightmap Image
	ImagePtr PerlinNoiseImage = createPerlinImage(Vec2s(256,256), Vec2f(10.0f,10.0f),0.5f,1.0f,Vec2f(0.0f,0.0f),0.25f,6,PERLIN_INTERPOLATE_COSINE,false,Image::OSG_L_PF, Image::OSG_UINT8_IMAGEDATA);

    TextureChunkPtr TheTextureChunk = TextureChunk::create();
    beginEditCP(TheTextureChunk);
        TheTextureChunk->setImage(PerlinNoiseImage);
    endEditCP(TheTextureChunk);

    //Lambert Material
    LambertMaterialPtr TheLambertMat = LambertMaterial::create();
    beginEditCP(TheLambertMat, LambertMaterial::ColorFieldMask | LambertMaterial::AmbientColorFieldMask | LambertMaterial::DiffuseFieldMask
                              | LambertMaterial::NumLightsFieldMask | LambertMaterial::DiffuseTextureFieldMask);
        TheLambertMat->setColor(Color3f(0.0,1.0,0.0));
        TheLambertMat->setAmbientColor(Color3f(1.0,0.0,0.0));
        TheLambertMat->setDiffuse(0.5);
        TheLambertMat->setNumLights(1);
    endEditCP(TheLambertMat, LambertMaterial::ColorFieldMask | LambertMaterial::AmbientColorFieldMask | LambertMaterial::DiffuseFieldMask
                              | LambertMaterial::NumLightsFieldMask | LambertMaterial::DiffuseTextureFieldMask);
    

    //Blinn Material
    TheBlinnMat = BlinnMaterial::create();
    beginEditCP(TheBlinnMat, BlinnMaterial::ColorFieldMask | BlinnMaterial::AmbientColorFieldMask | BlinnMaterial::DiffuseFieldMask
         | BlinnMaterial::SpecularColorFieldMask | BlinnMaterial::SpecularEccentricityFieldMask | BlinnMaterial::SpecularRolloffFieldMask | BlinnMaterial::DiffuseTextureFieldMask);
        TheBlinnMat->setColor(Color3f(1.0,0.0,0.0));
        TheBlinnMat->setAmbientColor(Color3f(0.0,0.0,0.0));
        TheBlinnMat->setSpecularColor(Color3f(0.0,0.0,1.0));
        TheBlinnMat->setSpecularEccentricity(0.35);
        TheBlinnMat->setSpecularRolloff(0.85);
        TheBlinnMat->setDiffuse(0.65);
        TheBlinnMat->setDiffuseTexture(TheTextureChunk);
    endEditCP(TheBlinnMat, BlinnMaterial::ColorFieldMask | BlinnMaterial::AmbientColorFieldMask | BlinnMaterial::DiffuseFieldMask
         | BlinnMaterial::SpecularColorFieldMask | BlinnMaterial::SpecularEccentricityFieldMask | BlinnMaterial::SpecularRolloffFieldMask | BlinnMaterial::DiffuseTextureFieldMask);
    
    //Phong Material
    Phong2MaterialPtr ThePhongMat = Phong2Material::create();
    beginEditCP(ThePhongMat, Phong2Material::ColorFieldMask | Phong2Material::AmbientColorFieldMask | Phong2Material::DiffuseFieldMask
         | Phong2Material::SpecularColorFieldMask | Phong2Material::SpecularCosinePowerFieldMask);
        ThePhongMat->setColor(Color3f(1.0,0.0,0.0));
        ThePhongMat->setAmbientColor(Color3f(0.0,0.0,0.0));
        ThePhongMat->setSpecularColor(Color3f(0.0,0.0,1.0));
        ThePhongMat->setSpecularCosinePower(50.0);
        ThePhongMat->setDiffuse(0.65);
    endEditCP(ThePhongMat, Phong2Material::ColorFieldMask | Phong2Material::AmbientColorFieldMask | Phong2Material::DiffuseFieldMask
         | Phong2Material::SpecularColorFieldMask | Phong2Material::SpecularCosinePowerFieldMask);

    //Anisotropic Material
    AnisotropicMaterialPtr TheAnisotropicMat = AnisotropicMaterial::create();
    beginEditCP(TheAnisotropicMat, AnisotropicMaterial::ColorFieldMask | AnisotropicMaterial::AmbientColorFieldMask | AnisotropicMaterial::DiffuseFieldMask
         | AnisotropicMaterial::SpecularColorFieldMask | AnisotropicMaterial::SpecularRoughnessFieldMask | AnisotropicMaterial::SpecularFresnelIndexFieldMask
          | AnisotropicMaterial::SpecularSpreadXFieldMask | AnisotropicMaterial::SpecularSpreadYFieldMask);
        TheAnisotropicMat->setColor(Color3f(1.0,0.0,0.0));
        TheAnisotropicMat->setAmbientColor(Color3f(0.0,0.0,0.0));
        TheAnisotropicMat->setDiffuse(0.65);
        TheAnisotropicMat->setSpecularColor(Color3f(0.0,0.0,1.0));
        TheAnisotropicMat->setSpecularRoughness(32.0);
        TheAnisotropicMat->setSpecularFresnelIndex(0.85);
        TheAnisotropicMat->setSpecularSpreadX(1.0);
        TheAnisotropicMat->setSpecularSpreadY(1.0);
    endEditCP(TheAnisotropicMat, AnisotropicMaterial::ColorFieldMask | AnisotropicMaterial::AmbientColorFieldMask | AnisotropicMaterial::DiffuseFieldMask
         | AnisotropicMaterial::SpecularColorFieldMask | AnisotropicMaterial::SpecularRoughnessFieldMask | AnisotropicMaterial::SpecularFresnelIndexFieldMask
          | AnisotropicMaterial::SpecularSpreadXFieldMask | AnisotropicMaterial::SpecularSpreadYFieldMask);

    PointChunkPtr TempChunk = PointChunk::create();
    //addRefCP(TempChunk);

    //Anisotropic Material
    TheRampMat = RampMaterial::create();
    beginEditCP(TheRampMat);
        //Color
        TheRampMat->setRampSource(RampMaterial::RAMP_SOURCE_FACING_ANGLE);
        TheRampMat->getColors().push_back(Color3f(1.0,0.0,0.0));
        TheRampMat->getColorPositions().push_back(0.4);
        TheRampMat->getColorInterpolations().push_back(RampMaterial::RAMP_INTERPOLATION_SMOOTH);
        TheRampMat->getColors().push_back(Color3f(0.0,1.0,0.0));
        TheRampMat->getColorPositions().push_back(1.0);
        
        //Transparency
        TheRampMat->getTransparencies().push_back(Color3f(0.0,0.0,0.0));
        TheRampMat->getTransparencyPositions().push_back(0.83);
        TheRampMat->getTransparencyInterpolations().push_back(RampMaterial::RAMP_INTERPOLATION_SMOOTH);
        TheRampMat->getTransparencies().push_back(Color3f(1.0,1.0,1.0));
        TheRampMat->getTransparencyPositions().push_back(1.0);

        TheRampMat->setAmbientColor(Color3f(0.0,0.0,0.0));
        TheRampMat->setSpecularity(1.0);
        TheRampMat->setSpecularEccentricity(0.8);
        TheRampMat->getSpecularColors().push_back(Color3f(1.0,1.0,1.0));
        TheRampMat->getSpecularColorPositions().push_back(0.95);
        TheRampMat->getSpecularColorInterpolations().push_back(RampMaterial::RAMP_INTERPOLATION_SMOOTH);
        TheRampMat->getSpecularColors().push_back(Color3f(0.0,0.0,1.0));
        TheRampMat->getSpecularColorPositions().push_back(1.0);
        TheRampMat->getSpecularRolloffs().push_back(1.0);
        TheRampMat->getExtraChunks().push_back(TempChunk);
    endEditCP(TheRampMat);



	//Make the Heightmap Geometry
	HeightmapGeometryPtr TutorialHeightmapGeo = HeightmapGeometry::create();
	beginEditCP(TutorialHeightmapGeo, HeightmapGeometry::HeightImageFieldMask | HeightmapGeometry::DimensionsFieldMask | HeightmapGeometry::SegmentsFieldMask | HeightmapGeometry::ScaleFieldMask | HeightmapGeometry::OffsetFieldMask | HeightmapGeometry::MaterialFieldMask);
		TutorialHeightmapGeo->setHeightImage(PerlinNoiseImage);
		TutorialHeightmapGeo->setDimensions(Vec2f(200.0,200.0));
		TutorialHeightmapGeo->setSegments(Vec2f(150.0,150.0));
		TutorialHeightmapGeo->setScale(30.0);
		TutorialHeightmapGeo->setOffset(0.0);
		TutorialHeightmapGeo->setMaterial( TheBlinnMat );
	endEditCP(TutorialHeightmapGeo, HeightmapGeometry::HeightImageFieldMask | HeightmapGeometry::DimensionsFieldMask | HeightmapGeometry::SegmentsFieldMask | HeightmapGeometry::ScaleFieldMask | HeightmapGeometry::OffsetFieldMask | HeightmapGeometry::MaterialFieldMask);

    calcVertexNormals(TutorialHeightmapGeo);
    calcVertexTangents(TutorialHeightmapGeo,0,Geometry::TexCoords7FieldId, Geometry::TexCoords6FieldId);

    //Make the Heightmap Node
    NodePtr TutorialHeightmapNode = Node::create();
    beginEditCP(TutorialHeightmapNode, Node::CoreFieldMask);
		TutorialHeightmapNode->setCore(TutorialHeightmapGeo);
    endEditCP  (TutorialHeightmapNode, Node::CoreFieldMask);

    //Make a SphereNode
    GeometryPtr SphereGeo = makeSphereGeo(2,50.0);
    //GeometryPtr SphereGeo = makeCylinderGeo(50,20.0, 16,true,true,true);
    beginEditCP(SphereGeo, Geometry::MaterialFieldMask);
		SphereGeo->setMaterial(TheLambertMat);
    endEditCP  (SphereGeo, Geometry::MaterialFieldMask);
    calcVertexNormals(SphereGeo);
    calcVertexTangents(SphereGeo,0,Geometry::TexCoords7FieldId, Geometry::TexCoords6FieldId);

    NodePtr SphereNode = Node::create();
    beginEditCP(SphereNode, Node::CoreFieldMask);
		SphereNode->setCore(SphereGeo);
    endEditCP  (SphereNode, Node::CoreFieldMask);

    //Make Main Scene Node
    NodePtr scene = Node::create();
    beginEditCP(scene, Node::CoreFieldMask | Node::ChildrenFieldMask);
		scene->setCore(Group::create());
 
        // add the torus as a child
        scene->addChild(TutorialHeightmapNode);
        //scene->addChild(SphereNode);
        scene->addChild(ThePointLightBeaconNode);
    endEditCP  (scene, Node::CoreFieldMask | Node::ChildrenFieldMask);

    //Add the scene to the Light Nodes
    //beginEditCP(ThePointLightNode, Node::ChildrenFieldMask);
        //ThePointLightNode->addChild(scene);
    //endEditCP(ThePointLightNode, Node::ChildrenFieldMask);


    //// tell the manager what to manage
    //mgr->setRoot  (ThePointLightNode);

    beginEditCP(TheSpotLightNode, Node::ChildrenFieldMask);
        TheSpotLightNode->addChild(scene);
    endEditCP(TheSpotLightNode, Node::ChildrenFieldMask);


    // tell the manager what to manage
    mgr->setRoot  (TheSpotLightNode);
    mgr->turnHeadlightOff();

    // show the whole scene
    mgr->showAll();
    
    //Open Window
    Vec2f WinSize(TutorialWindowEventProducer->getDesktopSize() * 0.85f);
    Pnt2f WinPos((TutorialWindowEventProducer->getDesktopSize() - WinSize) *0.5);
    TutorialWindowEventProducer->openWindow(WinPos,
                        WinSize,
                                        "06Heightmap");

    //Main Loop
    TutorialWindowEventProducer->mainLoop();

    osgExit();

    return 0;
}