Esempio n. 1
0
void string_of_float_aux(char* format_buffer, double x)
{
  sprintf(format_buffer, "%.12g", x);
  mkSMLMinus(format_buffer);
  if( countChar('.', format_buffer) == 0 &&
      countChar('E', format_buffer) == 0 )
    strcat(format_buffer, ".0");
}
Esempio n. 2
0
String
REG_POLY_FUN_HDR(stringOfFloat, Region rAddr, size_t arg) 
{
  char buf[64];
  sprintf(buf, "%.12g", get_d(arg));
  mkSMLMinus(buf);
  if( countChar('.', buf) == 0 && countChar('E', buf) == 0 ) 
    {
      strcat(buf, ".0");
    }
  return REG_POLY_CALL(convertStringToML, rAddr,buf);
}
Esempio n. 3
0
/* print the longest input line */
main()
{
    int len, charLen;                /* current line length */
    int max;                /* maximum length seen so far */
    char line[MAXLINE];     /* current input line */
    char longest[MAXLINE];   /* longest line saved here */
    
    max = 0;
    while ((len = getline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            copy(longest, line);
        }
    if (max > 80) {    /* there was a line */
        charLen = countChar(longest);
        printf("%d %s %d\n", len, longest, charLen);
    }
    return 0;
}
Esempio n. 4
0
void xbString::addBackSlash( char c )
{
 /* prefixes all char "c" with a backslash */
 int i, t, cnt;
 xbString ws;
  
  cnt = countChar( c );
  if( !cnt )
    return;
    
  ws.resize( size+cnt );
  for( i = 0, t = 0; i < (int)size; i++ ){
    if( data[i] == c )
      ws.putAt( t++, '\\' );
    ws.putAt( t++, data[i] );
  }
  ws.putAt( t, 0 );
  *this = ws.getData();
}
int main() {
   char string[50] = "Once upon a time", ch = 'n';
   int array[50], charCount, intCount, index = 7;

   array[0] = -99;
   array[1] = -98;
   array[2] = -99;
   array[3] = -98;
   array[4] = -99;


   charCount = countChar(string, ch);

   intCount = countReverses(array, index);

   printf("Number of characters '%c' is: %d\n", ch, charCount);
   printf("Number of reversals in array is: %d\n", intCount);

   return 0;
}
Esempio n. 6
0
static int bf_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *buf, int len) {
	ut64 dst = 0LL;
	if (op == NULL)
		return 1;
	/* Ayeeee! What's inside op? Do we have an initialized RAnalOp? Are we going to have a leak here? :-( */
	memset (op, 0, sizeof (RAnalOp)); /* We need to refactorize this. Something like r_anal_op_init would be more appropiate */
	r_strbuf_init (&op->esil);
	op->size = 1;
	switch (buf[0]) {
	case '[': op->type = R_ANAL_OP_TYPE_CJMP;
		  op->fail = addr+1;
		  {
			 const ut8 *p = buf + 1;
			 int lev = 0, i = 1;
			 while (*p && i<len) {
				 if (*p == '[')
					 lev++;
				 if (*p == ']') {
					 lev--;
					 if (lev==-1) {
						 dst = addr + (size_t)(p-buf);
						 dst ++;
						 op->jump = dst;
						 r_strbuf_setf (&op->esil,
							 "pc,brk,=[1],brk,++=,"
							 "ptr,[1],!,?{,0x%"PFMT64x",pc,=,}", dst);
						 break;
					 }
				 }
				 p++;
				i++;
			 }
		  }
	// ?1[ptr],pc=${NEW_PC
	break;
	case ']': op->type = R_ANAL_OP_TYPE_UJMP;
		// XXX This is wrong esil
		r_strbuf_set (&op->esil, "brk,--=,brk,[1],pc,=");
		break;
	case '>': op->type = R_ANAL_OP_TYPE_ADD;
		r_strbuf_set (&op->esil, "ptr,++=");
		break;
	case '<': op->type = R_ANAL_OP_TYPE_SUB;
		r_strbuf_set (&op->esil, "ptr,--=");
		break;
	case '+':
		op->size = countChar (buf, len, '+');
		op->type = R_ANAL_OP_TYPE_ADD;
		r_strbuf_setf (&op->esil, "ptr,[1],%d,+,ptr,=[1]", op->size);
		break;
	case '-':
		op->type = R_ANAL_OP_TYPE_SUB;
		op->size = countChar (buf, len, '-');
		r_strbuf_setf (&op->esil, "ptr,[1],%d,-,ptr,=[1]", op->size);
		break;
	case '.':
		// print element in stack to screen
		op->type = R_ANAL_OP_TYPE_STORE;
		r_strbuf_set (&op->esil, "ptr,[1],scr,=[1],scr,++=");
		break;
	case ',':
		op->type = R_ANAL_OP_TYPE_LOAD;
		r_strbuf_set (&op->esil, "kbd,[1],ptr,=[1],kbd,++=");
		break;
	case 0x00:
	case 0xff:
		op->type = R_ANAL_OP_TYPE_TRAP;
		break;
	default:
		op->type = R_ANAL_OP_TYPE_NOP;
		r_strbuf_set (&op->esil, ",");
		break;
	}
	return op->size;
}
Esempio n. 7
0
/** parse: parse user input and call the appropriate commands
 * @param input - user input (beginning with "cd ")
 * @return ERROR_CODE if anything throws an error
 */
int parse(char * input) {

	// helpers
	char util[SIZE];
	int savedSTDOUT = -1;

	// grab command
	strcpy(util, input);
	char * ptr = strtok(util, "> ");
	char * cmd = ptr;

	/* builtin: '!!' and '!n' */

	// '!!' run last command
	if (strcmp(bangbang, cmd) == 0) {

		// no commands yet
		if (historyCount == 0) {
			return throwError();
		}
		strcpy(input, historyArr[historyCount-1]);

		// reset command
		strcpy(util, input);
		ptr = strtok(util, "> ");
		cmd = ptr;
	}

	// '!n' run nth command in history
	else if (strncmp(bang, cmd, 1) == 0) {
		// no commands yet
		if (historyCount == 0) {
			return throwError();
		}

		int len = strlen(cmd);

		// if we get more than just '!'
		if (len != 1) {
			int ind = 1;
			long n = atoi(&cmd[ind]); // # of the entry requested

			// if the entry # is valid and within the last 10
			if (n < historyCount && n > historyCount-10) {
				strcpy(input, historyArr[n]);

				// reset command
				strcpy(util, input);
				ptr = strtok(util, "> ");
				cmd = ptr;
			}

			// the entry # is not valid
			else { return throwError(); }
		}
		// we only got a '!'
		else { return throwError(); }
	}

	// add last command to history
	addToHistory(input);


	/* checking for redirection */

	int arrCount = countChar(input, '>');

	// if there's a redirection
	if (arrCount > 0) {
		char * out = NULL;
		int args = 0;

		// while there are args
		while (ptr != NULL) {
			// more than one '>'
			if (arrCount > 1) { return throwError(); }
			// first argument
			else if (args == 0) {}
			// second argument
			else if (args == 1) { out = ptr; }
			// more than two args
			else { return throwError(); }

			// increment
			ptr = strtok(NULL, "> ");
			args++;
		}

		// check that we have 2 args and that the '>' comes after the two args
		if (args != 2 || strlen(out) + strlen(cmd) < findFirst(input, '>')) {
			return throwError();
		}

		// set redirect for outfile
		int outfile = open(out, O_RDWR|O_TRUNC|O_CREAT, S_IRUSR|S_IWUSR|S_IXUSR);
		savedSTDOUT = dup(STDOUT_FILENO);
		dup2(outfile, STDOUT_FILENO);
		close(outfile);
	}

	// recopy util
	strcpy(util, input);
	cmd = strtok(util, "> ");


	/* remaining builtins */

	// cd
	if (strcmp(cd, cmd) == 0) {
		changeDirectory(input);
	}

	// print working directory pwd
	else if (strcmp(pwd, cmd) == 0) {
		memset(&util[0], 0, sizeof(util));
		getcwd(util, SIZE);
		strcat(util, "\n");
		write(STDOUT_FILENO, (void*) util, sizeof(util));
	}

	// history
	else if (strcmp(history, cmd) == 0) {
		printHistory();
	}

	// wait
	else if (strcmp(_wait, cmd) == 0) {
		wait(0);
	}

	// exit
	else if (strcmp(ciao, cmd) == 0) {
		clearStack();
		clearCopyStack();
		return FORCE_EXIT;
	}

	// reset bools
	if (savedSTDOUT != -1) {
		dup2(savedSTDOUT, STDOUT_FILENO);
		savedSTDOUT = -1;
	}
	return SUCCESS;
}
Esempio n. 8
0
/* Main function of the program. Takes in file name as arguement. */
int main(int argc, char *argv[]){
    // Returns error if improper amount of files passed into the program
	if(argc==2){
		printf("The name of the file is missing!\n"); 
		return 0; 
	}

    // Calls countChar and passes file 1
	countChar(argv[1]);
    
    struct tree *t;
    int i;
    
    // Takes counts and initializes leaves and inserts into heap. This loop has a run time of O(n).
    for(i=0; i<256; i++){
        if(counts[i]!=0){
            t=createTree(counts[i], NULL, NULL);
            assert(t!=NULL);
            leaves[i]=t;
            insert(t);
        }
        else{
            leaves[i]=NULL;
        }
    }
    
    // Adds the end-of-file marker
    leaves[256]=createTree(0, NULL, NULL);
    assert(leaves[256]!=NULL);
    insert(leaves[256]);

    struct tree *x, *y, *tree;
    int data;
    
    // Generates the huffman tree while there is more than 1 tree in the heap. This loop has a run time of O(n).
    while(count>1){
        x=delete();
        y=delete();
        data=getData(x)+getData(y);
        tree=createTree(data, x, y);
        assert(tree!=NULL);
        insert(tree);
    }
    
    // Prints out each unique character present in the file, its count, as well as the corresponding binary. This loop as a run time of O(n).
    for(i=0; i<257; i++){
        if(leaves[i]!=NULL){
            if(isprint(i)!=0){ // Checks if the character is printable
                printf("'%c': %d: ", i, counts[i]);
            }
            else{
                printf("%03o: : %d: ", i, counts[i]);
            }
            print(leaves[i]);
            printf("\n");
        }
    }
    
    // Calls pack to compress the file
    pack(argv[1], argv[2], leaves);

	return 0; 
}
Esempio n. 9
0
void runProg(const char *progName,const char *progPath,const char *parameters,int amp_flag){
	int pid,status;
	char progPathName[PROGRUNBUFFER];
	char *arglist[MAXNUMOFARGUMENTS+1];
	char *pathList[MAXPATHCOUNT];
	for(int i=0;i<MAXPATHCOUNT;i++){
		pathList[i]=(char *)malloc(sizeof(char)*MAXPATHSIZE);
	}
	for(int i=0;i<MAXNUMOFARGUMENTS+1;i++){
		arglist[i] = (char *)malloc(sizeof(char)*MAXARGSIZE);
	}
	int pSize = strlen(parameters);
	char parameterX[pSize+1];
	copyString(parameterX,parameters);
	int argCount = countChar(parameterX,' ')+1;
	// printf("\nARG-COUNT = %d\n",argCount);
	if(argCount>MAXNUMOFARGUMENTS){
		printf("\nERROR : can not have more than %d arguments\n",MAXNUMOFARGUMENTS);
		return;
	}
	lineToWords(parameters,arglist+1,&argCount,' ');
	copyString(arglist[0],progName);
	// printf("\nargCount = %d",argCount);
	argCount++;
	// for(int i=0;i<argCount;i++){
	// 	printf("\narg[%d] = {%s}",i,arglist[i]);
	// }
	// printf("\n");
	free(arglist[argCount]);
	arglist[argCount]=NULL;
	sprintf(progPathName,"%s%s",progPath,progName);
	int success=0;
	pid = fork();
	if(pid == 0){
		// assuming prog is in current directory
		success = execv(progPathName,arglist);
		if(success==-1){
			// if the previous execv is failed
			// then try execv for different path combinations
			char* pPath;
			pPath = getenv ("PATH");
			int pathCount;
			pathCount = countChar(pPath,':')+1;
			lineToWords(pPath,pathList,&pathCount,':');
			// printf("\nPATH COUNT = %d\n",pathCount);
			// for(int i=0;i<pathCount;i++){
			// 	printf("\nPATH[%d] = {%s}",i,pathList[i]);
			// }
			for(int i=0;i<pathCount;i++){
				sprintf(progPathName,"%s/%s",pathList[i],progName);
				success = execv(progPathName,arglist);
			}
			if(success == -1){
				printf("\nERROR : INVALID COMMAND--{%s}\n",progName);
			}
		}
	}else{
		if(amp_flag == 1){
			printf("\nPID = %d",pid);
		}else{
			waitpid(pid,&status,0);
		}
	}
	for(int i=0;i<argCount;i++){
		free(arglist[i]);
	}
	for(int i=argCount+1;i<MAXNUMOFARGUMENTS+1;i++){
		free(arglist[i]);
	}
	for(int i=0;i<MAXPATHCOUNT;i++){
		free(pathList[i]);
	}
	// printf("PROCESS EXIT STATUS = %d\n",WEXITSTATUS(status));
	return;
}
Esempio n. 10
0
int execwrapper(char *cmd){
	// printf("\nIN EXECWRAPPER\n");
	// sleep(1);

	char parameterX[BUFFER];
	char progName[PROGRUNBUFFER];
	char progPath[PROGRUNBUFFER];// useless ... may take a default path parameter
	// in future
	char progPathName[2*PROGRUNBUFFER];
	progPath[0] = '\0';
	progName[0] = '\0';
	parameterX[0] = '\0';

	getFirstWord(cmd,progName,parameterX);

	char *arglist[MAXNUMOFARGUMENTS+1];
	char *pathList[MAXPATHCOUNT];
	for(int i=0;i<MAXPATHCOUNT;i++){
		pathList[i]=(char *)malloc(sizeof(char)*MAXPATHSIZE);
	}
	for(int i=0;i<MAXNUMOFARGUMENTS+1;i++){
		arglist[i] = (char *)malloc(sizeof(char)*MAXARGSIZE);
	}
	int argCount = countChar(parameterX,' ')+1;
	if(argCount>MAXNUMOFARGUMENTS){
		// printf("\nERROR : can not have more than %d arguments\n",MAXNUMOFARGUMENTS);
		return -1;
	}
	lineToWords(parameterX,arglist+1,&argCount,' ');
	copyString(arglist[0],progName);
	argCount++;
	free(arglist[argCount]);
	arglist[argCount]=NULL;
	sprintf(progPathName,"%s%s",progPath,progName);
	// printf("\nPROGPATHNAME = {%s}",progName);
	// printf("\nparameterX = {%s}",parameterX);
	// printf("\nPROGPATHNAME = {%s}",progPathName);
	int success=0;
	// assuming prog is in current directory
	success = execv(progPathName,arglist);
	if(success==-1){
		// if the previous execv is failed
		// then try execv for different path combinations
		// printf("\nEXEC UNSUCCESSFULL !!\n");
		// sleep(1);
		char* pPath;
		pPath = getenv ("PATH");
		int pathCount;
		pathCount = countChar(pPath,':')+1;
		lineToWords(pPath,pathList,&pathCount,':');
		for(int i=0;i<pathCount;i++){
			sprintf(progPathName,"%s/%s",pathList[i],progName);
			success = execv(progPathName,arglist);
		}
		if(success == -1){
			// printf("\nERROR : INVALID COMMAND--{%s}\n",progName);
		}
	}
	for(int i=0;i<argCount;i++){
		free(arglist[i]);
	}
	for(int i=argCount+1;i<MAXNUMOFARGUMENTS+1;i++){
		free(arglist[i]);
	}
	for(int i=0;i<MAXPATHCOUNT;i++){
		free(pathList[i]);
	}
	return success;
}
Esempio n. 11
0
int readOBJ(struct OBJ_Model * obj)
{

  if (obj->filename == 0 ) { fprintf(stderr,"readOBJ called with a null filename , cannot continue \n"); return 0; }
  /* Read the .obj model from file FILENAME */
  /* All faces are converted to be triangles */
  FILE *file=0;
  char buf[128];
  char buf1[128];
  unsigned int wrongDecimalSeperatorBug=0;
  long unsigned int    numvertices;		/* number of vertices in model */
  long unsigned int    numnormals;                 /* number of normals in model */
  long unsigned int    numcolors;
  long unsigned int    numtexs;                 /* number of normals in texture coordintaes */
  long unsigned int    numfaces;			/* number of faces in model */
  long unsigned int    numgroups;			/* number of groups in model */
  GLuint cur_group,material, mat;
  long unsigned int v,n,t,i;
  int grp;

  fprintf(stderr,"TODO : proper string allocation here for filename %s \n",obj->filename);
  char fname[2*MAX_MODEL_PATHS+1]={0};
  snprintf(fname,2*MAX_MODEL_PATHS,"%s/%s.obj",obj->directory , obj->filename);

  fprintf(stderr,"Opening File %s ..\n",fname);
  file=fopen(fname,"r");
  if(file==0) { fprintf(stderr,"Could not open file %s for reading Object\n",fname); return 0;  }
 // strcpy(name,filename);
  strcpy(obj->matLib,"");
  //Group Pass
  rewind(file);
  numgroups = 1;
  while(fscanf(file, "%s", buf) != EOF)
  {
	  if(buf[0]=='g')
		  numgroups++;
	  else
		  fgets(buf, sizeof(buf), file); // eat up rest of line
  }
  if(numgroups==0) { numgroups=1; }
  obj->groups = (Group*) malloc(sizeof(Group)* numgroups);
  if (obj->groups == 0) { fprintf(stderr,"Could not make enough space for %lu groups \n",numgroups); fclose(file); return 0; }
  obj->numGroups = 0;
  obj->numFaces =0;

  // 1st Pass
  rewind(file);
  numtexs = 0;
  numvertices = 0;
  numnormals = 0;
  numcolors = 0;
  numfaces = 0;
  cur_group = AddGroup(obj,"default");
  obj->groups[0].material=0;
  while(fscanf(file, "%s", buf) != EOF)
  {

	  if(strcmp(buf, "mtllib")==0)
	  {
		  fscanf(file, "%s", buf1);
		  strcpy(obj->matLib,  buf1);
		  loadMTL(obj,obj->directory ,buf1);
		  printf("loadmtl %s survived\n", obj->matLib);
	  }
    switch(buf[0])
    {
    case '#':	fgets(buf, sizeof(buf), file);	 break;		// comment   eat up rest of line

    // v, vn, vt
    case 'v':
               switch(buf[1])
               {
                  case '\0': // vertex  eat up rest of line
	                         fgets(buf, sizeof(buf), file);
	                         numvertices++;
	                         if (floatingPointCheck(buf,strlen(buf)) ) { ++wrongDecimalSeperatorBug; }
	                         if (countChar(buf,strlen(buf),' ',buf[1])==6) { numcolors++ ; } //meshlab extension for colors on obj files
	              break;
                  case 'n': // normal  eat up rest of line
	                         fgets(buf, sizeof(buf), file);
	                         numnormals++;
                  break;
                  case 't':	//texture coordinate  eat up rest of line
	                         fgets(buf, sizeof(buf), file);
	                         numtexs ++;
	              break;
                  default:
	                         fprintf(stderr,"Unexpected characters  ( \"%s\" ) while waiting for v, vn ,vt .\n", buf);
	                         return 0;
	              break;
                }
     break;

     case 'm': fgets(buf, sizeof(buf), file);  break;
     case 'u': fgets(buf, sizeof(buf), file);  break;// eat up rest of line

     case 'g': //group eat up rest of line
               fgets(buf, sizeof(buf), file);
               sscanf(buf, "%s", buf);
	           cur_group = AddGroup(obj,buf);
     break;

     case 'f':	// face
                v =0; n = 0; t = 0;
                fscanf(file, "%s", buf); // can be one of %d, %d//%d, %d/%d, %d/%d/%d
                if (strstr(buf, "//"))
                  { //        v//n
	                sscanf(buf, "%d//%d", &v, &n);
	                fscanf(file, "%d//%d", &v, &n);
	                fscanf(file, "%d//%d", &v, &n);
	                obj->numFaces++;
	                while(fscanf(file, "%d//%d", &v, &n) > 0) { obj->numFaces++; }
	              } else
                if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3)
                  { //        v/t/n
	                fscanf(file, "%d/%d/%d", &v, &t, &n);
	                fscanf(file, "%d/%d/%d", &v, &t, &n);
	                obj->numFaces++;
	                while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0) { obj->numFaces++; }
	               } else
                if (sscanf(buf, "%d/%d", &v, &t) == 2)
                  { //        v/t
	                fscanf(file, "%d/%d", &v, &t);
	                fscanf(file, "%d/%d", &v, &t);
	                obj->numFaces++;
	                while(fscanf(file, "%d/%d", &v, &t) > 0) { obj->numFaces++; }
	              } else
	              { //        v
	                fscanf(file, "%d", &v);
	                fscanf(file, "%d", &v);
	                obj->numFaces++;
	                while(fscanf(file, "%d", &v) > 0)  { obj->numFaces++; }
	              }
      break; //end of face case

    default: fgets(buf, sizeof(buf), file); break; // eat up rest of line


    }
  }





  // set the stats in the model structure
  obj->numVertices  = numvertices;
  obj->numNormals   = numnormals;
  obj->numTexs = numtexs;
  obj->numColors = numcolors;

  printf("Vertices : %ld\n",obj->numVertices);
  printf("Normals  : %ld\n",obj->numNormals);
  printf("Faces    : %ld\n",obj->numFaces);
  printf("Groups   : %ld\n",obj->numGroups);
  printf("Texes   : %ld\n",obj->numTexs);
  printf("Colors   : %ld\n",obj->numColors);

  if (wrongDecimalSeperatorBug)
  {
      fprintf(stderr,RED "! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !\n");
      fprintf(stderr,RED "\n\n\n\nThis OBJ file has a wrong seperator for floating point numbers \n");
      fprintf(stderr,"         please use    sed -i 's/,/./g' %s         \n\n\n" NORMAL,obj->filename);
      fprintf(stderr,RED "! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !\n");
  }

  for(i=0; i<obj->numGroups; i++)
  {
	  obj->groups[i].numFaces=0;
	  printf("%d\n", obj->groups[i].hasNormals);//0, 0
  }

  // Allocating memory
  fprintf(stderr,"Allocating memory for faces\n");
  obj->faceList = (Face*) malloc(sizeof(Face)*(obj->numFaces+2));
  if (obj->faceList == 0) { fprintf(stderr,"Could not allocate enough memory for face struct\n"); }
  memset (obj->faceList,0,sizeof(Face)*(obj->numFaces+2));

  fprintf(stderr,"Allocating memory for vertices\n");
  obj->vertexList = (Vertex*) malloc(sizeof(Vertex)*(obj->numVertices+2));
  if (obj->vertexList == 0) { fprintf(stderr,"Could not allocate enough memory for vertex struct\n"); }
  memset (obj->vertexList,0,sizeof(Vertex)*(obj->numVertices+2));

  if(obj->numNormals!=0)
  {
    fprintf(stderr,"Allocating memory for normals\n");
    obj->normalList=(Normal*)malloc(sizeof(Normal)*(obj->numNormals+2));
    if (obj->normalList == 0) { fprintf(stderr,"Could not allocate enough memory for normal struct\n"); }
    memset (obj->normalList,0,sizeof(Normal)*(obj->numNormals+2));
  }

  if(obj->numTexs!=0)
  {
    fprintf(stderr,"Allocating memory for textures\n");
    obj->texList=(TexCoords*)malloc(sizeof(TexCoords)*(obj->numTexs+2));
    if (obj->texList == 0) { fprintf(stderr,"Could not allocate enough memory for texture struct\n"); }
    memset (obj->texList,0,sizeof(TexCoords)*(obj->numTexs+2));
  }


  if(obj->numColors!=0)
  {
    fprintf(stderr,"Allocating memory for colors\n");
    obj->colorList=(RGBColors*)malloc(sizeof(RGBColors)*(obj->numColors+2));
    if (obj->colorList == 0) { fprintf(stderr,"Could not allocate enough memory for colors struct\n"); }
    memset (obj->colorList,0,sizeof(RGBColors)*(obj->numColors+2));
  }

  // Second Pass
  rewind(file);

  //These dont work if they become 0 :P
  obj->numVertices = 1;
  obj->numNormals = 1;
  obj->numTexs = 1;
  obj->numColors = 1;
  obj->customColor =( obj->numColors > 0 );
  obj->numFaces = 0;
  material = 0;
  grp = 0;

  while(!feof(file))
  {
    fscanf(file, "%s", buf);

	if(!strcmp(buf, "usemtl"))
	{
		  fscanf(file, "%s", buf1);
		  unsigned int foundMaterial;
		  if ( FindMaterial( obj, buf1 , &foundMaterial) )
          {
		    mat = foundMaterial;
		    obj->groups[grp].material = mat;
		    strcpy(obj->matLib, buf1);
		    printf("loadmtl %s\n", obj->matLib);
          }
    }
	switch(buf[0])
	{
      case '#':	fgets(buf, sizeof(buf), file);	break;		// comment  eat up rest of line

      case 'v':	 // v, vn, vt
                  switch(buf[1])
                  {
                       case '\0': //  vertex
                                  if ( obj->customColor )
                                    {
	                                 fscanf(file, "%f %f %f %f %f %f",
	                                 &obj->vertexList[obj->numVertices].x,
	                                 &obj->vertexList[obj->numVertices].y,
	                                 &obj->vertexList[obj->numVertices].z,
	                                 &obj->colorList[obj->numColors].r,
	                                 &obj->colorList[obj->numColors].g,
	                                 &obj->colorList[obj->numColors].b
	                                 );

	                                  obj->numVertices++;
	                                  obj->numColors++;

                                    } else
                                    {
	                                 fscanf(file, "%f %f %f",
	                                 &obj->vertexList[obj->numVertices].x,
	                                 &obj->vertexList[obj->numVertices].y,
	                                 &obj->vertexList[obj->numVertices].z);
	                                 obj->numVertices++;
                                    }


	                   break;
                       case 'n': // normal
	                             fscanf(file, "%f %f %f",
	                             &obj->normalList[obj->numNormals].n1,
	                             &obj->normalList[obj->numNormals].n2,
	                             &obj->normalList[obj->numNormals].n3);
	                             obj->numNormals++;
	                   break;

	                   case 't': // normal
	                             fscanf(file, "%f %f",
	                             &obj->texList[obj->numTexs].u,
	                             &obj->texList[obj->numTexs].v);
	                             obj->numTexs++;
	                   break;
                  }
      break;

      case 'u': fgets(buf, sizeof(buf), file);  break; // eat up rest of line

      case 'g': // group eat up rest of line
                fgets(buf, sizeof(buf), file);
	            sscanf(buf, "%s", buf);
	            grp = FindGroup(obj,buf);
                obj->groups[grp].material = material;
	  break;

      case 'f': //face
                v = 0;  n = 0; t = 0;
                fscanf(file, "%s", buf);
                // can be one of %d, %d//%d, %d/%d, %d/%d/%d
                if (strstr(buf, "//"))
                { //  v//n
	              sscanf(buf, "%d//%d", &v, &n);
	              obj->faceList[obj->numFaces].v[0] = v;
	              obj->faceList[obj->numFaces].n[0] = n;
	              fscanf(file, "%d//%d", &v, &n);
	              obj->faceList[obj->numFaces].v[1] = v;
	              obj->faceList[obj->numFaces].n[1] = n;
	              fscanf(file, "%d//%d", &v, &n);
	              obj->faceList[obj->numFaces].v[2] = v;
	              obj->faceList[obj->numFaces].n[2] = n;
	              AddFacetoG(&obj->groups[grp],obj->numFaces);
	              obj->numFaces++;
	              obj->groups[grp].hasNormals = 1;
	              obj->groups[grp].hasTex = 0;
	              while(fscanf(file, "%d//%d", &v, &n) > 0)
	               {
	                 obj->faceList[obj->numFaces].v[0] = obj->faceList[obj->numFaces-1].v[0];
	                 obj->faceList[obj->numFaces].n[0] = obj->faceList[obj->numFaces-1].n[0];
	                 obj->faceList[obj->numFaces].v[1] = obj->faceList[obj->numFaces-1].v[2];
	                 obj->faceList[obj->numFaces].n[1] = obj->faceList[obj->numFaces-1].n[2];
	                 obj->faceList[obj->numFaces].v[2] = v;
	                 obj->faceList[obj->numFaces].n[2] = n;
	                 AddFacetoG(&obj->groups[grp],obj->numFaces);
	                 obj->numFaces++;
	               }
	             } else
	             if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3)
	             { // v/t/n
	                obj->faceList[obj->numFaces].v[0] = v;
	                obj->faceList[obj->numFaces].n[0] = n;
	                obj->faceList[obj->numFaces].t[0] = t;
	                fscanf(file, "%d/%d/%d", &v, &t, &n);
	                obj->faceList[obj->numFaces].v[1] = v;
	                obj->faceList[obj->numFaces].n[1] = n;
	                obj->faceList[obj->numFaces].t[1] = t;
	                fscanf(file, "%d/%d/%d", &v, &t, &n);
	                obj->faceList[obj->numFaces].v[2] = v;
	                obj->faceList[obj->numFaces].n[2] = n;
	                obj->faceList[obj->numFaces].t[2] = t;
	                AddFacetoG(&obj->groups[grp],obj->numFaces);
	                obj->numFaces++;
	                obj->groups[grp].hasNormals = 1;
	                obj->groups[grp].hasTex = 1;

	                while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0)
	                  {
	                    obj->faceList[obj->numFaces].v[0] = obj->faceList[obj->numFaces-1].v[0];
	                    obj->faceList[obj->numFaces].n[0] = obj->faceList[obj->numFaces-1].n[0];
	                    obj->faceList[obj->numFaces].t[0] = obj->faceList[obj->numFaces-1].t[0];
	                    obj->faceList[obj->numFaces].v[1] = obj->faceList[obj->numFaces-1].v[2];
	                    obj->faceList[obj->numFaces].n[1] = obj->faceList[obj->numFaces-1].n[2];
	                    obj->faceList[obj->numFaces].t[1] = obj->faceList[obj->numFaces-1].t[2];
	                    obj->faceList[obj->numFaces].v[2] = v;
	                    obj->faceList[obj->numFaces].n[2] = n;
	                    obj->faceList[obj->numFaces].t[2] = t;
	                    AddFacetoG(&obj->groups[grp],obj->numFaces);
	                    obj->numFaces++;
	                  }
                } else
                if (sscanf(buf, "%d/%d", &v, &t) == 2)
                { // v/t
		          obj->groups[grp].hasTex = 1;
		          obj->faceList[obj->numFaces].v[0] = v;
		          obj->faceList[obj->numFaces].t[0] = t;
		          fscanf(file, "%d/%d", &v, &t);
		          obj->faceList[obj->numFaces].v[1] = v;
		          obj->faceList[obj->numFaces].t[1] = t;
		          fscanf(file, "%d/%d", &v, &t);
		          obj->faceList[obj->numFaces].v[2] = v;
		          obj->faceList[obj->numFaces].t[2] = t;
		          AddFacetoG(&obj->groups[grp],obj->numFaces);
		          obj->numFaces++;
		          while(fscanf(file, "%d/%d", &v, &t) > 0)
		          {
	  	           obj->faceList[obj->numFaces].v[0] = obj->faceList[obj->numFaces-1].v[0];
	  	           obj->faceList[obj->numFaces].t[0] = obj->faceList[obj->numFaces-1].t[0];
	  	           obj->faceList[obj->numFaces].v[1] = obj->faceList[obj->numFaces-1].v[2];
	  	           obj->faceList[obj->numFaces].t[1] = obj->faceList[obj->numFaces-1].t[2];
	  	           obj->faceList[obj->numFaces].v[2] = v;
	  	           obj->faceList[obj->numFaces].t[2] = t;
	  	           AddFacetoG(&obj->groups[grp],obj->numFaces);
	  	           obj->numFaces++;
		          }//while
               } else
               { // v
	             sscanf(buf, "%d", &v);
	             obj->faceList[obj->numFaces].v[0] = v;
	             fscanf(file, "%d", &v);
	             obj->faceList[obj->numFaces].v[1] = v;
	             fscanf(file, "%d", &v);
	             obj->faceList[obj->numFaces].v[2] = v;
	             obj->groups[grp].hasNormals = 0;
	             obj->groups[grp].hasTex = 0;
	             AddFacetoG(&obj->groups[grp],obj->numFaces);
	             obj->numFaces++;
	             while(fscanf(file, "%d", &v) == 1)
	              {
	               obj->faceList[obj->numFaces].v[0] = obj->faceList[obj->numFaces-1].v[0];
	               obj->faceList[obj->numFaces].v[1] = obj->faceList[obj->numFaces-1].v[2];
	               obj->faceList[obj->numFaces].v[2] = v;
	               AddFacetoG(&obj->groups[grp],obj->numFaces);
	               obj->numFaces++;
	              }
                }
      break;

     default: fgets(buf, sizeof(buf), file); break; // eat up rest of line
    }
  }
  fclose(file);
  printf("Model has %ld faces %u colors \n",obj->numFaces, obj->numColors);
  for(i=0; i<obj->numGroups; i++)
  {
	 // fprintf(stderr,"Group %s has %ld faces and material %s, \t \n",obj->groups[i].name,obj->groups[i].numFaces,obj->matList[obj->groups[i].material].name);
  }


#if CALCULATE_3D_BOUNDING_BOX
  calculateOBJBBox(obj);
#endif // CALCULATE_3D_BOUNDING_BOX

 return 1;
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
    /* Read out config file */
    initalizeConfigFileValues();

    /* Global var with program name */
    strcpy(programName,basename(argv[0]));

    /* Getopt variables */
    int getoptOption;
    int getoptVerbose = 0;
    int getoptPhoenix = 0;
    int getoptBaudrate = 9600;
    int getoptFramesize = 8;
    int getoptParity = 'E';
    int getoptReset = 0;
    int getoptResetAtr = 0;
    char *getoptApduCommands = 0; /* Contains the batch of APUD commands as a delimeter seperated list */

    char apduCommandString[3000];
    char apduCommand[1000];
    int apduCommandLen = 0;
    int apduCommandCount = 0; /* Number of APDU-Commands */
    char *apduSwStart = 0;
    char *apduStatusWordPointer = 0;
    char apduStatusWord[1000];

    int i;

    if(argc == 1)
        mainMenue();	/* No parameters given ==> Main menue */
    else
    {
        while ((getoptOption = getopt (argc, argv, "h?veb:f:p:aAc:")) != -1)
            switch (getoptOption)
            {
            case 'h':
                printHelp();
                break;
            case '?':
                printHelp();
                break;
            case 'v':
                getoptVerbose = 1;
                break;
            case 'e':
                getoptPhoenix = 1;
                break;
            case 'a':
                getoptReset = 1;
                break;
            case 'A':
                getoptResetAtr = 1;
                break;
            case 'b':
                getoptBaudrate = atoi(optarg);
                break;
            case 'f':
                getoptFramesize = atoi(optarg);
                break;
            case 'p':
                getoptParity = optarg[0];
                break;
            case 'c':
                getoptApduCommands = optarg;
                break;
            }

        if(getoptVerbose)
        {
            printHeadline();
            printf("\r\n");
            printf(" * Running in commandline mode:\r\n");
            printf(" * Verbose mode is on\r\n");
            printf(" * Serial port settings are:\r\n");
            printf("   Communication port is: %s\r\n",configfilePortValue);
            printf("   Baudrate (for chipcardLab hardware) is: %s baud\r\n",configfileBaudrateValue);
            printf("   Baudrate (for smartcard) is: %i baud\r\n",getoptBaudrate);
            printf("   Framesize (for smartcard) is: %i bits\r\n",getoptFramesize);
            printf("   Parity setting (for smartcard) is: %c bits\r\n",getoptParity);
        }

        /* Phoenix reader mode */
        if(getoptPhoenix)
        {
            setTerminalMode(PHOENIX); /* Tell the subsystem that we deal with a phoenix-reader */

            if(getoptVerbose)
                printf(" * Info: Phoenix-Mode selected.\r\n");

            phoenixSetup(getoptBaudrate, getoptFramesize, getoptParity, getoptVerbose);

            /* Reset the smartcard */
            if(getoptReset)
                phoenixReset(getoptVerbose);
            else if(getoptResetAtr)
            {
                phoenixReset(getoptVerbose);
                phoenixDisplayAtr(getoptVerbose);
                printf("\r\n");
            }

            /* Clear buffer */
            ttyClearBuffer(configfilePortValue);

            /* Some commands have to be executed */
            if(getoptApduCommands)
            {

                trimStringChar(getoptApduCommands, ' ');
                trimStringChar(getoptApduCommands, APDU_LIST_DELIMETER);
                trimStringChar(getoptApduCommands, ' ');
                apduCommandCount = countChar(getoptApduCommands, APDU_LIST_DELIMETER, strlen(getoptApduCommands)) + 1;
                if(getoptVerbose)
                    printf(" * Number of APDU-Commands to process is: %i\r\n",apduCommandCount);

                for(i = 0; i < apduCommandCount; i++)
                {
                    /* Extract item from delimeter seperated list */
                    listExtract(getoptApduCommands, strlen(getoptApduCommands),APDU_LIST_DELIMETER, apduCommandString, sizeof(apduCommandString),i);


                    /* Check for status word definition */
                    apduSwStart = strchr(apduCommandString, APDU_SW_DELIMETER);
                    if(apduSwStart)
                    {
                        strcpy(apduStatusWord,apduSwStart+1);
                        *apduSwStart = '\0';
                        hexString2numeric(apduSwStart + 1,apduStatusWord,2);
                        apduStatusWordPointer = apduStatusWord;
                    }
                    else
                        apduStatusWordPointer = 0;

                    if(getoptVerbose)
                        printf(" * Executing command #%i APDU=%s\r\n", i+1, apduCommandString);

                    apduCommandLen = hexString2numeric(apduCommandString,apduCommand,sizeof(apduCommand));
                    if(executeApduCommand(apduCommand, apduCommandLen, apduStatusWordPointer, getoptVerbose) != 0)
                    {
                        printf("\r\n");
                        exit(1);
                    }

                    if((!getoptVerbose)&&(i<apduCommandCount-1))
                        printf("/");

                    fflush(stdout);
                }

                if(!getoptVerbose)
                    printf("\r\n");
            }

            exit(0);
        }

        /* No suitable mode selected */
        else
        {
            printf(" * Error: No suitable mode selected - exiting...\r\n");
            exit(1);
        }
    }

    return 0;
}