コード例 #1
0
void QPlainTestLogger::enterTestFunction(const char * /*function*/)
{
    if (QTestLog::verboseLevel() >= 1)
        printMessage(QTest::messageType2String(Info), "entering");
}
コード例 #2
0
void 
OpenSteer::OpenSteerDemo::keyboardMiniHelp (void)
{
    printMessage ("");
    printMessage ("defined single key commands:");
    printMessage ("  r      restart current PlugIn.");
    printMessage ("  s      select next vehicle.");
    printMessage ("  c      select next camera mode.");
    printMessage ("  f      select next preset frame rate");
    printMessage ("  Tab    select next PlugIn.");
    printMessage ("  a      toggle annotation on/off.");
    printMessage ("  Space  toggle between Run and Pause.");
    printMessage ("  ->     step forward one frame.");
    printMessage ("  Esc    exit.");
    printMessage ("");

    // allow PlugIn to print mini help for the function keys it handles
    selectedPlugIn->printMiniHelpForFunctionKeys ();
}
コード例 #3
0
ファイル: firestudio_tube.cpp プロジェクト: EMATech/ffado
/**
 *  High rate not supported
 */
void
FirestudioTube::FirestudioTubeEAP::setupDefaultRouterConfig_high() {
    printMessage("High (192 kHz) sample rate not supported by Firestudio Tube\n");
}
コード例 #4
0
//this function takes the command from the cmd into commands that the program knows
void ParseCommand(Command cmd, std::vector<std::string> payload)
{
	if (cmd == Invalid)
	{
		printMessage("Invalid command.");
	}

	//adds a student
	else if (cmd == Add)
	{
		//Add a student
		if (payload.size() != 6)
		{
			//bad news throw the user an error.
			printMessage("Command add recieved incorrect # of arguments.");
		}
		else
		{
			//constuct the student
			Student toAdd = Student(payload[0], payload[1], payload[2],
				std::stoi(payload[3]), std::stoi(payload[4]), std::stoi(payload[5]));

			//make sure that id dosent exsist
			std::vector<Student> toCheck = students.searchStudents(students.ID, toAdd.getUID());

			//if to check == 0 then student doesnt exsist
			if (toCheck.size() < 100)
			{
				//make sure the student is valid
				if (!toAdd.isValidStudent())
				{
					printMessage("Invalid student attribute.");
					return;
				}

				//add
				students.addStudent(toAdd);
				students.saveStudent();
				std::cout << toAdd.getName() + " successfully added" << std::endl;
			}
			else
			{
				std::cout << "Student already exists" << std::endl;
			}
		}
	}

	//remove a student
	else if (cmd == Remove)
	{
		//see if student exsists
		std::vector<Student> toCheck = students.searchStudents(students.ID, payload[0]);

		//see if student exsist
		if (toCheck.size() != 0)
		{
			std::cout << "Student does not exist." << std::endl;
		}
		else
		{
			//delete student
			students.deleteStudent(toCheck[0]);
			students.saveStudent();
			std::cout << "Student deleted successfully" << std::endl;
		}
	}

	//search for student
	else if (cmd == Search)
	{
		//make sure there are arguments 
		if (payload.size() == 0)
		{
			std::cout << "Printing all students:" << std::endl;
			students.printAllStudents();
			return;
		}
		else
		{
			//slit the payload
			std::vector<std::string> commands = fileIO::split(payload[0], '=');

			//make sure the format  is correct
			if (commands.size() < 2)
			{
				printMessage("Search argument recieved invalid. Format should be [email protected].");
			}
			else
			{
				Students queryList = Students(students.searchStudents(commands[0],commands[1]));

				//iterate through rest of the arguments
				for (int i = 1; i < payload.size(); i++)
				{
					std::vector<std::string> commands = fileIO::split(payload[i], '=');

					if (commands.size() != 2)
					{
						printMessage("Search argument recieved invalid. Format should be [email protected].");
					}

					queryList = queryList.searchStudents(commands[0], commands[1]);
				}
			
				queryList.printAllStudents();
			}
		}
	}

	//update the student
	else if (cmd == Update)
	{
		//search for the student
		std::vector<Student> tempStudents = students.searchStudents(Students::ID, payload[0]);
		
		//for each argument update that one
		for (int i = 1; i < payload.size(); i++)
		{
			std::vector<std::string> commands = fileIO::split(payload[i], '=');
			students.updateInfo(tempStudents[0], commands);
		}

		students.saveStudent();
	}
	//you need help so print it
	else if (cmd == Help)
	{
		std::cout << "Here are a list of all the example commands: " << std::endl;
		std::cout << "add <name>,<UID>,<email>,<firstscore>,<secondscore>,<thirdscore>" << std::endl;
		std::cout << "remove <UID>" << std::endl;
		std::cout << "search UID=<id>,name=<bob>" << std::endl;
		std::cout << "update <UID>,UID=<id>,name=<new name>" << std::endl;
	}
}
コード例 #5
0
ファイル: main.c プロジェクト: Xenocidel/Chess
int main(){
	int in_game=0;
	int turnPre=0;
	int mode=-1;	 	/*range 1-3*/
	int diff=-1; 		/*range 0-3, 0 if pvp*/
	int timer=-1;		/*range 0, 5, 10, 20*/
	int side=-1;        /*range '0' for white, '1' for black*/
	int all41 = -1;		/* range 0-5 depending on piece */
	char confirm='n';	/*range 'n', 'y'*/
	char modeS[26];
	char diffS[26];
	char timerS[26];
	board *board = createNewGame();
	int timer1 = 0;
	int timer2 = 0;
	int timer3 = 0;
	int timer4 = 0;
	int timer5 = 0;
	int altcounter = 1;
	do{	/*game setup*/
		printf("\nChess v1.0 by nøl / C Gets Degrees\n\n");
		while (mode < 1){
			printf("Please select game mode:\n");
			printf("1. Player versus Player\n");
			printf("2. Player versus Computer\n");
			printf("3. Computer versus Computer\n\n");
			scanf("%d", &mode);
			switch(mode){
				case 1:
					printf("Player versus Player selected\n");
					break;
				case 2:
					printf("Player versus Computer selected\n\n");
					printf("Choose a side: White(0) or Black(1)?\n");
					scanf("%d", &side);
					switch(side){
						case 0:
							printf("White selected\n");
							break;
						case 1:
							printf("Black selected\n");
							break;
						default:
							printe(selection);
							side = -1;
							break;
					}
					break;
				case 3:
					printf("Computer versus Computer selected\n");
					break;
				default:
					printe(selection);
					mode = -1;
					break;
			}
		}
		while (all41 < 0){
			printf("\nPlease select game type. All-for-One mode creates all pieces of the same type!\n");
			printf("0. Standard Chess\n");
			printf("1. All-for-Pawn\n");
			printf("2. All-for-Knight\n");
			printf("3. All-for-Queen\n");
			printf("4. All-for-Rook\n");
			printf("5. All-for-Bishop\n");
			scanf("%d", &all41);
			switch(all41){
				case 0:
					printf("Standard chess selected\n");
					break;
				case 1:
					printf("All-for-Pawn selected\n");
					break;
				case 2:
					printf("All-for-Knight selected\n");
					break;
				case 3:
					printf("All-for-Queen selected\n");
					break;
				case 4:
					printf("All-for-Rook selected\n");
					break;
				case 5:
					printf("All-for-Bishop selected\n");
					break;
				default:
					printe(selection);
					all41 = -1;
					break;
			}
		}
		while (diff < 0){
			if (mode == 1){
				diff = 0;
				break;
			}
			printf("\nPlease select computer difficulty:\n");
			printf("1. Easy\n");
			printf("2. Medium\n");
			printf("3. Hard\n\n");
			scanf("%d", &diff);
			switch(diff){
				case 1:
					printf("Easy selected\n");
					break;
				case 2:
					printf("Medium selected\n");
					break;
				case 3:
					printf("Hard selected\n");
					break;
				default:
					printe(selection);
					diff = -1;
					break;
			}
		}
		while (timer < 0){
			printf("\nPlease select game timer length:\n");
			printf("0. No limit\n");
			printf("5. 5 minutes\n");
			printf("10. 10 minutes\n");
			printf("20. 20 minutes\n\n");
			scanf("%d", &timer);
			switch(timer){
				case 0:
					printf("No limit selected\n");
					timer = 0;
					break;
				case 5:
					printf("5 minutes selected\n");
					timer1 = timer*60;
					timer3 = timer*60;
					break;
				case 10:
					printf("10 minutes selected\n");
					timer1 = timer*60;
					timer3 = timer*60;
					break;
				case 20:
					printf("20 minutes selected\n");
					timer1 = timer*60;
					timer3 = timer*60;
					break;
				default:
					printe(selection);
					timer1 = 0;
					timer3 = 0;
					timer = -1;
					break;
			}
		}
		/*CREATE STRINGS FOR SELECTIONS*/
		switch(mode){
			case 1:
				strcpy(modeS, "Player versus Player");
				break;
			case 2:
				strcpy(modeS, "Player versus Computer");
				break;
			case 3:
				strcpy(modeS, "Computer versus Computer");
				break;
		}
		switch(diff){
			case 0:
				strcpy(diffS, "");
				break;
			case 1:
				strcpy(diffS, "\nDifficulty: Easy");
				break;
			case 2:
				strcpy(diffS, "\nDifficulty: Medium");
				break;
			case 3:
				strcpy(diffS, "\nDifficulty: Hard");
				break;
		}
		switch(timer){
			case 0:
				strcpy(timerS, "No time limit");
				break;
			case 5:
				strcpy(timerS, "5 minutes");
				break;
			case 10:
				strcpy(timerS, "10 minutes");
				break;
			case 20:
				strcpy(timerS, "20 minutes");
				break;
		}
		/*CONFIRM SELECTIONS*/
		printf("\n\nPlease confirm selections: [y/n]\n\n");
		printf("Mode: %s", modeS);
		printf("%s", diffS);
		printf("\nTimer: %s\n\n", timerS);
		scanf(" %c", &confirm);

		if (confirm == 'y' || confirm == 'Y'){
			in_game = 1;
			fgetc(stdin); /* absorb the /n produced by the last scanf */
			createMoveLog();
		}
		else if (confirm == 'n' || confirm == 'N'){
			mode = -1;
			side = -1;
			diff = -1;
			timer = -1;
			all41 = -1;
		}
		else{
			printe(selection);
		}
		
		int aiTeam1, aiTeam2;
		if(mode == 2){ /* Inverts input value 0 -> 1, 1 -> 0, other input will cause assertion failure */
			aiTeam1 = oppTeam(side); /* oppTeam function comes from ai.c. Reads an int, returns an int. */
		}
		if(mode == 3){ /* Default for CPU vs CPU */
			aiTeam1 = 0;
			aiTeam2 = 1;
		}
		
		while(in_game){ /* if side = 1, player is black */
			if (timer != 0){
				/* set up timer */
				if (altcounter % 2 != 0){
					timer5 = timer4 - timer2;
					timer1 = timer1 - timer5;
					altcounter = altcounter+1;
				}
				else{
					timer5 = timer4 - timer2;
					timer3 = timer3 - timer5;
					altcounter = altcounter+1;
				}
				if (timer1 <= 0){
				printf("\nWhite has run out of time!\n");
				exit(0);
				}
				if (timer3 <= 0){
					printf("\nBlack has run out of time!\n");
					exit(0);
				}
			}
			int alpha;
			cell *tmp1;
			switch(all41){
				case 0:
				break;
				case 1:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = pawn;
							updatePrintPiece(tmp1);
						}
					}
					break;
				case 2:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = knight;
							updatePrintPiece(tmp1);
						}
					}
					break;
				case 3:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = queen;
							updatePrintPiece(tmp1);
						}
					}
					break;
				case 4:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = rook;
							updatePrintPiece(tmp1);
						}
					}
					break;
				case 5:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = bishop;
							updatePrintPiece(tmp1);
						}
					}
					break;
			}
			
			turnPre = board->turn;
			timer2 = (int) time(NULL);
			updateGameDisplay(board); /* display the entire board only when its a new turn */
			while (turnPre == board->turn){
				cell *temp;
				switch(mode){
					case 1: /* PvP */ 
						updateMessage(board);
						/*board->turn++;*/
						break;
					case 2: /* P vs AI */
						if(board->turn%2 == aiTeam1){ /* AI's turn */
							printMessage(board->turn);
							if (board->turn == 0){
								temp = getCell(12, board);
								movePiece(temp->piece, getCell(20, board));
								temp = NULL;
							}
							else if (board->turn == 1){
								temp = getCell(52, board);
								movePiece(temp->piece, getCell(44, board));
							}
							else if (board->turn == 2){
								temp = getCell(3, board);
								movePiece(temp->piece, getCell(21, board));
							}
							else if (board->turn == 3){
								temp = getCell(59, board);
								movePiece(temp->piece, getCell(45, board));
							}
							else if (board->turn == 4){
								temp = getCell(5, board);
								movePiece(temp->piece, getCell(26, board));
							}
							else if (board->turn == 5){
								temp = getCell(61, board);
								movePiece(temp->piece, getCell(34, board));
							}
							else if (board->turn == 6){
								temp = getCell(21, board);
								movePiece(temp->piece, getCell(53, board));
							}
							else if (board->turn == 7){
								temp = getCell(45, board);
								movePiece(temp->piece, getCell(13, board));
							}
							else{
								aiMove(diff, aiTeam1, board);
							}
						}
						else{
							/* player's turn */
							updateMessage(board);
							/*board->turn++;*/
						}
						break;
					case 3: /* AI vs AI*/
						if(board->turn%2 == 0){ /* White's turn */
							/* aiTeam1 goes */
							printMessage(board->turn);
							aiMove(diff, aiTeam1, board);
							/*board->turn++;*/
						}
						else{ /* Black's turn */
							/* aiTeam2 goes */
							printMessage(board->turn);
							aiMove(diff, aiTeam2, board);
							/*board->turn++;*/
						}
						break;
				}
				/* Exits loop when turn is finished */
			}
			timer4 = (int) time(NULL);
			if (timer != 0 && board->turn > 1){
				printf("DEBUG: Current time: %d\n", timer4);
				printf("DEBUG: Current time: %d\n", timer2);
				printf("Time remaining for Player 1: %d seconds.\n", timer1);
				printf("Time remaining for Player 2: %d seconds.\n", timer3);
			}
		}
			
	}
	while(!in_game);
	
		
	return 0;
}
コード例 #6
0
ファイル: koil.cpp プロジェクト: luigialberti/dolomites
void Koil::initialize(const QStringList & /*arguments*/, QString * /*errorString*/){

    wid = new KoilWidget();
    connect(wid, SIGNAL(printMessage(QString,msgType)),this,SIGNAL(printMessage(QString,msgType)));
}
コード例 #7
0
ファイル: i2dimgs.cpp プロジェクト: ming-hai/ginkgocadx
/** Reads pixel data and corresponding attributes like rows etc. from image
*  file and inserts them into dataset.
*  @param dset - [out] The dataset to export the pixel data attributes to
*  @param outputTS - [out] The proposed transfex syntax of the dataset
*  @return EC_Normal, if successful, error otherwise
*/
OFCondition I2DImgSource::readAndInsertSpecificTags( DcmDataset* dset, E_TransferSyntax& outputTS)
{
        Uint16 samplesPerPixel, rows, cols, bitsAlloc, bitsStored, highBit, pixelRepr, planConf;
        Uint16 pixAspectH = 1;
        Uint16 pixAspectV = 1;
        OFString photoMetrInt;
        outputTS = EXS_Unknown;
        char* pixData = NULL;
        Uint32 length;

        OFCondition cond = readPixelData(rows, cols,
                                         samplesPerPixel, photoMetrInt, bitsAlloc, bitsStored, highBit, pixelRepr,
                                         planConf, pixAspectH, pixAspectV, pixData, length, outputTS);
        if (cond.bad())
                return cond;

        if (m_debug)
                printMessage(m_logStream, "Document2Dcm: Store imported pixel data to DICOM file");

        cond = dset->putAndInsertUint16(DCM_SamplesPerPixel, samplesPerPixel);
        if (cond.bad())
                return cond;

        cond = dset->putAndInsertOFStringArray(DCM_PhotometricInterpretation, photoMetrInt);
        if (cond.bad())
                return cond;

        cond = dset->putAndInsertOFStringArray(DCM_ConversionType, "WSD");
        if (cond.bad())
                return cond;
        /*
        cond = dset->putAndInsertOFStringArray(DCM_ImagerPixelSpacing, "1.000000\\1.000000");
        if (cond.bad())
        return cond;

        cond = dset->putAndInsertOFStringArray(DCM_PixelSpacing, "1.000000\\1.000000");
        if (cond.bad())
        return cond;
        */
        cond = dset->putAndInsertOFStringArray(DCM_ImagePositionPatient, "0.000000\\0.000000\\0.000000");
        if (cond.bad())
                return cond;

        cond = dset->putAndInsertOFStringArray(DCM_ImageOrientationPatient, "1.000000\\0.000000\\0.000000\\0.000000\\1.000000\\0.000000");
        if (cond.bad())
                return cond;


        // Should only be written if Samples per Pixel > 1
        if (samplesPerPixel > 1) {
                cond = dset->putAndInsertUint16(DCM_PlanarConfiguration, planConf);
                if (cond.bad())
                        return cond;
        }

        cond = dset->putAndInsertUint16(DCM_Rows, rows);
        if (cond.bad())
                return cond;

        cond = dset->putAndInsertUint16(DCM_Columns, cols);
        if (cond.bad())
                return cond;

        cond = dset->putAndInsertUint16(DCM_BitsAllocated, bitsAlloc);
        if (cond.bad())
                return cond;

        cond = dset->putAndInsertUint16(DCM_BitsStored, bitsStored);
        if (cond.bad())
                return cond;

        cond = dset->putAndInsertUint16(DCM_HighBit, highBit);
        if (cond.bad())
                return cond;

        cond = dset->putAndInsertUint16(DCM_PixelRepresentation, pixelRepr);
        if (cond.bad())
                return cond;


        if (Recompress()) {
                // create initial pixel sequence
                DcmElement* element = newDicomElement(DcmTag(DCM_PixelData, EVR_OW));
                element->putUint8Array((const Uint8*)pixData, length);
                cond = dset->insert(element);
                if (cond.bad()) {
                        delete element;
                        return cond;
                }

                //lo pasamos a jpeg lossless
                // create representation parameters for lossy and lossless
                OFCmdUnsignedInt opt_selection_value = 6;
                //este numero implica cierta perdida... si fuera 0 seria lossless real
                OFCmdUnsignedInt opt_point_transform = 3;

                E_TransferSyntax opt_oxfer;
                GNC::GCS::Permisos::EstadoPermiso codificacion = GNC::GCS::IControladorPermisos::Instance()->Get("core.importacion", "codec");
                switch (codificacion.ObtenerValor<int>()) {
                case 0: {
                        //baseline
                        opt_oxfer = EXS_JPEGProcess1;
                        DJ_RPLossy rp_lossy((int)90);
                        const DcmRepresentationParameter *rp = &rp_lossy;
                        dset->chooseRepresentation(opt_oxfer, rp);
                }
                break;
                case 1: {
                        //progresivo
                        opt_oxfer = EXS_JPEGProcess10_12;
                        DJ_RPLossy rp_lossy((int)90);
                        const DcmRepresentationParameter *rp = &rp_lossy;
                        dset->chooseRepresentation(opt_oxfer, rp);
                }
                break;
                case 2:
                default: {
                        //lossless
                        GNC::GCS::Permisos::EstadoPermiso estado = GNC::GCS::IControladorPermisos::Instance()->Get("core.importacion", "quality");
                        if (estado) {
                                opt_point_transform = std::min<int>(estado.ObtenerValor<int>(), 14);
                                opt_point_transform = std::max<int>(estado.ObtenerValor<int>(), 0);
                        }
                        opt_oxfer = EXS_JPEGProcess14SV1;
                        DJ_RPLossless rp_lossless((int)opt_selection_value, (int)opt_point_transform);
                        const DcmRepresentationParameter *rp = &rp_lossless;
                        dset->chooseRepresentation(opt_oxfer, rp);
                }
                break;
                }

                if(!dset->canWriteXfer(opt_oxfer))
                        return OFCondition(EC_UnsupportedEncoding);

                // force meta-header to refresh SOP Class/Instance UIDs.
                delete dset->remove(DCM_MediaStorageSOPClassUID);
                delete dset->remove(DCM_MediaStorageSOPInstanceUID);
                outputTS = opt_oxfer;

                return cond;
        } else {
                if (IsCompressed()) {
                        DcmPixelSequence *pixelSequence = NULL;

                        if (m_debug)
                                printMessage(m_logStream, "Document2Dcm: Store imported pixel data to DICOM file");
                        // create initial pixel sequence
                        pixelSequence = new DcmPixelSequence(DcmTag(DCM_PixelData, EVR_OB));
                        if (pixelSequence == NULL)
                                return EC_MemoryExhausted;
                        // insert empty offset table into sequence
                        DcmPixelItem *offsetTable = new DcmPixelItem(DcmTag(DCM_Item, EVR_OB));
                        if (offsetTable == NULL) {
                                delete pixelSequence;
                                pixelSequence = NULL;
                                return EC_MemoryExhausted;
                        }
                        cond = pixelSequence->insert(offsetTable);
                        if (cond.bad()) {
                                delete offsetTable;
                                offsetTable = NULL;
                                delete pixelSequence;
                                pixelSequence = NULL;
                                return cond;
                        }

                        // insert frame into pixel sequence
                        DcmOffsetList dummyList;
                        cond = pixelSequence->storeCompressedFrame(dummyList, (Uint8*) pixData, length, 0);
                        // storeCompressedFrame(..) does a deep copy, so the pixdata memory can be freed now
                        delete[] pixData;
                        if (cond.bad()) {
                                delete pixelSequence;
                                return cond;
                        }
                        cond = dset->insert(pixelSequence);
                        if (cond.bad())
                                delete pixelSequence;

                        if (m_debug)
                                printMessage(m_logStream, "Document2Dcm: Inserting Image Pixel module information");
                        return dset->putAndInsertUint16(DCM_PixelRepresentation, pixelRepr);
                } else {
                        //little endian to little endian...
                        // create initial pixel sequence
                        DcmElement* element = newDicomElement(DcmTag(DCM_PixelData, EVR_OW));
                        element->putUint8Array((const Uint8*)pixData, length);
                        cond = dset->insert(element);
                        if (cond.bad()) {
                                delete element;
                                return cond;
                        }
                        outputTS = EXS_LittleEndianExplicit;

                        return cond;
                }
        }
}
コード例 #8
0
//------------------------------------------------------------------------------
// processRecordImp
//------------------------------------------------------------------------------
void PrintSelected::processRecordImp(const DataRecordHandle* const handle)
{

   if (handle == nullptr) return;  // cannot continue
   const pb::DataRecord* dataRecord = handle->getRecord();
   if (dataRecord == nullptr) return;  // cannot continue

   // using reflection:
   // save to: const google::protobuf::Message* recMsg
   recMsg = dataRecord;
   //const google::protobuf::Message& root = *recMsg;
   const google::protobuf::Descriptor* descriptor = recMsg->GetDescriptor();
   const google::protobuf::Reflection* reflection = recMsg->GetReflection();

   const google::protobuf::FieldDescriptor* idField = descriptor->FindFieldByName("id");
   unsigned int id = reflection->GetUInt32(*recMsg, idField);

   foundSelected = false;

   // Process time message
   processMessage( &dataRecord->time());

   // Process the event message
   const google::protobuf::Message* processMsg = nullptr;
   std::string msgCat = "";
   std::string msgType = "";

   switch (msgToken) {
      case REID_FILE_ID: {
         processMsg = &dataRecord->file_id_msg();
         msgCat =  "FILE     ";
         msgType = "ID       ";
         static bool firstTime = true;
         if ((firstTime) || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_NEW_PLAYER: {
         processMsg = &dataRecord->new_player_event_msg();
         msgCat =  "PLAYER   ";
         msgType = "NEW      ";
         static bool firstTime = true;
         if ((firstTime) || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_PLAYER_REMOVED: {
         processMsg = &dataRecord->player_removed_event_msg();
         msgCat =  "PLAYER   ";
         msgType = "REMOVED  ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_PLAYER_DATA: {
         processMsg = &dataRecord->player_data_msg();
         msgCat =  "PLAYER   ";
         msgType = "DATA     ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) {
            printHeader = true;
         }
         firstTime = false;
         break;
      }
      case REID_PLAYER_DAMAGED: {
         processMsg = &dataRecord->player_damaged_event_msg();
         msgCat =  "PLAYER   ";
         msgType = "DAMAGED  ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_PLAYER_COLLISION: {
         processMsg = &dataRecord->player_collision_event_msg();
         msgCat =  "PLAYER   ";
         msgType = "COLLISION";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_PLAYER_CRASH: {
         processMsg = &dataRecord->player_crash_event_msg();
         msgCat =  "PLAYER   ";
         msgType = "CRASH    ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_PLAYER_KILLED: {
         processMsg = &dataRecord->player_killed_event_msg();
         msgCat =  "PLAYER   ";
         msgType = "KILLED   ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_WEAPON_RELEASED: {
         processMsg = &dataRecord->weapon_release_event_msg();
         msgCat =  "WEAPON   ";
         msgType = "RELEASED ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_WEAPON_HUNG: {
         processMsg = &dataRecord->weapon_hung_event_msg();
         msgCat =  "WEAPON   ";
         msgType = "HUNG     ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_WEAPON_DETONATION: {
         processMsg = &dataRecord->weapon_detonation_event_msg();
         msgCat =  "WEAPON  ";
         msgType = "DETONATE";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_GUN_FIRED: {
         processMsg = &dataRecord->gun_fired_event_msg();
         msgCat =  "GUN     ";
         msgType = "FIRED   ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_NEW_TRACK: {
         processMsg = &dataRecord->new_track_event_msg();
         msgCat =  "TRACK   ";
         msgType = "NEW     ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_TRACK_REMOVED: {
         processMsg = &dataRecord->track_removed_event_msg();
         msgCat =  "TRACK   ";
         msgType = "REMOVED ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      case REID_TRACK_DATA: {
         processMsg = &dataRecord->track_data_msg();
         msgCat =  "TRACK   ";
         msgType = "DATA    ";
         static bool firstTime = true;
         if (firstTime || isFileEmpty()) printHeader = true;
         firstTime = false;
         break;
      }
      default: break;
   }

   // Process the message and see if the conditions are found
   if (!timeOnly && (processMsg != nullptr)) {
      processMessage(processMsg);
   }

   // If the condition has been found and this is the message we want, print it
   std::stringstream soutFields;
   std::stringstream soutVals;
   if (foundSelected &&  timeOnly) {
      // print the message, whatever it is, because it matches the time criteria
      std::string msgName = getEventMsgName(recMsg);  // This also sets the event message
      if (eventMsg != nullptr) {
         soutFields << std::left << std::setw(32) << msgName << "\t" << "HEADER" << "\t";
         soutVals << std::left << std::setw(32) << msgName << "\t" "VALUES" << "\t";

         soutFields <<  std::left << std::setw(12)<< "exec time " << "\t";
         soutFields <<  std::left << std::setw(12)<< "sim time " << "\t";
         soutFields <<  std::left << std::setw(12)<< "utc time  "<< "\t" ;

         std::string timeStr = "";

         timeStr = printTimeMsg(dataRecord->time().exec_time());
         soutVals <<  std::left << std::setw(12) << timeStr << "\t";

         timeStr = printTimeMsg(dataRecord->time().sim_time());
         soutVals <<  std::left << std::setw(12) << timeStr << "\t";

         timeStr = printTimeMsg(dataRecord->time().utc_time());
         soutVals <<  std::left << std::setw(12) << timeStr << "\t";

     //    soutVals <<  std::left << std::setw(12) << dataRecord->time().sim_time() << "\t";
     //    soutVals <<  std::left << std::setw(12) << dataRecord->time().exec_time() << "\t";
     //    soutVals <<  std::left << std::setw(12) << dataRecord->time().utc_time() << "\t";

    //     printMessage(soutFields, soutVals, recMsg);  // Use this to include time and message ID
         printMessage(soutFields, soutVals, eventMsg);
         printToOutput( soutFields.str().c_str() );
         printToOutput( soutVals.str().c_str() );
      }
   }
   else if (foundSelected && (id == msgToken)) {

      // Print the message name

      soutFields << msgCat << "\t" << "HEADER" << "\t";
      soutVals << msgCat << "\t" << msgType << "\t";

      // Print the time
  //    const pb::Time* timeMsg  = &dataRecord->time();
  //    printMessage(soutFields, soutVals, timeMsg);  // print out the time message

         soutFields <<  std::left << std::setw(12)<< "exec time " << "\t";
         soutFields <<  std::left << std::setw(12)<< "sim time " << "\t";
         soutFields <<  std::left << std::setw(12)<< "utc time  "<< "\t" ;

         std::string timeStr = "";

         timeStr = printTimeMsg(dataRecord->time().exec_time());
         soutVals <<  std::left << std::setw(12) << timeStr << "\t";

         timeStr = printTimeMsg(dataRecord->time().sim_time());
         soutVals <<  std::left << std::setw(12) << timeStr << "\t";

         timeStr = printTimeMsg(dataRecord->time().utc_time());
         soutVals <<  std::left << std::setw(12) << timeStr << "\t";

      // Print out the event message
      // print the message, whatever it is, because it matches the time criteria
      std::string msgName = getEventMsgName(recMsg);  // This also sets event message
      if (eventMsg != nullptr) {
         printMessage(soutFields, soutVals, eventMsg);
      }

//      if (processMsg != 0) printMessage(soutFields, soutVals, processMsg);  // print out the event message
      // Print to output:
      if (printHeader) {
         printHeader = false;
         printToOutput( soutFields.str().c_str() );
      }
      printToOutput( soutVals.str().c_str() );
   }
}
コード例 #9
0
//------------------------------------------------------------------------------
// printMessage(): Recursive function to print all fields in this message
//---------------------------------------------------------------------------
void PrintSelected::printMessage(std::ostream& soutFields, std::ostream& soutVals, const google::protobuf::Message* const msg)
{
   std::streamsize oldWidth = soutFields.width();
   std::ostream::fmtflags oldFlags = soutFields.flags();

   const google::protobuf::Descriptor* descriptor = msg->GetDescriptor();
   const google::protobuf::Reflection* reflection = msg->GetReflection();

   const google::protobuf::Message& root = *msg;
   std::string msgName = descriptor->name();

   int fieldCount = descriptor->field_count();

   const google::protobuf::FieldDescriptor* fieldDescriptor = nullptr;

   std::string msgDivider = ";   ";
   std::string fieldDivider = ", ";

   bool lastField = false;

   if (fieldCount > 0) {
      for (int i = 0; i < fieldCount; i++) {
         if ((i+1) == fieldCount) lastField = true;

         // Get field descriptor (includes messages)
         fieldDescriptor = descriptor->field(i);

         // what type is this field?
         google::protobuf::FieldDescriptor::CppType cppType = fieldDescriptor->cpp_type();

         if (cppType == google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) {

            // do the same again for this message, etc.
            const google::protobuf::Message& sub_message = reflection->GetMessage(root, fieldDescriptor);
            printMessage(soutFields, soutVals, &sub_message);
         }
         else {
            // not a message: Print the field
            if (reflection->HasField(root, fieldDescriptor)) {
               soutFields <<  std::left << std::setw(12) << fieldDescriptor->name(); // Field name

               // get the value
               switch (cppType) {
                  case google::protobuf::FieldDescriptor::CPPTYPE_STRING: {
                     soutVals <<  std::left << std::setw(12)<<  reflection->GetString(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_INT32: {
                     soutVals <<  std::left << std::setw(12)<<  reflection->GetInt32(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_INT64: {
                     soutVals <<  std::left << std::setw(12)<< reflection->GetInt64(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_UINT32: {
                     soutVals <<  std::left << std::setw(12)<< reflection->GetUInt32(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_UINT64: {
                     soutVals <<  std::left << std::setw(12)<< reflection->GetUInt64(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_DOUBLE: {
                     soutVals  <<  std::left << std::setw(12)<< reflection->GetDouble(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_FLOAT: {
                     soutVals  <<  std::left << std::setw(12)<< reflection->GetFloat(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_BOOL: {
                     soutVals <<  std::left << std::setw(12)<< reflection->GetBool(root, fieldDescriptor);
                     break;
                  }
                  case google::protobuf::FieldDescriptor::CPPTYPE_ENUM: {
                     const google::protobuf::EnumValueDescriptor* enumVal = reflection->GetEnum(root, fieldDescriptor);
                     int enumIndex = enumVal->index();
                     soutVals <<  std::left << std::setw(12)<<  enumIndex;
                     break;
                  }
                  default: {
                     soutVals << "   \t";
                     break;
                  }
               }
            }  // end if has field
            else {
               // This field had no data. We should skip it
            }
            if (lastField) {
               // print message divider
               soutFields << msgDivider;
               soutVals << msgDivider;
            }
            else {
               // print field Divider
               soutFields << fieldDivider;
               soutVals << fieldDivider;
            }
         }
      }
   }

   soutFields.width( oldWidth );
   soutFields.setf( oldFlags );
}
コード例 #10
0
ファイル: win32gui.cpp プロジェクト: jefferis/rgl
   bool initGL () {
 
     bool success = false;
 
     // obtain a device context for the window 
     dcHandle = GetDC(windowHandle);
 
     if (dcHandle) {
 
       // describe requirements
  
       PIXELFORMATDESCRIPTOR pfd = { 
         sizeof(PIXELFORMATDESCRIPTOR),    // size of this pfd 
         1,                                // version number 
         0
         | PFD_DRAW_TO_WINDOW              // support window 
         | PFD_SUPPORT_OPENGL              // support OpenGL 
         | PFD_GENERIC_FORMAT              // generic format
         | PFD_DOUBLEBUFFER                // double buffered 
         ,
         PFD_TYPE_RGBA,                    // RGBA type 
         16,                               // 16-bit color depth 
         0, 0, 0, 0, 0, 0,                 // color bits ignored 
         1,                                // alpha buffer 
         0,                                // shift bit ignored 
         0,                                // no accumulation buffer 
         0, 0, 0, 0,                       // accum bits ignored 
         16,                               // 16-bit z-buffer     
         0,                                // no stencil buffer 
         0,                                // no auxiliary buffer 
         PFD_MAIN_PLANE,                   // main layer 
         0,                                // reserved 
         0, 0, 0                           // layer masks ignored 
       };
 
       int  iPixelFormat; 
 
       // get the device context's best, available pixel format match 
       iPixelFormat = ChoosePixelFormat(dcHandle, &pfd); 
 
       if (iPixelFormat != 0) {
 
         // make that match the device context's current pixel format 
         SetPixelFormat(dcHandle, iPixelFormat, &pfd); 
 
         // create GL context
 
         if ( ( glrcHandle = wglCreateContext( dcHandle ) ) )
             success = true;
         else
           printMessage("wglCreateContext failed");
 
       }
       else
         printMessage("iPixelFormat == 0!");
 
       ReleaseDC(windowHandle,dcHandle);
     }
 
     return success;
   }
コード例 #11
0
//this is a pathfinding algorithm
//you have to find the optimal path
int WorldMap::CalculateDistances(const ieResRef AreaName, int direction)
{
	//first, update reachable/visible areas by worlde.2da if exists
	UpdateReachableAreas();
	UpdateAreaVisibility(AreaName, direction);
	if (direction==-1) {
		return 0;
	}

	if (direction<0 || direction>3) {
		printMessage("WorldMap", "CalculateDistances for invalid direction: %s\n", LIGHT_RED, AreaName);
		return -1;
	}

	unsigned int i;
	if (!GetArea(AreaName, i)) {
		printMessage("WorldMap", "CalculateDistances for invalid Area: %s\n", LIGHT_RED, AreaName);
		return -1;
	}
	if (Distances) {
		free(Distances);
	}
	if (GotHereFrom) {
		free(GotHereFrom);
	}

	printMessage("WorldMap", "CalculateDistances for Area: %s\n", GREEN, AreaName);

	size_t memsize =sizeof(int) * area_entries.size();
	Distances = (int *) malloc( memsize );
	GotHereFrom = (int *) malloc( memsize );
	memset( Distances, -1, memsize );
	memset( GotHereFrom, -1, memsize );
	Distances[i] = 0; //setting our own distance
	GotHereFrom[i] = -1; //we didn't move

	int *seen_entry = (int *) malloc( memsize );

	std::list<int> pending;
	pending.push_back(i);
	while(pending.size()) {
		i=pending.front();
		pending.pop_front();
		WMPAreaEntry* ae=area_entries[i];
		memset( seen_entry, -1, memsize );
		//all directions should be used
		for(int d=0;d<4;d++) {
			int j=ae->AreaLinksIndex[d];
			int k=j+ae->AreaLinksCount[d];
			if ((size_t) k>area_links.size()) {
				printMessage("WorldMap", "The worldmap file is corrupted... and it would crash right now!\nEntry #: %d Direction: %d\n", RED,
					i, d);
				break;
			}
			for(;j<k;j++) {
				WMPAreaLink* al = area_links[j];
				WMPAreaEntry* ae2 = area_entries[al->AreaIndex];
				unsigned int mydistance = (unsigned int) Distances[i];

				// we must only process the FIRST seen link to each area from this one
				if (seen_entry[al->AreaIndex] != -1) continue;
				seen_entry[al->AreaIndex] = 0;
/*
				if ( ( (ae->GetAreaStatus() & WMP_ENTRY_PASSABLE) == WMP_ENTRY_PASSABLE) &&
				( (ae2->GetAreaStatus() & WMP_ENTRY_WALKABLE) == WMP_ENTRY_WALKABLE)
*/
				if ( (ae2->GetAreaStatus() & WMP_ENTRY_WALKABLE) == WMP_ENTRY_WALKABLE) {
					// al->Flags is the entry direction
					mydistance += al->DistanceScale * 4;
					//nonexisting distance is the biggest!
					if ((unsigned) Distances[al->AreaIndex] > mydistance) {
						Distances[al->AreaIndex] = mydistance;
						GotHereFrom[al->AreaIndex] = j;
						pending.push_back(al->AreaIndex);
					}
				}
			}
		}
	}

	free(seen_entry);
	return 0;
}
コード例 #12
0
int utManagerThread::run_with_templateTracker_SFM()
{
    int kalState = -1;

    switch (stateFlag)
    {
        case 0:
            yDebug("Looking for motion...\n");
            timeNow = yarp::os::Time::now();
            oldMcutPoss.clear();
            stateFlag++;
            deleteGuiTarget();
            break;
        case 1:
            // state #01: check the motionCUT and see if there's something interesting.
            // if so, initialize the tracker, and step up.
            if (processMotion())
            {
                yDebug("Initializing tracker...\n");
                timeNow = yarp::os::Time::now();
                initializeTracker();
                stateFlag++;
            }
            break;
        case 2:
            // state #02: read data from the Tracker and use the SFM to retrieve a 3D point.
            // with that, initialize the kalman filter, and then step up.
            readFromTracker();
            if (getPointFromStereo())
            {
                yDebug("Initializing Kalman filter...\n");
                kalThrd -> setKalmanState(KALMAN_INIT);
                kalThrd -> kalmanInit(SFMPos);
                stateFlag++;
            }
            break;
        case 3:
            // state #03: keep reading data from the Tracker and retrieving the 3D point from the SFM
            // With this info, keep feeding the kalman filter until it thinks that the object is still
            // tracked. If not, go back from the initial state.
            printMessage(2,"Reading from tracker and SFM...\n");
            readFromTracker();
            if (getPointFromStereo())
            {
                kalThrd -> setKalmanInput(SFMPos);
            }
            
            kalThrd -> getKalmanState(kalState);
            sendGuiTarget();
            if (kalState == KALMAN_STOPPED)
            {
                yDebug("For some reasons, the kalman filters stopped. Going back to initial state.\n");
                stateFlag = 0;
            }
            break;
        default:
            yError(" utManagerThread should never be here!!!\nState: %d\n",stateFlag);
            Time::delay(1);
            break;
    }

    return kalState;
}
コード例 #13
0
ファイル: PluginLoader.cpp プロジェクト: JeremyAgost/gemrb
void LoadPlugins(char* pluginpath)
{
	std::set<PluginID> libs;

	printMessage("PluginMgr", "Loading Plugins from %s\n", WHITE, pluginpath);

	char path[_MAX_PATH];
	strcpy( path, pluginpath );

	std::list< char * > files;
	if (! FindFiles( path, files ))
		return;

	//Iterate through all the available modules to load
	int file_count = files.size (); // keeps track of first-pass files
	while (! files.empty()) {
		char* file = files.front();
		files.pop_front();
		file_count--;

		PathJoin( path, pluginpath, file, NULL );
		printBracket( "PluginMgr", LIGHT_WHITE );
		print( ": Loading: " );
		textcolor( LIGHT_WHITE );
		print( "%s", path );
		textcolor( WHITE );
		print( "..." );


		ieDword flags = 0;
		core->plugin_flags->Lookup (file, flags);

		// module is sent to the back
		if ((flags == PLF_DELAY) && (file_count >= 0)) {
			printStatus( "DELAYING", YELLOW );
			files.push_back( file );
			continue;
		}

		// We do not need the basename anymore now
		free( file );

		// module is skipped
		if (flags == PLF_SKIP) {
			printStatus( "SKIPPING", YELLOW );
			continue;
		}



		// Try to load the Module
#ifdef WIN32
		HMODULE hMod = LoadLibrary( path );
#else
		// Note: the RTLD_GLOBAL is necessary to export symbols to modules
		//       which python may have to dlopen (-wjp, 20060716)
		// (to reproduce, try 'import bz2' or another .so module)
		void* hMod = dlopen( path, RTLD_NOW | RTLD_GLOBAL );
#endif
		if (hMod == NULL) {
			printBracket( "ERROR", LIGHT_RED );
			print( "\nCannot Load Module, Skipping...\n" );
			PRINT_DLERROR;
			continue;
		}

		//printStatus( "OK", LIGHT_GREEN );
		//using C bindings, so we don't need to jump through extra hoops
		//with the symbol name
		Version_t LibVersion = ( Version_t ) GET_PLUGIN_SYMBOL( hMod, "GemRBPlugin_Version" );
		Description_t Description = ( Description_t ) GET_PLUGIN_SYMBOL( hMod, "GemRBPlugin_Description" );
		ID_t ID = ( ID_t ) GET_PLUGIN_SYMBOL( hMod, "GemRBPlugin_ID" );
		Register_t Register = ( Register_t ) GET_PLUGIN_SYMBOL( hMod, "GemRBPlugin_Register" );

		//printMessage( "PluginMgr", "Checking Plugin Version...", WHITE );
		if (LibVersion==NULL) {
			printStatus( "ERROR", LIGHT_RED );
			print( "Invalid Plug-in, Skipping...\n" );
			FREE_PLUGIN( hMod );
			continue;
		}
		if (strcmp(LibVersion(), VERSION_GEMRB) ) {
			printStatus( "ERROR", LIGHT_RED );
			print( "Plug-in Version not valid, Skipping...\n" );
			FREE_PLUGIN( hMod );
			continue;
		}

		PluginDesc desc = { hMod, ID(), Description(), Register };

		//printStatus( "OK", LIGHT_GREEN );
		//printMessage( "PluginMgr", "Loading Exports for ", WHITE );
		print( " " );
		textcolor( LIGHT_WHITE );
		print( "%s", desc.Description );
		textcolor( WHITE );
		print( "..." );
		printStatus( "OK", LIGHT_GREEN );
		if (libs.find(desc.ID) != libs.end()) {
			printMessage( "PluginMgr", "Plug-in Already Loaded! ", WHITE );
			printStatus( "SKIPPING", YELLOW );
			FREE_PLUGIN( hMod );
			continue;
		}
		if (desc.Register != NULL) {
			if (!desc.Register(PluginMgr::Get())) {
				printMessage( "PluginMgr", "Plug-in Registration Failed! Perhaps a duplicate? ", WHITE );
				printStatus( "SKIPPING", YELLOW );
				FREE_PLUGIN( hMod );
			}
		}
		libs.insert(desc.ID);
	}
}
コード例 #14
0
/** Loads a PlayList for playing */
bool MUSImporter::OpenPlaylist(const char* name)
{
	if (PLName[0] != '\0') {
		int len = ( int ) strlen( PLName );
		if (strnicmp( name, PLName, len ) == 0)
			return true;
	}
	if (Playing) {
		return false;
	}
	core->GetAudioDrv()->ResetMusics();
	playlist.clear();
	PLpos = 0;
	if (name[0] == '*') {
		return false;
	}
	char path[_MAX_PATH];
	PathJoin(path, core->GamePath, musicsubfolder, name, NULL);
	printMessage("MUSImporter", "", WHITE);
	printf( "Loading %s...", path );
	if (!str->Open( path, true )) {
		printStatus("NOT FOUND", LIGHT_RED );
		return false;
	}
	printStatus("FOUND", LIGHT_GREEN );
	int c = str->ReadLine( PLName, 32 );
	while (c > 0) {
		if (( PLName[c - 1] == ' ' ) || ( PLName[c - 1] == '\t' ))
			PLName[c - 1] = 0;
		else
			break;
		c--;
	}
	char counts[5];
	str->ReadLine( counts, 5 );
	int count = atoi( counts );
	while (count != 0) {
		char line[64];
		int len = str->ReadLine( line, 64 );
		int i = 0;
		int p = 0;
		PLString pls;
		while (i < len) {
			if (( line[i] != ' ' ) && ( line[i] != '\t' ))
				pls.PLFile[p++] = line[i++];
			else {
				while (i < len) {
					if (( line[i] == ' ' ) || ( line[i] == '\t' ))
						i++;
					else
						break;
				}
				break;
			}
		}
		pls.PLFile[p] = 0;
		p = 0;
		if (line[i] != '@' && ( i < len )) {
			while (i < len) {
				if (( line[i] != ' ' ) && ( line[i] != '\t' ))
					pls.PLTag[p++] = line[i++];
				else
					break;
			}
			pls.PLTag[p] = 0;
			p = 0;
			while (i < len) {
				if (( line[i] == ' ' ) || ( line[i] == '\t' ))
					i++;
				else {
					break;
				}
			}
			if (line[i] == '@')
				strcpy( pls.PLLoop, pls.PLTag );
			else {
				while (i < len) {
					if (( line[i] != ' ' ) && ( line[i] != '\t' ))
						pls.PLLoop[p++] = line[i++];
					else
						break;
				}
				pls.PLLoop[p] = 0;
			}
			while (i < len) {
				if (( line[i] == ' ' ) || ( line[i] == '\t' ))
					i++;
				else
					break;
			}
			p = 0;
		} else {
			pls.PLTag[0] = 0;
			pls.PLLoop[0] = 0;
		}
		while (i < len) {
			if (( line[i] != ' ' ) && ( line[i] != '\t' ))
				i++;
			else {
				while (i < len) {
					if (( line[i] == ' ' ) || ( line[i] == '\t' ))
						i++;
					else
						break;
				}
				break;
			}
		}
		while (i < len) {
			if (( line[i] != ' ' ) && ( line[i] != '\t' ))
				pls.PLEnd[p++] = line[i++];
			else
				break;
		}
		pls.PLEnd[p] = 0;
		playlist.push_back( pls );
		count--;
	}
	return true;
}
コード例 #15
0
int main(int argc, char *argv[])
{

    char **playersNameList;
    int totalPlayersNumber;
    int turn, i;
    char buffer[BUFF_SIZE];
    FILE *configFile;

    /* legge gli argomenti */
    char **name1, **name2;

    if (argc < 4) {
        fprintf(stderr,
                "ERROR: Wrong number of arguments. \n USAGE: %s\n",
                USAGE);
        exit(EXIT_FAILURE);
    }
    playersNameList = argv + 3;
    totalPlayersNumber = argc - 3;

    /* controlla se ci sono due giocatori con lo stesso nome */
    for (name1 = playersNameList; *name1; name1++)
        for (name2 = name1 + 1; *name2; name2++)
            if (strcmp(*name1, *name2) == 0) {
                fprintf(stderr, "ERROR: found two player with the"
                        "same name \"%s\"\n", *name1);
                exit(EXIT_FAILURE);
            }
    initIoInterface(argv[2]);
    /* crea e inizializza le strutture dati per i giocatori */
    initPlayersManager(totalPlayersNumber);
    for (; *playersNameList; playersNameList++)
        addPlayer(*playersNameList);

    initBoard();
    /*
     * legge il file di configurazione secondo il formato: 
     *     numero_casella:descrizione della prova\n
     * e aggiunge le descrizioni al tabellone
     */
    if ((configFile = fopen(argv[1], "r")) == NULL) {
        printErr("ERROR: error while opening configuration file\n");
        exit(EXIT_FAILURE);
    }
    while (fgets(buffer, BUFF_SIZE, configFile)) {
        char *description;
        int boxNumber;
        /* legge il numero di casella */
        if ((boxNumber = atoi(buffer)) <= 0) {
            printErr("ERROR:invalid box num(\"%s\") in"
                     " configuration file\n", buffer);
            exit(EXIT_FAILURE);
        }
        /* aggiunge una nuova casella con la relativa descrizione */
        if ((description = strchr(buffer, ':')) == NULL) {
            printErr("ERROR: missing ':' in configuration file\n");
            exit(EXIT_FAILURE);
        }
        addBox(boxNumber, description + 1);
    }
    if (getTotalBoxesNumber() == 0) {
        printErr("ERROR: invalid configuration file\n");
        exit(EXIT_FAILURE);
    }
    fclose(configFile);
    printBoard();
    showGame();
    /* avvia la simulazione del gioco */
    srand(time(NULL));
    for (turn = 0; !allPlayersDone(); turn++) {
        if (!nextStep())
            return EXIT_SUCCESS;
        printMessage("\n**************************************\n");
        printMessage("turno %d", turn + 1);
        printMessage("\n**************************************\n");
        showGame();
        /*
         * per ogni giocatore G che non ha terminato il gioco: 
         * 1. se G  e' fermo per un turno cambia il suo stato in
         *      modo che al turno successivo venga rimesso in gioco 
         * 2. altrimenti viene lanciato il dado, mosso il giocatore
         *              e visualizzata la sua prova 
         */
        while (nextPlayer()) {
            int state = getPlayerState();

            if (state == ACTIVE || state == TEST_PASSED
                || state == TO_BE_ACTIVATED) {
                if (state != ACTIVE)
                    setPlayerState(ACTIVE, 0);
                movePlayer((rand() % 6) + 1);
                if (getPlayerBox() > getTotalBoxesNumber())
                    setPlayerState(DONE, turn);
                else
                    printMessage("player %s: \"%s\"\n",
                                 getPlayerName(),
                                 getDescription(getPlayerBox()));
            } else if (state == OUT_OF_TURN)
                setPlayerState(TO_BE_ACTIVATED, 0);
        }
        showGame();
        /*
         * Legge e registra l'esito di tutte le prove sostenute nel
         * turno corrente dai giocatori 
         */
        for (i = getActivePlayersNumber(); i > 0; i--) {
            int playerNumber;
            bool result;

            do {
                result = askPlayerResult(&playerNumber);
                if (playerNumber > totalPlayersNumber)
                    printErr("WARNING: player number %d out of "
                             "bounds [1; %d]\n", playerNumber,
                             totalPlayersNumber);
                else {
                    setCurrentPlayer(playerNumber);
                    if (getPlayerState() != ACTIVE)
                        printErr("WARNING: player number %d not "
                                 "valid because player:"
                                 "\n\t-won"
                                 "\n\t-is out of turn"
                                 "\n\t-already passed the test\n",
                                 playerNumber);
                }
            }
            while (playerNumber > totalPlayersNumber
                   || getPlayerState() != ACTIVE);
            if (result)
                setPlayerState(TEST_PASSED, 0);
            else
                setPlayerState(OUT_OF_TURN, 0);
        }
    }
    printScore();
    closeIoInterface();

    return EXIT_SUCCESS;
}
コード例 #16
0
ファイル: db.c プロジェクト: jpverdejo/kv-db
// Funcion para obtener una palabra en base a un indice
void * get(void * input) {
	sem_wait(Gavailable);

	// Obtenemos un indice de instruccion, con eso obtendremos el resto de la informacion
	int indice = (int) input;

	pthread_mutex_lock(&instructionsMutex);
	Instruction instruccion = instructions[indice];

	// Guardamos 2 copias de la palabra. La primera se usará para buscar las distintas partes del indice
	// La segunda es para el mensaje de salida
	char * index = instruccion.word;
	

	char * copyIndex = (char *) malloc(sizeof(char) * (strlen(index) +1));
	strcpy(copyIndex, index);
	pthread_mutex_unlock(&instructionsMutex);
	
	int found = 0;

	Page p;
	p.letter = index[0];

	char * token;

	// Verificamos que la palabra tenga por lo menos 2 puntos.
	token = strtok(index, ".");

	token = strtok(NULL, ".");

	size_t output_message_size;
	char * output_message;

	if (token != NULL) {
		p.number = atoi(token);

		token = strtok(NULL, ".");
		if (token != NULL) {
			p.index = atoi(token);

			// Verificamos que despues de las transformaciones el indice sea el mismo
			char * checkIndex;
			size_t checkIndexSize;
			checkIndexSize = snprintf(NULL, 0, "%c.%d.%d", p.letter, p.number, p.index);
			checkIndex = (char *)malloc(checkIndexSize + 1);
			snprintf(checkIndex, checkIndexSize+1, "%c.%d.%d", p.letter, p.number, p.index);

			if(strcmp(copyIndex, checkIndex) == 0) {
				size_t filename_size;
				char * filename;

				filename_size = snprintf(NULL, 0, "./data/%c.%d", p.letter, p.number);

				filename = (char *)malloc(filename_size + 1);
				snprintf(filename, filename_size+1, "./data/%c.%d", p.letter, p.number);

				char * word = NULL;
				size_t size;
				int i;

				FILE *fp = fopen(filename, "r");

				if(fp != NULL) {
					// Recorremos la linea hasta la que buscamos
					for (i=0; i<=p.index && !feof(fp); i++) {
						getline(&word, &size, fp);
					}

					// Si la palabra que encontramos no es una palabra vacia y el bucle alcanzo a llegar hasta la posicion entonces el indice existe
					if (!(strcmp(word, "") == 0 || i<=p.index)) {
						// Eliminamos el salto de linea
						word[(strlen(word)-1)] = '\0';

						// Seteamos el flag para identificar si encontramos la palabra
						found = 1;

						// Creamos el string de salida
						output_message_size = snprintf(NULL, 0, "[GET] %s:%s", copyIndex, word);
						output_message = (char *)malloc(output_message_size + 1);
						snprintf(output_message, output_message_size +1, "[GET] %s:%s", copyIndex, word);
					}
				}

				fclose(fp);
			}
		}
	}
	
	// Si no encontramos valor para el indice dado imprimimos un mensaje que lo indica
	if (!found) {
		output_message_size = snprintf(NULL, 0, "[GET] El indice %s no existe.", copyIndex);
		output_message = (char *)malloc(output_message_size + 1);
		snprintf(output_message, output_message_size +1, "[GET] El indice %s no existe.", copyIndex);
	}

	printMessage(instruccion, output_message);
	
	sem_post(Gavailable);

	return NULL;
}
コード例 #17
0
ファイル: chebyshevformaux.c プロジェクト: windover/sollya
/*Wrapper to get directly the coeffs in the Chebyshev basis
  from a polynomial in the monomial basis given by a *node
  We return in n = deg(f)+1;
*/
void getChebCoeffsFromPolynomial(sollya_mpfi_t**coeffs, int *n, node *f, sollya_mpfi_t x, mp_prec_t prec){
  sollya_mpfi_t z1, z2, ui, vi;
  node **coefficients;
  int d,i;
  sollya_mpfi_t *p, *c;
  mpfr_t u,v;
  if (isPolynomial(f) ){
    getCoefficients(&d, &coefficients, f);

    *n=d+1;

    *coeffs= (sollya_mpfi_t *)safeMalloc((d+1)*sizeof(sollya_mpfi_t));

    p=safeMalloc((d+1)*sizeof(sollya_mpfi_t));
    c=safeMalloc((d+1)*sizeof(sollya_mpfi_t));
    for (i=0;i<d+1;i++){
      sollya_mpfi_init2((*coeffs)[i],prec);
      sollya_mpfi_init2(p[i],prec);
      sollya_mpfi_init2(c[i],prec);
      if (coefficients[i]!= NULL)  mpfi_set_node(p[i],coefficients[i], prec);
      else sollya_mpfi_set_ui(p[i],0);
    }

    for (i=0;i<d+1;i++) {
      if (coefficients[i] != NULL)
        free_memory(coefficients[i]);
    }
    safeFree(coefficients);

    /*Here we have the coeffs of the polynomial in p, over the interval x=[a,b]*/
    /*we need to compute the polynomial over [-1,1]*/
    /*we make the change of variable: x= y*(b-a)/2 + (b+a)/2, hence for y \in [-1,1] we have x\in [a,b]*/
    /* we compute P(x)=Q(y)*/
    sollya_mpfi_init2(ui, prec);
    sollya_mpfi_init2(vi, prec);


    mpfr_init2(u, prec);
    mpfr_init2(v, prec);

    sollya_mpfi_init2(z1, prec);
    sollya_mpfi_init2(z2, prec);

    sollya_mpfi_get_left(u,x);
    sollya_mpfi_get_right(v,x);

    sollya_mpfi_set_fr(ui,u);
    sollya_mpfi_set_fr(vi,v);

    sollya_mpfi_add(z2,ui,vi);
    sollya_mpfi_sub(z1,vi,ui);

    sollya_mpfi_div_ui(z1,z1,2);
    sollya_mpfi_div_ui(z2,z2,2);

    getTranslatedPolyCoeffs(c, p, d+1, z1,z2);

    getPolyCoeffsChebBasis(*coeffs, c, d+1);

    /*cleaning*/

    for (i=0;i<d+1;i++){
      sollya_mpfi_clear(p[i]);
      sollya_mpfi_clear(c[i]);
    }
    safeFree(p);
    safeFree(c);

    sollya_mpfi_clear(ui);
    sollya_mpfi_clear(vi);


    mpfr_clear(u);
    mpfr_clear(v);

    sollya_mpfi_clear(z1);
    sollya_mpfi_clear(z2);


  }
  else{
    printMessage(1,SOLLYA_MSG_ERROR_IN_CHEBYSHEVFORM_NOT_A_POLYNOMIAL,
		 "The given function is not a polynomial, no modification is made.\n");
  }
}
コード例 #18
0
ファイル: db.c プロジェクト: jpverdejo/kv-db
// Funcion que maneja las busquedas por valor
void * find(void * input) {

	// Obtenemos el indice entregado, con eso buscaremos la informacion necesaria 
	int indice = (int) input;

	pthread_mutex_lock(&instructionsMutex);
	Instruction instruccion = instructions[indice];
	char * word = (char *) malloc(sizeof(char) * (strlen(instruccion.word) +1));
	strcpy(word, instruccion.word);
	pthread_mutex_unlock(&instructionsMutex);

	char letter = getLetter(word);
	int index = getIndex(letter);

	// Seteamos la cantidad de workers que necesitaremos
	int n_workers = pages_count[index];

	// Creamos un arreglo de strings donde guardaremos los archivos que necesitaremos
	char ** files = (char **) malloc(sizeof(char *) * n_workers);
	size_t filename_size;

	// Llenamos el arreglo de strings con los nombres de archivos
	int i, k;
	for (i = 0; i < n_workers; i++) {
		filename_size = snprintf(NULL, 0, "%c.%d", letter, (i+1));
		files[i] = (char *)malloc(filename_size + 1);
		snprintf(files[i], filename_size+1, "%c.%d", letter, (i +1));
	}

	int *pthread_ids;

	pthread_t *workers;

	// Creamos el arreglo de pthread_t para los workers
	pthread_ids = (int*) malloc(sizeof(int) * n_workers);
	workers = (pthread_t*) malloc(sizeof(pthread_t) * n_workers);

	// Levantamos los workers necesarios
	for (i = 0;i < n_workers; i++) {
		FindObject *C = (FindObject *) malloc(sizeof(FindObject));
		C->word = word;
		C->filename = files[i];
		pthread_ids[i] = pthread_create(&workers[i], NULL, findFromFile, C);
	}

	// Creamos un arreglo de strings dodne guardaremos los IDs que encontremos
	char ** resultIDs;
	int numberResults = 0;

	size_t indexLength;

	// Por cada worker esperamos que vuelva (con un join) y leemos el resultado
	for (i = 0; i < n_workers; i++) {
		FindObject *m;
		pthread_join(workers[i], (void *)&m);

		// Si encontramos la palabra:
		if (m != NULL && m->n_found > 0) {
			// Recorremos el listado de posiciones donde se encontro
			for (k = 0; k < m->n_found; k++) {
				numberResults++;
				
				// Agrandamos el arreglo de strings y guardamos el ID
				resultIDs = (char **) realloc(resultIDs, (sizeof(char *) * numberResults));

				indexLength = snprintf(NULL, 0, "%s.%d", m->filename, m->positions[k]);
				resultIDs[numberResults -1] = (char *)malloc(indexLength + 1);
				snprintf(resultIDs[numberResults -1], indexLength+1, "%s.%d", m->filename, m->positions[k]);
			}
		}
	}

	char * message = (char *) malloc(1);
	size_t message_size;

	if (numberResults) {
		// Si encontramos resultados generamos un string con los IDs asociados
		message_size = snprintf(NULL, 0, "[FIND] %s: ", word);
		message = (char *) realloc(message, message_size + 1);
		snprintf(message, message_size+1, "[FIND] %s: ", word);

		for (i = 0; i < numberResults; i++) {
			message_size = strlen(resultIDs[i]) +2;
			message = (char *) realloc(message, (sizeof(char) * (strlen(message) + message_size + 1)));
			strcat(message, resultIDs[i]);
			strcat(message, ", ");
		}

		message[(strlen(message) -2)] = '\0';
	}
	else {
		// SI no encontramos resultados generamos un mensaje con la informacion
		message_size = snprintf(NULL, 0, "[FIND] No se encontro la palabra: %s", word);
		message = (char *)malloc(message_size + 1);
		snprintf(message, message_size+1, "[FIND] No se encontro la palabra: %s", word);
	}

	printMessage(instruccion, message);

	return NULL;
}
コード例 #19
0
ファイル: external.c プロジェクト: hoangt/PandA-bambu
char *evaluateStringAsBashCommand(char *command, char *input) {
  char *res;
  int okay, errorOnInput;
  int exitcode;
  int pipesToBash[2];
  int pipesFromBash[2];
  pid_t pid;
  int childStatus;
  char readBuffer[READ_BUFFER_SIZE];
  int readLen;
  char *buf;
  int len;
  int i;

  if ((command == NULL) || (strlen(command) == 0)) {
    printMessage(1,"Warning in bashevaluate: no command provided\n");
    return NULL;
  }

  res = NULL;
  okay = 0;
  fflush(NULL);
  
  // Create two unnamed pipe
  if ((input != NULL) && (pipe(pipesToBash) == -1)) {
    // Error creating the pipe
    printMessage(1,"Warning in bashevaluate: error while creating a pipe");
  } else {
    if (pipe(pipesFromBash) == -1) {
      // Error creating the pipe
      printMessage(1, "Warning in bashevaluate: error while creating a pipe");
    } else {
      // Fork
      //
      // Flush before forking
      //
      fflush(NULL);
      if ((pid = fork()) == -1) {
	// Error forking
	printMessage(1, "Warning in bashevaluate: error while forking");
      } else {
	// Fork worked
	if (pid == 0) {
	  // I am the child
	  //
	  // Close the unneeded ends of the pipes.
	  //
	  if (input != NULL) close(pipesToBash[1]);
	  close(pipesFromBash[0]);
	  
	  // Connect my input and output to the pipe
	  //
	  if (input != NULL) {
	    if (dup2(pipesToBash[0],0) == -1) {
	      _exit(1);
	    }
	  }
	  if (dup2(pipesFromBash[1],1) == -1) {
	    _exit(1);
	  }
	  
	  // Execute bash
	  //
	  fflush(NULL);
	  execlp("sh","sh","-c",command,(char *) NULL);
	  fflush(NULL);

	  _exit(1);
	} else {
	  // I am the father
	  //
	  // Close the unneeded ends of the pipes.
	  //
	  if (input != NULL) close(pipesToBash[0]);
	  close(pipesFromBash[1]);
	  
	  // Do my job
	  //
	  errorOnInput = 0;
	  if (input != NULL) {
	    if (write(pipesToBash[1],input,
		      strlen(input) * sizeof(char)) == -1) {
	      printMessage(1,"Warning in bashevaluate: unable to write to bash");
	      errorOnInput = 1;
	    }
	    close(pipesToBash[1]);
	  }

	  fflush(NULL);

	  if (!errorOnInput) {
	    do {
	      readLen = read(pipesFromBash[0],readBuffer,READ_BUFFER_SIZE);
	      if (readLen > 0) {
		if (res == NULL) {
		  res = safeCalloc(readLen + 1, sizeof(char));
		  buf = res;
		} else {
		  len = strlen(res);
		  buf = safeCalloc(len + readLen + 1, sizeof(char));
		  strcpy(buf,res);
		  free(res);
		  res = buf;
		  buf += len;
		}
		for (i=0;i<readLen;i++) {
		  *buf = (readBuffer[i] == '\0') ? '?' : readBuffer[i];
		  buf++;
		}
	      }
	    } while (readLen == READ_BUFFER_SIZE);

	    // Wait for my child to exit
	    wait(&childStatus);
	    
	    // Read the rest of the pipe if it filled up again after 
	    // having been emptied already.
	    do {
	      readLen = read(pipesFromBash[0],readBuffer,READ_BUFFER_SIZE);
	      if (readLen > 0) {
		if (res == NULL) {
		  res = safeCalloc(readLen + 1, sizeof(char));
		  buf = res;
		} else {
		  len = strlen(res);
		  buf = safeCalloc(len + readLen + 1, sizeof(char));
		  strcpy(buf,res);
		  free(res);
		  res = buf;
		  buf += len;
		}
		for (i=0;i<readLen;i++) {
		  *buf = (readBuffer[i] == '\0') ? '?' : readBuffer[i];
		  buf++;
		}
	      }
	    } while (readLen == READ_BUFFER_SIZE);

	    if (WEXITSTATUS(childStatus) != 0) {
	      printMessage(1, "Warning in bashevaluate: the exit code of the child process is %d.\n", WEXITSTATUS(childStatus));
	    } else {
	      printMessage(2, "Information in bashevaluate: the exit code of the child process is %d.\n", WEXITSTATUS(childStatus));
	    }

	    close(pipesFromBash[0]);

	    okay = 1;
	    if (res == NULL) {
	      res = safeCalloc(2, sizeof(char));
	    }
	    len = strlen(res);
	    if (len >= 1) {
	      if (res[len-1] == '\n') res[len-1] = '\0';
	    }
	  }
	}
      }
    }
  }

  if (!okay) {
    if (res != NULL) free(res);
    res = NULL;
  }

  fflush(NULL);

  return res;
}
コード例 #20
0
int main (void)
{
	printMessage ();

	return 0;
}
コード例 #21
0
ファイル: ASTBase.cpp プロジェクト: bhanug/virtualbox
void ASTBase::panic(const char *msg)
{
	/* MR23 */ printMessage(stderr,"ASTBase panic: %s\n", msg);
	exit(PCCTS_EXIT_FAILURE);
}
コード例 #22
0
ファイル: KEYImporter.cpp プロジェクト: scriptedfate/gemrb
bool KEYImporter::Open(const char *resfile, const char *desc)
{
	free(description);
	description = strdup(desc);
	if (!core->IsAvailable( IE_BIF_CLASS_ID )) {
		print( "[ERROR]\nAn Archive Plug-in is not Available\n" );
		return false;
	}
	unsigned int i;
	// NOTE: Interface::Init has already resolved resfile.
	printMessage("KEYImporter", "Opening %s...", WHITE, resfile);
	FileStream* f = FileStream::OpenFile(resfile);
	if (!f) {
		// Check for backslashes (false escape characters)
		// this check probably belongs elsewhere (e.g. ResolveFilePath)
		if (strstr( resfile, "\\ " )) {
			print("%s", "\nEscaped space(s) detected in path!. Do not escape spaces in your GamePath! " );
		}
		printStatus( "ERROR", LIGHT_RED );
		printMessage( "KEYImporter", "Cannot open Chitin.key\n", LIGHT_RED );
		textcolor( WHITE );
		print("This means you set the GamePath config variable incorrectly.\n");
		print("It must point to the directory that holds a readable Chitin.key\n");
		return false;
	}
	printStatus( "OK", LIGHT_GREEN );
	printMessage( "KEYImporter", "Checking file type...", WHITE );
	char Signature[8];
	f->Read( Signature, 8 );
	if (strncmp( Signature, "KEY V1  ", 8 ) != 0) {
		printStatus( "ERROR", LIGHT_RED );
		printMessage( "KEYImporter", "File has an Invalid Signature.\n", LIGHT_RED );
		textcolor( WHITE );
		delete( f );
		return false;
	}
	printStatus( "OK", LIGHT_GREEN );
	printMessage( "KEYImporter", "Reading Resources...\n", WHITE );
	ieDword BifCount, ResCount, BifOffset, ResOffset;
	f->ReadDword( &BifCount );
	f->ReadDword( &ResCount );
	f->ReadDword( &BifOffset );
	f->ReadDword( &ResOffset );
	printMessage( "KEYImporter", " ", WHITE );
	print( "BIF Files Count: %d (Starting at %d Bytes)\n", BifCount,
		BifOffset );
	printMessage("KEYImporter", "RES Count: %d (Starting at %d Bytes)\n", WHITE,
		ResCount, ResOffset);
	f->Seek( BifOffset, GEM_STREAM_START );

	ieDword BifLen, ASCIIZOffset;
	ieWord ASCIIZLen;
	for (i = 0; i < BifCount; i++) {
		BIFEntry be;
		f->Seek( BifOffset + ( 12 * i ), GEM_STREAM_START );
		f->ReadDword( &BifLen );
		f->ReadDword( &ASCIIZOffset );
		f->ReadWord( &ASCIIZLen );
		f->ReadWord( &be.BIFLocator );
		be.name = ( char * ) malloc( ASCIIZLen );
		f->Seek( ASCIIZOffset, GEM_STREAM_START );
		f->Read( be.name, ASCIIZLen );
		for (int p = 0; p < ASCIIZLen; p++) {
			//some MAC versions use : as delimiter
			if (be.name[p] == '\\' || be.name[p] == ':')
				be.name[p] = PathDelimiter;
		}
		FindBIF(&be);
		biffiles.push_back( be );
	}
	f->Seek( ResOffset, GEM_STREAM_START );

	MapKey key;
	ieDword ResLocator;

	// limit to 32k buckets
	// only ~1% of the bg2 entries are of bucket lenght >4
	resources.init(ResCount > 32 * 1024 ? 32 * 1024 : ResCount, ResCount);

	for (i = 0; i < ResCount; i++) {
		f->ReadResRef(key.ref);
		f->ReadWord(&key.type);
		f->ReadDword(&ResLocator);

		// seems to be always the last entry?
		if (key.ref[0] != 0)
			resources.set(key, ResLocator);
	}

	printMessage( "KEYImporter", "Resources Loaded...", WHITE );
	printStatus( "OK", LIGHT_GREEN );
	delete( f );
	return true;
}
コード例 #23
0
/** Returns the i-th window in the Previously Loaded Stream */
Window* CHUImporter::GetWindow(unsigned int wid)
{
    ieWord WindowID, XPos, YPos, Width, Height, BackGround;
    ieWord ControlsCount, FirstControl;
    ieResRef MosFile;
    unsigned int i;

    bool found = false;
    for (unsigned int c = 0; c < WindowCount; c++) {
        str->Seek( WEOffset + ( 0x1c * c ), GEM_STREAM_START );
        str->ReadWord( &WindowID );
        if (WindowID == wid) {
            found = true;
            break;
        }
    }
    if (!found) {
        return NULL;
    }
    str->Seek( 2, GEM_CURRENT_POS );
    str->ReadWord( &XPos );
    str->ReadWord( &YPos );
    str->ReadWord( &Width );
    str->ReadWord( &Height );
    str->ReadWord( &BackGround );
    str->ReadWord( &ControlsCount );
    str->ReadResRef( MosFile );
    str->ReadWord( &FirstControl );

    Window* win = new Window( WindowID, XPos, YPos, Width, Height );
    if (BackGround == 1) {
        ResourceHolder<ImageMgr> mos(MosFile);
        if (mos != NULL) {
            win->SetBackGround( mos->GetSprite2D(), true );
        } else
            printMessage( "CHUImporter","Cannot Load BackGround, skipping\n",YELLOW );
    }
    if (!core->IsAvailable( IE_BAM_CLASS_ID )) {
        printMessage( "CHUImporter","No BAM Importer Available, skipping controls\n",LIGHT_RED );
        return win;
    }
    for (i = 0; i < ControlsCount; i++) {
        str->Seek( CTOffset + ( ( FirstControl + i ) * 8 ), GEM_STREAM_START );
        ieDword COffset, CLength, ControlID;
        ieWord XPos, YPos, Width, Height;
        ieByte ControlType, temp;
        str->ReadDword( &COffset );
        str->ReadDword( &CLength );
        str->Seek( COffset, GEM_STREAM_START );
        str->ReadDword( &ControlID );
        str->ReadWord( &XPos );
        str->ReadWord( &YPos );
        str->ReadWord( &Width );
        str->ReadWord( &Height );
        str->Read( &ControlType, 1 );
        str->Read( &temp, 1 );
        switch (ControlType) {
        case IE_GUI_BUTTON:
        {
            //Button
            Button* btn = new Button( );
            btn->ControlID = ControlID;
            btn->XPos = XPos;
            btn->YPos = YPos;
            btn->Width = Width;
            btn->Height = Height;
            btn->ControlType = ControlType;
            ieResRef BAMFile;
            ieWord Cycle, UnpressedIndex, PressedIndex,
                   SelectedIndex, DisabledIndex;
            str->ReadResRef( BAMFile );
            str->ReadWord( &Cycle );
            str->ReadWord( &UnpressedIndex );
            str->ReadWord( &PressedIndex );
            str->ReadWord( &SelectedIndex );
            str->ReadWord( &DisabledIndex );
            btn->Owner = win;
            /** Justification comes from the .chu, other bits are set by script */
            if (!Width) {
                btn->SetFlags(IE_GUI_BUTTON_NO_IMAGE, BM_OR);
            }
            if (core->HasFeature(GF_UPPER_BUTTON_TEXT)) {
                btn->SetFlags(IE_GUI_BUTTON_CAPS, BM_OR);
            }

            btn->SetFlags( Cycle&0xff00, BM_OR );
            if (strnicmp( BAMFile, "guictrl\0", 8 ) == 0) {
                if (UnpressedIndex == 0) {
                    printMessage("CHUImporter", "Special Button Control, Skipping Image Loading\n",GREEN );
                    win->AddControl( btn );
                    break;
                }
            }
            AnimationFactory* bam = ( AnimationFactory* )
                                    gamedata->GetFactoryResource( BAMFile,
                                            IE_BAM_CLASS_ID, IE_NORMAL );
            if (!bam ) {
                printMessage( "CHUImporter","Cannot Load Button Images, skipping control\n",LIGHT_RED );
                /* IceWind Dale 2 has fake BAM ResRefs for some Buttons,
                   this will handle bad ResRefs */
                win->AddControl( btn );
                break;
            }
            /** Cycle is only a byte for buttons */
            Sprite2D* tspr = bam->GetFrame( UnpressedIndex, (unsigned char) Cycle );
            btn->SetImage( IE_GUI_BUTTON_UNPRESSED, tspr );
            tspr = bam->GetFrame( PressedIndex, (unsigned char) Cycle );
            btn->SetImage( IE_GUI_BUTTON_PRESSED, tspr );
            //ignorebuttonframes is a terrible hack
            if (core->HasFeature( GF_IGNORE_BUTTON_FRAMES) ) {
                if (bam->GetCycleSize( (unsigned char) Cycle) == 4 )
                    SelectedIndex=2;
            }
            tspr = bam->GetFrame( SelectedIndex, (unsigned char) Cycle );
            btn->SetImage( IE_GUI_BUTTON_SELECTED, tspr );
            if (core->HasFeature( GF_IGNORE_BUTTON_FRAMES) ) {
                if (bam->GetCycleSize( (unsigned char) Cycle) == 4 )
                    DisabledIndex=3;
            }
            tspr = bam->GetFrame( DisabledIndex, (unsigned char) Cycle );
            btn->SetImage( IE_GUI_BUTTON_DISABLED, tspr );
            win->AddControl( btn );
        }
        break;

        case IE_GUI_PROGRESSBAR:
        {
            //GemRB specific, progressbar
            ieResRef MOSFile, MOSFile2;
            ieResRef BAMFile;
            ieWord KnobXPos, KnobYPos;
            ieWord CapXPos, CapYPos;
            ieWord KnobStepsCount;
            ieWord Cycle;

            str->ReadResRef( MOSFile );
            str->ReadResRef( MOSFile2 );
            str->ReadResRef( BAMFile );
            str->ReadWord( &KnobStepsCount );
            str->ReadWord( &Cycle );
            str->ReadWord( &KnobXPos );
            str->ReadWord( &KnobYPos );
            str->ReadWord( &CapXPos );
            str->ReadWord( &CapYPos );
            Progressbar* pbar = new Progressbar(KnobStepsCount, true );
            pbar->ControlID = ControlID;
            pbar->XPos = XPos;
            pbar->YPos = YPos;
            pbar->ControlType = ControlType;
            pbar->Width = Width;
            pbar->Height = Height;
            pbar->SetSliderPos( KnobXPos, KnobYPos, CapXPos, CapYPos );

            Sprite2D* img = NULL;
            Sprite2D* img2 = NULL;
            if ( MOSFile[0] ) {
                ResourceHolder<ImageMgr> mos(MOSFile);
                img = mos->GetSprite2D();
            }
            if ( MOSFile2[0] ) {
                ResourceHolder<ImageMgr> mos(MOSFile2);
                img2 = mos->GetSprite2D();
            }

            pbar->SetImage( img, img2 );
            if( KnobStepsCount ) {
                /* getting the bam */
                AnimationFactory *af = (AnimationFactory *)
                                       gamedata->GetFactoryResource(BAMFile, IE_BAM_CLASS_ID );
                /* Getting the Cycle of the bam */
                pbar->SetAnimation(af->GetCycle( Cycle & 0xff ) );
            }
            else {
                ResourceHolder<ImageMgr> mos(BAMFile);
                Sprite2D* img3 = mos->GetSprite2D();
                pbar->SetBarCap( img3 );
            }
            win->AddControl( pbar );
        }
        break;
        case IE_GUI_SLIDER:
        {
            //Slider
            ieResRef MOSFile, BAMFile;
            ieWord Cycle, Knob, GrabbedKnob;
            ieWord KnobXPos, KnobYPos, KnobStep, KnobStepsCount;
            str->ReadResRef( MOSFile );
            str->ReadResRef( BAMFile );
            str->ReadWord( &Cycle );
            str->ReadWord( &Knob );
            str->ReadWord( &GrabbedKnob );
            str->ReadWord( &KnobXPos );
            str->ReadWord( &KnobYPos );
            str->ReadWord( &KnobStep );
            str->ReadWord( &KnobStepsCount );
            Slider* sldr = new Slider( KnobXPos, KnobYPos, KnobStep, KnobStepsCount, true );
            sldr->ControlID = ControlID;
            sldr->XPos = XPos;
            sldr->YPos = YPos;
            sldr->ControlType = ControlType;
            sldr->Width = Width;
            sldr->Height = Height;
            ResourceHolder<ImageMgr> mos(MOSFile);
            Sprite2D* img = mos->GetSprite2D();
            sldr->SetImage( IE_GUI_SLIDER_BACKGROUND, img);

            AnimationFactory* bam = ( AnimationFactory* )
                                    gamedata->GetFactoryResource( BAMFile,
                                            IE_BAM_CLASS_ID, IE_NORMAL );
            if( bam ) {
                img = bam->GetFrame( Knob, 0 );
                sldr->SetImage( IE_GUI_SLIDER_KNOB, img );
                img = bam->GetFrame( GrabbedKnob, 0 );
                sldr->SetImage( IE_GUI_SLIDER_GRABBEDKNOB, img );
            }
            else {
                sldr->SetState(IE_GUI_SLIDER_BACKGROUND);
            }
            win->AddControl( sldr );
        }
        break;

        case IE_GUI_EDIT:
        {
            //Text Edit
            ieResRef BGMos;
            ieResRef FontResRef, CursorResRef;
            ieWord maxInput;
            ieWord CurCycle, CurFrame;
            ieWord PosX, PosY;

            str->ReadResRef( BGMos );
            str->Seek( 16, GEM_CURRENT_POS );
            str->ReadResRef( CursorResRef );
            str->ReadWord( &CurCycle );
            str->ReadWord( &CurFrame );
            str->ReadWord( &PosX );
            str->ReadWord( &PosY );
            str->Seek( 4, GEM_CURRENT_POS );
            str->ReadResRef( FontResRef );
            str->Seek( 34, GEM_CURRENT_POS );
            str->ReadWord( &maxInput );
            Font* fnt = core->GetFont( FontResRef );

            AnimationFactory* bam = ( AnimationFactory* )
                                    gamedata->GetFactoryResource( CursorResRef,
                                            IE_BAM_CLASS_ID,
                                            IE_NORMAL );
            Sprite2D *cursor = NULL;
            if (bam) {
                cursor = bam->GetFrame( CurCycle, CurFrame );
            }

            ResourceHolder<ImageMgr> mos(BGMos);
            Sprite2D *img = NULL;
            if(mos) {
                img = mos->GetSprite2D();
            }

            TextEdit* te = new TextEdit( maxInput, PosX, PosY );
            te->ControlID = ControlID;
            te->XPos = XPos;
            te->YPos = YPos;
            te->Width = Width;
            te->Height = Height;
            te->ControlType = ControlType;
            te->SetFont( fnt );
            te->SetCursor( cursor );
            te->SetBackGround( img );
            win->AddControl( te );
        }
        break;

        case IE_GUI_TEXTAREA:
        {
            //Text Area
            ieResRef FontResRef, InitResRef;
            Color fore, init, back;
            ieWord SBID;
            str->ReadResRef( FontResRef );
            str->ReadResRef( InitResRef );
            Font* fnt = core->GetFont( FontResRef );
            Font* ini = core->GetFont( InitResRef );
            str->Read( &fore, 4 );
            str->Read( &init, 4 );
            str->Read( &back, 4 );
            str->ReadWord( &SBID );
            TextArea* ta = new TextArea( fore, init, back );
            ta->ControlID = ControlID;
            ta->XPos = XPos;
            ta->YPos = YPos;
            ta->Width = Width;
            ta->Height = Height;
            ta->ControlType = ControlType;
            ta->SetFonts( ini, fnt );
            win->AddControl( ta );
            if (SBID != 0xffff)
                win->Link( SBID, ( unsigned short ) ControlID );
        }
        break;

        case IE_GUI_LABEL:
        {
            //Label
            ieResRef FontResRef;
            ieStrRef StrRef;
            RevColor fore, back;
            ieWord alignment;
            str->ReadDword( &StrRef );
            str->ReadResRef( FontResRef );
            Font* fnt = core->GetFont( FontResRef );
            str->Read( &fore, 4 );
            str->Read( &back, 4 );
            str->ReadWord( &alignment );
            Label* lab = new Label( fnt );
            lab->ControlID = ControlID;
            lab->XPos = XPos;
            lab->YPos = YPos;
            lab->Width = Width;
            lab->Height = Height;
            lab->ControlType = ControlType;
            char* str = core->GetString( StrRef );
            lab->SetText( str );
            core->FreeString( str );
            if (alignment & 1) {
                lab->useRGB = true;
                Color f, b;
                f.r = fore.b;
                f.g = fore.g;
                f.b = fore.r;
                f.a = 0;
                b.r = back.b;
                b.g = back.g;
                b.b = back.r;
                b.a = 0;
                lab->SetColor( f, b );
            }
            int align = IE_FONT_ALIGN_CENTER;
            if (( alignment & 0x10 ) != 0) {
                align = IE_FONT_ALIGN_RIGHT;
                goto endvertical;
            }
            if (( alignment & 0x04 ) != 0) {
                goto endvertical;
            }
            if (( alignment & 0x08 ) != 0) {
                align = IE_FONT_ALIGN_LEFT;
                goto endvertical;
            }
endvertical:
            if (( alignment & 0x20 ) != 0) {
                align |= IE_FONT_ALIGN_TOP;
                goto endalign;
            }
            if (( alignment & 0x80 ) != 0) {
                align |= IE_FONT_ALIGN_BOTTOM;
            } else {
                align |= IE_FONT_ALIGN_MIDDLE;
            }
endalign:
            lab->SetAlignment( align );
            win->AddControl( lab );
        }
        break;

        case IE_GUI_SCROLLBAR:
        {
            //ScrollBar
            ieResRef BAMResRef;
            ieWord Cycle, Trough, Slider, TAID;
            ieWord UpUnPressed, UpPressed;
            ieWord DownUnPressed, DownPressed;

            str->ReadResRef( BAMResRef );
            str->ReadWord( &Cycle );
            str->ReadWord( &UpUnPressed );
            str->ReadWord( &UpPressed );
            str->ReadWord( &DownUnPressed );
            str->ReadWord( &DownPressed );
            str->ReadWord( &Trough );
            str->ReadWord( &Slider );
            str->ReadWord( &TAID );
            ScrollBar* sbar = new ScrollBar();
            sbar->ControlID = ControlID;
            sbar->XPos = XPos;
            sbar->YPos = YPos;
            sbar->Width = Width;
            sbar->Height = Height;
            sbar->ControlType = ControlType;

            AnimationFactory* bam = ( AnimationFactory* )
                                    gamedata->GetFactoryResource( BAMResRef,
                                            IE_BAM_CLASS_ID, IE_NORMAL );
            if (bam) {
                sbar->SetImage( IE_GUI_SCROLLBAR_UP_UNPRESSED,
                                bam->GetFrame( UpUnPressed, Cycle ) );
                sbar->SetImage( IE_GUI_SCROLLBAR_UP_PRESSED,
                                bam->GetFrame( UpPressed, Cycle ) );
                sbar->SetImage( IE_GUI_SCROLLBAR_DOWN_UNPRESSED,
                                bam->GetFrame( DownUnPressed, Cycle ) );
                sbar->SetImage( IE_GUI_SCROLLBAR_DOWN_PRESSED,
                                bam->GetFrame( DownPressed, Cycle ) );
                sbar->SetImage( IE_GUI_SCROLLBAR_TROUGH,
                                bam->GetFrame( Trough, Cycle ) );
                sbar->SetImage( IE_GUI_SCROLLBAR_SLIDER,
                                bam->GetFrame( Slider, Cycle ) );
            }
            win->AddControl( sbar );
            if (TAID != 0xffff)
                win->Link( ( unsigned short ) ControlID, TAID );
        }
        break;

        default:
            printMessage( "CHUImporter","Control Not Supported\n",LIGHT_RED );
        }
    }
    return win;
}
コード例 #24
0
unsigned char * readEcat7(const char *fname, struct TDICOMdata *dcm, struct nifti_1_header *hdr, struct TDCMopts opts, bool isWarnIfNotEcat) {
//data type
#define	ECAT7_BYTE 1
#define	ECAT7_VAXI2 2
#define ECAT7_VAXI4 3
#define ECAT7_VAXR4 4
#define ECAT7_IEEER4 5
#define	ECAT7_SUNI2 6
#define	ECAT7_SUNI4 7
//file types
//#define ECAT7_UNKNOWN 0
#define ECAT7_2DSCAN 1
#define ECAT7_IMAGE16 2
#define ECAT7_ATTEN 3
#define ECAT7_2DNORM 4
#define ECAT7_POLARMAP 5
#define ECAT7_VOLUME8 6
#define ECAT7_VOLUME16 7
#define ECAT7_PROJ 8
#define ECAT7_PROJ16 9
#define ECAT7_IMAGE8 10
#define ECAT7_3DSCAN 11
#define ECAT7_3DSCAN8 12
#define ECAT7_3DNORM 13
#define ECAT7_3DSCANFIT 14
    PACK( typedef struct  {
        char magic[14],original_filename[32];
        uint16_t sw_version, system_type, file_type;
        char serial_number[10];
        uint32 scan_start_time;
        char isotope_name[8];
        Float32 isotope_halflife;
        char radiopharmaceutical[32];
        Float32 gantry_tilt, gantry_rotation, bed_elevation, intrinsic_tilt;
        int16_t wobble_speed, transm_source_type;
        Float32 distance_scanned, transaxial_fov;
        uint16_t angular_compression, coin_samp_mode, axial_samp_mode;
        Float32 ecat_calibration_factor;
        uint16_t calibration_unitS, calibration_units_type, compression_code;
        char study_type[12], patient_id[16], patient_name[32], patient_sex, patient_dexterity;
        Float32 patient_age, patient_height, patient_weight;
        uint32 patient_birth_date;
        char physician_name[32], operator_name[32], study_description[32];
        uint16_t acquisition_type, patient_orientation;
        char facility_name[20];
        uint16_t num_planes, num_frames, num_gates, num_bed_pos;
        Float32 init_bed_position;
        Float32 bed_position[15];
        Float32 plane_separation;
        uint16_t lwr_sctr_thres, lwr_true_thres, upr_true_thres;
        char user_process_code[10];
        uint16_t acquisition_mode;
        Float32 bin_size, branching_fraction;
        uint32 dose_start_time;
        Float32 dosage, well_counter_corr_factor;
        char data_units[32];
        uint16_t septa_state;
        char fill[12];
    }) ecat_main_hdr;
PACK( typedef struct {
	int16_t data_type, num_dimensions, x_dimension, y_dimension, z_dimension;
	Float32 x_offset, y_offset, z_offset, recon_zoom, scale_factor;
	int16_t image_min, image_max;
	Float32 x_pixel_size, y_pixel_size, z_pixel_size;
	int32_t frame_duration, frame_start_time;
	int16_t filter_code;
	Float32 x_resolution, y_resolution, z_resolution, num_r_elements, num_angles, z_rotation_angle, decay_corr_fctr;
	int32_t processing_code, gate_duration, r_wave_offset, num_accepted_beats;
	Float32 filter_cutoff_frequenc, filter_resolution, filter_ramp_slope;
	int16_t filter_order;
	Float32 filter_scatter_fraction, filter_scatter_slope;
	char annotation[40];
	Float32 mtx[9], rfilter_cutoff, rfilter_resolution;
	int16_t rfilter_code, rfilter_order;
	Float32 zfilter_cutoff, zfilter_resolution;
	int16_t zfilter_code, zfilter_order;
	Float32 mtx_1_4, mtx_2_4, mtx_3_4;
	int16_t scatter_type, recon_type, recon_views, fill_cti[87], fill_user[49];
}) ecat_img_hdr;
    PACK( typedef struct  {
        int32_t hdr[4], r[31][4];
    }) ecat_list_hdr;
    bool swapEndian = false;
    size_t n;
    FILE *f;
    ecat_main_hdr mhdr;
    f = fopen(fname, "rb");
    if (f)
        n = fread(&mhdr, sizeof(mhdr), 1, f);
    if(!f || n!=1) {
        printMessage("Problem reading ECAT7 file!\n");
        fclose(f);
        return NULL;
    }
    if ((mhdr.magic[0] != 'M') || (mhdr.magic[1] != 'A') || (mhdr.magic[2] != 'T')
        || (mhdr.magic[3] != 'R') || (mhdr.magic[4] != 'I') || (mhdr.magic[5] != 'X') ) {
        if (isWarnIfNotEcat)
        	printMessage("Signature not 'MATRIX' (ECAT7): '%s'\n", fname);
        fclose(f);
        return NULL;
    }
    swapEndian = mhdr.file_type > 255;
    if (swapEndian) {
        nifti_swap_2bytes(2, &mhdr.sw_version);
        nifti_swap_2bytes(1, &mhdr.file_type);
        //nifti_swap_2bytes(1, &mhdr.num_frames);
        nifti_swap_4bytes(1, &mhdr.ecat_calibration_factor);
        nifti_swap_4bytes(1, &mhdr.isotope_halflife);
        nifti_swap_4bytes(2, &mhdr.dosage);
    }
    if ((mhdr.file_type < ECAT7_2DSCAN) || (mhdr.file_type > ECAT7_3DSCANFIT)) {
        printMessage("Unknown ECAT file type %d\n", mhdr.file_type);
        fclose(f);
        return NULL;
    }
    //read list matrix
    ecat_list_hdr lhdr;
    fseek(f, 512, SEEK_SET);
    fread(&lhdr, sizeof(lhdr), 1, f);
    if (swapEndian) nifti_swap_4bytes(128, &lhdr.hdr[0]);
    //offset to first image
    int img_StartBytes = lhdr.r[0][1] * 512;
    //load image header for first image
    fseek(f, img_StartBytes - 512, SEEK_SET); //image header is block immediately before image
    ecat_img_hdr ihdr;
    fread(&ihdr, sizeof(ihdr), 1, f);
    if (swapEndian) {
    	nifti_swap_2bytes(5, &ihdr.data_type);
        nifti_swap_4bytes(5, &ihdr.x_offset);
        nifti_swap_2bytes(2, &ihdr.image_min);
        nifti_swap_4bytes(5, &ihdr.x_pixel_size);
        nifti_swap_2bytes(1, &ihdr.filter_code);
        nifti_swap_4bytes(14, &ihdr.x_resolution);
        nifti_swap_2bytes(1, &ihdr.filter_order);
        nifti_swap_4bytes(2, &ihdr.filter_scatter_fraction);
        nifti_swap_4bytes(11, &ihdr.mtx);
        nifti_swap_2bytes(2, &ihdr.rfilter_code);
        nifti_swap_4bytes(2, &ihdr.zfilter_cutoff);
        nifti_swap_2bytes(2, &ihdr.zfilter_code);
        nifti_swap_4bytes(3, &ihdr.mtx_1_4);
        nifti_swap_2bytes(3, &ihdr.scatter_type);
    }
    if ((ihdr.data_type != ECAT7_BYTE) && (ihdr.data_type != ECAT7_SUNI2) && (ihdr.data_type != ECAT7_SUNI4)) {
        printMessage("Unknown or unsupported ECAT data type %d\n", ihdr.data_type);
        fclose(f);
        return NULL;
    }
    int bytesPerVoxel = 2;
	if (ihdr.data_type == ECAT7_BYTE) bytesPerVoxel = 1;
    if (ihdr.data_type == ECAT7_SUNI4) bytesPerVoxel = 4;
    //next: read offsets for each volume: data not saved sequentially (each volume preceded by its own ecat_img_hdr)
    int num_vol = 0;
    bool isAbort = false;
    bool isScaleFactorVaries = false;
    #define kMaxVols 16000
	size_t * imgOffsets = (size_t *)malloc(sizeof(size_t) * (kMaxVols));
    float * imgSlopes = (float *)malloc(sizeof(float) * (kMaxVols));
    ecat_img_hdr ihdrN;
    while ((lhdr.hdr[0]+lhdr.hdr[3]) == 31) { //while valid list
    	if (num_vol > 0) { //read the next list
    		fseek(f, 512 * (lhdr.hdr[1] -1), SEEK_SET);
    		fread(&lhdr, 512, 1, f);
    		if (swapEndian) nifti_swap_4bytes(128, &lhdr.hdr[0]);
    	}
		if ((lhdr.hdr[0]+lhdr.hdr[3]) != 31) break; //if valid list
		if (lhdr.hdr[3] < 1) break;
		for (int k = 0; k < lhdr.hdr[3]; k++) {
    		//check images' ecat_img_hdr matches first
    		fseek(f, (lhdr.r[k][1]-1) * 512, SEEK_SET); //image header is block immediately before image
    		fread(&ihdrN, sizeof(ihdrN), 1, f);
    		if (swapEndian) {
				nifti_swap_2bytes(5, &ihdrN.data_type);
				nifti_swap_4bytes(5, &ihdrN.x_offset);
				nifti_swap_2bytes(2, &ihdrN.image_min);
				nifti_swap_4bytes(5, &ihdrN.x_pixel_size);
				nifti_swap_2bytes(1, &ihdrN.filter_code);
				nifti_swap_4bytes(14, &ihdrN.x_resolution);
				nifti_swap_2bytes(1, &ihdrN.filter_order);
				nifti_swap_4bytes(2, &ihdrN.filter_scatter_fraction);
				nifti_swap_4bytes(11, &ihdrN.mtx);
				nifti_swap_2bytes(2, &ihdrN.rfilter_code);
				nifti_swap_4bytes(2, &ihdrN.zfilter_cutoff);
				nifti_swap_2bytes(2, &ihdrN.zfilter_code);
				nifti_swap_4bytes(3, &ihdrN.mtx_1_4);
				nifti_swap_2bytes(3, &ihdrN.scatter_type);
			}
    		if (ihdr.scale_factor != ihdrN.scale_factor)
    			isScaleFactorVaries = true;
    		if ((ihdr.data_type != ihdrN.data_type) || (ihdr.x_dimension != ihdrN.x_dimension) || (ihdr.y_dimension != ihdrN.y_dimension) || (ihdr.z_dimension != ihdrN.z_dimension)) {
    			printError("Error: ECAT volumes have varying image dimensions\n");
    			isAbort = true;
    		}
    		if (num_vol < kMaxVols) {
    			imgOffsets[num_vol]	= lhdr.r[k][1];
    			imgSlopes[num_vol] = ihdrN.scale_factor;
    		}
    		num_vol ++;
    	}
    	if ((lhdr.hdr[0] > 0) || (isAbort)) break; //this list contains empty volumes: all lists have been read
    } //read all image offsets
    //report error reading image offsets
    if ((num_vol < 1) || (isAbort) || (num_vol >= kMaxVols)) {
        printMessage("Failure to extract ECAT7 images\n");
        if (num_vol >= kMaxVols) printMessage("Increase kMaxVols");
        fclose(f);
        free (imgOffsets);
        free(imgSlopes);
        return NULL;
    }
    if ((isScaleFactorVaries) && (bytesPerVoxel != 2)) {
    	printError("ECAT scale factor varies between volumes (check for updates) '%s'\n", fname);
        fclose(f);
        free (imgOffsets);
        free(imgSlopes);
        return NULL;
	}
	//load image data
	unsigned char * img = NULL;
	if ((isScaleFactorVaries) && (bytesPerVoxel == 2)) { //we need to convert volumes from 16-bit to 32-bit to preserve scaling factors
		int num_vox = ihdr.x_dimension * ihdr.y_dimension * ihdr.z_dimension;
		size_t bytesPerVolumeIn = num_vox * bytesPerVoxel; //bytesPerVoxel == 2
		unsigned char * imgIn = (unsigned char*)malloc(bytesPerVolumeIn);
		int16_t * img16i = (int16_t*) imgIn;
		bytesPerVoxel = 4;
		size_t bytesPerVolume = num_vox * bytesPerVoxel;
		img = (unsigned char*)malloc(bytesPerVolume * num_vol);
		float * img32 = (float*) img;
		for (int v = 0; v < num_vol; v++) {
			fseek(f, imgOffsets[v] * 512, SEEK_SET);
			fread( &imgIn[0], 1, bytesPerVolumeIn, f);
			if (swapEndian)
				nifti_swap_2bytes(num_vox, imgIn);
			int volOffset = v * num_vox;
			float scale = imgSlopes[v] * mhdr.ecat_calibration_factor;
			for (int i = 0; i < num_vox; i++)
				img32[i+volOffset] = (img16i[i] * scale);
		}
		//we have applied the scale factors to the data, so eliminate them
		ihdr.scale_factor = 1.0;
		mhdr.ecat_calibration_factor = 1.0;

	} else { //if isScaleFactorVaries else simple conversion
		size_t bytesPerVolume = ihdr.x_dimension * ihdr.y_dimension * ihdr.z_dimension * bytesPerVoxel;
		img = (unsigned char*)malloc(bytesPerVolume * num_vol);
		for (int v = 0; v < num_vol; v++) {
			fseek(f, imgOffsets[v] * 512, SEEK_SET);
			size_t  sz = fread( &img[v * bytesPerVolume], 1, bytesPerVolume, f);
            if (sz != bytesPerVolume) {
                free(img);
                return NULL;
            }
		}
		if ((swapEndian) && (bytesPerVoxel == 2)) nifti_swap_2bytes(ihdr.x_dimension * ihdr.y_dimension * ihdr.z_dimension * num_vol, img);
		if ((swapEndian) && (bytesPerVoxel == 4)) nifti_swap_4bytes(ihdr.x_dimension * ihdr.y_dimension * ihdr.z_dimension * num_vol, img);
	}
	printWarning("ECAT support VERY experimental (Spatial transforms unknown)\n");
    free (imgOffsets);
    free(imgSlopes);
    fclose(f);
    //fill DICOM header
    float timeBetweenVolumes = ihdr.frame_duration;
    if (num_vol > 1)
    	timeBetweenVolumes = (float)(ihdrN.frame_start_time- ihdr.frame_start_time)/(float)(num_vol-1);
    //copy and clean strings (ECAT can use 0x0D as a string terminator)
    strncpy(dcm->patientName, mhdr.patient_name, 32);
    strncpy(dcm->patientID, mhdr.patient_id, 16);
    strncpy(dcm->seriesDescription, mhdr.study_description, 32);
    strncpy(dcm->protocolName, mhdr.study_type, 12);
    strncpy(dcm->imageComments, mhdr.isotope_name, 8);
	strncpy(dcm->procedureStepDescription, mhdr.radiopharmaceutical, 32);
	strClean(dcm->patientName);
	strClean(dcm->patientID);
	strClean(dcm->seriesDescription);
	strClean(dcm->protocolName);
	strClean(dcm->imageComments);
	strClean(dcm->procedureStepDescription);
	dcm->ecat_dosage = mhdr.dosage;
	dcm->ecat_isotope_halflife = mhdr.isotope_halflife;
    if (opts.isVerbose) {
    	printMessage("ECAT7 details for '%s'\n", fname);
    	printMessage(" Software version %d\n", mhdr.sw_version);
    	printMessage(" System Type %d\n", mhdr.system_type);
    	printMessage(" Frame duration %dms\n", ihdr.frame_duration);
    	printMessage(" Time between volumes %gms\n", timeBetweenVolumes );
    	printMessage(" Patient name '%s'\n", dcm->patientName);
    	printMessage(" Patient ID '%s'\n", dcm->patientID);
    	printMessage(" Study description '%s'\n", dcm->seriesDescription);
    	printMessage(" Study type '%s'\n", dcm->protocolName);
    	printMessage(" Isotope name '%s'\n", dcm->imageComments);
    	printMessage(" Isotope halflife %gs\n", mhdr.isotope_halflife);
    	printMessage(" Radiopharmaceutical '%s'\n", dcm->procedureStepDescription);
    	printMessage(" Dosage %gbequerels/cc\n", mhdr.dosage);
    	if (!isScaleFactorVaries) {
    		printMessage(" Scale factor %12.12g\n", ihdr.scale_factor);
    		printMessage(" ECAT calibration factor %8.12g\n", mhdr.ecat_calibration_factor);
    	}
    	printMessage(" NIfTI scale slope %12.12g\n",ihdr.scale_factor * mhdr.ecat_calibration_factor);
    }
	dcm->manufacturer = kMANUFACTURER_SIEMENS;
	//dcm->manufacturersModelName = itoa(mhdr.system_type);
	sprintf(dcm->manufacturersModelName, "%d", mhdr.system_type);
    dcm->bitsAllocated = bytesPerVoxel * 8;
    if (isScaleFactorVaries) dcm->isFloat = true;
    dcm->bitsStored = 15; //ensures 16-bit images saved as INT16 not UINT16
	dcm->samplesPerPixel = 1;
	dcm->xyzMM[1] = ihdr.x_pixel_size * 10.0; //cm -> mm
	dcm->xyzMM[2] = ihdr.y_pixel_size * 10.0; //cm -> mm
	dcm->xyzMM[3] = ihdr.z_pixel_size * 10.0; //cm -> mm
	dcm->TR = timeBetweenVolumes;
	dcm->xyzDim[1] = ihdr.x_dimension;
	dcm->xyzDim[2] = ihdr.y_dimension;
	dcm->xyzDim[3] = ihdr.z_dimension;
    dcm->xyzDim[4] = num_vol;
    //create a NIfTI header
	headerDcm2Nii(*dcm, hdr, false);
	//here we mimic SPM's spatial starting estimate SForm
	mat44 m44;
	LOAD_MAT44(m44, -hdr->pixdim[1], 0.0f, 0.0f, ((float)dcm->xyzDim[1]-2.0)/2.0*dcm->xyzMM[1],
		0.0f, -hdr->pixdim[2], 0.0f, ((float)dcm->xyzDim[2]-2.0)/2.0*dcm->xyzMM[2],
		0.0f, 0.0f, -hdr->pixdim[3], ((float)dcm->xyzDim[3]-2.0)/2.0*dcm->xyzMM[3]);
	setQSForm(hdr, m44, false);
	//make sure image does not include a spatial matrix
	bool isMatrix = false;
	for (int i = 0; i < 9; i++)
		if (ihdr.mtx[i] != 0.0) isMatrix = true;
	if (isMatrix)
		printWarning("ECAT volume appears to store spatial transformation matrix (please check for updates)\n");
	hdr->scl_slope = ihdr.scale_factor * mhdr.ecat_calibration_factor;
    if (mhdr.gantry_tilt != 0.0) printMessage("Warning: ECAT gantry tilt not supported %g\n", mhdr.gantry_tilt);
    return img;
}
コード例 #25
0
void 
OpenSteer::OpenSteerDemo::printMessage (const std::ostringstream& message)
{
    printMessage (message.str().c_str());
}
コード例 #26
0
void Inventory::CalculateWeight()
{
	if (!Changed) {
		return;
	}
	Weight = 0;
	for (size_t i = 0; i < Slots.size(); i++) {
		CREItem *slot = Slots[i];
		if (!slot) {
			continue;
		}
		//printf ("%2d: %8s : %d x %d\n", (int) i, slot->ItemResRef, slot->Weight, slot->Usages[0]);
		if (slot->Weight == -1) {
			Item *itm = gamedata->GetItem( slot->ItemResRef );
			if (itm) {
				//simply adding the item flags to the slot
				slot->Flags |= (itm->Flags<<8);
				//some slot flags might be affected by the item flags
				if (!(slot->Flags & IE_INV_ITEM_CRITICAL)) {
					slot->Flags |= IE_INV_ITEM_DESTRUCTIBLE;
				}
				//this is for converting IWD items magic flag
				if (MagicBit) {
					if (slot->Flags&IE_INV_ITEM_UNDROPPABLE) {
						slot->Flags|=IE_INV_ITEM_MAGICAL;
						slot->Flags&=~IE_INV_ITEM_UNDROPPABLE;
					}
				}

				if (!(slot->Flags & IE_INV_ITEM_MOVABLE)) {
					slot->Flags |= IE_INV_ITEM_UNDROPPABLE;
				}

				if (slot->Flags & IE_INV_ITEM_STOLEN2) {
					slot->Flags |= IE_INV_ITEM_STOLEN;
				}

				//auto identify basic items
				if (!itm->LoreToID) {
					slot->Flags |= IE_INV_ITEM_IDENTIFIED;
				}

				//if item is stacked mark it as so
				if (itm->StackAmount) {
					slot->Flags |= IE_INV_ITEM_STACKED;
				}

				slot->Weight = itm->Weight;
				slot->StackAmount = itm->StackAmount;
				gamedata->FreeItem( itm, slot->ItemResRef, false );
			}
			else {
				printMessage( "Inventory", " ", LIGHT_RED);
				printf("Invalid item: %s!\n", slot->ItemResRef);
				slot->Weight = 0;
			}
		} else {
			slot->Flags &= ~IE_INV_ITEM_ACQUIRED;
		}
		if (slot->Weight > 0) {
			Weight += slot->Weight * ((slot->Usages[0] && slot->StackAmount > 1) ? slot->Usages[0] : 1);
		}
	}
	Changed = false;
}
コード例 #27
0
ファイル: Basename.cpp プロジェクト: MarcMil/cdt
int main(int nArgs, char **args) {
    printMessage("Hello, world!\n");
    printMessage("$(baseName)");
}
コード例 #28
0
static void InvalidSlot(int slot)
{
	printMessage("Inventory"," ",LIGHT_RED);
	printf("Invalid slot: %d!\n",slot);
	abort();
}
コード例 #29
0
ファイル: firestudio_tube.cpp プロジェクト: EMATech/ffado
//
// 192 kHz is not supported
//
void FirestudioTube::FirestudioTubeEAP::setupSources_high() {
    printMessage("High (192 kHz) sample rate not supported by Firestudio Tube\n");
}
コード例 #30
0
ファイル: main.c プロジェクト: Anon1234/obshutdown
void initWidgets(void)
{
	guint i;
	GtkWidget *hboxWidget = NULL;
	GdkColor color = myTheme.win_bg_color;

	// TODO: Typ okna
	winWidget = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_container_set_border_width(GTK_CONTAINER(winWidget), 8);
	gtk_window_set_title(GTK_WINDOW(winWidget), OBS_TITLE);
	gtk_widget_set_size_request(winWidget, myTheme.win_size_width, myTheme.win_size_heigh);
	if (myOptions.composite)
		gdk_color_parse("black", &color);
	gtk_widget_modify_bg(winWidget, GTK_STATE_NORMAL, &color);
	gtk_window_set_decorated(GTK_WINDOW(winWidget), myTheme.win_decor);
	gtk_window_set_skip_taskbar_hint(GTK_WINDOW(winWidget), TRUE);
	gtk_window_set_skip_pager_hint(GTK_WINDOW(winWidget), TRUE);
	GTK_WIDGET_SET_FLAGS(winWidget, GTK_CAN_FOCUS);

	gtk_widget_set_app_paintable(winWidget, TRUE);
	if (myTheme.win_pos == T_WIN_POS_CENTER) /* Window position - center */
		gtk_window_set_position(GTK_WINDOW(winWidget), GTK_WIN_POS_CENTER);
	else if (myTheme.win_pos == T_WIN_POS_CUSTOM) { /* Window position - custom */
		gtk_window_set_position(GTK_WINDOW(winWidget), GTK_WIN_POS_NONE);
		gtk_window_move(GTK_WINDOW(winWidget), myTheme.win_pos_x, myTheme.win_pos_y);
	}

	if (myTheme.win_size == T_WIN_SIZE_FULLSCREEN) /* Window size - fullscreen */
		gtk_window_resize(GTK_WINDOW(winWidget), gdk_screen_get_width(gdk_screen_get_default()), gdk_screen_get_height(gdk_screen_get_default()));
	else if (myTheme.win_size == T_WIN_SIZE_CUSTOM) /* Window size - custom */
		gtk_window_resize(GTK_WINDOW(winWidget), myTheme.win_size_width, myTheme.win_size_heigh);

	g_signal_connect(winWidget, "destroy", G_CALLBACK(onDestroy), NULL);
	g_signal_connect(winWidget, "key_press_event", G_CALLBACK(onKeyPress), NULL);
	g_signal_connect(winWidget, "window_state_event", G_CALLBACK(onWindowStateChange), NULL);
	g_signal_connect(winWidget, "show", G_CALLBACK(onWindowShow), NULL);

	if (myOptions.composite) {
		if (gtk_widget_is_composited(winWidget)) {
			printMessage(MSG_VERB, "Compositing enabled.\n");
			g_signal_connect(winWidget, "expose_event", G_CALLBACK(onExpose), NULL);
			g_signal_connect(winWidget, "screen-changed", G_CALLBACK(onScreenChanged), NULL);
			onScreenChanged(winWidget, NULL, NULL);
		} else {
			printMessage(MSG_WARN, "No compositing, enabling rendered effects!\n");
			myOptions.composite = FALSE;
		}

	}
	else {
		printMessage(MSG_VERB,  "Compositing disabled.\n");
	}

	hboxWidget = gtk_hbox_new(FALSE, 0);
	hboxButtonWidget = gtk_hbutton_box_new();
	/*gtk_hbutton_box_set_spacing_default(10);*/

	gtk_box_pack_start(GTK_BOX(hboxWidget), gtk_vbox_new(TRUE, 0), TRUE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(hboxWidget), hboxButtonWidget, FALSE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(hboxWidget), gtk_vbox_new(TRUE, 0), TRUE, TRUE, 0);

	gtk_container_add(GTK_CONTAINER(winWidget), hboxWidget);

	if (myOptions.buttons[0] != ACTION_NONE) {
		for (i = 0; i <= 8; i++)
			if (myOptions.buttons[i] != ACTION_NONE)
				addButton(myOptions.buttons[i]);
	}
	else {
		addButton(ACTION_CANCEL);
		addButton(ACTION_LOGOUT);
		addButton(ACTION_RESTART);
		addButton(ACTION_SHUTDOWN);
	}
}