示例#1
0
Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    loadConfig();
//    startServer();
    initializeLogging();
    _serv= QSharedPointer<PollsServer>(nullptr);
}
示例#2
0
文件: Util.cpp 项目: absorbguo/Paddle
void initMain(int argc, char** argv) {
  installLayerStackTracer();
  std::string line;
  for (int i = 0; i < argc; ++i) {
    line += argv[i];
    line += ' ';
  }

#ifndef GFLAGS_GFLAGS_H_
  namespace gflags = google;
#endif

  gflags::ParseCommandLineFlags(&argc, &argv, true);
  initializeLogging(argc, argv);
  LOG(INFO) << "commandline: " << line;
  CHECK_EQ(argc, 1) << "Unknown commandline argument: " << argv[1];

  installProfilerSwitch();

#ifdef __SSE__
  _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
#endif
#ifdef __SSE3__
  _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
#endif

  if (FLAGS_seed == 0) {
    unsigned int t = time(NULL);
    srand(t);
    ThreadLocalRand::initSeed(t);
    LOG(INFO) << "random number seed=" << t;
  } else {
    srand(FLAGS_seed);
    ThreadLocalRand::initSeed(FLAGS_seed);
  }

  if (FLAGS_use_gpu) {
    // This is the initialization of the CUDA environment,
    // need before runInitFunctions.
    // TODO(hedaoyuan) Can be considered in the runInitFunctions,
    // but to ensure that it is the first to initialize.
    hl_start();
    hl_init(FLAGS_gpu_id);
  }

  version::printVersion();
  checkCPUFeature().check();
  runInitFunctions();
}
示例#3
0
void TestFormats::initTestCase ()
{
  const QString NO_ERROR_REPORT_LOG_FILE;
  const bool NO_GNUPLOT_LOG_FILES = false;
  const bool DEBUG_FLAG = false;
  const QStringList NO_LOAD_STARTUP_FILES;

  initializeLogging ("engauge_test",
                     "engauge_test.log",
                     DEBUG_FLAG);

  MainWindow w (NO_ERROR_REPORT_LOG_FILE,
                NO_GNUPLOT_LOG_FILES,
                NO_LOAD_STARTUP_FILES);
  w.show ();
}
示例#4
0
int main(void) {
    initializePlatform();
    initializeLogging();
    initializeTimers();
    initializePower();
    initializeUsb(listener.usb);
    initializeSerial(listener.serial);
    initializeEthernet(listener.ethernet);
    initializeLights();
    initializeBluetooth();

    debug("Initializing as %s", getMessageSet());
    setup();

    for (;;) {
        loop();
        processListenerQueues(&listener);
        updateInterfaceLight();
        updatePower();
    }

    return 0;
}
示例#5
0
文件: nrd.cpp 项目: joaopapereira/NFD
void
Nrd::initialize()
{
  m_face.reset(new ndn::Face(getLocalNfdTransport(), getGlobalIoService(), m_keyChain));

  initializeLogging();

  m_ribManager.reset(new RibManager(*m_face, m_keyChain));

  ConfigFile config([] (const std::string& filename, const std::string& sectionName,
                        const ConfigSection& section, bool isDryRun) {
      // Ignore "log" and sections belonging to NFD,
      // but raise an error if we're missing a handler for a "rib" section.
      if (sectionName != "rib" || sectionName == "log") {
        // do nothing
      }
      else {
        // missing NRD section
        ConfigFile::throwErrorOnUnknownSection(filename, sectionName, section, isDryRun);
      }
    });
  m_ribManager->setConfigFile(config);

  // parse config file
  if (!m_configFile.empty()) {
    config.parse(m_configFile, true);
    config.parse(m_configFile, false);
  }
  else {
    config.parse(m_configSection, true, INTERNAL_CONFIG);
    config.parse(m_configSection, false, INTERNAL_CONFIG);
  }

  m_ribManager->registerWithNfd();
  m_ribManager->enableLocalControlHeader();
}
示例#6
0
int main(int argc,char* argv[])
{
	//initialize logging system, camera and network connection 
	processArgs(argc,argv);
	if (saveLog) initializeLogging();
	if (argc < 2) {
		fprintf(stderr,"usage: %s imageSource num_robots\ne.g. %s /dev/video0 1\n",argv[0],argv[0]);
		return 0;
	}
	camera = new CCamera();
	server = new CPositionServer();
	server->init("6666"); 

	moveOne = moveVal;
	moveOne  = 0;
	//process arguments
	camera->init(argv[1],&imageWidth,&imageHeight,saveVideo);
	camera->loadConfig("../etc/camera.cfg");

	//determine gui size so that it fits the screen
	while (imageHeight/guiScale > screenHeight || imageHeight/guiScale > screenWidth) guiScale = guiScale*2;

	//initialize GUI, image structures, coordinate transformation modules
	if (useGui) gui = new CGui(imageWidth,imageHeight,guiScale);
	image = new CRawImage(imageWidth,imageHeight);
	trans = new CTransformation(imageWidth,imageHeight,circleDiameter,true);
	trans->transformType = TRANSFORM_NONE;		//in our case, 2D is the default

	//initialize the circle detectors - each circle has its own detector instance 
	for (int i = 0;i<MAX_PATTERNS;i++) detectorArray[i] = new CCircleDetect(imageWidth,imageHeight,i);
	image->getSaveNumber();

	//setup timers to assess system performance
	CTimer timer;
	timer.reset();
	timer.start();

	CTimer globalTimer;
	globalTimer.reset();
	globalTimer.start();

	int frameID =0;
	int64_t frameTime = 0;
	while (stop == false)
	{
		if (useGui){
			camera->renewImage(image,moveOne-->0);
		}else{
			if (camera->renewImage(image,moveOne-->0)==-1)stop = true;
		}
		numFound = numStatic = 0;
		timer.reset();
		frameTime = globalTimer.getRealTime();
		//track the robots found in the last attempt 
		for (int i = 0;i<numBots;i++){
			if (currentSegmentArray[i].valid){
				lastSegmentArray[i] = currentSegmentArray[i];
				currentSegmentArray[i] = detectorArray[i]->findSegment(image,lastSegmentArray[i]);
			}
		}

		//search for untracked (not detected in the last frame) robots 
		for (int i = 0;i<numBots;i++){
			if (currentSegmentArray[i].valid == false){
				lastSegmentArray[i].valid = false;
				currentSegmentArray[i] = detectorArray[i]->findSegment(image,lastSegmentArray[i]);
			}
			if (currentSegmentArray[i].valid == false) break;		//does not make sense to search for more patterns if the last one was not found
		}

		//perform transformations from camera to world coordinates
		for (int i = 0;i<numBots;i++){
			if (currentSegmentArray[i].valid){
				objectArray[i] = trans->transform(currentSegmentArray[i],false);
				numFound++;
				if (currentSegmentArray[i].x == lastSegmentArray[i].x) numStatic++;
			}
		}
		printf("Pattern detection time: %i us. Found: %i Static: %i. Clients %i.\n",globalTimer.getTime(),numFound,numStatic,server->numConnections);
		evalTime = timer.getTime();

		//pack up the data for sending to other systems
		server->setNumOfPatterns(numFound,numBots,frameTime);
		for (int i = 0;i<numBots;i++) server->updatePosition(objectArray[i],i,frameTime);
		server->clearToSend();

		//draw stuff on the GUI 
		if (useGui){
			gui->drawImage(image);
			gui->drawTimeStats(evalTime,numBots);
			gui->displayHelp(displayHelp);
			gui->guideCalibration(calibNum,fieldLength,fieldWidth);
		}
		for (int i = 0;i<numBots && useGui && drawCoords;i++){
			if (currentSegmentArray[i].valid) gui->drawStats(currentSegmentArray[i].minx-30,currentSegmentArray[i].maxy,objectArray[i],trans->transformType == TRANSFORM_2D);
		}

		//establishing the coordinate system by manual or autocalibration
		if (autocalibrate && numFound == numBots) autocalibration();
		if (calibNum < 4) manualcalibration();

		
		for (int i = 0;i<numBots;i++){
			//if (currentSegmentArray[i].valid) printf("Object %i %03f %03f %03f %03f %03f\n",i,objectArray[i].x,objectArray[i].y,objectArray[i].z,objectArray[i].error,objectArray[i].esterror);
		}

		if (camera->cameraType == CT_WEBCAM){
			//for real camera, continue with capturing of another frame even if not all robots have been found
			moveOne = moveVal;
			for (int i = 0;i<numBots;i++){
			       	//printf("Frame %i Object %03i %03i %.5f %.5f %.5f \n",frameID,i,currentSegmentArray[i].ID,objectArray[i].x,objectArray[i].y,objectArray[i].yaw);
			       	if (robotPositionLog != NULL) fprintf(robotPositionLog,"Frame %i Time %ld Object %03i %03i %.5f %.5f %.5f \n",frameID,frameTime,i,currentSegmentArray[i].ID,objectArray[i].x,objectArray[i].y,objectArray[i].yaw);
			}
			if (moveVal > 0) frameID++;
		}else{
			//for postprocessing, try to find all robots before loading next frame
			if (numFound ==  numBots)
			{
				//gui->saveScreen(runs++);
				for (int i = 0;i<numBots;i++){
				       		//printf("Frame %i Object %03i %03i %.5f %.5f %.5f \n",frameID,i,currentSegmentArray[i].ID,objectArray[i].x,objectArray[i].y,objectArray[i].yaw);
						if (robotPositionLog != NULL) fprintf(robotPositionLog,"Frame %i Time %ld Object %03i %03i %.5f %.5f %.5f \n",frameID,frameTime,i,currentSegmentArray[i].ID,objectArray[i].x,objectArray[i].y,objectArray[i].yaw);
				}
				moveOne = moveVal; 
				if (moveVal > 0) frameID++;
			}else{
				if (moveOne-- < -100) moveOne = moveVal;
			}
		}

		//gui->saveScreen(runs);
		if (useGui) gui->update();
		if (useGui) processKeys();
	}
	if (robotPositionLog != NULL) fclose(robotPositionLog);
	delete server;
	runs--;
	delete image;
	if (useGui) delete gui;
	for (int i = 0;i<MAX_PATTERNS;i++) delete detectorArray[i];
	camera->saveConfig("../etc/camera.cfg");
	delete camera;
	delete trans;
	return 0;
}
示例#7
0
文件: phero.cpp 项目: gemad/CosPhi
int main(int argc,char* argv[])
{
	//register ctrl+c handler
	signal (SIGINT,ctrl_c_handler);
	//initialize the logging system
	if (initializeLogging()==false) return -1;

	//auto-detect screen resolution (in case of a single display) and initialize the GUI
	gui = new CGui(&imageWidth,&imageHeight,dualMonitor);
	image = new CRawImage(imageWidth,imageHeight);

	//read number of robots and pheromone half-life from the command line
	numBots = atoi(argv[2]);
	float evaporation = atof(argv[1]);

	float diffusion = 0;
	float influence = 1.0;

	/*initialize the pheromone fields
	* pheromone field 0 simulates a longer-decay pheromone that the other robots follow
	* pheromone field 1 is released by the leader if it gets too close to arena boundaries causing the leader to avoid them - this pheromone decays quickly
	* pheromone field 2 is released by the leader to supress pheromone field 0 (this avoids the leader to detect pheromone 0 by its sensors)
	*evaporation defines pheromone's half-life, diffusion its spreading over time and strength determines how the pheromone influences the LCD-displayed image
	for details, see the chapter 2 of paper Arvin, Krajnik, Turgut, Yue: "CosPhi: Artificial Pheromone System for Robotic Swarms Research", IROS 2015*/
	pherofield[0] = new CPheroField(imageWidth,imageHeight,evaporation,diffusion,influence);
	pherofield[1] = new CPheroField(imageWidth,imageHeight,0.1,0,1);
	pherofield[2] = new CPheroField(imageWidth,imageHeight,0.1,0,-5);

	/*connect to the localization system*/
	client = new CPositionClient();
	client->init(whyconIP,"6666");
	image->getSaveNumber();

	randomPlacement();

	globalTimer.pause();
	CTimer performanceTimer;
	performanceTimer.start();
	while (stop == false){
		//get the latest data from localization system and check if the calibration finished
		stop = (globalTimer.getTime()/1000000>experimentTime);
	

		/*PHEROMONE DECAY*/ 
		pherofield[0]->recompute();	//main pheromone half-life (user-settable, usually long)
		pherofield[1]->recompute();		//collision avoidance pheromone with quick decay
		pherofield[2]->recompute();		//suppression pheromone with quick decay

		client->checkForData();

		/*PHEROMONE INJECTION*/
		if (calibration==false && placement==false)
		{
			int leader = 0;

			/*PHEROMONE 1 - released by the leading robot*/
			for (int i = 0;i<numBots;i++)
			{
				if (client->getID(i) == leaderID){
				       	pherofield[0]->addTo(client->getX(i)*imageWidth/arenaLength,client->getY(i)*imageHeight/arenaWidth,i,pheroStrength);
					leader = i;
				}
			}
			/*cause the leading robot to release pheromone 1 that is used for obstacle avoidance and 2 that temporarily suppresses pheromone 0*/
			float dist = 0.030;	//distance of the pheromone release relatively to the leader (controls pheromones 1 and 2 only) 
			float addPhi = 0;	//angle of the pheromone release relatively to the leader (controls pheromones 1 and 2 only) 
			float phi = client->getPhi(leader);
		
			/*is the leader close to the arena edge ?*/
			if ((client->getX(leader)<avoidDistance && cos(phi)<0) || (client->getX(leader)>arenaLength-avoidDistance && cos(phi) > 0 )|| (client->getY(leader)<avoidDistance && sin(phi)<0) || (client->getY(leader)>arenaWidth-avoidDistance && sin(phi)>0))
			{
				/*leader is close to the arena edge -> release pheromone 1 that causes the robot to turn away */
				pherofield[1]->addTo((client->getX(leader)+dist*cos(phi+addPhi))*imageWidth/arenaLength,(client->getY(leader)+dist*sin(phi+addPhi))*imageHeight/arenaWidth,0,pheroStrength,35);
			}else{
				/*leader is not close to the arena edge -> release pheromone 2 suporessed pheromone 0, so that the leader does not pick it's own pheromone */
				pherofield[2]->addTo((client->getX(leader)+dist*cos(phi+addPhi))*imageWidth/arenaLength,(client->getY(leader)+dist*sin(phi+addPhi))*imageHeight/arenaWidth,0,pheroStrength,45);
			}
			/*save positions for later analysis*/
			logRobotPositions();
		}

		//convert the pheromone field to grayscale image
		image->combinePheromones(pherofield,3,0);		//the last value determines the color channel - 0 is for grayscale, 1 is red etc. 
		gui->drawImage(image);
		
	
		//experiment preparation phase 2: draw initial and real robot positions
		initRadius = robotDiameter/arenaLength*imageWidth/2;	//calculate robot radius in pixels, so that it matches the real robot dimensions
		for (int i = 0;i<numBots && placement;i++)
		{
			 gui->displayInitialPositions(initX[i],initY[i],initA[i],initBrightness,initRadius+10);
			 if (client->exists(i) && calibration == false)  gui->displayRobot(client->getX(i)*imageWidth/arenaLength,client->getY(i)*imageHeight/arenaWidth,client->getPhi(i),0,initRadius+10);
		}
	
		/*this chunk of code is used to determine lag*/
		/*float t = globalTimer.getTime()/1000000.0;	
		for (int i = 0;i<numBots;i++){
			if (client->exists(i)){
				gui->displayRobot(client->getX(i)*imageWidth/arenaLength,client->getY(i)*imageHeight/arenaWidth,client->getPhi(i),0,initRadius+10);
				float dx = fabs(100+50*t-client->getX(i)*imageWidth/arenaLength);
				float dy = fabs(imageHeight/2-client->getY(i)*imageHeight/arenaWidth);
				printf("Distance: %.3f Lag: %f \n",sqrt(dx*dx+dy*dy),sqrt(dx*dx+dy*dy)/50);
			}
		}
		gui->displayPattern(100+t*50,imageHeight/2,initRadius);*/


		//experiment preparation phase 1: draw calibration, contact WhyCon to calibrate and draw initial robot positions
		if (calibration){
			int calibRadius = initRadius/(cameraHeight-robotHeight)*cameraHeight;		//slightly enlarge to compensate for the higher distance from the camera
			gui->displayCalibrationInfo(cameraHeight,client->numSearched,client->numDetected,calibRadius,performanceTimer.getTime()/1000);
			client->calibrate(numBots,arenaLength,arenaWidth,cameraHeight,robotDiameter,robotHeight);
			client->checkForData();
		}else if (placement){
			 gui->displayPlacementInfo(client->numSearched,client->numDetected);
		}
		calibration = client->calibrated==false;


		//update GUI etc
		gui->update();
		processEvents();
		printf("GUI refresh: %i ms, updates %i frame delay %.0f ms\n",performanceTimer.getTime()/1000,client->updates,(performanceTimer.getRealTime()-client->frameTime)/1000.0);
		performanceTimer.reset();
	}
	fclose(robotPositionLog);
	if (globalTimer.getTime()/1000000<experimentTime) {
		remove(logFileName); 
		printf("EXPERIMENT TERMINATED MANUALLY\n");
	}else{
		printf("EXPERIMENT FINISHED SUCESSFULLY, results saved to %s.\n",logFileName);
	}
	for (int i = 0;i<3;i++) delete pherofield[i];
	delete client;
	delete image;
	delete gui;
	return 0;
}
示例#8
0
  //--------------------------------------------------------------------------------
  Server::Server(std::size_t        io_service_pool_size,
                 const std::string& application_id,
                 const std::string& application_instance,
                 bool               runAsDaemon          /*= true*/,
                 const std::string& config_root_path     /*= ""*/,
                 const std::string& address              /*= "get_from_config"*/,
                 const std::string& port                 /*= "get_from_config"*/)
    : io_service_pool_   (io_service_pool_size),
      stop_signals_      (io_service_pool_.get_io_service()),
      log_reopen_signals_(io_service_pool_.get_io_service()),
      acceptor_          (io_service_pool_.get_io_service()),
      new_connection_    (),
      request_router_    ()
  {
    if (createLockFile(application_id, application_instance)) {

      std::cerr << "Lock file created for: [" << application_id << "] [" << application_instance << "]" << std::endl;

      if(runAsDaemon) {
        std::cerr << "Running as Daemon." << std::endl;
        becomeDaemonProcess();
      }

      signalRegistrations();
      std::cerr << "Signal registration completed." << std::endl;

      Config::instance(application_id, application_instance, config_root_path);
      std::cerr << "Configuration instance created." << std::endl;

      initializeLogging((!runAsDaemon));
      std::cerr << "Initialized Logging." << std::endl;

      // create the stats keeper instance here. So that it's available as soon as the server is constructed.
      StatsKeeper::instance(Config::instance()->get<unsigned long int>("kcc-stats.gather-period" ,300),
                            Config::instance()->get<unsigned long int>("kcc-stats.history-length",12));
      std::cerr << "Initialized StatsKeeper." << std::endl;

      ErrorStateList::instance();   // same goes for the error state list.
      std::cerr << "Initialized ErrorStateList." << std::endl;

      initialize_standard_handlers();
      std::cerr << "Initialized Standard Handlers." << std::endl;

      boost::asio::ip::tcp::resolver        resolver(acceptor_.get_io_service()); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
      std::cerr << "Initialized resolver." << std::endl;

      boost::asio::ip::tcp::resolver::query query(Config::instance()->get<std::string>("kcc-server.address"),
                                                  Config::instance()->get<std::string>("kcc-server.port"));
      std::cerr << "Initialized query object." << std::endl;

      boost::asio::ip::tcp::endpoint        endpoint = *resolver.resolve(query);
      std::cerr << "Initialized endpoint." << std::endl;

      acceptor_.open(endpoint.protocol());
      std::cerr << "Acceptor opened." << std::endl;

      acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
      std::cerr << "Acceptor options set." << std::endl;

      acceptor_.bind(endpoint);
      std::cerr << "Acceptor bound." << std::endl;

      acceptor_.listen();

      std::cerr << "Server started, now accepting connections." << std::endl;
      start_accept();
      std::cerr << "Server Ready." << std::endl;
    } else {
      std::cerr << "Could not create Lockfile for this appid and instance: ["
                << lockFilePath.native()
                << "]"
                << std::endl
                << "If this message is not preceded by a message indicating that a lock file already exists, "
                << "you most likely have a permissions problem, or the directory in which you wish to create lock files, "
                << "does not exist."
                << std::endl;

      throw std::runtime_error("Could not create lock file: Terminating.");
    }
  }
示例#9
0
int prepare(const char *lpCmdLine)
{
    char tmp[MAX_ARGS] = {0};
    hModule = GetModuleHandle(NULL);
    if (hModule == NULL)
    {
        return FALSE;
    }

    // Get executable path
    char exePath[_MAX_PATH] = {0};
    int pathLen = getExePath(exePath);
    if (pathLen == -1)
    {
        return FALSE;
    }

    if (!initializeLogging(lpCmdLine, exePath, pathLen))
    {
        return FALSE;
    }

    debug("\n\nVersion:\t%s\n", VERSION);
    debug("CmdLine:\t%s %s\n", exePath, lpCmdLine);
    setWow64Flag();

    // Set default error message, title and optional support web site url.
    loadString(SUPPORT_URL, errUrl);
    loadString(ERR_TITLE, errTitle);
    if (!loadString(STARTUP_ERR, errMsg))
    {
        debug(ERROR_FORMAT, "Startup error message not defined.");
        return FALSE;
    }

    // Single instance
    loadString(MUTEX_NAME, mutexName);
    if (*mutexName)
    {
        SECURITY_ATTRIBUTES security;
        security.nLength = sizeof(SECURITY_ATTRIBUTES);
        security.bInheritHandle = TRUE;
        security.lpSecurityDescriptor = NULL;
        CreateMutexA(&security, FALSE, mutexName);
        if (GetLastError() == ERROR_ALREADY_EXISTS)
        {
            debug(ERROR_FORMAT, "Instance already exists.");
            return ERROR_ALREADY_EXISTS;
        }
    }

    // Working dir
    char tmp_path[_MAX_PATH] = {0};
    GetCurrentDirectory(_MAX_PATH, oldPwd);
    if (loadString(CHDIR, tmp_path))
    {
        strncpy(workingDir, exePath, pathLen);
        appendPath(workingDir, tmp_path);
        _chdir(workingDir);
        debug("Working dir:\t%s\n", workingDir);
    }

    // Use bundled jre or find java
    if (loadString(JRE_PATH, tmp_path))
    {
        char jrePath[MAX_ARGS] = {0};
        expandVars(jrePath, tmp_path, exePath, pathLen);
        debug("Bundled JRE:\t%s\n", jrePath);
        if (jrePath[0] == '\\' || jrePath[1] == ':')
        {
            // Absolute
            strcpy(cmd, jrePath);
        }
        else
        {
            // Relative
            strncpy(cmd, exePath, pathLen);
            appendPath(cmd, jrePath);
        }

        if (isLauncherPathValid(cmd))
        {
            foundJava = (wow64 && loadBool(BUNDLED_JRE_64_BIT))
                        ? FOUND_BUNDLED | KEY_WOW64_64KEY
                        : FOUND_BUNDLED;
        }
    }

    if (foundJava == NO_JAVA_FOUND)
    {
        if (!loadString(JAVA_MIN_VER, javaMinVer))
        {
            loadString(BUNDLED_JRE_ERR, errMsg);
            return FALSE;
        }

        loadString(JAVA_MAX_VER, javaMaxVer);
        if (!findJavaHome(cmd, loadInt(JDK_PREFERENCE)))
        {
            loadString(JRE_VERSION_ERR, errMsg);
            strcat(errMsg, " ");
            strcat(errMsg, javaMinVer);

            if (*javaMaxVer)
            {
                strcat(errMsg, " - ");
                strcat(errMsg, javaMaxVer);
            }

            if (runtimeBits == USE_64_BIT_RUNTIME
                    || runtimeBits == USE_32_BIT_RUNTIME)
            {
                strcat(errMsg, " (");
                strcat(errMsg, runtimeBits == USE_64_BIT_RUNTIME ? "64" : "32");
                strcat(errMsg, "-bit)");
            }

            if (corruptedJreFound)
            {
                char launcherErrMsg[BIG_STR] = {0};

                if (loadString(LAUNCHER_ERR, launcherErrMsg))
                {
                    strcat(errMsg, "\n");
                    strcat(errMsg, launcherErrMsg);
                }
            }

            loadString(DOWNLOAD_URL, errUrl);
            return FALSE;
        }
    }

    // Store the JRE Home Dir
    strcpy(jreHomeDir, cmd);

    // Append a path to the Path environment variable
    char jreBinPath[_MAX_PATH] = {0};
    strcpy(jreBinPath, cmd);
    strcat(jreBinPath, "\\bin");
    if (!appendToPathVar(jreBinPath))
    {
        debug(ERROR_FORMAT, "appendToPathVar failed.");
        return FALSE;
    }

    // Set environment variables
    char envVars[MAX_VAR_SIZE] = {0};
    loadString(ENV_VARIABLES, envVars);
    char *var = strtok(envVars, "\t");
    while (var != NULL)
    {
        char *varValue = strchr(var, '=');
        *varValue++ = 0;
        *tmp = 0;
        expandVars(tmp, varValue, exePath, pathLen);
        debug("Set var:\t%s = %s\n", var, tmp);
        SetEnvironmentVariable(var, tmp);
        var = strtok(NULL, "\t");
    }
    *tmp = 0;

    // Process priority
    priority = loadInt(PRIORITY_CLASS);

    // Launcher
    appendJavaw(cmd);

    // Heap sizes
    appendHeapSizes(args);

    // JVM options
    char jvmOptions[MAX_ARGS] = {0};
    setJvmOptions(jvmOptions, exePath);

    // Expand environment %variables%
    expandVars(args, jvmOptions, exePath, pathLen);

    // MainClass + Classpath or Jar
    char mainClass[STR] = {0};
    char jar[_MAX_PATH] = {0};

    const BOOL wrapper = loadBool(WRAPPER);
    loadString(JAR, jar);

    if (loadString(MAIN_CLASS, mainClass))
    {
        if (!loadString(CLASSPATH, tmp))
        {
            debug("Info:\t\tClasspath not defined.\n");
        }
        char exp[MAX_ARGS] = {0};
        expandVars(exp, tmp, exePath, pathLen);
        strcat(args, "-classpath \"");
        if (wrapper)
        {
            appendAppClasspath(args, exePath);
        }
        else if (*jar)
        {
            appendAppClasspath(args, jar);
        }

        // Deal with wildcards or >> strcat(args, exp); <<
        char* cp = strtok(exp, ";");
        while(cp != NULL)
        {
            debug("Add classpath:\t%s\n", cp);
            if (strpbrk(cp, "*?") != NULL)
            {
                int len = strrchr(cp, '\\') - cp + 1;
                strncpy(tmp_path, cp, len);
                char* filename = tmp_path + len;
                *filename = 0;
                struct _finddata_t c_file;
                long hFile;
                if ((hFile = _findfirst(cp, &c_file)) != -1L)
                {
                    do
                    {
                        strcpy(filename, c_file.name);
                        appendAppClasspath(args, tmp_path);
                        debug("      \"      :\t%s\n", tmp_path);
                    } while (_findnext(hFile, &c_file) == 0);
                }
                _findclose(hFile);
            }
            else
            {
                appendAppClasspath(args, cp);
            }
            cp = strtok(NULL, ";");
        }
        *(args + strlen(args) - 1) = 0;

        strcat(args, "\" ");
        strcat(args, mainClass);
    }
    else if (wrapper)
    {
        strcat(args, "-jar \"");
        strcat(args, exePath);
        strcat(args, "\"");
    }
    else
    {
        strcat(args, "-jar \"");
        strncat(args, exePath, pathLen);
        appendPath(args, jar);
        strcat(args, "\"");
    }

    // Constant command line args
    if (loadString(CMD_LINE, tmp))
    {
        strcat(args, " ");
        strcat(args, tmp);
    }

    // Command line args
    if (*lpCmdLine)
    {
        strcpy(tmp, lpCmdLine);
        char* dst;
        while ((dst = strstr(tmp, "--l4j-")) != NULL)
        {
            char* src = strchr(dst, ' ');
            if (src == NULL || *(src + 1) == 0)
            {
                *dst = 0;
            }
            else
            {
                strcpy(dst, src + 1);
            }
        }
        if (*tmp)
        {
            strcat(args, " ");
            strcat(args, tmp);
        }
    }

    debug("Launcher:\t%s\n", cmd);
    debug("Launcher args:\t%s\n", args);
    debug("Args length:\t%d/32768 chars\n", strlen(args));
    return TRUE;
}
示例#10
0
Int32 MainApplication::run(int argc, char **argv)
{
    //Get the date/time run
    _DateTimeRun = boost::posix_time::second_clock::local_time();

    //Get the path to the command
    BoostPath CommandPath(argv[0]);
    if(!CommandPath.is_complete() && !CommandPath.has_root_directory())
    {
        CommandPath = boost::filesystem::complete(CommandPath);
    }
    CommandPath.normalize();

    //Parse the Program arguments
    boost::program_options::variables_map OptionsVariableMap;
    try
    {
        boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
                                      options(_OptionsDescription).
#ifdef __APPLE__
                                      extra_parser(procSerialNumParser).
#endif
                                      positional(_PositionalOptions).run(), OptionsVariableMap);

        boost::program_options::notify(OptionsVariableMap);
    }
    catch(boost::program_options::error& e)
    {
        std::cout << "Error parsing command line: " << e.what() << std::endl;
        printCommandLineHelp();
    }

    //Check for the help argument
    if(OptionsVariableMap.count("help"))
    {
        printCommandLineHelp();
        return 1;
    }
    
    //Setup the Logging
    LogLevel KELogLevel(LOG_NOTICE);
    if(OptionsVariableMap.count("log-level"))
    {
        KELogLevel = OptionsVariableMap["log-level"].as<LogLevel>();
    }

    _LogFilePath = getLoggingDir()
                 / BoostPath(boost::posix_time::to_iso_string(_DateTimeRun) + ".log");  //ISO date/time format
    if(OptionsVariableMap.count("log-file"))
    {
        _LogFilePath = BoostPath(OptionsVariableMap["log-file"].as<std::string>());
    }
    if(OptionsVariableMap.count("disable-log"))
    {
        _EnableLogging = false;
    }
    if(OptionsVariableMap.count("disable-file-log"))
    {
        _LogToFile = false;
    }

    initializeLogging(_LogFilePath);
    osgLogP->setLogLevel(KELogLevel, true);
    osgLogP->setHeaderElem((LOG_TYPE_HEADER | LOG_FUNCNAME_HEADER), true);

    //Check if the last run crashed
    if(didCrashLastExecution())
    {
        handleCrashLastExecution();
    }

    //Create a file to indicate if a crash occurs
    createCrashIndicationFile();

    // Set up Settings
    //Check for the settings file
    if(OptionsVariableMap.count("settings-file"))
    {
        setSettingsLoadFile(BoostPath(OptionsVariableMap["settings-file"].as<std::string>()));
    }
    else
    {
        //Use default location
        setSettingsLoadFile(getUserAppDataDir()
                          / BoostPath("KEDefaultSettings.xml"));
    }
    loadSettings(getSettingsLoadFile());

    //Cleanup the Logging Directory
    cleanupLoggingDir();

    //If the settings aren't being overriden by the command-line options
    //then set the logging with the settings values
    if(!OptionsVariableMap.count("log-level"))
    {
        osgLogP->setLogLevel(static_cast<LogLevel>(getSettings().get<UInt8>("logging.level")), true);
    }
    osgLogP->setHeaderElem(getSettings().get<UInt32>("logging.header_elements"), true);

    //Initialize OpenSG
    initOpenSG(argc,argv);

    //Log information about the Engine
    {
        PLOG << "Starting Kabala Engine:" << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Arguments: ";
        for(UInt32 i(0) ; i<argc ; ++i)
        {
            PLOG << argv[i] << " ";
        }
        PLOG << std::endl;

        OSG::indentLog(4,PLOG);
        PLOG << "System:" << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Operating System: " << getPlatformName() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Processor: " << getPlatformProcessors() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "RAM: " << getPlatformRAM() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Time: " << to_simple_string(_DateTimeRun) << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Version: " << getKabalaEngineVersion() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Revision: " << getKabalaEngineBuildRepositoryRevision() << std::endl;
        OSG::indentLog(8,PLOG);
        PLOG << "Build Type: " << getKabalaEngineBuildType() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Working Directory: " << boost::filesystem::current_path().string() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Executable Directory: " << CommandPath.parent_path().string() << std::endl;
        OSG::indentLog(4,PLOG);
        PLOG << "Settings File: " << getSettingsLoadFile().string() << std::endl;

        OSG::indentLog(4,PLOG);
        PLOG << "Logging: " << (_EnableLogging ? "Enabled" : "Disabled" ) << std::endl;
        if(_EnableLogging)
        {
            OSG::indentLog(8,PLOG);
            PLOG << "Log File: " << (_LogToFile ? _LogFilePath.string() : "Disabled" ) << std::endl;
        }
    }

    //Check if the Data Directory exists
    if(!boost::filesystem::exists(getSettings().get<BoostPath>("basic.data.directory")))
    {
        BoostPath DataDirPath(getSettings().get<BoostPath>("basic.data.directory"));
        DataDirPath = boost::filesystem::complete(DataDirPath);
        DataDirPath.normalize();
        SWARNING << "Could not find Application Data directory: \""
                 << DataDirPath.string()
                 << "\" specified in the Settings file because the directory doesn't exist." << std::endl;

        //Try to find the data directory in a few locations
        std::vector<BoostPath> PathsToTry;

#ifdef __APPLE__
        PathsToTry.push_back(CommandPath.parent_path() /
                             BoostPath("../Resources") /
                             EngineAppDataDirectory);       //Path to try for OS X Bundles
        PathsToTry.push_back(CommandPath.parent_path() /
                             BoostPath("../Resources/share") /
                             EngineAppDataDirectory);       //Path to try for OS X Bundles
#endif

        PathsToTry.push_back(BoostPath("/usr/local/share") / EngineAppDataDirectory);
        PathsToTry.push_back(BoostPath("/usr/share") / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / BoostPath("..") / EngineAppDataDirectory);
        PathsToTry.push_back(CommandPath.parent_path() / BoostPath("../share") / EngineAppDataDirectory);

        for(UInt32 i(0) ; i<PathsToTry.size() ; ++i)
        {
            SNOTICE << "Looking for Data directory in: "
                << PathsToTry[i].string() << std::endl;
            if(boost::filesystem::exists(PathsToTry[i]))
            {
                PNOTICE << "FOUND" << std::endl;
                PathsToTry[i].normalize();
                getSettings().put("basic.data.directory",PathsToTry[i]);
                break;
            }
            else
            {
                PNOTICE << "NOT FOUND" << std::endl;
            }
        }
    }

    if(!boost::filesystem::exists(getSettings().get<BoostPath>("basic.data.directory")))
    {
        SWARNING << "Could not find Application Data directory: \""
                 << getSettings().get<BoostPath>("basic.data.directory").string()
                 << "\" because the directory doesn't exist." << std::endl;
    }
    else
    {
        SLOG << "Using Application Data directory: \""
                 << getSettings().get<BoostPath>("basic.data.directory").string()
                 << "\"" << std::endl;
    }

    // Set up Window
    WindowEventProducerUnrecPtr MainWindow(createNativeWindow());
    setMainWindow(MainWindow);
    setName(getMainWindow(),"__KABALA_ENGINE_WINDOW_EVENT_PRODUCER");

    //If Fullscreen option -> Fullscreen
    if(OptionsVariableMap.count("fullscreen"))
    {
        getMainWindow()->setFullscreen(true);
    }
    //If no-fullscreen     -> not Fullscreen
    else if(OptionsVariableMap.count("no-fullscreen"))
    {
        getMainWindow()->setFullscreen(false);
    }
    //else                 -> use the value in the settings
    else
    {
        getMainWindow()->setFullscreen(getSettings().get<bool>("basic.window.fullscreen"));
    }

    getMainWindow()->initWindow();

    _WindowClosingConnection = getMainWindow()->connectWindowClosing(boost::bind(&MainApplication::handleWindowClosing, this, _1));
    _WindowClosedConnection = getMainWindow()->connectWindowClosed(boost::bind(&MainApplication::handleWindowClosed, this, _1));

    // Initialize the LookAndFeelManager to enable default settings
    KELookAndFeel::the()->init();


    //Open Window
    Vec2f WindowSize(getSettings().get<Vec2f>("basic.window.size"));
    if(getSettings().get<Vec2f>("basic.window.size").x() <= 1.0f )
    {
        WindowSize[0] = getMainWindow()->getDesktopSize().x() * getSettings().get<Vec2f>("basic.window.size").x();
    }
    if(getSettings().get<Vec2f>("basic.window.size").y() <= 1.0f )
    {
        WindowSize[1] = getMainWindow()->getDesktopSize().y() * getSettings().get<Vec2f>("basic.window.size").y();
    }
    Pnt2f WindowPos(getSettings().get<Pnt2f>("basic.window.position"));
    if(getSettings().get<Pnt2f>("basic.window.position").x() < 0.0f )
    {
        WindowPos[0] = (getMainWindow()->getDesktopSize().x() - WindowSize.x()) * 0.5f;
    }
    if(getSettings().get<Pnt2f>("basic.window.position").y() < 0.0f )
    {
        WindowPos[1] = (getMainWindow()->getDesktopSize().y() - WindowSize.y()) * 0.5f;
    }

    getMainWindow()->openWindow(WindowPos,
                                WindowSize,
                                "Kabala Engine");

        
    //Store a pointer to the application thread
    //_ApplicationThread = dynamic_cast<OSG::Thread *>(OSG::ThreadManager::getAppThread());
    
    //Create the rendering thread
    //_RenderThread = OSG::dynamic_pointer_cast<OSG::Thread>(OSG::ThreadManager::the()->getThread("__KABALA_ENGINE_RENDER_THREAD", true));
    
    //Create the loading thread
    //_LoadingThread = OSG::dynamic_pointer_cast<OSG::Thread>(OSG::ThreadManager::the()->getThread("__KABALA_ENGINE_LOADING_THREAD", true));

    //Draw the loading thread
    activateLoadingScreen();

    //Load the Project file, if given
    if(OptionsVariableMap.count("project-file"))
    {
        loadProject(BoostPath(OptionsVariableMap["project-file"].as<std::string>()));
    }
    else if(getSettings().get<bool>("basic.load_most_recent_project"))
    {
        boost::optional<BoostPath> LastOpenedProjectFile = getSettings().get_optional<BoostPath>("basic.last_opened_project");
        if(LastOpenedProjectFile)
        {
            loadProject(LastOpenedProjectFile.get());
            commitChanges();
        }
    }

    if(getProject() == NULL)
    {
        //Project Failed to load, or file didn't exist
        ProjectRecPtr NewProject = createDefaultProject();
        setProject(NewProject);
    }

    //Detach the loading screen
    detachLoadingScreen();

#ifdef BUILD_WITH_WORLD_BUILDER
    if(OptionsVariableMap.count("builder"))
    {
        attachBuilder();
    }
    else 
#endif
        if(OptionsVariableMap.count("play"))
    {
        attachPlayer();
        if(OptionsVariableMap.count("debug"))
        {
            dynamic_cast<ApplicationPlayer*>(getPlayerMode())->enableDebug(true);
        }
    }
    else
    {
#ifdef BUILD_WITH_WORLD_BUILDER
        if(getSettings().get<std::string>("basic.initial_mode").compare(std::string("builder")) == 0)
        {
            attachBuilder();
        }
        else
#endif
            if(getSettings().get<std::string>("basic.initial_mode").compare(std::string("play")) == 0)
        {
            attachPlayer();
            if(OptionsVariableMap.count("debug") || getSettings().get<bool>("player.debugger.initially_active"))
            {
                dynamic_cast<ApplicationPlayer*>(getPlayerMode())->enableDebug(true);
            }
        }
        else
        {
            attachStartScreen();
        }
    }
    
    //Start the render thread on aspect 1
    //_RenderThread->runFunction(MainApplication::mainRenderLoop, 1, NULL);
    
    //Start the loading thread on aspect 2
    //_LoadingThread->runFunction(MainApplication::mainLoadingLoop, 2, NULL);

    //Main Loop
    getMainWindow()->mainLoop();

    //Exited Main Loop
    //Save Settings
    saveSettings(getSettingsLoadFile());
    
    SLOG << "Stopping Kabala Engine" << std::endl;
    OSG::indentLog(4,PLOG);
    PLOG << "Time: " << to_simple_string(boost::posix_time::second_clock::local_time()) << std::endl;

    //OSG exit
    OSG::osgExit();

    //Uninitialize logging
    uninitializeLogging();

    //Create a file to indicate if a crash occurs
    removeCrashIndicationFile();

    return 0;
}