Search Results

Search found 77 results on 4 pages for 'fscanf'.

Page 1/4 | 1 2 3 4  | Next Page >

  • I need to know inside of "while(fscanf != EOF){blah}" if the next fscanf is going to return EOF-- be

    - by Rancur3p1c
    I've got some code executing in a while(fscanf != EOF) loop. However, even when fscanf has finished executing, I need to keep running that code until some conditions are met. I mean I guess I could copy/paste the code to outside the while(fscanf) loop, and only use global variables, but that seems messy. Surely someone has encountered something like this before and has a cleaner solution.

    Read the article

  • Using fscanf with dynamically allocated buffer.

    - by ryyst
    Hi, I got the following code: char buffer[2047]; int charsRead; do { if(fscanf(file, "%2047[^\n]%n%*c", buffer, &charsRead) == 1) { // Do something } } while (charsRead == 2047); I wanted to convert this code to use dynamically allocated variables so that when calling this code often I won't get heavy memory leakage. Thus, I tried this: char *buffer = malloc(sizeof(char) * 2047); int *charsRead = malloc(sizeof(int)); do { if(fscanf(file, "%2047[^\n]%n%*c", *buffer, charsRead) == 1) { // Do something } } while (*charsRead == 2047); Unfortunately, this does not work. I always get “EXC_BAD_ACCESS” errors, just before the if-statement with the fscanf call. What am I doing wrong? Thanks for any help! -- Ry

    Read the article

  • How can I create an fscanf format string to accept white space and comma (,) tokenization

    - by Jamie
    I've got some analysis code (myprog) that sucks in data using the following: if(5 == fscanf(in, "%s%lf%f%f%f", tag, & sec, & tgt, & s1, & s2)) which works just fine. But in the situation where I've got data files that are separated by commas, I'm currently doing something like: sed 's/,/ /g' data | myprog Can I modify the format string in the fscanf() function to accept both delimitation formats?

    Read the article

  • What is the modern eqivalent (C++) style for the older (C-like) fscanf method?

    - by Chris_45
    What is the best option if I want to "upgrade" old C-code to newer C++ when reading a file with a semicolon delimiter: /* reading in from file C-like: */ fscanf(tFile, "%d", &mypost.nr); /*delimiter ; */ fscanf(tFile, " ;%[^;];", mypost.aftername);/* delimiter ; */ fscanf(tFile, " %[^;]", mypost.forename); /*delimiter ; */ fscanf(tFile, " ;%[^;];", mypost.dept);/*delimiter ; */ fscanf(tFile, " %[^;];", mypost.position);/* delimiter ; */ fscanf(tFile, "%d", &mypost.nr2); //eqivalent best C++ method achieving the same thing?

    Read the article

  • What is the modern equivalent (C++) style for the older (C-like) fscanf method?

    - by Chris_45
    What is the best option if I want to "upgrade" old C-code to newer C++ when reading a file with a semicolon delimiter: /* reading in from file C-like: */ fscanf(tFile, "%d", &mypost.nr); /*delimiter ; */ fscanf(tFile, " ;%[^;];", mypost.aftername);/* delimiter ; */ fscanf(tFile, " %[^;]", mypost.forename); /*delimiter ; */ fscanf(tFile, " ;%[^;];", mypost.dept);/*delimiter ; */ fscanf(tFile, " %[^;];", mypost.position);/* delimiter ; */ fscanf(tFile, "%d", &mypost.nr2); //eqivalent best C++ method achieving the same thing?

    Read the article

  • C language - Fscanf and sprint commands in unix environment

    - by yanag
    I am trying to read file with 30 rows and 5 columns with separator of "tab". Each time I get only part of the rows. In the windows environment it's working good. Any idea why in unix it is not working? while (fscanf(FFMapFile,"%s\t%s\t%s\t%s\t%s\t",fnfMap[i].COS_ID,fnfMap[i].FF_First_Act,fnfMap[i].FF_Next_Act,fnfMap[i].Free_FF_allowed,fnfMap[i].FF_Change_Charge)!=EOF) { sprintf(s,"%s\t%s\t%s\t%s\t%s\t",fnfMap[i].COS_ID,fnfMap[i].FF_First_Act,fnfMap[i].FF_Next_Act,fnfMap[i].Free_FF_allowed,fnfMap[i].FF_Change_Charge); error_log(s,ERROR); i++; }

    Read the article

  • Is there a way to know when fscanf reads a whitespace or a new line?

    - by user1493813
    I want to know if there is a way to know when fscanf reads a whitespace or a new line. Example: formatting asking words italic links returns As fscanf read a string till it meets a newline or a whitespace(using %s), it'll read formatting and the space after it and before a. The thing is, is there a way to know that it read a space? And after it entered the second line is there is a way to know that it read a carriage return?

    Read the article

  • C - how to get fscanf() to determine whether what it read is only digits, and no characters

    - by hatorade
    Imagine I have a csv with and each value is an integer. so the first value is the INTEGER 100. I want fscanf() to read this line, and either tell me it's an integer ONLY, or not. So, it would pass 100 but fail on 100t. What i've been trying to get work is "%d," where the comma is the delimiter of my CSV. so the whole function is fscanf(fp, "%d,", &count) Unfortunately, this fails to fail on '100t,' works on '100' and works on 't'. so it just isn't distinguishing between 100 and 100t (all of these numbers are followed by commas, of course

    Read the article

  • ansi-c fscanf problem

    - by mongoose
    hi i read the file as follows fscanf(fp,"%f %f %f",&*(p1+i), &*(p2+i), &*(p3+i)); my file's lines consists of three floating point numbers... the problem i have is that in the file let's say i have some floating points with let's say maximum of two digits after the dot. but when i ask c to print those values using different formatting, for example %lf,%.2lf,%.4lf... it starts to play with the digits... my only concern is this, if i have let's say 1343.23 in the file, then will c use this value exactly as it is in computations or it will play with the digits after the dot. if it will play, then how is it possible to make it so that it uses floating point numbers exactly as they are? for example in last case even if i ask it to print that value using %.10lf i would expect it to print only 1343.2300000000.? thanks a lot!

    Read the article

  • Making fscanf Ignore Optional Parameter

    - by adi92
    I am using fscanf to read a file which has lines like Number <-whitespace- string <-whitespace- optional_3rd_column I wish to extract the number and string out of each column, but ignore the 3rd_column if it exists Example Data: 12 foo something 03 bar 24 something #randomcomment I would want to extract 12,foo; 03,bar; 24, something while ignoring "something" and "#randomcomment" I currently have something like while(scanf("%d %s %*s",&num,&word)>=2) { assign stuff } However this does not work with lines with no 3rd column. How can I make it ignore everything after the 2nd string?

    Read the article

  • Infinite loop when using fscanf

    - by user1409641
    I wrote this simple program in C, because I'm studying FILES right now at University. I take a txt file with a list of the results of the last race so my program will show the data formatted as I want. Here's my code: /* Esercizio file Motogp */ #include <stdio.h> #define SIZE 20 int main () { int pos, punt, num; float kmh; char nome[SIZE+1], cognome[SIZE+1], moto[SIZE+1]; char naz[SIZE+1], nome_file[SIZE+1]; FILE *fp; printf ("Inserisci il nome del file da aprire: "); gets (nome_file); fp = fopen (nome_file, "r"); if (fopen == NULL) printf ("Errore nell' apertura del file %s\n", nome_file); else { while (fscanf (fp, "%d %d %d %s %s %s %s %.2f", &pos, &punt, &num, nome, cognome, naz, moto, &kmh) != EOF ) { printf ("Posizione di arrivo: %d\n", pos); printf ("Punteggio: %d\n", punt); printf ("Numero pilota: %d\n", num); printf ("Nome pilota: %s\n", nome); printf ("Cognome pilota: %s\n", cognome); printf ("Nazione: %s\n", naz); printf ("Moto: %s\n", moto); printf ("Media Kmh: %d\n\n", kmh); } } fclose(fp); return 0; } and there's my txt file: 1 25 99 Jorge LORENZO SPA Yamaha 164.4 2 20 26 Dani PEDROSA SPA Honda 164.1 3 16 4 Andrea DOVIZIOSO ITA Yamaha 163.8 4 13 1 Casey STONER AUS Honda 163.8 5 11 35 Cal CRUTCHLOW GBR Yamaha 163.6 6 10 19 Alvaro BAUTISTA SPA Honda 163.5 7 9 46 Valentino ROSSI ITA Ducati 163.3 8 8 6 Stefan BRADL GER Honda 162.9 9 7 69 Nicky HAYDEN USA Ducati 162.5 10 6 11 Ben SPIES USA Yamaha 162.3 11 5 8 Hector BARBERA SPA Ducati 162.1 12 4 17 Karel ABRAHAM CZE Ducati 160.9 13 3 41 Aleix ESPARGARO SPA ART 160.2 14 2 51 Michele PIRRO ITA FTR 160.1 15 1 14 Randy DE PUNIET FRA ART 160.0 16 0 77 James ELLISON GBR ART 159.9 17 0 54 Mattia PASINI ITA ART 159.4 18 0 68 Yonny HERNANDEZ COL BQR 159.4 19 0 9 Danilo PETRUCCI ITA Ioda 158.2 20 0 22 Ivan SILVA SPA BQR 158.2 When I run my program, it return me an infinite loop of the first one. Why? Is there another function to read those data?

    Read the article

  • C : files manipulation Can't figure out how to simplify this code with files manipulation.

    - by Bon_chan
    Hey guys, I have been working on this code but I can't find out what is wrong. This program does compile and run but it ends up having a fatal error. I have a file called myFile.txt, with the following content : James------ 07.50 Anthony--- 17.00 And here is the code : int main() { int n =2, valueTest=0,count=0; FILE* file = NULL; float temp= 00.00f, average= 00.00f, flTen = 10.00f; float *totalNote = (float*)malloc(n*sizeof(float)); int position = 0; char selectionNote[5+1], nameBuffer[10+1], noteBuffer[5+1]; file = fopen("c:\\myFile.txt","r"); fseek(file,10,SEEK_SET); while(valueTest<2) { fscanf(file,"%5s",&selectionNote); temp = atof(selectionNote); totalNote[position]= temp; position++; valeurTest++; } for(int counter=0;counter<2;counter++) { average += totalNote[counter]; } printf("The total is : %f \n",average); rewind(file); printf("here is the one with less than 10.00 :\n"); while(count<2) { fscanf(file,"%10s",&nameBuffer); fseek(file,10,SEEK_SET); fscanf(file,"%5s",&noteBuffer); temp = atof(noteBuffer); if(temp<flTen) { printf("%s who has %f\n",nameBuffer,temp); } fseek(file,1,SEEK_SET); count++; } fclose(file); } I am pretty new to c and find it more difficult than c# or java. And I woud like to get some suggestions to help me to get better. I think this code could be simplier. Do you think the same ?

    Read the article

  • scanf formatting issue

    - by da_rockwilder
    I have a log file with the following format: INFO 2011-03-09 10:26:15,270 [user] message I want to parse the log file using PHP: // assume file exists and all that $handle = fopen("log_file.txt", "r"); while ($line_data = fscanf($handle, "%s %s %s [%s] %s\n")) { var_dump($line_data); } fclose($handle); When I run this code I get: [0]=> array(5) { [0]=> string(4) "INFO" [1]=> string(10) "2011-03-09" [2]=> string(12) "10:26:15,270" [3]=> string(5) "user]" [4]=> NULL } // snip It appears the closing bracket in the format string ("%s %s %s [%s] %s") is disrupting the rest of the line from getting parsed. I checked the PHP docs for scanf (as suggested by fscanf), and I didn't see anything mentioning having to escape a left bracket. Any suggestions on how to get the 4th and 5th elements to look like "user" and "message" respectively?

    Read the article

  • Convert function to read from string instead of file in C

    - by Dusty
    I've been tasked with updating a function which currently reads in a configuration file from disk and populates a structure: static int LoadFromFile(FILE *Stream, ConfigStructure *cs) { int tempInt; ... if ( fscanf( Stream, "Version: %d\n",&tempInt) != 1 ) { printf("Unable to read version number\n"); return 0; } cs->Version = tempInt; ... } to one which allows us to bypass writing the configuration to disk and instead pass it directly in memory, roughly equivalent to this: static int LoadFromString(char *Stream, ConfigStructure *cs) A few things to note: The current LoadFromFile function is incredibly dense and complex, reading dozens of versions of the config file in a backward compatible manner, which makes duplication of the overall logic quite a pain. The functions that generate the config file and those that read it originate in totally different parts of the old system and therefore don't share any data structures so I can't pass those directly. I could potentially write a wrapper, but again, it would need to handle any structure passed in in a backwards compatible manner. I'm tempted to just pass the file as is in as a string (as in the prototype above) and convert all the fscanf's to sscanf's but then I have to handle incrementing the pointer along (and potentially dealing with buffer overrun errors) manually. This has to remain in C, so no C++ functionality like streams can help here Am I missing a better option? Is there some way to create a FILE * that actually just points to a location in memory instead of on disk? Any pointers, suggestions or other help is greatly appreciated.

    Read the article

  • c read float from file and sort

    - by Franky
    Hi all I have a problem with a C application; i have on a .txt file some float numbers and I have to read them and sort in descending way. When i do the fscanf command and then the printf, i get on the screen strange numbers (memory location I suppose). How can i solve the problem? Thanks in advance

    Read the article

  • Reading ASCII numbers using "D" instead of "E" for scientific notation using C

    - by Arrieta
    Hello, I have a list of numbers which looks like this: 1.234D+1 or 1.234D-02. I want to read the file using C. The function atof will merely ignore the D and translate only the mantissa. The function fscanf will not accept the format '%10.6e' because it expects an E instead of a D in the exponent. When I ran into this problem in Python, I have up and merely used a string substitution before converting from string to float. But in C, I am sure there must be another way. So, how would you read a file with numbers using D instead of E for scientific notation? Notice that I do not mean how to read the strings themselves, but rather how to convert them to floats. Thanks.

    Read the article

  • How to move file pointer to a particular location using fseek()?

    - by Noge
    My intention is to read every elements in the 2nd column into a buffer[] from the following .txt file: 9992891234 09.920 15.771 11.909 9992345971 07.892 12.234 09.234 9992348971 64.567 70.456 50.987 9992348231 89.234 85.890 58.982 I have know of a way to do it by using fscanf(): for (int i=0;i<4;i++) { fscanf(pFile, "%lld", &junk); fscanf(pFile, "%f", &buffer[i]); fscanf(pFile, "%f", &junk); fscanf(pFile, "%f", &junk); } However, since I'm doing parallel programing which requires me to use different Windows Threads to read different columns, so I'll need to read the elements in the 2nd column directly using fseek(). The question here is, what should I put in the 2nd argument in fseek() in the code below to move my file pointer to read the 2nd element of the 2nd line? fscanf(pFile, "%llf", &junk);//<------this is used to skip the 1st data for (int i=0;i<4;i++) { fscanf(pFile, "%f", &buffer[i]); fseek ( pFile , ??, SEEK_CUR );//<----how do I calculate this offset? }

    Read the article

  • Reading different data from a textfile delimited with semicolons in C.

    - by Chris_45
    How do one read different records of data that are separated with semicolons into an array in C? from textfile: Text One; 12.25; Text Two; 5; Text Three; 1.253 fopen ... for(i = 0; i < nrRecords; i++) { fscanf(myFile, " %[^;];", myRecords[i].firstText); /* Ok first text*/ fscanf(myFile, "%lf", &myRecords[i].myDouble1); /* But goes wrong with first double */ fscanf(myFile, " %[^;];", myRecords[i].secondText); fscanf(myFile, "%d", &myRecords[i].myInt1); fscanf(myFile, " %[^;];", myRecords[i].thirdText); fscanf(myFile, "%lf",&myRecords[i].myDouble2); } fclose...

    Read the article

  • Unwanted character being added to string in C

    - by Church
    I have a program that gives you shipping addresses from an input file. However at the beginning of one of the strings, order.add_one, a number is being added to the beginning of the string, that number is equivalent to the variable "choice" every time. Why is it doing this? #include <stdio.h> #include <math.h> #include <string.h> //structure typedef struct {char cust_name[25]; char cust_id[3]; char add_one[30]; char add_two[30]; char bike; char risky; int number_ordered; char cust_information[500]; }ORDER; ORDER order; int main(void){ fflush(stdin); system ( "clear" ); //initialize variables float price; float m = 359.95; float s = 279.95; //while loop, runs until user declares they no longer wish to input orders while (1==1){ printf("Options: \nEnter Customer information manually : 1 \nSearch Customer by ID(input.txt reader) : 2 \n"); int option = 0; scanf(" %d", &option); if (option == 1){ //Print and scan statements printf("Enter Customer Information\n"); printf("Customer Name: "); scanf(" %[^\n]s", &order.cust_name); printf("\nEnter Address Line One: "); scanf(" %[^\n]s", &order.add_one); printf("\nEnter Addres Line Two: "); scanf(" %[^\n]s", &order.add_two); printf("\nHow Many Bicycles Are Ordered: "); scanf(" %d", &order.number_ordered); printf("\nWhat Type Of Bike Is Ordered\n M Mountain Bike \n S Street Bike"); printf("\nChoose One (M or S): "); scanf(" %c", &order.bike); printf("\nIs The Customer Risky (Y/N): "); scanf(" %c", &order.risky); system ( "clear" ); } if (option == 2){ FILE *fpt; fpt = fopen("input.txt", "r"); if (fpt==NULL){ printf("Text file did not open\n"); return 1; } printf("Enter Customer ID: "); scanf("%s", &order.cust_id); char choice; choice = order.cust_id[0]; char x[3]; int w, u, y, z; char a[10], b[10], c[10], d[10], e[20], f[10], g[10], i[1], j[1]; int h; printf("%s value of c", c); if (choice >='1'){ while ((w = fgetc(fpt)) != '\n' ){ } } if (choice >='2'){ while ((u = fgetc(fpt)) != '\n' ){ } } if (choice >='3'){ while ((y = fgetc(fpt)) != '\n' ){ } } if (choice >= '4'){ while ((z = fgetc(fpt)) != '\n' ){ } } printf("\n"); fscanf(fpt, "%s", x); fscanf(fpt, "%s", a); printf("%s", a); strcat(order.cust_name, a); fscanf(fpt, " %s", b); printf(" %s", b); strcat(order.cust_name, " "); strcat(order.cust_name, b); fscanf(fpt, "%s", c); printf(" %s", c); strcat(order.add_one, "\0"); strcat(order.add_one, c); fscanf(fpt, "%s", d); printf(" %s", d); strcat(order.add_one, " "); strcat(order.add_one, d); fscanf(fpt, "%s", e); printf(" %s", e); strcat(order.add_two, e); fscanf(fpt, "%s", f); printf(" %s", f); strcat(order.add_two, " "); strcat(order.add_two, f); fscanf(fpt, "%s", g); printf(" %s", g); strcat(order.add_two, " "); strcat(order.add_two, g); strcat(order.add_two, "\0"); fscanf(fpt, "%d", &h); printf(" %d", h); order.number_ordered = h; fscanf(fpt, "%s", i); printf(" %s", i); order.bike = i[0]; fscanf(fpt, "%s", j); printf(" %s", j); order.risky = j[0]; fclose(fpt); printf("%s %s %s %d %c %c", order.cust_name, order.add_one, order.add_two, order.number_ordered, order.bike, order.risky); }

    Read the article

  • Time complexity of a sorting algorithm

    - by Passonate Learner
    The two programs below get n integers from file and calculates the sum of ath to bth integers q(number of question) times. I think the upper program has worse time complexity than the lower, but I'm having problems calculating the time complexity of these two algorithms. [input sample] 5 3 5 4 3 2 1 2 3 3 4 2 4 [output sample] 7 5 9 Program 1: #include <stdio.h> FILE *in=fopen("input.txt","r"); FILE *out=fopen("output.txt","w"); int n,q,a,b,sum; int data[1000]; int main() int i,j; fscanf(in,"%d%d",&n,&q); for(i=1;i<=n;i++) fscanf(in,"%d",&data[i]); for i=0;i<q;i++) { fscanf(in,"%d%d",&a,&b); sum=0; for(j=a;j<=b;j++) sum+=data[j]; fprintf(out,"%d\n",sum); } return 0; } Program 2: #include <stdio.h> FILE *in=fopen("input.txt","r"); FILE *out=fopen("output.txt","w"); int n,q,a,b; int data[1000]; int sum[1000]; int main() { int i,j; fscanf(in,"%d%d",&n,&q); for(i=1;i<=n;i++) fscanf(in,"%d",&data[i]); for(i=1;i<=n;i++) sum[i]=sum[i-1]+data[i]; for(i=0;i<q;i++) { fscanf(in,"%d%d",&a,&b); fprintf(out,"%d\n",sum[b]-sum[a-1]); } return 0; } The programs below gets n integers from 1 to m and sorts them. Again, I cannot calculate the time complexity. [input sample] 5 5 2 1 3 4 5 [output sample] 1 2 3 4 5 Program: #include <stdio.h> FILE *in=fopen("input.txt","r") FILE *out=fopen("output.txt","w") int n,m; int data[1000]; int count[1000]; int main() { int i,j; fscanf(in,"%d%d",&n,&m); for(i=0;i<n;i++) { fscanf(in,"%d",&data[i]); count[data[i]]++ } for(i=1;i<=m;i++) { for(j=0;j<count[i];j++) fprintf(out,"%d ",i); } return 0; } It's ironic(or not) that I cannot calculate the time complexity of my own algorithms, but I have passions to learn, so please programming gurus, help me!

    Read the article

  • exporting bind and keyframe bone poses from blender to use in OpenGL

    - by SaldaVonSchwartz
    I'm having a hard time trying to understand how exactly Blender's concept of bone transforms maps to the usual math of skinning (which I'm implementing in an OpenGL-based engine of sorts). Or I'm missing out something in the math.. It's gonna be long, but here's as much background as I can think of. First, a few notes and assumptions: I'm using column-major order and multiply from right to left. So for instance, vertex v transformed by matrix A and then further transformed by matrix B would be: v' = BAv. This also means whenever I export a matrix from blender through python, I export it (in text format) in 4 lines, each representing a column. This is so I can then I can read them back into my engine like this: if (fscanf(fileHandle, "%f %f %f %f", &skeleton.joints[currentJointIndex].inverseBindTransform.m[0], &skeleton.joints[currentJointIndex].inverseBindTransform.m[1], &skeleton.joints[currentJointIndex].inverseBindTransform.m[2], &skeleton.joints[currentJointIndex].inverseBindTransform.m[3])) { if (fscanf(fileHandle, "%f %f %f %f", &skeleton.joints[currentJointIndex].inverseBindTransform.m[4], &skeleton.joints[currentJointIndex].inverseBindTransform.m[5], &skeleton.joints[currentJointIndex].inverseBindTransform.m[6], &skeleton.joints[currentJointIndex].inverseBindTransform.m[7])) { if (fscanf(fileHandle, "%f %f %f %f", &skeleton.joints[currentJointIndex].inverseBindTransform.m[8], &skeleton.joints[currentJointIndex].inverseBindTransform.m[9], &skeleton.joints[currentJointIndex].inverseBindTransform.m[10], &skeleton.joints[currentJointIndex].inverseBindTransform.m[11])) { if (fscanf(fileHandle, "%f %f %f %f", &skeleton.joints[currentJointIndex].inverseBindTransform.m[12], &skeleton.joints[currentJointIndex].inverseBindTransform.m[13], &skeleton.joints[currentJointIndex].inverseBindTransform.m[14], &skeleton.joints[currentJointIndex].inverseBindTransform.m[15])) { I'm simplifying the code I show because otherwise it would make things unnecessarily harder (in the context of my question) to explain / follow. Please refrain from making remarks related to optimizations. This is not final code. Having said that, if I understand correctly, the basic idea of skinning/animation is: I have a a mesh made up of vertices I have the mesh model-world transform W I have my joints, which are really just transforms from each joint's space to its parent's space. I'll call these transforms Bj meaning matrix which takes from joint j's bind pose to joint j-1's bind pose. For each of these, I actually import their inverse to the engine, Bj^-1. I have keyframes each containing a set of current poses Cj for each joint J. These are initially imported to my engine in TQS format but after (S)LERPING them I compose them into Cj matrices which are equivalent to the Bjs (not the Bj^-1 ones) only that for the current spacial configurations of each joint at that frame. Given the above, the "skeletal animation algorithm is" On each frame: check how much time has elpased and compute the resulting current time in the animation, from 0 meaning frame 0 to 1, meaning the end of the animation. (Oh and I'm looping forever so the time is mod(total duration)) for each joint: 1 -calculate its world inverse bind pose, that is Bj_w^-1 = Bj^-1 Bj-1^-1 ... B0^-1 2 -use the current animation time to LERP the componets of the TQS and come up with an interpolated current pose matrix Cj which should transform from the joints current configuration space to world space. Similar to what I did to get the world version of the inverse bind poses, I come up with the joint's world current pose, Cj_w = C0 C1 ... Cj 3 -now that I have world versions of Bj and Cj, I store this joint's world- skinning matrix K_wj = Cj_w Bj_w^-1. The above is roughly implemented like so: - (void)update:(NSTimeInterval)elapsedTime { static double time = 0; time = fmod((time + elapsedTime),1.); uint16_t LERPKeyframeNumber = 60 * time; uint16_t lkeyframeNumber = 0; uint16_t lkeyframeIndex = 0; uint16_t rkeyframeNumber = 0; uint16_t rkeyframeIndex = 0; for (int i = 0; i < aClip.keyframesCount; i++) { uint16_t keyframeNumber = aClip.keyframes[i].number; if (keyframeNumber <= LERPKeyframeNumber) { lkeyframeIndex = i; lkeyframeNumber = keyframeNumber; } else { rkeyframeIndex = i; rkeyframeNumber = keyframeNumber; break; } } double lTime = lkeyframeNumber / 60.; double rTime = rkeyframeNumber / 60.; double blendFactor = (time - lTime) / (rTime - lTime); GLKMatrix4 bindPosePalette[aSkeleton.jointsCount]; GLKMatrix4 currentPosePalette[aSkeleton.jointsCount]; for (int i = 0; i < aSkeleton.jointsCount; i++) { F3DETQSType& lPose = aClip.keyframes[lkeyframeIndex].skeletonPose.jointPoses[i]; F3DETQSType& rPose = aClip.keyframes[rkeyframeIndex].skeletonPose.jointPoses[i]; GLKVector3 LERPTranslation = GLKVector3Lerp(lPose.t, rPose.t, blendFactor); GLKQuaternion SLERPRotation = GLKQuaternionSlerp(lPose.q, rPose.q, blendFactor); GLKVector3 LERPScaling = GLKVector3Lerp(lPose.s, rPose.s, blendFactor); GLKMatrix4 currentTransform = GLKMatrix4MakeWithQuaternion(SLERPRotation); currentTransform = GLKMatrix4Multiply(currentTransform, GLKMatrix4MakeTranslation(LERPTranslation.x, LERPTranslation.y, LERPTranslation.z)); currentTransform = GLKMatrix4Multiply(currentTransform, GLKMatrix4MakeScale(LERPScaling.x, LERPScaling.y, LERPScaling.z)); if (aSkeleton.joints[i].parentIndex == -1) { bindPosePalette[i] = aSkeleton.joints[i].inverseBindTransform; currentPosePalette[i] = currentTransform; } else { bindPosePalette[i] = GLKMatrix4Multiply(aSkeleton.joints[i].inverseBindTransform, bindPosePalette[aSkeleton.joints[i].parentIndex]); currentPosePalette[i] = GLKMatrix4Multiply(currentPosePalette[aSkeleton.joints[i].parentIndex], currentTransform); } aSkeleton.skinningPalette[i] = GLKMatrix4Multiply(currentPosePalette[i], bindPosePalette[i]); } } At this point, I should have my skinning palette. So on each frame in my vertex shader, I do: uniform mat4 modelMatrix; uniform mat4 projectionMatrix; uniform mat3 normalMatrix; uniform mat4 skinningPalette[6]; attribute vec4 position; attribute vec3 normal; attribute vec2 tCoordinates; attribute vec4 jointsWeights; attribute vec4 jointsIndices; varying highp vec2 tCoordinatesVarying; varying highp float lIntensity; void main() { vec3 eyeNormal = normalize(normalMatrix * normal); vec3 lightPosition = vec3(0., 0., 2.); lIntensity = max(0.0, dot(eyeNormal, normalize(lightPosition))); tCoordinatesVarying = tCoordinates; vec4 skinnedVertexPosition = vec4(0.); for (int i = 0; i < 4; i++) { skinnedVertexPosition += jointsWeights[i] * skinningPalette[int(jointsIndices[i])] * position; } gl_Position = projectionMatrix * modelMatrix * skinnedVertexPosition; } The result: The mesh parts that are supposed to animate do animate and follow the expected motion, however, the rotations are messed up in terms of orientations. That is, the mesh is not translated somewhere else or scaled in any way, but the orientations of rotations seem to be off. So a few observations: In the above shader notice I actually did not multiply the vertices by the mesh modelMatrix (the one which would take them to model or world or global space, whichever you prefer, since there is no parent to the mesh itself other than "the world") until after skinning. This is contrary to what I implied in the theory: if my skinning matrix takes vertices from model to joint and back to model space, I'd think the vertices should already be premultiplied by the mesh transform. But if I do so, I just get a black screen. As far as exporting the joints from Blender, my python script exports for each armature bone in bind pose, it's matrix in this way: def DFSJointTraversal(file, skeleton, jointList): for joint in jointList: poseJoint = skeleton.pose.bones[joint.name] jointTransform = poseJoint.matrix.inverted() file.write('Joint ' + joint.name + ' Transform {\n') for col in jointTransform.col: file.write('{:9f} {:9f} {:9f} {:9f}\n'.format(col[0], col[1], col[2], col[3])) DFSJointTraversal(file, skeleton, joint.children) file.write('}\n') And for current / keyframe poses (assuming I'm in the right keyframe): def exportAnimations(filepath): # Only one skeleton per scene objList = [object for object in bpy.context.scene.objects if object.type == 'ARMATURE'] if len(objList) == 0: return elif len(objList) > 1: return #raise exception? dialog box? skeleton = objList[0] jointNames = [bone.name for bone in skeleton.data.bones] for action in bpy.data.actions: # One animation clip per action in Blender, named as the action animationClipFilePath = filepath[0 : filepath.rindex('/') + 1] + action.name + ".aClip" file = open(animationClipFilePath, 'w') file.write('target skeleton: ' + skeleton.name + '\n') file.write('joints count: {:d}'.format(len(jointNames)) + '\n') skeleton.animation_data.action = action keyframeNum = max([len(fcurve.keyframe_points) for fcurve in action.fcurves]) keyframes = [] for fcurve in action.fcurves: for keyframe in fcurve.keyframe_points: keyframes.append(keyframe.co[0]) keyframes = set(keyframes) keyframes = [kf for kf in keyframes] keyframes.sort() file.write('keyframes count: {:d}'.format(len(keyframes)) + '\n') for kfIndex in keyframes: bpy.context.scene.frame_set(kfIndex) file.write('keyframe: {:d}\n'.format(int(kfIndex))) for i in range(0, len(skeleton.data.bones)): file.write('joint: {:d}\n'.format(i)) joint = skeleton.pose.bones[i] jointCurrentPoseTransform = joint.matrix translationV = jointCurrentPoseTransform.to_translation() rotationQ = jointCurrentPoseTransform.to_3x3().to_quaternion() scaleV = jointCurrentPoseTransform.to_scale() file.write('T {:9f} {:9f} {:9f}\n'.format(translationV[0], translationV[1], translationV[2])) file.write('Q {:9f} {:9f} {:9f} {:9f}\n'.format(rotationQ[1], rotationQ[2], rotationQ[3], rotationQ[0])) file.write('S {:9f} {:9f} {:9f}\n'.format(scaleV[0], scaleV[1], scaleV[2])) file.write('\n') file.close() Which I believe follow the theory explained at the beginning of my question. But then I checked out Blender's directX .x exporter for reference.. and what threw me off was that in the .x script they are exporting bind poses like so (transcribed using the same variable names I used so you can compare): if joint.parent: jointTransform = poseJoint.parent.matrix.inverted() else: jointTransform = Matrix() jointTransform *= poseJoint.matrix and exporting current keyframe poses like this: if joint.parent: jointCurrentPoseTransform = joint.parent.matrix.inverted() else: jointCurrentPoseTransform = Matrix() jointCurrentPoseTransform *= joint.matrix why are they using the parent's transform instead of the joint in question's? isn't the join transform assumed to exist in the context of a parent transform since after all it transforms from this joint's space to its parent's? Why are they concatenating in the same order for both bind poses and keyframe poses? If these two are then supposed to be concatenated with each other to cancel out the change of basis? Anyway, any ideas are appreciated.

    Read the article

  • One row is skipped each time the program scans a matrix from file !

    - by ZaZu
    Hello there, I had this code working yesterday, but it seems like I edited it a bit and lost the working version. I cant get this to work anymore. I basically want to scan a matrix from a .txt file. But each time it scans the first row, the second one is skipped, and it reads the third instead :( Here is my code : for(i=0;i<=test->rowmat1;i++){ for(j=0;j<=test->colmat1;j++){ fscanf(fin,"%f\t",&test->mat[i][j]); } fscanf(fin,"%*[^\n]",&test->mat[i][j]); } For example, for a matrix of : 1.00 2.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 10.00 11.00 12.00 If I extract 3 rows and 3 cols, I get : 1.00 2.00 3.00 7.00 8.00 9.00 Then fails, it wants to skip over the second line but there is nothing after 10 11 12 Why did it stop working ? What do I have wrong ? Please help, Thanks in advance.

    Read the article

  • Last in First out UDP structure in MatLab.

    - by D Zondervan
    I am using MatLabs UDP function in their instrument control toolbox to send data packets from one computer to another. The first computer is constantly updating data values and sending them to the other computer, and I want that computer to be able to query the first one for the most recent values whenever it needs them. However, the default implementation of the UDP send and receive in MatLab is a FIFO structure- the first packet I send is the first the other computer receives when they execute the "fscanf" function. I want the last packet I sent to be the one the fscanf function returns. Is this possible or do I need to use a different protocol?

    Read the article

1 2 3 4  | Next Page >