void
MapNodeHelper::parse(MapNode*             mapNode,
                     osg::ArgumentParser& args,
                     osgViewer::View*     view,
                     osg::Group*          root,
                     Control*             userControl ) const
{
    if ( !root )
        root = mapNode;

    // parse out custom example arguments first:

    bool useSky        = args.read("--sky");
    bool useOcean      = args.read("--ocean");

    bool useMGRS       = args.read("--mgrs");
    bool useDMS        = args.read("--dms");
    bool useDD         = args.read("--dd");
    bool useCoords     = args.read("--coords") || useMGRS || useDMS || useDD;

    std::string kmlFile;
    args.read( "--kml", kmlFile );

    // install a canvas for any UI controls we plan to create:
    ControlCanvas* canvas = ControlCanvas::get(view, false);

    Container* mainContainer = canvas->addControl( new VBox() );
    mainContainer->setBackColor( Color(Color::Black, 0.8) );
    mainContainer->setHorizAlign( Control::ALIGN_LEFT );
    mainContainer->setVertAlign( Control::ALIGN_BOTTOM );

    // install the user control:
    if ( userControl )
        mainContainer->addControl( userControl );

    // look for external data in the map node:
    const Config& externals = mapNode->externalConfig();

    const Config& skyConf         = externals.child("sky");
    const Config& oceanConf       = externals.child("ocean");
    const Config& annoConf        = externals.child("annotations");
    const Config& declutterConf   = externals.child("decluttering");
    Config        viewpointsConf  = externals.child("viewpoints");

    // backwards-compatibility: read viewpoints at the top level:
    const ConfigSet& old_viewpoints = externals.children("viewpoint");
    for( ConfigSet::const_iterator i = old_viewpoints.begin(); i != old_viewpoints.end(); ++i )
        viewpointsConf.add( *i );

    // Loading a viewpoint list from the earth file:
    if ( !viewpointsConf.empty() )
    {
        std::vector<Viewpoint> viewpoints;

        const ConfigSet& children = viewpointsConf.children();
        if ( children.size() > 0 )
        {
            for( ConfigSet::const_iterator i = children.begin(); i != children.end(); ++i )
            {
                viewpoints.push_back( Viewpoint(*i) );
            }
        }

        if ( viewpoints.size() > 0 )
        {
            Control* c = ViewpointControlFactory().create(viewpoints, view);
            if ( c )
                mainContainer->addControl( c );
        }
    }

    // Adding a sky model:
    if ( useSky || !skyConf.empty() )
    {
        double hours = skyConf.value( "hours", 12.0 );
        SkyNode* sky = new SkyNode( mapNode->getMap() );
        sky->setDateTime( 2011, 3, 6, hours );
        sky->attach( view );
        root->addChild( sky );
        Control* c = SkyControlFactory().create(sky, view);
        if ( c )
            mainContainer->addControl( c );
    }

    // Adding an ocean model:
    if ( useOcean || !oceanConf.empty() )
    {
        OceanSurfaceNode* ocean = new OceanSurfaceNode( mapNode, oceanConf );
        if ( ocean )
        {
            root->addChild( ocean );
            Control* c = OceanControlFactory().create(ocean, view);
            if ( c )
                mainContainer->addControl(c);
        }
    }

    // Loading KML from the command line:
    if ( !kmlFile.empty() )
    {
        KMLOptions kml_options;
        kml_options.declutter() = true;
        kml_options.defaultIconImage() = URI( KML_PUSHPIN_URL ).getImage();

        osg::Node* kml = KML::load( URI(kmlFile), mapNode, kml_options );
        if ( kml )
        {
            Control* c = AnnotationGraphControlFactory().create(kml, view);
            if ( c )
            {
                c->setVertAlign( Control::ALIGN_TOP );
                canvas->addControl( c );
            }
            root->addChild( kml );
        }
    }

    // Annotations in the map node externals:
    if ( !annoConf.empty() )
    {
        osg::Group* annotations = 0L;
        AnnotationRegistry::instance()->create( mapNode, annoConf, annotations );
        if ( annotations )
        {
            root->addChild( annotations );
        }
    }

    // Configure the de-cluttering engine for labels and annotations:
    if ( !declutterConf.empty() )
    {
        Decluttering::setOptions( DeclutteringOptions(declutterConf) );
    }

    // Configure the mouse coordinate readout:
    if ( useCoords )
    { 
        LabelControl* readout = new LabelControl();
        readout->setBackColor( Color(Color::Black, 0.8) );
        readout->setHorizAlign( Control::ALIGN_RIGHT );
        readout->setVertAlign( Control::ALIGN_BOTTOM );

        Formatter* formatter = 
            useMGRS ? (Formatter*)new MGRSFormatter(MGRSFormatter::PRECISION_1M, 0L, MGRSFormatter::USE_SPACES) :
            useDMS  ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DEGREES_MINUTES_SECONDS) :
            useDD   ? (Formatter*)new LatLongFormatter(LatLongFormatter::FORMAT_DECIMAL_DEGREES) :
            0L;

        MouseCoordsTool* mcTool = new MouseCoordsTool( mapNode );
        mcTool->addCallback( new MouseCoordsLabelCallback(readout, formatter) );
        view->addEventHandler( mcTool );

        canvas->addControl( readout );
    }

    root->addChild( canvas );
}
Пример #2
0
void writeDISSection(std::ostream& out, Config& config)
{
    out << "# DIS" << std::endl;
    out << config.getParameter("VRLINK") << std::endl;
    out << config.getParameter("VRLINK-PROTOCOL") << std::endl;

    out << config.getParameter("VRLINK-DIS-IP-ADDRESS") << std::endl;
    out << config.getParameter("VRLINK-DIS-NETWORK-INTERFACE") << std::endl;
    out << config.getParameter("VRLINK-DIS-PORT") << std::endl;
    if (config.parameterExists("VRLINK-DIS-SUBNET-MASK"))
    {
        out << config.getParameter("VRLINK-DIS-SUBNET-MASK") << std::endl;
    }

    out << config.getParameter("VRLINK-ENTITIES-FILE-PATH") << std::endl;
    out << config.getParameter("VRLINK-RADIOS-FILE-PATH") << std::endl;
    out << config.getParameter("VRLINK-NETWORKS-FILE-PATH") << std::endl;

    out << config.getParameter("VRLINK-DEBUG-PRINT-COMMS") << std::endl;
    out << config.getParameter("VRLINK-DEBUG-PRINT-COMMS-2") << std::endl;
    out << config.getParameter("VRLINK-DEBUG-PRINT-MAPPING") << std::endl;
    out << config.getParameter("VRLINK-DEBUG-PRINT-DAMAGE") << std::endl;
    out << config.getParameter("VRLINK-DEBUG-PRINT-TX-STATE") << std::endl;
    out << config.getParameter("VRLINK-DEBUG-PRINT-TX-POWER") << std::endl;
    out << config.getParameter("VRLINK-DEBUG-PRINT-MOBILITY") << std::endl;
    out << config.getParameter(
        "VRLINK-DEBUG-PRINT-TRANSMITTER-PDU") << std::endl;
    out << config.getParameter("VRLINK-DEBUG-PRINT-PDUS") << std::endl;
    out << config.getParameter("VRLINK-RECEIVE-DELAY") << std::endl;
    out << config.getParameter("VRLINK-MAX-RECEIVE-DURATION") << std::endl;
    out << config.getParameter("VRLINK-XYZ-EPSILON") << std::endl;
    out << config.getParameter("VRLINK-MOBILITY-INTERVAL") << std::endl;

    out << std::endl;
}
Пример #3
0
// ---------------------------------------------------------
void ResourceAudio::Load(const Config & config)
{
	Resource::Load(config);
	format = (Format) config.GetInt("Format", unknown);
}
Пример #4
0
void
TerrainLayerOptions::fromConfig( const Config& conf )
{
    _name = conf.value("name");
    conf.getIfSet( "min_level", _minLevel );
    conf.getIfSet( "max_level", _maxLevel );        
    conf.getIfSet( "min_resolution", _minResolution );
    conf.getIfSet( "max_resolution", _maxResolution );
    conf.getIfSet( "loading_weight", _loadingWeight );
    conf.getIfSet( "enabled", _enabled );
    conf.getIfSet( "visible", _visible );
    conf.getIfSet( "edge_buffer_ratio", _edgeBufferRatio);    
    conf.getIfSet( "reprojected_tilesize", _reprojectedTileSize);

    conf.getIfSet( "vdatum", _vertDatum );
    conf.getIfSet( "vsrs", _vertDatum );    // back compat

    conf.getIfSet   ( "cacheid",      _cacheId );
    conf.getIfSet   ( "cache_format", _cacheFormat );
    conf.getObjIfSet( "cache_policy", _cachePolicy );
    conf.getObjIfSet( "proxy",        _proxySettings );

    // legacy support:
    if ( conf.value<bool>( "cache_only", false ) == true )
        _cachePolicy->usage() = CachePolicy::USAGE_CACHE_ONLY;
    if ( conf.value<bool>( "cache_enabled", true ) == false )
        _cachePolicy->usage() = CachePolicy::USAGE_NO_CACHE;

    if ( conf.hasValue("driver") )
        driver() = TileSourceOptions(conf);
}
Пример #5
0
void writePhysicalSection(std::ostream& out, Config& config, NodeSet& ns)
{
    out << "# Physical" << std::endl;
    NetworkSet& nets = ns.networksUsed();

    std::string defaultModel =
                    config.getParameter("VRLINK-DEFAULT-ROUTER-MODEL").value;

    std::set<std::string> models;
    NetworkSet::iterator nit = nets.begin();
    while (nit != nets.end())
    {
        if ((*nit)->models.size() == 0)
        {
            models.insert(defaultModel);
        }
        else
        {
            models.insert((*nit)->models.begin(), (*nit)->models.end());
        }
        nit++;
    }
    if (models.size() == 1)
    {
        ParameterMap* parameters = config.getModelParameterList(*models.begin());
        if (parameters)
        {
            writeParameters(out, "", parameters);
        }
    }
    else if (models.size() > 1)
    {
        nit = nets.begin();
        while (nit != nets.end())
        {
            Network* n = *nit;
            ParameterMap* common = n->getCommonParameters();
            std::stringstream subnet;
            subnet << "[" << n->address << "]";
            writeParameters(out, subnet.str(), common);

            std::set<std::string>::iterator mit = n->models.begin();
            while (mit != n->models.end())
            {
                ParameterMap* parameters = config.getModelParameterList(*mit);
                ParameterMap* specfic = *parameters - *common;
                std::string group = n->getGroup(*mit);
                if (parameters && !group.empty())
                {
                    writeParameters(out, group, specfic);
                }
                delete specfic;
                mit++;
            }
            nit++;
        }
    }

    std::set<std::string>::iterator it = ns.modelsUsed().begin();
    if (it != ns.modelsUsed().end())
    {
        out << config.getParameter("ROUTER-MODEL-CONFIG-FILE") << std::endl;
    }
}
Пример #6
0
void
AltitudeSymbol::parseSLD(const Config& c, Style& style)
{
    if ( match(c.key(), "altitude-clamping") ) {
        if      ( match(c.value(), "none") )
            style.getOrCreate<AltitudeSymbol>()->clamping() = CLAMP_NONE;
        else if ( match(c.value(), "terrain") )
            style.getOrCreate<AltitudeSymbol>()->clamping() = CLAMP_TO_TERRAIN;
        else if ( match(c.value(), "absolute") )
            style.getOrCreate<AltitudeSymbol>()->clamping() = CLAMP_ABSOLUTE;
        else if ( match(c.value(), "relative") )
            style.getOrCreate<AltitudeSymbol>()->clamping() = CLAMP_RELATIVE_TO_TERRAIN;
        else if ( match(c.value(), "terrain-drape") )
        {
            style.getOrCreate<AltitudeSymbol>()->clamping()  = CLAMP_TO_TERRAIN;
            style.getOrCreate<AltitudeSymbol>()->technique() = TECHNIQUE_DRAPE;
        }
        else if ( match(c.value(), "terrain-gpu") )
        {
            style.getOrCreate<AltitudeSymbol>()->clamping()  = CLAMP_TO_TERRAIN;
            style.getOrCreate<AltitudeSymbol>()->technique() = TECHNIQUE_GPU;
        }
    }
    else if ( match(c.key(), "altitude-technique") ) {
        if      ( match(c.value(), "map") )
            style.getOrCreate<AltitudeSymbol>()->technique() = TECHNIQUE_MAP;
        else if ( match(c.value(), "scene") )
            style.getOrCreate<AltitudeSymbol>()->technique() = TECHNIQUE_SCENE;
        else if ( match(c.value(), "gpu") )
            style.getOrCreate<AltitudeSymbol>()->technique() = TECHNIQUE_GPU;
        else if ( match(c.value(), "drape") )
            style.getOrCreate<AltitudeSymbol>()->technique() = TECHNIQUE_DRAPE;
    }
    else if ( match(c.key(), "altitude-binding") ) {
        if      ( match(c.value(), "vertex") )
            style.getOrCreate<AltitudeSymbol>()->binding() = BINDING_VERTEX;
        else if ( match(c.value(), "centroid") )
            style.getOrCreate<AltitudeSymbol>()->binding() = BINDING_CENTROID;
    }
    else if ( match(c.key(), "altitude-resolution") ) {
        style.getOrCreate<AltitudeSymbol>()->clampingResolution() = as<float>( c.value(), 0.0f );
    }
    else if ( match(c.key(), "altitude-offset") ) {
        style.getOrCreate<AltitudeSymbol>()->verticalOffset() = NumericExpression( c.value() );
    }
    else if ( match(c.key(), "altitude-scale") ) {
        style.getOrCreate<AltitudeSymbol>()->verticalScale() = NumericExpression( c.value() );
    }
}
Пример #7
0
//======================================================================
// event-handler methods
//======================================================================
bool Window::processEvent( const Event& event )
{
    ConfigEvent configEvent;
    switch( event.type )
    {
    case Event::WINDOW_HIDE:
        setPixelViewport( PixelViewport( 0, 0, 0, 0 ));
        break;

    case Event::WINDOW_SHOW:
    case Event::WINDOW_RESIZE:
        setPixelViewport( PixelViewport( event.resize.x, event.resize.y,
                                         event.resize.w, event.resize.h ));
        break;

    case Event::KEY_PRESS:
    case Event::KEY_RELEASE:
        if( event.key.key == KC_VOID )
            return true; // ignore
    // else fall through
    case Event::WINDOW_EXPOSE:
    case Event::WINDOW_CLOSE:
    case Event::WINDOW_POINTER_WHEEL:
    case Event::STATISTIC:
        break;

    case Event::WINDOW_POINTER_MOTION:
    case Event::WINDOW_POINTER_BUTTON_PRESS:
    case Event::WINDOW_POINTER_BUTTON_RELEASE:
    {
        // dispatch pointer events to destination channel, if any
        const Channels& channels = getChannels();
        for( Channels::const_iterator i = channels.begin();
                i != channels.end(); ++i )
        {
            Channel* channel = *i;
            if( !channel->isDestination( ))
                continue;

            const PixelViewport& pvp = getPixelViewport();
            const PixelViewport& channelPVP =
                channel->getNativePixelViewport();

            // convert y to GL notation (Channel PVP uses GL coordinates)
            const int32_t y = pvp.h - event.pointer.y;
            if( !channelPVP.isInside( event.pointer.x, y ))
                continue;

            Event channelEvent = event;
            switch( event.type )
            {
            case Event::WINDOW_POINTER_MOTION:
                channelEvent.type = Event::CHANNEL_POINTER_MOTION;
                break;
            case Event::WINDOW_POINTER_BUTTON_PRESS:
                channelEvent.type = Event::CHANNEL_POINTER_BUTTON_PRESS;
                break;
            case Event::WINDOW_POINTER_BUTTON_RELEASE:
                channelEvent.type = Event::CHANNEL_POINTER_BUTTON_RELEASE;
                break;
            default:
                LBWARN << "Unhandled window event of type " << event.type
                       << std::endl;
                LBUNIMPLEMENTED;
            }

            LBASSERT( channel->getID() != UUID::ZERO );
            channelEvent.originator = channel->getID();
            channelEvent.serial = channel->getSerial();
            channelEvent.pointer.x -= channelPVP.x;
            channelEvent.pointer.y = channelPVP.h - y + channelPVP.y;
            channel->processEvent( channelEvent );
        }
        break;
    }

    case Event::WINDOW_SCREENSAVER:
        switch( getIAttribute( IATTR_HINT_SCREENSAVER ))
        {
        case OFF:
            return true; // screen saver stays inactive
        case ON:
            return false; // screen saver becomes active
        default: // AUTO
            if( getDrawableConfig().doublebuffered &&
                    getIAttribute( IATTR_HINT_DRAWABLE ) == WINDOW )
            {
                return true; // screen saver stays inactive
            }
            return false;
        }

    case Event::UNKNOWN:
        // unknown window-system native event, which was not handled
        return false;

    default:
        LBWARN << "Unhandled window event of type " << event.type
               << std::endl;
        LBUNIMPLEMENTED;
    }

    configEvent.data = event;

    Config* config = getConfig();
    config->sendEvent( configEvent );
    return true;
}
Пример #8
0
bool
SplatExtension::connect(MapNode* mapNode)
{
    if ( !mapNode )
    {
        OE_WARN << LC << "Illegal: MapNode cannot be null." << std::endl;
        return false;
    }

    OE_INFO << LC << "Connecting to MapNode.\n";

    if ( !_options.catalogURI().isSet() )
    {
        OE_WARN << LC << "Illegal: catalog URI is required" << std::endl;
        return false;
    }

    if ( !_options.legendURI().isSet() )
    {
        OE_WARN << LC << "Illegal: legend URI is required" << std::endl;
        return false;
    }

    if ( !_options.coverageLayerName().isSet() )
    {
        OE_WARN << LC << "Illegal: coverage layer name is required" << std::endl;
        return false;
    }

    // Locate the coverage layer in the map.
    const Map* map = mapNode->getMap();
    const ImageLayer* coverageLayer = map->getImageLayerByName( _options.coverageLayerName().get() );
    if ( !coverageLayer )
    {
        OE_WARN << LC << "Coverage layer \""
            << _options.coverageLayerName().get()
            << "\" not found in map."
            << std::endl;
        return false;
    }

    // Read in the catalog.
    osg::ref_ptr<SplatCatalog> catalog = new SplatCatalog();
    {
        ReadResult result = _options.catalogURI()->readString( _dbOptions.get() );
        if ( result.succeeded() )
        {
            Config conf;
            conf.setReferrer(_options.catalogURI()->full());

            std::string json = result.getString();
            conf.fromJSON( json );
            catalog->fromConfig( conf );

            OE_INFO << LC << "Catalog: " << catalog->getClasses().size() << " classes\n";
        }
        else
        {
            OE_WARN << LC
                << "Failed to read catalog from \""
                << _options.catalogURI()->full() << "\"\n";
            return false;
        }
    }

    // Read in the legend.
    osg::ref_ptr<SplatCoverageLegend> legend = new SplatCoverageLegend();
    {
        ReadResult result = _options.legendURI()->readString( _dbOptions.get() );
        if ( result.succeeded() )
        {
            Config conf;
            conf.setReferrer(_options.legendURI()->full());

            conf.fromJSON( result.getString() );
            legend->fromConfig( conf );

            OE_INFO << LC << "Legend: " << legend->getPredicates().size() << " mappings \n";
        }
        else
        {
            OE_WARN << LC
                << "Failed to read legend from \""
                << _options.legendURI()->full() << "\"\n";
            return false;
        }
    }

    // Install the splatter on the terrain engine.
    _effect = new SplatTerrainEffect( catalog, legend, _dbOptions.get() );

    // set the coverage layer (mandatory)
    _effect->setCoverageLayer( coverageLayer );

    // set the render order (optional)
    if ( _options.drawAfterImageLayers() == true )
        _effect->setRenderOrder( 1.0f );

    mapNode->getTerrainEngine()->addEffect( _effect.get() );

    return true;
}
Пример #9
0
void TextureUtil::initGrx() {
  Config * config = Config::getInstance();

#if EM_USE_SDL
  cerr << "Initing SDL" << endl << endl;
  if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0) {
    cerr << "Couldn't initialize SDL video" << SDL_GetError() << endl;
    exit(1);
  }

  if (SDL_InitSubSystem(SDL_INIT_JOYSTICK) < 0) {
    cerr << "Couldn't initialize SDL joystick: " <<  SDL_GetError() << endl << endl;
  } else {
    int njoystick = SDL_NumJoysticks();
    cerr << njoystick << " joysticks were found." << endl;
    if (njoystick != 0) {
      cerr << "The names of the joysticks are:" << endl;
      for(int a=0; a<njoystick; a++ ) {
        cerr << "  " << SDL_JoystickName(a) << endl;
      }
      cerr << "Using " << SDL_JoystickName(0) << endl << endl;
      SDL_JoystickOpen(0);
      SDL_JoystickEventState(SDL_ENABLE);
    }
  }

  // See if we should detect the display depth
  if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 8 ) {
    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 2 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 3 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 3 );
  } else        if ( SDL_GetVideoInfo()->vfmt->BitsPerPixel <= 16 ) {
    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 5 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
  }     else {
    SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 );
    SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 );
    SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 );
  }

  SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 16 );
  SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

  /* Initialize the display */
  SDL_Surface* screen =
    SDL_SetVideoMode(config->getWidth(), config->getHeight(), config->getBpp(),
                     SDL_OPENGL
                     | (config->useFullScreen() ? SDL_FULLSCREEN : 0));

  //    if (config->useFullScreen()) {
  SDL_ShowCursor(SDL_DISABLE);
  //    }
  SDL_WM_SetCaption("Emilia Pinball", NULL);

  if (screen == NULL) {
    cerr << "Couldn't set video mode: " << SDL_GetError() << endl;
    exit(1);
  }

  cerr << "Vendor     : " << glGetString( GL_VENDOR ) << endl;
  cerr << "Renderer   : " << glGetString( GL_RENDERER ) << endl;
  cerr << "Version    : " << glGetString( GL_VERSION ) << endl;
  cerr << "Extensions : " << glGetString( GL_EXTENSIONS ) << endl << endl;
  //TODO: that would be usefull to report CPU/RAM specs also //!rzr

  int value;
  SDL_GL_GetAttribute( SDL_GL_RED_SIZE, &value );
  cerr << "SDL_GL_RED_SIZE: " << value << endl;
  SDL_GL_GetAttribute( SDL_GL_GREEN_SIZE, &value );
  cerr << "SDL_GL_GREEN_SIZE: " << value << endl;
  SDL_GL_GetAttribute( SDL_GL_BLUE_SIZE, &value );
  cerr << "SDL_GL_BLUE_SIZE: " << value << endl;
  SDL_GL_GetAttribute( SDL_GL_DEPTH_SIZE, &value );
  cerr << "SDL_GL_DEPTH_SIZE: " << value << endl;
  SDL_GL_GetAttribute( SDL_GL_DOUBLEBUFFER, &value );
  cerr << "SDL_GL_DOUBLEBUFFER: " << value << endl << endl;

  this->resizeView(config->getWidth(), config->getHeight());
#endif // EM_USE_SDL

#if EM_USE_ALLEGRO
  //config->setSize(320, 240);

  allegro_init();
  install_keyboard();
  install_timer();
  install_mouse();

  COLOR_MAP colorMap;
  RGB_MAP rgbMap;
  COLOR_MAP transMap;

  RGB* paPalette = (RGB*) calloc(256, sizeof(RGB));
  generate_332_palette(paPalette);
  // create rgb table
  create_rgb_table(&rgbMap, paPalette, NULL);
  rgb_map = &rgbMap;
  // create light table and setup the truecolor blending functions.
  create_light_table(&colorMap, paPalette, 0, 0, 0, NULL);
  color_map = &colorMap;
  // texture and flat polygons are 50% transparent
  create_trans_table(&transMap, paPalette, 128, 128, 128, NULL);
  set_trans_blender(0, 0, 0, 128);
  // set the graphics mode
  int tc = GFX_AUTODETECT_WINDOWED, tw = config->getWidth();
  int th = config->getHeight(), tbpp = 16;
  /*
    set_gfx_mode(GFX_SAFE, 320, 200, 0, 0);
    set_palette(desktop_palette);

    if (!gfx_mode_select_ex(&tc, &tw, &th, &tbpp)) {
    allegro_exit();
    cerr << "Error setting safe graphics mode" << endl;
    }
  */
  set_color_depth(tbpp);
  if (set_gfx_mode(tc, tw, th, 0, 0) != 0) {
    allegro_exit();
    cerr << "Error setting graphics mode " << endl << allegro_error << endl;
  }
  set_palette(paPalette);
  config->setSize(tw, th);
  set_projection_viewport(0, 0, tw, th);
  // Create back buffer.
  backbuffer = create_bitmap(tw, th);
  clear(backbuffer);
  zbuffer = create_zbuffer(backbuffer);
  set_zbuffer(zbuffer);
  clear_zbuffer(zbuffer, 0);
#endif // EM_USE_ALLEGRO
}
Пример #10
0
int Global::init(){
    Global::CONFIG_FILE = "game.conf";
    Config * config = new Config(Global::CONFIG_FILE);

    Global::SCREEN_WIDTH=960;
    Global::SCREEN_HEIGHT=540;
    Global::SCREEN_RES_WIDTH=atoi(config->getSetting("GAMESETTINGS","RES_X").c_str());
    Global::SCREEN_RES_HEIGHT=atoi(config->getSetting("GAMESETTINGS","RES_Y").c_str());;

    Global::GRAVITY=840;

    //Initialize SDL
	if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
	{
		printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
		return 1;
	}

    //Enable VSync
    if( !SDL_SetHint( SDL_HINT_RENDER_VSYNC, "1" ) )
    {
        printf( "Warning: VSync not enabled!" );
    }

    //Set texture filtering to linear
    if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
    {
        printf( "Warning: Linear texture filtering not enabled!" );
    }

    //Create window
    Uint32 flags = SDL_WINDOW_SHOWN;
    if(config->getSetting("GAMESETTINGS","WINDOW_BORDER").compare("FALSE")==0){
        flags = flags|SDL_WINDOW_BORDERLESS;
    }
    Global::gameWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, Global::SCREEN_RES_WIDTH, Global::SCREEN_RES_HEIGHT, flags);
    if( Global::gameWindow == NULL )
    {
        printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
        return 1;
    }

    //Create renderer for window
    Global::gameRenderer = SDL_CreateRenderer( Global::gameWindow, -1, SDL_RENDERER_ACCELERATED );
    if( Global::gameRenderer == NULL )
    {
        printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
        return 1;
    }
    SDL_RenderSetScale(gameRenderer,(float)Global::SCREEN_RES_WIDTH/(float)Global::SCREEN_WIDTH,(float)Global::SCREEN_RES_HEIGHT/(float)Global::SCREEN_HEIGHT);

    //Initialize PNG loading
    int imgFlags = IMG_INIT_PNG;
    if( !( IMG_Init( imgFlags ) & imgFlags ) )
    {
        printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
        return 1;
    }

    return 0;
}
Пример #11
0
// Entry point of the slot machine engine
int main(int argc, char**argv)
{	
	// Money input
	int money = 0;

	// Check argc and set flags
	if(argc <= 1)
	{
		DisplayInfos(argv[0]);
		return 0;
	}
	else
	{
		// Check for flag and money input
		for(int i = 1; i < argc; i++)
		{
			// Flag input
			if(argv[i][0] == '-')
			{	
				// Trace enabled
				if(strncmp(argv[i], "-t", 2) == 0)
				{
					g_trace = true;
				}
				// RTE enabled
				else if(strncmp(argv[i], "-rte", 4) == 0)
				{
					g_rte = true;
				}
				// Variance enabled
				else if(strncmp(argv[i], "-v", 2) == 0)
				{
					g_var = true;
				}
			}
			// Money input
			else
			{
				money = atoi(argv[i]);
			}
		}
	}

	// Check money value
	if(money <= 0)
	{
		DisplayInfos(argv[0]);
		return 0;
	}

	// Reset the random seed at start
	// Take the time in µsec in order to get different result all the time
	timeval tv;
	gettimeofday(&tv, NULL);
	std::srand(tv.tv_sec * 1000000 + tv.tv_usec);

	// Load main configuration first
	Config* config = Config::GetInst();
	if(config->GetLoadErr())
	{	
		std::cerr << std::endl << "Error while loading " << CONFIG_FILE << "." << std::endl << "Closing application." << std::endl;
		
		// Delete the config Singleton
		config->DeleteSingleton();

		return ERR_LOAD_FILE;
	}

	// Display for debug
	if(g_trace)
	{
		config->DebugPrint();
	}

	// Load Line Shape Manager Then
	LineShapeManager* LSM = LineShapeManager::GetInst();
	if(LSM->GetLoadErr())
	{
		std::cerr << std::endl << "Error while loading " << LINE_SHAPES_FILE << "." << std::endl << "Closing application." << std::endl;
		
		// Delete the LSM Singleton
		LSM->DeleteSingleton();

		// Delete the config Singleton
		config->DeleteSingleton();

		return ERR_LOAD_FILE;
	}

	// Display for debug
	if(g_trace)
	{
		LSM->DebugPrint();
	}

	// Load Symbol Manager
	SymbolManager* SM = SymbolManager::GetInst();
	if(SM->GetLoadErr())
	{
		std::cerr << std::endl << "Error while loading " << SYMBOLS_FILE << "." << std::endl << "Closing application." << std::endl;
		
		// Delete the SM Singleton
		SM->DeleteSingleton();

		// Delete the LSM Singleton
		LSM->DeleteSingleton();

		// Delete the config Singleton
		config->DeleteSingleton();

		return ERR_LOAD_FILE;
	}

	// Display for debug
	if(g_trace)
	{
		SM->DebugPrint();
	}

	// Load Wheel Manager
	WheelManager* WM = WheelManager::GetInst();
	if(WM->GetLoadErr())
	{
		std::cerr << std::endl << "Error while loading " << WHEELS_FILE << "." << std::endl << "Closing application." << std::endl;
		
		// Delete the WM Singleton
		WM->DeleteSingleton();

		// Delete the SM Singleton
		SM->DeleteSingleton();

		// Delete the LSM Singleton
		LSM->DeleteSingleton();

		// Delete the config Singleton
		config->DeleteSingleton();
		
		return ERR_LOAD_FILE;
	}
	
	// Display for debug
	if(g_trace)
	{
		WM->DebugPrint();
	}

	// Compute the output now
	Engine* engine = new Engine(money);
	
	// Display for debug
	if(g_trace)
	{
		engine->DebugPrint();
		engine->SendResultExplanation();
	}
	
	// Display the output for php page
	engine->SendResult();
	
	// Display RTE
	if(g_var)
	{
		std::cout << "Computing RTE..." << std::endl;
		float rte = engine->ComputeRTE();
		std::cout << "RTE = " << rte << std::endl;
		std::cout << "Computing Variance..." << std::endl;
		std::cout << "Variance = " << engine->ComputeVariance(rte) << std::endl;
	}
	else if(g_rte)
	{	
		std::cout << "Computing RTE..." << std::endl;
		std::cout << "RTE = " << engine->ComputeRTE() << std::endl;
	}	
	
	// Delete all Singletons at the end of the main
	config->DeleteSingleton();
	LSM->DeleteSingleton();
	SM->DeleteSingleton();
	WM->DeleteSingleton();

	// Clean memory
	delete engine;
	return 0;
}
Пример #12
0
Config
MapNodeOptions::getConfig() const
{
    Config conf; // start with a fresh one since this is a FINAL object  // = ConfigOptions::getConfig();
    conf.key() = "options";

    conf.updateObjIfSet( "proxy",                    _proxySettings );
    conf.updateIfSet   ( "cache_only",               _cacheOnly );
    conf.updateIfSet   ( "lighting",                 _enableLighting );
    conf.updateIfSet   ( "terrain",                  _terrainOptionsConf );
    conf.updateIfSet   ( "overlay_warping",          _overlayVertexWarping );
    conf.updateIfSet   ( "overlay_blending",         _overlayBlending );
    conf.updateIfSet   ( "overlay_texture_size",     _overlayTextureSize );
    conf.updateIfSet   ( "overlay_mipmapping",       _overlayMipMapping );
    conf.updateIfSet   ( "overlay_attach_stencil",   _overlayAttachStencil );
    conf.updateIfSet   ( "overlay_resolution_ratio", _overlayResolutionRatio );

    return conf;
}
Пример #13
0
void
MapNodeOptions::mergeConfig( const Config& conf )
{
    ConfigOptions::mergeConfig( conf );

    conf.getObjIfSet( "proxy",                    _proxySettings );
    conf.getIfSet   ( "cache_only",               _cacheOnly );
    conf.getIfSet   ( "lighting",                 _enableLighting );
    conf.getIfSet   ( "overlay_warping",          _overlayVertexWarping );
    conf.getIfSet   ( "overlay_blending",         _overlayBlending );
    conf.getIfSet   ( "overlay_texture_size",     _overlayTextureSize );
    conf.getIfSet   ( "overlay_mipmapping",       _overlayMipMapping );
    conf.getIfSet   ( "overlay_attach_stencil",   _overlayAttachStencil );
    conf.getIfSet   ( "overlay_resolution_ratio", _overlayResolutionRatio );

    if ( conf.hasChild( "terrain" ) )
    {
        _terrainOptionsConf = conf.child( "terrain" );
        if ( _terrainOptions )
        {
            delete _terrainOptions;
            _terrainOptions = 0L;
        }
    }
}
Пример #14
0
int main(int argc, char *argv[])
{
	Config config;
	config.setValue("bool", true);
	config.setValue("int", 21334);
	config.setValue("string", "babablsh?");
	config.setValue("awful string::", "babablsh? Hayouasd");
	
	Config merge;
	merge.setValue("test", "lololo");
	merge.setValue("test/subkey", "..adasdasd");
	config.beginGroup("group");
	config.addValues(merge);
	config.beginGroup("test");
	config.values().save("test_subkeys.conf");
	config.endGroup();
	config.endGroup();
	config.save("test.conf");
	
	Config *read = Config::load("test.conf");
	assert(read);
	assert(read->boolValue("bool") == true);
	assert(read->intValue("int") == 21334);
	assert(read->stringValue("awful string::").compare("babablsh? Hayouasd") == 0);
	delete read;
	
	
	
	return 0;
}
Пример #15
0
Config
AltitudeSymbol::getConfig() const
{
    Config conf;
    conf.key() = "altitude";
    conf.addIfSet   ( "clamping",  "none",       _clamping, CLAMP_NONE );
    conf.addIfSet   ( "clamping",  "terrain",    _clamping, CLAMP_TO_TERRAIN );
    conf.addIfSet   ( "clamping",  "absolute",   _clamping, CLAMP_ABSOLUTE );
    conf.addIfSet   ( "clamping",  "relative",   _clamping, CLAMP_RELATIVE_TO_TERRAIN );

    conf.addIfSet   ( "technique", "map",   _technique, TECHNIQUE_MAP );
    conf.addIfSet   ( "technique", "scene", _technique, TECHNIQUE_SCENE );
    conf.addIfSet   ( "technique", "gpu",   _technique, TECHNIQUE_GPU );
    conf.addIfSet   ( "technique", "drape", _technique, TECHNIQUE_DRAPE );

    conf.addIfSet   ( "binding", "vertex",   _binding, BINDING_VERTEX );
    conf.addIfSet   ( "binding", "centroid", _binding, BINDING_CENTROID );

    conf.addIfSet   ( "clamping_resolution",     _resolution );
    conf.addObjIfSet( "vertical_offset",         _verticalOffset );
    conf.addObjIfSet( "vertical_scale",          _verticalScale );
    return conf;
}
// Training of client Speakers
// The same than TrainTarget but train simultaneoulsy 1 model for each cluster (set of segments with the same label)
// found in the input files labels.
// One option in order to save the n models as a modification of the world model - save disk space
 int TrainTargetByLabel(Config& config)
{
  String inputClientListFileName = config.getParam("targetIdList");
  String inputWorldFilename = config.getParam("inputWorldFilename");
  String outputSERVERFilename = config.getParam("mixtureServer");
  // label for selected frames - Only the frames associated with this label, in the label files, will be used
  //bool fixedLabelSelectedFrame;
  bool initByClient=false;
  bool aprioriWorld=true;
  if (config.existsParam("initByClient")) initByClient=true;
  if (config.existsParam("aprioriClient")){
    aprioriWorld=false;
    initByClient=true;
  }
  bool saveCompleteServer=false;
  bool outputAdaptParam=false;
  if (config.existsParam("outputAdaptParam")) outputAdaptParam=config.getParam("outputAdaptParam").toBool();
  
  try{
    XList inputClientList(inputClientListFileName,config);          // read the Id + filenames for each client
    XLine *linep;
    inputClientList.getLine(0);
    MixtureServer ms(config);
    StatServer ss(config, ms);
    if (verbose) cout << "TrainTarget - by label opption - Load world model [" << inputWorldFilename<<"]"<<endl;
    MixtureGD& world = ms.loadMixtureGD(inputWorldFilename);
    // *********** Target loop ***************** 
    while ((linep=inputClientList.getLine()) != NULL){             // linep gives the XLine with the Id of a given client and the list of files
      String clientId=(*linep->getElement());                      // Get the Client ID (clientId)
      XLine featureFileListp=linep->getElements();	           // Get the list of feature file for the client (end of the line)
      FeatureServer fs(config,featureFileListp);                   // Reading the features (from several files)
      if (verbose) cout << "Train label models for client ["<<clientId<<"]"<<endl;   
      MixtureGD &clientGModel=ms.createMixtureGD();
      if (initByClient) {
          if (verbose) cout << "Load client model [" << clientId <<"]"<<endl;
          clientGModel = ms.loadMixtureGD(clientId); //not necessary to load client model
      }
      SegServer segmentsServer;                                                             // Create the segment server for managing the segments/clusters
      LabelServer labelServer;                                                              // Create the lable server, for indexing the segments/clusters
      initializeClusters(featureFileListp,segmentsServer,labelServer,config);               // Reading the segmentation files for each feature input file
      verifyClusterFile(segmentsServer,fs,config);                                          // Verify if the segments ending before the end of the feature files...
      for (unsigned long codeSelectedFrame=0;codeSelectedFrame<segmentsServer.getClusterCount();codeSelectedFrame++){ // For each cluster
	String clientIdByLabel=clientId+"_"+labelServer.getLabel(codeSelectedFrame).getString(); // Build the model name for the client and the label
	if (verbose) cout << "Train labeldependent model ["<<clientIdByLabel<<"]"<<endl;   
	SegCluster& selectedSegments=segmentsServer.getCluster(codeSelectedFrame);          // Gives the cluster of the selected/used segments
	MixtureGD & clientMixture = ms.duplicateMixture(world,DUPL_DISTRIB);       // Creating clientMixture as a copy of the world model
	ms.setMixtureId(clientMixture,clientIdByLabel);                                     // Set the client model Id
	if (initByClient)                                                                   // During trainig data statistic estimation by EM,
	  clientMixture=clientGModel;                                                       // the global client model is used for initalization
	if (aprioriWorld)                                                                   // EM algo with MAP criterion
	  adaptModel(config,ss,ms,fs,selectedSegments,world,clientMixture);          // A priori info is the world model  
	else adaptModel(config,ss,ms,fs,selectedSegments,clientGModel,clientMixture);// A priori info is the client model-by default initByClient is also set
        if (!outputAdaptParam) {
            if (verbose) cout << "Save client model ["<<clientIdByLabel<<"]" << endl;
            clientMixture.save(clientIdByLabel, config);                                           // Save the client model
        }
	if (!saveCompleteServer){
	  long tid=ms.getMixtureIndex(clientIdByLabel);      // TO BE SUPPRESSED BY
	  ms.deleteMixtures(tid,tid);            // ADDING a delete on a mixture pointor
	  ms.deleteUnusedDistribs();
	  }
      }      
      if (!saveCompleteServer){
	long tid=ms.getMixtureIndex(clientId);      // TO BE SUPPRESSED BY
	ms.deleteMixtures(tid,tid);                 // ADDING a delete on a mixture pointor
	ms.deleteUnusedDistribs();
      }                                                                   // end of the the label loop fr a speaker
    } // end of the the target loop 
    
    // Save the complete mixture server
    // TODO
  } // fin try
  

  
  catch (Exception& e)
    { 
      cout << e.toString().c_str() << endl;
    }
  return 0;
}
Пример #17
0
void
AltitudeSymbol::mergeConfig( const Config& conf )
{
    conf.getIfSet   ( "clamping",  "none",     _clamping, CLAMP_NONE );
    conf.getIfSet   ( "clamping",  "terrain",  _clamping, CLAMP_TO_TERRAIN );
    conf.getIfSet   ( "clamping",  "absolute", _clamping, CLAMP_ABSOLUTE );
    conf.getIfSet   ( "clamping",  "relative", _clamping, CLAMP_RELATIVE_TO_TERRAIN );

    conf.getIfSet   ( "technique", "map",   _technique, TECHNIQUE_MAP );
    conf.getIfSet   ( "technique", "scene", _technique, TECHNIQUE_SCENE );
    conf.getIfSet   ( "technique", "gpu",   _technique, TECHNIQUE_GPU );
    conf.getIfSet   ( "technique", "drape", _technique, TECHNIQUE_DRAPE );

    conf.getIfSet   ( "binding", "vertex",   _binding, BINDING_VERTEX );
    conf.getIfSet   ( "binding", "centroid", _binding, BINDING_CENTROID );

    conf.getIfSet   ( "clamping_resolution",   _resolution );
    conf.getObjIfSet( "vertical_offset",       _verticalOffset );
    conf.getObjIfSet( "vertical_scale",        _verticalScale );
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
int TrainTargetFA(Config& config)
{
  String inputClientListFileName = config.getParam("targetIdList");
  String inputWorldFilename = config.getParam("inputWorldFilename");
  String outputSERVERFilename = "";
  if (config.existsParam("mixtureServer")) outputSERVERFilename =config.getParam("mixtureServer");
  bool initByClient=false;                                              // In this case, the init model is read from the file
  if (config.existsParam("initByClient")) initByClient=config.getParam("initByClient").toBool();
  bool saveEmptyModel=false;
  if (config.existsParam("saveEmptyModel")) saveEmptyModel=config.getParam("saveEmptyModel").toBool();
  // label for selected frames - Only the frames associated with this label, in the label files, will be used
  bool fixedLabelSelectedFrame=true;
  String labelSelectedFrames;
  if (config.existsParam("useIdForSelectedFrame"))    // the ID of each speaker is used as labelSelectedFrame ?
    fixedLabelSelectedFrame=(config.getParam("useIdForSelectedFrame").toBool()==false);  
  if (fixedLabelSelectedFrame)                        // the label is decided by the command line and is unique for the run
    labelSelectedFrames=config.getParam("labelSelectedFrames");
  bool modelData=false;
  if (config.existsParam("useModelData")) modelData=config.getParam("useModelData").toBool();
  String initModelS=inputWorldFilename;
  if (modelData) if (config.existsParam("initModel")) initModelS=config.getParam("initModel"); // Use a specific model for Em init
  bool outputAdaptParam=false;
  if (config.existsParam("superVectors")) outputAdaptParam=true;
  Matrix <double> ChannelMatrix;
  if (verbose) cout<< "EigenMAP and Eigenchannel with [" << config.getParam("initChannelMatrix") << "] of size: ["; 
  ChannelMatrix.load(config.getParam("initChannelMatrix"),config); //get Channel Matrix from args and load in a Matrix object
  if (verbose) cout << ChannelMatrix.rows() << "," <<ChannelMatrix.cols() << "]" << endl;
  bool varAdapt=false;
  if (config.existsParam("FAVarAdapt")) varAdapt=true;
  bool saveCompleteServer=false;
 
  try{
    XList inputClientList(inputClientListFileName,config);          // read the Id + filenames for each client
    XLine * linep;
    inputClientList.getLine(0);
    MixtureServer ms(config);
    StatServer ss(config, ms);
    if (verbose) cout << "(TrainTarget) Factor Analysis - Load world model [" << inputWorldFilename<<"]"<<endl;
    MixtureGD& world = ms.loadMixtureGD(inputWorldFilename);      
    if (verbose) cout <<"(TrainTarget) Use["<<initModelS<<"] for initializing EM"<<endl;
    
    // *********** Target loop ***************** 
    while ((linep=inputClientList.getLine()) != NULL){             // linep gives the XLine with the Id of a given client and the list of files

      String *id=linep->getElement();                              // Get the Client ID (id)
      XLine featureFileListp=linep->getElements();	           // Get the list of feature file for the client (end of the line)
      if (verbose) cout << "(TrainTarget) Train model ["<<*id<<"]"<<endl;   
      FeatureServer fs(config,featureFileListp);                                            // Reading the features (from several files)
      SegServer segmentsServer;                                                             // Create the segment server for managing the segments/clusters
      LabelServer labelServer;                                                              // Create the lable server, for indexing the segments/clusters
      initializeClusters(featureFileListp,segmentsServer,labelServer,config);               // Reading the segmentation files for each feature input file
      verifyClusterFile(segmentsServer,fs,config);                                          // Verify if the segments ending before the end of the feature files...
      MixtureGD & adaptedMixture = ms.duplicateMixture(world,DUPL_DISTRIB);                 // Creating final as a copy of the world model
      MixtureGD & clientMixture= ms.duplicateMixture(world,DUPL_DISTRIB);
      long codeSelectedFrame=labelServer.getLabelIndexByString(labelSelectedFrames);        // Get the index of the cluster with in interest audio segments
      if (codeSelectedFrame==-1){                                                           // No data for this model !!!!!!!!!!!!!!
	cout << " WARNING - NO DATA FOR TRAINING ["<<*id<<"]";
	if (saveEmptyModel){
	  cout <<" World model is returned"<<endl;                                    // In this case, the client model is the world model
	  if (verbose) cout << "Save client model ["<<*id<<"]" << endl;
	  adaptedMixture.save(*id, config);                                           // Save the client model
	}
      }
      else{
	SegCluster& selectedSegments=segmentsServer.getCluster(codeSelectedFrame); // Gives the cluster of the selected/used segments                                   
        /// **** Factor Analysis Stuff
        XList faNdx;
        faNdx.addLine()=featureFileListp; 
        FactorAnalysisStat FA(faNdx,fs,config); // give all features to FA stats
        
        //FA.computeAndAccumulateGeneralFAStats(selectedSegments,fs,config);    
        for(int i=0;i<config.getParam("nbTrainIt").toLong();i++){
          if (verbose) cout << "------ Iteration ["<<i<<"] ------"<<endl;
          FA.computeAndAccumulateGeneralFAStats(selectedSegments,fs,config);                
          /*if (!varAdapt) FA.getTrueSpeakerModel(clientMixture,linep->getElement(1));
          else FA.getFactorAnalysisModel(clientMixture,linep->getElement(1));
          if (verbose) cout << "LLK for model["<<*id<<"] at it["<<i-1<<"]="<<FA.getLLK(selectedSegments,clientMixture,fs,config) << endl; */
          FA.estimateAndInverseL(config);
          FA.substractSpeakerStats();
          FA.getXEstimate();
          FA.substractChannelStats(); 
          FA.getYEstimate();    
      }      
      MixtureGD & sessionMixture= ms.duplicateMixture(world,DUPL_DISTRIB);
      bool saveSessionModel=false;
      if (config.existsParam("saveSessionModel")) saveSessionModel=true;
      if (saveSessionModel) FA.getSessionModel(sessionMixture,linep->getElement(1));
      if (!varAdapt) FA.getTrueSpeakerModel(clientMixture,linep->getElement(1)); // basically compute M_s_h=M+Dy_s and get a model
      else FA.getFactorAnalysisModel(clientMixture,linep->getElement(1)); // get FA variance adapted model
      if (verbose) cout << "Final LLK for model["<<*id<<"]="<<FA.getLLK(selectedSegments,clientMixture,fs,config) << endl;    

      /// **** End of FA
        if (!outputAdaptParam) {
            if (verbose) cout << "Save client model ["<<*id<<"]" << endl;
            clientMixture.save(*id, config);                                           // Save the client model
            if (saveSessionModel) {
              String sessionfile=*id+".session";
              if (verbose) cout << "Save session model ["<<sessionfile<<"]" << endl;              
              sessionMixture.save(sessionfile,config);   
            }              
        }
	if (!saveCompleteServer){
	  long tid=ms.getMixtureIndex(*id);      // TO BE SUPPRESSED BY
	  ms.deleteMixtures(tid,tid);            // ADDING a delete on a mixture pointor
	  ms.deleteUnusedDistribs();
	  }
      }
    }    
  } // fin try
catch (Exception& e) {cout << e.toString().c_str() << endl;}
  return 0;
}
Пример #19
0
void
VisibleLayerOptions::fromConfig(const Config& conf)
{
    conf.getIfSet( "visible", _visible );
    conf.getIfSet("opacity", _opacity);
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
int TrainTargetJFA(Config& config)
{
	String inputClientListFileName = config.getParam("targetIdList");
	String inputWorldFilename = config.getParam("inputWorldFilename");
	String outputSERVERFilename = "";
	if (config.existsParam("mixtureServer")) outputSERVERFilename =config.getParam("mixtureServer");
	bool initByClient=false;                                              // In this case, the init model is read from the file
	if (config.existsParam("initByClient")) initByClient=config.getParam("initByClient").toBool();
	bool saveEmptyModel=false;
	if (config.existsParam("saveEmptyModel")) saveEmptyModel=config.getParam("saveEmptyModel").toBool();
	// label for selected frames - Only the frames associated with this label, in the label files, will be used
	bool fixedLabelSelectedFrame=true;
	String labelSelectedFrames;
	if (config.existsParam("useIdForSelectedFrame"))    // the ID of each speaker is used as labelSelectedFrame ?
		fixedLabelSelectedFrame=(config.getParam("useIdForSelectedFrame").toBool()==false);  
	if (fixedLabelSelectedFrame)                        // the label is decided by the command line and is unique for the run
		labelSelectedFrames=config.getParam("labelSelectedFrames");
	bool modelData=false;
	if (config.existsParam("useModelData")) modelData=config.getParam("useModelData").toBool();
	String initModelS=inputWorldFilename;
	if (modelData) if (config.existsParam("initModel")) initModelS=config.getParam("initModel"); // Use a specific model for Em init
	bool outputAdaptParam=false;
	if (config.existsParam("superVectors")) outputAdaptParam=true;
 
try{
	XList inputClientList(inputClientListFileName,config);          // read the Id + filenames for each client
	XLine * linep;
	inputClientList.getLine(0);
	MixtureServer ms(config);
	StatServer ss(config, ms);
	if (verbose) cout << "(TrainTarget) Joint Factor Analysis - Load world model [" << inputWorldFilename<<"]"<<endl;
	MixtureGD& world = ms.loadMixtureGD(inputWorldFilename);      
	if (verbose) cout <<"(TrainTarget) Use["<<initModelS<<"] for initializing EM"<<endl;
	
	//LOAD JFA MAtrices
	Matrix<double> U, V; 
	DoubleVector D;
	
	//Initialise EC matrix
	if(config.existsParam("eigenChannelMatrix")){
		String uName = config.getParam("matrixFilesPath") + config.getParam("eigenChannelMatrix") + config.getParam("loadMatrixFilesExtension");
 		U.load (uName, config);
		if (verboseLevel >=1) cout << "(TrainTargetJFA) Init EC matrix from "<< config.getParam("eigenChannelMatrix") <<"  from EigenChannel Matrix: "<<", rank: ["<<U.rows() << "] sv size: [" << U.cols() <<"]"<<endl;
	}
	else{
		unsigned long sS = world.getVectSize() * world.getDistribCount();
		U.setDimensions(1,sS);
		U.setAllValues(0.0);
		if (verboseLevel >=1) cout << "(TrainTargetJFA) Init EC matrix to 0"<<endl;
	}
	
	//Initialise EV matrix
	if(config.existsParam("eigenVoiceMatrix")){
		String vName = config.getParam("matrixFilesPath") + config.getParam("eigenVoiceMatrix") + config.getParam("loadMatrixFilesExtension");
		V.load (vName, config);
		if (verboseLevel >=1) cout << "(TrainTargetJFA) Init EV matrix from "<< config.getParam("eigenVoiceMatrix") <<"  from EigenVoice Matrix: "<<", rank: ["<<V.rows() << "] sv size: [" << V.cols() <<"]"<<endl;
	}
	else{
		unsigned long sS = world.getVectSize() * world.getDistribCount();
		V.setDimensions(1,sS);
		V.setAllValues(0.0);
		if (verboseLevel >=1) cout << "(TrainTargetJFA) Init EV matrix to 0"<<endl;
	}
	
	//Initialise D matrix
	if(config.existsParam("DMatrix")){
		String dName = config.getParam("matrixFilesPath") + config.getParam("DMatrix") + config.getParam("loadMatrixFilesExtension");
		Matrix<double> tmpD(dName, config);
		
		if( (tmpD.rows() != 1) || ( tmpD.cols() != world.getVectSize()*world.getDistribCount() ) ){
			throw Exception("Incorrect dimension of D Matrix",__FILE__,__LINE__);
		}
		else{
			D.setSize(world.getVectSize()*world.getDistribCount());
			D.setAllValues(0.0);
			for(unsigned long i=0; i<world.getVectSize()*world.getDistribCount(); i++){
				D[i] = tmpD(0,i);
			}
			if (verboseLevel >=1) cout << "(TrainTargetJFA) Init D matrix from "<<config.getParam("DMatrix")<<endl;
		}
	}
	else{
		unsigned long sS = world.getVectSize() * world.getDistribCount();
		D.setSize(sS);
		D.setAllValues(0.0);
		if (verboseLevel >1) cout << "(TrainTargetJFA) Init D matrix to 0"<<endl;
	}
	
	// *********** Target loop ***************** 
	while ((linep=inputClientList.getLine()) != NULL){             	// linep gives the XLine with the Id of a given client and the list of files

		String *id=linep->getElement();                              		// Get the Client ID (id)
		XLine featureFileListp=linep->getElements();	           	// Get the list of feature file for the client (end of the line)
		if (verbose) cout << "(TrainTarget) Train model ["<<*id<<"]"<<endl;
	
		XList ndx; ndx.addLine() = featureFileListp;
		JFAAcc jfaAcc(ndx,config,"TrainTarget");

		//Load V, U and D from existing matrices.
		jfaAcc.loadEV(V, config); jfaAcc.loadEC(U, config); jfaAcc.loadD(D);  

		//Initialize VU matrix
		jfaAcc.initVU();

		FeatureServer fs(config,featureFileListp);                                            			// Reading the features (from several files)
		SegServer segmentsServer;                                                             				// Create the segment server for managing the segments/clusters
		LabelServer labelServer;                                                              				// Create the lable server, for indexing the segments/clusters
		initializeClusters(featureFileListp,segmentsServer,labelServer,config);         		// Reading the segmentation files for each feature input file
		verifyClusterFile(segmentsServer,fs,config);                                     				// Verify if the segments ending before the end of the feature files...

		MixtureGD & adaptedMixture = ms.duplicateMixture(world,DUPL_DISTRIB);                 	// Creating final as a copy of the world model
		MixtureGD & clientMixture= ms.duplicateMixture(world,DUPL_DISTRIB);
		long codeSelectedFrame=labelServer.getLabelIndexByString(labelSelectedFrames);   	// Get the index of the cluster with in interest audio segments
		if (codeSelectedFrame==-1){                                                           					// No data for this model !!!!!!!!!!!!!!
			cout << " WARNING - NO DATA FOR TRAINING ["<<*id<<"]";
			if (saveEmptyModel){
				cout <<" World model is returned"<<endl;                                    				// In this case, the client model is the world model
				if (verbose) cout << "Save client model ["<<*id<<"]" << endl;
				adaptedMixture.save(*id, config);                                           					// Save the client model
			}
		}			

		else{
			SegCluster& selectedSegments=segmentsServer.getCluster(codeSelectedFrame); // Gives the cluster of the selected/used segments                                   

			//Compute the JFA statistics
			jfaAcc.computeAndAccumulateJFAStat(selectedSegments,fs,config);

			//Estimate X and Y in one time for each speaker
			jfaAcc.storeAccs();
			jfaAcc.estimateVUEVUT(config);

			jfaAcc.estimateAndInverseL_VU(config);

			jfaAcc.substractMplusDZ(config);

			jfaAcc.estimateYX();
			//Reinitialise the accumulators
			jfaAcc.resetTmpAcc();
			jfaAcc.restoreAccs();
			
			//Split X and Y estimates
			jfaAcc.splitYX();

			//Substract speaker and channel statistics M + VUYX
			jfaAcc.substractMplusVUYX();		
			//Estimate Z for each speaker
			jfaAcc.estimateZ();
			//Reinitialise the accumulators
			jfaAcc.resetTmpAcc();
			jfaAcc.restoreAccs();

			bool varAdapt = false;
			if((config.existsParam("varAdapt")) && ( config.getParam("varAdapt").toBool() )){
				varAdapt = true;
			}

			DoubleVector clientSV(jfaAcc.getSvSize(), jfaAcc.getSvSize());
			clientSV.setSize(jfaAcc.getSvSize());
			DoubleVector clientModel(jfaAcc.getSvSize(), jfaAcc.getSvSize());
			clientModel.setSize(jfaAcc.getSvSize());

			bool saveMixture = true;
			if((config.existsParam("saveMixture")) && !( config.getParam("saveMixture").toBool() ))	saveMixture = false;
			bool saveSuperVector = true;
			if((config.existsParam("saveSuperVector")) && !( config.getParam("saveSuperVector").toBool() ))	saveSuperVector = false;
			bool saveX = false;
			bool saveY = false;
			bool saveZ = false;


			if(config.existsParam("saveX"))			saveX = config.getParam("saveX").toBool();
			if(config.existsParam("saveY"))			saveY = config.getParam("saveY").toBool();
			if(config.existsParam("saveZ"))			saveZ = config.getParam("saveZ").toBool();
			String xExtension = ".x"; String yExtension = ".y"; String zExtension = ".z";
			if(config.existsParam("xExtension"))	xExtension = config.getParam("xExtension");
			if(config.existsParam("yExtension"))	yExtension = config.getParam("yExtension");
			if(config.existsParam("zExtension"))	zExtension = config.getParam("zExtension");

			jfaAcc.getVYplusDZ(clientSV, 0);
			jfaAcc.getMplusVYplusDZ(clientModel, 0);
			
			//WARNING !!!!! only the SuperVector model is divided by the UBM Co-Variance.
			for(unsigned long i=0; i<jfaAcc.getSvSize(); i++){
				clientSV[i] *= jfaAcc.getUbmInvVar()[i];
			}
			
			//Create the ClientMixture to save if required
			if(saveMixture){
				svToModel(clientModel, clientMixture);
				clientMixture.save(*id, config);
			}
			String svPath,svExt,svFile;

			if(saveSuperVector){
				String svPath =config.getParam("saveVectorFilesPath");
				String svExt =config.getParam("vectorFilesExtension"); 
				String svFile =svPath+*id+svExt; 
				((Matrix<double>)clientSV).save(svFile,config);   
			}

//			String svPath=config.getParam("saveVectorFilesPath");

			if(saveX){
				String xFile=svPath+*id+xExtension;
				jfaAcc.saveX(xFile,config);
			}
			if(saveY){
				String yFile=svPath+*id+yExtension;
				jfaAcc.saveY(yFile,config);
			}
			if(saveZ){
				String zFile=svPath+*id+zExtension;
				jfaAcc.saveZ(zFile,config);
			}

			long tid=ms.getMixtureIndex(*id);
			ms.deleteMixtures(tid,tid);
			ms.deleteUnusedDistribs();
		}
	}
} // fin try
catch (Exception& e) {cout << e.toString().c_str() << endl;}
return 0;
}
Пример #21
0
Config
FeatureModelSourceOptions::getConfig() const
{
    Config conf = ModelSourceOptions::getConfig();

    conf.updateObjIfSet( "features", _featureOptions );    
    if (_featureSource.valid())
    {
        conf.addNonSerializable("feature_source", _featureSource);
    }
    //conf.updateObjIfSet( "feature_source", _featureSource);
    conf.updateObjIfSet( "gridding", _gridding ); // to be deprecated
    conf.updateObjIfSet( "styles", _styles );
    conf.updateObjIfSet( "layout", _levels );

    conf.updateIfSet( "lighting", _lit );
    conf.updateIfSet( "max_granularity", _maxGranularity_deg );
    conf.updateIfSet( "merge_geometry", _mergeGeometry );
    conf.updateIfSet( "cluster_culling", _clusterCulling );


    if ( _geomTypeOverride.isSet() ) {
        if ( _geomTypeOverride == Geometry::TYPE_LINESTRING )
            conf.update( "geometry_type", "line" );
        else if ( _geomTypeOverride == Geometry::TYPE_POINTSET )
            conf.update( "geometry_type", "point" );
        else if ( _geomTypeOverride == Geometry::TYPE_POLYGON )
            conf.update( "geometry_type", "polygon" );
    }

    return conf;
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
int TrainTargetLFA(Config& config)
{
	String inputClientListFileName = config.getParam("targetIdList");
	String inputWorldFilename = config.getParam("inputWorldFilename");
	String outputSERVERFilename = "";
	if (config.existsParam("mixtureServer")) outputSERVERFilename =config.getParam("mixtureServer");
	bool initByClient=false;                                              // In this case, the init model is read from the file
	if (config.existsParam("initByClient")) initByClient=config.getParam("initByClient").toBool();
	bool saveEmptyModel=false;
	if (config.existsParam("saveEmptyModel")) saveEmptyModel=config.getParam("saveEmptyModel").toBool();
	// label for selected frames - Only the frames associated with this label, in the label files, will be used
	bool fixedLabelSelectedFrame=true;
	String labelSelectedFrames;
	if (config.existsParam("useIdForSelectedFrame"))    // the ID of each speaker is used as labelSelectedFrame ?
		fixedLabelSelectedFrame=(config.getParam("useIdForSelectedFrame").toBool()==false);  
	if (fixedLabelSelectedFrame)                        // the label is decided by the command line and is unique for the run
		labelSelectedFrames=config.getParam("labelSelectedFrames");
	bool modelData=false;
	if (config.existsParam("useModelData")) modelData=config.getParam("useModelData").toBool();
	String initModelS=inputWorldFilename;
	if (modelData) if (config.existsParam("initModel")) initModelS=config.getParam("initModel"); // Use a specific model for Em init
	bool outputAdaptParam=false;
	if (config.existsParam("superVectors")) outputAdaptParam=true;
 
try{
	XList inputClientList(inputClientListFileName,config);          // read the Id + filenames for each client
	XLine * linep;
	inputClientList.getLine(0);
	MixtureServer ms(config);
	StatServer ss(config, ms);
	if (verbose) cout << "(TrainTarget) Latent Factor Analysis - Load world model [" << inputWorldFilename<<"]"<<endl;
	MixtureGD& world = ms.loadMixtureGD(inputWorldFilename);      
	if (verbose) cout <<"(TrainTarget) Use["<<initModelS<<"] for initializing EM"<<endl;
	
	//LOAD JFA MAtrices
	unsigned long svsize=world.getDistribCount()*world.getVectSize();
	Matrix<double> U, V; 
	DoubleVector D(svsize,svsize);
	
	//Initialise EC matrix
	if(config.existsParam("eigenChannelMatrix")){
		String uName = config.getParam("matrixFilesPath") + config.getParam("eigenChannelMatrix") + config.getParam("loadMatrixFilesExtension");
 		U.load (uName, config);
		if (verboseLevel >=1) cout << "(TrainTargetLFA) Init EC matrix from "<< config.getParam("eigenChannelMatrix") <<"  from EigenChannel Matrix: "<<", rank: ["<<U.rows() << "] sv size: [" << U.cols() <<"]"<<endl;
	}
	else{
		U.setDimensions(1,svsize);
		U.setAllValues(0.0);
		if (verboseLevel >1) cout << "(TrainTargetLFA) Init EC matrix to 0"<<endl;
	}
	
	V.setDimensions(1,svsize);
	V.setAllValues(0.0);
	if (verboseLevel >=1) cout << "(TrainTargetLFA) Init EV matrix to 0"<<endl;

	//Initialise the D matrix for MAP adaptation
	for(unsigned long i=0; i<world.getDistribCount(); i++){
		for(unsigned long j = 0; j<world.getVectSize(); j++){
			D[i*world.getVectSize()+j] = sqrt(1.0/(world.getDistrib(i).getCovInv(j)*config.getParam("regulationFactor").toDouble()));
		}
	}

	// *********** Target loop ***************** 
	while ((linep=inputClientList.getLine()) != NULL){             	// linep gives the XLine with the Id of a given client and the list of files

		String *id=linep->getElement();                              		// Get the Client ID (id)
		XLine featureFileListp=linep->getElements();	           	// Get the list of feature file for the client (end of the line)
		if (verbose) cout << "(TrainTargetLFA) Train model ["<<*id<<"]"<<endl;
	
		XList ndx; ndx.addLine() = featureFileListp;
		JFAAcc jfaAcc(ndx,config,"TrainTarget");
		
		//Charger les matrices V, U et D a partir des objets matrice existant.
		jfaAcc.loadEV(V, config); jfaAcc.loadEC(U, config); jfaAcc.loadD(D);  

		//Initialise VU matrix
		jfaAcc.initVU();

		FeatureServer fs(config,featureFileListp);											// Reading the features (from several files)
		SegServer segmentsServer;															// Create the segment server for managing the segments/clusters
		LabelServer labelServer;															// Create the lable server, for indexing the segments/clusters
		initializeClusters(featureFileListp,segmentsServer,labelServer,config);				// Reading the segmentation files for each feature input file
		verifyClusterFile(segmentsServer,fs,config);                                     	// Verify if the segments ending before the end of the feature files...

		MixtureGD & adaptedMixture = ms.duplicateMixture(world,DUPL_DISTRIB);               // Creating final as a copy of the world model
		MixtureGD & clientMixture= ms.duplicateMixture(world,DUPL_DISTRIB);
		long codeSelectedFrame=labelServer.getLabelIndexByString(labelSelectedFrames);   	// Get the index of the cluster with in interest audio segments
		if (codeSelectedFrame==-1){                                                         	// No data for this model !!!!!!!!!!!!!!
			cout << " WARNING - NO DATA FOR TRAINING ["<<*id<<"]";
			if (saveEmptyModel){
				cout <<" World model is returned"<<endl;                                    // In this case, the client model is the world model
				if (verbose) cout << "Save client model ["<<*id<<"]" << endl;
				adaptedMixture.save(*id, config);                                           // Save the client model
			}
		}			

		else{
			SegCluster& selectedSegments=segmentsServer.getCluster(codeSelectedFrame); // Gives the cluster of the selected/used segments                                   

			//Compute the JFA statistics
			jfaAcc.computeAndAccumulateJFAStat(selectedSegments,fs,config);

			//Estimate X and Y in one time for each speaker
			jfaAcc.storeAccs();
			jfaAcc.estimateVUEVUT(config);
			jfaAcc.estimateAndInverseL_VU(config);
			jfaAcc.substractMplusDZ(config);
			jfaAcc.estimateYX();
			//Reinitialise the accumulators
			jfaAcc.resetTmpAcc();
			jfaAcc.restoreAccs();
			
			//Split X and Y estimates
			jfaAcc.splitYX();

			//Substract speaker and channel statistics M + VUYX
			jfaAcc.substractMplusVUYX();		
			//Estimate Z for each speaker
			double tau = config.getParam("regulationFactor").toLong();
			jfaAcc.estimateZMAP(tau);
			//Reinitialise the accumulators
			jfaAcc.resetTmpAcc();
			jfaAcc.restoreAccs();

			bool varAdapt = false;
			if((config.existsParam("varAdapt")) && ( config.getParam("varAdapt").toBool() )){
				varAdapt = true;
			}

			DoubleVector clientModel(jfaAcc.getSvSize(), jfaAcc.getSvSize());
			clientModel.setSize(jfaAcc.getSvSize());

			jfaAcc.getMplusVYplusDZ(clientModel, 0);
			
			//Create the ClientMixture
			svToModel(clientModel, clientMixture);
			clientMixture.save(*id, config);

			long tid=ms.getMixtureIndex(*id);
			ms.deleteMixtures(tid,tid);
			ms.deleteUnusedDistribs();
		}
	}
} // fin try
catch (Exception& e) {cout << e.toString().c_str() << endl;}
return 0;
}
Пример #23
0
Config
TerrainLayerOptions::getConfig( bool isolate ) const
{
    Config conf = isolate ? ConfigOptions::newConfig() : ConfigOptions::getConfig();

    conf.set("name", _name);
    conf.updateIfSet( "min_level", _minLevel );
    conf.updateIfSet( "max_level", _maxLevel );
    conf.updateIfSet( "min_resolution", _minResolution );
    conf.updateIfSet( "max_resolution", _maxResolution );
    conf.updateIfSet( "loading_weight", _loadingWeight );
    conf.updateIfSet( "enabled", _enabled );
    conf.updateIfSet( "visible", _visible );
    conf.updateIfSet( "edge_buffer_ratio", _edgeBufferRatio);    
    conf.updateIfSet( "reprojected_tilesize", _reprojectedTileSize);

    conf.updateIfSet( "vdatum", _vertDatum );

    conf.updateIfSet   ( "cacheid",      _cacheId );
    conf.updateIfSet   ( "cache_format", _cacheFormat );
    conf.updateObjIfSet( "cache_policy", _cachePolicy );
    conf.updateObjIfSet( "proxy",        _proxySettings );

    // Merge the TileSource options
    if ( !isolate && driver().isSet() )
        conf.merge( driver()->getConfig() );

    return conf;
}
// Training of client Speakers
// Input: Xlist	Format: ID_Client Seg1 Seg2 ..
// Output: ALIZE_MixtureServer (binaire) + GMM / Client (binary)
 int TrainTarget(Config& config)
{
  String inputClientListFileName = config.getParam("targetIdList");
  String inputWorldFilename = config.getParam("inputWorldFilename");
  String outputSERVERFilename = "";
  if (config.existsParam("mixtureServer")) outputSERVERFilename =config.getParam("mixtureServer");
  bool initByClient=false;                                              // In this case, the init model is read from the file
  if (config.existsParam("initByClient")) initByClient=config.getParam("initByClient").toBool();
  bool saveEmptyModel=false;
  if (config.existsParam("saveEmptyModel")) saveEmptyModel=config.getParam("saveEmptyModel").toBool();
  // label for selected frames - Only the frames associated with this label, in the label files, will be used
  bool fixedLabelSelectedFrame=true;
  String labelSelectedFrames;
  if (config.existsParam("useIdForSelectedFrame"))    // the ID of each speaker is used as labelSelectedFrame ?
    fixedLabelSelectedFrame=(config.getParam("useIdForSelectedFrame").toBool()==false);  
  if (fixedLabelSelectedFrame)                        // the label is decided by the command line and is unique for the run
    labelSelectedFrames=config.getParam("labelSelectedFrames");
  bool modelData=false;
  if (config.existsParam("useModelData")) modelData=config.getParam("useModelData").toBool();
  String initModelS=inputWorldFilename;
  if (modelData) if (config.existsParam("initModel")) initModelS=config.getParam("initModel"); // Use a specific model for Em init
  bool outputAdaptParam=false;
   if (config.existsParam("superVector")) outputAdaptParam=true;
  bool NAP=false;
  Matrix <double> ChannelMatrix;
  if (config.existsParam("NAP")) {
     if (verbose) cout<< "Removing channel effect with NAP from " << config.getParam("NAP") << " of size: ["; 
    NAP=true; // enable NAP
    ChannelMatrix.load(config.getParam("NAP"),config); //get Channel Matrix from args and load in a Matrix object
     if (verbose) cout << ChannelMatrix.rows() << "," <<ChannelMatrix.cols() << "]" << endl;
    }
    

  bool saveCompleteServer=false;
 
  try{
    XList inputClientList(inputClientListFileName,config);          // read the Id + filenames for each client
    XLine * linep;
    inputClientList.getLine(0);
    MixtureServer ms(config);
    StatServer ss(config, ms);
    if (verbose) cout << "TrainTarget - Load world model [" << inputWorldFilename<<"]"<<endl;
    MixtureGD& world = ms.loadMixtureGD(inputWorldFilename);
    MixtureGD& initModel =ms.loadMixtureGD(initModelS);
   
    if (verbose) cout <<"Use["<<initModelS<<"] for initializing EM"<<endl;
    
    // *********** Target loop ***************** 
    while ((linep=inputClientList.getLine()) != NULL){             // linep gives the XLine with the Id of a given client and the list of files
      String *id=linep->getElement();                              // Get the Client ID (id)
      XLine featureFileListp=linep->getElements();	           // Get the list of feature file for the client (end of the line)
      if (verbose) cout << "Train model ["<<*id<<"]"<<endl;   
      if (!fixedLabelSelectedFrame){                                // the ID is used as label for selecting the frame
	labelSelectedFrames=*id;
	if (verbose) cout <<*id<<" is used for label selected frames"<<endl;
      }
      FeatureServer fs(config,featureFileListp);                                            // Reading the features (from several files)
      SegServer segmentsServer;                                                             // Create the segment server for managing the segments/clusters
      LabelServer labelServer;                                                              // Create the lable server, for indexing the segments/clusters
      initializeClusters(featureFileListp,segmentsServer,labelServer,config);               // Reading the segmentation files for each feature input file
      verifyClusterFile(segmentsServer,fs,config);                                          // Verify if the segments ending before the end of the feature files...
      MixtureGD & adaptedMixture = ms.duplicateMixture(world,DUPL_DISTRIB);                 // Creating final as a copy of the world model
      MixtureGD & clientMixture= ms.duplicateMixture(world,DUPL_DISTRIB);
      if (initByClient){                                                                   // During trainig data statistic estimation by EM,
	clientMixture= ms.loadMixtureGD(*id);                                               // the client model is used for initalization
	adaptedMixture=clientMixture;
      }
      long codeSelectedFrame=labelServer.getLabelIndexByString(labelSelectedFrames);        // Get the index of the cluster with in interest audio segments
      if (codeSelectedFrame==-1){                                                           // No data for this model !!!!!!!!!!!!!!
	cout << " WARNING - NO DATA FOR TRAINING ["<<*id<<"]";
	if (saveEmptyModel){
	  cout <<" World model is returned"<<endl;                                    // In this case, the client model is the world model
	  if (verbose) cout << "Save client model ["<<*id<<"]" << endl;
	  adaptedMixture.save(*id, config);                                           // Save the client model
	}
      }
      else{
	SegCluster& selectedSegments=segmentsServer.getCluster(codeSelectedFrame); // Gives the cluster of the selected/used segments                                   
	if (!initByClient) ms.setMixtureId(clientMixture,*id);                                        // Set the client model Id
	if (modelData) modelBasedadaptModel(config,ss,ms,fs,selectedSegments,world,clientMixture,initModel);          // EM algo with MAP criterion
	else adaptModel(config,ss,ms,fs,selectedSegments,world,clientMixture);          // EM algo with MAP criterion
        if (NAP) {
          if (verbose) cout << "NAP on SVs" << endl;
          computeNap(clientMixture,ChannelMatrix);
        }
        if (outputAdaptParam) {
            RealVector<double> v;
            getSuperVector(v,world,clientMixture,config);   
           String out=config.getParam("saveVectorFilesPath")+*id+config.getParam("vectorFilesExtension");        
            Matrix <double> vv=(Matrix<double>)v;
            vv.save(out,config);     
          }
        if (!outputAdaptParam) {
            if (verbose) cout << "Save client model ["<<*id<<"]" << endl;
            clientMixture.save(*id, config);                                           // Save the client model
        }
	if (!saveCompleteServer){
	  long tid=ms.getMixtureIndex(*id);      // TO BE SUPPRESSED BY
	  ms.deleteMixtures(tid,tid);            // ADDING a delete on a mixture pointor
	  ms.deleteUnusedDistribs();
	  }
      }
    }                                                                              // end of the the target loop 
    
    // Save the complete mixture server
    // TODO
  } // fin try
   


  catch (Exception& e)
    { 
      cout << e.toString().c_str() << endl;
    }
  return 0;
}
Пример #25
0
void writeHLASection(std::ostream& out, Config& config)
{
    out << "# HLA" << std::endl;
    out << config.getParameter("VRLINK") << std::endl;
    out << config.getParameter("VRLINK-PROTOCOL") << std::endl;

    out << config.getParameter("VRLINK-FEDERATION-NAME") << std::endl;
    out << config.getParameter("VRLINK-FED-FILE-PATH") << std::endl;
    out << config.getParameter("VRLINK-FEDERATE-NAME") << std::endl;
    out << config.getParameter("VRLINK-RPR-FOM-VERSION") << std::endl;

    out << config.getParameter("VRLINK-ENTITIES-FILE-PATH") << std::endl;
    out << config.getParameter("VRLINK-RADIOS-FILE-PATH") << std::endl;
    out << config.getParameter("VRLINK-NETWORKS-FILE-PATH") << std::endl;

    out << config.getParameter("VRLINK-DEBUG") << std::endl;
    out << config.getParameter("VRLINK-DEBUG-2") << std::endl;
    out << config.getParameter("VRLINK-TICK-INTERVAL") << std::endl;
    out << config.getParameter("VRLINK-XYZ-EPSILON") << std::endl;
    out << config.getParameter("VRLINK-MOBILITY-INTERVAL") << std::endl;
    out << config.getParameter("VRLINK-HLA-DYNAMIC-STATISTICS") << std::endl;
    out << config.getParameter(
        "VRLINK-HLA-DYNAMIC-STATISTICS-METRIC-UPDATE-MODE") << std::endl;
    out << config.getParameter(
        "VRLINK-HLA-DYNAMIC-STATISTICS-SEND-NODEID-DESCRIPTIONS")<<std::endl;
    out << config.getParameter(
        "VRLINK-HLA-DYNAMIC-STATISTICS-SEND-METRIC-DEFINITIONS") <<std::endl;

    out << std::endl;
}
Пример #26
0
static void InitSystem(Config& config) {
    unordered_map<string, string> parentMap; //child -> parent
    unordered_map<string, vector<string>> childMap; //parent -> children (a parent may have multiple children, they are ordered by appearance in the file)

    //If a network file is specificied, build a Network
    string networkFile = config.get<const char*>("sys.networkFile", "");
    Network* network = (networkFile != "")? new Network(networkFile.c_str()) : NULL;

    //Build the caches
    vector<const char*> cacheGroupNames;
    config.subgroups("sys.caches", cacheGroupNames);
    string prefix = "sys.caches.";

    for (const char* grp : cacheGroupNames) {
        string group(grp);
        if (group == "mem") panic("'mem' is an invalid cache group name");
        if (parentMap.count(group)) panic("Duplicate cache group %s", (prefix + group).c_str());
        string parent = config.get<const char*>(prefix + group + ".parent");
        parentMap[group] = parent;
        if (!childMap.count(parent)) childMap[parent] = vector<string>();
        childMap[parent].push_back(group);
    }

    //Check that all parents are valid: Either another cache, or "mem"
    for (const char* grp : cacheGroupNames) {
        string group(grp);
        string parent = parentMap[group];
        if (parent != "mem" && !parentMap.count(parent)) panic("%s has invalid parent %s", (prefix + group).c_str(), parent.c_str());
    }

    //Get the (single) LLC
    if (!childMap.count("mem")) panic("One cache must have mem as parent, none found");
    if (childMap["mem"].size() != 1) panic("One cache must have mem as parent, multiple found");
    string llc = childMap["mem"][0];

    //Build each of the groups, starting with the LLC
    unordered_map<string, CacheGroup*> cMap;
    list<string> fringe; //FIFO
    fringe.push_back(llc);
    while (!fringe.empty()) {
        string group = fringe.front();
        fringe.pop_front();

        bool isTerminal = (childMap.count(group) == 0); //if no children, connected to cores
        if (cMap.count(group)) panic("The cache 'tree' has a loop at %s", group.c_str());
        cMap[group] = BuildCacheGroup(config, group, isTerminal);
        if (!isTerminal) for (string child : childMap[group]) fringe.push_back(child);
    }

    //Check single LLC
    if (cMap[llc]->size() != 1) panic("Last-level cache %s must have caches = 1, but %ld were specified", llc.c_str(), cMap[llc]->size());

    /* Since we have checked for no loops, parent is mandatory, and all parents are checked valid,
     * it follows that we have a fully connected tree finishing at the LLC.
     */

    //Build the memory controllers
    uint32_t memControllers = config.get<uint32_t>("sys.mem.controllers", 1);
    assert(memControllers > 0);

    g_vector<MemObject*> mems;
    mems.resize(memControllers);
    zinfo->numMemoryControllers = memControllers;
    zinfo->hasNVMain = (config.get<const char*>("sys.mem.type", "Simple") == string("NVMain")) ? true : false;
    zinfo->hasDRAMCache = config.get<bool>("sys.mem.hasDRAMCache", false);

    for (uint32_t i = 0; i < memControllers; i++) {
        stringstream ss;
        ss << "mem-" << i;
        g_string name(ss.str().c_str());
        //uint32_t domain = nextDomain(); //i*zinfo->numDomains/memControllers;
        uint32_t domain = i*zinfo->numDomains/memControllers;
        mems[i] = BuildMemoryController(config, zinfo->lineSize, zinfo->freqMHz, domain, name);
    }

    zinfo->memoryControllers = mems;

    if (memControllers > 1) {
        bool splitAddrs = config.get<bool>("sys.mem.splitAddrs", true);
        if (splitAddrs) {
            MemObject* splitter = new SplitAddrMemory(mems, "mem-splitter");
            mems.resize(1);
            mems[0] = splitter;
        }
    }

    //Connect everything

    // mem to llc is a bit special, only one llc
    uint32_t childId = 0;
    for (BaseCache* llcBank : (*cMap[llc])[0]) {
        llcBank->setParents(childId++, mems, network);
    }

    // Rest of caches
    for (const char* grp : cacheGroupNames) {
        if (childMap.count(grp) == 0) continue; //skip terminal caches

        CacheGroup& parentCaches = *cMap[grp];
        uint32_t parents = parentCaches.size();
        assert(parents);

        //Concatenation of all child caches
        CacheGroup childCaches;
        for (string child : childMap[grp]) childCaches.insert(childCaches.end(), cMap[child]->begin(), cMap[child]->end());

        uint32_t children = childCaches.size();
        assert(children);

        uint32_t childrenPerParent = children/parents;
        if (children % parents != 0) {
            panic("%s has %d caches and %d children, they are non-divisible. "
                    "Use multiple groups for non-homogeneous children per parent!", grp, parents, children);
        }

        //HACK FIXME: This solves the L1I+D-L2 connection bug, but it's not very clear.
        //A long-term solution is to specify whether the children should be interleaved or concatenated.
        bool terminalChildren = true;
        for (string child : childMap[grp]) terminalChildren &= (childMap.count(child) == 0 || config.get<bool>("sys.caches." + child + ".isPrefetcher", false));
        if (terminalChildren) {
            info("%s's children are all terminal OR PREFETCHERS, interleaving them", grp);
            CacheGroup tmp(childCaches);
            uint32_t stride = children/childrenPerParent;
            for (uint32_t i = 0; i < children; i++) childCaches[i] = tmp[(i % childrenPerParent)*stride + i/childrenPerParent];
        }

        for (uint32_t p = 0; p < parents; p++) {
            g_vector<MemObject*> parentsVec;
            parentsVec.insert(parentsVec.end(), parentCaches[p].begin(), parentCaches[p].end()); //BaseCache* to MemObject* is a safe cast

            uint32_t childId = 0;
            g_vector<BaseCache*> childrenVec;
            for (uint32_t c = p*childrenPerParent; c < (p+1)*childrenPerParent; c++) {
                for (BaseCache* bank : childCaches[c]) {
                    bank->setParents(childId++, parentsVec, network);
                    childrenVec.push_back(bank);
                }
            }

            for (BaseCache* bank : parentCaches[p]) {
                bank->setChildren(childrenVec, network);
            }
        }
    }

    //Check that all the terminal caches have a single bank
    for (const char* grp : cacheGroupNames) {
        if (childMap.count(grp) == 0) {
            uint32_t banks = (*cMap[grp])[0].size();
            if (banks != 1) panic("Terminal cache group %s needs to have a single bank, has %d", grp, banks);
        }
    }

    //Tracks how many terminal caches have been allocated to cores
    unordered_map<string, uint32_t> assignedCaches;
    for (const char* grp : cacheGroupNames) if (childMap.count(grp) == 0) assignedCaches[grp] = 0;

    //Instantiate the cores
    vector<const char*> coreGroupNames;
    unordered_map <string, vector<Core*>> coreMap;

    config.subgroups("sys.cores", coreGroupNames);

    uint32_t coreIdx = 0;
    for (const char* group : coreGroupNames) {
        if (parentMap.count(group)) panic("Core group name %s is invalid, a cache group already has that name", group);

        coreMap[group] = vector<Core*>();

        string prefix = string("sys.cores.") + group + ".";
        uint32_t cores = config.get<uint32_t>(prefix + "cores", 1);
        string type = config.get<const char*>(prefix + "type", "Simple");

        //Build the core group
        union {
            SimpleCore* simpleCores;
            TimingCore* timingCores;
            OOOCore* oooCores;
            NullCore* nullCores;
        };
        if (type == "Simple") {
            simpleCores = gm_memalign<SimpleCore>(CACHE_LINE_BYTES, cores);
        } else if (type == "Timing") {
            timingCores = gm_memalign<TimingCore>(CACHE_LINE_BYTES, cores);
        } else if (type == "OOO") {
            oooCores = gm_memalign<OOOCore>(CACHE_LINE_BYTES, cores);
            zinfo->oooDecode = true; //enable uop decoding, this is false by default, must be true if even one OOO cpu is in the system
        } else if (type == "Null") {
            nullCores = gm_memalign<NullCore>(CACHE_LINE_BYTES, cores);
        } else {
            panic("%s: Invalid core type %s", group, type.c_str());
        }

        if (type != "Null") {
            string icache = config.get<const char*>(prefix + "icache");
            string dcache = config.get<const char*>(prefix + "dcache");

            if (!assignedCaches.count(icache)) panic("%s: Invalid icache parameter %s", group, icache.c_str());
            if (!assignedCaches.count(dcache)) panic("%s: Invalid dcache parameter %s", group, dcache.c_str());

            for (uint32_t j = 0; j < cores; j++) {
                stringstream ss;
                ss << group << "-" << j;
                g_string name(ss.str().c_str());
                Core* core;

                //Get the caches
                CacheGroup& igroup = *cMap[icache];
                CacheGroup& dgroup = *cMap[dcache];

                if (assignedCaches[icache] >= igroup.size()) {
                    panic("%s: icache group %s (%ld caches) is fully used, can't connect more cores to it", name.c_str(), icache.c_str(), igroup.size());
                }
                FilterCache* ic = dynamic_cast<FilterCache*>(igroup[assignedCaches[icache]][0]);
                assert(ic);
                ic->setSourceId(coreIdx);
                ic->setFlags(MemReq::IFETCH | MemReq::NOEXCL);
                assignedCaches[icache]++;

                if (assignedCaches[dcache] >= dgroup.size()) {
                    panic("%s: dcache group %s (%ld caches) is fully used, can't connect more cores to it", name.c_str(), dcache.c_str(), dgroup.size());
                }
                FilterCache* dc = dynamic_cast<FilterCache*>(dgroup[assignedCaches[dcache]][0]);
                assert(dc);
                dc->setSourceId(coreIdx);
                assignedCaches[dcache]++;

                //Build the core
                if (type == "Simple") {
                    core = new (&simpleCores[j]) SimpleCore(ic, dc, name);
                } else if (type == "Timing") {
                    uint32_t domain = j*zinfo->numDomains/cores;
                    TimingCore* tcore = new (&timingCores[j]) TimingCore(ic, dc, domain, name);
                    zinfo->eventRecorders[coreIdx] = tcore->getEventRecorder();
                    zinfo->eventRecorders[coreIdx]->setSourceId(coreIdx);
                    core = tcore;
                } else {
                    assert(type == "OOO");
                    OOOCore* ocore = new (&oooCores[j]) OOOCore(ic, dc, name, j);
                    zinfo->eventRecorders[coreIdx] = ocore->getEventRecorder();
                    zinfo->eventRecorders[coreIdx]->setSourceId(coreIdx);
                    core = ocore;
                }
                coreMap[group].push_back(core);
                coreIdx++;
            }
        } else {
            assert(type == "Null");
            for (uint32_t j = 0; j < cores; j++) {
                stringstream ss;
                ss << group << "-" << j;
                g_string name(ss.str().c_str());
                Core* core = new (&nullCores[j]) NullCore(name);
                coreMap[group].push_back(core);
                coreIdx++;
            }
        }
    }

    //Check that all the terminal caches are fully connected
    for (const char* grp : cacheGroupNames) {
        if (childMap.count(grp) == 0 && assignedCaches[grp] != cMap[grp]->size()) {
            panic("%s: Terminal cache group not fully connected, %ld caches, %d assigned", grp, cMap[grp]->size(), assignedCaches[grp]);
        }
    }

    //Populate global core info
    assert(zinfo->numCores == coreIdx);
    zinfo->cores = gm_memalign<Core*>(CACHE_LINE_BYTES, zinfo->numCores);
    coreIdx = 0;
    for (const char* group : coreGroupNames) for (Core* core : coreMap[group]) zinfo->cores[coreIdx++] = core;

    //Init stats: cores, caches, mem
    for (const char* group : coreGroupNames) {
        AggregateStat* groupStat = new AggregateStat(true);
        groupStat->init(gm_strdup(group), "Core stats");
        for (Core* core : coreMap[group]) core->initStats(groupStat);
        zinfo->rootStat->append(groupStat);
    }

    for (const char* group : cacheGroupNames) {
        AggregateStat* groupStat = new AggregateStat(true);
        groupStat->init(gm_strdup(group), "Cache stats");
        for (vector<BaseCache*>& banks : *cMap[group]) for (BaseCache* bank : banks) bank->initStats(groupStat);
        zinfo->rootStat->append(groupStat);
    }

    //Initialize event recorders
    //for (uint32_t i = 0; i < zinfo->numCores; i++) eventRecorders[i] = new EventRecorder();

    AggregateStat* memStat = new AggregateStat(true);
    memStat->init("mem", "Memory controller stats");
    for (auto mem : mems) mem->initStats(memStat);
    zinfo->rootStat->append(memStat);

    //Odds and ends: BuildCacheGroup new'd the cache groups, we need to delete them
    for (pair<string, CacheGroup*> kv : cMap) delete kv.second;
    cMap.clear();

    info("Initialized system");
}
Пример #27
0
// ---------------------------------------------------------
void ResourceAudio::Save(Config & config) const
{
	Resource::Save(config);
	config.AddInt("Format", format);
}
Пример #28
0
void SimInit(const char* configFile, const char* outputDir, uint32_t shmid) {
    zinfo = gm_calloc<GlobSimInfo>();
    zinfo->outputDir = gm_strdup(outputDir);

    Config config(configFile);

    //Debugging
    //NOTE: This should be as early as possible, so that we can attach to the debugger before initialization.
    zinfo->attachDebugger = config.get<bool>("sim.attachDebugger", false);
    zinfo->harnessPid = getppid();
    getLibzsimAddrs(&zinfo->libzsimAddrs);

    if (zinfo->attachDebugger) {
        gm_set_secondary_ptr(&zinfo->libzsimAddrs);
        notifyHarnessForDebugger(zinfo->harnessPid);
    }

    PreInitStats();

    //Get the number of cores
    //TODO: There is some duplication with the core creation code. This should be fixed eventually.
    uint32_t numCores = 0;
    vector<const char*> groups;
    config.subgroups("sys.cores", groups);
    for (const char* group : groups) {
        uint32_t cores = config.get<uint32_t>(string("sys.cores.") + group + ".cores", 1);
        numCores += cores;
    }

    if (numCores == 0) panic("Config must define some core classes in sys.cores; sys.numCores is deprecated");
    zinfo->numCores = numCores;
    assert(numCores <= MAX_THREADS); //TODO: Is there any reason for this limit?

    zinfo->numDomains = config.get<uint32_t>("sim.domains", 1);
    uint32_t numSimThreads = config.get<uint32_t>("sim.contentionThreads", MAX((uint32_t)1, zinfo->numDomains/2)); //gives a bit of parallelism, TODO tune
    zinfo->contentionSim = new ContentionSim(zinfo->numDomains, numSimThreads);
    zinfo->contentionSim->initStats(zinfo->rootStat);
    zinfo->eventRecorders = gm_calloc<EventRecorder*>(numCores);

    // Global simulation values
    zinfo->numPhases = 0;

    zinfo->phaseLength = config.get<uint32_t>("sim.phaseLength", 10000);
    zinfo->statsPhaseInterval = config.get<uint32_t>("sim.statsPhaseInterval", 100);
    zinfo->freqMHz = config.get<uint32_t>("sys.frequency", 2000);

    //Maxima/termination conditions
    zinfo->maxPhases = config.get<uint64_t>("sim.maxPhases", 0);
    zinfo->maxMinInstrs = config.get<uint64_t>("sim.maxMinInstrs", 0);
    zinfo->maxTotalInstrs = config.get<uint64_t>("sim.maxTotalInstrs", 0);

    uint64_t maxSimTime = config.get<uint32_t>("sim.maxSimTime", 0);
    zinfo->maxSimTimeNs = maxSimTime*1000L*1000L*1000L;

    zinfo->maxProcEventualDumps = config.get<uint32_t>("sim.maxProcEventualDumps", 0);
    zinfo->procEventualDumps = 0;

    zinfo->skipStatsVectors = config.get<bool>("sim.skipStatsVectors", false);
    zinfo->compactPeriodicStats = config.get<bool>("sim.compactPeriodicStats", false);

    //Fast-forwarding and magic ops
    zinfo->ignoreHooks = config.get<bool>("sim.ignoreHooks", false);
    zinfo->ffReinstrument = config.get<bool>("sim.ffReinstrument", false);
    if (zinfo->ffReinstrument) warn("sim.ffReinstrument = true, switching fast-forwarding on a multi-threaded process may be unstable");

    zinfo->registerThreads = config.get<bool>("sim.registerThreads", false);
    zinfo->globalPauseFlag = config.get<bool>("sim.startInGlobalPause", false);

    zinfo->eventQueue = new EventQueue(); //must be instantiated before the memory hierarchy

    //Build the scheduler
    uint32_t parallelism = config.get<uint32_t>("sim.parallelism", 2*sysconf(_SC_NPROCESSORS_ONLN));
    if (parallelism < zinfo->numCores) info("Limiting concurrent threads to %d", parallelism);
    assert(parallelism > 0); //jeez...

    uint32_t schedQuantum = config.get<uint32_t>("sim.schedQuantum", 10000); //phases
    zinfo->sched = new Scheduler(EndOfPhaseActions, parallelism, zinfo->numCores, schedQuantum);

    zinfo->blockingSyscalls = config.get<bool>("sim.blockingSyscalls", false);

    if (zinfo->blockingSyscalls) {
        warn("sim.blockingSyscalls = True, will likely deadlock with multi-threaded apps!");
    }

    InitGlobalStats();

    //Core stats (initialized here for cosmetic reasons, to be above cache stats)
    AggregateStat* allCoreStats = new AggregateStat(false);
    allCoreStats->init("core", "Core stats");
    zinfo->rootStat->append(allCoreStats);

    //Process tree needs this initialized, even though it is part of the memory hierarchy
    zinfo->lineSize = config.get<uint32_t>("sys.lineSize", 64);
    assert(zinfo->lineSize > 0);

    //Address randomization
    zinfo->addressRandomization = config.get<bool>("sys.addressRandomization", false);

    //Port virtualization
    for (uint32_t i = 0; i < MAX_PORT_DOMAINS; i++) zinfo->portVirt[i] = new PortVirtualizer();

    //Process hierarchy
    //NOTE: Due to partitioning, must be done before initializing memory hierarchy
    CreateProcessTree(config);
    zinfo->procArray[0]->notifyStart(); //called here so that we can detect end-before-start races

    zinfo->pinCmd = new PinCmd(&config, NULL /*don't pass config file to children --- can go either way, it's optional*/, outputDir, shmid);

    //Caches, cores, memory controllers
    InitSystem(config);

    //Sched stats (deferred because of circular deps)
    zinfo->sched->initStats(zinfo->rootStat);

    zinfo->processStats = new ProcessStats(zinfo->rootStat);

    //It's a global stat, but I want it to be last...
    zinfo->profHeartbeats = new VectorCounter();
    zinfo->profHeartbeats->init("heartbeats", "Per-process heartbeats", zinfo->lineSize);
    zinfo->rootStat->append(zinfo->profHeartbeats);

    bool perProcessDir = config.get<bool>("sim.perProcessDir", false);
    PostInitStats(perProcessDir, config);

    zinfo->perProcessCpuEnum = config.get<bool>("sim.perProcessCpuEnum", false);

    //Odds and ends
    bool printMemoryStats = config.get<bool>("sim.printMemoryStats", false);
    if (printMemoryStats) {
        gm_stats();
    }

    //HACK: Read all variables that are read in the harness but not in init
    //This avoids warnings on those elements
    config.get<uint32_t>("sim.gmMBytes", (1 << 10));
    if (!zinfo->attachDebugger) config.get<bool>("sim.deadlockDetection", true);
    config.get<bool>("sim.aslr", false);

    //Write config out
    bool strictConfig = config.get<bool>("sim.strictConfig", true); //if true, panic on unused variables
    config.writeAndClose((string(zinfo->outputDir) + "/out.cfg").c_str(), strictConfig);

    zinfo->contentionSim->postInit();

    info("Initialization complete");

    //Causes every other process to wake up
    gm_set_glob_ptr(zinfo);
}
Пример #29
0
void QuetzalAccount::load(Config cfg)
{
	cfg.beginGroup(QLatin1String("general"));
	QByteArray password = cfg.value(QLatin1String("passwd"), QString(), Config::Crypted).toUtf8();
	if (!password.isEmpty()) {
		purple_account_set_password(m_account, password.constData());
		purple_account_set_remember_password(m_account, true);
	}
	purple_account_set_alias(m_account, cfg.value(QLatin1String("alias"),
												  QString()).toUtf8().constData());
	purple_account_set_user_info(m_account, cfg.value(QLatin1String("userInfo"),
													  QString()).toUtf8().constData());
	QMapIterator<QString, QVariant> it(cfg.value(QLatin1String("quetzal_settings")).toMap());
	while (it.hasNext()) {
		it.next();
		QByteArray key = it.key().toUtf8();
		QVariant::Type type = it.value().type();
		if (type == QVariant::Bool) {
			purple_account_set_bool(m_account, key.constData(), it.value().toBool());
		} else if (type == QVariant::Int || type == QVariant::UInt
				 || type == QVariant::LongLong || type == QVariant::ULongLong) {
			purple_account_set_int(m_account, key.constData(), it.value().toInt());
		} else {
			purple_account_set_string(m_account, key.constData(), it.value().toString().toUtf8());
		}
	}
	cfg.endGroup();
	
	RosterStorage::instance()->load(this);
	
	int size = cfg.beginArray(QLatin1String("chats"));
	QString name = QLatin1String("name");
	QString recent = QLatin1String("recent");
	QString data = QLatin1String("data");
	for (int i = 0; i < size; i++) {
		cfg.setArrayIndex(i);
		QByteArray alias = cfg.value(name, QString()).toUtf8();
		PurpleGroup *group = NULL;
		if (cfg.value(recent, false)) {
			group = purple_find_group("Recent");
			if (!group) {
				group = purple_group_new("Recent");
				purple_blist_add_group(group, NULL);
			}
		}
		GHashTable *comps = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
		QMapIterator<QString, QVariant> it(cfg.value(data).toMap());
		while (it.hasNext()) {
			it.next();
			QByteArray key = it.key().toUtf8();
			QByteArray value = it.value().toString().toUtf8();
			g_hash_table_insert(comps, g_strdup(key.constData()), g_strdup(value.constData()));
		}
		PurpleChat *pc = purple_chat_new(m_account, alias.constData(), comps);
		purple_blist_add_chat(pc, NULL, NULL);
	}
	
	_purple_buddy_icons_blist_loaded_cb();
}
Пример #30
0
/*
+-----------------+------------------------------------------------------------+
| FUNCION         | SndTrxOffLine::ProcessIt                                   |
+-----------------+------------------------------------------------------------+
| DESCRIPCION     | Proceso del objeto                                         |
|                 |                                                            | 
+-----------------+------------------------------------------------------------+
*/
int SndTrxOffLine::ProcessIt()
{
    int             len;
    int             ret;
    int				iCont;
	str_sel_cadata  term_data;
    char            msg_str[2000];
    char            aux_str[20];
    trxOffHeap      infoHeap;         
    DBInfoEnvio     InfoEnvio;        
    str_fet_bu_trx  trxOff;
    int             pos_ocup;
    str_tarjeta     data_tar;
	char			aux_str1[100];	
    DBTrxPk         trxPk;             
    char			idHeap[20];
	char			szFechaEnvio[16];
	int				iErrorBD;
	int				iNroCuotas;

	/* Carga estructura para busqueda de transaccion offline */
    strncpy(trxOff.cod_tar   , CodTarjeta, sizeof(trxOff.cod_tar));
    strncpy(trxOff.cod_est   , "00"      , sizeof(trxOff.cod_est));
    strncpy(trxOff.nro_caj_ca, NroCajCa  , sizeof(trxOff.nro_caj_ca));
    strncpy(trxOff.nro_trx   , NroTrx    , sizeof(trxOff.nro_trx));
	trxOff.nro_caj_ca[sizeof(trxOff.nro_caj_ca)-1]='\0';
    trxOff.cod_tar   [sizeof(trxOff.cod_tar)   -1]='\0';
	trxOff.cod_est   [sizeof(trxOff.cod_est)   -1]='\0';
	trxOff.nro_trx   [sizeof(trxOff.nro_trx)   -1]='\0';

    /* Busca en BD una transaccion offline */
    LogAlarm.Put(0, "TrxOff: Lee offline [%s] [%s] [%s] [%s]\n", trxOff.nro_caj_ca, trxOff.cod_tar, trxOff.cod_est, trxOff.nro_trx);
	ret=DBGetNextTrx(&trxOff, &iErrorBD);
    if (ret!=OK)
    {
		LogAlarm.Put( 0, "TrxOff: Retorno de recuperacion de offline:%d Errno:%d\n", ret, iErrorBD);
		EnviarMsg(orig_pid, "ERROR", 5);
		return OK; 
	}
    //LogAlarm.Put(0, "TrxOff: Rowid a enviar [%s]\n",trxOff.rowid);

	/* Obtiene datos del centro autorizador */
    LogAlarm.Put(5, "TrxOff: Obtiene codigo de centro\n");
	strcpy(data_tar.cod_tar, trxOff.cod_tar);
	ret = ObtCA(&data_tar);
	if (ret!=OK)
	{
		LogAlarm.Put(0, "TrxOff: ERROR al obtener CA. Tar:[%s]\n", trxOff.cod_tar);
		EnviarMsg(orig_pid, "ERROR", 5);
		return OK; 
	}       

	/* Verifica si la caja esta libre */
    strcpy(term_data.nro_caj, trxOff.nro_caj);
    pos_ocup = P.IsPosFree(data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
    if (pos_ocup)
    {    
		/* Marca la caja como ocupada */
		ret = P.SetPosBusy(data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
		if (ret!=OK)
		{
			LogAlarm.Put(0, "TrxOff: ERROR al setear caja como ocupada\n");
		}
    }
    else
    {
        /* Retorna envio de caja bloqueada */
		LogAlarm.Put(0, "TrxOff: ERROR. Caja bloqueada\n");
		EnviarMsg(orig_pid, "BLOCK", 5);
		return NOOK;
    }

    /* Arma el mensaje base de acuerdo al codigo de transaccion */
	switch (atoi(trxOff.cod_trx))
	{
	case T_VENT:
		IsoMsg=new Iso_Msg(TYPE_VISA_VENTA_LOCAL);
		break;
	case T_DEVO:
		IsoMsg=new Iso_Msg(TYPE_VISA_DEVOL_LOCAL);
		break;
	case T_PAGO:
		IsoMsg=new Iso_Msg(TYPE_VISA_VENTA_LOCAL);
		sprintf(aux_str1, "%06d", OPCODE_VISA_PAGO_RESUMEN);
		IsoMsg->PutField(3, aux_str1);
		break;
	case T_DEVP:
		IsoMsg=new Iso_Msg(TYPE_VISA_DEVOL_LOCAL);
		sprintf(aux_str1, "%06d", OPCODE_VISA_DEVO_RESUMEN);
		IsoMsg->PutField(3, aux_str1);
		break;
	default: /* Tipo de transaccion desconocida */
		/* Libera la caja */
		ret = P.SetPosFree(data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
		if (ret != OK)
		{
			LogAlarm.Put(0, "TrxOff: ERROR en SetPosFree. CA:[%s] Emp:[%s] Caj:[%s]\n", 
							data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
		}
		LogAlarm.Put(0, "TrxOff: ERROR. Mensaje desconocido\n");
		EnviarMsg(orig_pid, "ERROR", 5);
		return NOOK;
	}

	/* Setea centro autorizador */
	IsoMsg->SetNroCA8583(data_tar.nro_ca);

	/* Arma la informacion para el heap */
    infoHeap.origPid=orig_pid;
    strncpy( infoHeap.nroSuc  , trxOff.nro_suc, sizeof(infoHeap.nroSuc  ) );
    strncpy( infoHeap.nroTerm , trxOff.nro_caj, sizeof(infoHeap.nroTerm ) );
    strncpy( infoHeap.nroTrans, trxOff.nro_tic, sizeof(infoHeap.nroTrans) );
    strncpy( infoHeap.fechaTrx, trxOff.fec_loc, sizeof(infoHeap.fechaTrx) );
    strncpy( infoHeap.codTar  , trxOff.cod_tar, sizeof(infoHeap.codTar  ) );
    strncpy( infoHeap.NroCajCa, trxOff.nro_caj_ca,sizeof(infoHeap.NroCajCa));
    strcpy ( infoHeap.Rowid,    trxOff.rowid);
    infoHeap.nroSuc  [sizeof(infoHeap.nroSuc   )-1]='\0';
    infoHeap.nroTerm [sizeof(infoHeap.nroTerm  )-1]='\0';
    infoHeap.nroTrans[sizeof(infoHeap.nroTrans )-1]='\0';
    infoHeap.fechaTrx[sizeof(infoHeap.fechaTrx )-1]='\0';
    infoHeap.codTar  [sizeof(infoHeap.codTar   )-1]='\0';
    infoHeap.NroCajCa[sizeof(infoHeap.NroCajCa )-1]='\0';   

     /* Convierte la tarjeta a standard ISO (sin espsacio y formato LLL-VAR */
    int counter=0;
    for (counter=0;counter<sizeof(trxOff.nro_tar);counter++)
    {
		if (trxOff.nro_tar[counter]<'0' || trxOff.nro_tar[counter]>'9')
		{
			break;
		} 
    }
    trxOff.nro_tar[counter]='\0';

    /* Configura datos de la terminal */
	strcpy(term_data.cod_tar, trxOff.cod_tar);
    strcpy(term_data.nro_suc, infoHeap.nroSuc);
    strcpy(term_data.nro_caj, infoHeap.nroTerm);
    strcpy(term_data.plan_sf, trxOff.plan_sf);

    /* Busca terminal en base de datos */
	ret=getDataByNT2(&term_data);
    if ( (ret!=OK) || (term_data.caj_bloq==1) )
    {
		/* Loguea error de terminal */
		LogErrTerminal.Put(0, "Fecha Hora %s", currentTimeLog() );
        LogErrTerminal.Put(0, "Caja: %s - Sucursal: %s - Tarjeta: %s - Plan: %s - Evento: TrxOff\n\n", 
							term_data.nro_caj, term_data.nro_suc, term_data.cod_tar, term_data.plan_sf);
        LogAlarm.Put(0, "TrxOff: ERROR (%d) de terminal (%s) bloqueada (%d)\n", ret, term_data.nro_caj, term_data.caj_bloq);
    
        /* Libera la caja */
		ret = P.SetPosFree(data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
        if (ret != OK)
        {
             LogAlarm.Put(0, "TrxOff: ERROR en SetPosFree. CA:[%s] Emp:[%s] Caj:[%s]\n", 
								data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
        }
        EnviarMsg(orig_pid, "ERROR", 5);
        return NOOK;
    }

    /* Numero de Tarjeta */
	sprintf(aux_str1,"%02d%s",counter,trxOff.nro_tar);
    IsoMsg->PutField(2, aux_str1);

    /* Monto */
	sprintf(aux_str1,"%012ld",atol(trxOff.monto));
    IsoMsg->PutField(4, aux_str1);

	/* Fecha de transmision */
	sprintf(szFechaEnvio, currentTimestamp());
    IsoMsg->PutField(7, szFechaEnvio);

	/* Si hora operacion mayor a transmision se rechaza */
	/* Quitar si sincronizan hora los servidores        */
	switch (DBTipoProtocoloISO(trxOff.nro_ca))
	{
	case PROT_ISO_AMEX: 
		if (strcmp(trxOff.fec_loc, szFechaEnvio)>0)
		{
			LogAlarm.Put(0, "TrxOff: Ter:[%s] Trx:[%04d]\n", infoHeap.nroTerm, atoi(infoHeap.nroTrans));
			LogAlarm.Put(0, "TrxOff: ERROR fecha/hora FHoperac[%s] FHtransm[%s]\n", trxOff.fec_loc, szFechaEnvio);
			/* Libera la caja */
			ret = P.SetPosFree(data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
			if (ret != OK)
			{
				LogAlarm.Put(0, "TrxOff: ERROR en SetPosFree. CA:[%s] Emp:[%s] Caj:[%s]\n", 
								data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
			}
			EnviarMsg(orig_pid, "ERROR", 5);
	        return NOOK;
		}
		break;
	default:
		break;
	}

   	/* Numero de trace */
    TraceNumber.SetNroSuc(term_data.nro_suc);
    TraceNumber.SetNroCaj(term_data.nro_caj);
    TraceNumber.SetNroCA (term_data.nro_ca );
    TraceNumber.SetCodConCie(term_data.cod_con_cie);
    strcpy(aux_str, TraceNumber);
    TraceNumber.Inc();
    IsoMsg->PutField(11, aux_str); 

	/* Hora local */
	IsoMsg->PutField(12, trxOff.fec_loc+4);
    
	/* Fecha local */
	IsoMsg->PutField(13, trxOff.fec_loc);
    
	/* Fecha de expiracion */
	IsoMsg->PutField(14, trxOff.fec_ven);
    
	/* Fecha de captura */
	switch (DBTipoProtocoloISO(trxOff.nro_ca))
	{
	case PROT_ISO_AMEX:
		break;
	default:
		IsoMsg->PutField(17, trxOff.fec_loc);
		break;
	}
    
	/* Modo de ingreso */
	IsoMsg->PutField(22, trxOff.mod_ing );
		
	/* Codigo de red */
    IsoMsg->PutField(24, term_data.cod_red);
    
	/* Codigo de condicion */
	IsoMsg->PutField(25, "00" );

	/* Track 2 si ingreso fue por banda */
	switch (DBTipoProtocoloISO(trxOff.nro_ca))
	{
	case PROT_ISO_AMEX:
		break;
	default:
		if (   !strcmp(trxOff.mod_ing, "022") 
			|| !strcmp(trxOff.mod_ing, "062") ) 
		{
			sprintf(aux_str1, "%02d%s", strlen(trxOff.track2), trxOff.track2);
			IsoMsg->PutField(35, aux_str1);
		}
		break;
	}

	/* Codigo de autorizacion */
	sprintf(aux_str1, "%s", trxOff.cod_aut);
	switch (DBTipoProtocoloISO(trxOff.nro_ca))
	{
	case PROT_ISO_AMEX:
		if( (atoi(trxOff.cod_trx)==T_DEVO) || (atoi(trxOff.cod_trx)==T_DEVP) )
		{
			if (atoi(trxOff.mod_env)==T_OFLI)
			{
				sprintf(aux_str1, "      "); // Devolucion offline Amex
			}
		}
		break;
	default:
		break;
	}
	IsoMsg->PutField(38, aux_str1);

	/* Terminal centro autorizador */
    IsoMsg->PutField(41, term_data.nro_caj_ca);

	/* Comercio centro autorizador */	
    sprintf(aux_str1,"%-15s",term_data.nro_com);
    IsoMsg->PutField(42, aux_str1);

	/* #37322 Cuotas articulos nacionales */
	iNroCuotas = ( term_data.plan_esp > 0 ) ? term_data.plan_esp : atoi(trxOff.nro_cuo) ;
	/* Campo Cuotas */
	sprintf(aux_str1,"003%1.1s%2.2d",trxOff.plan_iso, iNroCuotas);
	if( (atoi(trxOff.cod_trx)==T_DEVO) || (atoi(trxOff.cod_trx)==T_DEVP) )
    {
		if(useCampCuot(trxOff.nro_ca)==1)
		{
			sprintf(aux_str1, "013%1.1s%02d%04d%6s", 
						trxOff.plan_iso, iNroCuotas, atoi(trxOff.nro_tic_ori), trxOff.fec_ori);
		}
    }
	/* Compras AMEX de contado no se envia campo 48 */
	switch (DBTipoProtocoloISO(trxOff.nro_ca))
	{
	case PROT_ISO_AMEX: 
		if (strcmp(aux_str1, "003001")==0) 
		{
			memset(aux_str1, 0, sizeof(aux_str1));
		}
		break;
	default:
		break;
	}
	/* Agrega campo */
	if ( strlen(aux_str1) > 0 )
	{
		IsoMsg->PutField(48, aux_str1);
	}

	/* Codigo de moneda */
	IsoMsg->PutField(49, trxOff.cod_mon );

	/* Fecha de diferimiento (si no es devolucion) */
	if (term_data.dias_dif > 0)
	{
		if( (atoi(trxOff.cod_trx)!=T_DEVO) && (atoi(trxOff.cod_trx)!=T_DEVP) )
		{
			char szFechaDif[6+1];
			if (getFechaDif(trxOff.fec_trx, term_data.dias_dif, szFechaDif)==0)
			{
				ret = strlen(CAMPO_FECHA_DIFE) + strlen(szFechaDif);
				sprintf(aux_str1, "%03d%s%s", ret, CAMPO_FECHA_DIFE, szFechaDif);
				ret = IsoMsg->PutField(59, aux_str1);
				LogAlarm.Put(10, "TrxOff: Campo 59:[%s] Ret:[%d]\n", aux_str1, ret);
			}
		}
	}

    /* Numero de ticket */
	sprintf(aux_str1,"004%04d", atoi(trxOff.nro_tic));
    IsoMsg->PutField(62, aux_str1 );

    LogAlarm.Put(0, "TrxOff: Emp:[%s] Suc:[%s] Ter:[%s] Trx:[%04d] Rowid:[%s]\n", 
						term_data.nro_suc, term_data.nro_caj_sf, infoHeap.nroTerm, 
						atoi(infoHeap.nroTrans), trxOff.rowid);

	/* Arma clave para el heap */
    sprintf(idHeap, "%2.2s%3.3s%5.5s%8.8s", term_data.nro_ca, term_data.nro_suc, term_data.nro_caj, IsoMsg->GetField(11));

    /* Pone datos en el heap */
    LogAlarm.Put(5, "TrxOff: Pone datos en el Heap\n");
	ret=Heap.PutData(idHeap,(char *)&infoHeap, sizeof(infoHeap));
	if (ret==NOOK)
	{
		LogAlarm.Put(0, "TrxOff: ERROR (%d) al insertar en Heap. Clave:[%s]\n", Heap.GetErrno(), idHeap);

		/* Libera la caja */
		ret = P.SetPosFree(data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
		if (ret != OK)
		{
			LogAlarm.Put(0, "TrxOff: ERROR en SetPosFree. CA:[%s] Emp:[%s] Caj:[%s]\n", 
								data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
		}
        EnviarMsg(orig_pid, "ERROR", 5);
		return NOOK;
	}

    /* Carga estructura para actualizar la base de datos */
	strncpy( trxPk.nroSuc  , trxOff.nro_suc, sizeof(trxPk.nroSuc  ) );
    strncpy( trxPk.nroTerm , trxOff.nro_caj, sizeof(trxPk.nroTerm ) );
    strncpy( trxPk.nroTrans, trxOff.nro_tic, sizeof(trxPk.nroTrans) );
    strncpy( trxPk.fechaTrx, trxOff.fec_loc, sizeof(trxPk.fechaTrx) );
    strncpy( trxPk.rowid   , trxOff.rowid  , sizeof(trxPk.rowid   ) );

    /* Carga estructura para actualizar la base de datos */
	strncpy(InfoEnvio.cod_est, "01", sizeof(InfoEnvio.cod_est ));
    strncpy(InfoEnvio.fec_env, szFechaEnvio, sizeof(InfoEnvio.fec_env ));
    strncpy(InfoEnvio.nro_lot, "0000", sizeof(InfoEnvio.nro_lot));
    strncpy(InfoEnvio.nro_trc, IsoMsg->GetField(11), sizeof(InfoEnvio.nro_trc));

	/* Actualiza la base de datos */
    ret=DBUpdEnvio(trxPk , InfoEnvio);
    LogAlarm.Put(0, "TrxOff: Actualiza informacion de Envio. Retorno:%d\n", ret);

    /* Registra en cola de timeout */
	strcpy(aux_str, IsoMsg->GetField(11));
    Cfg.GetItem("TimeOutDaemon", "MsgTimeOut1", aux_str1);
	LogAlarm.Put(0, "TrxOff: Timeout ID Trace [%s]\n", idHeap);
    ret=timeout_queue.SetTimeOut(idHeap, atoi(aux_str1), GetType(), "");
    if (ret==NOOK)
    {
        LogAlarm.Put(0, "TrxOff: ERROR (%d) al registrar en TOQ\n",ret);

		/* Libera la caja */
		ret = P.SetPosFree(data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
		if (ret != OK)
		{
			LogAlarm.Put(0, "TrxOff: ERROR en SetPosFree. CA:[%s] Emp:[%s] Caj:[%s]\n", 
							data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
		}

		/* Retira del heap */
		ret=Heap.GetData(idHeap,(char *)&infoHeap, sizeof(infoHeap));
		if (ret == NOOK)
		{
			LogAlarm.Put( 0, "TrxOff: ERROR (%d) al obtener del heap\n", Heap.GetErrno());
		}
		
		/* Envia respuesta */
		EnviarMsg(orig_pid, "ERROR", 5);
		
		return NOOK;
    }

    /* Aplana el mensaje */
    len=IsoMsg->GetMsgString(msg_str);

	/* Loguea el mensaje */
	for (iCont=0; iCont<64; iCont++)
	{
		if (IsoMsg->ChkField(iCont))
		{
			LogAlarm.Put(5, "TrxOff: Campo %02d: Valor:[%s]\n", iCont, IsoMsg->GetField(iCont) );
		}
	}

    /* Envia el mensaje a X25 */
	LogAlarm.Put(0, "TrxOff: Envia a X.25. CAut [%s]\n", term_data.nro_ca);
    ret=XQueue.SendMsg(atoi(term_data.nro_ca)+1, msg_str, len);
    if (ret!=OK)
    {
        LogAlarm.Put(0, "TrxOff: ERROR en Envio X.25(%d)\n", XQueue.GetErrno());

		/* Libera la caja */
        ret = P.SetPosFree(data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
        if (ret != OK)
        {
             LogAlarm.Put(0, "TrxOff: ERROR en SetPosFree. CA:[%s] Emp:[%s] Caj:[%s]\n", 
								data_tar.nro_ca, trxOff.nro_suc, trxOff.nro_caj);
        }
        
		/* Envia respuesta */
		EnviarMsg(orig_pid, "ERROR", 5);

        return NOOK;
    }
    return OK;
}