void AppStateTest::Initialize() {
    std::cout << "Beginning Initialization..." << std::endl;

    Sound_Manager * music = Sound_Manager::Get_Instance();
    music->Load_Music("Sound/Music/Battle.ogg");
    music->Play_Music();

    //Just makes sure the instance is initialized before gameplay begins
    std::cout << "Beginning Collision_Manager Initialization..." << std::endl;
    Collision_Manager::Get_Instance();

    //background_texture = surface_manager->background_game;

    std::cout << "Beginning Math Initialization..." << std::endl;
    srand(time(NULL));
    Initialize_Trig_Table();

    std::cout << "Beginning Map Initialization..." << std::endl;
    map = new Map(rand(), 0.5);
    map->Generate_Map();

    std::cout << "Beginning Ship Initialization..." << std::endl;
    Ship::Initialize_Ships(map->max_players_per_team * 2);
    int pawn_index = Ship::Add_Ship(BLUE_TEAM, INTERCEPTOR, 100, 100, 5.0);

    if (pawn_index >= 0)
        player.pawn = Ship::ships[pawn_index];

    Print_Collidables();
    Print_Drawables();
    Print_Rigid_Bodies();

    // Always create HUDs last
    createHUD();
}
Exemplo n.º 2
0
osg::Node* creatQuad(const std::string& name, 
                     osg::Image* image, 
                     osg::Texture::InternalFormatMode formatMode,
                     osg::Texture::FilterMode minFilter)
{

    osg::Group* group = new osg::Group;
    
    {
        osg::Geode* geode = new osg::Geode;

        geode->addDrawable(createTexturedQuadGeometry(
                osg::Vec3(0.0f,0.0f,0.0f),
                osg::Vec3(float(image->s()),0.0f,0.0f),
                osg::Vec3(0.0f,0.0f,float(image->t()))));

        geode->setName(name);

        osg::StateSet* stateset = geode->getOrCreateStateSet();

        osg::Texture2D* texture = new osg::Texture2D(image);
        texture->setInternalFormatMode(formatMode);
        texture->setFilter(osg::Texture::MIN_FILTER, minFilter);
        stateset->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);

        group->addChild(geode);
    }
    
    {
        group->addChild(createHUD(name));
    }
    
    return group;
}
Exemplo n.º 3
0
bool SkeletalAnimationSample::initialize()
{
    splashScreen_.addLogo("CarbonLogo.png");

    createHUD();
    createScene();

    return true;
}
Exemplo n.º 4
0
void HUD_pauseSet(u8 joy, u8 pauseState){
	clearPlayerSide(joy);

	if (! pauseState){
		createHUD(joy);
	}
	else {
		createPauseMenu(joy);
	}
}
Exemplo n.º 5
0
int main(int argc, char **argv)
{
	// use an ArgumentParser object to manage the program arguments.
	osg::ArgumentParser arguments(&argc, argv);


	// if not loaded assume no arguments passed in, try use default model instead.
	osg::ref_ptr<osg::Node> scene = osgDB::readRefNodeFile("dumptruck.osgt");


	if (!scene)
	{
		osg::notify(osg::NOTICE) << "No model loaded" << std::endl;
		return 1;
	}

	{
		// construct the viewer.
		osgViewer::Viewer viewer;

		SnapImage* postDrawCallback = new SnapImage("PostDrawCallback.png");
		viewer.getCamera()->setPostDrawCallback(postDrawCallback);
		viewer.addEventHandler(new SnapeImageHandler('p', postDrawCallback));

		SnapImage* finalDrawCallback = new SnapImage("FinalDrawCallback.png");
		viewer.getCamera()->setFinalDrawCallback(finalDrawCallback);
		viewer.addEventHandler(new SnapeImageHandler('f', finalDrawCallback));

		viewer.addEventHandler(new osgViewer::WindowSizeHandler);

		osg::ref_ptr<osg::Group> group = new osg::Group;

		// add the HUD subgraph.
		if (scene.valid()) group->addChild(scene);
		group->addChild(createHUD(viewer));

		viewer.setUpViewInWindow(20, 20, 400, 400, 0);

		// set the scene to render
		viewer.setSceneData(group);

		osgViewer::GraphicsWindow* gw = dynamic_cast<osgViewer::GraphicsWindow*>(viewer.getCamera()->getGraphicsContext());
		if (gw)
		{
			// Send window size for MyGUI to initialize
			int x, y, w, h; gw->getWindowRectangle(x, y, w, h);
			viewer.getEventQueue()->windowResize(x, y, w, h);
		}

		return viewer.run();
	}

}
Exemplo n.º 6
0
osg::Node* createModel(const std::string& filename)
{
    osg::Group* root = new osg::Group;

    if (filename != "X") {
        osg::BoundingBox bb(0.0f,0.0f,0.0f,1.0f,1.0f,1.0f);
        root->addChild(createRectangle(bb, filename)); // XXX
    }

    root->addChild(createHUD());

    return root;
}
Exemplo n.º 7
0
ViewerQT::ViewerQT(QWidget * parent, const char * name, const QGLWidget * shareWidget, WindowFlags f):
    AdapterWidget( parent, name, shareWidget, f)
{
    setCamera(this->getCamera());
    // Camera
     getCamera()->setViewport(new osg::Viewport(0,0,width(),height()));
     getCamera()->setProjectionMatrixAsPerspective(30.0f, static_cast<double>(width())/static_cast<double>(height()), 1.0f, 10000.0f);
     getCamera()->setGraphicsContext(getGraphicsWindow());
    getCamera()->setClearColor(osg::Vec4d(51/255.0, 51/255.0, 102/255.0, 0));
    getCamera()->setViewMatrix(osg::Matrix::identity());
//   // getCamera()->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
//   // getCamera()->setClearColor(osg::Vec4d(1, 1, 1, 0));
//    getCamera()->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
//    getCamera()->setClearMask(GL_DEPTH_BUFFER_BIT);
//    getCamera()->setRenderOrder(osg::Camera::POST_RENDER);
//    getCamera()->setUpdateCallback(new AxisCameraUpdateCallback());
//    QString axespath = QCoreApplication::applicationDirPath() + "/axes.osg";
//    osg::Node* axes = osgDB::readNodeFile(axespath.toLatin1().data());
//    qDebug()<<axes->asGroup()->getNumChildren();
//    qDebug()<<axespath;
//    getCamera()->addChild(axes);
    // Trackball
    m_rpTrackball = new osgGA::TrackballManipulator;
  //  setCameraManipulator(m_rpTrackball.get());
    addEventHandler(new osgGA::StateSetManipulator(getCamera()->getOrCreateStateSet()));
   // addEventHandler(new osgViewer::WindowSizeHandler);
    addEventHandler(new osgViewer::StatsHandler);
    // Scene root
    m_rpSceneGroupRoot = new osg::Group;
    setSceneData(m_rpSceneGroupRoot.get());
    osg::Camera* camera = createHUD();
    addSlave(camera, false);
    m_rpSceneGroupRoot->addChild(camera);
    osgText::Text* text = new osgText::Text;
    m_rpSceneGroupRoot->addChild( createHUD_viewPoint( text));//加入HUD文字
//    pickHandler = new PickHandler;
//    addEventHandler(pickHandler);

    addEventHandler(new PickDragHandler(text));
    osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator =
            new osgGA::KeySwitchMatrixManipulator;
    keyswitchManipulator->addMatrixManipulator(1,"Trackball",new osgGA::TrackballManipulator());
    keyswitchManipulator->addMatrixManipulator(2,"Flight",new osgGA::FlightManipulator());
    keyswitchManipulator->addMatrixManipulator(3,"Drive",new osgGA::DriveManipulator());
    keyswitchManipulator->addMatrixManipulator(4,"Terrain",new osgGA::TerrainManipulator());
    setCameraManipulator(keyswitchManipulator.get());
    setThreadingModel(osgViewer::Viewer::SingleThreaded);

    connect(&_timer, SIGNAL(timeout()), this, SLOT(updateGL()));
    _timer.start(10);
}
Exemplo n.º 8
0
 App() : mTimer(0), mTimer2(0), mBasePower(150), mNextUpdate(0)
 {
  
  _makeOgre();
  _makeOIS();
  
  // Create Silverback and load in dejavu
  mSilverback = new Gorilla::Silverback();
  mSilverback->loadAtlas("dejavu");
  
  createHUD();
  createControlPanel();
  
 }
Exemplo n.º 9
0
int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // construct the viewer.
    osgViewer::Viewer viewer;

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);

    // if no model has been successfully loaded report failure.
    if (!loadedModel) 
    {
        loadedModel=makeTessellateExample();

    } else { // if there is a loaded model:

        // tessellate by searching for geode called tessellate & tessellate it
        setTessellateVisitor tsv;
        loadedModel->accept(tsv);

    }

    // create the hud.
    osg::Group *gload= dynamic_cast<osg::Group *> (loadedModel.get());
    gload->addChild(createHUD());


    osgUtil::Optimizer optimizer;
    optimizer.optimize(loadedModel.get() );

    // set the scene to render
    viewer.setSceneData(loadedModel.get());

    // add event handler for keyboard 'n' to retessellate
    viewer.addEventHandler(new KeyboardEventHandler(loadedModel.get()));

    return viewer.run();
}
Exemplo n.º 10
0
int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // construct the viewer.
    osgViewer::Viewer viewer;
    // root
    osg::Group* rootNode = new osg::Group;

    // create info display
    const char* text[] = {
        "osg::Sequence Mini-Howto",
        "- can be used for simple flip-book-style animation",
        "- is subclassed from osg::Switch",
        "- assigns a display duration to each child",
        "- can loop or swing through an interval of it's children",
        "- can repeat the interval a number of times or indefinitively",
        "- press 's' to start/pause/resume",
        "- press 'l' to toggle loop/swing mode",
        NULL
    };
    rootNode->addChild(createHUD(createTextGroup(text)));

    // add sequence of models from command line
    osg::Sequence* seq = createSequence(arguments);
    rootNode->addChild(seq);

    // add model to viewer.
    viewer.setSceneData(rootNode);

    // add event handler to control sequence
    viewer.addEventHandler(new SequenceEventHandler(seq));

    return viewer.run();
}
Exemplo n.º 11
0
int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);


    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
    
    // if not loaded assume no arguments passed in, try use default mode instead.
    if (!scene) scene = osgDB::readNodeFile("dumptruck.osg");
    
    
    if (!scene)
    {
        osg::notify(osg::NOTICE)<<"No model loaded"<<std::endl;
        return 1;
    }


    if (arguments.read("--Viewer"))
    {
        // construct the viewer.
        osgViewer::Viewer viewer;

        // create a HUD as slave camera attached to the master view.
        
        viewer.setUpViewAcrossAllScreens();

        osgViewer::Viewer::Windows windows;
        viewer.getWindows(windows);
        
        if (windows.empty()) return 1;
        
        osg::Camera* hudCamera = createHUD();
        
        // set up cameras to rendering on the first window available.
        hudCamera->setGraphicsContext(windows[0]);
        hudCamera->setViewport(0,0,windows[0]->getTraits()->width, windows[0]->getTraits()->height);

        viewer.addSlave(hudCamera, false);

        // set the scene to render
        viewer.setSceneData(scene.get());

        return viewer.run();

    }
    if (arguments.read("--CompositeViewer"))
    {
        // construct the viewer.
        osgViewer::CompositeViewer viewer;

        // create the main 3D view
        osgViewer::View* view = new osgViewer::View;
        viewer.addView(view);

        view->setSceneData(scene.get());
        view->setUpViewAcrossAllScreens();;
        view->setCameraManipulator(new osgGA::TrackballManipulator);

        // now create the HUD camera's view
        
        osgViewer::Viewer::Windows windows;
        viewer.getWindows(windows);
        
        if (windows.empty()) return 1;
        
        osg::Camera* hudCamera = createHUD();
        
        // set up cameras to rendering on the first window available.
        hudCamera->setGraphicsContext(windows[0]);
        hudCamera->setViewport(0,0,windows[0]->getTraits()->width, windows[0]->getTraits()->height);
        
        osgViewer::View* hudView = new osgViewer::View;
        hudView->setCamera(hudCamera);
        
        viewer.addView(hudView);

        return viewer.run();

    }
    else
    {
        // construct the viewer.
        osgViewer::Viewer viewer;
        
        SnapImage* postDrawCallback = new SnapImage("PostDrawCallback.png");
        viewer.getCamera()->setPostDrawCallback(postDrawCallback);        
        viewer.addEventHandler(new SnapeImageHandler('p',postDrawCallback));
        
        SnapImage* finalDrawCallback = new SnapImage("FinalDrawCallback.png");
        viewer.getCamera()->setFinalDrawCallback(finalDrawCallback);        
        viewer.addEventHandler(new SnapeImageHandler('f',finalDrawCallback));

        osg::ref_ptr<osg::Group> group  = new osg::Group;

        // add the HUD subgraph.    
        if (scene.valid()) group->addChild(scene.get());
        group->addChild(createHUD());

        // set the scene to render
        viewer.setSceneData(group.get());

        return viewer.run();
    }
    
}
Exemplo n.º 12
0
DePee::DePee(osg::Group* parent, osg::Group* subgraph, unsigned width, unsigned height)
{
    _renderToFirst = false;

    _isSketchy =false;
    _isColored = false;
    _isEdgy = true;
    _isCrayon = false;

    _normalDepthMapProgram = Utility::createProgram("shaders/depthpeel_normaldepthmap.vert","shaders/depthpeel_normaldepthmap.frag");
    _colorMapProgram = Utility::createProgram("shaders/depthpeel_colormap.vert","shaders/depthpeel_colormap.frag" );
    _edgeMapProgram = Utility::createProgram("shaders/depthpeel_edgemap.vert", "shaders/depthpeel_edgemap.frag");

    _parent = new osg::Group;
    parent->addChild(_parent.get());
    _subgraph = subgraph;

    _width = width;
    _height = height;
    _texWidth = width;
    _texHeight = height;

    assert(parent);
    assert(subgraph);

    _fps = 0;
    _colorCamera = 0;

    _sketchy = new osg::Uniform("sketchy", false);
    _colored = new osg::Uniform("colored", false);
    _edgy = new osg::Uniform("edgy", true);
    _sketchiness = new osg::Uniform("sketchiness", (float) 1.0);

    _normalDepthMap0  = Utility::newColorTexture2D(_texWidth, _texHeight, 32);
    _normalDepthMap1  = Utility::newColorTexture2D(_texWidth, _texHeight, 32);
    _edgeMap = Utility::newColorTexture2D(_texWidth, _texHeight, 8);
    _colorMap = Utility::newColorTexture2D(_texWidth, _texHeight, 8);

    //create a noise map...this doesn't end up in a new rendering pass
    (void) createMap(NOISE_MAP);

    //the viewport aligned quad
    _quadGeode = Utility::getCanvasQuad(_width, _height);


    //!!!Getting problems if assigning unit to texture in depth peeling subgraph and removing depth peeling steps!!!
    //That's why it is done here
    osg::StateSet* stateset = _parent->getOrCreateStateSet();
    stateset->setTextureAttributeAndModes(1, _normalDepthMap0.get(), osg::StateAttribute::ON);
    stateset->setTextureAttributeAndModes(2, _normalDepthMap1.get(), osg::StateAttribute::ON);
    stateset->setTextureAttributeAndModes(3, _edgeMap.get(), osg::StateAttribute::ON);
    stateset->setTextureAttributeAndModes(4, _colorMap.get(), osg::StateAttribute::ON);
    stateset->setTextureAttributeAndModes(5, _noiseMap.get(), osg::StateAttribute::ON);

    // render the final thing
    (void) createFinal();

    //take one step initially
    addDePeePass();

    //render head up display
    (void) createHUD();
}
Exemplo n.º 13
0
int
main(int argc, char* argv[])
{
    std::string project_file = "project.xml";
    std::string map_name;
    std::string temp;
    bool unlit_terrain = false;
    int overlay_tex_unit = 1;
    osg::ref_ptr<osgText::Text> text = new osgText::Text();

    // Begin by parsing the command-line arguments:
    osg::ArgumentParser args( &argc, argv );

    if ( args.read( "--help" ) || args.read( "-h" ) )
    {
        usage( argv[0], "Usage" );
        exit(0);
    }

    if ( args.read( "--project-file", temp ) || args.read( "-f", temp ) )
    {
        project_file = temp;
    }

    if ( args.read( "--map", temp ) )
    {
        map_name = temp;
    }

    if ( args.read( "--overlay-texture-unit", temp) || args.read( "-t", temp) )
    {
        overlay_tex_unit = atoi( temp.c_str() );
    }

    unlit_terrain = args.read( "--unlit-terrain" );

    
    // set up the viewer:
    osgViewer::Viewer viewer( args );
    osgGA::MatrixManipulator* manip = new osgGA::TerrainManipulator();
    viewer.setCameraManipulator( manip );
    viewer.addEventHandler( new osgViewer::ThreadingHandler() );
    viewer.addEventHandler( new osgViewer::WindowSizeHandler() );
    viewer.addEventHandler( new osgViewer::StatsHandler() );
    viewer.addEventHandler( new osgGA::StateSetManipulator( viewer.getCamera()->getOrCreateStateSet()) );


    // Load up the project file:
    osgGIS::Registry* registry = osgGIS::Registry::instance();

    osg::ref_ptr<osgGISProjects::Project> project = osgGISProjects::XmlSerializer::loadProject( project_file );
    if ( !project.valid() )
        return die( "Project file not found; exiting." );
    
    std::string workdir = project->getAbsoluteWorkingDirectory();
    if ( workdir.length() == 0 )
        workdir = PathUtils::combinePaths( project->getBaseURI(), "work_" + project->getName() );
    if ( osgDB::makeDirectory( workdir ) )
        registry->setWorkDirectory( workdir );


    // Look for the specified build target. If not found, fall back on "default"; otherwise fall back on the
    // first one found.
    osg::ref_ptr<osgGISProjects::RuntimeMap> map;
    if ( map_name.length() > 0 )
        map = project->getMap( map_name );
    if ( !map.valid() )
        map = project->getMap( "default" );
    if ( !map.valid() )
        return die( "Unable to load map .. no default map found in the project file .. exiting." );

    osgGIS::notice() << "Loading map " << map->getName() << std::endl;

    // Load up all the content by scanning the project contents:

    osg::ref_ptr<osg::Group> map_node = new osg::Group();

    // Start by loading up the terrain:
    osgGISProjects::Terrain* terrain = map->getTerrain();
    if ( !terrain )
        return die( "Target does not specify a valid terrain; exiting." );

    osg::Node* terrain_node = osgDB::readNodeFile( terrain->getAbsoluteURI() );
    if ( !terrain_node )
        return die( "Unable to load terrain file; exiting." );

    osg::ref_ptr<osgGIS::SpatialReference> terrain_srs = terrain->getExplicitSRS();
    if ( terrain_srs.valid() && terrain_srs->isGeographic() )
        terrain_srs = osgGIS::Registry::SRSFactory()->createGeocentricSRS( terrain_srs.get() );
    else if ( !terrain_srs.valid() )
        terrain_srs = registry->getSRSFactory()->createSRSfromTerrain( terrain_node );

    // activate a polygon offset so that draped vector layers don't z-fight:
    terrain_node->getOrCreateStateSet()->setAttributeAndModes(
        new osg::PolygonOffset( 1.0, 1.0 ),
        osg::StateAttribute::ON );

    terrain_node->getOrCreateStateSet()->setAttributeAndModes(
        new osg::CullFace(),
        osg::StateAttribute::ON );

    // Optionally disable lighting on the terrain:
    if ( unlit_terrain )
    {
        terrain_node->getOrCreateStateSet()->setMode(
            GL_LIGHTING,
            osg::StateAttribute::OFF );
    }

    map_node->addChild( terrain_node->asGroup()->getChild(0) );

    // construct an overlay node for highlighting:
    osgSim::OverlayNode* overlay = new osgSim::OverlayNode( osgSim::OverlayNode::OBJECT_DEPENDENT_WITH_ORTHOGRAPHIC_OVERLAY );
    overlay->setOverlaySubgraph( NULL );
    overlay->setOverlayTextureSizeHint( 1024 );
    overlay->addChild( map_node.get() );
    overlay->setOverlayTextureUnit( overlay_tex_unit );

    // replicate the terrain's CSN above the overlay:
    osg::Group* root = overlay;
    if ( dynamic_cast<osg::CoordinateSystemNode*>( terrain_node ) )
    {
        root = new osg::CoordinateSystemNode( *static_cast<osg::CoordinateSystemNode*>( terrain_node ) );
        root->addChild( overlay );
    }        

    // Now find and load each feature layer. For each feature layer, install an event handler
    // that will perform the spatial lookup when you click on the map.
    for( osgGISProjects::RuntimeMapLayerList::const_iterator i = map->getMapLayers().begin(); i != map->getMapLayers().end(); i++ )
    {
        osgGISProjects::RuntimeMapLayer* map_layer = i->get();
        osgGISProjects::BuildLayer* layer = map_layer->getBuildLayer();
        if ( layer )
        {
            osg::Node* node = NULL;

            if ( map_layer->getVisible() )
            {
                osg::Node* node = osgDB::readNodeFile( layer->getAbsoluteTargetPath() );
                if ( node )
                    map_node->addChild( node );
            }

            if ( map_layer->getSearchable() && map_layer->getSearchLayer()->getSource() )
            {
                // open a feature layer to the source data for this node:
                osgGIS::FeatureLayer* feature_layer = registry->createFeatureLayer( 
                    map_layer->getSearchLayer()->getSource()->getAbsoluteURI() );
                
                if ( !node )
                    node = terrain_node;

                if ( feature_layer )
                {
                    viewer.addEventHandler( new FeatureLayerQueryHandler( 
                        node, feature_layer, terrain_srs.get(), overlay, text.get() ) );
                }
            }
        }
    }

    // Attach the HUD for feature attribute readout:
    root->addChild( createHUD( text.get() ) );

    // configure some decent lighting
    viewer.setLightingMode( osg::View::SKY_LIGHT );
    osg::Light* light = viewer.getLight();
    light->setAmbient( osg::Vec4( .4, .4, .4, 1 ) );
    light->setDiffuse( osg::Vec4( 1, 1, .8, 1 ) );
    light->setPosition( osg::Vec4( 1, 0, 1, 0 ) );
    osg::Vec3 dir( -1, -1, -1 ); dir.normalize();
    light->setDirection( dir );

    viewer.setSceneData( root );

    osgDB::Registry::instance()->getOrCreateSharedStateManager();

    osgDB::DatabasePager* pager = viewer.getScene()->getDatabasePager();

    // We must wait until after the first frame to apply the manipulator node, otherwise it will
    // use the root node instead of our terrain node:
    viewer.realize();
    viewer.frame();
    if ( terrain_node )
        manip->setNode( terrain_node );
    
    // Run until the user quits.
    while( !viewer.done() )
    {
        viewer.frame();
        if ( !pager->isRunning() )
        {
            osgGIS::warn() << "*** PAGER is NOT Running" << std::endl;
        }
    }
    //viewer.run();
	return 0;
}
Exemplo n.º 14
0
int main(int argc,char** argv)
{
	osgViewer::Viewer viewer;

	osg::Camera* camera = createMasterCamera( 50, 50, 640, 480 );
	viewer.setCamera(camera);
	viewer.addEventHandler(new PickNode);

	osg::ref_ptr<osg::Group> root = new osg::Group;
	viewer.setSceneData(root.get());
	osgDragger::ShowBound::Instence()->setNodeMask(~0x1);
	root->addChild(osgDragger::ShowBound::Instence()->getRoot());

	osg::ref_ptr<osg::MatrixTransform> scene = new osg::MatrixTransform;
	root->addChild(scene.get());
	scene->setNodeMask(0x1);

	osg::ref_ptr<osg::Camera> hudCamera = 0;

	osg::ref_ptr<osgDragger::HudCamera> _hudCamera;

	osgViewer::Viewer::Windows windows;
	viewer.getWindows(windows);
	
	if (windows.size() != 0)
	{
		hudCamera = createHUD(windows[0]);
		hudCamera->addChild(CustomDraggerManager::Instence()->getRoot());
		viewer.addSlave(hudCamera.get(), false);
		_hudCamera = new osgDragger::HudCamera(hudCamera.get(), 60, 60);//左下角坐标系
	}
	else
	{
		CustomDraggerManager::Instence()->getRoot()->getOrCreateStateSet()->setAttributeAndModes(new osgDragger::ClearDepth);
		CustomDraggerManager::Instence()->getRoot()->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
		CustomDraggerManager::Instence()->getRoot()->getOrCreateStateSet()->setMode(GL_NORMALIZE, osg::StateAttribute::ON);
		root->addChild(CustomDraggerManager::Instence()->getRoot());
		_hudCamera = new osgDragger::HudCamera(camera, 60, 60);//左下角坐标系
	}
	
	osgDragger::MoveDragger* move = new osgDragger::MoveDragger;
	move->setName("move");
	move->setIntersectionMask(0x2);
	move->setIntersectionCamera(hudCamera.get());
	move->setupDefaultGeometry();
	move->setHandleEvents(true);
	CustomDraggerManager::Instence()->addDragger(move, true);
	CustomDraggerManager::Instence()->setIntersectionMask(0x2);

	osgDragger::RotateDragger* rotate = new osgDragger::RotateDragger;
	rotate->setName("rotate");
	rotate->setIntersectionMask(0x2);
	rotate->setIntersectionCamera(hudCamera.get());
	rotate->setupDefaultGeometry();
	rotate->setHandleEvents(true);
	CustomDraggerManager::Instence()->addDragger(rotate, false);
	CustomDraggerManager::Instence()->setIntersectionMask(0x2);

	osg::ref_ptr<osg::Geode> geode = new osg::Geode;
	geode->addDrawable(new osg::ShapeDrawable(new osg::Box(osg::Vec3(), 5.0f)));

	SelectionList sl;
	{
		osg::ref_ptr<osg::MatrixTransform> mt = new osg::MatrixTransform;
		mt->setName("mt");
		mt->addChild(geode.get());
		sl.push_back(mt.get());
		scene->addChild(mt.get());
	}
	{
		osg::ref_ptr<osg::MatrixTransform> mt = new osg::MatrixTransform;
		mt->setName("mt");
		mt->setMatrix(osg::Matrix::translate(osg::Vec3(20,0,0)));
		mt->addChild(geode.get());
		scene->addChild(mt.get());
	}

	CustomDraggerManager::Instence()->setSelections(sl);

	viewer.setCameraManipulator(new osgGA::TrackballManipulator);

	while (!viewer.done())
	{
		viewer.frame();
	}

	return 0;
}
Exemplo n.º 15
0
int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
     
    // if not loaded assume no arguments passed in, try use default mode instead.
    if (!scene) scene = osgDB::readNodeFile("fountain.osg");

    osg::ref_ptr<osg::Group> group = dynamic_cast<osg::Group*>(scene.get());
    if (!group)
    {
        group = new osg::Group;
        group->addChild(scene.get());
    }

    osg::ref_ptr<osgText::Text> updateText = new osgText::Text;

    // add the HUD subgraph.    
    group->addChild(createHUD(updateText.get()));

    if (arguments.read("--CompositeViewer"))
    {
        osg::ref_ptr<osgViewer::View> view = new osgViewer::View;
        // add the handler for doing the picking
        view->addEventHandler(new PickHandler(updateText.get()));

        // set the scene to render
        view->setSceneData(group.get());

        view->setUpViewAcrossAllScreens();

        osgViewer::CompositeViewer viewer;
        viewer.addView(view.get());

        return viewer.run();

    }
    else
    {
        osgViewer::Viewer viewer;


        // add all the camera manipulators
        {
            osg::ref_ptr<osgGA::KeySwitchMatrixManipulator> keyswitchManipulator = new osgGA::KeySwitchMatrixManipulator;

            keyswitchManipulator->addMatrixManipulator( '1', "Trackball", new osgGA::TrackballManipulator() );
            keyswitchManipulator->addMatrixManipulator( '2', "Flight", new osgGA::FlightManipulator() );
            keyswitchManipulator->addMatrixManipulator( '3', "Drive", new osgGA::DriveManipulator() );

            unsigned int num = keyswitchManipulator->getNumMatrixManipulators();
            keyswitchManipulator->addMatrixManipulator( '4', "Terrain", new osgGA::TerrainManipulator() );

            std::string pathfile;
            char keyForAnimationPath = '5';
            while (arguments.read("-p",pathfile))
            {
                osgGA::AnimationPathManipulator* apm = new osgGA::AnimationPathManipulator(pathfile);
                if (apm || !apm->valid()) 
                {
                    num = keyswitchManipulator->getNumMatrixManipulators();
                    keyswitchManipulator->addMatrixManipulator( keyForAnimationPath, "Path", apm );
                    ++keyForAnimationPath;
                }
            }

            keyswitchManipulator->selectMatrixManipulator(num);

            viewer.setCameraManipulator( keyswitchManipulator.get() );
        }

        // add the handler for doing the picking
        viewer.addEventHandler(new PickHandler(updateText.get()));

        // set the scene to render
        viewer.setSceneData(group.get());

        return viewer.run();
    }

}
Exemplo n.º 16
0
void main()
{
    bool patternfound = false;
    bool reset = false;
    bool resetAuto = false;
    int nbImages = 0;
    double moyFinale = 0;

    cv::TermCriteria termcrit(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03);
    cv::Size winSize(31, 31);
    
    cv::Mat cameraMatrix, distCoeffs;
    cv::Mat imCalib;
    cv::Mat imCalibColor;
    cv::Mat imCalibNext;
    cv::Mat rvecs, tvecs;
    
    std::vector<cv::Point2f> imagePoints;
    std::vector<cv::Point3f> objectPoints;
    std::vector<cv::Point3f> cubeObjectPoints;
    std::vector<std::vector<cv::Point2f>> chessCornersInit(2);
    std::vector<cv::Point3f> chessCorners3D;
    std::vector<double> distances;
    double moyDistances;
    

    // Creation des points a projeter
    for(int x = 0; x < COLCHESSBOARD; x++)
        for(int y = 0; y < ROWCHESSBOARD; y++)
            objectPoints.push_back(cv::Point3f(x * 26.0f, y * 26.0f, 0.0f));

    // Creation des points a projeter
    cubeObjectPoints.push_back(cv::Point3f(52, 26, 0));
    cubeObjectPoints.push_back(cv::Point3f(156, 26, 0));
    cubeObjectPoints.push_back(cv::Point3f(156, 128, 0));
    cubeObjectPoints.push_back(cv::Point3f(52, 128, 0));
    cubeObjectPoints.push_back(cv::Point3f(52, 26, 104));
    cubeObjectPoints.push_back(cv::Point3f(156, 26, 104));
    cubeObjectPoints.push_back(cv::Point3f(156, 128, 104));
    cubeObjectPoints.push_back(cv::Point3f(52, 128, 104));

    // Creation des coins de la mire
    for(int x = 0; x < COLCHESSBOARD; x++)
        for(int y = 0; y < ROWCHESSBOARD; y++)
            chessCorners3D.push_back(cv::Point3f(x * 26.0f, y * 26.0f, 0.0f));  

    cv::FileStorage fs("../rsc/intrinsicMatrix.yml", cv::FileStorage::READ);

    fs["cameraMatrix"] >> cameraMatrix;
    fs["distCoeffs"] >> distCoeffs;

    fs.release();

    cv::VideoCapture vcap(0); 
    if(!vcap.isOpened()){
        std::cout << "FAIL!" << std::endl;
        return;
    }

    cv::Mat *frame = new cv::Mat(cv::Mat::zeros(vcap.get(CV_CAP_PROP_FRAME_HEIGHT), vcap.get(CV_CAP_PROP_FRAME_WIDTH), CV_8UC3));
    
    do
    {
        vcap >> *frame;
    }while(frame->empty());

    osg::ref_ptr<osg::Image> backgroundImage = new osg::Image;
    backgroundImage->setImage(frame->cols, frame->rows, 3,
        GL_RGB, GL_BGR, GL_UNSIGNED_BYTE,
        (uchar*)(frame->data),
        osg::Image::AllocationMode::NO_DELETE, 1);

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Group> group = new osg::Group;
    osg::ref_ptr<osg::Node> objet3D = osgDB::readNodeFile("dumptruck.osgt");
    osg::ref_ptr<osg::Camera> cam = createHUD(backgroundImage);
    osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform;
    osg::ref_ptr<osg::PositionAttitudeTransform> pat2 = new osg::PositionAttitudeTransform;

    // construct the viewer.
    osgViewer::Viewer viewer;

    // add the HUD subgraph.
    group->addChild(cam);
    pat->addChild(pat2);
    pat2->addChild(objet3D);
    group->addChild(pat);

    // set the scene to render
    viewer.setSceneData(group.get());
    viewer.realize();  // set up windows and associated threads.

    char key = 0;
    bool detectionMire = false;

    cv::Mat Rc, C = cv::Mat(3, 1, CV_64F), rotVecInv;
    pat->setScale(osg::Vec3d(0.08, 0.08, 0.08));
    pat->setAttitude(osg::Quat(osg::DegreesToRadians(180.0), osg::Vec3d(1.0, 0.0, 0.0)));
    pat2->setPosition(osg::Vec3d(15.0, 4.0, 5.0));

/*  
    // projection
    double fx = cameraMatrix.at<double>(0, 0);
    double fy = cameraMatrix.at<double>(1, 1);
    double cx = cameraMatrix.at<double>(1, 2);
    double cy = cameraMatrix.at<double>(1, 0);
    double W  = (double)frame->cols;
    double H  = (double)frame->rows;
    double near = .1;
    double far = 100.0;

    osg::Matrixd projectionMatrix;
    projectionMatrix.set(
        2 * fx / W, 0, 0, 0, 
        0, 2 * fy / H, 0, 0, 
        2 * (cx / W) - 1, 2 * (cy - H) - 1, (far + near) / (far - near), 1,
        0, 0, 2 * far * near / (near - far), 0);
        
    projectionMatrix.set(
        2 * fx / W, 0, 0, 0, 
        0, 2 * fy / H, 0, 0,
        2 * (cx / W) - 1, 2 * (cy / H) - 1, (far + near) / (far - near), 1,
        0, 0, 2 * far * near / (near - far), 0);

    viewer.getCamera()->setProjectionMatrix(projectionMatrix);*/


    do
    {       
        patternfound = false;
        resetAuto = false;
        detectionMire = false;
            
        imagePoints.clear();
        chessCornersInit[0].clear();
        chessCornersInit[1].clear();
        moyDistances = 0;
        distances.clear();
        imCalibNext.release();
        
        group->removeChild(pat);
        std::cout << "recherche de mire" << std::endl;

        do
        {
            vcap >> *frame;
            backgroundImage->dirty();
            detectionMire = detecterMire(frame, &chessCornersInit[1], &imCalibNext);
            viewer.frame();
        }while(!detectionMire && !viewer.done());

        if(viewer.done())
            break;

        std::cout << "mire detectee" << std::endl << std::endl;
        group->addChild(pat);

        do
        {           
            vcap >> *frame;
            
            cv::Mat rotVec = trackingMire(frame, &imCalibNext, &chessCornersInit, &chessCorners3D, &cameraMatrix, &distCoeffs, &tvecs);

            imagePoints = dessinerPoints(frame, objectPoints, rotVec, tvecs, cameraMatrix, distCoeffs);
            
            cv::transpose(rotVec, Rc);
            cv::invert(rotVec, rotVecInv);

            for(int i = 0; i < 3; i++)
                C.at<double>(i, 0) = -1 * (
                rotVecInv.at<double>(i, 0) * tvecs.at<double>(0, 0) +
                rotVecInv.at<double>(i, 1) * tvecs.at<double>(1, 0) +
                rotVecInv.at<double>(i, 2) * tvecs.at<double>(2, 0));
            
            osg::Matrixd viewMatrixR, viewMatrixT, viewMatrix90;

            viewMatrixT.makeTranslate(
                -C.at<double>(0, 0) / 100,
                C.at<double>(1, 0) / 100,
                C.at<double>(2, 0) / 100);
            
            double r11 = rotVec.at<double>(0, 0);
            double r21 = rotVec.at<double>(1, 0);
            double r31 = rotVec.at<double>(2, 0);
            double r32 = rotVec.at<double>(2, 1);
            double r33 = rotVec.at<double>(2, 2);

            viewMatrixR.makeRotate(
                atan2(r32, r33), osg::Vec3d(1.0, 0.0, 0.0),
                -atan2(-r31, sqrt((r32 * r32) + (r33 * r33))), osg::Vec3d(0.0, 1.0, 0.0),
                -atan2(r21, r11), osg::Vec3d(0.0, 0.0, 1.0));
            

            viewMatrix90.makeRotate(osg::DegreesToRadians(-90.0), osg::Vec3d(1.0, 0.0, 0.0));
            
            viewer.getCamera()->setViewMatrix(viewMatrixT * viewMatrixR);
            
            // Calcul d'erreur de reprojection
            double moy = 0;
            for(int j = 0; j < COLCHESSBOARD * ROWCHESSBOARD; j++)
            {
                double d = sqrt(pow(chessCornersInit[0][j].y - imagePoints[j].y, 2) + pow(chessCornersInit[0][j].x - imagePoints[j].x, 2));
                distances.push_back(d);
                moy += d;
            }

            moyDistances = moy / (COLCHESSBOARD * ROWCHESSBOARD);

            if(moyDistances > 2) // si l'ecart de reproj est trop grand, reset
                resetAuto = true;

            key = cv::waitKey(33);

            backgroundImage->dirty();
            viewer.frame();
        }while(!viewer.done() && !resetAuto && key != 32);

    }while(!viewer.done());
}
Exemplo n.º 17
0
static void createHUDAll(){
	u8 i;
	for (i=0; i<2; i++){
		createHUD(i);
	}
}
Exemplo n.º 18
0
void main()
{
    bool patternfound = false;
    bool reset = false;
    bool resetAuto = false;
    int nbImages = 0;
    double moyFinale = 0;
    char key = 0;
    bool detectionMire = false;
	bool detectionVisage = false;
	int cpt = 0, moyCpt = 0, i = 0;

	std::cout << "initialisation de Chehra..." << std::endl;
	Chehra chehra;
	std::cout << "done" << std::endl;

    cv::TermCriteria termcrit(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03);
    cv::Size winSize(31, 31);
    
    cv::Mat cameraMatrix, distCoeffs;
    cv::Mat imCalib;
    cv::Mat imCalibColor;
    cv::Mat imCalibNext;
    cv::Mat rvecs, tvecs;
    cv::Mat Rc, C = cv::Mat(3, 1, CV_64F), rotVecInv;
    
    std::vector<cv::Point2f> imagePoints;
    std::vector<cv::Point3f> objectPoints;
    std::vector<cv::Point3f> cubeObjectPoints;
	std::vector<cv::Point3f> dessinPointsVisage;
    std::vector<std::vector<cv::Point2f>> chessCornersInit(2);
	std::vector<std::vector<cv::Point2f>> pointsVisageInit(2);
    std::vector<cv::Point3f> chessCorners3D;
	std::vector<cv::Point3f> pointsVisage3D;
	std::vector<cv::Point3f> visage;
    std::vector<double> distances;
    double moyDistances;

    // Creation des coins de la mire
    for(int x = 0; x < COLCHESSBOARD; x++)
        for(int y = 0; y < ROWCHESSBOARD; y++)
            chessCorners3D.push_back(cv::Point3f(x * SIZEMIRE, y * SIZEMIRE, 0.0f));  

    // Creation des points a projeter
    for(int x = 0; x < COLCHESSBOARD; x++)
        for(int y = 0; y < ROWCHESSBOARD; y++)
            objectPoints.push_back(cv::Point3f(x * SIZEMIRE, y * SIZEMIRE, 0.0f));
	
	cv::FileStorage fs("../rsc/intrinsicMatrix.yml", cv::FileStorage::READ);

	fs["cameraMatrix"] >> cameraMatrix;
	fs["distCoeffs"] >> distCoeffs;

	double f = (cameraMatrix.at<double>(0, 0) + cameraMatrix.at<double>(1, 1)) / 2; // NEAR = distance focale ; si pixels carrés, fx = fy -> np 
	//mais est généralement différent de fy donc on prend (pour l'instant) par défaut la valeur médiane
	double g = 2000 * f; // je sais pas pourquoi. au pif.

	fs.release();

	cv::VideoCapture vcap(0); 
	if(!vcap.isOpened()){
		std::cout << "FAIL!" << std::endl;
		return;
	}

	cv::Mat *frame = new cv::Mat(cv::Mat::zeros(vcap.get(CV_CAP_PROP_FRAME_HEIGHT), vcap.get(CV_CAP_PROP_FRAME_WIDTH), CV_8UC3));

	do
	{
		vcap >> *frame;
	}while(frame->empty());

	osg::ref_ptr<osg::Image> backgroundImage = new osg::Image;
	backgroundImage->setImage(frame->cols, frame->rows, 3,
		GL_RGB, GL_BGR, GL_UNSIGNED_BYTE,
		(uchar*)(frame->data),
		osg::Image::AllocationMode::NO_DELETE, 1);

	// read the scene from the list of file specified commandline args.
	osg::ref_ptr<osg::Group> group = new osg::Group;
	osg::ref_ptr<osg::Geode> cam = createHUD(backgroundImage, vcap.get(CV_CAP_PROP_FRAME_WIDTH), vcap.get(CV_CAP_PROP_FRAME_HEIGHT), cameraMatrix.at<double>(0, 2), cameraMatrix.at<double>(1, 2), f);

	std::cout << "initialisation de l'objet 3D..." << std::endl;
	osg::ref_ptr<osg::Node> objet3D = osgDB::readNodeFile("../rsc/objets3D/Creature.obj");
	std::cout << "done" << std::endl;
   
	osg::StateSet* obectStateset = objet3D->getOrCreateStateSet();
       obectStateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
	osg::ref_ptr<osg::MatrixTransform> mat = new osg::MatrixTransform();
	osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform();

	// construct the viewer.
	osgViewer::CompositeViewer compositeViewer;
	osgViewer::View* viewer = new osgViewer::View;
	osgViewer::View* viewer2 = new osgViewer::View;

	// add the HUD subgraph.
	group->addChild(cam);

	mat->addChild(objet3D);
	pat->addChild(mat);
	group->addChild(pat);

    pat->setScale(osg::Vec3d(3, 3, 3));

	osg::Matrixd projectionMatrix;

	projectionMatrix.makeFrustum(
		-cameraMatrix.at<double>(0, 2),		vcap.get(CV_CAP_PROP_FRAME_WIDTH) - cameraMatrix.at<double>(0, 2),
		-cameraMatrix.at<double>(1, 2),		vcap.get(CV_CAP_PROP_FRAME_HEIGHT) - cameraMatrix.at<double>(1, 2),
		f,								g);

	osg::Vec3d eye(0.0f, 0.0f, 0.0f), target(0.0f, g, 0.0f), normal(0.0f, 0.0f, 1.0f);

	// set the scene to render
	viewer->setSceneData(group.get());
	viewer->setUpViewInWindow(0, 0, 1920 / 2, 1080 / 2); 
	viewer->getCamera()->setProjectionMatrix(projectionMatrix);
	viewer->getCamera()->setViewMatrixAsLookAt(eye, target, normal);

	viewer2->setSceneData(group.get());
	viewer2->setUpViewInWindow(1920 / 2, 0, 1920 / 2, 1080 / 2); 
	viewer2->getCamera()->setProjectionMatrix(projectionMatrix);
	osg::Vec3d eye2(4 * f, 3 * f / 2, 0.0f), target2(0.0f, f, 0.0f), normal2(0.0f, 0.0f, 1.0f);
	viewer2->getCamera()->setViewMatrixAsLookAt(eye2, target2, normal2);

	compositeViewer.addView(viewer);
	compositeViewer.addView(viewer2);

	compositeViewer.realize();  // set up windows and associated threads.



    do
    {       
		group->removeChild(pat);
        patternfound = false;
        resetAuto = false;
        detectionMire = false;
		detectionVisage = false;
            
        imagePoints.clear();
        chessCornersInit[0].clear();
        chessCornersInit[1].clear();
		pointsVisageInit[0].clear();
		pointsVisageInit[1].clear();
		pointsVisage3D.clear();
		dessinPointsVisage.clear();
		visage.clear();
        moyDistances = 0;
        distances.clear();
        imCalibNext.release();
        
        std::cout << "recherche de pattern" << std::endl;

		time_t start = clock();
		double timer = 0;
		
        do
        {
			start = clock();

            vcap >> *frame;

			backgroundImage->dirty();
            //detectionMire = detecterMire(frame, &chessCornersInit[1], &imCalibNext);
			detectionVisage = detecterVisage(frame, &chehra, &pointsVisageInit[1], &visage, &pointsVisage3D, &imCalibNext);

			cpt++;
			double duree = (clock() - start)/(double) CLOCKS_PER_SEC;
			timer += duree;

			if(timer >= 1){
				std::cout << cpt << " fps" << std::endl;
				moyCpt += cpt;
				timer = 0;
				duree = 0;
				i++;
				cpt = 0;
				start = clock();
			}

            compositeViewer.frame();
        }while(!detectionMire && !detectionVisage && !compositeViewer.done());

        if(compositeViewer.done())
            break;

        std::cout << "pattern detectee" << std::endl << std::endl;

		group->addChild(pat);
		
        do
        {           
			start = clock();

            vcap >> *frame;
            
			cv::Mat rotVec = trackingMire(frame, &imCalibNext, &pointsVisageInit, &pointsVisage3D, &cameraMatrix, &distCoeffs, &tvecs);
            //cv::Mat rotVec = trackingMire(frame, &imCalibNext, &chessCornersInit, &chessCorners3D, &cameraMatrix, &distCoeffs, &tvecs);

            //imagePoints = dessinerPoints(frame, objectPoints, rotVec, tvecs, cameraMatrix, distCoeffs);
			imagePoints = dessinerPoints(frame, pointsVisage3D, rotVec, tvecs, cameraMatrix, distCoeffs);
            
            double r11 = rotVec.at<double>(0, 0);
            double r21 = rotVec.at<double>(1, 0);
            double r31 = rotVec.at<double>(2, 0);
            double r32 = rotVec.at<double>(2, 1);
            double r33 = rotVec.at<double>(2, 2);

			osg::Matrixd matrixR;
            matrixR.makeRotate(
                atan2(r32, r33), osg::Vec3d(1.0, 0.0, 0.0),
                -atan2(-r31, sqrt((r32 * r32) + (r33 * r33))), osg::Vec3d(0.0, 0.0, 1.0),
                atan2(r21, r11), osg::Vec3d(0.0, 1.0, 0.0));
            
            mat->setMatrix(matrixR);
			pat->setPosition(osg::Vec3d(tvecs.at<double>(0, 0), tvecs.at<double>(2, 0), -tvecs.at<double>(1, 0)));

			//std::cout << "x = " << tvecs.at<double>(0, 0) << " - y = " << tvecs.at<double>(1, 0) << " - z = " << tvecs.at<double>(2, 0) << std::endl;

            // Calcul d'erreur de reprojection
            double moy = 0;
            for(int j = 0; j < pointsVisageInit[1].size() ; j++)
			{
				double d = sqrt(pow(pointsVisageInit[0][j].y - imagePoints[j].y, 2) + pow(pointsVisageInit[0][j].x - imagePoints[j].x, 2));
				distances.push_back(d);
				moy += d;
			}

            moyDistances = moy / pointsVisageInit[1].size();

            if(moyDistances > 1) // si l'ecart de reproj est trop grand, reset
                resetAuto = true;

			double duree = (clock() - start)/(double) CLOCKS_PER_SEC;


				std::cout << (int)(1/duree) << " fps" << std::endl;
				moyCpt += (int)(1/duree);
				duree = 0;
				i++;
			
            backgroundImage->dirty();
            compositeViewer.frame();
        }while(!compositeViewer.done() && !resetAuto);
		
    }while(!compositeViewer.done());

	std::cout << std::endl << "Moyenne des fps : " << moyCpt/i << std::endl;

	std::system("PAUSE");
}
Exemplo n.º 19
0
int main( int argc, char **argv )
{
    osg::ArgumentParser args( &argc, argv );
    args.getApplicationUsage()->setApplicationName(args.getApplicationName());
    args.getApplicationUsage()->setDescription(args.getApplicationName()+" is mew's testbench");
    args.getApplicationUsage()->setCommandLineUsage(args.getApplicationName()+" [options] filename ...");
    args.getApplicationUsage()->addCommandLineOption("-h","display all help.");

    args.getApplicationUsage()->addKeyboardMouseBinding( "x", "Reload and recompile shader source files." );

    osgProducer::Viewer viewer( args );
    viewer.setUpViewer( osgProducer::Viewer::TRACKBALL_MANIPULATOR |
            osgProducer::Viewer::STATE_MANIPULATOR  |
            osgProducer::Viewer::HEAD_LIGHT_SOURCE  |
            //osgProducer::Viewer::SKY_LIGHT_SOURCE   |
            osgProducer::Viewer::VIEWER_MANIPULATOR |
            osgProducer::Viewer::ESCAPE_SETS_DONE );

    viewer.getUsage( *args.getApplicationUsage() );

    if( args.read("-h") )
    {
        args.getApplicationUsage()->write( std::cout,
                osg::ApplicationUsage::COMMAND_LINE_OPTION |
                osg::ApplicationUsage::ENVIRONMENTAL_VARIABLE |
                osg::ApplicationUsage::KEYBOARD_MOUSE_BINDING );
        return 1;
    }

    if( args.errors() )
    {
        args.writeErrorMessages(std::cout);
        return 1;
    }

    osg::Group* scene = createScene( viewer, args );

    args.reportRemainingOptionsAsUnrecognized();
    if( args.errors() )
    {
        args.writeErrorMessages(std::cout);
        return 1;
    }

    viewer.getEventHandlerList().push_front( new svUtil::EventHandler );

#if ENABLE_REAR_VIEW //[
    osg::Group* group = new osg::Group;
    group->addChild( scene );
    group->addChild( createRearView( scene, viewer.getClearColor() ) );
    scene = group;
#endif //]

#if ENABLE_HUD //[
    scene->addChild( createHUD() );
#endif //]

    //osgUtil::Optimizer optimizer;
    //optimizer.optimize( scene );

#if 0 //[
void addVrpnManip( osgProducer::Viewer& viewer );
    addVrpnManip( viewer );
#endif //]

    viewer.setSceneData( scene );
    viewer.realize();
    while( !viewer.done() )
    {
        viewer.sync();
        viewer.update();
        DirectionColor( viewer );
        viewer.frame();
    }
    viewer.sync();
    return 0;
}
Exemplo n.º 20
0
void main()
{
	bool patternfound = false;
    bool reset = false;
    bool resetAuto = false;

    cv::TermCriteria termcrit(CV_TERMCRIT_ITER | CV_TERMCRIT_EPS, 20, 0.03);
    cv::Size winSize(31, 31);
    
    cv::Mat cameraMatrix, distCoeffs;
    cv::Mat imCalib;
    cv::Mat imCalibColor;
    cv::Mat imCalibNext;
    cv::Mat rvecs, tvecs;
    
    std::vector<cv::Point2f> imagePoints;
    std::vector<cv::Point3f> objectPoints;
    std::vector<cv::Point3f> cubeObjectPoints;
    std::vector<std::vector<cv::Point2f>> chessCornersInit(2);
    std::vector<cv::Point3f> chessCorners3D;
    std::vector<double> distances;
    double moyDistances;
    

    // Creation des points a projeter
    for(int x = 0; x < COLCHESSBOARD; x++)
        for(int y = 0; y < ROWCHESSBOARD; y++)
            objectPoints.push_back(cv::Point3f(x * 26.0f, y * 26.0f, 0.0f));

	// Creation des coins de la mire
    for(int x = 0; x < COLCHESSBOARD; x++)
        for(int y = 0; y < ROWCHESSBOARD; y++)
            chessCorners3D.push_back(cv::Point3f(x * 26.0f, y * 26.0f, 0.0f));  

    cv::FileStorage fs("../rsc/intrinsicMatrix.yml", cv::FileStorage::READ);

    fs["cameraMatrix"] >> cameraMatrix;
    fs["distCoeffs"] >> distCoeffs;

    fs.release();

    cv::VideoCapture vcap(0); 
    if(!vcap.isOpened()){
        std::cout << "FAIL!" << std::endl;
        return;
    }

    cv::Mat *frame = new cv::Mat(cv::Mat::zeros(vcap.get(CV_CAP_PROP_FRAME_HEIGHT), vcap.get(CV_CAP_PROP_FRAME_WIDTH), CV_8UC3));

	do
    {
        vcap >> *frame;
    }while(frame->empty());

	osg::ref_ptr<osg::Image> backgroundImage = new osg::Image;
    backgroundImage->setImage(frame->cols, frame->rows, 3,
        GL_RGB, GL_BGR, GL_UNSIGNED_BYTE,
        (uchar*)(frame->data),
        osg::Image::AllocationMode::NO_DELETE, 1);

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Group> group = new osg::Group;
    osg::ref_ptr<osg::Node> objet3D;

    objet3D = osgDB::readNodeFile("dumptruck.osgt");
    osg::ref_ptr<osg::Camera> cam = createHUD(backgroundImage);

	osgViewer::Viewer viewer; 

    group->addChild(cam);
    group->addChild(objet3D);

    // set the scene to render
    viewer.setSceneData(group.get());

	// projection
	viewer.getCamera()->setProjectionMatrixAsPerspective( 40., 1., 1., 100. ); 

	// Create a matrix to specify a distance from the viewpoint. 
	osg::Matrix trans; 
	trans.makeTranslate( 7, 0., -50. ); 
	// Rotation angle (in radians) 
	double angle( 0. ); 

	char key = 0;
    bool detectionMire = false;

	do
	{
		patternfound = false;
        resetAuto = false;
        detectionMire = false;
            
        imagePoints.clear();
        chessCornersInit[0].clear();
        chessCornersInit[1].clear();
        moyDistances = 0;
        distances.clear();
        imCalibNext.release();
        
        group->removeChild(objet3D);
        std::cout << "recherche de mire" << std::endl;

        do
        {
            vcap >> *frame;
            backgroundImage->dirty();
            detectionMire = detecterMire(frame, &chessCornersInit[1], &imCalibNext);
            viewer.frame();
        }while(!detectionMire && !viewer.done());

        if(viewer.done())
            break;

        std::cout << "mire detectee" << std::endl << std::endl;
        group->addChild(objet3D);

		do
		{
			vcap >> *frame;

			cv::Mat rotVec = trackingMire(frame, &imCalibNext, &chessCornersInit, &chessCorners3D, &cameraMatrix, &distCoeffs, &tvecs);

            imagePoints = dessinerPoints(frame, objectPoints, rotVec, tvecs, cameraMatrix, distCoeffs);
				
			// Create the rotation matrix. 
			osg::Matrix rot; 
			rot.makeRotate( angle, osg::Vec3( 1., 0., 0. ) ); 
			angle += 0.01; 
			// Set the view matrix (the concatenation of the rotation and 
			//   translation matrices). 
			viewer.getCamera()->setViewMatrix( rot * trans ); 

			double moy = 0;
			for(int j = 0; j < COLCHESSBOARD * ROWCHESSBOARD; j++)
			{
			     double d = sqrt(pow(chessCornersInit[0][j].y - imagePoints[j].y, 2) + pow(chessCornersInit[0][j].x - imagePoints[j].x, 2));
			     distances.push_back(d);
			     moy += d;
			}

			moyDistances = moy / (COLCHESSBOARD * ROWCHESSBOARD);

			if(moyDistances > 2) // si l'ecart de reproj est trop grand, reset
			     resetAuto = true;

			key = cv::waitKey(33);

			// Draw the next frame. 
			backgroundImage->dirty();
			viewer.frame(); 

		}while(!viewer.done() && !resetAuto && key != 32);
	} while(!viewer.done());
}
Exemplo n.º 21
0
int main( int argc, char **argv )
{

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

    arguments.getApplicationUsage()->addCommandLineOption("--zeroconf","uses zeroconf to advertise the osc-plugin and to discover it");
    arguments.getApplicationUsage()->addCommandLineOption("--sender","create a view which sends its events via osc");
    arguments.getApplicationUsage()->addCommandLineOption("--recevier","create a view which receive its events via osc");



    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);

    if (!scene)
    {
        std::cout << argv[0] << ": requires filename argument." << std::endl;
        return 1;
    }

    bool use_zeroconf(false);
    bool use_sender(false);
    bool use_receiver(false);
    if(arguments.find("--zeroconf") > 0) { use_zeroconf = true; }
    if(arguments.find("--sender") > 0) { use_sender = true; }
    if(arguments.find("--receiver") > 0) { use_receiver = true; }
    // construct the viewer.
    osgViewer::CompositeViewer viewer(arguments);

    // receiver view
    if (use_receiver) {
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->x = 600;
        traits->y = 100;
        traits->width = 400;
        traits->height = 400;
        traits->windowDecoration = true;
        traits->doubleBuffer = true;
        traits->sharedContext = 0;
        traits->windowName = "Receiver / view two";

        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());

        osgViewer::View* view = new osgViewer::View;
        view->setName("View two");
        viewer.addView(view);

        osg::Group* group = new osg::Group();
        group->addChild(scene.get());
        osg::Geode* geode = new osg::Geode();
        group->addChild(geode);

        osgText::Text* text = new osgText::Text();
        geode->addDrawable( text );

        text->setFont("Arial.ttf");
        text->setText("Waiting for data");
        text->setPosition(osg::Vec3(-50,0,30));
        text->setAxisAlignment(osgText::TextBase::SCREEN);
        text->setDataVariance(osg::Object::DYNAMIC);
        text->setCharacterSize(2.0f);
        view->setSceneData(group);
        view->getCamera()->setName("Cam two");
        view->getCamera()->setViewport(new osg::Viewport(0,0, traits->width, traits->height));
        view->getCamera()->setGraphicsContext(gc.get());

        view->addEventHandler( new osgViewer::StatsHandler );
        view->addEventHandler( new UserEventHandler(text) );

        osg::ref_ptr<osgGA::Device> device = osgDB::readFile<osgGA::Device>("0.0.0.0:9000.receiver.osc");
        if (device.valid() && (device->getCapabilities() & osgGA::Device::RECEIVE_EVENTS))
        {
            view->addDevice(device.get());

            // add a zeroconf device, advertising the osc-device
            if(use_zeroconf)
            {
                osgGA::Device* zeroconf_device = osgDB::readFile<osgGA::Device>("_osc._udp:9000.advertise.zeroconf");
                if (zeroconf_device)
                {
                    view->addDevice(zeroconf_device);
                }
            }
        }
        else {
            OSG_WARN << "could not open osc-device, receiving will not work" << std::endl;
        }
    }

    // sender view
    if(use_sender) {
        osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
        traits->x = 100;
        traits->y = 100;
        traits->width = 400;
        traits->height = 400;
        traits->windowDecoration = true;
        traits->doubleBuffer = true;
        traits->sharedContext = 0;
        traits->windowName = "Sender / view one";

        osg::ref_ptr<osg::GraphicsContext> gc = osg::GraphicsContext::createGraphicsContext(traits.get());


        osgViewer::View* view = new osgViewer::View;
        view->setName("View one");
        viewer.addView(view);

        osg::Group* g = new osg::Group();
        g->addChild(scene.get());
        g->addChild(createHUD());
        view->setSceneData(g);
        view->getCamera()->setName("Cam one");
        view->getCamera()->setViewport(new osg::Viewport(0,0, traits->width, traits->height));
        view->getCamera()->setGraphicsContext(gc.get());
        view->setCameraManipulator(new osgGA::TrackballManipulator);

        // add the state manipulator
        osg::ref_ptr<osgGA::StateSetManipulator> statesetManipulator = new osgGA::StateSetManipulator;
        statesetManipulator->setStateSet(view->getCamera()->getOrCreateStateSet());

        view->addEventHandler( statesetManipulator.get() );
        view->addEventHandler( new osgViewer::StatsHandler );

        if (use_zeroconf)
        {
            osgGA::Device* zeroconf_device = osgDB::readFile<osgGA::Device>("_osc._udp.discover.zeroconf");
            if(zeroconf_device) {
                view->addDevice(zeroconf_device);
                view->getEventHandlers().push_front(new OscServiceDiscoveredEventHandler());

            }
        }
        else
        {
            osg::ref_ptr<osgGA::Device> device = osgDB::readFile<osgGA::Device>("localhost:9000.sender.osc");
            if (device.valid() && (device->getCapabilities() & osgGA::Device::SEND_EVENTS))
            {
                // add as first event handler, so it gets ALL events ...
                view->getEventHandlers().push_front(new ForwardToDeviceEventHandler(device.get()));

                // add the demo-pick-event-handler
                view->addEventHandler(new PickHandler(device.get()));
            }
            else {
                OSG_WARN << "could not open osc-device, sending will not work" << std::endl;
            }
        }
    }




    while (arguments.read("-s")) { viewer.setThreadingModel(osgViewer::CompositeViewer::SingleThreaded); }
    while (arguments.read("-g")) { viewer.setThreadingModel(osgViewer::CompositeViewer::CullDrawThreadPerContext); }
    while (arguments.read("-c")) { viewer.setThreadingModel(osgViewer::CompositeViewer::CullThreadPerCameraDrawThreadPerContext); }

     // run the viewer's main frame loop
     return viewer.run();
}
Exemplo n.º 22
0
OSGWidget::OSGWidget(cv::Mat* webcamMat, QWidget* parent, const QGLWidget* shareWidget)
    : QGLWidget( parent, shareWidget)
    , _graphicsWindow( new osgViewer::GraphicsWindowEmbedded( this->x(),
                                                               this->y(),
                                                               this->width(),
                                                               this->height() ) )
    , _viewer( new osgViewer::Viewer )
{
    //////////////////////////////////////////////////
    ////////// initialisation OpenCV /////////////////
    //////////////////////////////////////////////////

    cv::FileStorage fs("../rsc/intrinsicMatrix.yml", cv::FileStorage::READ);

    cv::Mat cameraMatrix;

    fs["cameraMatrix"] >> cameraMatrix;

    double NEAR_VALUE = (cameraMatrix.at<double>(0, 0) + cameraMatrix.at<double>(1, 1)) / 2; // NEAR = distance focale ; si pixels carrés, fx = fy -> np
    //mais est généralement différent de fy donc on prend (pour l'instant) par défaut la valeur médiane
    double FAR_VALUE = 2000 * NEAR_VALUE;

    fs.release();

    //////////////////////////////////////////////////
    ////////// initialisation OpenSceneGraph /////////
    //////////////////////////////////////////////////

    _backgroundImage = new osg::Image;
    _backgroundImage->setImage(webcamMat->cols, webcamMat->rows, 3,
                                GL_RGB, GL_BGR, GL_UNSIGNED_BYTE,
                                (uchar*)(webcamMat->data),
                                osg::Image::AllocationMode::NO_DELETE, 1);

    _hud = createHUD(_backgroundImage, webcamMat->cols, webcamMat->rows, cameraMatrix.at<double>(0, 2), cameraMatrix.at<double>(1, 2), NEAR_VALUE);

    _group = new osg::Group();
    _mainMat = new osg::MatrixTransform();
    _globalMat = new Our3DObject();
    _mainCam = new osg::Camera();
    _hudCam = new osg::Camera();

    // Projection

    osg::Matrixd projectionMatrix;

    projectionMatrix.makeFrustum(
                -cameraMatrix.at<double>(0, 2),		webcamMat->cols - cameraMatrix.at<double>(0, 2),
                -cameraMatrix.at<double>(1, 2),		webcamMat->rows - cameraMatrix.at<double>(1, 2),
                NEAR_VALUE,							FAR_VALUE);

    _corrector = (NEAR_VALUE / 2) / (cameraMatrix.at<double>(1, 2) - webcamMat->rows / 2);

    osg::Vec3d eye(0.0f, 0.0f, 0.0f), target(0.0f, FAR_VALUE, 0.0f), normal(0.0f, 0.0f, 1.0f);

    _hudCam->setProjectionMatrix(projectionMatrix);
    _hudCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
    _hudCam->setViewMatrixAsLookAt(eye, target, normal);
    _hudCam->setClearMask(GL_DEPTH_BUFFER_BIT);
    _hudCam->setRenderOrder(osg::Camera::PRE_RENDER);

    _mainCam->setProjectionMatrix(projectionMatrix);
    _mainCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
    _mainCam->setViewMatrixAsLookAt(eye, target, normal);
    _mainCam->setClearMask(GL_DEPTH_BUFFER_BIT);
    _mainCam->setRenderOrder(osg::Camera::POST_RENDER);

    //_mainCam->addChild(_mainMat);
    _mainMat->addChild(_globalMat);
    _hudCam->addChild(_hud);

    _group->addChild(_mainCam);
    _group->addChild(_hudCam);

    //float aspectRatio = static_cast<float>(this->width()) / static_cast<float>( this->height() );
    _viewer->setSceneData(_group.get());
    _viewer->getCamera()->setProjectionMatrix(projectionMatrix);
    _viewer->getCamera()->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
    _viewer->getCamera()->setViewMatrixAsLookAt(eye, target, normal);
    _viewer->getCamera()->setClearMask(GL_DEPTH_BUFFER_BIT);
    _viewer->getCamera()->setGraphicsContext(_graphicsWindow);

    _viewer->setThreadingModel( osgViewer::Viewer::SingleThreaded );
    _viewer->realize();

    this->setAutoBufferSwap(false);
}
Exemplo n.º 23
0
void main()
{
	bool patternfound = false;
	bool resetAuto = false;
	int nbImages = 0;
	double moyFinale = 0;
	bool detectionVisage = false;

	int nbrLoopSinceLastDetection = 0;
	int criticalValueOfLoopWithoutDetection = 15;

	std::cout << "initialisation de Chehra..." << std::endl;
	Chehra chehra;
	std::cout << "done" << std::endl;

	cv::Mat cameraMatrix, distCoeffs;
	cv::Mat rvecs, tvecs;

	std::vector<cv::Point2f> imagePoints;
	std::vector<cv::Point2f> pointsVisage2D;
	std::vector<cv::Point2f> moyPointsVisage2D;
	std::vector<cv::Point3f> pointsVisage3D;
	std::vector<cv::Point3f> visage;
	std::vector<double> distances;
	double moyDistances;

	std::vector<std::vector<cv::Point2f>> images;
	std::vector<cv::Mat> frames;

	double s = 10.0f;

	osg::Matrixd matrixS; // scale
	matrixS.set(
		s,	0,	0,	0,
		0,	s,	0,	0,
		0,	0,	s,	0,
		0,	0,	0,	1);
	
	pointsVisage3D.push_back(cv::Point3f(90,0,-80));
	pointsVisage3D.push_back(cv::Point3f(-90,0,-80));
	pointsVisage3D.push_back(cv::Point3f(0,0,0));
	pointsVisage3D.push_back(cv::Point3f(600,0,600));
	pointsVisage3D.push_back(cv::Point3f(0,0,600));
	pointsVisage3D.push_back(cv::Point3f(-600,0,600));
	/*
	pointsVisage3D.push_back(cv::Point3f(13.1, -98.1,108.3)); // exterieur narine gauche
	pointsVisage3D.push_back(cv::Point3f(-13.1, -98.1,108.3)); // exterieur narine droite
	pointsVisage3D.push_back(cv::Point3f(0, -87.2, 124.2)); // bout du nez
	pointsVisage3D.push_back(cv::Point3f(44.4, -57.9, 83.7)); // exterieur oeil gauche
	pointsVisage3D.push_back(cv::Point3f(0, 55.4, 101.4)); // haut du nez, centre des yeux
	pointsVisage3D.push_back(cv::Point3f(-44.4, -57.9, 83.7)); // exterieur oeil droit
	*/
	cv::FileStorage fs("../rsc/intrinsicMatrix.yml", cv::FileStorage::READ);

	fs["cameraMatrix"] >> cameraMatrix;
	fs["distCoeffs"] >> distCoeffs;

	double f = (cameraMatrix.at<double>(0, 0) + cameraMatrix.at<double>(1, 1)) / 2; // NEAR = distance focale ; si pixels carrés, fx = fy -> np 
	//mais est généralement différent de fy donc on prend (pour l'instant) par défaut la valeur médiane
	double g = 2000 * f; // je sais pas pourquoi. au pif.

	fs.release();

	cv::VideoCapture vcap(0); 
	if(!vcap.isOpened())
	{
		std::cout << "FAIL!" << std::endl;
		return;
	}

	cv::Mat *frame = new cv::Mat(cv::Mat::zeros(vcap.get(CV_CAP_PROP_FRAME_HEIGHT), vcap.get(CV_CAP_PROP_FRAME_WIDTH), CV_8UC3));

	do
	{
		vcap >> *frame;
	}while(frame->empty());

	osg::ref_ptr<osg::Image> backgroundImage = new osg::Image;
	backgroundImage->setImage(frame->cols, frame->rows, 3,
		GL_RGB, GL_BGR, GL_UNSIGNED_BYTE,
		(uchar*)(frame->data),
		osg::Image::AllocationMode::NO_DELETE, 1);

	// read the scene from the list of file specified commandline args.
	osg::ref_ptr<osg::Group> group = new osg::Group;
	osg::ref_ptr<osg::Geode> cam = createHUD(backgroundImage, vcap.get(CV_CAP_PROP_FRAME_WIDTH), vcap.get(CV_CAP_PROP_FRAME_HEIGHT), cameraMatrix.at<double>(0, 2), cameraMatrix.at<double>(1, 2), f);

	std::cout << "initialisation de l'objet 3D..." << std::endl;
	osg::ref_ptr<osg::Node> objet3D = osgDB::readNodeFile("../rsc/objets3D/brain.obj");
	//osg::ref_ptr<osg::Node> objet3D = osgDB::readNodeFile("../rsc/objets3D/dumptruck.osgt");

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////  
	/*
	osg::Sphere* unitSphere = new osg::Sphere(osg::Vec3(0, -1000, 1000), 100.0);
	osg::ShapeDrawable* unitSphereDrawable = new osg::ShapeDrawable(unitSphere);

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

	objet3D->addDrawable(unitSphereDrawable);
	*/
	//osg::StateSet* sphereStateset = unitSphereDrawable->getOrCreateStateSet();
	//sphereStateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
	//sphereStateset->setMode(GL_LIGHTING, osg::StateAttribute::OFF); 
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	std::cout << "done" << std::endl;

	osg::StateSet* obectStateset = objet3D->getOrCreateStateSet();
	obectStateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
	obectStateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
	osg::ref_ptr<osg::MatrixTransform> mat = new osg::MatrixTransform();

	// construct the viewer.
	osgViewer::CompositeViewer compositeViewer;
	osgViewer::View* viewer = new osgViewer::View;
	osgViewer::View* viewer2 = new osgViewer::View;

	// add the HUD subgraph.
	group->addChild(cam);

	mat->addChild(objet3D);
	group->addChild(mat);

	osg::Matrixd projectionMatrix;

	projectionMatrix.makeFrustum(
		-cameraMatrix.at<double>(0, 2),		vcap.get(CV_CAP_PROP_FRAME_WIDTH) - cameraMatrix.at<double>(0, 2),
		-cameraMatrix.at<double>(1, 2),		vcap.get(CV_CAP_PROP_FRAME_HEIGHT) - cameraMatrix.at<double>(1, 2),
		f,									g);

	osg::Vec3d eye(0.0f, 0.0f, 0.0f), target(0.0f, g, 0.0f), normal(0.0f, 0.0f, 1.0f);

	// set the scene to render
	viewer->setSceneData(group.get());
	viewer->setUpViewInWindow(0, 0, 1920 / 2, 1080 / 2); 
	viewer->getCamera()->setProjectionMatrix(projectionMatrix);
	viewer->getCamera()->setViewMatrixAsLookAt(eye, target, normal);

	viewer2->setSceneData(group.get());
	viewer2->setUpViewInWindow(1920 / 2, 0, 1920 / 2, 1080 / 2); 
	viewer2->getCamera()->setProjectionMatrix(projectionMatrix);
	osg::Vec3d eye2(4 * f, 3 * f / 2, 0.0f), target2(0.0f, f, 0.0f), normal2(0.0f, 0.0f, 1.0f);
	viewer2->getCamera()->setViewMatrixAsLookAt(eye2, target2, normal2);

	compositeViewer.addView(viewer2);
	compositeViewer.addView(viewer);

	compositeViewer.realize();  // set up windows and associated threads.

	do
	{       
		patternfound = false;
		resetAuto = false;
		detectionVisage = false;

		moyPointsVisage2D.clear();
		pointsVisage2D.clear();
		visage.clear();
		moyDistances = 0;
		distances.clear();

		std::cout << "recherche de pattern" << std::endl
			<< "nbr images sauvegardees : " << images.size() << std::endl;

		vcap >> *frame;
		frames.push_back(*frame);

		detectionVisage = detecterVisage(frame, &chehra, &pointsVisage2D, &visage);

		if(detectionVisage)
		{
			images.push_back(pointsVisage2D);
			nbrLoopSinceLastDetection = 0;
			group->addChild(mat);
		}
		else
			nbrLoopSinceLastDetection++;

		if((images.size() > NBRSAVEDIMAGES || nbrLoopSinceLastDetection > criticalValueOfLoopWithoutDetection) && !images.empty())
			images.erase(images.begin());

		if(images.empty())
			group->removeChild(mat);

		else
		{
			//cv::cornerSubPix(*frame, pointsVisage2D, cv::Size(5, 5), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));

			for(int i = 0; i < NBRFACEPOINTSDETECTED; i++)
			{
				cv::Point2f coordonee(0.0f, 0.0f);
				for(int j = 0; j < images.size(); j++)
				{
					coordonee.x += images[j][i].x;
					coordonee.y += images[j][i].y;
				}
				coordonee.x /= images.size();
				coordonee.y /= images.size();

				moyPointsVisage2D.push_back(coordonee);
			}

			cv::solvePnP(pointsVisage3D, moyPointsVisage2D, cameraMatrix, distCoeffs, rvecs, tvecs);

			cv::Mat rotVec(3, 3, CV_64F);
			cv::Rodrigues(rvecs, rotVec);
			
			imagePoints = dessinerPoints(frame, pointsVisage3D, rotVec, tvecs, cameraMatrix, distCoeffs);

			double t3 = tvecs.at<double>(2, 0);
			double t1 = tvecs.at<double>(0, 0);
			double t2 = tvecs.at<double>(1, 0) + t3 / 27.5; // and now, magic !

			double r11 = rotVec.at<double>(0, 0);
			double r12 = rotVec.at<double>(0, 1);
			double r13 = rotVec.at<double>(0, 2);
			double r21 = rotVec.at<double>(1, 0);
			double r22 = rotVec.at<double>(1, 1);
			double r23 = rotVec.at<double>(1, 2);
			double r31 = rotVec.at<double>(2, 0);
			double r32 = rotVec.at<double>(2, 1);
			double r33 = rotVec.at<double>(2, 2);


			osg::Matrixd matrixR; // rotation (transposee de rotVec)
			matrixR.set(
				r11,	r21,	r31,	0,
				r12,	r22,	r32,	0,
				r13,	r23,	r33,	0,
				0,		0,		0,		1);

			osg::Matrixd matrixT; // translation
			matrixT.makeTranslate(t1, t2, t3);

			osg::Matrixd matrix90; // rotation de repere entre opencv et osg
			matrix90.makeRotate(osg::Quat(osg::DegreesToRadians(-90.0f), osg::Vec3d(1.0, 0.0, 0.0)));

			mat->setMatrix(matrixS * matrixR * matrixT * matrix90);

			// Calcul d'erreur de reprojection
			double moy = 0;
			for(int i = 0; i < pointsVisage2D.size(); i++)
			{
				double d = sqrt(pow(pointsVisage2D[i].y - imagePoints[i].y, 2) + pow(pointsVisage2D[i].x - imagePoints[i].x, 2));
				distances.push_back(d);
				moy += d;
			}

			moyDistances = moy / pointsVisage2D.size();

			if(moyDistances > 2) // si l'ecart de reproj est trop grand, reset
				resetAuto = true;
		}
		
		backgroundImage->dirty();
		compositeViewer.frame();

	}while(!compositeViewer.done());
}
Exemplo n.º 24
0
int main( int argc, char **argv )
{
    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);
    

    unsigned int helpType = 0;
    if ((helpType = arguments.readHelpType()))
    {
        arguments.getApplicationUsage()->write(std::cout, helpType);
        return 1;
    }

    // report any errors if they have occurred when parsing the program arguments.
    if (arguments.errors())
    {
        arguments.writeErrorMessages(std::cout);
        return 1;
    }

    // read the scene from the list of file specified commandline args.
    osg::ref_ptr<osg::Node> scene = osgDB::readNodeFiles(arguments);
    
    // if not loaded assume no arguments passed in, try use default model instead.
    if (!scene) scene = osgDB::readNodeFile("dumptruck.osgt");
    
    if (!scene) 
    {
            osg::Geode* geode = new osg::Geode();
            osg::ShapeDrawable* drawable = new osg::ShapeDrawable(new osg::Box(osg::Vec3(0,0,0), 100));
            drawable->setColor(osg::Vec4(0.5, 0.5, 0.5,1));
            geode->addDrawable(drawable);
            scene = geode;
    }


    // construct the viewer.
    osgViewer::Viewer viewer(arguments);
    
    
    //opening devices
    std::string device;
    while(arguments.read("--device", device))
    {
        osg::ref_ptr<osgGA::Device> dev = osgDB::readFile<osgGA::Device>(device);
        if (dev.valid())
        {
            viewer.addDevice(dev.get());
        }
    }
    
    
    osg::ref_ptr<osg::Group> group  = new osg::Group;

    // add the HUD subgraph.    
    if (scene.valid()) group->addChild(scene.get());
    
    viewer.setCameraManipulator(new osgGA::MultiTouchTrackballManipulator());
    viewer.realize();
    
    osg::GraphicsContext* gc = viewer.getCamera()->getGraphicsContext();
    
    #ifdef __APPLE__
        // as multitouch is disabled by default, enable it now
        osgViewer::GraphicsWindowCocoa* win = dynamic_cast<osgViewer::GraphicsWindowCocoa*>(gc);
        if (win) win->setMultiTouchEnabled(true);
    #endif
    
    std::cout << "creating hud with " << gc->getTraits()->width << "x" <<  gc->getTraits()->height << std::endl;
    osg::Camera* hud_camera = createHUD(gc->getTraits()->width, gc->getTraits()->height);
    
    
    viewer.addEventHandler(new TestMultiTouchEventHandler(hud_camera, gc->getTraits()->width, gc->getTraits()->height));
    
    
    group->addChild(hud_camera);

    // set the scene to render
    viewer.setSceneData(group.get());

    return viewer.run();

    
}