예제 #1
0
Mineserver::Mineserver()
  :  m_socketlisten  (0),
     m_saveInterval  (0),
     m_lastSave      (std::time(NULL)),
     m_pvp_enabled   (false),
     m_damage_enabled(false),
     m_only_helmets  (false),
     m_running       (false),
     m_eventBase     (NULL),

     // core modules
     m_config        (new Config),
     m_screen        (new CliScreen),
     m_logger        (new Logger),

     m_plugin        (NULL),
     m_chat          (NULL),
     m_furnaceManager(NULL),
     m_packetHandler (NULL),
     m_inventory     (NULL),
     m_mobs          (NULL)
{
  memset(&m_listenEvent, 0, sizeof(event));
  initConstants();
}
예제 #2
0
int openCommon(openni::Device& device, DeviceConfig config)
{
    g_pPlaybackControl = g_device.getPlaybackControl();

    int ret;

    ret = openStream(device, "depth", openni::SENSOR_DEPTH, config.openDepth, g_depthStream, &g_depthSensorInfo, &g_bIsDepthOn);
    if (ret != 0)
    {
        return ret;
    }

    ret = openStream(device, "color", openni::SENSOR_COLOR, config.openColor, g_colorStream, &g_colorSensorInfo, &g_bIsColorOn);
    if (ret != 0)
    {
        return ret;
    }

    ret = openStream(device, "IR", openni::SENSOR_IR, config.openIR, g_irStream, &g_irSensorInfo, &g_bIsIROn);
    if (ret != 0)
    {
        return ret;
    }

    initConstants();

    readFrame();

    return 0;
}
예제 #3
0
ObjectMan::ObjectMan(DMEngine *vm) : _vm(vm) {
	for (uint16 i = 0; i < k199_ObjectNameCount; ++i)
		_objectNames[i] = nullptr;

	_objectIconForMousePointer = nullptr;

	initConstants();
}
예제 #4
0
SpeexPlugin::SpeexPlugin() {
	initConstants();
	encoder = 0;
	decoder = 0;
	preprocess = 0;
	//	usingEchoCancellation = false;
	//	echoCapturedLast = true;
}
예제 #5
0
CLAB::CLAB( const unsigned char R, const unsigned char G, const unsigned char B ) {
	initConstants();

	// RGB -> XYZ
	double var_R = ( R / 255.0 );        //R from 0 to 255
	double var_G = ( G / 255.0 );        //G from 0 to 255
	double var_B = ( B / 255.0 );        //B from 0 to 255

	if ( var_R > 0.04045 )
		var_R = pow( ( ( var_R + 0.055 ) / 1.055 ), 2.4 );
	else
		var_R = var_R / 12.92;

	if ( var_G > 0.04045 )
		var_G = pow( ( ( var_G + 0.055 ) / 1.055 ), 2.4 );
	else
		var_G = var_G / 12.92;

	if ( var_B > 0.04045 )
		var_B = pow( ( ( var_B + 0.055 ) / 1.055 ), 2.4 );
	else
		var_B = var_B / 12.92;

	var_R = var_R * 100.0;
	var_G = var_G * 100.0;
	var_B = var_B * 100.0;

	//Observer. = 2°, Illuminant = D65
	double X = var_R * 0.4124 + var_G * 0.3576 + var_B * 0.1805;
	double Y = var_R * 0.2126 + var_G * 0.7152 + var_B * 0.0722;
	double Z = var_R * 0.0193 + var_G * 0.1192 + var_B * 0.9505;

	//////////////////////////////////////////////////////////////////////////
	// XYZ -> LAB

	double var_X = X / ref_X;          //ref_X =  95.047   Observer= 2°, Illuminant= D65
	double var_Y = Y / ref_Y;          //ref_Y = 100.000
	double var_Z = Z / ref_Z;          //ref_Z = 108.883

	if ( var_X > 0.008856 )
		var_X = pow( var_X, 1 / 3.0 );
	else
		var_X = ( 7.787 * var_X ) + ( 16 / 116.0 );

	if ( var_Y > 0.008856 )
		var_Y = pow( var_Y, 1 / 3.0 );
	else
		var_Y = ( 7.787 * var_Y ) + ( 16 / 116.0 );

	if ( var_Z > 0.008856 )
		var_Z = pow( var_Z, 1 / 3.0 );
	else
		var_Z = ( 7.787 * var_Z ) + ( 16 / 116.0 );

	mL = ( 116.0 * var_Y ) - 16.0;
	mA = 500.0 * ( var_X - var_Y );
	mB = 200.0 * ( var_Y - var_Z );
}
예제 #6
0
void openCommon()
{
	XnStatus nRetVal = XN_STATUS_OK;

	g_bIsDepthOn = false;
	g_bIsImageOn = false;
	g_bIsIROn = false;
	g_bIsAudioOn = false;
	g_bIsPlayerOn = false;

	NodeInfoList list;
	nRetVal = g_Context.EnumerateExistingNodes(list);
	if (nRetVal == XN_STATUS_OK)
	{
		for (NodeInfoList::Iterator it = list.Begin(); it != list.End(); ++it)
		{
			switch ((*it).GetDescription().Type)
			{
			case XN_NODE_TYPE_DEVICE:
				(*it).GetInstance(g_Device);
				break;
			case XN_NODE_TYPE_DEPTH:
				g_bIsDepthOn = true;
				(*it).GetInstance(g_Depth);
				break;
			case XN_NODE_TYPE_IMAGE:
				g_bIsImageOn = true;
				(*it).GetInstance(g_Image);
				break;
			case XN_NODE_TYPE_IR:
				g_bIsIROn = true;
				(*it).GetInstance(g_IR);
				break;
			case XN_NODE_TYPE_AUDIO:
				g_bIsAudioOn = true;
				(*it).GetInstance(g_Audio);
				break;
			case XN_NODE_TYPE_PLAYER:
				g_bIsPlayerOn = true;
				(*it).GetInstance(g_Player);
			}
		}
	}

	XnCallbackHandle hDummy;
	g_Context.RegisterToErrorStateChange(onErrorStateChanged, NULL, hDummy);

	initConstants();

	readFrame();
}
예제 #7
0
int main() {
	// init predefined constants
	initConstants();
	// init solver with bounds
	LBFGSB MySolver(l, r);
	// create starting point
	Vector XOpt = Vector::Zero(2, 1);
	XOpt << 0.3, 0.3;
	// solve the problem
	MySolver.Solve(XOpt, Quadratic_ValueSimple, Quadratic_GradientSimple);
	// print the solution
	std::cout << MySolver.XOpt.transpose();
	std::cout << std::endl;

	return 0;
}
예제 #8
0
파일: oscil.c 프로젝트: silky/SpaceElevator
int main(int argc, char **argv)
{
    initConstants();

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH | GLUT_ALPHA);

    glutInitWindowSize(WIDTH,HEIGHT);
    glutCreateWindow("Elevator");
    glutDisplayFunc(mainloop);
    glutIdleFunc(mainloop);

    glMatrixMode(GL_MODELVIEW);
    glScaled(1/90e6,1/90e6,1/90e6);

    init();
    glutMainLoop();
    return 0;
}
예제 #9
0
파일: dm.cpp 프로젝트: WinterGrascph/dm
Common::Error DMEngine::run() {
	initConstants();

	// scummvm/engine specific
	initGraphics(320, 200, false);
	_console = new Console(this);
	_displayMan = new DisplayMan(this);
	_dungeonMan = new DungeonMan(this);
	_eventMan = new EventManager(this);
	_menuMan = new MenuMan(this);
	_championMan = new ChampionMan(this);
	_objectMan = new ObjectMan(this);
	_inventoryMan = new InventoryMan(this);
	_textMan = new TextMan(this);
	_moveSens = new MovesensMan(this);
	_groupMan = new GroupMan(this);
	_timeline = new Timeline(this);
	_projexpl = new ProjExpl(this);
	_dialog = new DialogMan(this);
	_sound = SoundMan::getSoundMan(this, _gameVersion);
	_displayMan->setUpScreens(320, 200);

	initializeGame();
	while (true) {
		gameloop();

		if (_engineShouldQuit)
			return Common::kNoError;

		if (_loadSaveSlotAtRuntime == -1)
			endGame(_championMan->_partyDead);
		else {
			loadGameState(_loadSaveSlotAtRuntime);
			_menuMan->drawEnabledMenus();
			_displayMan->updateScreen();
			_loadSaveSlotAtRuntime = -1;
		}
	}

	return Common::kNoError;
}
예제 #10
0
	//------------------------------------------------------------------------------------
	CameraPositionTool::CameraPositionTool()
	{
		initConstants();

		MenuBar* mb = MenuBarList::getSingleton().getMenuBar( "EditorMenuBar" );
		mb->insertItem( ROOT_MENU_ID, MenuItemType::Popup, ROOT_MENU_CAPTION );
		mb->insertItem( MENU_SEPARATOR_ID[0], MenuItemType::Separator, StringUtil::BLANK, ROOT_MENU_ID );
		mb->insertItem( POPUP_MENU_ID, MenuItemType::Popup, POPUP_MENU_CAPTION, ROOT_MENU_ID );

		size_t i;
		for(i = 0; i != NUM_POSITIONS; ++i)
		{
			mb->insertItem( STORE_MENU_ITEM_ID[i], MenuItemType::Normal, STORE_MENU_ITEM_CAPTION[i], POPUP_MENU_ID );
			mb->insertHotkey( STORE_MENU_ITEM_ID[i], STORE_HOTKEY_CONFIG_KEY_NAME[i], "Editor", DEFAULT_STORE_HOTKEY[i] );
			mb->setItemDescription( STORE_MENU_ITEM_ID[i], STORE_MENU_ITEM_DESC );

			ToolParam tp;
			tp.store = true;
			tp.index = i;
			mb->attachTool( STORE_MENU_ITEM_ID[i], this, (AnyLite) tp );
		}
		
		mb->insertItem( MENU_SEPARATOR_ID[1], MenuItemType::Separator, StringUtil::BLANK, POPUP_MENU_ID );

		for(i = 0; i != NUM_POSITIONS; ++i)
		{
			mb->insertItem( RESTORE_MENU_ITEM_ID[i], MenuItemType::Normal, RESTORE_MENU_ITEM_CAPTION[i], POPUP_MENU_ID );
			mb->insertHotkey( RESTORE_MENU_ITEM_ID[i], RESTORE_HOTKEY_CONFIG_KEY_NAME[i], "Editor", DEFAULT_RESTORE_HOTKEY[i]);
			mb->setItemDescription( RESTORE_MENU_ITEM_ID[i], RESTORE_MENU_ITEM_DESC );
			
			ToolParam tp;
			tp.store = false;
			tp.index = i;
			mb->attachTool(RESTORE_MENU_ITEM_ID[i], this, (AnyLite) tp);
		}

		updateMenuItems();
		registerWorldListener();
	}
예제 #11
0
int Mineserver::run(int argc, char *argv[])
{
  uint32 starttime = (uint32)time(0);
  uint32 tick      = (uint32)time(0);

  // Init our Screen
  screen()->init(VERSION);
  screen()->log("Welcome to Mineserver v" + VERSION);
  updatePlayerList();

  initConstants();

  std::string file_config;
  file_config.assign(CONFIG_FILE);
  std::string file_commands;
  file_commands.assign(COMMANDS_FILE);

  if (argc > 1)
  {
    file_config.assign(argv[1]);
  }

  // Initialize conf
  Mineserver::get()->conf()->load(file_config);
  Mineserver::get()->conf()->load(file_commands, COMMANDS_NAME_PREFIX);

  // Write PID to file
  std::ofstream pid_out((Mineserver::get()->conf()->sValue("pid_file")).c_str());
  if (!pid_out.fail())
  {
#ifdef WIN32
     pid_out << _getpid();
#else
     pid_out << getpid();
#endif
  }
  pid_out.close();

  // Load MOTD
  Mineserver::get()->chat()->checkMotd(Mineserver::get()->conf()->sValue("motd_file"));

  // Set physics enable state according to config
  Mineserver::get()->physics()->enabled = (Mineserver::get()->conf()->bValue("liquid_physics"));

  // Initialize map
  Mineserver::get()->map()->init();

  if (Mineserver::get()->conf()->bValue("map_generate_spawn"))
  {
    Mineserver::get()->screen()->log("Generating spawn area...");
    int size = Mineserver::get()->conf()->iValue("map_generate_spawn_size");
    bool show_progress = Mineserver::get()->conf()->bValue("map_generate_spawn_show_progress");
#ifdef WIN32
    DWORD t_begin,t_end;
#else
    clock_t t_begin,t_end;
#endif

    for (int x=-size;x<=size;x++)
    {
#ifdef WIN32
      if(show_progress)
      {
        t_begin = timeGetTime();
      }
#else
      if(show_progress)
      {
        t_begin = clock();
      }
#endif
      for (int z = -size; z <= size; z++)
      {
        Mineserver::get()->map()->loadMap(x, z);
      }

      if(show_progress)
      {
#ifdef WIN32
        t_end = timeGetTime ();
        Mineserver::get()->screen()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos((t_end-t_begin)/(size*2+1)) + "ms per chunk");
#else
        t_end = clock();
        Mineserver::get()->screen()->log(dtos((x+size+1)*(size*2+1)) + "/" + dtos((size*2+1)*(size*2+1)) + " done. " + dtos(((t_end-t_begin)/(CLOCKS_PER_SEC/1000))/(size*2+1)) + "ms per chunk");
#endif
      }
    }
#ifdef _DEBUG
    Mineserver::get()->screen()->log("Spawn area ready!");
#endif
  }

  // Initialize packethandler
  Mineserver::get()->packetHandler()->init();

  // Load ip from config
  std::string ip = Mineserver::get()->conf()->sValue("ip");

  // Load port from config
  int port = Mineserver::get()->conf()->iValue("port");

  // Initialize plugins
  Mineserver::get()->plugin()->init();

#ifdef WIN32
  WSADATA wsaData;
  int iResult;
  // Initialize Winsock
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if(iResult != 0)
  {
    printf("WSAStartup failed with error: %d\n", iResult);
    Mineserver::get()->screen()->end();
    return EXIT_FAILURE;
  }
#endif

  struct sockaddr_in addresslisten;
  int reuse = 1;

  m_eventBase = (event_base*)event_init();
#ifdef WIN32
  m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
  m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif

  if(m_socketlisten < 0)
  {
    Mineserver::get()->screen()->log(LOG_ERROR, "Failed to create listen socket");
    Mineserver::get()->screen()->end();
    return 1;
  }

  memset(&addresslisten, 0, sizeof(addresslisten));

  addresslisten.sin_family      = AF_INET;
  addresslisten.sin_addr.s_addr = inet_addr(ip.c_str());
  addresslisten.sin_port        = htons(port);

  setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));

  //Bind to port
  if(bind(m_socketlisten, (struct sockaddr*)&addresslisten, sizeof(addresslisten)) < 0)
  {
    Mineserver::get()->screen()->log(LOG_ERROR, "Failed to bind");
    return 1;
  }

  if(listen(m_socketlisten, 5) < 0)
  {
    Mineserver::get()->screen()->log(LOG_ERROR, "Failed to listen to socket");
    Mineserver::get()->screen()->end();
    return 1;
  }

  setnonblock(m_socketlisten);
  event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
  event_add(&m_listenEvent, NULL);

  if(ip == "0.0.0.0")
  {
    // Print all local IPs
    char name[255];
    gethostname ( name, sizeof(name));
    struct hostent* hostinfo = gethostbyname(name);
    Mineserver::get()->screen()->log("Listening on: ");
    int ipIndex = 0;
    while(hostinfo && hostinfo->h_addr_list[ipIndex])
    {
      std::string ip(inet_ntoa(*(struct in_addr*)hostinfo->h_addr_list[ipIndex++]));
      Mineserver::get()->screen()->log(" " + ip + ":" + dtos(port));
    }
  }
  else
  {
    std::string myip(ip);
    Mineserver::get()->screen()->log("Listening on " + myip + ":" + dtos(port));
  }
  //std::cout << std::endl;

  timeval loopTime;
  loopTime.tv_sec  = 0;
  loopTime.tv_usec = 200000; //200ms

  m_running = true;
  event_base_loopexit(m_eventBase, &loopTime);

  // Create our Server Console user so we can issue commands
  User* serverUser = new User(-1, SERVER_CONSOLE_UID);
  serverUser->changeNick("[Server]");

  while(m_running && event_base_loop(m_eventBase, 0) == 0)
  {
    // Append current command and check if user entered return
    if(Mineserver::get()->screen()->hasCommand())
    {
      // Now handle this command as normal
      Mineserver::get()->chat()->handleMsg(serverUser, Mineserver::get()->screen()->getCommand().c_str());
    }

    if(time(0)-starttime > 10)
    {
      starttime = (uint32)time(0);

      //If users, ping them
      if(User::all().size() > 0)
      {
        //0x00 package
        uint8 data = 0;
        User::all()[0]->sendAll(&data, 1);

        //Send server time
        Packet pkt;
        pkt << (sint8)PACKET_TIME_UPDATE << (sint64)Mineserver::get()->map()->mapTime;
        User::all()[0]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
      }

      // TODO: Run garbage collection for chunk storage dealie?
    }

    //Every second
    if(time(0)-tick > 0)
    {
      tick = (uint32)time(0);
      //Loop users
      for(unsigned int i = 0; i < User::all().size(); i++)
      {
        User::all()[i]->pushMap();
        User::all()[i]->popMap();

        //Minecart hacks!!
        /*
        if(User::all()[i]->attachedTo)
        {
          Packet pkt;
          pkt << PACKET_ENTITY_VELOCITY << (sint32)User::all()[i]->attachedTo <<  (sint16)10000       << (sint16)0 << (sint16)0;
          //pkt << PACKET_ENTITY_RELATIVE_MOVE << (sint32)User::all()[i]->attachedTo <<  (sint8)100       << (sint8)0 << (sint8)0;
          User::all()[i]->sendAll((uint8*)pkt.getWrite(), pkt.getWriteLen());
        }
        */
      }

      map()->mapTime+=20;
      if (map()->mapTime >= 24000)
      {
        map()->mapTime = 0;
      }

      map()->checkGenTrees();

      // Check for Furnace activity
      Mineserver::get()->furnaceManager()->update();
    }

    // Physics simulation every 200ms
    Mineserver::get()->physics()->update();

    // Underwater check / drowning
    int i = 0;
    int s = User::all().size();
    for(i=0;i<s;i++)
    {
      User::all()[i]->isUnderwater();
    }

//    event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
//    event_add(&m_listenEvent, NULL);

    event_base_loopexit(m_eventBase, &loopTime);
  }

#ifdef WIN32
  closesocket(m_socketlisten);
#else
  close(m_socketlisten);
#endif

  // Remove the PID file
#ifdef WIN32
  _unlink((Mineserver::get()->conf()->sValue("pid_file")).c_str());
#else
  unlink((Mineserver::get()->conf()->sValue("pid_file")).c_str());
#endif

  // End our NCurses session
  screen()->end();

  /* Free memory */
  delete m_map;
  delete m_chat;
  delete m_plugin;
  delete m_screen;
  delete m_physics;
  delete m_conf;
  delete m_furnaceManager;
  delete m_packetHandler;
  delete m_mapGen;
  delete m_logger;

  return EXIT_SUCCESS;
}
예제 #12
0
Mineserver::Mineserver(int args, char **argarray)
    :  argv(argarray),
       argc(args),
       m_socketlisten  (0),
       m_saveInterval  (0),
       m_lastSave      (std::time(NULL)),
       m_pvp_enabled   (false),
       m_damage_enabled(false),
       m_only_helmets  (false),
       m_running       (false),
       m_eventBase     (NULL),

       // core modules
       m_config        (new Config()),
       m_screen        (new CliScreen()),
       m_logger        (new Logger()),

       m_plugin        (NULL),
       m_chat          (NULL),
       m_furnaceManager(NULL),
       m_packetHandler (NULL),
       m_inventory     (NULL),
       m_mobs          (NULL)
{
    pthread_mutex_init(&m_validation_mutex,NULL);
    ServerInstance = this;
    InitSignals();

    std::srand((uint32_t)std::time(NULL));
    initPRNG();

    std::string cfg;
    std::vector<std::string> overrides;

    for (int i = 1; i < argc; i++)
    {
        const std::string arg(argv[i]);

        switch (arg[0])
        {
        case '-':   // option
            // we have only '-h' and '--help' now, so just return with help
            printHelp(0);
            throw CoreException();

        case '+':   // override
            overrides.push_back(arg.substr(1));
            break;

        default:    // otherwise, it is config file
            if (!cfg.empty())
                throw CoreException("Only single CONFIG_FILE argument is allowed!");
            cfg = arg;
            break;
        }
    }

    const std::string path_exe = "./";

    // If config file is provided as an argument
    if (!cfg.empty())
    {
        std::cout << "Searching for configuration file..." << std::endl;
        if (fileExists(cfg))
        {
            const std::pair<std::string, std::string> fullpath = pathOfFile(cfg);
            cfg = fullpath.first + PATH_SEPARATOR + fullpath.second;
            this->config()->config_path = fullpath.first;
        }
        else
        {
            std::cout << "Config not found...\n";;
            cfg.clear();
        }
    }

    if (cfg.empty())
    {
        if (fileExists(path_exe + PATH_SEPARATOR + CONFIG_FILE))
        {
            cfg = path_exe + PATH_SEPARATOR + CONFIG_FILE;
            this->config()->config_path = path_exe;
        }
        else
        {
            std::cout << "Config not found\n";
        }
    }

    // load config
    Config &configvar = *this->config();
    if (!configvar.load(cfg))
    {
        throw CoreException("Could not load config!");
    }

    m_plugin = new Plugin();

    LOG2(INFO, "Using config: " + cfg);

    if (overrides.size())
    {
        std::stringstream override_config;
        for (size_t i = 0; i < overrides.size(); i++)
        {
            LOG2(INFO, "Overriden: " + overrides[i]);
            override_config << overrides[i] << ';' << std::endl;
        }
        // override config
        if (!configvar.load(override_config))
            throw CoreException("Error when parsing overrides: maybe you forgot to doublequote string values?");
    }

    memset(&m_listenEvent, 0, sizeof(event));
    initConstants();
    // Write PID to file
    std::ofstream pid_out((config()->sData("system.pid_file")).c_str());
    if (!pid_out.fail())
    {
        pid_out << getpid();
    }
    pid_out.close();




    init_plugin_api();

    if (config()->bData("system.interface.use_cli"))
    {
        // Init our Screen
        screen()->init(VERSION);
    }


    LOG2(INFO, "Welcome to Mineserver v" + VERSION);
    LOG2(INFO, "Using zlib "+std::string(ZLIB_VERSION)+" libevent "+std::string(event_get_version()));

    LOG2(INFO, "Generating RSA key pair for protocol encryption");
    //Protocol encryption
    srand(microTime());
    if((rsa = RSA_generate_key(1024, 17, 0, 0)) == NULL)
    {
        LOG2(INFO, "KEY GENERATION FAILED!");
        exit(1);
    }
    LOG2(INFO, "RSA key pair generated.");

    /* Get ASN.1 format public key */
    x=X509_new();
    pk=EVP_PKEY_new();
    EVP_PKEY_assign_RSA(pk,rsa);
    X509_set_version(x,0);
    X509_set_pubkey(x,pk);

    int len;
    unsigned char *buf;
    buf = NULL;
    len = i2d_X509(x, &buf);

    //Glue + jesus tape, dont ask - Fador
    publicKey = std::string((char *)(buf+28),len-36);
    OPENSSL_free(buf);
    /* END key fetching */

    const std::string temp_nums="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890=-";

    const std::string temp_hex="0123456789abcdef";

    for(int i = 0; i < 4; i++)
    {
        encryptionBytes += (char)(temp_nums[rand()%temp_nums.size()]);
    }

    for(int i = 0; i < 16; i++)
    {
        serverID += (char)(temp_hex[rand()%temp_hex.size()]);
    }

    LOG2(INFO, "ServerID: " + serverID);

    if(!m_config->bData("system.user_validation"))
    {
        serverID = "-";
    }

    MapGen* mapgen = new MapGen();
    MapGen* nethergen = new NetherGen();
    MapGen* heavengen = new HeavenGen();
    MapGen* biomegen = new BiomeGen();
    MapGen* eximgen = new EximGen();
    m_mapGenNames.push_back(mapgen);
    m_mapGenNames.push_back(nethergen);
    m_mapGenNames.push_back(heavengen);
    m_mapGenNames.push_back(biomegen);
    m_mapGenNames.push_back(eximgen);

    m_saveInterval = m_config->iData("map.save_interval");

    m_only_helmets = m_config->bData("system.armour.helmet_strict");
    m_pvp_enabled = m_config->bData("system.pvp.enabled");
    m_damage_enabled = m_config->bData("system.damage.enabled");

    const char* key = "map.storage.nbt.directories"; // Prefix for worlds config
    if (m_config->has(key) && (m_config->type(key) == CONFIG_NODE_LIST))
    {
        std::list<std::string> tmp = m_config->mData(key)->keys();
        int n = 0;
        for (std::list<std::string>::const_iterator it = tmp.begin(); it != tmp.end(); ++it)
        {
            m_map.push_back(new Map());
            Physics* phy = new Physics;
            phy->map = n;

            m_physics.push_back(phy);
            RedstoneSimulation* red = new RedstoneSimulation;
            red->map = n;
            m_redstone.push_back(red);
            int k = m_config->iData((std::string(key) + ".") + (*it));
            if ((uint32_t)k >= m_mapGenNames.size())
            {
                std::ostringstream s;
                s << "Error! Mapgen number " << k << " in config. " << m_mapGenNames.size() << " Mapgens known";
                LOG2(INFO, s.str());
            }
            // WARNING: if k is too big this will be an access error! -- louisdx
            MapGen* m = m_mapGenNames[k];
            m_mapGen.push_back(m);
            n++;
        }
    }
    else
    {
        LOG2(WARNING, "Cannot find map.storage.nbt.directories.*");
    }

    if (m_map.size() == 0)
        throw CoreException("No worlds in Config");

    m_chat           = new Chat;
    m_furnaceManager = new FurnaceManager;
    m_packetHandler  = new PacketHandler;
    m_inventory      = new Inventory(m_config->sData("system.path.data") + '/' + "recipes", ".recipe", "ENABLED_RECIPES.cfg");
    m_mobs           = new Mobs;

} // End Mineserver constructor
예제 #13
0
파일: wigner.cpp 프로젝트: fjarri-attic/bec
int main(int argc, char** argv)
{
	ModelParameters model_params;

	fillCalculationParameters(model_params);
	fillDerivedParameters(model_params, params);

	if (CUTFalse == initGL(argc, argv, params))
		return CUTFalse;

	// use command-line specified CUDA device, otherwise use device with highest Gflops/s
	if(cutCheckCmdLineFlag(argc, (const char**)argv, "device"))
		cutilDeviceInit(argc, argv);
	else
		cudaSetDevice(cutGetMaxGflopsDeviceId());

	// initialize calculations
	initConstants(params);

	timeval init_start, init_stop;

	// calculate steady state
	value_pair *steady_state = new value_pair[params.cells];

	initSpectre();
	initWaveVectors(params);

	gettimeofday(&init_start, NULL);
	calculateSteadyState(steady_state, params);
	gettimeofday(&init_stop, NULL);
	printf("Steady state calculation: %.3f s\n", time_diff(init_start, init_stop));

/*
	FILE *f = fopen("plot_gs_mu.txt", "w");
	int shift = (params.nvz / 2) * params.nvx * params.nvy + (params.nvy / 2) * params.nvx;
	for(int i = 0; i < params.nvx; i++)
	{
		value_pair val = steady_state[shift + i];
		fprintf(f, "%f %f\n", (-params.xmax + params.dx * i) * 1000000, (val.x * val.x + val.y * val.y));
	}
	fclose(f);
 */

	gettimeofday(&init_start, NULL);
	state.init(params);
	initEvolution(steady_state, params, state);
	gettimeofday(&init_stop, NULL);
	printf("Evolution init: %.3f s\n", time_diff(init_start, init_stop));

	delete[] steady_state;

	// measure propagation time, for testing purposes
	calculateEvolution(params, state, 0.0); // warm-up
	gettimeofday(&init_start, NULL);
	calculateEvolution(params, state, 0.0); // zero time step - because we are just measuring speed here
	gettimeofday(&init_stop, NULL);
	printf("Propagation time: %.3f ms\n", time_diff(init_start, init_stop) * 1000.0f);

	// prepare textures
	a_xy.init(params.nvx, params.nvy);
	b_xy.init(params.nvx, params.nvy);
	a_zy.init(params.nvz, params.nvy);
	b_zy.init(params.nvz, params.nvy);

	// remember starting time
	gettimeofday(&time_start, NULL);

	// start main application cycle
        atexit(cleanup);
        glutMainLoop();
	return 0;
}
예제 #14
0
void openCommon(openni::Device& device, bool defaultRightColor)
{
	XnStatus nRetVal = XN_STATUS_OK;

	g_bIsDepthOn = false;
	g_bIsColorOn = false;
	g_bIsIROn    = false;

	g_depthSensorInfo = device.getSensorInfo(openni::SENSOR_DEPTH);
	g_colorSensorInfo = device.getSensorInfo(openni::SENSOR_COLOR);
	g_irSensorInfo = device.getSensorInfo(openni::SENSOR_IR);

	if (g_depthSensorInfo != NULL)
	{
		nRetVal = g_depthStream.create(device, openni::SENSOR_DEPTH);
		if (nRetVal != openni::STATUS_OK)
		{
			printf("Failed to create depth stream:\n%s\n", openni::OpenNI::getExtendedError());
			return;
		}

		nRetVal = g_depthStream.start();
		if (nRetVal != openni::STATUS_OK)
		{
			printf("Failed to start depth stream:\n%s\n", openni::OpenNI::getExtendedError());
			g_depthStream.destroy();
			return;
		}

		g_bIsDepthOn = true;
	}

	if (g_colorSensorInfo != NULL)
	{
		nRetVal = g_colorStream.create(device, openni::SENSOR_COLOR);
		if (nRetVal != openni::STATUS_OK)
		{
			printf("Failed to create color stream:\n%s\n", openni::OpenNI::getExtendedError());
			return;
		}

		if (defaultRightColor)
		{
			nRetVal = g_colorStream.start();
			if (nRetVal != openni::STATUS_OK)
			{
				printf("Failed to start color stream:\n%s\n", openni::OpenNI::getExtendedError());
				g_colorStream.destroy();
				return;
			}

			g_bIsColorOn = true;
		}
	}

	if (g_irSensorInfo != NULL)
	{
		nRetVal = g_irStream.create(device, openni::SENSOR_IR);
		if (nRetVal != openni::STATUS_OK)
		{
			printf("Failed to create IR stream:\n%s\n", openni::OpenNI::getExtendedError());
			return;
		}

		if (!g_bIsColorOn)
		{
			nRetVal = g_irStream.start();
			if (nRetVal != openni::STATUS_OK)
			{
				printf("Failed to start IR stream:\n%s\n", openni::OpenNI::getExtendedError());
				g_irStream.destroy();
				return;
			}

			g_bIsIROn = true;
		}
	}

	initConstants();

	readFrame();
}
예제 #15
0
파일: main.cpp 프로젝트: soulik/luambedtls
	extern "C" LUAMBEDTLS_DLL_EXPORTED int luaopen_luambedtls(lua_State * L){
		State * state = new State(L);
		Stack * stack = state->stack;
		Module luambedtls_module;

		stack->newTable();

		initMPI(state, luambedtls_module);
		initASN1buf(state, luambedtls_module);
		initASN1named(state, luambedtls_module);
		initASN1sequence(state, luambedtls_module);

		//key-pairs
		initPKContext(state, luambedtls_module);
		initPKinfo(state, luambedtls_module);

		initCTRDRBGContext(state, luambedtls_module);
		initDHMContext(state, luambedtls_module);
		initEntropyContext(state, luambedtls_module);
		initSSLConfig(state, luambedtls_module);
		initSSLContext(state, luambedtls_module);
		initSSLCookieContext(state, luambedtls_module);
		initSSLSession(state, luambedtls_module);
		initx509crt(state, luambedtls_module);
		initx509crl(state, luambedtls_module);
		initx509crlEntry(state, luambedtls_module);
		initx509crtProfile(state, luambedtls_module);
		initx509csr(state, luambedtls_module);
		initx509writeCert(state, luambedtls_module);
		initx509writeCSR(state, luambedtls_module);
		initTimingDelayContext(state, luambedtls_module);
		initAESContext(state, luambedtls_module);

		//symmetric-encryption
		initARC4Context(state, luambedtls_module);
		initBlowfishContext(state, luambedtls_module);
		initCamelliaContext(state, luambedtls_module);
		initDESContext(state, luambedtls_module);
		initDES3Context(state, luambedtls_module);
		initGCMContext(state, luambedtls_module);
		initXTEAContext(state, luambedtls_module);

		//asymmetric-ecnryption
		initDHMContext(state, luambedtls_module);
		initRSAContext(state, luambedtls_module);

		//EC
		initECPCurveInfo(state, luambedtls_module);
		initECPPoint(state, luambedtls_module);
		initECPGroup(state, luambedtls_module);
		initECPKeyPair(state, luambedtls_module);
		initECDHContext(state, luambedtls_module);
		initECSDAContext(state, luambedtls_module);

		//message-digest
		initMDContext(state, luambedtls_module);
		initMDinfo(state, luambedtls_module);

		//cipher
		initCipherContext(state, luambedtls_module);
		initCipherInfo(state, luambedtls_module);

		//utils
		initUtils(state, luambedtls_module);

		luambedtls_module["init"] = init;
		initConstants(state, luambedtls_module);
		luambedtls_module["strError"] = strError;
		luambedtls_module["debugTreshhold"] = debugTreshhold;
		luambedtls_module["MPIlen"] = MPIlen;
		luambedtls_module["pushOIDAttrShortName"] = pushOIDAttrShortName;
		luambedtls_module["pushOIDNumericString"] = pushOIDNumericString;
		luambedtls_module["pushOIDExtType"] = pushOIDExtType;
		luambedtls_module["pushOIDPkAlg"] = pushOIDPkAlg;

		state->registerLib(luambedtls_module);
		return 1;
	}
예제 #16
0
int Mineserver::Run()
{

  uint32 starttime = (uint32)time(0);
  uint32 tick      = (uint32)time(0);

  initConstants();

  Chat::get().loadAdmins(ADMINFILE);
  Chat::get().checkMotd(MOTDFILE);

  //Initialize conf
  Conf::get().load(CONFIGFILE);
  // Load item aliases
  Conf::get().load(ITEMALIASFILE);

  //Set physics enable state according to config
  Physics::get().enabled = (Conf::get().iValue("liquid_physics") ? true : false);

  //Initialize map
  Map::get().initMap();

  //Initialize packethandler
  PacketHandler::get().initPackets();

  // Load port from config
  int port = Conf::get().iValue("port");

#ifdef WIN32
  _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
  _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_DEBUG );
  WSADATA wsaData;
  int iResult;
  // Initialize Winsock
  iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
  if(iResult != 0)
  {
    printf("WSAStartup failed with error: %d\n", iResult);
    return EXIT_FAILURE;
  }
#endif

  struct sockaddr_in addresslisten;
  int reuse             = 1;

  m_eventBase = (event_base *)event_init();
#ifdef WIN32
  m_socketlisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
#else
  m_socketlisten = socket(AF_INET, SOCK_STREAM, 0);
#endif

  if(m_socketlisten < 0)
  {
    fprintf(stderr, "Failed to create listen socket\n");
    return 1;
  }

  memset(&addresslisten, 0, sizeof(addresslisten));

  addresslisten.sin_family      = AF_INET;
  addresslisten.sin_addr.s_addr = INADDR_ANY;
  addresslisten.sin_port        = htons(port);

  setsockopt(m_socketlisten, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(reuse));

  //Bind to port
  if(bind(m_socketlisten, (struct sockaddr *)&addresslisten, sizeof(addresslisten)) < 0)
  {
    fprintf(stderr, "Failed to bind\n");
    return 1;
  }

  if(listen(m_socketlisten, 5) < 0)
  {
    fprintf(stderr, "Failed to listen to socket\n");
    return 1;
  }


  setnonblock(m_socketlisten);
  event_set(&m_listenEvent, m_socketlisten, EV_WRITE|EV_READ|EV_PERSIST, accept_callback, NULL);
  event_add(&m_listenEvent, NULL);

  std::cout << std::endl<<
  "   _____  .__  "<<
  std::endl<<
  "  /     \\ |__| ____   ____   ______ ______________  __ ___________ "<<
  std::endl<<
  " /  \\ /  \\|  |/    \\_/ __ \\ /  ___// __ \\_  __ \\  \\/ // __ \\_  __ \\"<<
  std::endl<<
  "/    Y    \\  |   |  \\  ___/ \\___ \\\\  ___/|  | \\/\\   /\\  ___/|  | \\/"<<
  std::endl<<
  "\\____|__  /__|___|  /\\___  >____  >\\___  >__|    \\_/  \\___  >__|   "<<
  std::endl<<
  "        \\/        \\/     \\/     \\/     \\/                 \\/       "<<
  std::endl<<
  "Version " << VERSION <<" by Fador & Nredor"<<
  std::endl << std::endl;

  std::cout << "Listening at port " << port << std::endl;

  timeval loopTime;
  loopTime.tv_sec  = 0;
  loopTime.tv_usec = 200000; //200ms

  m_running=true;
  event_base_loopexit(m_eventBase, &loopTime);
  while(m_running && event_base_loop(m_eventBase, 0) == 0)
  {
    if(time(0)-starttime > 10)
    {
      starttime = (uint32)time(0);
      std::cout << "Currently " << Users.size() << " users in!" << std::endl;

      //If users, ping them
      if(Users.size() > 0)
      {
        //0x00 package
        uint8 data = 0;
        Users[0]->sendAll(&data, 1);

        //Send server time (after dawn)
        uint8 data3[9] = {0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00};
        Users[0]->sendAll((uint8 *)&data3[0], 9);
      }

      //Try to load port from config
      int map_release_time = Conf::get().iValue("map_release_time");

      //Release chunks not used in <map_release_time> seconds
      std::vector<uint32> toRelease;
      for(std::map<uint32, int>::const_iterator it = Map::get().mapLastused.begin();
          it != Map::get().mapLastused.end();
          ++it)
      {
        if(Map::get().mapLastused[it->first] <= time(0)-map_release_time)
          toRelease.push_back(it->first);
      }

      int x_temp, z_temp;
      for(unsigned i = 0; i < toRelease.size(); i++)
      {
        Map::get().idToPos(toRelease[i], &x_temp, &z_temp);
        Map::get().releaseMap(x_temp, z_temp);
      }
    }

    //Every second
    if(time(0)-tick > 0)
    {
      tick = (uint32)time(0);
      //Loop users
      for(unsigned int i = 0; i < Users.size(); i++)
      {
        Users[i]->pushMap();
        Users[i]->popMap();
      }
    }

    //Physics simulation every 200ms
    Physics::get().update();

    event_base_loopexit(m_eventBase, &loopTime);
  }

  Map::get().freeMap();

  #ifdef WIN32
  closesocket(m_socketlisten);
  #else
    close(m_socketlisten);
  #endif

  //Windows debug
#ifdef WIN32
  _CrtDumpMemoryLeaks();
#endif

  return EXIT_SUCCESS;
}
예제 #17
0
CLAB::CLAB() {
	initConstants();
}