void
viewerSetUp( osgViewer::Viewer& viewer, double aspect, osg::Node* node )
{
    viewer.getCamera()->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
    viewer.getCamera()->setProjectionMatrixAsPerspective( 35., aspect, .1, 50. );

    viewer.getCamera()->setClearMask( 0 );

    viewer.setSceneData( backdropFX::Manager::instance()->getManagedRoot() );

    // No longer needed, apparently. Seems like Viewer used to focus the
    // camera manipulator on the entire SkyDome, putting it too far away from
    // the scene. This code compensated for that.
    //osgGA::TrackballManipulator* tb = new osgGA::TrackballManipulator();
    //viewer.setCameraManipulator( tb );
    //tb->setNode( root.get() );
    //tb->home( 0 );

    viewer.addEventHandler( new osgViewer::StatsHandler );
    viewer.addEventHandler( new osgViewer::ThreadingHandler );

    osgGA::TrackballManipulator* tbm = new osgGA::TrackballManipulator;
    viewer.setCameraManipulator( tbm );
    tbm->setNode( node );
    tbm->home( 0 );
}
void
viewerSetUp( osgViewer::Viewer& viewer, unsigned int width, unsigned int height, osg::Node* node )
{
    double aspect = (double)width / (double)height;

    viewer.setThreadingModel( osgViewer::ViewerBase::SingleThreaded );
    viewer.getCamera()->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
    viewer.getCamera()->setProjectionMatrix( createProjection( aspect ) );

    viewer.getCamera()->setClearMask( 0 );

    viewer.setSceneData( backdropFX::Manager::instance()->getManagedRoot() );

    // No longer needed, apparently. Seems like Viewer used to focus the
    // camera manipulator on the entire SkyDome, putting it too far away from
    // the scene. This code compensated for that.
    //osgGA::TrackballManipulator* tb = new osgGA::TrackballManipulator();
    //viewer.setCameraManipulator( tb );
    //tb->setNode( root.get() );
    //tb->home( 0 );

    viewer.addEventHandler( new osgViewer::StatsHandler );
    viewer.addEventHandler( new osgViewer::ThreadingHandler );
    viewer.addEventHandler( new ResizeHandler( viewer, width, height ) );

    osgGA::TrackballManipulator* tbm = new osgGA::TrackballManipulator;
    viewer.setCameraManipulator( tbm );
    tbm->setNode( node );
    tbm->home( 0 );
}
Exemple #3
0
void AppState::updateNear()
{
    // Assume that the viewing frustum is symmetric.
    double fovy, aspectRatio, cNear, cFar;
    viewer->getCamera()->getProjectionMatrixAsPerspective(fovy, aspectRatio,
                                                          cNear, cFar);
    viewer->getCamera()->setProjectionMatrixAsPerspective(fovy, aspectRatio,
                                                          zNear, cFar);
    stringstream nearStream;
    nearStream << "near: " << zNear;
    zNearText->setText(nearStream.str());
    zNearText->update();
}
Exemple #4
0
void updateUserStats(osgViewer::Viewer& viewer)
{
    // Test the custom stats line by just adding up the update and cull 
    // times for the viewer main camera for the previous frame.
    if (viewer.getViewerStats()->collectStats("update") && viewer.getCamera()->getStats()->collectStats("rendering"))
    {
        // First get the frame number. The code below assumes that 
        // updateUserStats() is called after advance(), so the frame number
        // that will be returned is for the frame that has just started and is
        // not rendered yet. The previous frame is framenumber-1, but we can't
        // use that frame's timings because it's probably not finished 
        // rendering yet (in multithreaded viewer modes). So we'll use the
        // timings for framenumber-2 for this demo.
        int framenumber = viewer.getFrameStamp()->getFrameNumber();

        // Get the update time and the viewer main camera's cull time. We use 
        // getAveragedAttribute() in order to get the actual time elapsed as 
        // calculated by the stats.
        double update = 0.0, cull = 0.0;
        viewer.getViewerStats()->getAveragedAttribute("Update traversal time taken", update);
        viewer.getCamera()->getStats()->getAveragedAttribute("Cull traversal time taken", cull);

        // Get various begin and end times, note these are not elapsed times 
        // in a frame but rather the simulation time at those moments.
        double eventBegin = 0.0, updateBegin = 0.0, cullEnd = 0.0, drawEnd = 0.0;
        viewer.getViewerStats()->getAttribute(framenumber-2, "Event traversal begin time", eventBegin);
        viewer.getViewerStats()->getAttribute(framenumber-2, "Update traversal begin time", updateBegin);
        viewer.getCamera()->getStats()->getAttribute(framenumber-2, "Cull traversal end time", cullEnd);
        viewer.getCamera()->getStats()->getAttribute(framenumber-2, "Draw traversal end time", drawEnd);

        // This line displays the frame number. It's not averaged, just displayed as is.
        viewer.getViewerStats()->setAttribute(framenumber, frameNumberName, framenumber);

        // This line displays the frame time (from beginning of event to end of draw). No bars.
        viewer.getViewerStats()->setAttribute(framenumber-1, frameTimeName, drawEnd - eventBegin);

        // This line displays the sum of update and main camera cull times.
        viewer.getViewerStats()->setAttribute(framenumber-1, customTimeName + " time taken", update+cull);
        // Since we give begin and end times that correspond to the begin of 
        // the update phase and the end of the cull phase, the bar in the 
        // graph will not correspond to the summed times above if something 
        // happened between update and cull (as in this demo). Also, we need 
        // to translate the updateBegin and cullEnd times by one frame since 
        // we're taking the times for framenumber-2 but using them to display
        // in the framenumber-1 graph.
        viewer.getViewerStats()->setAttribute(framenumber-1, customTimeName + " begin", updateBegin + (1.0/60.0));
        viewer.getViewerStats()->setAttribute(framenumber-1, customTimeName + " end", cullEnd + (1.0/60.0));
    }
}
Exemple #5
0
void setViewer(osgViewer::Viewer& viewer, float width, float height, float distance)
{
    double vfov = osg::RadiansToDegrees(atan2(height/2.0f,distance)*2.0);
    // double hfov = osg::RadiansToDegrees(atan2(width/2.0f,distance)*2.0);

    viewer.getCamera()->setProjectionMatrixAsPerspective( vfov, width/height, 0.1, 1000.0);
}
int main(int argc, char* argv[]) {
  ref_ptr<Group> root = new Group;
  viewer.setUpViewInWindow(0, 0, 640, 480);
  viewer.realize();
  ref_ptr<Camera> cam = viewer.getCamera();
  ref_ptr<Geode> geode = new Geode;
  root->addChild(geode.get());



  for (int i=0; i < 10; i++) {
    osg::Sphere* sphere = new osg::Sphere( Vec3f(i+1,10,0), .1*i);
    osg::ShapeDrawable* sphereDrawable = new osg::ShapeDrawable(sphere);
    geode->addDrawable(sphereDrawable);
  }

  // osg::Sphere* sphere = new osg::Sphere( Vec3f(10,10,0), .2);
  // osg::ShapeDrawable* sphereDrawable = new osg::ShapeDrawable(sphere);
  // sphereDrawable->setColor(osg::Vec4f(1,0,0,1));
  // geode->addDrawable(sphereDrawable);

  ref_ptr<osgGA::TrackballManipulator> manip = new osgGA::TrackballManipulator();


    viewer.setCameraManipulator(manip);

  viewer.setSceneData(root.get());
  cam->setViewMatrixAsLookAt(Vec3f(10,0,0), Vec3f(10,1,0), Vec3f(0,0,1));
  //manip->setHomePosition(Vec3f(10,0,0), Vec3f(11,1,0), Vec3f(10,0,1));
  //  cam->setProjectionMatrixAsPerspective(49,640/480., .1, 10);

  viewer.run();


}
Exemple #7
0
void LevelMenu::loadLevels()
{
    _itemsPat = new osg::PositionAttitudeTransform();
	_itemsPat->setPosition(osg::Vec3(viewer.getCamera()->getViewport()->width() - 400, viewer.getCamera()->getViewport()->height() - 250, 0)); 
    
    // load XML document
    rapidxml::file<> mf(LEVEL_OVERVIEW_FILE);
    rapidxml::xml_document<> xml_doc;
    xml_doc.parse<0>(mf.data());
    
    int itemIndex = 0;
    
    // parse XML document
    for(rapidxml::node_iterator<char> it(xml_doc.first_node()); it.dereference() != NULL; ++it, ++itemIndex)
    {
        if(strcmp(it->name(), "road") == 0)
        {         
            std::string name = it->first_attribute("name")->value();

        	osg::Geode *itemNode = new osg::Geode();

        	osgText::Text *text = new osgText::Text();
        	text->setFont(MENU_FONT);
        	text->setPosition(osg::Vec3(0, - (itemIndex * MENU_ITEM_HEIGHT), 0));
            text->setText(name);

            itemNode->addDrawable(text);
            _itemsPat->addChild(itemNode);
            
            std::map<std::string, std::string> item;

            item["name"] = it->first_attribute("name")->value();
            item["filename"] = it->first_attribute("filename")->value();
            item["besttime"] = it->first_attribute("besttime")->value();
            item["completions"] = it->first_attribute("completions")->value();
            item["deaths"] = it->first_attribute("deaths")->value();
            
            _items.push_back(item);
        }
        else
        {
            throw std::runtime_error("Error: Unrecognized element in level file!");
        }
    }
    
    _menuPat->addChild(_itemsPat);
}
Exemple #8
0
void SetCameraProjectionMatrix (osgViewer::Viewer& viewer, dFloat viewAngleInDegress, dFloat aspectRatio, dFloat nearPlane, dFloat farPlane)
{
	osg::Camera* const camera = viewer.getCamera();
	camera->setProjectionMatrixAsPerspective (viewAngleInDegress, aspectRatio, nearPlane, farPlane);

//	camera->setViewMatrixAsLookAt (osg::Vec3 (-3.0f, -5.0f, 2.0f), osg::Vec3 (0.0f, 0.0f, 2.0f), osg::Vec3 (0.0f, 0.0f, 1.0f));
	camera->setViewMatrixAsLookAt (osg::Vec3 (-0.0f, -5.0f, 2.0f), osg::Vec3 (0.0f, 0.0f, 2.0f), osg::Vec3 (0.0f, 0.0f, 1.0f));
}
Exemple #9
0
void setViewer(osgViewer::Viewer& viewer, float width, float height, float distance)
{
    double vfov = osg::RadiansToDegrees(atan2(height/2.0f,distance)*2.0);
    // double hfov = osg::RadiansToDegrees(atan2(width/2.0f,distance)*2.0);

    viewer.getCamera()->setProjectionMatrixAsPerspective( vfov, width/height, 0.1, 1000.0);

    OSG_NOTICE<<"setProjectionMatrixAsPerspective( "<<vfov<<", "<<width/height<<", "<<0.1<<", "<<1000.0<<");"<<std::endl;
}
Exemple #10
0
void LevelMenu::initializeHeader()
{
    osg::PositionAttitudeTransform *headerPat = new osg::PositionAttitudeTransform();
    osg::Geode *headerGeode = new osg::Geode();
    osg::Geometry *textureDrawable = new osg::Geometry();
    osg::Texture2D *texture;

    osg::Vec3Array *vertices = new osg::Vec3Array();
    {
        vertices->push_back(osg::Vec3(0, 0, 0));
        vertices->push_back(osg::Vec3(436, 0, 0));
        vertices->push_back(osg::Vec3(436, 75, 0));
        vertices->push_back(osg::Vec3(0, 75, 0));
    }

    textureDrawable->setVertexArray( vertices );

    osg::DrawElementsUInt *face = new osg::DrawElementsUInt(osg::PrimitiveSet::QUADS, 0);
    face->push_back(0);
    face->push_back(1);
    face->push_back(2);
    face->push_back(3);
    
    textureDrawable->addPrimitiveSet(face);
        
    osg::Vec2Array* texcoords = new osg::Vec2Array(4);
    {
        (*texcoords)[0].set(0.0f, 0.0f);
        (*texcoords)[1].set(1.0f, 0.0f); 
        (*texcoords)[2].set(1.0f, 1.0f);
        (*texcoords)[3].set(0.0f, 1.0f);

        textureDrawable->setTexCoordArray(0, texcoords);
    }
             
    texture = new osg::Texture2D;
    texture->setDataVariance(osg::Object::DYNAMIC); 
    texture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); 
    texture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);

    osg::StateSet* stateSet = new osg::StateSet();
    stateSet->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
    
    textureDrawable->setStateSet(stateSet);
    headerGeode->addDrawable(textureDrawable);
    headerPat->addChild(headerGeode);
    _menuPat->addChild(headerPat);
    
    headerPat->setPosition(osg::Vec3(100, viewer.getCamera()->getViewport()->height() - 125, -0.01)); 
	
    osg::Image *image = osgDB::readImageFile(LEVEL_HEADER_TEXTURE);
    texture->setImage(image);
}
void
viewerSetUp( osgViewer::Viewer& viewer, unsigned int width, unsigned int height, osg::Node* node )
{
    double aspect = (double)width / (double)height;

    viewer.setThreadingModel( osgViewer::ViewerBase::SingleThreaded );
    viewer.getCamera()->setComputeNearFarMode( osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR );
    viewer.getCamera()->setProjectionMatrix( createProjection( aspect ) );

    viewer.getCamera()->setClearMask( 0 );

    viewer.setSceneData( backdropFX::Manager::instance()->getManagedRoot() );

    viewer.addEventHandler( new osgViewer::StatsHandler );
    viewer.addEventHandler( new osgViewer::ThreadingHandler );
    viewer.addEventHandler( new ResizeHandler( viewer, width, height ) );

    osgGA::TrackballManipulator* tbm = new osgGA::TrackballManipulator;
    viewer.setCameraManipulator( tbm );
    tbm->setNode( node );
    tbm->home( 0 );
}
Exemple #12
0
void Sky::initializeCamera()
{   	
	_camera = new osg::Camera();
	_camera->setProjectionMatrix(osg::Matrix::ortho2D(0, viewer.getCamera()->getViewport()->width(), 0, viewer.getCamera()->getViewport()->height()));
	_camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
	_camera->setViewMatrix(osg::Matrix::identity());
	
	_camera->setClearColor(osg::Vec4(0.0f, 0.0f, 0.0f, 1.0f));
    _camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
	_camera->setRenderOrder(osg::Camera::PRE_RENDER);
	_camera->addChild(_skyPat);
}
int main(void){
	osg::DisplaySettings::instance()->setNumMultiSamples( 4 );
	viewer.setUpViewInWindow( 100, 50, 800, 600 );
	viewer.getCamera()->setClearColor( osg::Vec4( 0.5,0.5,0.5,1) );
	viewer.addEventHandler(new osgViewer::StatsHandler);
	
	scene = new osg::Group;
	
	osg::ref_ptr<osg::LightSource> lumiere = new osg::LightSource;
	lumiere->getLight()->setLightNum(0); // GL_LIGHT1
	lumiere->getLight()->setPosition(osg::Vec4(1, -1, 10, 0)); // 0 = directionnel
	lumiere->getLight()->setAmbient(osg::Vec4(0.5, 0.5, 0.5, 1.0));
	lumiere->getLight()->setDiffuse(osg::Vec4(0.9, 0.9, 0.9, 1.0));
	lumiere->getLight()->setSpecular(osg::Vec4(1.0, 1.0, 1.0, 1.0));
	scene->addChild(lumiere.get());
	
	terrain = creation_terrain();
	scene->addChild(terrain.get());
	scene->addChild(creation_foret(terrain, 500));
	
	LECHARRR = creation_CHARRR(0,0,terrain);
	scene->addChild(LECHARRR);
	
	LECHARRR->accept(rechercheTourelle);
	
	fumeeTank = new osgParticle::SmokeEffect;
	fumeeTank->setTextureFileName("fumee.tga");
	fumeeTank->setIntensity(2);
	fumeeTank->setScale(4);
	fumeeTank->setPosition(LECHARRR->getPosition());
	scene->addChild(fumeeTank.get());
	posCanonX = LECHARRR->getPosition().x();
	posCanonY = LECHARRR->getPosition().y() + 3.5;
	posCanonZ = LECHARRR->getPosition().z() + 4.0;
	
	
	
	
	viewer.setSceneData(scene);
	
	osg::ref_ptr<GestionEvenements> gestionnaire = new GestionEvenements();
	viewer.addEventHandler(gestionnaire.get());
	
	return viewer.run();
}
Exemple #14
0
void LevelMenu::returnFromLevel()
{
   	
    if(_currentLevel->playerReachedFinish())
    {
        // update completions
        {
            std::stringstream ss;
            ss << atoi(_items[_currentItemIndex]["completions"].c_str()) + 1;
            _items[_currentItemIndex]["completions"] = ss.str();
        }
        
        // update best time
        {
            time_t t = _currentLevel->getTime();

            if(_items[_currentItemIndex]["besttime"] == "" | t < atol(_items[_currentItemIndex]["besttime"].c_str()))
            {
                std::stringstream ss;
                ss << t;
                _items[_currentItemIndex]["besttime"] =  ss.str();
            }
        }
    }

    // update number of deaths
    {
        std::stringstream ss;
        ss << atoi(_items[_currentItemIndex]["deaths"].c_str()) + _currentLevel->getNumDeaths();
        _items[_currentItemIndex]["deaths"] = ss.str();
    }
    
    viewer.setCameraManipulator(NULL); 
    viewer.getCamera()->setViewMatrixAsLookAt(MENU_CAMERA_HOME_EYE, MENU_CAMERA_HOME_CENTER, MENU_CAMERA_HOME_UP);
	
    _currentLevel->resetScene();
    viewer.setSceneData(this);
    _currentLevel = NULL;
    
    Player::getInstance()->reset();
    updateDetails();
    
    Sound::getInstance()->stop(LEVEL_MUSIC_FILE);
    Sound::getInstance()->playInLoop(MENU_MUSIC_FILE);
}
Exemple #15
0
void InitWindowsSystem (osgViewer::Viewer& viewer, const char* const title, int x, int y, int width, int height)
{
	viewer.setUpViewInWindow(x, y, width, height);

	//Get the traits of the current window
	osg::ref_ptr< osg::GraphicsContext::Traits > traits = new osg::GraphicsContext::Traits( *viewer.getCamera()->getGraphicsContext()->getTraits());

	//Set the title
	traits->windowName = title;

	// disable vertical sync
	traits->vsync = false;

	//Create a new graphics context with the modified traits
	osg::ref_ptr< osg::GraphicsContext > gc = osg::GraphicsContext::createGraphicsContext( traits.get() );
	gc->realize();
	gc->makeCurrent();

	// set the vertical black off by default
	osgViewer::Viewer::Windows windows;
	viewer.getWindows(windows);
	for(osgViewer::Viewer::Windows::iterator itr = windows.begin(); itr != windows.end(); ++itr) {
		osgViewer::GraphicsWindow* const graphicsWindow = (*itr);
		graphicsWindow->setSyncToVBlank (false);
	}

	//Create the new camera which is a copy of the current camera in the viewer
	osg::ref_ptr<osg::Camera> cam = new osg::Camera( *viewer.getCamera() ); 

	//Set the cameras graphics context to the gc we made above
	cam->setGraphicsContext( gc );

	//assign the viewer the new camera
	viewer.setCamera( cam.get() );

	// int the camera default perspective matrix
	SetCameraProjectionMatrix (viewer, 60.0f, dFloat (width) / height, 0.01, 1000.0f);


	// set the file find callback
	osg::ref_ptr<DemosFindFileCallback> filecallback = new DemosFindFileCallback;
	osgDB::Registry::instance()->setFindFileCallback (filecallback.get());
}
Exemple #16
0
LevelMenu::LevelMenu() :
    _currentLevel(NULL),
    _currentItemIndex(0)
{
	_menuPat = new osg::PositionAttitudeTransform();
	_menuPat->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

    _keyboardHandler = new MenuKeyboardHandler(this);
    viewer.addEventHandler(_keyboardHandler);

	initializeCamera();
    initializeHeader();
    initializeBackgroundAnimation();
    initializeSelector();
    loadLevels();
    updateDetails();
            
    viewer.getCamera()->setUpdateCallback(new LevelMenuUpdater(this));

    Sound::getInstance()->playInLoop(MENU_MUSIC_FILE);    
}
Exemple #17
0
void LevelMenu::resetCamera()
{
    viewer.setCameraManipulator(NULL); 
    viewer.getCamera()->setViewMatrixAsLookAt(MENU_CAMERA_HOME_EYE, MENU_CAMERA_HOME_CENTER, MENU_CAMERA_HOME_UP);
}
Exemple #18
0
Sky::Sky() 
{
	_skyPat = new osg::PositionAttitudeTransform();
	_skyPat->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);

	initializeCamera();
	
	osg::Geode* geode = new osg::Geode();
    osg::Geometry *geometry = new osg::Geometry();
    geode->addDrawable(geometry);
    
    osg::Vec3Array *vertices = new osg::Vec3Array;

    int screenWidth = viewer.getCamera()->getViewport()->width();
    int screenHeight = viewer.getCamera()->getViewport()->height();
    
    vertices->push_back( osg::Vec3(0, 0, 0) );
    vertices->push_back( osg::Vec3(0, screenHeight, 0) );
    vertices->push_back( osg::Vec3(screenWidth, screenHeight, 0) ); 
    vertices->push_back( osg::Vec3(screenWidth, 0, 0) );
    
    geometry->setVertexArray(vertices);
    
    osg::DrawElementsUInt *rectangle = new osg::DrawElementsUInt(osg::PrimitiveSet::QUADS, 0);
    
    rectangle->push_back(0);
    rectangle->push_back(1);
    rectangle->push_back(2);
    rectangle->push_back(3);
    
    geometry->addPrimitiveSet(rectangle);    
    
    osg::Vec2Array* texcoords = new osg::Vec2Array(4);

    (*texcoords)[0].set(0.0f, 0.0f);
    (*texcoords)[1].set(0.0f, 1.0f);
    (*texcoords)[2].set(1.0f, 1.0f);
    (*texcoords)[3].set(1.0f, 0.0f); 
    
    geometry->setTexCoordArray(0, texcoords);
    
    osg::Texture2D *texture = new osg::Texture2D;
    texture->setDataVariance(osg::Object::DYNAMIC); 

    osg::Image *image = osgDB::readImageFile(BACKGROUND_IMAGE);

    if (!image)
    {
        std::cout << " couldn't find texture, quiting." << std::endl;
        exit(0);
    }

    // assign image to texture
    texture->setImage(image); 
    
    osg::StateSet* stateOne = new osg::StateSet();

    stateOne->setTextureAttributeAndModes(0, texture,osg::StateAttribute::ON);

    geode->setStateSet(stateOne);
    _skyPat->addChild(geode);  
}
Exemple #19
0
//-----------------------------------------------------------------------------
// Dynamics plugin entry point.
    void init( int argc, char** argv ) {

        //+++++++++++++++++++++++++++++++++++++++
        dyn_error_log = log_c( FD_ERROR_LOG );
        if( dyn_error_log.open( ) != LOG_ERROR_NONE ) {
            // Note: this is not really necessary
            printf( "(dynamics.cpp) ERROR: init(argc,argv) failed calling log_c.open() on FD_ERROR_LOG\n" );
        }
        //+++++++++++++++++++++++++++++++++++++++

        const unsigned ONECHAR_ARG = 3, TWOCHAR_ARG = 4;

#ifdef USE_OSG
        viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
        viewer_pointer = &viewer;
#endif

        // setup some default options
        std::string scene_path;
        THREED_IVAL = 0;
        IMAGE_IVAL = 0;

        // check that syntax is ok
        if (argc < 2) {
            std::cerr << "syntax: driver [OPTIONS] <xml file>" << std::endl;
            std::cerr << "        (see README for OPTIONS)" << std::endl;
            return;
        }

        // get all options
        for (int i=1; i< argc-1; i++) {
            // get the option
            std::string option(argv[i]);

            // process options
            if (option == "-r") {
                ONSCREEN_RENDER = true;
                UPDATE_GRAPHICS = true;
                check_osg();
            } else if (option.find("-of") != std::string::npos) {
                OUTPUT_FRAME_RATE = true;
            } else if (option.find("-ot") != std::string::npos) {
                OUTPUT_TIMINGS = true;
            } else if (option.find("-oi") != std::string::npos) {
                OUTPUT_ITER_NUM = true;
            } else if (option.find("-or") != std::string::npos) {
                OUTPUT_SIM_RATE = true;
            } else if (option.find("-v=") != std::string::npos) {
                UPDATE_GRAPHICS = true;
                check_osg();
                THREED_IVAL = std::atoi(&argv[i][ONECHAR_ARG]);
                //assert(THREED_IVAL >= 0);     // Note: remarked because always true
            } else if (option.find("-i=") != std::string::npos) {
                check_osg();
                UPDATE_GRAPHICS = true;
                IMAGE_IVAL = std::atoi(&argv[i][ONECHAR_ARG]);
                //assert(IMAGE_IVAL >= 0);      // Note: remarked because always true
            } else if (option.find("-t") != std::string::npos) {
                OUTPUT_TO_TIME = true;
            } else if (option.find("-s=") != std::string::npos) {
                STEP_SIZE = std::atof(&argv[i][ONECHAR_ARG]);
                assert(STEP_SIZE >= 0.0 && STEP_SIZE < 1);
            } else if (option.find("-lf=") != std::string::npos) {
                std::string fname(&argv[i][TWOCHAR_ARG]);
                OutputToFile::stream.open(fname.c_str());
            } else if (option.find("-l=") != std::string::npos) {
                LOG_REPORTING_LEVEL = std::atoi(&argv[i][ONECHAR_ARG]);
                Log<OutputToFile>::reporting_level = LOG_REPORTING_LEVEL;
            } else if (option.find("-lt=") != std::string::npos) {
                LOG_START = std::atoi(&argv[i][TWOCHAR_ARG]);
            } else if (option.find("-lp=") != std::string::npos) {
                LOG_STOP = std::atoi(&argv[i][TWOCHAR_ARG]);
            } else if (option.find("-mi=") != std::string::npos) {
                MAX_ITER = std::atoi(&argv[i][TWOCHAR_ARG]);
                assert(MAX_ITER > 0);
            } else if (option.find("-mt=") != std::string::npos) {
                MAX_TIME = std::atof(&argv[i][TWOCHAR_ARG]);
                assert(MAX_TIME > 0);
            } else if (option.find("-x=") != std::string::npos) {
                check_osg();
                scene_path = std::string(&argv[i][ONECHAR_ARG]);
            } else if (option.find("-p=") != std::string::npos) {
                /// read_plugin(&argv[i][ONECHAR_ARG]);
            } else if (option.find("-y=") != std::string::npos) {
                strcpy(THREED_EXT, &argv[i][ONECHAR_ARG]);
            } else if (option.find("-vcp") != std::string::npos) {
                RENDER_CONTACT_POINTS = true;
            }
        }

        // setup the simulation
        READ_MAP = XMLReader::read(std::string(argv[argc-1]));

        // setup the offscreen renderer if necessary
#ifdef USE_OSG
        if (IMAGE_IVAL > 0) {
            // TODO: setup offscreen renderer here
        }
#endif

        // get the (only) simulation object

        for (std::map<std::string, BasePtr>::const_iterator i = READ_MAP.begin(); i != READ_MAP.end(); i++) {
            sim = boost::dynamic_pointer_cast<Simulator>(i->second);
            if (sim)
                break;
        }

        // make sure that a simulator was found
        if (!sim) {
            std::cerr << "driver: no simulator found in " << argv[argc-1] << std::endl;
            //return -1;
            return;
        }

        // setup osg window if desired
#ifdef USE_OSG
        if (ONSCREEN_RENDER) {
            // setup any necessary handlers here
            viewer.setCameraManipulator(new osgGA::TrackballManipulator());
            viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));
            viewer.addEventHandler(new osgViewer::WindowSizeHandler);
            viewer.addEventHandler(new osgViewer::StatsHandler);
        }

        // init the main group
        MAIN_GROUP = new osg::Group;
#endif

        // look for a scene description file
#ifdef USE_OSG
        if (scene_path != "") {
            std::ifstream in(scene_path.c_str());
            if (in.fail()) {
                std::cerr << "driver: unable to find scene description from " << scene_path << std::endl;
                add_lights();
            } else {
                in.close();
                osg::Node* node = osgDB::readNodeFile(scene_path);
                if (!node) {
                    std::cerr << "driver: unable to open scene description file!" << std::endl;
                    add_lights();
                } else
                    MAIN_GROUP->addChild(node);
            }
        } else {
            add_lights();
        }
#endif

        // process XML options
        process_xml_options(std::string(argv[argc-1]));

        // get the simulator visualization
#ifdef USE_OSG
        MAIN_GROUP->addChild(sim->get_persistent_vdata());
        MAIN_GROUP->addChild(sim->get_transient_vdata());
#endif

        // setup the timers
        FIRST_STEP_TIME = get_current_time();
        LAST_STEP_TIME = FIRST_STEP_TIME;

        // begin timing
        start_time = clock();

        // prepare to render
#ifdef USE_OSG
        if (ONSCREEN_RENDER) {
            viewer.setSceneData(MAIN_GROUP);
            viewer.realize();
        }
#endif

        // custom implementation follows

        // Get reference to the pendulum for usage in the command publish and response
        if( READ_MAP.find("pendulum") == READ_MAP.end() ) {
            sprintf( strbuffer, "(dynamics.cpp) init(argc,argv) failed- unable to find pendulum in xml!\n" );
            dyn_error_log.write( strbuffer );
            // TODO : return error condition
        }
        pendulum = dynamic_pointer_cast<Moby::RCArticulatedBody>( READ_MAP.find("pendulum")->second  );
        if( !pendulum ) {
            sprintf( strbuffer, "(dynamics.cpp) init(argc,argv)- unable to cast pendulum to type RCArticulatedBody\n" );
            dyn_error_log.write( strbuffer );
            // TODO : return error condition
        }

        // open the command buffer
        dyn_amsgbuffer = actuator_msg_buffer_c( ACTUATOR_MSG_BUFFER_NAME, ACTUATOR_MSG_BUFFER_MUTEX_NAME, false );
        if( dyn_amsgbuffer.open( ) != BUFFER_ERROR_NONE) {
            sprintf( strbuffer, "(dynamics.cpp) init(argc,argv) failed calling actuator_msg_buffer_c.open(...,false)\n" );
            dyn_error_log.write( strbuffer );
            // TODO : return error condition
        }

        printf( "(dynamics::initialized)\n" );
    }
Exemple #20
0
void LevelMenu::initializeSelector()
{   	
    osg::PositionAttitudeTransform *selectorPat = new osg::PositionAttitudeTransform();
    osg::Geode *selectorGeode = new osg::Geode();
    osg::Geometry *textureDrawable = new osg::Geometry();
    osg::Texture2D *texture;

    osg::Vec3Array *vertices = new osg::Vec3Array();
    {
        vertices->push_back(osg::Vec3(0, 0, 0));
        vertices->push_back(osg::Vec3(682, 0, 0));
        vertices->push_back(osg::Vec3(682, 172, 0));
        vertices->push_back(osg::Vec3(0, 172, 0));
    }

    textureDrawable->setVertexArray( vertices );

    osg::DrawElementsUInt *face = new osg::DrawElementsUInt(osg::PrimitiveSet::QUADS, 0);
    face->push_back(0);
    face->push_back(1);
    face->push_back(2);
    face->push_back(3);
    
    textureDrawable->addPrimitiveSet(face);
        
    osg::Vec2Array* texcoords = new osg::Vec2Array(4);
    {
        (*texcoords)[0].set(0.0f, 0.0f);
        (*texcoords)[1].set(1.0f, 0.0f); 
        (*texcoords)[2].set(1.0f, 1.0f);
        (*texcoords)[3].set(0.0f, 1.0f);

        textureDrawable->setTexCoordArray(0, texcoords);
    }
             
    texture = new osg::Texture2D;
    texture->setDataVariance(osg::Object::DYNAMIC); 
    texture->setWrap(osg::Texture::WRAP_S, osg::Texture::REPEAT); 
    texture->setWrap(osg::Texture::WRAP_T, osg::Texture::REPEAT);

    osg::StateSet* stateSet = new osg::StateSet();
    stateSet->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);
    
    textureDrawable->setStateSet(stateSet);
    selectorGeode->addDrawable(textureDrawable);
    selectorPat->addChild(selectorGeode);
    _menuPat->addChild(selectorPat);
    
    selectorPat->setPosition(osg::Vec3(viewer.getCamera()->getViewport()->width() - 900, viewer.getCamera()->getViewport()->height() - 325, -0.01)); 
	
    osg::Image *image = osgDB::readImageFile(LEVEL_SELECTOR_TEXTURE);
    texture->setImage(image);
    
    //////////////////
    
    osg::PositionAttitudeTransform *detailsPat = new osg::PositionAttitudeTransform();

    // completions
    {
        osg::Geode *completionsNode = new osg::Geode();

	    _completionsText = new osgText::Text();
	    _completionsText->setFont(MENU_FONT);
	    _completionsText->setCharacterSize(MENU_DETAIL_FONT_SIZE);
	    _completionsText->setPosition(osg::Vec3(0, - MENU_ITEM_HEIGHT, 0));

        completionsNode->addDrawable(_completionsText);
        detailsPat->addChild(completionsNode);
    }
    
    // deaths
    {
        osg::Geode *deathsNode = new osg::Geode();

	    _deathsText = new osgText::Text();
	    _deathsText->setFont(MENU_FONT);
	    _deathsText->setCharacterSize(MENU_DETAIL_FONT_SIZE);
	    _deathsText->setPosition(osg::Vec3(0, - MENU_ITEM_HEIGHT * 2, 0));

        deathsNode->addDrawable(_deathsText);
        detailsPat->addChild(deathsNode);
    }
    
    // best time
    {
        osg::Geode *bestTimeNode = new osg::Geode();

	    _bestTimeText = new osgText::Text();
	    _bestTimeText->setFont(MENU_FONT);
	    _bestTimeText->setCharacterSize(MENU_DETAIL_FONT_SIZE);    	
	    _bestTimeText->setPosition(osg::Vec3(0, - MENU_ITEM_HEIGHT * 3, 0));

        bestTimeNode->addDrawable(_bestTimeText);
        detailsPat->addChild(bestTimeNode);
    }
    

    detailsPat->setPosition(osg::Vec3(viewer.getCamera()->getViewport()->width() - 860, viewer.getCamera()->getViewport()->height() - 170, 0));
    _menuPat->addChild(detailsPat);
}
Exemple #21
0
int Metrics::run(osgViewer::Viewer& viewer)
{
    if (Metrics::enabled())
    {
        if (!viewer.isRealized())
        {
            viewer.realize();
        }

        // If Metrics are enabled, enable stats on the Viewer so that it we can report them for the Metrics
        if (Metrics::enabled())
        {
            osgViewer::ViewerBase::Scenes scenes;
            viewer.getScenes(scenes);
            for (osgViewer::ViewerBase::Scenes::iterator itr = scenes.begin();
                itr != scenes.end();
                ++itr)
            {
                osgViewer::Scene* scene = *itr;
                osgDB::DatabasePager* dp = scene->getDatabasePager();
                if (dp && dp->isRunning())
                {
                    dp->resetStats();
                }
            }

            viewer.getViewerStats()->collectStats("frame_rate", true);
            viewer.getViewerStats()->collectStats("event", true);
            viewer.getViewerStats()->collectStats("update", true);

            viewer.getCamera()->getStats()->collectStats("rendering", true);
            viewer.getCamera()->getStats()->collectStats("gpu", true);
        }

        // Report memory and fps every 10 frames.
        unsigned int reportEvery = 10;

        while (!viewer.done())
        {
            {
                METRIC_SCOPED_EX("frame", 1, "number", toString<int>(viewer.getFrameStamp()->getFrameNumber()).c_str());
                {
                    METRIC_SCOPED("advance");
                    viewer.advance();
                }

                {
                    METRIC_SCOPED("event");
                    viewer.eventTraversal();
                }

                {
                    METRIC_SCOPED("update");
                    viewer.updateTraversal();
                }

                {
                    METRIC_SCOPED("render");
                    viewer.renderingTraversals();
                }

            }

            // Report memory and fps periodically. periodically.
            if (viewer.getFrameStamp()->getFrameNumber() % reportEvery == 0)
            {
                // Only report the metrics if they are enabled to avoid computing the memory.
                if (Metrics::enabled())
                {
                    Metrics::counter("Memory::WorkingSet", "WorkingSet", Memory::getProcessPhysicalUsage() / 1048576);
                    Metrics::counter("Memory::PrivateBytes", "PrivateBytes", Memory::getProcessPrivateUsage() / 1048576);
                    Metrics::counter("Memory::PeakPrivateBytes", "PeakPrivateBytes", Memory::getProcessPeakPrivateUsage() / 1048576);
                }
            }

            double eventTime = 0.0;
            if (viewer.getViewerStats()->getAttribute(viewer.getViewerStats()->getLatestFrameNumber(), "Event traversal time taken", eventTime))
            {
                Metrics::counter("Viewer::Event", "Event", eventTime * 1000.0);
            }

            double updateTime = 0.0;
            if (viewer.getViewerStats()->getAttribute(viewer.getViewerStats()->getLatestFrameNumber(), "Update traversal time taken", updateTime))
            {
                Metrics::counter("Viewer::Update", "Update", updateTime * 1000.0);
            }

            double cullTime = 0.0;
            if (viewer.getCamera()->getStats()->getAttribute(viewer.getCamera()->getStats()->getLatestFrameNumber(), "Cull traversal time taken", cullTime))
            {
                Metrics::counter("Viewer::Cull", "Cull", cullTime * 1000.0);
            }

            double drawTime = 0.0;
            if (viewer.getCamera()->getStats()->getAttribute(viewer.getCamera()->getStats()->getLatestFrameNumber(), "Draw traversal time taken", drawTime))
            {
                Metrics::counter("Viewer::Draw", "Draw", drawTime * 1000.0);
            }

            double gpuTime = 0.0;
            if (viewer.getCamera()->getStats()->getAttribute(viewer.getCamera()->getStats()->getLatestFrameNumber()-1, "GPU draw time taken", gpuTime))
            {
                Metrics::counter("Viewer::GPU", "GPU", gpuTime * 1000.0);
            }

            double frameRate = 0.0;
            if (viewer.getViewerStats()->getAttribute(viewer.getViewerStats()->getLatestFrameNumber() - 1, "Frame rate", frameRate))
            {
                Metrics::counter("Viewer::FPS", "FPS", frameRate);
            }

        }

        return 0;
    }

    else
    {
        return viewer.run();
    }
}
Exemple #22
0
// dynamics plugin entry point, signature per tas plugin requirement as defined in coordinator
void init( int argc, char** argv ) {

    const unsigned ONECHAR_ARG = 3, TWOCHAR_ARG = 4;

    #ifdef USE_OSG
    viewer.setThreadingModel(osgViewer::Viewer::SingleThreaded);
    viewer_pointer = &viewer;
    #endif

    // setup some default options
    std::string scene_path;
    THREED_IVAL = 0;
    IMAGE_IVAL = 0;

    // check that syntax is ok
    if (argc < 2)
    {
      std::cerr << "syntax: driver [OPTIONS] <xml file>" << std::endl;
      std::cerr << "        (see README for OPTIONS)" << std::endl;
      //return -1;
      return;
    }

    // get all options
    for (int i=1; i< argc-1; i++)
    {
      // get the option
      std::string option(argv[i]);

      // process options
      if (option == "-r")
      {
        ONSCREEN_RENDER = true;
        UPDATE_GRAPHICS = true;
        check_osg();
      }
      else if (option.find("-of") != std::string::npos)
        OUTPUT_FRAME_RATE = true;
      else if (option.find("-ot") != std::string::npos)
        OUTPUT_TIMINGS = true;
      else if (option.find("-oi") != std::string::npos)
        OUTPUT_ITER_NUM = true;
      else if (option.find("-or") != std::string::npos)
        OUTPUT_SIM_RATE = true;
      else if (option.find("-v=") != std::string::npos)
      {
        UPDATE_GRAPHICS = true;
        check_osg();
        THREED_IVAL = std::atoi(&argv[i][ONECHAR_ARG]);
        assert(THREED_IVAL >= 0);
      }
      else if (option.find("-i=") != std::string::npos)
      {
        check_osg();
        UPDATE_GRAPHICS = true;
        IMAGE_IVAL = std::atoi(&argv[i][ONECHAR_ARG]);
        assert(IMAGE_IVAL >= 0);
      }
      else if (option.find("-t") != std::string::npos)
        OUTPUT_TO_TIME = true;
      else if (option.find("-s=") != std::string::npos)
      {
        STEP_SIZE = std::atof(&argv[i][ONECHAR_ARG]);
        assert(STEP_SIZE >= 0.0 && STEP_SIZE < 1);
      }
      else if (option.find("-lf=") != std::string::npos)
      {
        std::string fname(&argv[i][TWOCHAR_ARG]);
        OutputToFile::stream.open(fname.c_str());
      }
      else if (option.find("-l=") != std::string::npos)
      {
        LOG_REPORTING_LEVEL = std::atoi(&argv[i][ONECHAR_ARG]);
        Log<OutputToFile>::reporting_level = LOG_REPORTING_LEVEL;
      }
      else if (option.find("-lt=") != std::string::npos)
      {
        LOG_START = std::atoi(&argv[i][TWOCHAR_ARG]);
      }
      else if (option.find("-lp=") != std::string::npos)
      {
        LOG_STOP = std::atoi(&argv[i][TWOCHAR_ARG]);
      }
      else if (option.find("-mi=") != std::string::npos)
      {
        MAX_ITER = std::atoi(&argv[i][TWOCHAR_ARG]);
        assert(MAX_ITER > 0);
      }
      else if (option.find("-mt=") != std::string::npos)
      {
        MAX_TIME = std::atof(&argv[i][TWOCHAR_ARG]);
        assert(MAX_TIME > 0);
      }
      else if (option.find("-x=") != std::string::npos)
      {
        check_osg();
        scene_path = std::string(&argv[i][ONECHAR_ARG]);
      }
      else if (option.find("-p=") != std::string::npos) {
        /// read_plugin(&argv[i][ONECHAR_ARG]);
      } else if (option.find("-y=") != std::string::npos)
      {
        strcpy(THREED_EXT, &argv[i][ONECHAR_ARG]);
      } else if (option.find("-vcp") != std::string::npos)
        RENDER_CONTACT_POINTS = true;

    }

    // setup the simulation
    READ_MAP = XMLReader::read(std::string(argv[argc-1]));

    // setup the offscreen renderer if necessary
    #ifdef USE_OSG
    if (IMAGE_IVAL > 0)
    {
      // TODO: setup offscreen renderer here
    }
    #endif

    // get the (only) simulation object

    for (std::map<std::string, BasePtr>::const_iterator i = READ_MAP.begin(); i != READ_MAP.end(); i++)
    {
      sim = boost::dynamic_pointer_cast<Simulator>(i->second);
      if (sim)
        break;
    }

    // make sure that a simulator was found
    if (!sim)
    {
      std::cerr << "driver: no simulator found in " << argv[argc-1] << std::endl;
      //return -1;
      return;
    }

    // setup osg window if desired
    #ifdef USE_OSG
    if (ONSCREEN_RENDER)
    {
      // setup any necessary handlers here
      viewer.setCameraManipulator(new osgGA::TrackballManipulator());
      viewer.addEventHandler(new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()));
      viewer.addEventHandler(new osgViewer::WindowSizeHandler);
      viewer.addEventHandler(new osgViewer::StatsHandler);
    }

    // init the main group
    MAIN_GROUP = new osg::Group;
    #endif

    /**
      // Note: In this architecture, Moby doesn't have any direct relationship to
      // controllers, so the ability to load control plugins is removed

    // call the initializers, if any
    if (!INIT.empty())
    {
      #ifdef USE_OSG
      BOOST_FOREACH(init_t i, INIT)
        (*i)(MAIN_GROUP, READ_MAP, STEP_SIZE);
      #else
      BOOST_FOREACH(init_t i, INIT)
        (*i)(NULL, READ_MAP, STEP_SIZE);
      #endif
    }
    */

    // look for a scene description file
    #ifdef USE_OSG
    if (scene_path != "")
    {
      std::ifstream in(scene_path.c_str());
      if (in.fail())
      {
        std::cerr << "driver: unable to find scene description from " << scene_path << std::endl;
        add_lights();
      }
      else
      {
        in.close();
        osg::Node* node = osgDB::readNodeFile(scene_path);
        if (!node)
        {
          std::cerr << "driver: unable to open scene description file!" << std::endl;
          add_lights();
        }
        else
          MAIN_GROUP->addChild(node);
      }
    }
    else
      add_lights();
    #endif

    // process XML options
    process_xml_options(std::string(argv[argc-1]));

    // get the simulator visualization
    #ifdef USE_OSG
    MAIN_GROUP->addChild(sim->get_persistent_vdata());
    MAIN_GROUP->addChild(sim->get_transient_vdata());
    #endif

    // setup the timers
    FIRST_STEP_TIME = get_current_time();
    LAST_STEP_TIME = FIRST_STEP_TIME;

    // begin timing
    start_time = clock();

    // prepare to render
    #ifdef USE_OSG
    if (ONSCREEN_RENDER)
    {
      viewer.setSceneData(MAIN_GROUP);
      viewer.realize();
    }
    #endif

    // custom implementation follows

    // Get reference to the pendulum for usage in the command publish and response
    if( READ_MAP.find("pendulum") == READ_MAP.end() )
      printf( "dynamics.cpp:init()- unable to find pendulum!\n" );
    pendulum = dynamic_pointer_cast<Moby::RCArticulatedBody>( READ_MAP.find("pendulum")->second  );
    if( !pendulum )
        printf( "dynamics.cpp:init()- unable to cast pendulum to type RCArticulatedBody\n" );

    // open the command buffer
    cmdbuffer = CommandBuffer( getpid( ) );
    cmdbuffer.open();   // TODO : sanity/safety checking

    //printf( "(dynamics::initialized)\n" );
}