示例#1
0
/*
	updates values needed from driver, pathfinder, etc. the are stored here, that we don't need to compute
	them several times or pass tons of parameters.
*/
void MyCar::update(TrackDesc* track, tCarElt* car, tSituation *situation)
{
	updatePos();
	updateDir();
	updateSpeedSqr();
	updateSpeed();

	/* update currentsegment and destination segment id's */
	int searchrange = MAX((int) ceil(situation->deltaTime*speed+1.0) * 2, 4);
	currentsegid = destsegid = pf->getCurrentSegment(car, searchrange);
	double l = 0.0;

	while (l < 2.0 * wheelbase) {
		l = l + pf->getPathSeg(destsegid)->getLength();
		destsegid = (destsegid + 1 + pf->getnPathSeg()) % pf->getnPathSeg();
	}

	currentseg = track->getSegmentPtr(currentsegid);
	destseg = track->getSegmentPtr(destsegid);
	currentpathseg = pf->getPathSeg(currentsegid);
	updateDError();
	int lookahead = (destsegid + (int) (MIN(LOOKAHEAD_MAX_ERROR,derror)*speed*LOOKAHEAD_FACTOR)) % pf->getnPathSeg();
	destpathseg = pf->getPathSeg(lookahead);

	mass = carmass + car->priv.fuel;
	trtime += situation->deltaTime;
	deltapitch = MAX(-track->getSegmentPtr(currentsegid)->getKgamma() - me->_pitch, 0.0);
}
示例#2
0
/*
 * Deletes a file
 */
static int cs1550_unlink(const char *path)
{

	char dir[MAX_FILENAME + 1];
	char fileName[MAX_FILENAME + 1];
	char ext[MAX_EXTENSION + 1];
	getPath(path, dir, fileName, ext);
	int pathType = getPathType(path, dir, fileName, ext);
	int fileSize = getFileSize(dir, fileName, ext, pathType);

	if (pathType < 2) {
		return -EISDIR;
	}
	else if (fileSize == -1){
		return -ENOENT;
	}
	else {
		cs1550_directory_entry parentDir;
		getDir(&parentDir, dir);
		int i =0;
		for (i = 0; i < parentDir.nFiles; i++) {
			if ((pathType==2 && strcmp(parentDir.files[i].fname, fileName)==0) || (pathType==3 && strcmp(parentDir.files[i].fname, fileName) == 0 && strcmp(parentDir.files[i].fext, ext) == 0)) {
				long startBlock = parentDir.files[i].nStartBlock;
				long seek = startBlock;
				FILE *f = fopen(".disk", "rb");
				while(seek != 0) {
					fseek(f, seek, SEEK_SET);
					cs1550_disk_block curBlock;
					fread(&curBlock, BLOCK_SIZE, 1, f);
					cs1550_disk_block empty;
					memset(&empty, 0, BLOCK_SIZE);
					writeBlock(&empty, seek);
					int index = seek / BLOCK_SIZE;
					updateBitmap(index, 0);
					if (curBlock.magic_number != 0) {
						seek = curBlock.magic_number;
					}
					else {
						seek = 0;
					}
				}
				fclose(f);
				int x =0;
				for (x = 0; x < parentDir.nFiles; x++) {
					if (x >= i && x != parentDir.nFiles-1) {
						strcpy(parentDir.files[x].fname, parentDir.files[x+1].fname);
						strcpy(parentDir.files[x].fext, parentDir.files[x+1].fext);
						parentDir.files[x].fsize = parentDir.files[x+1].fsize;
						parentDir.files[x].nStartBlock = parentDir.files[x+1].nStartBlock;
					}
				}
				parentDir.nFiles--;
				updateDir(&parentDir, dir);
			}
		}
	}
  return 0;
}
示例#3
0
void OtherCar::update()
{
	updatePos();
	updateDir();
	updateSpeedSqr();
	updateSpeed();

    int searchrange = MAX((int) ceil(dt*speed+1.0) * 2, 4);
	currentsegid = track->getCurrentSegment(getCarPtr(), currentsegid, searchrange);
}
示例#4
0
void GLWidget::panView(const QPoint& newPos) {           
    float dx = (float)(newPos.x() - _oldMousePos.x()) / (float)_width;
    float dy = (float)(newPos.y() - _oldMousePos.y()) / (float)_height;
    _oldMousePos = newPos;
    float length = 2* (_eye-_center).norm() * tan( (_fovy/360)*2*PI /2);
    updateDir();
    P3<float> y_pan = _diry * ( dx*length* (float)_width/(float)_height );
    P3<float> x_pan = _dirx * ( dy*length ); 
    _center += y_pan + x_pan; 
    _eye += y_pan + x_pan;
    updateGL();
}
示例#5
0
void OtherCar::init(TrackDesc* itrack, tCarElt* car, tSituation *situation)
{
	track = itrack;
	dt = situation->deltaTime;
	setCarPtr(car);
	currentsegid = track->getCurrentSegment(car);

	initCGh();
	updatePos();
	updateDir();
	updateSpeedSqr();
	updateSpeed();
}
示例#6
0
bool SyncProcess::run()
{
  if (!QFile::exists(folder1)) {
    QMessageBox::warning(NULL, QObject::tr("Synchronization error"), QObject::tr("The directory '%1' doesn't exist!").arg(folder1));
    return true;
  }

  if (!QFile::exists(folder2)) {
    QMessageBox::warning(NULL, QObject::tr("Synchronization error"), QObject::tr("The directory '%1' doesn't exist!").arg(folder2));
    return true;
  }

  count = getFilesCount(folder1) + getFilesCount(folder2);
  progress->setMaximum(count);

  QStringList errors = updateDir(folder1, folder2) + updateDir(folder2, folder1);
  if (errors.count() > 0) {
    QMessageBox::warning(NULL, QObject::tr("Synchronization error"), errors.join("\n"));
  }

  // don't close the window unless the user wanted
  return closed;
}
示例#7
0
/*!
  \fn QString Qtopia::defaultButtonsFile()
  \internal

  Return the name of the defaultbuttons.conf file.
  This allows Qt Extended to use a QVFb-supplied defaultbuttons.conf file
  (if one exists).
*/
QString Qtopia::defaultButtonsFile()
{
    QString r;
#if !defined(QTOPIA_HOST) && !defined(QT_NO_QWS_VFB)
    r = QString("/tmp/qtembedded-%1/defaultbuttons.conf").arg(qtopia_display_id());
    if ( QFileInfo(r).exists() )
        return r;
#endif
    r = updateDir() + "etc/defaultbuttons.conf";
    if (QFileInfo(r).exists())
        return r;

    return qtopiaDir()+"etc/defaultbuttons.conf";
}
示例#8
0
void AutoUpdater::checkUpdatesAsyncInteractiveWorker()
{
    if (!isUpdateAvailable())
        return;

    // If there's already an update dir, resume updating, otherwise ask the user
    QString updateDirStr = Settings::getInstance().getSettingsDirPath() + "/update/";
    QDir updateDir(updateDirStr);

    if ((updateDir.exists() && QFile(updateDirStr+"flist").exists())
            || GUI::askQuestion(QObject::tr("Update", "The title of a message box"),
        QObject::tr("An update is available, do you want to download it now?\nIt will be installed when qTox restarts."), true, false))
    {
        downloadUpdate();
    }
}
示例#9
0
void GLWidget::rotateView(const QPoint& newPos) {
    float dx = (float)(newPos.x() - _oldMousePos.x()) / (float)_width;
    float dy = (float)(newPos.y() - _oldMousePos.y()) / (float)_height;
    _oldMousePos = newPos;
    updateDir();
    // rotate eye around center
    _eye.rotate(_center, _dirx, -dx * PI );
    _eye.rotate(_center, _diry, dy*PI );
    
    // now calculate the new up-vector
    P3<float> upCenter = _center + _up;
    upCenter.rotate( _center , _diry, dy*PI);
    _up = upCenter - _center;
    _up *= 1.0/_up.norm();
    
    updateGL();
}
示例#10
0
bool AutoUpdater::isLocalUpdateReady()
{
    // Updates only for supported platforms
    if (platform.isEmpty())
        return false;

    // Check that there's an update dir in the first place, valid or not
    QString updateDirStr = Settings::getInstance().getSettingsDirPath() + "/update/";
    QDir updateDir(updateDirStr);
    if (!updateDir.exists())
        return false;

    // Check that we have a flist and generate a diff
    QFile updateFlistFile(updateDirStr+"flist");
    if (!updateFlistFile.open(QIODevice::ReadOnly))
        return false;
    QByteArray updateFlistData = updateFlistFile.readAll();
    updateFlistFile.close();

    QList<UpdateFileMeta> updateFlist = parseFlist(updateFlistData);
    QList<UpdateFileMeta> diff = genUpdateDiff(updateFlist);

    // If the update wasn't downloaded correctly, redownload it
    // We don't check signatures to not block qTox too long, the updater will do it anyway
    for (UpdateFileMeta fileMeta : diff)
    {
        if (!QFile::exists(updateDirStr+fileMeta.installpath))
        {
            QtConcurrent::run(&AutoUpdater::downloadUpdate);
            return false;
        }

        QFile f(updateDirStr+fileMeta.installpath);
        if (f.size() != (int64_t)fileMeta.size)
        {
            QtConcurrent::run(&AutoUpdater::downloadUpdate);
            return false;
        }
    }

    return true;
}
示例#11
0
GLWidget::GLWidget( QWidget *parent, char *name ) 
  : QGLWidget(parent) {
    timer = new QTimer(this);
    timer->setInterval(1000);
    connect( timer, SIGNAL(timeout()), this, SLOT(timeOutSlot()) );
    timer->start();
    _fovy = 60.0;
    z_near = 0.1;
    z_far = 100.0;
    _up.x=0;
    _up.y=1;
    _up.z=0;
    _up *= 1/_up.norm();
    _eye.x=0;
    _eye.y=0;
    _eye.z=6;
    _center.x=0;
    _center.y=0;
    _center.z=0;
    //setCursor(cursor);
    updateDir();
}
示例#12
0
bool AutoUpdater::isLocalUpdateReady()
{
    // Updates only for supported platforms
    if (platform.isEmpty())
        return false;

    if (isDownloadingUpdate)
        return false;

    // Check that there's an update dir in the first place, valid or not
    QString updateDirStr = Settings::getInstance().getSettingsDirPath() + "/update/";
    QDir updateDir(updateDirStr);
    if (!updateDir.exists())
        return false;

    // Check that we have a flist and generate a diff
    QFile updateFlistFile(updateDirStr+"flist");
    if (!updateFlistFile.open(QIODevice::ReadOnly))
        return false;
    QByteArray updateFlistData = updateFlistFile.readAll();
    updateFlistFile.close();

    QList<UpdateFileMeta> updateFlist = parseFlist(updateFlistData);
    QList<UpdateFileMeta> diff = genUpdateDiff(updateFlist);

    // Check that we have every file
    for (UpdateFileMeta fileMeta : diff)
    {
        if (!QFile::exists(updateDirStr+fileMeta.installpath))
            return false;

        QFile f(updateDirStr+fileMeta.installpath);
        if (f.size() != (int64_t)fileMeta.size)
            return false;
    }

    return true;
}
示例#13
0
void AutoUpdater::checkUpdatesAsyncInteractiveWorker()
{
    if (!isUpdateAvailable())
        return;

    // If there's already an update dir, resume updating, otherwise ask the user
    QString updateDirStr = Settings::getInstance().getSettingsDirPath() + "/update/";
    QDir updateDir(updateDirStr);



    if (updateDir.exists() && QFile(updateDirStr+"flist").exists())
    {
        setProgressVersion(getUpdateVersion().versionString);
        downloadUpdate();
        return;
    }

    VersionInfo newVersion = getUpdateVersion();
    QString contentText = QObject::tr("An update is available, do you want to download it now?\n"
                                      "It will be installed when qTox restarts.");
    if (!newVersion.versionString.isEmpty())
        contentText += "\n\n" + QObject::tr("Version %1, %2").arg(newVersion.versionString,
                                QDateTime::fromMSecsSinceEpoch(newVersion.timestamp*1000).toString());


    if (abortFlag)
        return;

    if (GUI::askQuestion(QObject::tr("Update", "The title of a message box"),
                              contentText, true, false))
    {
        setProgressVersion(newVersion.versionString);
        GUI::showUpdateDownloadProgress();
        downloadUpdate();
    }
}
示例#14
0
bool AutoUpdater::downloadUpdate()
{
    // Updates only for supported platforms
    if (platform.isEmpty())
        return false;

    // Get a list of files to update
    QByteArray newFlistData = getUpdateFlist();
    QList<UpdateFileMeta> newFlist = parseFlist(newFlistData);
    QList<UpdateFileMeta> diff = genUpdateDiff(newFlist);

    if (abortFlag)
        return false;

    qDebug() << "AutoUpdater: Need to update "<<diff.size()<<" files";

    // Create an empty directory to download updates into
    QString updateDirStr = Settings::getInstance().getSettingsDirPath() + "/update/";
    QDir updateDir(updateDirStr);
    if (updateDir.exists())
        updateDir.removeRecursively();
    QDir().mkdir(updateDirStr);
    updateDir = QDir(updateDirStr);
    if (!updateDir.exists())
    {
        qWarning() << "AutoUpdater::downloadUpdate: Can't create update directory, aborting...";
        return false;
    }

    // Write the new flist for the updater
    QFile newFlistFile(updateDirStr+"flist");
    if (!newFlistFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        qWarning() << "AutoUpdater::downloadUpdate: Can't save new flist file, aborting...";
        return false;
    }
    newFlistFile.write(newFlistData);
    newFlistFile.close();

    // Download and write each new file
    for (UpdateFileMeta fileMeta : diff)
    {
        if (abortFlag)
            return false;

        qDebug() << "AutoUpdater: Downloading '"+fileMeta.installpath+"' ...";

        // Create subdirs if necessary
        QString fileDirStr{QFileInfo(updateDirStr+fileMeta.installpath).absolutePath()};
        if (!QDir(fileDirStr).exists())
            QDir().mkpath(fileDirStr);

        // Download
        UpdateFile file = getUpdateFile(fileMeta);
        if (abortFlag)
            return false;
        if (file.data.isNull())
        {
            qWarning() << "AutoUpdater::downloadUpdate: Error downloading a file, aborting...";
            return false;
        }

        // Check signature
        if (crypto_sign_verify_detached(file.metadata.sig, (unsigned char*)file.data.data(),
                                        file.data.size(), key) != 0)
        {
            qCritical() << "AutoUpdater: downloadUpdate: RECEIVED FORGED FILE, aborting...";
            return false;
        }

        // Save
        QFile fileFile(updateDirStr+fileMeta.installpath);
        if (!fileFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
        {
            qWarning() << "AutoUpdater::downloadUpdate: Can't save new update file, aborting...";
            return false;
        }
        fileFile.write(file.data);
        fileFile.close();
    }

    return true;
}
示例#15
0
MyCar::MyCar(TrackDesc* track, tCarElt* car, tSituation *situation)
{
    AEROMAGIC = GfParmGetNum(car->_carHandle, BERNIW_SECT_PRIV, BERNIW_ATT_AMAGIC, (char*)NULL, 1.6f);
	CFRICTION = GfParmGetNum(car->_carHandle, BERNIW_SECT_PRIV, BERNIW_ATT_FMAGIC, (char*)NULL, 1.0f);

	/* init pointer to car data */
	setCarPtr(car);
	initCGh();
	initCarGeometry();
	updatePos();
	updateDir();
	updateSpeedSqr();
	updateSpeed();

	/* damage and fuel status */
	lastfuel = GfParmGetNum(car->_carHandle, SECT_CAR, PRM_FUEL, NULL, 100.0);
	undamaged = situation->_maxDammage;
	if (undamaged == 0) undamaged = 10000;
	MAXDAMMAGE = undamaged / 2;
	fuelperlap = 0.0;
	lastpitfuel = 0.0;

	/* set up some car properties */
	wheelbase = car->priv.wheel[FRNT_RGT].relPos.x - car->priv.wheel[REAR_RGT].relPos.x;
	wheeltrack = 2* fabs(car->priv.wheel[REAR_RGT].relPos.y);

	carmass = GfParmGetNum(car->_carHandle, SECT_CAR, PRM_MASS, NULL, 0.0);
	mass = carmass + lastfuel;

	/* which wheels are driven */
	char *traintype = GfParmGetStr(car->_carHandle, SECT_DRIVETRAIN, PRM_TYPE, VAL_TRANS_RWD);
	if (strcmp(traintype, VAL_TRANS_RWD) == 0) {
		drivetrain = DRWD;
	} else if (strcmp(traintype, VAL_TRANS_FWD) == 0) {
		drivetrain = DFWD;
	} else if (strcmp(traintype, VAL_TRANS_4WD) == 0) {
		drivetrain = D4WD;
	}

	updateCa();

	double cx = GfParmGetNum(car->_carHandle, SECT_AERODYNAMICS, PRM_CX, (char*)NULL, 0.0);
	double frontarea = GfParmGetNum(car->_carHandle, SECT_AERODYNAMICS, PRM_FRNTAREA, (char*)NULL, 0.0);
	cw = 0.625*cx*frontarea;

	cgcorr_b = 0.46;

	pf = new Pathfinder(track, car, situation);
	currentsegid = destsegid = pf->getCurrentSegment(car);

	currentseg = track->getSegmentPtr(currentsegid);
	destseg = track->getSegmentPtr(destsegid);
	currentpathseg = pf->getPathSeg(currentsegid);
	destpathseg = pf->getPathSeg(destsegid);

	turnaround = 0.0;
    tr_mode = 0;
	accel = 1.0;
	fuelchecked = false;
	startmode = true;
	trtime = 0.0;
	derror = 0.0;

	/*
		DIST; MAXRELAX; MAXANGLE; ACCELINC; SPEEDSQRFACTOR; GCTIME; ACCELLIMIT; PATHERRFACTOR
	*/

	double ba[6][8] = {
		{1.2, 0.9, 25.0, 0.1, 1.2, 0.2, 1.0, 5.0},
		{1.2, 0.9, 20.0, 0.1, 1.1, 0.5, 1.0, 5.0},
		{1.2, 0.9, 15.0, 0.1, 1.0, 0.5, 1.0, 5.0},
		{1.3, 0.9, 15.0, 0.02, 0.98, 0.5, 1.0, 5.0},
		{1.6, 0.9, 15.0, 0.01, 0.95, 0.5, 1.0, 5.0},
		{1.2, 0.9, 45.0, 0.1, 1.0, 0.5, 1.0, 1.0}
	};

	for (int i = 0; i < 6; i++) {
		for (int j = 0; j < 8; j++) {
			behaviour[i][j] = ba[i][j];
		}
	}

	loadBehaviour(NORMAL);

	/* this call is needed! perhaps i shold move it into the constructor of pathfinder. */
	pf->plan(this);
}
示例#16
0
/*
 * Write size bytes from buf into file starting from offset
 *
 */
static int cs1550_write(const char *path, const char *buf, size_t size,
			  off_t offset, struct fuse_file_info *fi)
{
	int ret = 0;
	(void) fi;

	char dir[MAX_FILENAME + 1];
	char fileName[MAX_FILENAME + 1];
	char ext[MAX_EXTENSION + 1];
	getPath(path, dir, fileName, ext);
	int pathType = getPathType(path, dir, fileName, ext);
	int fileSize = getFileSize(dir, fileName, ext, pathType);

	if (dirExists(dir) == 1 && pathType >= 2 && fileSize != -1 && size > 0) {
		cs1550_directory_entry parentDir;
		getDir(&parentDir, dir);
		int i =0;
		for (i = 0; i < parentDir.nFiles; i++) {
			if ((pathType==2 && strcmp(parentDir.files[i].fname, fileName)==0) || (pathType==3 && strcmp(parentDir.files[i].fname, fileName) == 0 && strcmp(parentDir.files[i].fext, ext) == 0)) {
				if (offset > parentDir.files[i].fsize) {
					return -EFBIG;
				}
				else {
					long startBlock = parentDir.files[i].nStartBlock;
					int blockNum = offset / BLOCK_SIZE;

					long seek = startBlock;
					long bStart = 0;
					FILE *f = fopen(".disk", "rb+");
					int j = 0;
					for (j = 0; j <= blockNum; j++) {
						bStart = seek;
						fseek(f, seek, SEEK_SET);
						cs1550_disk_block fileBlock;
						fread(&fileBlock, BLOCK_SIZE, 1, f);
						seek = fileBlock.magic_number;
					}
					rewind(f);
					int off = (int)offset - (blockNum * BLOCK_SIZE);
					int index;
					int count = off;
					seek = bStart;
					fseek(f, seek, SEEK_SET);
					cs1550_disk_block curBlock;
					fread(&curBlock, BLOCK_SIZE, 1, f);
					for (index = 0; index < strlen(buf); index++) {
						if (count < MAX_DATA_IN_BLOCK) {
							curBlock.data[count] = (char)buf[index];
							count++;
						}
						else {
							count = 0;
							if (curBlock.magic_number != 0) {
								writeBlock(&curBlock, seek);
								seek = curBlock.magic_number;
								fseek(f, seek, SEEK_SET);
								fread(&curBlock, BLOCK_SIZE, 1, f);
							}
							else {
								long cSeek = seek;
								int nextBlock = getNextBlock();
								seek = nextBlock * BLOCK_SIZE;
								curBlock.magic_number = seek;
								writeBlock(&curBlock, cSeek);
								fseek(f, seek, SEEK_SET);
								fread(&curBlock, BLOCK_SIZE, 1, f);
								updateBitmap(nextBlock, 1);
							}
						}
						if (index == strlen(buf)-1) {
							writeBlock(&curBlock, seek);
							count = 0;
						}
					}
					fclose(f);
					int old = parentDir.files[i].fsize;
					int newSize =  (size - (old - offset)) + (old - (old - offset));
					parentDir.files[i].fsize = newSize;
					updateDir(&parentDir, dir);
					ret = newSize;
				}
			}
		}
	}
	return ret;
}
示例#17
0
void updateDir(Node &node){
	if(node.next != nullptr){
	updateDir(*node.next);
	node.next->dir = node.dir;
	}
}
示例#18
0
int main(){
	Node* head = new Node(SIZE / 2,SIZE/2,UP);
	head->next = new Node(SIZE/2,SIZE/2-1,UP);
	head->next->next = new Node(SIZE/2,SIZE/2 - 2,UP);
	head->next->next->next = new Node(SIZE/2,SIZE/2-3,UP);
	head->next->next->next->next = new Node(SIZE/2,SIZE/2-4,UP);
	head->next->next->next->next->next = nullptr;
	float speed = 150;
	sf::SoundBuffer soundBuffer;
	soundBuffer.loadFromFile("boop.wav");
	sf::Sound sound;
	sound.setBuffer(soundBuffer);
	gameOver = false;
	  srand (time(NULL));

	//sq[32][32] = UP;
	//sq[32][31] = UP;
	//sq[32][30] = UP;
	//sq[32][29] = UP;
	//sq[32][28] = UP;
	for(int x = 0; x <SIZE; x++){
		for( int y = 0; y < SIZE; y++){
			blacklist[x][y] = false;
		}
	}
	

	sf::RenderWindow window(sf::VideoMode(640, 640, 32), "Snake", sf::Style::Titlebar | sf::Style::Close);
	sf::Clock clock;
	clock.restart();
	sf::Event windowEvent;
	renderTexture.create(640,640);
	renderTexture.display();
	sf::Texture gameOverScreen;
	gameOverScreen.loadFromFile("gameover.png", sf::IntRect(320,192,640,640));
	sf::Sprite sprite;
	sprite.setTexture(gameOverScreen);
	bool upPress, downPress, leftPress, rightPress = false;
	int addCount = 0;
	int soundCount = 0;

	while(window.isOpen()){
		bool anyEvent = false ;
		while (window.pollEvent(windowEvent))
		{//Event Handling
			anyEvent = true;
			switch (windowEvent.type)
			{
				//running = false;
			case sf::Event::KeyPressed:
				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
					//std::cout << "left" << leftPress <<"\n";
					if(head->dir != RIGHT && !leftPress){
						head->dir = LEFT;
						leftPress = true;
					}
				}else{
					leftPress = false;
				}

				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
					//std::cout << "right\n";
					if(head->dir != LEFT && !rightPress){
						head->dir = RIGHT;
						rightPress = true;
					}
				}else{
					//std::cout << "rightcall";
					rightPress = false;
				}

				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)){//inverted
					//std::cout << "down\n";
					if(head->dir != DOWN && !upPress){
						head->dir = UP;
						upPress = true;
					}
				}else{
					upPress = false;
				}


				if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){//inverted
					//std::cout << "up\n";
					if(head->dir != UP && !downPress){
						head->dir = DOWN;
						downPress = true;
					}
				}else{
					downPress = false;
				}

				break;

			case sf::Event::Closed:
				//delete head;
				window.close();
				break;

			}
		}//\EventHandling
		if(!anyEvent){
			leftPress = false;
			rightPress = false;
			upPress = false;
			downPress = false;
		}
		anyEvent = false;


		//for(int x = 0; x < 64; ++x){
		//	for(int y = 0; y < 64; ++y){
		sf::Time t = clock.getElapsedTime();
		if(t.asMilliseconds() > speed){
			updatePos(*head);
			updateDir(*head);
			soundCount++;
			if(soundCount > 5){
				sound.play();
				soundCount = 0;
			}
			clock.restart();
			if(!gameOver)
				gameOver = !checkBounds(*head);
			checkIntersect(*head);//gen blacklist
			if(addCount > 0){
				--addCount;
				Node* end = getEnd(*head);
				switch(end->dir){
				case UP:
					end->next = new Node(end->x, end->y - 1, end->dir);//backwards
					break;
				case DOWN:
					end->next = new Node(end->x, end->y + 1, end->dir);//backwards
					break;
				case LEFT:
					end->next = new Node(end->x + 1, end->y, end->dir);//backwards
					break;
				case RIGHT:
					end->next = new Node(end->x - 1, end->y, end->dir);//backwards
					break;}
				end->next->next = nullptr;
			}

			if(newFood){
				addCount = 4;
				if(speed >100){
				speed *= .95;
				//sound.setPitch(sound.getPitch()*1.1);
				}
				foodX = rand() % SIZE;
				foodY = rand() % SIZE;
				while(blacklist[foodX][foodY] == true){
					foodX = rand() % SIZE;
					foodY = rand() % SIZE;
				}

				newFood = false;
			}
		}
		if(gameOver){
			window.draw(sprite);
			window.display();
			gameOver = false;
			sf::Time t = sf::seconds(.5);
			for(int i = 0; i < 6; ++i)
			sf::sleep(t);
			delete head->next;
			head->x = SIZE/2;
			head->y = SIZE/2;
			head->next = new Node(SIZE/2,SIZE/2-1,UP);
			head->next->next = new Node(SIZE/2,SIZE/2 - 2,UP);
			head->next->next->next = new Node(SIZE/2,SIZE/2-3,UP);
			head->next->next->next->next = new Node(SIZE/2,SIZE/2-4,UP);
			head->next->next->next->next->next = nullptr;
			float speed = 150;
			foodX = SIZE*.75;
			foodY = SIZE*.75;
			newFood = false;
		}
		if(!gameOver){
			displaySnake(*head);
			
			sf::RectangleShape draw1 = sf::RectangleShape(sf::Vector2f(640/SIZE,640/SIZE));
			draw1.setPosition(sf::Vector2f(foodX * (640/SIZE), foodY * (640/SIZE)));
			draw1.setFillColor(sf::Color::White);
			renderTexture.draw(draw1);
		}
		sf::Texture texture = renderTexture.getTexture();
		// draw it to the window
		sf::Sprite sprite(texture);
		window.draw(sprite);
		window.display();
		renderTexture.clear();
		for(int x = 0; x < SIZE; x++){
			for( int y = 0; y < SIZE; y++){
				blacklist[x][y] = false;
			}
		}
	}
}
示例#19
0
文件: mycar.cpp 项目: COHRINT/cuTORCS
MyCar::MyCar(TrackDesc* track, tCarElt* car, tSituation *situation)
{
    AEROMAGIC = GfParmGetNum(car->_carHandle, BERNIW_SECT_PRIV, BERNIW_ATT_AMAGIC, (char*)NULL, 1.6f);
	CFRICTION = GfParmGetNum(car->_carHandle, BERNIW_SECT_PRIV, BERNIW_ATT_FMAGIC, (char*)NULL, 1.0f);

	setCarPtr(car);
	initCGh();
	initCarGeometry();
	updatePos();
	updateDir();
	updateSpeedSqr();
	updateSpeed();

	// Damage and fuel status.
	lastfuel = GfParmGetNum(car->_carHandle, SECT_CAR, PRM_FUEL, NULL, 100.0);
	undamaged = situation->_maxDammage;
	if (undamaged == 0) {
		undamaged = 10000;
	}
	MAXDAMMAGE = undamaged / 2;
	fuelperlap = 0.0;
	lastpitfuel = 0.0;

	// Set up some car properties.
	wheelbase = car->priv.wheel[FRNT_RGT].relPos.x - car->priv.wheel[REAR_RGT].relPos.x;
	wheeltrack = 2* fabs(car->priv.wheel[REAR_RGT].relPos.y);

	carmass = GfParmGetNum(car->_carHandle, SECT_CAR, PRM_MASS, NULL, 0.0);
	mass = carmass + lastfuel;

	// Which wheels are driven.
	const char *traintype = GfParmGetStr(car->_carHandle, SECT_DRIVETRAIN, PRM_TYPE, VAL_TRANS_RWD);
	if (strcmp(traintype, VAL_TRANS_RWD) == 0) {
		drivetrain = DRWD;
	} else if (strcmp(traintype, VAL_TRANS_FWD) == 0) {
		drivetrain = DFWD;
	} else if (strcmp(traintype, VAL_TRANS_4WD) == 0) {
		drivetrain = D4WD;
	}

	updateCa();
	double cx = GfParmGetNum(car->_carHandle, SECT_AERODYNAMICS, PRM_CX, (char*)NULL, 0.0);
	double frontarea = GfParmGetNum(car->_carHandle, SECT_AERODYNAMICS, PRM_FRNTAREA, (char*)NULL, 0.0);
	cw = 0.625*cx*frontarea;

	// Get PGAIN.
	STEER_P_CONTROLLER_GAIN = GfParmGetNum(car->_carHandle, BERNIW_SECT_PRIV, BERNIW_ATT_STEERPGAIN, (char*)NULL, 0.02f);
	STEER_P_CONTROLLER_MAX = GfParmGetNum(car->_carHandle, BERNIW_SECT_PRIV, BERNIW_ATT_STEERPGAIN_MAX, (char*)NULL, 0.1f);
	//printf("PC: %f, %f\n", STEER_P_CONTROLLER_GAIN, STEER_P_CONTROLLER_MAX);
	// Magic number for friction in pit lane, because the current code does not consider the pit surface.
	// TODO: Consider the pit surface properties.
	cgcorr_b = 0.46;

	pf = new Pathfinder(track, car, situation);
	currentsegid = destsegid = pf->getCurrentSegment(car);

	currentseg = track->getSegmentPtr(currentsegid);
	destseg = track->getSegmentPtr(destsegid);
	currentpathsegid = currentsegid;
	destpathsegid = destsegid;
	dynpath = pf->getPath();

	turnaround = 0.0;
    tr_mode = 0;
	accel = 1.0;
	fuelchecked = false;
	startmode = true;
	trtime = 0.0;
	derror = 0.0;
	clutchtime = 0.0;

	// DIST; MAXRELAX; MAXANGLE; ACCELINC; SPEEDSQRFACTOR; GCTIME; ACCELLIMIT; PATHERRFACTOR
	double ba[6][8] = {
		{1.2, 0.9, 25.0, 0.1, 1.2, 0.2, 1.0, 5.0},
		{1.2, 0.9, 20.0, 0.1, 1.1, 0.5, 1.0, 5.0},
		{1.2, 0.9, 15.0, 0.1, 1.0, 0.5, 1.0, 5.0},
		{1.3, 0.9, 15.0, 0.02, 0.98, 0.5, 1.0, 5.0},
		{1.6, 0.9, 15.0, 0.01, 0.95, 0.5, 1.0, 5.0},
		{1.2, 0.9, 45.0, 0.1, 1.0, 0.5, 1.0, 1.0}
	};

	for (int i = 0; i < 6; i++) {
		for (int j = 0; j < 8; j++) {
			behaviour[i][j] = ba[i][j];
		}
	}

	loadBehaviour(NORMAL);

	// Init optimal trajectory.
	pf->plan(this, currentsegid);
}
示例#20
0
XJudgerMain::XJudgerMain(QMainWindow *parent): QMainWindow(parent){
	//Basic Building
	CurrentDir = getCwd();
	if (objectName().isEmpty()) setObjectName("XJudgerMain");
	setGeometry((QApplication::desktop() -> width() - 800) / 2, (QApplication::desktop() -> height() - 600) / 2, 800, 600);
	QIcon WindowIcon;
	setWindowIcon(QIcon(":/Icons/XJudgerMain.png"));
    MainActionExit = new QAction(this);
    MainActionExit -> setObjectName("MainActionExit");
	MainActionAbout = new QAction(this);
	MainActionAbout -> setObjectName("MainActionAbout");
    CentralWidget = new QWidget(this);
    CentralWidget -> setObjectName("CentralWidget");
    TestForm = new XJudgerTest(this);
	ViewForm = new XJudgerView(this);
	setCentralWidget(CentralWidget);
    MenuBar = new QMenuBar(this);
    MenuBar -> setObjectName("MenuBar");
    MainMenuFile = new QMenu(MenuBar);
    MainMenuFile -> setObjectName("MainMenuFile");
	MainMenuHelp = new QMenu(MenuBar);
	MainMenuHelp -> setObjectName("MainMenuHelp");
    setMenuBar(MenuBar);
    StatusBar = new QStatusBar(this);
    StatusBar -> setObjectName("StatusBar");
    setStatusBar(StatusBar);
    MenuBar -> addAction(MainMenuFile -> menuAction());
    MainMenuFile -> addAction(MainActionExit);
    MenuBar -> addAction(MainMenuHelp -> menuAction());
	MainMenuHelp -> addAction(MainActionAbout);
	MainTab = new QTabWidget(this);
	MainTab -> setObjectName("MainTab");
	DataConfig = new DataInfo(CurrentDir);
	LayoutMain = new QGridLayout(CentralWidget);
	LayoutMain -> setObjectName("LayoutMain");
	LayoutMain -> addWidget(MainTab, 0, 0, 0, 0);
	
	//Building TabData
	TabData = new QWidget;
	TabData -> setObjectName(QString::fromUtf8("TabData"));
	MainTab -> addTab(TabData, QString::fromUtf8("Data"));
	GroupViewProb = new QGroupBox(TabData);
	GroupViewProb -> setObjectName(QString::fromUtf8("GroupViewProb"));
	GroupViewCase = new QGroupBox(TabData);
	GroupViewCase -> setObjectName(QString::fromUtf8("GroupViewCase"));
	GroupViewData = new QGroupBox(TabData);
	GroupViewData -> setObjectName(QString::fromUtf8("GroupViewData"));
	MainViewData = new TreeView(GroupViewData);
	MainViewData -> setObjectName(QString::fromUtf8("MainViewData"));
	MainViewData -> setMaximumWidth(200);

	TextProbName = new QPlainTextEdit(GroupViewProb);
	TextProbName -> setObjectName("TextProbName");
	TextProbName -> setMaximumHeight(30);
	TextProbName -> setTabChangesFocus(1);
	LabelProb = new QLabel(GroupViewProb);
	LabelProb -> setObjectName("LabelProb");
	LabelProb -> setText("Problem Name: ");
	TextInput = new QPlainTextEdit(GroupViewProb);
	TextInput -> setObjectName("TextInput");
	TextInput -> setMaximumHeight(30);
	TextInput -> setTabChangesFocus(1);
	LabelInput = new QLabel(GroupViewProb);
	LabelInput -> setObjectName("LabelInput");
	LabelInput -> setText("Input File Name: ");
	TextOutput = new QPlainTextEdit(GroupViewProb);
	TextOutput -> setObjectName("TextOutput");
	TextOutput -> setMaximumHeight(30);
	TextOutput -> setTabChangesFocus(1);
	LabelOutput = new QLabel(GroupViewProb);
	LabelOutput -> setObjectName("LabelOutput");
	LabelOutput -> setText("Output File Name: ");
	TextSource = new QPlainTextEdit(GroupViewProb);
	TextSource -> setObjectName("TextSource");
	TextSource -> setMaximumHeight(30);
	TextSource -> setTabChangesFocus(1);
	LabelSource = new QLabel(GroupViewProb);
	LabelSource -> setObjectName("LabelSource");
	LabelSource -> setText("Source File Name: ");
	
	LabelCaseInput = new QLabel(GroupViewCase);
	LabelCaseInput -> setObjectName("LabelCaseInput");
	LabelCaseInput -> setText("Input File Name: ");
	TextCaseInput = new QPlainTextEdit(GroupViewCase);
	TextCaseInput -> setObjectName("TextCaseInput");
	TextCaseInput -> setMaximumHeight(30);
	TextCaseInput -> setTabChangesFocus(1);
	LabelCaseOutput = new QLabel(GroupViewCase);
	LabelCaseOutput -> setObjectName("LabelCaseOutput");
	LabelCaseOutput -> setText("Output File Name: ");
	TextCaseOutput = new QPlainTextEdit(GroupViewProb);
	TextCaseOutput -> setObjectName("TextCaseOutput");
	TextCaseOutput -> setMaximumHeight(30);
	TextCaseOutput -> setTabChangesFocus(1);
	LabelCaseScore = new QLabel(GroupViewCase);
	LabelCaseScore -> setObjectName("LabelCaseScore");
	LabelCaseScore -> setText("Score: ");
	TextCaseScore = new QPlainTextEdit(GroupViewCase);
	TextCaseScore -> setObjectName("TextCaseScore");
	TextCaseScore -> setMaximumHeight(30);
	TextCaseScore -> setTabChangesFocus(1);
	LabelCaseTL = new QLabel(GroupViewCase);
	LabelCaseTL -> setObjectName("LabelCaseTL");
	LabelCaseTL -> setText("Time Limit (second): ");
	TextCaseTL = new QPlainTextEdit(GroupViewCase);
	TextCaseTL -> setObjectName("TextCaseTL");
	TextCaseTL -> setMaximumHeight(30);
	TextCaseTL -> setTabChangesFocus(1);
	LabelCaseML = new QLabel(GroupViewCase);
	LabelCaseML -> setObjectName("LabelCaseML");
	LabelCaseML -> setText("Memory Limit (kb): ");
	TextCaseML = new QPlainTextEdit(GroupViewCase);
	TextCaseML -> setObjectName("TextCaseML");
	TextCaseML -> setMaximumHeight(30);
	TextCaseML -> setTabChangesFocus(1);

	LayoutTabData = new QGridLayout(TabData);
	LayoutTabData -> setObjectName("LayoutTabData");
	LayoutTabData -> addWidget(GroupViewData, 0, 0, 10, 1, Qt::AlignLeft);
	LayoutTabData -> addWidget(GroupViewProb, 0, 1, 10, 1, Qt::AlignTop);
	LayoutTabData -> addWidget(GroupViewCase, 0, 1, 10, 1, Qt::AlignTop);
	GroupViewProb -> setVisible(0);
	GroupViewCase -> setVisible(0);
	LayoutGroupProb = new QGridLayout(GroupViewProb);
	LayoutGroupProb -> setObjectName("LayoutGroupProb");
	LayoutGroupProb -> addWidget(TextProbName, 0, 1, 1, 1);
	LayoutGroupProb -> addWidget(LabelProb, 0, 0, 1, 1);
	LayoutGroupProb -> addWidget(TextInput, 1, 1, 1, 1);
	LayoutGroupProb -> addWidget(LabelInput, 1, 0, 1, 1);
	LayoutGroupProb -> addWidget(TextOutput, 2, 1, 1, 1);
	LayoutGroupProb -> addWidget(LabelOutput, 2, 0, 1, 1);
	LayoutGroupProb -> addWidget(TextSource, 3, 1, 1, 1);
	LayoutGroupProb -> addWidget(LabelSource, 3, 0, 1, 1);
	LayoutGroupProb -> setSizeConstraint(QLayout::SetMinAndMaxSize);
	LayoutGroupData = new QGridLayout(GroupViewData);
	LayoutGroupData -> setObjectName("LayoutGroupData");
	LayoutGroupData -> setSizeConstraint(QLayout::SetMinAndMaxSize);
	LayoutGroupData -> addWidget(MainViewData, 0, 0, 1, 1);
	LayoutGroupCase = new QGridLayout(GroupViewCase);
	LayoutGroupCase -> setObjectName("LayoutGroupCase");
	LayoutGroupCase -> addWidget(TextCaseInput, 0, 1, 1, 1);
	LayoutGroupCase -> addWidget(LabelCaseInput, 0, 0, 1, 1);
	LayoutGroupCase -> addWidget(TextCaseOutput, 1, 1, 1, 1);
	LayoutGroupCase -> addWidget(LabelCaseOutput, 1, 0, 1, 1);
	LayoutGroupCase -> addWidget(TextCaseScore, 2, 1, 1, 1);
	LayoutGroupCase -> addWidget(LabelCaseScore, 2, 0, 1, 1);
	LayoutGroupCase -> addWidget(TextCaseTL, 3, 1, 1, 1);
	LayoutGroupCase -> addWidget(LabelCaseTL, 3, 0, 1, 1);
	LayoutGroupCase -> addWidget(TextCaseML, 4, 1, 1, 1);
	LayoutGroupCase -> addWidget(LabelCaseML, 4, 0, 1, 1);
	
	//Building TabTest
	TabTest = new QWidget;
	TabTest -> setObjectName(QString::fromUtf8("TabTest"));
	MainTab -> addTab(TabTest, QString::fromUtf8("Test"));
	MainViewScore = new TreeView(TabTest);
	MainViewScore -> setObjectName(QString::fromUtf8("MainViewScore"));
	MainViewScore -> setSelectionMode(QAbstractItemView::ExtendedSelection);
	MainViewScore -> setRootIsDecorated(0);
	MainViewScore -> setSortingEnabled(1);
	MainButtonTest = new QPushButton(TabTest);
	MainButtonTest -> setObjectName(QString::fromUtf8("MainButtonTest"));
	MainButtonTestAll = new QPushButton(TabTest);
	MainButtonTestAll -> setObjectName(QString::fromUtf8("MainButtonTestAll"));
    MainButtonRefresh = new QPushButton(TabTest);
	MainButtonRefresh -> setObjectName(QString::fromUtf8("MainButtonRefresh"));
	LayoutTabTest = new QGridLayout(TabTest);
	LayoutTabTest -> setObjectName("LayoutTabTest");
	LayoutTabTest -> addWidget(MainViewScore, 0, 0, 1, 4);
	LayoutTabTest -> addWidget(MainButtonTest, 1, 0, 1, 1);
	LayoutTabTest -> addWidget(MainButtonTestAll, 1, 1, 1, 1);
	LayoutTabTest -> addWidget(MainButtonRefresh, 1, 2, 1, 1);
	
	//Building MenuData
	MenuData = new QMenu(this);
	MenuData -> setObjectName("MenuData");
	MainViewData -> setMenu(MenuData);
	QAction *ActProbInsert = MenuData -> addAction("Insert Problem");
	QAction *ActProbRemove = MenuData -> addAction("Remove Problem");
	MenuData -> addSeparator();
	QAction *ActCaseInsert = MenuData -> addAction("Insert Test Case");
	QAction *ActCaseRemove = MenuData -> addAction("Remove Test Case");
	MenuData -> addSeparator();
	QAction *ActConfigCase = MenuData -> addAction("Automatically Configing Test Cases");

	//Set Title
    setWindowTitle(ProjectName " - " MainVersion " - " VersionNumber);
    MainActionExit -> setText("Exit");
	MainActionAbout -> setText("About");
    MainMenuFile -> setTitle("File");
	MainMenuHelp -> setTitle("Help");
    MainButtonTest -> setText("Test");
    MainButtonTestAll -> setText("Test All");
    MainButtonRefresh -> setText("Refresh");
	
	//Connecting Objects
	connect(MainActionExit, SIGNAL(triggered()), this, SLOT(shut()));
	connect(MainActionAbout, SIGNAL(triggered()), this, SLOT(showAbout()));
	connect(ActProbInsert, SIGNAL(triggered()), this, SLOT(insertProblem()));
	connect(ActProbRemove, SIGNAL(triggered()), this, SLOT(removeProblem()));
	connect(ActCaseInsert, SIGNAL(triggered()), this, SLOT(insertTestCase()));
	connect(ActCaseRemove, SIGNAL(triggered()), this, SLOT(removeTestCase()));
	connect(ActConfigCase, SIGNAL(triggered()), this, SLOT(configTestCase()));
	connect(MainButtonTest, SIGNAL(clicked()), this, SLOT(testSelUser()));
	connect(MainButtonTestAll, SIGNAL(clicked()), this, SLOT(testAllUser()));
	connect(MainButtonRefresh, SIGNAL(clicked()), this, SLOT(scoreRefresh()));
	connect(MainViewData, SIGNAL(leftClicked()), this, SLOT(showProbCase()));
	connect(MainViewData, SIGNAL(rightClicked()), this, SLOT(showProbCase()));
	connect(MainViewData, SIGNAL(keyPressed(int)), this, SLOT(showProbCase()));
	connect(MainViewScore, SIGNAL(doubleClicked()), this, SLOT(viewUserInfo()));
	//Connect to Case Change
	connect(TextCaseInput, SIGNAL(textChanged()), this, SLOT(updateTestCase()));
	connect(TextCaseScore, SIGNAL(textChanged()), this, SLOT(updateTestCase()));
	connect(TextCaseOutput, SIGNAL(textChanged()), this, SLOT(updateTestCase()));
	connect(TextCaseTL, SIGNAL(textChanged()), this, SLOT(updateTestCase()));
	connect(TextCaseML, SIGNAL(textChanged()), this, SLOT(updateTestCase()));
	//Connect to Problem Change
	connect(TextInput, SIGNAL(textChanged()), this, SLOT(updateProblem()));
	connect(TextSource, SIGNAL(textChanged()), this, SLOT(updateProblem()));
	connect(TextOutput, SIGNAL(textChanged()), this, SLOT(updateProblem()));
	connect(TextProbName, SIGNAL(textChanged()), this, SLOT(updateProblem()));
	
	//List -- Show Objects
	updateDir();
	showData();
}
示例#21
0
int XJudgerMain::scoreRefresh(void){
	updateDir();
	return 0;
}
示例#22
0
文件: widget.cpp 项目: An-dy/qTox
void Widget::update()
{
    /// 1. Find and parse the update (0-5%)
    // Check that the dir exists
    QString updateDirStr = getSettingsDirPath()+"/update/";
    QDir updateDir(updateDirStr);
    if (!updateDir.exists())
        fatalError(tr("No update found."));

    // Check that we have a flist and that every file on the diff exists
    QFile updateFlistFile(updateDirStr+"flist");
    if (!updateFlistFile.open(QIODevice::ReadOnly))
        fatalError(tr("The update is incomplete."));

    QByteArray updateFlistData = updateFlistFile.readAll();
    updateFlistFile.close();

    setProgress(1);

    QList<UpdateFileMeta> updateFlist = parseFlist(updateFlistData);
    setProgress(2);
    QList<UpdateFileMeta> diff = genUpdateDiff(updateFlist);
    setProgress(4);
    for (UpdateFileMeta fileMeta : diff)
        if (!QFile::exists(updateDirStr+fileMeta.installpath))
            fatalError(tr("The update is incomplete."));

    if (diff.size() == 0)
       fatalError(tr("The diff list is empty."));

    setProgress(5);

    /// 2. Check the update (5-50%)
    float checkProgressStep = 45.0/(float)diff.size();
    float checkProgress = 5;
    for (UpdateFileMeta fileMeta : diff)
    {
        UpdateFile file;
        file.metadata = fileMeta;

        QFile fileFile(updateDirStr+fileMeta.installpath);
        if (!fileFile.open(QIODevice::ReadOnly))
            fatalError(tr("Update files are unreadable."));

        file.data = fileFile.readAll();
        fileFile.close();

        if (file.data.size() != (int)fileMeta.size)
            fatalError(tr("Update files are corrupted."));

        if (crypto_sign_verify_detached(file.metadata.sig, (unsigned char*)file.data.data(),
                                        file.data.size(), key) != 0)
            fatalError(tr("Update files are corrupted."));

        checkProgress += checkProgressStep;
        setProgress(checkProgress);
    }
    setProgress(50);

    /// 3. Install the update (50-95%)
    float installProgressStep = 45.0/(float)diff.size();
    float installProgress = 50;
    for (UpdateFileMeta fileMeta : diff)
    {
        // Backup old files
        if (QFile(fileMeta.installpath).exists())
        {
            QFile(fileMeta.installpath+".bak").remove();
            QFile(fileMeta.installpath).rename(fileMeta.installpath+".bak");
            backups.append(fileMeta.installpath);
        }

        // Install new ones
        QDir().mkpath(QFileInfo(fileMeta.installpath).absolutePath());
        QFile fileFile(updateDirStr+fileMeta.installpath);
        if (!fileFile.copy(fileMeta.installpath))
            fatalError(tr("Unable to copy the update's files from ")+(updateDirStr+fileMeta.installpath)+" to "+fileMeta.installpath);
        installProgress += installProgressStep;
        setProgress(installProgress);
    }
    setProgress(95);

    /// 4. Delete the update and backups (95-100%)
    deleteUpdate();
    setProgress(97);
    deleteBackups();
    setProgress(100);

    /// 5. Start qTox and exit
    startQToxAndExit();
}
示例#23
0
文件: widget.cpp 项目: An-dy/qTox
void Widget::deleteUpdate()
{
    QDir updateDir(getSettingsDirPath()+"/update/");
    updateDir.removeRecursively();
}
示例#24
0
bool AutoUpdater::downloadUpdate()
{
    // Updates only for supported platforms
    if (platform.isEmpty())
        return false;

    bool expectFalse = false;
    if (!isDownloadingUpdate.compare_exchange_strong(expectFalse,true))
        return false;

    // Get a list of files to update
    QByteArray newFlistData = getUpdateFlist();
    QList<UpdateFileMeta> newFlist = parseFlist(newFlistData);
    QList<UpdateFileMeta> diff = genUpdateDiff(newFlist);

    // Progress
    progressValue = 0;

    if (abortFlag)
    {
        isDownloadingUpdate = false;
        return false;
    }

    qDebug() << "Need to update" << diff.size() << "files";

    // Create an empty directory to download updates into
    QString updateDirStr = Settings::getInstance().getSettingsDirPath() + "/update/";
    QDir updateDir(updateDirStr);
    if (!updateDir.exists())
        QDir().mkdir(updateDirStr);
    updateDir = QDir(updateDirStr);
    if (!updateDir.exists())
    {
        qWarning() << "downloadUpdate: Can't create update directory, aborting...";
        isDownloadingUpdate = false;
        return false;
    }

    // Write the new flist for the updater
    QFile newFlistFile(updateDirStr+"flist");
    if (!newFlistFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        qWarning() << "downloadUpdate: Can't save new flist file, aborting...";
        isDownloadingUpdate = false;
        return false;
    }
    newFlistFile.write(newFlistData);
    newFlistFile.close();

    progressValue = 1;

    // Download and write each new file
    for (UpdateFileMeta fileMeta : diff)
    {
        float initialProgress = progressValue, step = 99./diff.size();
        auto stepProgressCallback = [&](int current, int total)
        {
            progressValue = initialProgress + step * (float)current/total;
        };

        if (abortFlag)
        {
            isDownloadingUpdate = false;
            return false;
        }

        // Skip files we already have
        QFile fileFile(updateDirStr+fileMeta.installpath);
        if (fileFile.open(QIODevice::ReadOnly) && fileFile.size() == (qint64)fileMeta.size)
        {
            qDebug() << "Skipping already downloaded file   '" + fileMeta.installpath+ "'";
            fileFile.close();
            progressValue = initialProgress + step;
            continue;
        }

        qDebug() << "Downloading '" + fileMeta.installpath + "' ...";

        // Create subdirs if necessary
        QString fileDirStr{QFileInfo(updateDirStr+fileMeta.installpath).absolutePath()};
        if (!QDir(fileDirStr).exists())
            QDir().mkpath(fileDirStr);

        // Download
        UpdateFile file = getUpdateFile(fileMeta, stepProgressCallback);
        if (abortFlag)
            goto fail;
        if (file.data.isNull())
        {
            qCritical() << "downloadUpdate: Error downloading a file, aborting...";
            goto fail;
        }

        // Check signature
        if (crypto_sign_verify_detached(file.metadata.sig, (unsigned char*)file.data.data(),
                                        file.data.size(), key) != 0)
        {
            qCritical() << "downloadUpdate: RECEIVED FORGED FILE, aborting...";
            goto fail;
        }

        // Save
        if (!fileFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
        {
            qCritical() << "downloadUpdate: Can't save new update file, aborting...";
            goto fail;
        }
        fileFile.write(file.data);
        fileFile.close();

        progressValue = initialProgress + step;
    }

    qDebug() << "downloadUpdate: The update is ready, it'll be installed on the next restart";

    isDownloadingUpdate = false;
    progressValue = 100;
    return true;

fail:
    isDownloadingUpdate = false;
    progressValue = 0;
    setProgressVersion("");
    return false;
}
示例#25
0
//increments game one turn by updating directions and running snake
void takeTurn( void ) {
	updateDir();
	runSnake();
}