예제 #1
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 );
}
예제 #2
0
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 );
}
예제 #3
0
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();
}
예제 #4
0
Level::Level(const std::string &mapfile) :
    _numDeaths(0),
    _reachedFinish(false)
{
    _shadowedScene = new osgShadow::ShadowedScene;
    _shadowedScene->setReceivesShadowTraversalMask(RECEIVE_SHADOW_MASK);
	_shadowedScene->setCastsShadowTraversalMask(CAST_SHADOW_MASK);
	_shadowedScene->setShadowTechnique(new osgShadow::ShadowMap);
 
    addChild(_shadowedScene);

    _headUpDisplay = new HeadUpDisplay();
    addChild(_headUpDisplay->getCamera());
    addChild((new Sky())->getCamera());
    
    initializePhysicsWorld();
    
    // load map from file
    loadMapFromFile(mapfile);
    
    // add player to level
    _shadowedScene->addChild(Player::getInstance());
    addChild(Player::getInstance()->getParticleEffects());
	
    // add player ghost object to world
    _physicsWorld->addCollisionObject(Player::getInstance()->getGhostObject(),
                               btBroadphaseProxy::CharacterFilter,
                               btBroadphaseProxy::StaticFilter | btBroadphaseProxy::DefaultFilter);
                               
    // register player controller
    _physicsWorld->addAction(Player::getInstance()->getController());
    
    // initialize members
    LazyCameraManipulator *cameraManipulator = new LazyCameraManipulator();
    
    // setup manipulator to track the player
    cameraManipulator->setTrackNode(Player::getInstance());
    cameraManipulator->setHomePosition(LEVEL_CAMERA_HOME_EYE, LEVEL_CAMERA_HOME_CENTER, LEVEL_CAMERA_HOME_UP);

    // player must be updated after physic is updated
    Player::getInstance()->setUpdateCallback(new PlayerUpdater());
    
    // set _cameraManipulator as manipulator for the scene
    viewer.setCameraManipulator(cameraManipulator);
                
    LevelUpdater *stepCallback = new LevelUpdater(this);
    setUpdateCallback(stepCallback);
    
    // player keyboard control
    _keyboardHandler = new LevelKeyboardHandler();
    viewer.addEventHandler(_keyboardHandler);
    
    initializeLighting();
    
    Sound::getInstance()->stop(MENU_MUSIC_FILE);
    Sound::getInstance()->playInLoop(LEVEL_MUSIC_FILE);    
}
예제 #5
0
void build_world(osg::Group* root, osg::Node* scene, osgViewer::Viewer& viewer)
{
    osg::ref_ptr<EffectPanel> effect_panel = build_gui(root);
    effect_panel->setScene(scene);
    effect_panel->rebuild();

    viewer.addEventHandler(new EffectPanel::KeyboardHandler(effect_panel.get()));

    root->addChild(effect_panel->getRoot());
}
예제 #6
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() );

    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 );
}
예제 #7
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);    
}
예제 #8
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" );
    }
예제 #9
0
파일: program.cpp 프로젝트: nsmoooose/csp
int main( int argc, char **argv )
{
	int windowWidth, windowHeight;
	std::string osgEarthFileName = "D:/Dev/csp/csp/examples/cspEarth/data/srtm.earth";

	// use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

	// Allow a debugger to be attached before the interesting parts start
	if (arguments.read("-p"))
	{
		std::cout << "Attach debugger and press a key..." << std::endl;
		std::getchar();
	}

	// if an .earth file definition was specified, use this one instead of the default
	arguments.read("-file", osgEarthFileName);

	// get screen size
	arguments.read("-window", windowWidth, windowHeight);

	// =====================================================================
	// SETUP
	// Make it possible for this application to locate images bound
	// to textures.
	std::string search_path = ";";
	csp::ospath::addpath(search_path, "./data/images/");
	csp::ospath::addpath(search_path, "./data/models/");
	csp::ObjectModel::setDataFilePathList(search_path);

	// Set paths for shader files.
	Shader::instance()->setShaderPath("./data/shaders/");


	// =====================================================================
	// Manual creation of a object model.
	Ref<ObjectModel> my_model = new ObjectModel();

	// An external is used to handle the path to the scene graph file.
	// It is also ensuring that paths is handled independent on operating
	// system.
	External modelPath;
	modelPath.setSource("industry/refinery_column01/refinery_column01.osg");
	my_model->setModelPath(modelPath);
	my_model->setSmooth(true);

	// Load the model from disc. This will also apply needed shaders.
	// smoothing and more things.
	my_model->loadModel();

	// read osgEarth config file and create the globe
	std::cout << "reading osgEarth config file: " << osgEarthFileName << std::endl;
	osg::ref_ptr<osg::Node> globe = osgDB::readNodeFile(osgEarthFileName);
	osg::ref_ptr<osg::Node> topNode = new osg::Node;

	osg::Group* group = new osg::Group;
	group->setName("root group");

	// =====================================================================
	// construct the viewer
	viewer.addEventHandler(new osgViewer::StatsHandler);
	viewer.addEventHandler(new osgViewer::HelpHandler);
    viewer.addEventHandler(new osgViewer::WindowSizeHandler);
	viewer.addEventHandler(new osgViewer::ScreenCaptureHandler);

	// modify the key mapping of an osg default event handler
	// this is just to demonstrate the principle, no real use case behind it...
	osgViewer::View::EventHandlers eventHandlers = viewer.getEventHandlers();
	// iterate through the viewer's event handlers and modify their default behavior
	for (osgViewer::View::EventHandlers::iterator it = eventHandlers.begin(); it != eventHandlers.end(); ++it)
	{
		// EventHandlers is a list of osgGA::GUIEventHandlers, so RTTI is used to find out the derived class
		if(osgViewer::WindowSizeHandler *winSizeHandler = 
			dynamic_cast<osgViewer::WindowSizeHandler *>(it->get()))
		{
			winSizeHandler->setKeyEventToggleFullscreen(osgGA::GUIEventAdapter::KEY_F2);
		}
	}


	// Create overlay data
	osg::ref_ptr<osg::Geode> statsGeometry = createStatsGeometry();
	group->addChild( statsGeometry );
	
	// add the osgEarth globe to the scene
	group->addChild( globe.get() );
	group->addChild( my_model->getModel().get() );

	//viewer.setSceneData(my_model->getModel().get());
	viewer.setSceneData( group );
	//viewer.setSceneData(globe.get());

	// create camera and context
	setupCameraAndContext( viewer, windowWidth, windowHeight );

	// the overlay geometry is added to an individual camera
	// QUESTION: But why isn't it rendered by the primary cam?!?
	statsCamera->addChild( statsGeometry );

	//viewer.setCameraManipulator(new osgGA::FlightManipulator);

	osgEarth::MapNode* mapNode = osgEarth::MapNode::findMapNode(globe);
    manip = new osgEarthUtil::EarthManipulator();
	manip->setNode(globe);
    if ( mapNode->getMap()->isGeocentric() )
    {
        manip->setHomeViewpoint( 
            osgEarthUtil::Viewpoint( osg::Vec3d( -90, 0, 0 ), 0.0, -90.0, 5e7 ) );
    }
	manip->getSettings()->bindMouseDoubleClick(
		osgEarthUtil::EarthManipulator::ACTION_GOTO, osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON );

	viewer.setCameraManipulator(manip);
	viewer.addEventHandler(new inputHandler());
	// run the viewers frame loop
    viewer.realize();

    // main loop (note, window toolkits which take control over the main loop will require 
	// a window redraw callback containing the code below.)
    while(!viewer.done())
    {
        viewer.frame();
    }
}
예제 #10
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" );
}
예제 #11
0
int main( int argc, char **argv )
{
	if(argc<4) {
		usage(argc,argv);
		return 1;
	}
	is = helper::createImageSource(argv[1]);
	if(is.empty() || is->done()) {
		loglne("[main] createImageSource failed or no valid imagesource!");
		return -1;
	}
	is->pause(false);
	is->reportInfo();
	is->get(frame);
	imgW = frame.cols; imgH = frame.rows;
	videoFromWebcam = false;
	if( is->classname() == "ImageSource_Camera" ) {
		videoFromWebcam = true;
	}

	loglni("[main] loading K matrix from: "<<argv[2]);
	double K[9];
	std::ifstream kfile(argv[2]);
	for(int i=0; i<9; ++i) kfile >> K[i];
	tracker.loadK(K);
	loglni("[main] K matrix loaded:");
	loglni(helper::PrintMat<>(3,3,K));

	loglni("[main] load template image from: "<<argv[3]);
	tracker.loadTemplate(argv[3]);

	//////////////// TagDetector /////////////////////////////////////////
	int tagid = 0; //default tag16h5
	if(argc>5) tagid = atoi(argv[5]);
	tagFamily = TagFamilyFactory::create(tagid);
	if(tagFamily.empty()) {
		loglne("[main] create TagFamily fail!");
		return -1;
	}
	detector = new TagDetector(tagFamily);
	if(detector.empty()) {
		loglne("[main] create TagDetector fail!");
		return -1;
	}
	Mat temp = imread(argv[3]);
	if( findAprilTag(temp, 0, HI, true) ) {
		namedWindow("template");
		imshow("template", temp);
		iHI = HI.inv();
	} else {
		loglne("[main error] detector did not find any apriltag on template image!");
		return -1;
	}

	//////////////// OSG ////////////////////////////////////////////////
	osg::ref_ptr<osg::Group> root = new osg::Group;

	string scenefilename = (argc>4?argv[4]:("cow.osg"));
	osg::ref_ptr<osg::Node> cow = osgDB::readNodeFile(scenefilename);
	arscene = new helper::ARSceneRoot;
	helper::FixMat<3,double>::Type matK = helper::FixMat<3,double>::ConvertType(K);
	CV2CG::cv2cg(matK,0.01,500,imgW,imgH,*arscene);
	manipMat = new osg::MatrixTransform(osg::Matrix::identity());
	manipMat->addChild(cow);
	manipMat->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
	arscene->addChild(manipMat);

	osg::ref_ptr<osg::Image> backgroundImage = new osg::Image;
	helper::cvmat2osgimage(frame,backgroundImage);
	arvideo = new helper::ARVideoBackground(backgroundImage);
	root->setUpdateCallback(new ARUpdateCallback);

	root->addChild(arvideo);
	root->addChild(arscene);

	viewer.setSceneData(root);
	viewer.addEventHandler(new osgViewer::StatsHandler);
	viewer.addEventHandler(new osgViewer::WindowSizeHandler);
	viewer.addEventHandler(new QuitHandler);

	//start tracking thread
	OpenThreads::Thread::Init();
	TrackThread* thr = new TrackThread;
	thr->start();

	viewer.run();

	delete thr;
	loglni("[main] DONE...exit!");
	return 0;
}