Ejemplo n.º 1
0
int main( int argc, char **argv ) {
    num_particles = read_int( argc, argv, "-n", 1000 );
    char *savename = read_string( argc, argv, "-o", NULL );
    MPI_Init( &argc, &argv );
    MPI_Comm_size( MPI_COMM_WORLD, &num_procs );
    MPI_Comm_rank( MPI_COMM_WORLD, &rank );
    fsave = savename && rank == 0 ? fopen( savename, "w" ) : NULL;
    particles = (particle_t*) malloc( num_particles * sizeof(particle_t) );
    MPI_Type_contiguous( 7, MPI_DOUBLE, &PARTICLE );
    MPI_Type_commit( &PARTICLE );
    set_size( num_particles );

    init_vars();
    init_partitions();

    if( rank == 0 ) {
        init_particles( num_particles, particles );
    }
    MPI_Bcast(particles, num_particles, PARTICLE, 0, MPI_COMM_WORLD);
    partition_particles();
    init_grid();

    double simulation_time = read_timer();

    for( int step = 0; step < NSTEPS; step++ ) {
        if (rank == 0) {
            right_fringe();
            MPI_Isend(right_sending_buffer, num_sending_right, PARTICLE, rank+1, 0, MPI_COMM_WORLD, &send_right_req);
            MPI_Irecv(right_receiving_buffer, num_my_particles, PARTICLE, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_right_req);
            MPI_Wait(&send_right_req, &send_right_stat);
            MPI_Wait(&recv_right_req, &recv_right_stat);
            MPI_Get_count(&recv_right_stat, PARTICLE, &recvd_right_count);
            num_augmented_particles = num_my_particles + recvd_right_count;
            memcpy(my_particles + num_my_particles, right_receiving_buffer, recvd_right_count * sizeof(particle_t));
        } else if (rank == (num_procs-1)) {
            left_fringe();
            MPI_Isend(left_sending_buffer, num_sending_left, PARTICLE, rank-1, 0, MPI_COMM_WORLD, &send_left_req);
            MPI_Irecv(left_receiving_buffer, num_my_particles, PARTICLE, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_left_req);
            MPI_Wait(&send_left_req, &send_left_stat);
            MPI_Wait(&recv_left_req, &recv_left_stat);
            MPI_Get_count(&recv_left_stat, PARTICLE, &recvd_left_count);
            num_augmented_particles = num_my_particles + recvd_left_count;
            memcpy(my_particles + num_my_particles, left_receiving_buffer, recvd_left_count * sizeof(particle_t));
        } else {
            left_fringe();
            right_fringe();
            MPI_Isend(left_sending_buffer, num_sending_left, PARTICLE, rank-1, 0, MPI_COMM_WORLD, &send_left_req);
            MPI_Irecv(left_receiving_buffer, num_my_particles, PARTICLE, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_left_req);
            MPI_Isend(right_sending_buffer, num_sending_right, PARTICLE, rank+1, 0, MPI_COMM_WORLD, &send_right_req);
            MPI_Irecv(right_receiving_buffer, num_my_particles, PARTICLE, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_right_req);
            MPI_Wait(&send_left_req, &send_left_stat);
            MPI_Wait(&send_right_req, &send_right_stat);
            MPI_Wait(&recv_left_req, &recv_left_stat);
            MPI_Wait(&recv_right_req, &recv_right_stat);
            MPI_Get_count(&recv_left_stat, PARTICLE, &recvd_left_count);
            MPI_Get_count(&recv_right_stat, PARTICLE, &recvd_right_count);
            num_augmented_particles = num_my_particles + recvd_left_count + recvd_right_count;
            memcpy(my_particles + num_my_particles, left_receiving_buffer, recvd_left_count * sizeof(particle_t));
            memcpy(my_particles + num_my_particles + recvd_left_count, right_receiving_buffer, recvd_right_count * sizeof(particle_t));
        }

        populate_grid();
        time_step();

        num_sending_left = 0;
        num_sending_right = 0;
        int num_remaining_particles = 0;
        for ( int i = 0; i < num_my_particles; i++ ) {
            if (rank != 0 && my_particles[i].x <= partition_offsets[rank]) {
                left_sending_buffer[num_sending_left++] = my_particles[i];
            } else if (rank != (num_procs-1) && my_particles[i].x > partition_offsets[rank+1]) {
                right_sending_buffer[num_sending_right++] = my_particles[i];
            } else {
                remaining_particles[num_remaining_particles++] = my_particles[i];
            }
        }
        if (rank == 0) {
            MPI_Isend(right_sending_buffer, num_sending_right, PARTICLE, rank+1, 0, MPI_COMM_WORLD, &send_right_req);
            MPI_Irecv(right_receiving_buffer, num_my_particles, PARTICLE, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_right_req);
            MPI_Wait(&send_right_req, &send_right_stat);
            MPI_Wait(&recv_right_req, &recv_right_stat);
            MPI_Get_count(&recv_right_stat, PARTICLE, &recvd_right_count);
            num_augmented_particles = num_remaining_particles + recvd_right_count;
            memcpy(my_particles, remaining_particles, num_remaining_particles * sizeof(particle_t));
            memcpy(my_particles + num_remaining_particles, right_receiving_buffer, recvd_right_count * sizeof(particle_t));
            num_my_particles = num_augmented_particles;
        } else if (rank == (num_procs-1)) {
            MPI_Isend(left_sending_buffer, num_sending_left, PARTICLE, rank-1, 0, MPI_COMM_WORLD, &send_left_req);
            MPI_Irecv(left_receiving_buffer, num_my_particles, PARTICLE, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_left_req);
            MPI_Wait(&send_left_req, &send_left_stat);
            MPI_Wait(&recv_left_req, &recv_left_stat);
            MPI_Get_count(&recv_left_stat, PARTICLE, &recvd_left_count);
            num_augmented_particles = num_remaining_particles + recvd_left_count;
            memcpy(my_particles, remaining_particles, num_remaining_particles * sizeof(particle_t));
            memcpy(my_particles + num_remaining_particles, left_receiving_buffer, recvd_left_count * sizeof(particle_t));
            num_my_particles = num_augmented_particles;
        } else {
            MPI_Isend(right_sending_buffer, num_sending_right, PARTICLE, rank+1, 0, MPI_COMM_WORLD, &send_right_req);
            MPI_Irecv(right_receiving_buffer, num_my_particles, PARTICLE, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_right_req);
            MPI_Isend(left_sending_buffer, num_sending_left, PARTICLE, rank-1, 0, MPI_COMM_WORLD, &send_left_req);
            MPI_Irecv(left_receiving_buffer, num_my_particles, PARTICLE, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &recv_left_req);
            MPI_Wait(&send_right_req, &send_right_stat);
            MPI_Wait(&recv_right_req, &recv_right_stat);
            MPI_Wait(&send_left_req, &send_left_stat);
            MPI_Wait(&recv_left_req, &recv_left_stat);
            MPI_Get_count(&recv_left_stat, PARTICLE, &recvd_left_count);
            MPI_Get_count(&recv_right_stat, PARTICLE, &recvd_right_count);
            num_augmented_particles = num_remaining_particles + recvd_left_count + recvd_right_count;
            memcpy(my_particles, remaining_particles, num_remaining_particles * sizeof(particle_t));
            memcpy(my_particles + num_remaining_particles, left_receiving_buffer, recvd_left_count * sizeof(particle_t));
            memcpy(my_particles + num_remaining_particles + recvd_left_count, right_receiving_buffer, recvd_right_count * sizeof(particle_t));
            num_my_particles = num_augmented_particles;
        }
    }

    simulation_time = read_timer() - simulation_time;
    if( rank == 0 ) {
        printf( "num_particles = %d, num_procs = %d, simulation time = %g s\n", num_particles, num_procs, simulation_time );
    }

    if (savename) {
        if (rank == 0) {
            final_partition_sizes = (int*) malloc( num_procs * sizeof(int) );
        }
        MPI_Gather(&num_my_particles, 1, MPI_INT, final_partition_sizes, 1, MPI_INT, 0, MPI_COMM_WORLD);
        if (rank == 0) {
            final_partition_offsets = (int*) malloc( num_procs * sizeof(int) );
            final_partition_offsets[0] = 0;
            for (int i = 1; i < num_procs; i++) {
                final_partition_offsets[i] = final_partition_offsets[i-1] + final_partition_sizes[i-1];
            }
        }
        MPI_Gatherv(my_particles, num_my_particles, PARTICLE, particles, final_partition_sizes, final_partition_offsets, PARTICLE, 0, MPI_COMM_WORLD);
        if (rank == 0) {
            save( fsave, num_particles, particles );
            free(final_partition_sizes);
            free(final_partition_offsets);
        }
    }

    free( partition_offsets );
    free( partition_sizes );
    free( my_particles ); // same as my_particles
    free(remaining_particles);
    free( left_sending_buffer );
    free( right_sending_buffer );
    free( left_receiving_buffer );
    free( right_receiving_buffer );
    if( fsave ) fclose( fsave );
    MPI_Finalize();
    return 0;
}
Ejemplo n.º 2
0
static value unserialize_rec( sbuffer *b, value loader ) {
	switch( read_char(b) ) {
	case 'N':
		return val_null;
	case 'T':
		return val_true;
	case 'F':
		return val_false;
	case 'i':
		return alloc_int(read_int(b));
	case 'I':
		return alloc_int32(read_int(b));
	case 'f':
		{
			tfloat d;
			read_str(b,sizeof(tfloat),&d);
			return alloc_float(d);
		}
	case 's':
		{
			int l = read_int(b);
			value v;
			if( l < 0 || l > max_string_size )
				ERROR();
			v = alloc_empty_string(l);
			add_ref(b,v);
			read_str(b,l,(char*)val_string(v));
			return v;
		}
	case 'o':
		{
			int f;
			value o = alloc_object(NULL);
			add_ref(b,o);
			while( (f = read_int(b)) != 0 ) {
				value fval = unserialize_rec(b,loader);
				alloc_field(o,(field)f,fval);
			}
			switch( read_char(b) ) {
			case 'p':
				{
					value v = unserialize_rec(b,loader);
					if( !val_is_object(v) )
						ERROR();
					((vobject*)o)->proto = (vobject*)v;
				}
				break;
			case 'z':
				break;
			default:
				ERROR();
			}
			return o;
		}
	case 'r':
		{
			int n = read_int(b);
			if( n < 0 || n >= b->nrefs )
				ERROR();
			return b->trefs[b->nrefs - n - 1];
		}
	case 'a':
		{
			int i;
			int n = read_int(b);
			value o;
			value *t;
			if( n < 0 || n > max_array_size )
				ERROR();
			o = alloc_array(n);
			t = val_array_ptr(o);
			add_ref(b,o);
			for(i=0;i<n;i++)
				t[i] = unserialize_rec(b,loader);
			return o;

		}
	case 'p':
		{
			int nargs = read_int(b);
			vfunction *f = (vfunction*)alloc_function((void*)1,nargs,NULL);
			vfunction *f2;
			value name;
			add_ref(b,(value)f);
			name = unserialize_rec(b,loader);
			f2 = (vfunction*)val_ocall2(loader,id_loadprim,name,alloc_int(nargs));
			if( !val_is_function(f2) || val_fun_nargs(f2) != nargs )
				failure("Loader returned not-a-function");
			f->t = f2->t;
			f->addr = f2->addr;
			f->module = f2->module;
			return (value)f;
		}
	case 'L':
		{
			vfunction *f = (vfunction*)alloc_function((void*)1,0,NULL);
			value mname;
			int pos;
			int nargs;
			value env;
			add_ref(b,(value)f);
			mname = unserialize_rec(b,loader);
			pos = read_int(b);
			nargs = read_int(b);
			env = unserialize_rec(b,loader);
			if( !val_is_array(env) )
				ERROR();
			{
				value exp = val_ocall2(loader,id_loadmodule,mname,loader);
				value mval;
				unsigned int i;
				int_val *mpos;
				neko_module *m;
				if( !val_is_object(exp) ) {
					buffer b = alloc_buffer("module ");
					val_buffer(b,mname);
					buffer_append(b," is not an object");
					bfailure(b);
				}
				mval = val_field(exp,id_module);
				if( !val_is_kind(mval,neko_kind_module) ) {
					buffer b = alloc_buffer("module ");
					val_buffer(b,mname);
					buffer_append(b," has invalid type");
					bfailure(b);
				}
				m = (neko_module*)val_data(mval);
				mpos = m->code + pos;
				for(i=0;i<m->nglobals;i++) {
					vfunction *g = (vfunction*)m->globals[i];
					if( val_is_function(g) && g->addr == mpos && g->module == m && g->nargs == nargs ) {
						f->t = VAL_FUNCTION;
						f->env = env;
						f->addr = mpos;
						f->nargs = nargs;
						f->module = m;
						return (value)f;
					}
				}
				{
					buffer b = alloc_buffer("module ");
					val_buffer(b,mname);
					buffer_append(b," has been modified");
					bfailure(b);
				}
			}
			return val_null;
		}
	case 'x':
		{
			value mname = unserialize_rec(b,loader);
			value data = unserialize_rec(b,loader);
			value exports = val_ocall2(loader,id_loadmodule,mname,loader);
			value s;
			if( !val_is_object(exports) ) {
				buffer b = alloc_buffer("module ");
				val_buffer(b,mname);
				buffer_append(b," is not an object");
				bfailure(b);
			}
			s = val_field(exports,id_unserialize);
			if( !val_is_function(s) || (val_fun_nargs(s) != 1 && val_fun_nargs(s) != VAR_ARGS) ) {
				buffer b = alloc_buffer("module ");
				val_buffer(b,mname);
				buffer_append(b," has invalid __unserialize function");
			}
			s = val_call1(s,data);
			add_ref(b,s);
			return s;
		}
	case 'h':
		{
			int i;
			vhash *h = (vhash*)alloc(sizeof(vhash));
			h->ncells = read_int(b);
			h->nitems = read_int(b);
			h->cells = (hcell**)alloc(sizeof(hcell*)*h->ncells);
			for(i=0;i<h->ncells;i++)
				h->cells[i] = NULL;
			for(i=0;i<h->nitems;i++) {
				hcell **p;
				hcell *c = (hcell*)alloc(sizeof(hcell));
				c->hkey = read_int(b);
				c->key = unserialize_rec(b,loader);
				c->val = unserialize_rec(b,loader);
				c->next = NULL;
				p = &h->cells[c->hkey % h->ncells];
				while( *p != NULL )
					p = &(*p)->next;
				*p = c;
			}
			return alloc_abstract(k_hash,h);
		}
	default:
		ERROR();
		return val_null;
	}
}
Ejemplo n.º 3
0
char *
gstrptime(char *s, char *fmt, struct tm *tm)
{
    int yday, date;

    date = yday = 0;
    tm->tm_mday = 1;
    tm->tm_mon = tm->tm_hour = tm->tm_min = tm->tm_sec = 0;
    /* make relative times work (user-defined tic step) */
    tm->tm_year = ZERO_YEAR;

    /* we do not yet calculate wday or yday, so make them illegal
     * [but yday will be read by %j]
     */

    tm->tm_yday = tm->tm_wday = -1;

    while (*fmt) {
        if (*fmt != '%') {
            if (*fmt == ' ') {
                /* space in format means zero or more spaces in input */
                while (*s == ' ')
                    ++s;
                ++fmt;
                continue;
            } else if (*fmt == *s) {
                ++s;
                ++fmt;
                continue;
            } else
                break;		/* literal match has failed */
        }
        /* we are processing a percent escape */

        switch (*++fmt) {
        case 'b':		/* abbreviated month name */
        {
            int m;

            for (m = 0; m < 12; ++m)
                if (strncasecmp(s, abbrev_month_names[m],
                                strlen(abbrev_month_names[m])) == 0) {
                    s += strlen(abbrev_month_names[m]);
                    goto found_abbrev_mon;
                }
            /* get here => not found */
            int_warn(DATAFILE, "Bad abbreviated month name");
            m = 0;
found_abbrev_mon:
            tm->tm_mon = m;
            break;
        }

        case 'B':		/* full month name */
        {
            int m;

            for (m = 0; m < 12; ++m)
                if (strncasecmp(s, full_month_names[m],
                                strlen(full_month_names[m])) == 0) {
                    s += strlen(full_month_names[m]);
                    goto found_full_mon;
                }
            /* get here => not found */
            int_warn(DATAFILE, "Bad full month name");
            m = 0;
found_full_mon:
            tm->tm_mon = m;
            break;
        }

        case 'd':		/* read a day of month */
            s = read_int(s, 2, &tm->tm_mday);
            date++;
            break;

        case 'm':		/* month number */
            s = read_int(s, 2, &tm->tm_mon);
            date++;
            --tm->tm_mon;
            break;

        case 'y':		/* year number */
            s = read_int(s, 2, &tm->tm_year);
            /* In line with the current UNIX98 specification by
             * The Open Group and major Unix vendors,
             * two-digit years 69-99 refer to the 20th century, and
             * values in the range 00-68 refer to the 21st century.
             */
            if (tm->tm_year <= 68)
                tm->tm_year += 100;
            date++;
            tm->tm_year += 1900;
            break;

        case 'Y':
            s = read_int(s, 4, &tm->tm_year);
            date++;
            break;

        case 'j':
            s = read_int(s, 3, &tm->tm_yday);
            tm->tm_yday--;
            date++;
            yday++;
            break;

        case 'H':
            s = read_int(s, 2, &tm->tm_hour);
            break;

        case 'M':
            s = read_int(s, 2, &tm->tm_min);
            break;

        case 'S':
            s = read_int(s, 2, &tm->tm_sec);
            break;

        /* read EPOCH data
         * EPOCH is the std. unixtimeformat seconds since 01.01.1970 UTC
         * actualy i would need a read_long (or what time_t is else)
         *  aktualy this is not my idea       i got if from
         * AlunDa Penguin Jones (21.11.97)
         * but changed %t to %s because of strftime
         * and fixed the localtime() into gmtime()
         * maybe we should use ggmtime() ? but who choose double ????
         * Walter Harms <*****@*****.**> 26 Mar 2000
         */

        case 's':
#if 0 /* HBB 20040213: comment this out, but keep it around for now */
        {
            /* time_t when; */
            int when;
            struct tm *tmwhen;
            s = read_int(s, 10, &when);
            tmwhen = gmtime((time_t*)&when);
            tmwhen->tm_year += 1900;
            *tm = *tmwhen;
            break;
        }
#else
            /* HBB 20040213: New version of this.  64-bit proof and
             * more in line with the rest of this module than the
             * original one. */
        {
            double when;
            /* offset from UNIX epoch (1970) to gnuplot epoch */
            static const long epoch_offset
                = (long)((ZERO_YEAR - 1970) * 365.25) * DAY_SEC;

            when = strtod (s, &s) - epoch_offset;
            ggmtime(tm, when);
            break;
        }
#endif
        default:
            int_warn(DATAFILE, "Bad time format in string");
        }
        fmt++;
    }

    FPRINTF((stderr, "read date-time : %02d/%02d/%d:%02d:%02d:%02d\n", tm->tm_mday, tm->tm_mon + 1, tm->tm_year, tm->tm_hour, tm->tm_min, tm->tm_sec));

    /* now check the date/time entered, normalising if necessary
     * read_int cannot read a -ve number, but can read %m=0 then decrement
     * it to -1
     */

#define S (tm->tm_sec)
#define M (tm->tm_min)
#define H (tm->tm_hour)

    if (S >= 60) {
        M += S / 60;
        S %= 60;
    }
    if (M >= 60) {
        H += M / 60;
        M %= 60;
    }
    if (H >= 24) {
        if (yday)
            tm->tm_yday += H / 24;
        tm->tm_mday += H / 24;
        H %= 24;
    }
#undef S
#undef M
#undef H

    FPRINTF((stderr, "normalised time : %02d/%02d/%d:%02d:%02d:%02d\n", tm->tm_mday, tm->tm_mon + 1, tm->tm_year, tm->tm_hour, tm->tm_min, tm->tm_sec));

    if (date) {
        if (yday) {

            if (tm->tm_yday < 0)
                int_error(DATAFILE, "Illegal day of year");

            /* we just set month to jan, day to yday, and let the
             * normalising code do the work.
             */

            tm->tm_mon = 0;
            /* yday is 0->365, day is 1->31 */
            tm->tm_mday = tm->tm_yday + 1;
        }
        if (tm->tm_mon < 0) {
            int_error(DATAFILE, "illegal month");
            return (NULL);
        }
        if (tm->tm_mday < 1) {
            int_error(DATAFILE, "illegal day of month");
            return (NULL);
        }
        if (tm->tm_mon > 11) {
            tm->tm_year += tm->tm_mon / 12;
            tm->tm_mon %= 12;
        } {
            int days_in_month;
            while (tm->tm_mday > (days_in_month = (mndday[tm->tm_mon] + (tm->tm_mon == 1 && (gdysize(tm->tm_year) > 365))))) {
                if (++tm->tm_mon == 12) {
                    ++tm->tm_year;
                    tm->tm_mon = 0;
                }
                tm->tm_mday -= days_in_month;
            }
        }
    }
    return (s);
}
Ejemplo n.º 4
0
void read_prepfoldinfo(prepfoldinfo * in, char *filename)
/* Read a prepfoldinfo data structure from a binary file */
{
   FILE *infile;
   int itmp, byteswap = 0;
   float ftmp;
   char temp[16];

   infile = chkfopen(filename, "rb");
   in->numdms = read_int(infile, byteswap);
   in->numperiods = read_int(infile, byteswap);
   in->numpdots = read_int(infile, byteswap);
   in->nsub = read_int(infile, byteswap);
   in->npart = read_int(infile, byteswap);
   /* The following is not exactly the most robust, but it should work... */
   if (in->npart < 1 || in->npart > 10000) {
      byteswap = 1;
      in->numdms = swap_int(in->numdms);
      in->numperiods = swap_int(in->numperiods);
      in->numpdots = swap_int(in->numpdots);
      in->nsub = swap_int(in->nsub);
      in->npart = swap_int(in->npart);
   }
   in->proflen = read_int(infile, byteswap);
   in->numchan = read_int(infile, byteswap);
   in->pstep = read_int(infile, byteswap);
   in->pdstep = read_int(infile, byteswap);
   in->dmstep = read_int(infile, byteswap);
   in->ndmfact = read_int(infile, byteswap);
   in->npfact = read_int(infile, byteswap);
   itmp = read_int(infile, byteswap);
   in->filenm = calloc(itmp + 1, sizeof(char));
   chkfread(in->filenm, sizeof(char), itmp, infile);
   itmp = read_int(infile, byteswap);
   in->candnm = calloc(itmp + 1, sizeof(char));
   chkfread(in->candnm, sizeof(char), itmp, infile);
   itmp = read_int(infile, byteswap);
   in->telescope = calloc(itmp + 1, sizeof(char));
   chkfread(in->telescope, sizeof(char), itmp, infile);
   itmp = read_int(infile, byteswap);
   in->pgdev = calloc(itmp + 1, sizeof(char));
   chkfread(in->pgdev, sizeof(char), itmp, infile);
   {
      int has_posn = 1, ii;
      chkfread(temp, sizeof(char), 16, infile);
      /* Check to see if a position string was written */
      for (ii = 0; ii < 16; ii++) {
         if (!isdigit(temp[ii]) &&
             temp[ii] != ':' &&
             temp[ii] != '.' && temp[ii] != '-' && temp[ii] != '\0') {
            has_posn = 0;
            break;
         }
      }
      if (has_posn) {
         strcpy(in->rastr, temp);
         chkfread(in->decstr, sizeof(char), 16, infile);
         in->dt = read_double(infile, byteswap);
         in->startT = read_double(infile, byteswap);
      } else {
         strcpy(in->rastr, "Unknown");
         strcpy(in->decstr, "Unknown");
         in->dt = *(double *) (temp + 0);
         if (byteswap)
            in->dt = swap_double(in->dt);
         in->startT = *(double *) (temp + sizeof(double));
         if (byteswap)
            in->startT = swap_double(in->startT);
      }
   }
   in->endT = read_double(infile, byteswap);
   in->tepoch = read_double(infile, byteswap);
   in->bepoch = read_double(infile, byteswap);
   in->avgvoverc = read_double(infile, byteswap);
   in->lofreq = read_double(infile, byteswap);
   in->chan_wid = read_double(infile, byteswap);
   in->bestdm = read_double(infile, byteswap);
   /* The .pow elements were written as doubles (Why??) */
   in->topo.pow = read_float(infile, byteswap);
   ftmp = read_float(infile, byteswap);
   in->topo.p1 = read_double(infile, byteswap);
   in->topo.p2 = read_double(infile, byteswap);
   in->topo.p3 = read_double(infile, byteswap);
   /* The .pow elements were written as doubles (Why??) */
   in->bary.pow = read_float(infile, byteswap);
   ftmp = read_float(infile, byteswap);
   in->bary.p1 = read_double(infile, byteswap);
   in->bary.p2 = read_double(infile, byteswap);
   in->bary.p3 = read_double(infile, byteswap);
   /* The .pow elements were written as doubles (Why??) */
   in->fold.pow = read_float(infile, byteswap);
   ftmp = read_float(infile, byteswap);
   in->fold.p1 = read_double(infile, byteswap);
   in->fold.p2 = read_double(infile, byteswap);
   in->fold.p3 = read_double(infile, byteswap);
   in->orb.p = read_double(infile, byteswap);
   in->orb.e = read_double(infile, byteswap);
   in->orb.x = read_double(infile, byteswap);
   in->orb.w = read_double(infile, byteswap);
   in->orb.t = read_double(infile, byteswap);
   in->orb.pd = read_double(infile, byteswap);
   in->orb.wd = read_double(infile, byteswap);
   in->dms = gen_dvect(in->numdms);
   chkfread(in->dms, sizeof(double), in->numdms, infile);
   in->periods = gen_dvect(in->numperiods);
   chkfread(in->periods, sizeof(double), in->numperiods, infile);
   in->pdots = gen_dvect(in->numpdots);
   chkfread(in->pdots, sizeof(double), in->numpdots, infile);
   in->rawfolds = gen_dvect(in->nsub * in->npart * in->proflen);
   chkfread(in->rawfolds, sizeof(double), in->nsub *
            in->npart * in->proflen, infile);
   in->stats = (foldstats *) malloc(sizeof(foldstats) * in->nsub * in->npart);
   chkfread(in->stats, sizeof(foldstats), in->nsub * in->npart, infile);
   fclose(infile);
   if (byteswap) {
      int ii;
      for (ii = 0; ii < in->numdms; ii++)
         in->dms[ii] = swap_double(in->dms[ii]);
      for (ii = 0; ii < in->numperiods; ii++)
         in->periods[ii] = swap_double(in->periods[ii]);
      for (ii = 0; ii < in->numpdots; ii++)
         in->pdots[ii] = swap_double(in->pdots[ii]);
      for (ii = 0; ii < in->nsub * in->npart * in->proflen; ii++)
         in->rawfolds[ii] = swap_double(in->rawfolds[ii]);
      for (ii = 0; ii < in->nsub * in->npart; ii++) {
         in->stats[ii].numdata = swap_double(in->stats[ii].numdata);
         in->stats[ii].data_avg = swap_double(in->stats[ii].data_avg);
         in->stats[ii].data_var = swap_double(in->stats[ii].data_var);
         in->stats[ii].numprof = swap_double(in->stats[ii].numprof);
         in->stats[ii].prof_avg = swap_double(in->stats[ii].prof_avg);
         in->stats[ii].prof_var = swap_double(in->stats[ii].prof_var);
         in->stats[ii].redchi = swap_double(in->stats[ii].redchi);
      }
   }
}
Ejemplo n.º 5
0
static struct grub_diskfilter_vg *
make_vg (grub_disk_t disk,
	 const struct grub_ldm_label *label)
{
  grub_disk_addr_t startsec, endsec, cursec;
  struct grub_diskfilter_vg *vg;
  grub_err_t err;

  /* First time we see this volume group. We've to create the
     whole volume group structure. */
  vg = grub_malloc (sizeof (*vg));
  if (! vg)
    return NULL;
  vg->extent_size = 1;
  vg->name = grub_malloc (LDM_NAME_STRLEN + 1);
  vg->uuid = grub_malloc (LDM_GUID_STRLEN + 1);
  if (! vg->uuid || !vg->name)
    {
      grub_free (vg->uuid);
      grub_free (vg->name);
      return NULL;
    }
  grub_memcpy (vg->uuid, label->group_guid, LDM_GUID_STRLEN);
  grub_memcpy (vg->name, label->group_name, LDM_NAME_STRLEN);
  vg->name[LDM_NAME_STRLEN] = 0;
  vg->uuid[LDM_GUID_STRLEN] = 0;
  vg->uuid_len = grub_strlen (vg->uuid);

  vg->lvs = NULL;
  vg->pvs = NULL;

  startsec = grub_be_to_cpu64 (label->config_start);
  endsec = startsec + grub_be_to_cpu64 (label->config_size);

  /* First find disks.  */
  for (cursec = startsec + 0x12; cursec < endsec; cursec++)
    {
      struct grub_ldm_vblk vblk[GRUB_DISK_SECTOR_SIZE
				/ sizeof (struct grub_ldm_vblk)];
      unsigned i;
      err = grub_disk_read (disk, cursec, 0,
			    sizeof(vblk), &vblk);
      if (err)
	goto fail2;

      for (i = 0; i < ARRAY_SIZE (vblk); i++)
	{
	  struct grub_diskfilter_pv *pv;
	  grub_uint8_t *ptr;
	  if (grub_memcmp (vblk[i].magic, LDM_VBLK_MAGIC,
			   sizeof (vblk[i].magic)) != 0)
	    continue;
	  if (grub_be_to_cpu16 (vblk[i].update_status)
	      != STATUS_CONSISTENT
	      && grub_be_to_cpu16 (vblk[i].update_status)
	      != STATUS_STILL_ACTIVE)
	    continue;
	  if (vblk[i].type != ENTRY_DISK)
	    continue;
	  pv = grub_zalloc (sizeof (*pv));
	  if (!pv)
	    goto fail2;

	  pv->disk = 0;
	  ptr = vblk[i].dynamic;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic
	      + sizeof (vblk[i].dynamic))
	    {
	      grub_free (pv);
	      goto fail2;
	    }
	  pv->internal_id = grub_malloc (ptr[0] + 2);
	  if (!pv->internal_id)
	    {
	      grub_free (pv);
	      goto fail2;
	    }
	  grub_memcpy (pv->internal_id, ptr, (grub_size_t) ptr[0] + 1);
	  pv->internal_id[(grub_size_t) ptr[0] + 1] = 0;
	  
	  ptr += *ptr + 1;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic
	      + sizeof (vblk[i].dynamic))
	    {
	      grub_free (pv);
	      goto fail2;
	    }
	  /* ptr = name.  */
	  ptr += *ptr + 1;
	  if (ptr + *ptr + 1
	      >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (pv);
	      goto fail2;
	    }
	  pv->id.uuidlen = *ptr;
	  pv->id.uuid = grub_malloc (pv->id.uuidlen + 1);
	  grub_memcpy (pv->id.uuid, ptr + 1, pv->id.uuidlen);
	  pv->id.uuid[pv->id.uuidlen] = 0;

	  pv->next = vg->pvs;
	  vg->pvs = pv;
	}
    }

  /* Then find LVs.  */
  for (cursec = startsec + 0x12; cursec < endsec; cursec++)
    {
      struct grub_ldm_vblk vblk[GRUB_DISK_SECTOR_SIZE
				/ sizeof (struct grub_ldm_vblk)];
      unsigned i;
      err = grub_disk_read (disk, cursec, 0,
			    sizeof(vblk), &vblk);
      if (err)
	goto fail2;

      for (i = 0; i < ARRAY_SIZE (vblk); i++)
	{
	  struct grub_diskfilter_lv *lv;
	  grub_uint8_t *ptr;
	  if (grub_memcmp (vblk[i].magic, LDM_VBLK_MAGIC,
			   sizeof (vblk[i].magic)) != 0)
	    continue;
	  if (grub_be_to_cpu16 (vblk[i].update_status)
	      != STATUS_CONSISTENT
	      && grub_be_to_cpu16 (vblk[i].update_status)
	      != STATUS_STILL_ACTIVE)
	    continue;
	  if (vblk[i].type != ENTRY_VOLUME)
	    continue;
	  lv = grub_zalloc (sizeof (*lv));
	  if (!lv)
	    goto fail2;

	  lv->vg = vg;
	  lv->segment_count = 1;
	  lv->segment_alloc = 1;
	  lv->visible = 1;
	  lv->segments = grub_zalloc (sizeof (*lv->segments));
	  if (!lv->segments)
	    goto fail2;
	  lv->segments->start_extent = 0;
	  lv->segments->type = GRUB_DISKFILTER_MIRROR;
	  lv->segments->node_count = 0;
	  lv->segments->node_alloc = 8;
	  lv->segments->nodes = grub_zalloc (sizeof (*lv->segments->nodes)
					     * lv->segments->node_alloc);
	  if (!lv->segments->nodes)
	    goto fail2;
	  ptr = vblk[i].dynamic;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic
	      + sizeof (vblk[i].dynamic))
	    {
	      grub_free (lv);
	      goto fail2;
	    }
	  lv->internal_id = grub_malloc ((grub_size_t) ptr[0] + 2);
	  if (!lv->internal_id)
	    {
	      grub_free (lv);
	      goto fail2;
	    }
	  grub_memcpy (lv->internal_id, ptr, ptr[0] + 1);
	  lv->internal_id[ptr[0] + 1] = 0;

	  ptr += *ptr + 1;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic
	      + sizeof (vblk[i].dynamic))
	    {
	      grub_free (lv);
	      goto fail2;
	    }
	  lv->name = grub_malloc (*ptr + 1);
	  if (!lv->name)
	    {
	      grub_free (lv->internal_id);
	      grub_free (lv);
	      goto fail2;
	    }
	  grub_memcpy (lv->name, ptr + 1, *ptr);
	  lv->name[*ptr] = 0;
	  lv->fullname = grub_xasprintf ("ldm/%s/%s",
					 vg->uuid, lv->name);
	  if (!lv->fullname)
	    {
	      grub_free (lv->internal_id);
	      grub_free (lv->name);
	      grub_free (lv);
	      goto fail2;
	    }
	  ptr += *ptr + 1;
	  if (ptr + *ptr + 1
	      >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (lv->internal_id);
	      grub_free (lv->name);
	      grub_free (lv);
	      goto fail2;
	    }
	  /* ptr = volume type.  */
	  ptr += *ptr + 1;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (lv->internal_id);
	      grub_free (lv->name);
	      grub_free (lv);
	      goto fail2;
	    }
	  /* ptr = flags.  */
	  ptr += *ptr + 1;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (lv->internal_id);
	      grub_free (lv->name);
	      grub_free (lv);
	      goto fail2;
	    }

	  /* Skip state, type, unknown, volume number, zeros, flags. */
	  ptr += 14 + 1 + 1 + 1 + 3 + 1;
	  /* ptr = number of children.  */
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (lv->internal_id);
	      grub_free (lv->name);
	      grub_free (lv);
	      goto fail2;
	    }
	  ptr += *ptr + 1;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (lv->internal_id);
	      grub_free (lv->name);
	      grub_free (lv);
	      goto fail2;
	    }

	  /* Skip 2 more fields.  */
	  ptr += 8 + 8;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)
	      || ptr + *ptr + 1>= vblk[i].dynamic
	      + sizeof (vblk[i].dynamic))
	    {
	      grub_free (lv->internal_id);
	      grub_free (lv->name);
	      grub_free (lv);
	      goto fail2;
	    }
	  lv->size = read_int (ptr + 1, *ptr);
	  lv->segments->extent_count = lv->size;

	  lv->next = vg->lvs;
	  vg->lvs = lv;
	}
    }

  /* Now the components.  */
  for (cursec = startsec + 0x12; cursec < endsec; cursec++)
    {
      struct grub_ldm_vblk vblk[GRUB_DISK_SECTOR_SIZE
				/ sizeof (struct grub_ldm_vblk)];
      unsigned i;
      err = grub_disk_read (disk, cursec, 0,
			    sizeof(vblk), &vblk);
      if (err)
	goto fail2;

      for (i = 0; i < ARRAY_SIZE (vblk); i++)
	{
	  struct grub_diskfilter_lv *comp;
	  struct grub_diskfilter_lv *lv;
	  grub_uint8_t type;

	  grub_uint8_t *ptr;
	  if (grub_memcmp (vblk[i].magic, LDM_VBLK_MAGIC,
			   sizeof (vblk[i].magic)) != 0)
	    continue;
	  if (grub_be_to_cpu16 (vblk[i].update_status)
	      != STATUS_CONSISTENT
	      && grub_be_to_cpu16 (vblk[i].update_status)
	      != STATUS_STILL_ACTIVE)
	    continue;
	  if (vblk[i].type != ENTRY_COMPONENT)
	    continue;
	  comp = grub_zalloc (sizeof (*comp));
	  if (!comp)
	    goto fail2;
	  comp->visible = 0;
	  comp->name = 0;
	  comp->fullname = 0;

	  ptr = vblk[i].dynamic;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      goto fail2;
	    }
	  comp->internal_id = grub_malloc ((grub_size_t) ptr[0] + 2);
	  if (!comp->internal_id)
	    {
	      grub_free (comp);
	      goto fail2;
	    }
	  grub_memcpy (comp->internal_id, ptr, ptr[0] + 1);
	  comp->internal_id[ptr[0] + 1] = 0;

	  ptr += *ptr + 1;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (comp->internal_id);
	      grub_free (comp);
	      goto fail2;
	    }
	  /* ptr = name.  */
	  ptr += *ptr + 1;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (comp->internal_id);
	      grub_free (comp);
	      goto fail2;
	    }
	  /* ptr = state.  */
	  ptr += *ptr + 1;
	  type = *ptr++;
	  /* skip zeros.  */
	  ptr += 4;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (comp->internal_id);
	      grub_free (comp);
	      goto fail2;
	    }

	  /* ptr = number of children. */
	  ptr += *ptr + 1;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      grub_free (comp->internal_id);
	      grub_free (comp);
	      goto fail2;
	    }
	  ptr += 8 + 8;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic
	      + sizeof (vblk[i].dynamic))
	    {
	      grub_free (comp->internal_id);
	      grub_free (comp);
	      goto fail2;
	    }
	  for (lv = vg->lvs; lv; lv = lv->next)
	    {
	      if (lv->internal_id[0] == ptr[0]
		  && grub_memcmp (lv->internal_id + 1, ptr + 1, ptr[0]) == 0)
		break;
	    }
	  if (!lv)
	    {
	      grub_free (comp->internal_id);
	      grub_free (comp);
	      continue;
	    }
	  comp->size = lv->size;
	  if (type == SPANNED)
	    {
	      comp->segment_alloc = 8;
	      comp->segment_count = 0;
	      comp->segments = grub_malloc (sizeof (*comp->segments)
					    * comp->segment_alloc);
	      if (!comp->segments)
		goto fail2;
	    }
	  else
	    {
	      comp->segment_alloc = 1;
	      comp->segment_count = 1;
	      comp->segments = grub_malloc (sizeof (*comp->segments));
	      if (!comp->segments)
		goto fail2;
	      comp->segments->start_extent = 0;
	      comp->segments->extent_count = lv->size;
	      comp->segments->layout = 0;
	      if (type == STRIPE)
		comp->segments->type = GRUB_DISKFILTER_STRIPED;
	      else if (type == RAID5)
		{
		  comp->segments->type = GRUB_DISKFILTER_RAID5;
		  comp->segments->layout = GRUB_RAID_LAYOUT_SYMMETRIC_MASK;
		}
	      else
		goto fail2;
	      ptr += *ptr + 1;
	      ptr++;
	      if (!(vblk[i].flags & 0x10))
		goto fail2;
	      if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)
		  || ptr + *ptr + 1 >= vblk[i].dynamic
		  + sizeof (vblk[i].dynamic))
		{
		  grub_free (comp->internal_id);
		  grub_free (comp);
		  goto fail2;
		}
	      comp->segments->stripe_size = read_int (ptr + 1, *ptr);
	      ptr += *ptr + 1;
	      if (ptr + *ptr + 1 >= vblk[i].dynamic
		  + sizeof (vblk[i].dynamic))
		{
		  grub_free (comp->internal_id);
		  grub_free (comp);
		  goto fail2;
		}
	      comp->segments->node_count = read_int (ptr + 1, *ptr);
	      comp->segments->node_alloc = comp->segments->node_count;
	      comp->segments->nodes = grub_zalloc (sizeof (*comp->segments->nodes)
						   * comp->segments->node_alloc);
	      if (!lv->segments->nodes)
		goto fail2;
	    }

	  if (lv->segments->node_alloc == lv->segments->node_count)
	    {
	      void *t;
	      lv->segments->node_alloc *= 2; 
	      t = grub_realloc (lv->segments->nodes,
				sizeof (*lv->segments->nodes)
				* lv->segments->node_alloc);
	      if (!t)
		goto fail2;
	      lv->segments->nodes = t;
	    }
	  lv->segments->nodes[lv->segments->node_count].pv = 0;
	  lv->segments->nodes[lv->segments->node_count].start = 0;
	  lv->segments->nodes[lv->segments->node_count++].lv = comp;
	  comp->next = vg->lvs;
	  vg->lvs = comp;
	}
    }
  /* Partitions.  */
  for (cursec = startsec + 0x12; cursec < endsec; cursec++)
    {
      struct grub_ldm_vblk vblk[GRUB_DISK_SECTOR_SIZE
				/ sizeof (struct grub_ldm_vblk)];
      unsigned i;
      err = grub_disk_read (disk, cursec, 0,
			    sizeof(vblk), &vblk);
      if (err)
	goto fail2;

      for (i = 0; i < ARRAY_SIZE (vblk); i++)
	{
	  struct grub_diskfilter_lv *comp;
	  struct grub_diskfilter_node part;
	  grub_disk_addr_t start, size;

	  grub_uint8_t *ptr;
	  part.name = 0;
	  if (grub_memcmp (vblk[i].magic, LDM_VBLK_MAGIC,
			   sizeof (vblk[i].magic)) != 0)
	    continue;
	  if (grub_be_to_cpu16 (vblk[i].update_status)
	      != STATUS_CONSISTENT
	      && grub_be_to_cpu16 (vblk[i].update_status)
	      != STATUS_STILL_ACTIVE)
	    continue;
	  if (vblk[i].type != ENTRY_PARTITION)
	    continue;
	  part.lv = 0;
	  part.pv = 0;

	  ptr = vblk[i].dynamic;
	  if (ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      goto fail2;
	    }
	  /* ID */
	  ptr += *ptr + 1;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      goto fail2;
	    }
	  /* ptr = name.  */
	  ptr += *ptr + 1;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      goto fail2;
	    }

	  /* skip zeros and logcommit id.  */
	  ptr += 4 + 8;
	  if (ptr + 16 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      goto fail2;
	    }
	  part.start = read_int (ptr, 8);
	  start = read_int (ptr + 8, 8);
	  ptr += 16;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)
	      || ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      goto fail2;
	    }
	  size = read_int (ptr + 1, *ptr);
	  ptr += *ptr + 1;
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)
	      || ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      goto fail2;
	    }

	  for (comp = vg->lvs; comp; comp = comp->next)
	    if (comp->internal_id[0] == ptr[0]
		&& grub_memcmp (ptr + 1, comp->internal_id + 1,
				comp->internal_id[0]) == 0)
	      goto out;
	  continue;
	out:
	  if (ptr >= vblk[i].dynamic + sizeof (vblk[i].dynamic)
	      || ptr + *ptr + 1 >= vblk[i].dynamic + sizeof (vblk[i].dynamic))
	    {
	      goto fail2;
	    }
	  ptr += *ptr + 1;
	  struct grub_diskfilter_pv *pv;
	  for (pv = vg->pvs; pv; pv = pv->next)
	    if (pv->internal_id[0] == ptr[0]
		&& grub_memcmp (pv->internal_id + 1, ptr + 1, ptr[0]) == 0)
	      part.pv = pv;

	  if (comp->segment_alloc == 1)
	    {
	      unsigned node_index;
	      ptr += *ptr + 1;
	      if (ptr + *ptr + 1 >= vblk[i].dynamic
		  + sizeof (vblk[i].dynamic))
		{
		  goto fail2;
		}
	      node_index = read_int (ptr + 1, *ptr);
	      if (node_index < comp->segments->node_count)
		comp->segments->nodes[node_index] = part;
	    }
	  else
	    {
	      if (comp->segment_alloc == comp->segment_count)
		{
		  void *t;
		  comp->segment_alloc *= 2;
		  t = grub_realloc (comp->segments,
				    comp->segment_alloc
				    * sizeof (*comp->segments));
		  if (!t)
		    goto fail2;
		  comp->segments = t;
		}
	      comp->segments[comp->segment_count].start_extent = start;
	      comp->segments[comp->segment_count].extent_count = size;
	      comp->segments[comp->segment_count].type = GRUB_DISKFILTER_STRIPED;
	      comp->segments[comp->segment_count].node_count = 1;
	      comp->segments[comp->segment_count].node_alloc = 1;
	      comp->segments[comp->segment_count].nodes
		= grub_malloc (sizeof (*comp->segments[comp->segment_count].nodes));
	      if (!comp->segments[comp->segment_count].nodes)
		goto fail2;
	      comp->segments[comp->segment_count].nodes[0] = part;
	      comp->segment_count++;
	    }
	}
    }
  if (grub_diskfilter_vg_register (vg))
    goto fail2;
  return vg;
 fail2:
  {
    struct grub_diskfilter_lv *lv, *next_lv;
    struct grub_diskfilter_pv *pv, *next_pv;
    for (lv = vg->lvs; lv; lv = next_lv)
      {
	unsigned i;
	for (i = 0; i < lv->segment_count; i++)
	  grub_free (lv->segments[i].nodes);

	next_lv = lv->next;
	grub_free (lv->segments);
	grub_free (lv->internal_id);
	grub_free (lv->name);
	grub_free (lv->fullname);
	grub_free (lv);
      }
    for (pv = vg->pvs; pv; pv = next_pv)
      {
	next_pv = pv->next;
	grub_free (pv->id.uuid);
	grub_free (pv);
      }
  }
  grub_free (vg->uuid);
  grub_free (vg);
  return NULL;
}
Ejemplo n.º 6
0
 /* For wilderness levels, dun_depth has been changed from 1 to 4 bytes. */
static void rd_item(object_type *o_ptr)
{
	byte old_dd;
	byte old_ds;

	u32b f1, f2, f3;

	object_kind *k_ptr;

	char note[128];

	start_section_read("item");
	
	/* Hack -- wipe */
	WIPE(o_ptr, object_type);

	/* Skip name */
	skip_value("name");

	/* Kind */
	o_ptr->k_idx = read_int("k_idx");

	/* Location */
	o_ptr->iy = read_int("iy");
	o_ptr->ix = read_int("ix");
	
	o_ptr->dun_depth = read_int("dun_depth");

	/* Type/Subtype */
	o_ptr->tval = read_int("tval");
	o_ptr->sval = read_int("sval");

	/* Base pval */
	o_ptr->bpval = read_int("bpval");

	/* Special pval */
	o_ptr->pval = read_int("pval");


	o_ptr->discount = read_int("discount");
	o_ptr->number = read_int("number");
	o_ptr->weight = read_int("weight");

	o_ptr->name1 = read_int("name1");
	o_ptr->name2 = read_int("name2");
	o_ptr->name3 = read_int("name3");
	o_ptr->timeout = read_int("timeout");

	o_ptr->to_h = read_int("to_h");
	o_ptr->to_d = read_int("to_d");
	o_ptr->to_a = read_int("to_a");

	o_ptr->ac = read_int("ac");

	old_dd = read_int("dd");
	old_ds = read_int("ds");

	o_ptr->ident = read_int("ident");

	/* Special powers */
	o_ptr->xtra1 = read_int("xtra1");
	o_ptr->xtra2 = read_int("xtra2");

	/* Inscription */
	read_str("inscription",note); 
 
	/* Save the inscription */
	if (note[0]) o_ptr->note = quark_add(note);

	/* Owner information */
	if (value_exists("owner_name"))
	{
		/* Name */
		read_str("owner_name",note);
		/* Save */
		if (!STRZERO(note)) o_ptr->owner_name = quark_add(note); 
		/* Id */
		o_ptr->owner_id = read_int("owner_id");
	}

	/* Monster holding object */ 
   o_ptr->held_m_idx = read_int("held_m_idx");

	end_section_read("item");

	/* Mega-Hack -- handle "dungeon objects" later */
	if ((o_ptr->k_idx >= 445) && (o_ptr->k_idx <= 479)) return;


	/* Obtain the "kind" template */
	k_ptr = &k_info[o_ptr->k_idx];

	/* Obtain tval/sval from k_info */
	o_ptr->tval = k_ptr->tval;
	o_ptr->sval = k_ptr->sval;


	/* Hack -- notice "broken" items */
	if (k_ptr->cost <= 0) o_ptr->ident |= ID_BROKEN;


	/* Repair non "wearable" items */
	if (!wearable_p(o_ptr))
	{
		/* Acquire correct fields */
		o_ptr->to_h = k_ptr->to_h;
		o_ptr->to_d = k_ptr->to_d;
		o_ptr->to_a = k_ptr->to_a;

		/* Acquire correct fields */
		o_ptr->ac = k_ptr->ac;
		o_ptr->dd = k_ptr->dd;
		o_ptr->ds = k_ptr->ds;

		/* Acquire correct weight */
		o_ptr->weight = k_ptr->weight;

		/* Paranoia */
		o_ptr->name1 = o_ptr->name2 = 0;

		/* All done */
		return;
	}


	/* Extract the flags */
	object_flags(o_ptr, &f1, &f2, &f3);


	/* Paranoia */
	if (true_artifact_p(o_ptr))
	{
		artifact_type *a_ptr;

		/* Obtain the artifact info */
		a_ptr = &a_info[o_ptr->name1];

		/* Verify that artifact */
		if (!a_ptr->name) o_ptr->name1 = 0;
	}

	/* Paranoia */
	if (o_ptr->name2)
	{
		ego_item_type *e_ptr;

		/* Obtain the ego-item info */
		e_ptr = &e_info[o_ptr->name2];

		/* Verify that ego-item */
		if (!e_ptr->name) o_ptr->name2 = 0;
	}


	/* Acquire standard fields */
	o_ptr->ac = k_ptr->ac;
	o_ptr->dd = k_ptr->dd;
	o_ptr->ds = k_ptr->ds;

	/* Acquire standard weight */
	o_ptr->weight = k_ptr->weight;

	/* Hack -- extract the "broken" flag */
	if (o_ptr->pval < 0) o_ptr->ident |= ID_BROKEN;


	/* Artifacts */
	if (artifact_p(o_ptr))
	{
		artifact_type *a_ptr;

		/* Obtain the artifact info */
#if defined(RANDART)
		if (o_ptr->name1 == ART_RANDART)
		{
			a_ptr = randart_make(o_ptr);
		}
		else
		{
#endif
		a_ptr = &a_info[o_ptr->name1];
#if defined(RANDART)
		}
#endif
		/* Acquire new artifact "pval" */
		o_ptr->pval = a_ptr->pval;

		/* Acquire new artifact fields */
		o_ptr->ac = a_ptr->ac;
		o_ptr->dd = a_ptr->dd;
		o_ptr->ds = a_ptr->ds;

		/* Acquire new artifact weight */
		o_ptr->weight = a_ptr->weight;

		/* Hack -- extract the "broken" flag */
		if (!a_ptr->cost) o_ptr->ident |= ID_BROKEN;
	}

	/* Ego items */
	if (o_ptr->name2)
	{
		ego_item_type *e_ptr;

		/* Obtain the ego-item info */
		e_ptr = &e_info[o_ptr->name2];

		/* Hack -- keep some old fields */
		if ((o_ptr->dd < old_dd) && (o_ptr->ds == old_ds))
		{
			/* Keep old boosted damage dice */
			o_ptr->dd = old_dd;
		}

		/* Hack -- extract the "broken" flag */
		if (!e_ptr->cost) o_ptr->ident |= ID_BROKEN;

		/* Mega-Hack - Enforce the special broken items */
		if ((o_ptr->name2 == EGO_BLASTED) ||
			(o_ptr->name2 == EGO_SHATTERED))
		{
			/* These were set to k_info values by preceding code */
			o_ptr->ac = 0;
			o_ptr->dd = 0;
			o_ptr->ds = 0;
		}
	}
}
Ejemplo n.º 7
0
/*
 * Read the monster lore
 */
static void rd_lore(player_type *p_ptr, int r_idx)
{
	int i;
	
	monster_lore *l_ptr = p_ptr->l_list + r_idx;

	start_section_read("lore");

	/* Count sights/deaths/kills */
	l_ptr->sights = read_int("sights");
	l_ptr->deaths = read_int("deaths");
	l_ptr->pkills = read_int("pkills");
	l_ptr->tkills = read_int("tkills");

	/* Count wakes and ignores */
	l_ptr->wake = read_int("wake");
	l_ptr->ignore = read_int("ignore");

	/* Count drops */
	l_ptr->drop_gold = read_int("drop_gold");
	l_ptr->drop_item = read_int("drop_item");

	/* Count spells */
	l_ptr->cast_innate = read_int("cast_innate");
	l_ptr->cast_spell = read_int("cast_spell");

	/* Count blows of each type */
	start_section_read("blows");
	for (i = 0; i < MONSTER_BLOW_MAX; i++)
		l_ptr->blows[i] = read_int("blow");
	end_section_read("blows");


	/* Memorize flags */
	start_section_read("flags");
	l_ptr->flags1 = read_int("flag");
	l_ptr->flags2 = read_int("flag");
	l_ptr->flags3 = read_int("flag");
	l_ptr->flags4 = read_int("flag");
	l_ptr->flags5 = read_int("flag");
	l_ptr->flags6 = read_int("flag");
	end_section_read("flags");

	/* Repair the lore flags */
	/* No need to repair AFAIU
	l_ptr->flags1 &= r_ptr->flags1;
	l_ptr->flags2 &= r_ptr->flags2;
	l_ptr->flags3 &= r_ptr->flags3;
	l_ptr->flags4 &= r_ptr->flags4;
	l_ptr->flags5 &= r_ptr->flags5;
	l_ptr->flags6 &= r_ptr->flags6;
	*/
	end_section_read("lore");
}
Ejemplo n.º 8
0
 // BCI encoding is mostly unsigned, but -1 is a distinguished value
 int read_bci() { return read_int() + InvocationEntryBci; }
Ejemplo n.º 9
0
/*
=================
ReadLevel

SpawnEntities will allready have been called on the
level the same way it was when the level was saved.

That is necessary to get the baselines
set up identically.

The server will have cleared all of the world links before
calling ReadLevel.

No clients are connected yet.
=================
*/
void ReadLevel (const char *filename) {
    int     entnum;
    FILE    *f;
    int     i;
    edict_t *ent;

    // free any dynamic memory allocated by loading the level
    // base state
    gi.FreeTags (TAG_LEVEL);

    f = fopen (filename, "rb");
    if (!f)
        gi.error ("Couldn't open %s", filename);

    // wipe all the entities
    memset (g_edicts, 0, game.maxentities*sizeof(g_edicts[0]));
    globals.num_edicts = maxclients->value+1;

    i = read_int( f );
    if( i != SAVE_MAGIC2 ) {
        fclose (f);
        gi.error ("Not a save game");
    }

    i = read_int( f );
    if( i != SAVE_VERSION ) {
        fclose (f);
        gi.error ("Savegame from an older version.\n");
    }

    // load the level locals
    read_fields( f, levelfields, &level );

    // load all the entities
    while( 1 ) {
        entnum = read_int( f );
        if( entnum == -1 )
            break;
        if( entnum < 0 || entnum >= game.maxentities ) {
            gi.error( "%s: bad entity number", __func__ );
        }
        if( entnum >= globals.num_edicts )
            globals.num_edicts = entnum + 1;

        ent = &g_edicts[entnum];
        read_fields( f, entityfields, ent );
        ent->inuse = qtrue;
        ent->s.number = entnum;

        // let the server rebuild world links for this ent
        memset (&ent->area, 0, sizeof(ent->area));
        gi.linkentity (ent);
    }

    fclose (f);

    // mark all clients as unconnected
    for (i=0 ; i<maxclients->value ; i++)
    {
        ent = &g_edicts[i+1];
        ent->client = game.clients + i;
        ent->client->pers.connected = qfalse;
    }

    // do any load time things at this point
    for (i=0 ; i<globals.num_edicts ; i++)
    {
        ent = &g_edicts[i];

        if (!ent->inuse)
            continue;

        // fire any cross-level triggers
        if (ent->classname)
            if (strcmp(ent->classname, "target_crosslevel_target") == 0)
                ent->nextthink = level.time + ent->delay;
    }
}
Ejemplo n.º 10
0
 oop read_oop() {
   oop o = code()->oop_at(read_int());
   assert(o == NULL || o->is_oop(), "oop only");
   return o;
 }
Ejemplo n.º 11
0
 Method* read_method() {
   Method* o = (Method*)(code()->metadata_at(read_int()));
   assert(o == NULL ||
          o->is_metadata(), "meta data only");
   return o;
 }
Ejemplo n.º 12
0
int main(int argc, char* argv[])
{

	// Print help if necessary
	bool help = read_bool(argc, argv, "--help", false);
	if ((argc < 2) || (help)) {
		usage(argv);
		return 0;
	}

	// Use parameters struct for passing parameters to kernels efficiently
	parameters prm;

	// Parse inputs
	prm.matDims[0] = read_int(argc, argv, "--m", 2);
	prm.matDims[1] = read_int(argc, argv, "--k", 2);
	prm.matDims[2] = read_int(argc, argv, "--n", 2);
	prm.rank = read_int(argc, argv, "--rank", 7);
	prm.method = read_string(argc, argv, "--method", (char *)"als");
	int maxIters = read_int(argc, argv, "--maxiters", 1000);
	int maxSecs = read_int(argc, argv, "--maxsecs", 1000);
	double tol = read_double(argc, argv, "--tol", 1e-8);
	int printItn = read_int(argc, argv, "--printitn", 0);
	double printTol = read_double(argc, argv, "--printtol", 1.0);
	int seed = read_int(argc, argv, "--seed", 0);
	int numSeeds = read_int(argc, argv, "--numseeds", 1);
	bool verbose = read_bool(argc, argv, "--verbose", false);
	prm.rnd_maxVal = read_double(argc,argv,"--maxval",1.0);
	prm.rnd_pwrOfTwo = read_int(argc,argv,"--pwrof2",0);
	bool roundFinal = read_bool(argc, argv, "--rndfin",false);
	prm.alpha = read_double(argc,argv, "--alpha", 0.1);
	int M = read_int(argc,argv, "--M", 0);
	if (M)
	{
		prm.M[0] = M;
		prm.M[1] = M;
		prm.M[2] = M;
	} else {	    
		prm.M[0] = read_int(argc, argv, "--M0", -1);
		prm.M[1] = read_int(argc, argv, "--M1", -1);
		prm.M[2] = read_int(argc, argv, "--M2", -1);
	}
	char * infile = read_string(argc, argv, "--input", NULL);
	char * outfile = read_string(argc, argv, "--output", NULL);

	if (verbose) {
		setbuf(stdout, NULL);
		printf("\n\n---------------------------------------------------------\n");
		printf("PARAMETERS\n");
		printf("dimensions = %d %d %d\n",prm.matDims[0],prm.matDims[1],prm.matDims[2]);
		printf("rank       = %d\n",prm.rank);
		printf("method     = %s\n",prm.method);
		if (infile)
			printf("input      = %s\n",infile);
		else
		{
			if (numSeeds == 1)
				printf("input      = seed %d\n",seed); 
			else
				printf("inputs     = seeds %d-%d\n",seed,seed+numSeeds-1);
		}
		if (outfile)
			printf("output     = %s\n",outfile);
		else
			printf("output     = none\n"); 
		if (!strcmp(prm.method,"als"))
		{
			printf("tol        = %1.2e\n",tol);
			printf("alpha      = %1.2e\n",prm.alpha);
			printf("maval      = %1.2e\n",prm.rnd_maxVal);
			printf("M's        = (%d,%d,%d)\n",prm.M[0],prm.M[1],prm.M[2]);
			printf("maxiters   = %d\n",maxIters);
			printf("maxsecs    = %d\n",maxSecs);
			printf("printitn   = %d\n",printItn);
			printf("printtol   = %1.2e\n",printTol);
		}
		printf("---------------------------------------------------------\n");
	}

	// Initialize other variables
	int i, j, k, numIters, mkn, tidx[3];
	double err, errOld, errChange = 0.0, start_als, start_search, elapsed, threshold;

	// Compute tensor dimensions
	prm.dims[0] = prm.matDims[0]*prm.matDims[1];
	prm.dims[1] = prm.matDims[1]*prm.matDims[2];
	prm.dims[2] = prm.matDims[0]*prm.matDims[2];

	// Compute tensor's nnz, total number of entries, and Frobenius norm
	mkn = prm.matDims[0]*prm.matDims[1]*prm.matDims[2];
	prm.mkn2 = mkn*mkn;
	prm.xNorm = sqrt(mkn);

	// Compute number of columns in matricized tensors
	for (i = 0; i < 3; i++)
		prm.mtCols[i] = prm.mkn2 / prm.dims[i];

	// Construct three matricizations of matmul tensor
	prm.X = (double**) malloc( 3 * sizeof(double*) );
	for (i = 0; i < 3; i++)
		prm.X[i] = (double*) calloc( prm.mkn2, sizeof(double) );
	for (int mm = 0; mm < prm.matDims[0]; mm++)
		for (int kk = 0; kk < prm.matDims[1]; kk++)
			for (int nn = 0; nn < prm.matDims[2]; nn++)
			{
				tidx[0] = mm + kk*prm.matDims[0];
				tidx[1] = kk + nn*prm.matDims[1];
				tidx[2] = mm + nn*prm.matDims[0];
				prm.X[0][tidx[0]+prm.dims[0]*(tidx[1]+prm.dims[1]*tidx[2])] = 1;
				prm.X[1][tidx[1]+prm.dims[1]*(tidx[0]+prm.dims[0]*tidx[2])] = 1;
				prm.X[2][tidx[2]+prm.dims[2]*(tidx[0]+prm.dims[0]*tidx[1])] = 1;
			}

	// Allocate factor weights and matrices: working, initial, and model
	prm.lambda = (double*) malloc( prm.rank * sizeof(double) );
	prm.U  = (double**) malloc( 3 * sizeof(double*) );
	double** U0 = (double**) malloc( 3 * sizeof(double*) );
	prm.model = (double**) malloc( 3 * sizeof(double*) );
	for (i = 0; i < 3; i++)
	{
		prm.U[i] =  (double*) calloc( prm.mkn2, sizeof(double) );
		U0[i] = (double*) calloc( prm.dims[i]*prm.rank, sizeof(double) );
		prm.model[i] = (double*) calloc( prm.dims[i]*prm.rank, sizeof(double) );
	}

	// Allocate coefficient matrix within ALS (Khatri-Rao product) 
	int maxMatDim = prm.matDims[0];
	if (maxMatDim < prm.matDims[1]) maxMatDim = prm.matDims[1];
	if (maxMatDim < prm.matDims[2]) maxMatDim = prm.matDims[2];
	prm.A = (double*) malloc( maxMatDim*mkn*prm.rank * sizeof(double) );

	// Allocate workspaces
	prm.tau = (double*) malloc( mkn * sizeof(double) );
	prm.lwork = maxMatDim*mkn*prm.rank;
	prm.work = (double*) malloc( prm.lwork * sizeof(double) );
	prm.iwork = (int*) malloc( prm.mkn2 * sizeof(int) );    

	// Allocate matrices for normal equations 
	int maxDim = prm.dims[0];
	if (maxDim < prm.dims[1]) maxDim = prm.dims[1];
	if (maxDim < prm.dims[2]) maxDim = prm.dims[2];
	prm.NE_coeff = (double*) malloc( prm.rank*prm.rank * sizeof(double) );
	prm.NE_rhs = (double*) malloc( maxDim*prm.rank * sizeof(double) );
	prm.residual = (double*) malloc( prm.mkn2 * sizeof(double) );

	//--------------------------------------------------
	// Search Loop
	//--------------------------------------------------
	int mySeed = seed, numGoodSeeds = 0, statusCnt = 0, status = 1;
	start_search = wall_time(); 
	for (int seed_cnt = 0; seed_cnt < numSeeds; ++seed_cnt)
	{
		// Set starting point from random seed (match Matlab Tensor Toolbox)
		RandomMT cRMT(mySeed);
		for (i = 0; i < 3; i++)
			for (j = 0; j < prm.dims[i]; j++)
				for (k = 0; k < prm.rank; k++)
					U0[i][j+k*prm.dims[i]] = cRMT.genMatlabMT();
		for (i = 0; i < prm.rank; i++)
			prm.lambda[i] = 1.0;  

		// Copy starting point
		for (i = 0; i < 3; i++)
			cblas_dcopy(prm.dims[i]*prm.rank,U0[i],1,prm.U[i],1); 

		// read from file if input is given    
		if( infile )
			read_input( infile, prm ); 

		if (verbose)
		{ 
			printf("\nSTARTING POINT...\n");
			for (i = 0; i < 3; i++)
			{
				printf("Factor matrix %d:\n",i);
				print_matrix(prm.U[i],prm.dims[i],prm.rank,prm.dims[i]);
			}
			printf("\n");
		}   

		//--------------------------------------------------
		// Main ALS Loop
		//--------------------------------------------------
		start_als = wall_time();
		err = 1.0; 
		threshold = 1e-4;
		for (numIters = 0; numIters < maxIters && (wall_time()-start_als) < maxSecs; numIters++)
		{
			errOld = err;

			if (!strcmp(prm.method,"als"))
			{
				// Perform an iteration of ALS using NE with Smirnov's penalty term
				err = als( prm );
			}
			else if (!strcmp(prm.method,"sparsify"))
			{   
				// print stats before sparsifying
				printf("Old residual: %1.2e\n",compute_residual(prm,2,true));
				printf("Old nnz (larger than %1.1e): %d %d %d\n", threshold, nnz(prm.U[0],prm.dims[0]*prm.rank,threshold), nnz(prm.U[1],prm.dims[1]*prm.rank,threshold), nnz(prm.U[2],prm.dims[2]*prm.rank,threshold) );

				// sparsify and return
				printf("\nSparsifying...\n\n");
				sparsify( prm );
				numIters = maxIters;

				// print stats after sparsifying
				printf("New residual: %1.2e\n",compute_residual(prm,2,true));
				printf("New nnz (larger than %1.1e): %d %d %d\n", threshold, nnz(prm.U[0],prm.dims[0]*prm.rank,threshold), nnz(prm.U[1],prm.dims[1]*prm.rank,threshold), nnz(prm.U[2],prm.dims[2]*prm.rank,threshold) );
			}
			else if (!strcmp(prm.method,"round"))
			{
				// print stats before rounding
				printf("Old residual: %1.2e\n",compute_residual(prm,2,true));
				printf("Old nnz (larger than %1.1e): %d %d %d\n", threshold, nnz(prm.U[0],prm.dims[0]*prm.rank,threshold), nnz(prm.U[1],prm.dims[1]*prm.rank,threshold), nnz(prm.U[2],prm.dims[2]*prm.rank,threshold) );
				// round and return
				for (i = 0; i < 3; i++)
				{
					capping(prm.U[i],prm.dims[i]*prm.rank,prm.rnd_maxVal);
					rounding(prm.U[i],prm.dims[i]*prm.rank,prm.rnd_pwrOfTwo);
				}
				numIters = maxIters;

				// print stats after rounding
				printf("New residual: %1.2e\n",compute_residual(prm,2,true));
				printf("New nnz (larger than %1.1e): %d %d %d\n", threshold, nnz(prm.U[0],prm.dims[0]*prm.rank,threshold), nnz(prm.U[1],prm.dims[1]*prm.rank,threshold), nnz(prm.U[2],prm.dims[2]*prm.rank,threshold) );
			}
			else
				die("Invalid method\n");   

			// Compute change in relative residual norm
			errChange = fabs(err - errOld);          

			// Print info at current iteration
			if ((printItn > 0) && (((numIters + 1) % printItn) == 0))
			{                
				// print info                    
				printf ("Iter %d: residual = %1.5e change = %1.5e\n", numIters + 1, err, errChange);
			} 

			// Check for convergence 
			if ( numIters > 0 && errChange < tol )
				break;

		}

		// If rounding, round final solution and re-compute residual
		if(roundFinal)
		{
			// normalize columns in A and B factors, put arbitrary weights into C
			normalize_model( prm, 2 );

			// cap large values and round to nearest power of 2
			for (i = 0; i < 3; i++)
			{
				capping(prm.U[i],prm.dims[i]*prm.rank,prm.rnd_maxVal);
				rounding(prm.U[i],prm.dims[i]*prm.rank,prm.rnd_pwrOfTwo);
			}

			err = compute_residual(prm,0,true);
		}    

		// Print status if searching over many seeds
		statusCnt++;
		if (numSeeds > 1000 && statusCnt == numSeeds/10)
		{
			printf("...%d%% complete...\n",10*status);
			status++;
			statusCnt = 0;
		}

		// Print final info
		elapsed = wall_time() - start_als;
		if ((printItn > 0 || verbose) && !strcmp(prm.method,"als"))
		{
			if (infile)
				printf("\nInput %s ",infile);
			else
				printf("\nInitial seed %d ",mySeed);
			printf("achieved residual %1.3e in %d iterations and %1.3e seconds\n \t final residual change: %1.3e\n \t average time per iteration: %1.3e s\n", err, numIters, elapsed, errChange, elapsed/numIters);
		}

		if (verbose)
		{
			printf("\nSOLUTION...\n");
			for (i = 0; i < 3; i++)
			{
				printf("Factor matrix %d:\n",i);
				if (roundFinal || !strcmp(prm.method,"round"))
					print_int_matrix(prm.U[i], prm.dims[i], prm.rank, prm.dims[i], prm.rnd_pwrOfTwo);
				else
					print_matrix(prm.U[i],prm.dims[i],prm.rank,prm.dims[i]);
			}
			
			if (err < printTol)
				numGoodSeeds++;
		}
		else if (err < printTol)
		{
			numGoodSeeds++;

			printf("\n\n***************************************\n");
			if (infile)
				printf("Input %s: ",infile);
			else
				printf("Initial seed %d: ",mySeed);
			printf("after %d iterations, achieved residual %1.3e with final residual change of %1.3e\n", numIters, err, errChange);
			if (roundFinal)
			{

				for (i = 0; i < 3; i++)
				{
					printf("Factor matrix %d:\n",i);
					print_int_matrix(prm.U[i], prm.dims[i], prm.rank, prm.dims[i], prm.rnd_pwrOfTwo);
				}

				int count = 0;
				for (i = 0; i < 3; i++)
					count += nnz(prm.U[i],prm.dims[i]*prm.rank);
				printf("\ttotal nnz in solution: %d\n",count);
				printf("\tnaive adds/subs:       %d\n",count - prm.dims[2] - 2*prm.rank);
			}
			printf("***************************************\n\n\n");
		}

		// write to output
		if( outfile )
			write_output( outfile, prm ); 

		mySeed++;
	}      

	// Final report of processor statistics
	elapsed = wall_time()-start_search;

	// Print stats
	if (!strcmp(prm.method,"als"))
	{
		printf("\n\n------------------------------------------------------------\n");
		printf("Time elapsed:                \t%1.1e\tseconds\n",elapsed);
		printf("Total number of seeds tried: \t%d\n",numSeeds);
		printf("Total number of good seeds:  \t%d",numGoodSeeds);
		printf("\t(residual < %2.1e)\n",printTol);   
		printf("------------------------------------------------------------\n");
	}


	// free allocated memory
	for (i = 0; i < 3; i++)
	{
		free( prm.X[i] );
		free( prm.U[i] );
		free( U0[i] );
		free( prm.model[i] );
	} 
	free( prm.X );
	free( prm.U );
	free( U0 );
	free( prm.model );
	free( prm.lambda );
	free( prm.A );
	free( prm.NE_coeff );
	free( prm.NE_rhs );
	free( prm.residual );
	free( prm.tau );
	free( prm.work );
	free( prm.iwork );

	return 0;

}
Ejemplo n.º 13
0
__parse_one_specmb (const UCHAR_T *format, size_t posn,
		    struct printf_spec *spec, size_t *max_ref_arg)
#endif
{
  unsigned int n;
  size_t nargs = 0;

  /* Skip the '%'.  */
  ++format;

  /* Clear information structure.  */
  spec->data_arg = -1;
  spec->info.alt = 0;
  spec->info.space = 0;
  spec->info.left = 0;
  spec->info.showsign = 0;
  spec->info.group = 0;
  spec->info.i18n = 0;
  spec->info.extra = 0;
  spec->info.pad = ' ';
  spec->info.wide = sizeof (UCHAR_T) > 1;

  /* Test for positional argument.  */
  if (ISDIGIT (*format))
    {
      const UCHAR_T *begin = format;

      n = read_int (&format);

      if (n != 0 && *format == L_('$'))
	/* Is positional parameter.  */
	{
	  ++format;		/* Skip the '$'.  */
	  if (n != -1)
	    {
	      spec->data_arg = n - 1;
	      *max_ref_arg = MAX (*max_ref_arg, n);
	    }
	}
      else
	/* Oops; that was actually the width and/or 0 padding flag.
	   Step back and read it again.  */
	format = begin;
    }

  /* Check for spec modifiers.  */
  do
    {
      switch (*format)
	{
	case L_(' '):
	  /* Output a space in place of a sign, when there is no sign.  */
	  spec->info.space = 1;
	  continue;
	case L_('+'):
	  /* Always output + or - for numbers.  */
	  spec->info.showsign = 1;
	  continue;
	case L_('-'):
	  /* Left-justify things.  */
	  spec->info.left = 1;
	  continue;
	case L_('#'):
	  /* Use the "alternate form":
	     Hex has 0x or 0X, FP always has a decimal point.  */
	  spec->info.alt = 1;
	  continue;
	case L_('0'):
	  /* Pad with 0s.  */
	  spec->info.pad = '0';
	  continue;
	case L_('\''):
	  /* Show grouping in numbers if the locale information
	     indicates any.  */
	  spec->info.group = 1;
	  continue;
	case L_('I'):
	  /* Use the internationalized form of the output.  Currently
	     means to use the `outdigits' of the current locale.  */
	  spec->info.i18n = 1;
	  continue;
	default:
	  break;
	}
      break;
    }
  while (*++format);

  if (spec->info.left)
    spec->info.pad = ' ';

  /* Get the field width.  */
  spec->width_arg = -1;
  spec->info.width = 0;
  if (*format == L_('*'))
    {
      /* The field width is given in an argument.
	 A negative field width indicates left justification.  */
      const UCHAR_T *begin = ++format;

      if (ISDIGIT (*format))
	{
	  /* The width argument might be found in a positional parameter.  */
	  n = read_int (&format);

	  if (n != 0 && *format == L_('$'))
	    {
	      if (n != -1)
		{
		  spec->width_arg = n - 1;
		  *max_ref_arg = MAX (*max_ref_arg, n);
		}
	      ++format;		/* Skip '$'.  */
	    }
	}

      if (spec->width_arg < 0)
	{
	  /* Not in a positional parameter.  Consume one argument.  */
	  spec->width_arg = posn++;
	  ++nargs;
	  format = begin;	/* Step back and reread.  */
	}
    }
  else if (ISDIGIT (*format))
    {
      int n = read_int (&format);

      /* Constant width specification.  */
      if (n != -1)
	spec->info.width = n;
    }
  /* Get the precision.  */
  spec->prec_arg = -1;
  /* -1 means none given; 0 means explicit 0.  */
  spec->info.prec = -1;
  if (*format == L_('.'))
    {
      ++format;
      if (*format == L_('*'))
	{
	  /* The precision is given in an argument.  */
	  const UCHAR_T *begin = ++format;

	  if (ISDIGIT (*format))
	    {
	      n = read_int (&format);

	      if (n != 0 && *format == L_('$'))
		{
		  if (n != -1)
		    {
		      spec->prec_arg = n - 1;
		      *max_ref_arg = MAX (*max_ref_arg, n);
		    }
		  ++format;
		}
	    }

	  if (spec->prec_arg < 0)
	    {
	      /* Not in a positional parameter.  */
	      spec->prec_arg = posn++;
	      ++nargs;
	      format = begin;
	    }
	}
      else if (ISDIGIT (*format))
	{
	  int n = read_int (&format);

	  if (n != -1)
	    spec->info.prec = n;
	}
      else
	/* "%.?" is treated like "%.0?".  */
	spec->info.prec = 0;
    }

  /* Check for type modifiers.  */
  spec->info.is_long_double = 0;
  spec->info.is_short = 0;
  spec->info.is_long = 0;
  spec->info.is_char = 0;
  spec->info.user = 0;

  if (__builtin_expect (__printf_modifier_table == NULL, 1)
      || __printf_modifier_table[*format] == NULL
      || HANDLE_REGISTERED_MODIFIER (&format, &spec->info) != 0)
    switch (*format++)
      {
      case L_('h'):
	/* ints are short ints or chars.  */
	if (*format != L_('h'))
	  spec->info.is_short = 1;
	else
	  {
	    ++format;
	    spec->info.is_char = 1;
	  }
	break;
      case L_('l'):
	/* ints are long ints.  */
	spec->info.is_long = 1;
	if (*format != L_('l'))
	  break;
	++format;
	/* FALLTHROUGH */
      case L_('L'):
	/* doubles are long doubles, and ints are long long ints.  */
      case L_('q'):
	/* 4.4 uses this for long long.  */
	spec->info.is_long_double = 1;
	break;
      case L_('z'):
      case L_('Z'):
	/* ints are size_ts.  */
	assert (sizeof (size_t) <= sizeof (unsigned long long int));
#if LONG_MAX != LONG_LONG_MAX
	spec->info.is_long_double = (sizeof (size_t)
				     > sizeof (unsigned long int));
#endif
	spec->info.is_long = sizeof (size_t) > sizeof (unsigned int);
	break;
      case L_('t'):
	assert (sizeof (ptrdiff_t) <= sizeof (long long int));
#if LONG_MAX != LONG_LONG_MAX
	spec->info.is_long_double = (sizeof (ptrdiff_t) > sizeof (long int));
#endif
	spec->info.is_long = sizeof (ptrdiff_t) > sizeof (int);
	break;
      case L_('j'):
	assert (sizeof (uintmax_t) <= sizeof (unsigned long long int));
#if LONG_MAX != LONG_LONG_MAX
	spec->info.is_long_double = (sizeof (uintmax_t)
				     > sizeof (unsigned long int));
#endif
	spec->info.is_long = sizeof (uintmax_t) > sizeof (unsigned int);
	break;
      default:
	/* Not a recognized modifier.  Backup.  */
	--format;
	break;
      }

  /* Get the format specification.  */
  spec->info.spec = (wchar_t) *format++;
  spec->size = -1;
  if (__builtin_expect (__printf_function_table == NULL, 1)
      || spec->info.spec > UCHAR_MAX
      || __printf_arginfo_table[spec->info.spec] == NULL
      /* We don't try to get the types for all arguments if the format
	 uses more than one.  The normal case is covered though.  If
	 the call returns -1 we continue with the normal specifiers.  */
      || (int) (spec->ndata_args = (*__printf_arginfo_table[spec->info.spec])
				   (&spec->info, 1, &spec->data_arg_type,
				    &spec->size)) < 0)
    {
      /* Find the data argument types of a built-in spec.  */
      spec->ndata_args = 1;

      switch (spec->info.spec)
	{
	case L'i':
	case L'd':
	case L'u':
	case L'o':
	case L'X':
	case L'x':
#if LONG_MAX != LONG_LONG_MAX
	  if (spec->info.is_long_double)
	    spec->data_arg_type = PA_INT|PA_FLAG_LONG_LONG;
	  else
#endif
	    if (spec->info.is_long)
	      spec->data_arg_type = PA_INT|PA_FLAG_LONG;
	    else if (spec->info.is_short)
	      spec->data_arg_type = PA_INT|PA_FLAG_SHORT;
	    else if (spec->info.is_char)
	      spec->data_arg_type = PA_CHAR;
	    else
	      spec->data_arg_type = PA_INT;
	  break;
	case L'e':
	case L'E':
	case L'f':
	case L'F':
	case L'g':
	case L'G':
	case L'a':
	case L'A':
	  if (spec->info.is_long_double)
	    spec->data_arg_type = PA_DOUBLE|PA_FLAG_LONG_DOUBLE;
	  else
	    spec->data_arg_type = PA_DOUBLE;
	  break;
	case L'c':
	  spec->data_arg_type = PA_CHAR;
	  break;
	case L'C':
	  spec->data_arg_type = PA_WCHAR;
	  break;
	case L's':
	  spec->data_arg_type = PA_STRING;
	  break;
	case L'S':
	  spec->data_arg_type = PA_WSTRING;
	  break;
	case L'p':
	  spec->data_arg_type = PA_POINTER;
	  break;
	case L'n':
	  spec->data_arg_type = PA_INT|PA_FLAG_PTR;
	  break;

	case L'm':
	default:
	  /* An unknown spec will consume no args.  */
	  spec->ndata_args = 0;
	  break;
	}
    }

  if (spec->data_arg == -1 && spec->ndata_args > 0)
    {
      /* There are args consumed, but no positional spec.  Use the
	 next sequential arg position.  */
      spec->data_arg = posn;
      nargs += spec->ndata_args;
    }

  if (spec->info.spec == L'\0')
    /* Format ended before this spec was complete.  */
    spec->end_of_fmt = spec->next_fmt = format - 1;
  else
    {
      /* Find the next format spec.  */
      spec->end_of_fmt = format;
#ifdef COMPILE_WPRINTF
      spec->next_fmt = __find_specwc (format);
#else
      spec->next_fmt = __find_specmb (format);
#endif
    }

  return nargs;
}
Ejemplo n.º 14
0
static void checksums_readfile() {
	CHECKSUMDATA *last;
	FILE *f;
	int bad_cache, ch;
	const char	*version;
	BUFFER buff;
	long buffsize;

	if ( checksumsfileread ) {
		return;
	}

	checksumsfileread = 1;

	checksumhash = hashinit( sizeof( CHECKSUMDATA ), "checksums" );

	if ( !( f = fopen( checksums_filename(), "rb" ) ) )
		return;

	fseek( f, 0, SEEK_END );
	buffsize = ftell( f );
	fseek( f, 0, SEEK_SET );
	buffer_init( &buff );
	buffer_resize( &buff, buffsize + 1 );
	if ( fread( buffer_ptr( &buff ), buffsize, 1, f ) != 1 )
	{
		fclose( f );
		goto bail;
	}
	buffer_ptr( &buff )[buffsize] = 0;
	fclose( f );

	version = read_string( &buff );
	ch = buffer_getchar( &buff );
	if ( !version  ||  strcmp( version, CHECKSUM_FILE_VERSION ) || ch != '\n' ) {
		goto bail;
	}

	last = 0;
	bad_cache = 1;

	for (;;) {
		CHECKSUMDATA	checksumdata, *c = &checksumdata;
		int ch;

		c->boundname = read_string( &buff );
		if ( !c->boundname ) { /* Test for eof */
			break;
		}

		c->age = read_int( &buff ) + 1; /* we're getting older... */

		c->mtime = read_int( &buff );
		read_md5sum( &buff, c->contentmd5sum );
		c->contentmd5sum_changed = 0;
		c->contentmd5sum_calculated = 0;

		/* Read the newline */
		ch = skip_spaces( &buff );
		if ( ch != '!' ) {
			goto bail;
		}
		ch = skip_spaces( &buff );
		if ( ch != '\n' ) {
			goto bail;
		}

		if ( !hashcheck( checksumhash, (HASHDATA **) &c ) ) {
			if ( !hashenter( checksumhash, (HASHDATA **)&c ) ) {
				printf( "jam: can't insert checksum cache item, bailing...\n" );
				goto bail;
			}
		}

		c->next = 0;
		if ( last ) {
			last->next = c;
		} else {
			checksumdatalist = c;
		}
		last = c;
	}

	bad_cache = 0;

	if ( DEBUG_HEADER ) {
		printf( "checksums read from file %s\n", checksums_filename() );
	}

bail:
	/* If its bad, no worries, it'll be overwritten in hcache_done() */
	if ( bad_cache )
		printf( "jam: warning: the checksum cache was invalid: %s\n", checksums_filename() );
	buffer_free( &buff );
}
Ejemplo n.º 15
0
/*
 * Actually read the savefile
 *
 */
static errr rd_savefile_new_aux(player_type *p_ptr)
{
	int i;

	u16b tmp16u;
	u32b tmp32u;
	bool clear = FALSE;
	bool had_header = FALSE;
	char stat_order_hack[6];

	start_section_read("mangband_player_save");
	start_section_read("version");
	read_int("major"); 
	read_int("minor");
	read_int("patch");
	end_section_read("version");
	
	if (section_exists("header")) 
	{
		start_section_read("header");
		had_header = TRUE;

		read_str("playername",p_ptr->name); /* 32 */

		skip_value("pass");

		p_ptr->prace = read_int("prace");
		p_ptr->pclass = read_int("pclass");
		p_ptr->male = read_int("male");

		read_binary("stat_order", stat_order_hack, 6);
		for (i = 0; i < 6; i++)
			p_ptr->stat_order[i] = stat_order_hack[i];

		end_section_read("header");
	}

	/* Operating system info */
	sf_xtra = read_uint("sf_xtra");

	/* Time of savefile creation */
	sf_when = read_uint("sf_when");

	/* Number of resurrections */
	sf_lives = read_int("sf_lives");

	/* Number of times played */
	sf_saves = read_int("sf_saves");

	/* Skip the turn info - if present */
	skip_value("turn");
	
	/* Turn this character was born on */
	if(value_exists("birth_turn"))
		read_hturn("birth_turn", &p_ptr->birth_turn);
	else
		/* Disable character event logging if no birth turn */
		ht_clr(&p_ptr->birth_turn);

	/* Player turns (actually time spent playing) */
	if(value_exists("player_turn"))
		read_hturn("player_turn", &p_ptr->turn);
	else
		ht_clr(&p_ptr->turn);

	/* Read birth options */
	if (rd_birthoptions(p_ptr))
	{
		return (28);
	}

	/* Monster Memory */
	if (section_exists("monster_lore")) {
	start_section_read("monster_lore");
	tmp16u = read_int("max_r_idx");

	/* Incompatible save files */
	if (tmp16u > z_info->r_max)
	{
		note(format("Too many (%u) monster races!", tmp16u));
		return (21);
	}

	/* Read the available records */
	for (i = 0; i < tmp16u; i++)
	{
		/* Read the lore */
		rd_lore(p_ptr, i);
	}
	end_section_read("monster_lore");
	}
	
	/* Object Memory */
	start_section_read("object_memory");
	tmp16u = read_int("max_k_idx");

	/* Incompatible save files */
	if (tmp16u > z_info->k_max)
	{
		note(format("Too many (%u) object kinds!", tmp16u));
		return (22);
	}

	/* Read the object memory */
	for (i = 0; i < tmp16u; i++)
	{
		byte tmp8u;

		tmp8u = read_int("flags");

		p_ptr->obj_aware[i] = (tmp8u & 0x01) ? TRUE : FALSE;
		p_ptr->obj_tried[i] = (tmp8u & 0x02) ? TRUE : FALSE;
	}
	end_section_read("object_memory");

	/*if (arg_fiddle) note("Loaded Object Memory");*/

	/* Read the extra stuff */
	rd_extra(p_ptr, had_header);

	/*if (arg_fiddle) note("Loaded extra information");*/


	/* Read the player_hp array */
	start_section_read("hp");
	tmp16u = read_int("py_max_level");

	/* Read the player_hp array */
	for (i = 0; i < tmp16u; i++)
	{
		p_ptr->player_hp[i] = read_int("hp");
	}
	end_section_read("hp");


	/* Important -- Initialize the race/class */
	p_ptr->rp_ptr = &p_info[p_ptr->prace];
	p_ptr->cp_ptr = &c_info[p_ptr->pclass];
	

	/* Important -- Choose the magic info */
	p_ptr->mp_ptr = &c_info[p_ptr->pclass].spells;


	/* Read spell info */
	if (section_exists("spell_flags"))
	{
		start_section_read("spell_flags");
		for (i = 0; i < PY_MAX_SPELLS; i++)
		{
			p_ptr->spell_flags[i] = read_int("flag");
		}
		end_section_read("spell_flags");
	}
	else
	{
		/* Port spell flags from old format */
		u32b spell_learned1, spell_learned2;
		u32b spell_worked1, spell_worked2;
		u32b spell_forgotten1, spell_forgotten2;
		spell_learned1 = read_uint("spell_learned1");
		spell_learned2 = read_uint("spell_learned2");
		spell_worked1 = read_uint("spell_worked1");
		spell_worked2 = read_uint("spell_worked2");
		spell_forgotten1 = read_uint("spell_forgotten1");
		spell_forgotten2 = read_uint("spell_forgotten2");
		for (i = 0; i < PY_MAX_SPELLS; i++)
		{
			if ((i < 32) ?
				(spell_forgotten1 & (1L << i)) :
				(spell_forgotten2 & (1L << (i - 32))))
			{
				p_ptr->spell_flags[i] |= PY_SPELL_FORGOTTEN;
			} 
			if ((i < 32) ?
				(spell_learned1 & (1L << i)) :
				(spell_learned2 & (1L << (i - 32))))
			{
				p_ptr->spell_flags[i] |= PY_SPELL_LEARNED;
			}
			if ((i < 32) ?
				(spell_worked1 & (1L << i)) :
				(spell_worked2 & (1L << (i - 32))))
			{
				p_ptr->spell_flags[i] |= PY_SPELL_WORKED;
			}			
		}
	}

	start_section_read("spell_order");
	for (i = 0; i < PY_MAX_SPELLS; i++)
	{
		p_ptr->spell_order[i] = read_int("order");
	}
	end_section_read("spell_order");

	/* Read the inventory */
	if (rd_inventory(p_ptr))
	{
		/*note("Unable to read inventory");*/
		return (21);
	}

	/* Read hostility information if new enough */
	if (rd_hostilities(p_ptr))
	{
		return (22);
	}
	rd_cave_memory(p_ptr);
	
	/* read the wilderness map */
	start_section_read("wilderness");
	/* get the map size */
	tmp32u = read_int("max_wild");
		
	/* if too many map entries */
	if (tmp32u > MAX_WILD)
	{
		return 23;
	}
		
	/* read in the map */
	for (i = 0; i < tmp32u; i++)
	{
		p_ptr->wild_map[i] = read_int("wild_map");
	}
	end_section_read("wilderness");
	
	/* Read the character event history */
	if(section_exists("event_history"))
	{
		char buf[160];
		cptr msg;
		history_event evt;
		history_event *last = NULL;
		start_section_read("event_history");
		while(value_exists("hist"))
		{
			int depth, level;
			history_event *n_evt = NULL;
			read_str("hist", buf);
			if (sscanf(buf, "%02i:%02i:%02i   %4ift   %2i   ", &evt.days, &evt.hours, &evt.mins,
				&depth, &level) == 5)
			{
				msg = &buf[25];/* skip 25 characters ^ */
				evt.depth = depth / 50;
				evt.message = quark_add(msg);
			}
			/* Allocate */
			MAKE(n_evt, history_event);
			n_evt->days = evt.days; n_evt->hours = evt.hours; n_evt->mins = evt.mins;
			n_evt->depth = evt.depth; n_evt->level = level;
			n_evt->message = evt.message;
			/* Add to chain */
			if (!last)
			{
				p_ptr->charhist = n_evt;
				last = n_evt;
			}
			else
			{
				last->next = n_evt;
				last = n_evt;
			}
		}
		end_section_read("event_history");
	}

	/* Read the characters quest list */
	if(section_exists("quests"))
	{
		start_section_read("quests");
		tmp16u = read_int("max_q_idx");
		for(i = 0; i < MAX_Q_IDX; i++)
		{
			tmp16u = read_int("level");
			p_ptr->q_list[i].level = tmp16u;
		}
		end_section_read("quests");
	}

	/* Read the characters sold artifact list */
	if(section_exists("found_artifacts"))
	{
		start_section_read("found_artifacts");
		tmp16u = read_int("max_a_idx");
		tmp32u = tmp16u;
		/* If we have an unexpected number of arts, just reset our list
		 * of sold artifacts. It's not so important we want to break
		 * save file compatability for it. */
		if( tmp16u != z_info->a_max )
		{
			clear = TRUE;
			tmp16u = 0;
		}
		for(i = 0; i < z_info->a_max; i++)
		{
			if(i < tmp32u)
			{
				if(!clear) tmp16u = read_int("a_info");
			}
			p_ptr->a_info[i] = tmp16u;
		}
		end_section_read("found_artifacts");
	}

	/* Hack -- no ghosts */
	/* r_info[z_info->r_max - 1].max_num = 0; */

  end_section_read("mangband_player_save");
  
	/* Success */
	return (0);
}
Ejemplo n.º 16
0
//
//  benchmarking program
//
int main( int argc, char **argv )
{    
    //
    //  process command line
    //
    if( find_option( argc, argv, "-h" ) >= 0 )
    {
        printf( "Options:\n" );
        printf( "-h to see this help\n" );
        printf( "-n <int> to set the number of particles\n" );
        printf( "-p <int> to set the number of threads\n" );
        printf( "-o <filename> to specify the output file name\n" );
        return 0;
    }
    
    n = read_int( argc, argv, "-n", 1000 );
    n_threads = read_int( argc, argv, "-p", 2 );
    char *savename = read_string( argc, argv, "-o", NULL );
    
    //
    //  allocate resources
    //
    fsave = savename ? fopen( savename, "w" ) : NULL;

    particles = (particle_t*) malloc( n * sizeof(particle_t) );
    set_size( n );
    init_particles( n, particles );

    pthread_attr_t attr;
    P( pthread_attr_init( &attr ) );
    P( pthread_barrier_init( &barrier, NULL, n_threads ) );

	// VIRAJ
	doBinning();
	// !VIRAJ

	// create threads
    int *thread_ids = (int *) malloc( n_threads * sizeof( int ) );
    for( int i = 0; i < n_threads; i++ ) 
        thread_ids[i] = i;

    pthread_t *threads = (pthread_t *) malloc( n_threads * sizeof( pthread_t ) );
    
    //
    //  do the parallel work
    //
    double simulation_time = read_timer( );
    for( int i = 1; i < n_threads; i++ ) 
        P( pthread_create( &threads[i], &attr, thread_routine, &thread_ids[i] ) );
    
    thread_routine( &thread_ids[0] );
    
    for( int i = 1; i < n_threads; i++ ) 
        P( pthread_join( threads[i], NULL ) );
    simulation_time = read_timer( ) - simulation_time;
    
    printf( "n = %d, n_threads = %d, simulation time = %g seconds\n", n, n_threads, simulation_time );
    
    //
    //  release resources
    //
    P( pthread_barrier_destroy( &barrier ) );
    P( pthread_attr_destroy( &attr ) );
    free( thread_ids );
    free( threads );
    free( particles );
    if( fsave )
        fclose( fsave );

    return 0;
}
Ejemplo n.º 17
0
errr rd_server_savefile()
{
        int i;

	errr err = 0;

	char savefile[1024];

	byte tmp8u;
        u16b tmp16u;
        u32b tmp32u;
	s32b tmp32s;
	int major;
	char name[80];

	/* Savefile name */
	path_build(savefile, 1024, ANGBAND_DIR_SAVE, "server");

	/* The server savefile is a binary file */
	file_handle = my_fopen(savefile, "r");
	line_counter = 0;

	start_section_read("mangband_server_save");
	start_section_read("version");
	major = read_int("major"); 
	major = read_int("minor");
	major = read_int("patch");
	end_section_read("version");

	/* Paranoia */
	if (!file_handle) return (-1);

        /* Clear the checksums */
        v_check = 0L;
        x_check = 0L;

        /* Operating system info */
		sf_xtra = read_uint("xtra");

        /* Time of savefile creation */
		sf_when = read_uint("timestamp");

        /* Number of lives */
		sf_lives = read_int("sf_lives");

        /* Number of times played */
		sf_saves = read_int("sf_saves");

        /* Monster Memory */
		start_section_read("monster_lore");

		tmp16u = read_int("max_r_idx");

        /* Incompatible save files */
        if (tmp16u > z_info->r_max)
        {
                note(format("Too many (%u) monster races!", tmp16u));
                return (21);
        }

        /* Read the available records */
        for (i = 0; i < tmp16u; i++)
        {
		monster_race *r_ptr;

                /* Read the lore */
               rd_u_lore(i);

		/* Access the monster race */
		r_ptr = &r_info[i];

        }

		end_section_read("monster_lore");
		
        /* Load the Artifacts */
		start_section_read("artifacts");
		tmp16u = read_int("max_a_idx");

        /* Incompatible save files */
        if (tmp16u > z_info->a_max)
        {
                note(format("Too many (%u) artifacts!", tmp16u));
                return (24);
        }

        /* Read the artifact flags */
        for (i = 0; i < tmp16u; i++)
        {
				tmp8u = read_int("artifact");
                a_info[i].cur_num = tmp8u;
        }
		end_section_read("artifacts");

	/* Read the stores */
	start_section_read("stores");
	tmp16u = read_int("max_stores");
	for (i = 0; i < tmp16u; i++)
	{
		if (rd_store(i)) return (22);
	}
	end_section_read("stores");

	/* Read party info if savefile is new enough */
		start_section_read("parties");
		tmp16u = read_int("max_parties");
		
		/* Incompatible save files */
		if (tmp16u > MAX_PARTIES)
		{
			note(format("Too many (%u) parties!", tmp16u));
			return (25);
		}

		/* Read the available records */
		for (i = 0; i < tmp16u; i++)
		{
			rd_party(i);
		}
		end_section_read("parties");

	/* XXX If new enough, read in the saved levels and monsters. */

		start_section_read("dungeon_levels");
		/* read the number of levels to be loaded */
		tmp32u = read_uint("num_levels");
		/* load the levels */
		for (i = 0; i < tmp32u; i++) rd_dungeon(FALSE, 0);
		/* load any special static levels */
		rd_dungeon_special();
		end_section_read("dungeon_levels");

		start_section_read("monsters");
		/* get the number of monsters to be loaded */
		tmp32u = read_int("max_monsters");
		if (tmp32u > MAX_M_IDX)
		{
			note(format("Too many (%u) monsters!", tmp16u));
			return (29);
		}
		/* load the monsters */
		for (i = 1; i < tmp32u; i++)
		{
			rd_monster(&m_list[m_pop()]);
		}
		end_section_read("monsters");

		/* Read object info */
		start_section_read("objects");
		tmp16u = read_int("max_objects");

		/* Incompatible save files */
		if (tmp16u > MAX_O_IDX)
		{
			note(format("Too many (%u) objects!", tmp16u));
			return (26);
		}

		/* Read the available records */
		for (i = 1; i < tmp16u; i++)
		{		
			rd_item(&o_list[i]);
		}

		/* Set the maximum object number */
		o_max = tmp16u;
		end_section_read("objects");

		/* Read holding info */
		/* Reacquire objects */
		for (i = 1; i < o_max; ++i)
		{
			object_type *o_ptr;
			monster_type *m_ptr;
	
			/* Get the object */
			o_ptr = &o_list[i];
	
			/* Ignore dungeon objects */
			if (!o_ptr->held_m_idx) continue;
	
			/* Verify monster index */
			if (o_ptr->held_m_idx > z_info->m_max)
			{
				note("Invalid monster index");
				return (-1);
			}
	
			/* Get the monster */
			m_ptr = &m_list[o_ptr->held_m_idx];
	
			/* Link the object to the pile */
			o_ptr->next_o_idx = m_ptr->hold_o_idx;
	
			/* Link the monster to the object */
			m_ptr->hold_o_idx = i;
		}
	
		/* Read house info */
		start_section_read("houses");
		tmp16u = read_int("num_houses");

		/* Incompatible save files */
		if (tmp16u > MAX_HOUSES)
		{
			note(format("Too many (%u) houses!", tmp16u));
			return (27);
		}

		/* Read the available records */
		for (i = 0; i < tmp16u; i++)
		{
			rd_house(i);
		}
		num_houses = tmp16u;
		end_section_read("houses");

		/* Read arenas info */
		if (section_exists("arenas")) 
		{
			start_section_read("arenas");
			tmp16u = read_int("num_arenas");
	
			/* Incompatible save files */
			if (tmp16u > MAX_ARENAS)
			{
				note(format("Too many (%u) arenas!", tmp16u));
				return (27);
			}
	
			/* Read the available records */
			for (i = 0; i < tmp16u; i++)
			{
				rd_arena(i);
			}
			num_arenas = tmp16u;
			end_section_read("arenas");
		}

		/* Read wilderness info */
		start_section_read("wilderness");
		/* read how many wilderness levels */
		tmp32u = read_int("max_wild");
				
		if (tmp32u > MAX_WILD)
		{
			note("Too many wilderness levels");
			return 28;
		}
	
		for (i = 1; i < tmp32u; i++)
		{
			rd_wild(i);
		}	
		end_section_read("wilderness");

		/* Read the player name database  */
		start_section_read("player_names");

		tmp32u = read_int("num_players");

		/* Read the available records */
		for (i = 0; i < tmp32u; i++)
		{
			start_section_read("player");
			/* Read the ID */
			tmp32s = read_int("id");

			/* Read the player name */
			read_str("name",name);

			/* Store the player name */
			add_player_name(name, tmp32s);
			end_section_read("player");
		}
		end_section_read("player_names");

	seed_flavor = read_uint("seed_flavor");
	seed_town = read_uint("seed_town");

	player_id = read_int("player_id");

	read_hturn("turn", &turn);

        /* Hack -- no ghosts */
        /*r_info[z_info->r_max - 1].max_num = 0;*/

	end_section_read("mangband_server_save");

	/* Check for errors */
	if (ferror(file_handle)) err = -1;

	/* Close the file */
	my_fclose(file_handle);

	/* Result */
	return (err);
}
Ejemplo n.º 18
0
int main(int argc, char **argv) {




	if (find_option(argc, argv, "-h") >= 0)
	{
		printf("Options:\n");
		printf("-h to see this help\n");
		printf("-n <int> to set the number of particles\n");
		printf("-o <filename> to specify the output file name\n");
		printf("-s <filename> to specify the summary output file name\n");
		return 0;
	}


	int n = read_int(argc, argv, "-n", 1000);

	char *savename = read_string(argc, argv, "-o", NULL);
	char *sumname = read_string(argc, argv, "-s", NULL);

	// For return values.
	cl_int ret;

	// OpenCL stuff.
	// Loading kernel files.
	FILE *kernelFile;
	char *kernelSource;
	size_t kernelSize;

	kernelFile = fopen("simulationKernel.cl", "r");

	if (!kernelFile) {
		fprintf(stderr, "No file named simulationKernel.cl was found\n");
		exit(-1);
	}
	kernelSource = (char*)malloc(MAX_SOURCE_SIZE);
	kernelSize = fread(kernelSource, 1, MAX_SOURCE_SIZE, kernelFile);
	fclose(kernelFile);

	// Getting platform and device information
	cl_platform_id platformId = NULL;
	cl_device_id deviceID = NULL;
	cl_uint retNumDevices;
	cl_uint retNumPlatforms;
	ret = clGetPlatformIDs(1, &platformId, &retNumPlatforms);
	// Different types of devices to pick from. At the moment picks the default opencl device.
	//CL_DEVICE_TYPE_GPU
	//CL_DEVICE_TYPE_ACCELERATOR
	//CL_DEVICE_TYPE_DEFAULT
	//CL_DEVICE_TYPE_CPU
	ret = clGetDeviceIDs(platformId, CL_DEVICE_TYPE_ACCELERATOR, 1, &deviceID, &retNumDevices);

	// Max workgroup size
	size_t max_available_local_wg_size;
	ret = clGetDeviceInfo(deviceID, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &max_available_local_wg_size, NULL);
	// Creating context.
	cl_context context = clCreateContext(NULL, 1, &deviceID, NULL, NULL, &ret);


	// Creating command queue
        cl_command_queue commandQueue = clCreateCommandQueueWithProperties (context, deviceID, 0, &ret);
	
	// Build program
	cl_program program = clCreateProgramWithSource(context, 1, (const char **)&kernelSource, (const size_t *)&kernelSize, &ret);
//	printf("program = ret %i \n", ret);
	ret = clBuildProgram(program, 1, &deviceID, NULL, NULL, NULL);
//	printf("clBuildProgram: ret %i \n", ret);
	
	// Create kernels
	cl_kernel forceKernel = clCreateKernel(program, "compute_forces_gpu", &ret);

	cl_kernel moveKernel = clCreateKernel(program, "move_gpu", &ret);

	cl_kernel binInitKernel = clCreateKernel(program, "bin_init_gpu", &ret);
	cl_kernel binKernel = clCreateKernel(program, "bin_gpu", &ret);

	FILE *fsave = savename ? fopen(savename, "w") : NULL;
	FILE *fsum = sumname ? fopen(sumname, "a") : NULL;
	particle_t *particles = (particle_t*)malloc(n * sizeof(particle_t));

	// GPU particle data structure
	cl_mem d_particles = clCreateBuffer(context, CL_MEM_READ_WRITE, n * sizeof(particle_t), NULL, &ret);

	// Set size
	set_size(n);

	init_particles(n, particles);

	double copy_time = read_timer();

	// Copy particles to device.
	ret = clEnqueueWriteBuffer(commandQueue, d_particles, CL_TRUE, 0, n * sizeof(particle_t), particles, 0, NULL, NULL);
	copy_time = read_timer() - copy_time;
	

	// Calculating thread and thread block counts.
	// sizes
	size_t globalItemSize;
	size_t localItemSize;
	// Global item size
	if (n <= NUM_THREADS) {
		globalItemSize = NUM_THREADS;
		localItemSize = 16;
	}
	else if (n % NUM_THREADS != 0) {
		globalItemSize = (n / NUM_THREADS + 1) * NUM_THREADS;
	}
	else {
		globalItemSize = n;
	}

	// Local item size
	localItemSize = globalItemSize / NUM_THREADS;	

	// Bins and bin sizes.
	// Because of uniform distribution we will know that bins size is amortized. Therefore I picked the value of 10.
	// There will never be 10 particles in one bin.
	int maxParticles = 10;
	
	// Calculating the number of bins.
	int numberOfBins = (int)ceil(size/(2*cutoff)) + 2;
	
	// Bins will only exist on the device.
	particle_t* bins;
	
	// How many particles are there in each bin - also only exists on the device.
	volatile int* binSizes;
	
	// Number of bins to be initialized.
	size_t clearAmt = numberOfBins*numberOfBins;
	
	// Allocate memory for bins on the device.
	cl_mem d_binSizes = clCreateBuffer(context, CL_MEM_READ_WRITE, numberOfBins * numberOfBins * sizeof(volatile int), NULL, &ret);
	cl_mem d_bins = clCreateBuffer(context, CL_MEM_READ_WRITE, numberOfBins * numberOfBins * maxParticles * sizeof(particle_t), NULL, &ret);
	
	// SETTING ARGUMENTS FOR THE KERNELS
	
	// Set arguments for the init / clear kernel
	ret = clSetKernelArg(binInitKernel, 0, sizeof(cl_mem), (void *)&d_binSizes);
	ret = clSetKernelArg(binInitKernel, 1, sizeof(int), &numberOfBins);

	// Set arguments for the binning kernel
	ret = clSetKernelArg(binKernel, 0, sizeof(cl_mem), (void *)&d_particles);
	ret = clSetKernelArg(binKernel, 1, sizeof(int), &n);
	ret = clSetKernelArg(binKernel, 2, sizeof(cl_mem), (void *)&d_bins);
	ret = clSetKernelArg(binKernel, 3, sizeof(cl_mem), (void *)&d_binSizes);
	ret = clSetKernelArg(binKernel, 4, sizeof(int), &numberOfBins);

	// Set arguments for force kernel.
	ret = clSetKernelArg(forceKernel, 0, sizeof(cl_mem), (void *)&d_particles);
	ret = clSetKernelArg(forceKernel, 1, sizeof(int), &n);
	ret = clSetKernelArg(forceKernel, 2, sizeof(cl_mem), (void *)&d_bins);
	ret = clSetKernelArg(forceKernel, 3, sizeof(cl_mem), (void *)&d_binSizes);
	ret = clSetKernelArg(forceKernel, 4, sizeof(int), &numberOfBins);


	// Set arguments for move kernel
	ret = clSetKernelArg(moveKernel, 0, sizeof(cl_mem), (void *)&d_particles);
	ret = clSetKernelArg(moveKernel, 1, sizeof(int), &n);
	ret = clSetKernelArg(moveKernel, 2, sizeof(double), &size);
	
	
	// Variable to check if kernel execution is done.
	cl_event kernelDone;
	
	
	double simulation_time = read_timer();
	int step = 0;
	for (step = 0; step < NSTEPS; step++) {


		// Execute bin initialization (clearing after first iteration)
		ret = clEnqueueNDRangeKernel(commandQueue, binInitKernel, 1, NULL, &clearAmt, NULL, 0, NULL, &kernelDone);
		ret = clWaitForEvents(1, &kernelDone);
		// Execute binning kernel
		ret = clEnqueueNDRangeKernel(commandQueue, binKernel, 1, NULL, &globalItemSize, &localItemSize, 0, NULL, &kernelDone);
//		ret = clEnqueueNDRangeKernel(commandQueue, binKernel, 1, NULL, &globalItemSize, &localItemSize, 0, NULL, &kernelDone);
		ret = clWaitForEvents(1, &kernelDone);	
		// Execute force kernel
		ret = clEnqueueNDRangeKernel(commandQueue, forceKernel, 1, NULL, &globalItemSize, &localItemSize, 0, NULL, &kernelDone);
		ret = clWaitForEvents(1, &kernelDone);
		// Execute move kernel
		ret = clEnqueueNDRangeKernel(commandQueue, moveKernel, 1, NULL, &globalItemSize, &localItemSize, 0, NULL, &kernelDone);
		ret = clWaitForEvents(1, &kernelDone);

		if (fsave && (step%SAVEFREQ) == 0) {
			// Copy the particles back to the CPU
			ret = clEnqueueReadBuffer(commandQueue, d_particles, CL_TRUE, 0, n * sizeof(particle_t), particles, 0, NULL, &kernelDone);
			ret = clWaitForEvents(1, &kernelDone);

			save(fsave, n, particles);
		}

	}
	simulation_time = read_timer() - simulation_time;
	printf("CPU-GPU copy time = %g seconds\n", copy_time);
	printf("n = %d, simulation time = %g seconds\n", n, simulation_time);

	if (fsum)
		fprintf(fsum, "%d %lf \n", n, simulation_time);

	if (fsum)
		fclose(fsum);
	free(particles);
	if (fsave)
		fclose(fsave);


	ret = clFlush(commandQueue);
	ret = clFinish(commandQueue);
	ret = clReleaseCommandQueue(commandQueue);
	ret = clReleaseKernel(forceKernel);
	ret = clReleaseKernel(moveKernel);
	ret = clReleaseProgram(program);
	ret = clReleaseMemObject(d_particles);
	ret = clReleaseContext(context);


	return 0;
}
Ejemplo n.º 19
0
static void rd_monster(monster_type *m_ptr)
{
	start_section_read("monster");

	/* Hack -- wipe */
	WIPE(m_ptr, monster_type);

	skip_value("name");

	/* Read the monster race */
	m_ptr->r_idx = read_int("r_idx");

	/* Read the other information */
	m_ptr->fy = read_int("fy");
	m_ptr->fx = read_int("fx");
	m_ptr->dun_depth = read_int("dun_depth");
	m_ptr->hp = read_int("hp");
	m_ptr->maxhp = read_int("maxhp");
	m_ptr->csleep = read_int("csleep");
	m_ptr->mspeed = read_int("mspeed");
	m_ptr->energy = read_uint("energy");
	m_ptr->stunned = read_int("stunned");
	m_ptr->confused = read_int("confused");
	m_ptr->monfear = read_int("afraid");

	end_section_read("monster");
}
Ejemplo n.º 20
0
void setup_protocol(int f_out,int f_in)
{
	if (am_sender)
		file_extra_cnt += PTR_EXTRA_CNT;
	else
		file_extra_cnt++;
	if (preserve_uid)
		uid_ndx = ++file_extra_cnt;
	if (preserve_gid)
		gid_ndx = ++file_extra_cnt;
	if (preserve_acls && !am_sender)
		acls_ndx = ++file_extra_cnt;
	if (preserve_xattrs)
		xattrs_ndx = ++file_extra_cnt;

	if (am_server)
		set_allow_inc_recurse();

	if (remote_protocol == 0) {
		if (am_server && !local_server)
			check_sub_protocol();
		if (!read_batch)
			write_int(f_out, protocol_version);
		remote_protocol = read_int(f_in);
		if (protocol_version > remote_protocol)
			protocol_version = remote_protocol;
	}
	if (read_batch && remote_protocol > protocol_version) {
		rprintf(FERROR, "The protocol version in the batch file is too new (%d > %d).\n",
			remote_protocol, protocol_version);
		exit_cleanup(RERR_PROTOCOL);
	}

	if (DEBUG_GTE(PROTO, 1)) {
		rprintf(FINFO, "(%s) Protocol versions: remote=%d, negotiated=%d\n",
			am_server? "Server" : "Client", remote_protocol, protocol_version);
	}
	if (remote_protocol < MIN_PROTOCOL_VERSION
	 || remote_protocol > MAX_PROTOCOL_VERSION) {
		rprintf(FERROR,"protocol version mismatch -- is your shell clean?\n");
		rprintf(FERROR,"(see the rsync man page for an explanation)\n");
		exit_cleanup(RERR_PROTOCOL);
	}
	if (remote_protocol < OLD_PROTOCOL_VERSION) {
		rprintf(FINFO,"%s is very old version of rsync, upgrade recommended.\n",
			am_server? "Client" : "Server");
	}
	if (protocol_version < MIN_PROTOCOL_VERSION) {
		rprintf(FERROR, "--protocol must be at least %d on the %s.\n",
			MIN_PROTOCOL_VERSION, am_server? "Server" : "Client");
		exit_cleanup(RERR_PROTOCOL);
	}
	if (protocol_version > PROTOCOL_VERSION) {
		rprintf(FERROR, "--protocol must be no more than %d on the %s.\n",
			PROTOCOL_VERSION, am_server? "Server" : "Client");
		exit_cleanup(RERR_PROTOCOL);
	}
	if (read_batch)
		check_batch_flags();

#ifndef SUPPORT_PREALLOCATION
	if (preallocate_files && !am_sender) {
		rprintf(FERROR, "preallocation is not supported on this %s\n",
			am_server ? "Server" : "Client");
		exit_cleanup(RERR_SYNTAX);
	}
#endif

	if (protocol_version < 30) {
		if (append_mode == 1)
			append_mode = 2;
		if (preserve_acls && !local_server) {
			rprintf(FERROR,
			    "--acls requires protocol 30 or higher"
			    " (negotiated %d).\n",
			    protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}
		if (preserve_xattrs && !local_server) {
			rprintf(FERROR,
			    "--xattrs requires protocol 30 or higher"
			    " (negotiated %d).\n",
			    protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}
	}

	if (delete_mode && !(delete_before+delete_during+delete_after)) {
		if (protocol_version < 30)
			delete_before = 1;
		else
			delete_during = 1;
	}

	if (protocol_version < 29) {
		if (fuzzy_basis) {
			rprintf(FERROR,
			    "--fuzzy requires protocol 29 or higher"
			    " (negotiated %d).\n",
			    protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}

		if (basis_dir_cnt && inplace) {
			rprintf(FERROR,
			    "%s with --inplace requires protocol 29 or higher"
			    " (negotiated %d).\n",
			    dest_option, protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}

		if (basis_dir_cnt > 1) {
			rprintf(FERROR,
			    "Using more than one %s option requires protocol"
			    " 29 or higher (negotiated %d).\n",
			    dest_option, protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}

		if (prune_empty_dirs) {
			rprintf(FERROR,
			    "--prune-empty-dirs requires protocol 29 or higher"
			    " (negotiated %d).\n",
			    protocol_version);
			exit_cleanup(RERR_PROTOCOL);
		}
	} else if (protocol_version >= 30) {
		if (am_server) {
			compat_flags = allow_inc_recurse ? CF_INC_RECURSE : 0;
#ifdef CAN_SET_SYMLINK_TIMES
			compat_flags |= CF_SYMLINK_TIMES;
#endif
#ifdef ICONV_OPTION
			compat_flags |= CF_SYMLINK_ICONV;
#endif
			if (local_server || strchr(client_info, 'f') != NULL)
				compat_flags |= CF_SAFE_FLIST;
			if (local_server || strchr(client_info, 'x') != NULL)
				compat_flags |= CF_AVOID_XATTR_OPTIM;
			write_byte(f_out, compat_flags);
		} else
			compat_flags = read_byte(f_in);
		/* The inc_recurse var MUST be set to 0 or 1. */
		inc_recurse = compat_flags & CF_INC_RECURSE ? 1 : 0;
		want_xattr_optim = protocol_version >= 31 && !(compat_flags & CF_AVOID_XATTR_OPTIM);
		if (am_sender) {
			receiver_symlink_times = am_server
			    ? strchr(client_info, 'L') != NULL
			    : !!(compat_flags & CF_SYMLINK_TIMES);
		}
#ifdef CAN_SET_SYMLINK_TIMES
		else
			receiver_symlink_times = 1;
#endif
#ifdef ICONV_OPTION
		sender_symlink_iconv = iconv_opt && (am_server
		    ? local_server || strchr(client_info, 's') != NULL
		    : !!(compat_flags & CF_SYMLINK_ICONV));
#endif
		if (inc_recurse && !allow_inc_recurse) {
			/* This should only be able to happen in a batch. */
			fprintf(stderr,
			    "Incompatible options specified for inc-recursive %s.\n",
			    read_batch ? "batch file" : "connection");
			exit_cleanup(RERR_SYNTAX);
		}
		use_safe_inc_flist = (compat_flags & CF_SAFE_FLIST) || protocol_version >= 31;
		need_messages_from_generator = 1;
#ifdef CAN_SET_SYMLINK_TIMES
	} else if (!am_sender) {
		receiver_symlink_times = 1;
#endif
	}

	if (need_unsorted_flist && (!am_sender || inc_recurse))
		unsort_ndx = ++file_extra_cnt;

	if (partial_dir && *partial_dir != '/' && (!am_server || local_server)) {
		int rflags = FILTRULE_NO_PREFIXES | FILTRULE_DIRECTORY;
		if (!am_sender || protocol_version >= 30)
			rflags |= FILTRULE_PERISHABLE;
		parse_filter_str(&filter_list, partial_dir, rule_template(rflags), 0);
	}


#ifdef ICONV_OPTION
	if (protect_args && files_from) {
		if (am_sender)
			filesfrom_convert = filesfrom_host && ic_send != (iconv_t)-1;
		else
			filesfrom_convert = !filesfrom_host && ic_recv != (iconv_t)-1;
	}
#endif

	if (am_server) {
		if (!checksum_seed)
			checksum_seed = time(NULL);
		write_int(f_out, checksum_seed);
	} else {
		checksum_seed = read_int(f_in);
	}
}
Ejemplo n.º 21
0
static bool rd_extra(player_type *p_ptr, bool had_header)
{
	int i = 0;

	start_section_read("player");

	if (!had_header)
	{
		read_str("playername",p_ptr->name); /* 32 */
		skip_value("pass");
	}

	read_str("died_from",p_ptr->died_from); /* 80 */

	read_str("died_from_list",p_ptr->died_from_list); /* 80 */
	p_ptr->died_from_depth = read_int("died_from_depth");

	start_section_read("history");
	for (i = 0; i < 4; i++)
	{
		read_str("history",p_ptr->history[i]); /* 60 */
	}
	if (value_exists("descrip"))
	read_str("descrip",p_ptr->descrip); /* 240?! */
	end_section_read("history");

	/* Class/Race/Gender/Party */
	if (!had_header)
	{
		p_ptr->prace = read_int("prace");
		p_ptr->pclass = read_int("pclass");
		p_ptr->male = read_int("male");
	}
	p_ptr->party = read_int("party");

	/* Special Race/Class info */
	p_ptr->hitdie = read_int("hitdie");
	p_ptr->expfact = read_int("expfact");

	/* Age/Height/Weight */
	p_ptr->age = read_int("age");
	p_ptr->ht = read_int("ht");
	p_ptr->wt = read_int("wt");

	/* Read the stat info */
	start_section_read("stats");
	for (i = 0; i < 6; i++) p_ptr->stat_max[i] = read_int("stat_max");
	for (i = 0; i < 6; i++) p_ptr->stat_cur[i] = read_int("stat_cur");
	end_section_read("stats");

	p_ptr->id = read_int("id");

	/* If he was created in the pre-ID days, give him one */
	if (!p_ptr->id)
		p_ptr->id = player_id++;

	p_ptr->au = read_int("au");

	p_ptr->max_exp = read_int("max_exp");
	p_ptr->exp = read_int("exp");
	p_ptr->exp_frac = read_int("exp_frac");

	p_ptr->lev = read_int("lev");

	p_ptr->mhp = read_int("mhp");
	p_ptr->chp = read_int("chp");
	p_ptr->chp_frac = read_int("chp_frac");

	p_ptr->msp = read_int("msp");
	p_ptr->csp = read_int("csp");
	p_ptr->csp_frac = read_int("csp_frac");

	if(value_exists("no_ghost"))
	{
		(void)read_int("no_ghost");
	}
	
	p_ptr->max_plv = read_int("max_plv");
	p_ptr->max_dlv = read_int("max_dlv");
	
	p_ptr->recall_depth = p_ptr->max_dlv;

	p_ptr->py = read_int("py");
	p_ptr->px = read_int("px");
	p_ptr->dun_depth = read_int("dun_depth");

	p_ptr->world_x = read_int("world_x");
	p_ptr->world_y = read_int("world_y");

	/* More info */
	
	p_ptr->ghost = read_int("ghost");
	p_ptr->sc = read_int("sc");
	p_ptr->fruit_bat = read_int("fruit_bat");

	/* Read the flags */
	p_ptr->lives = read_int("lives");

	/* hack */
	p_ptr->blind = read_int("blind");
	p_ptr->paralyzed = read_int("paralyzed");
	p_ptr->confused = read_int("confused");
	p_ptr->food = read_int("food");
	p_ptr->energy = read_uint("energy");
	p_ptr->fast = read_int("fast");
	p_ptr->slow = read_int("slow");
	p_ptr->afraid = read_int("afraid");
	p_ptr->cut = read_int("cut");
	p_ptr->stun = read_int("stun");
	p_ptr->poisoned = read_int("poisoned");
	p_ptr->image = read_int("image");
	p_ptr->protevil = read_int("protevil");
	p_ptr->invuln = read_int("invuln");
	p_ptr->hero = read_int("hero");
	p_ptr->shero = read_int("shero");
	p_ptr->shield = read_int("shield");
	p_ptr->blessed = read_int("blessed");
	p_ptr->tim_invis = read_int("tim_invis");
	p_ptr->word_recall = read_int("word_recall");
	p_ptr->see_infra = read_int("see_infra");
	p_ptr->tim_infra = read_int("tim_infra");
	
	p_ptr->oppose_fire = read_int("oppose_fire");
	p_ptr->oppose_cold = read_int("oppose_cold");
	p_ptr->oppose_acid = read_int("oppose_acid");
	p_ptr->oppose_elec = read_int("oppose_elec");
	p_ptr->oppose_pois = read_int("oppose_pois");

	p_ptr->confusing = read_int("confusing");
	p_ptr->searching = read_int("searching");
	p_ptr->maximize = read_int("maximize");
	p_ptr->preserve = read_int("preserve");

	/* Read the unique list info */
	start_section_read("uniques");
	for (i = 0; i < z_info->r_max; i++) p_ptr->r_killed[i] = read_int("unique");
	end_section_read("uniques");

	/* Special stuff */
	panic_save = read_int("panic_save");
	p_ptr->total_winner = read_int("total_winner");
	p_ptr->retire_timer = read_int("retire_timer");
	p_ptr->noscore = read_int("noscore");

	/* Read "death" */
	p_ptr->death = read_int("death");

	end_section_read("player");

	/* Success */
	return FALSE;
}
Ejemplo n.º 22
0
double read_num2(unsigned char *buf) {
  int words;
  unsigned char *limit;
  double i, result, denom;
  switch (buf[0]) {
  case S2_FIXNUM32:
    return (double)read_int32(buf, 1);
  case S2_FIXNUM64:
    return (double)read_int64(buf, 1);
  case S2_SYMBOL_ID:
    return (double)read_int(buf, 1);
  case S2_CHAR:
    return (double)read_uint32(buf, 1);
  case S2_SHORT_FLOAT:
    return (double)read_float(buf, 1);
  case S2_SINGLE_FLOAT:
    return (double)read_float(buf, 1);
  case S2_DOUBLE_FLOAT:
    return read_double(buf, 1);
  case S2_NEGATIVE_BIGNUM:
    result = 0;
    buf += 5;
    words = read_uint32(buf, -4) / 4;
    for(i=0 ; i < words; i++, buf = buf+4) {
      result -= exp2(i*32) * read_uint32(buf, 0);
    }
    return result;
  case S2_POSITIVE_BIGNUM:
    result = 0;
    buf += 5;
    words = read_uint32(buf, -4) / 4;
    for(i=0 ; i < words; i++, buf = buf+4) {
      result += exp2(i*32) * read_uint32(buf, 0);
    }
    return result;
  case S2_RATIONAL:
  case S2_COMPLEX:
  default:
    switch ((++buf)[0]) {
    case S2_FIXNUM32:
    case S2_FIXNUM64:
      result = (double)read_int(++buf, 0);
      buf += 4;
      break;
    case S2_NEGATIVE_BIGNUM:
      result = 0;
      buf += 5;
      limit = buf + read_uint(buf, -4);
      for(i=0 ; buf < limit; i++, buf = buf+4) {
	result -= exp2(i*32) - read_uint(buf, 0);
      }
      break;
    case S2_POSITIVE_BIGNUM:
    default:
      result = 0;
      buf += 5;
      limit = buf + read_uint(buf, -4);
      for(i=0 ; buf < limit; i++, buf = buf+4) {
	result += exp2(i*32) * read_uint(buf, 0);
      }
      break;
    }
    
    switch (buf[0]) {
    case S2_FIXNUM32: 
    case S2_FIXNUM64:
      return result / read_int(++buf, 0);
    case S2_NEGATIVE_BIGNUM:
      denom = 0;
      buf += 5;
      limit = buf + read_uint(buf, -4);
      for(i=0 ; buf < limit; i++, buf = buf+4) {
	denom -= exp2(i*32) * read_uint(buf, 0);
      }
      return result / denom;
    case S2_POSITIVE_BIGNUM:
    default:
      denom = 0;
      buf += 5;
      limit = buf + read_uint(buf, -4);
      for(i=0 ; buf < limit; i++, buf = buf+4) {
	denom += exp2(i*32) * read_uint(buf, 0);
      }
      return result / denom;
    }    
  }
}
Ejemplo n.º 23
0
/*
 * main() - loop forever, reading the hdaps values and
 *          parking/unparking as necessary
 */
int main (int argc, char** argv)
{
	struct utsname sysinfo;
	struct list *p = NULL;
	int c, park_now, protect_factor;
	int x = 0, y = 0, z = 0;
	int fd, i, ret, threshold = 15, adaptive = 0,
	pidfile = 0, parked = 0, forceadd = 0;
	double unow = 0, parked_utime = 0;

	struct option longopts[] =
	{
		{"device", required_argument, NULL, 'd'},
		{"sensitivity", required_argument, NULL, 's'},
		{"adaptive", no_argument, NULL, 'a'},
		{"verbose", no_argument, NULL, 'v'},
		{"background", no_argument, NULL, 'b'},
		{"pidfile", optional_argument, NULL, 'p'},
		{"dry-run", no_argument, NULL, 't'},
		{"poll-sysfs", no_argument, NULL, 'y'},
		{"hardware-logic", no_argument, NULL, 'H'},
		{"software-logic", no_argument, NULL, 'S'},
		{"version", no_argument, NULL, 'V'},
		{"help", no_argument, NULL, 'h'},
		{"no-leds", no_argument, NULL, 'L'},
		{"syslog", no_argument, NULL, 'l'},
		{"force", no_argument, NULL, 'f'},
		{"force-rotational", no_argument, NULL, 'r'},
		{NULL, 0, NULL, 0}
	};

	if (uname(&sysinfo) < 0 || strcmp("2.6.27", sysinfo.release) <= 0) {
		protect_factor = 1000;
		kernel_interface = UNLOAD_HEADS;
	}
	else {
		protect_factor = 1;
		kernel_interface = PROTECT;
	}

	openlog(PACKAGE_NAME, LOG_PID, LOG_DAEMON);

	while ((c = getopt_long(argc, argv, "d:s:vbap::tyHSVhLlfr", longopts, NULL)) != -1) {
		switch (c) {
			case 'd':
				add_disk(optarg);
				break;
			case 's':
				threshold = atoi(optarg);
				break;
			case 'b':
				background = 1;
				break;
			case 'a':
				adaptive = 1;
				break;
			case 'v':
				verbose = 1;
				break;
			case 'p':
				pidfile = 1;
				if (optarg == NULL) {
					snprintf(pid_file, sizeof(pid_file), "%s", PID_FILE);
				} else {
					snprintf(pid_file, sizeof(pid_file), "%s", optarg);
				}
				break;
			case 't':
				printlog(stdout, "Dry run, will not actually park heads or freeze queue.");
				dry_run = 1;
				break;
			case 'y':
				poll_sysfs = 1;
				break;
			case 'H':
				hardware_logic = 1;
				position_interface = INTERFACE_FREEFALL;
				break;
			case 'S':
				force_software_logic = 1;
				break;
			case 'V':
				version();
				break;
			case 'l':
				dosyslog = 1;
				break;
			case 'L':
				use_leds = 0;
				break;
			case 'f':
				forceadd = 1;
				break;
			case 'r':
				forcerotational = 1;
				break;
			case 'h':
			default:
				usage();
				break;
		}
	}

	printlog(stdout, "Starting "PACKAGE_NAME);

	if (disklist && forceadd) {
		char protect_method[FILENAME_MAX] = "";
		p = disklist;
		while (p != NULL) {
			snprintf(protect_method, sizeof(protect_method), QUEUE_METHOD_FMT, p->name);
			if (kernel_interface == UNLOAD_HEADS)
				fd = open (p->protect_file, O_RDWR);
			else
				fd = open (protect_method, O_RDWR);
			if (fd > 0) {
				if (kernel_interface == UNLOAD_HEADS)
					ret = write(fd, FORCE_UNLOAD_HEADS, strlen(FORCE_UNLOAD_HEADS));
				else
					ret = write(fd, FORCE_PROTECT_METHOD, strlen(FORCE_PROTECT_METHOD));
				if (ret == -1)
					printlog(stderr, "Could not forcely enable UNLOAD feature for %s", p->name);
				else
					printlog(stdout, "Forcely enabled UNLOAD for %s", p->name);
				close(fd);
			}
			else
				printlog(stderr, "Could not open %s for forcely enabling UNLOAD feature", p->protect_file);

			p = p->next;
		}
	}

	if (disklist == NULL) {
		printlog(stdout, "WARNING: You did not supply any devices to protect, trying autodetection.");
		if (autodetect_devices() < 1)
			printlog(stderr, "Could not detect any devices.");
	}

	if (disklist == NULL)
		usage(argv);

	/* Let's see if we're on a ThinkPad or on an *Book */
	if (!position_interface)
		select_interface(0);
	if (!position_interface)
		select_interface(1);

	if (!position_interface && !hardware_logic) {
		printlog(stdout, "Could not find a suitable interface");
		return -1;
	}
	else
		printlog(stdout, "Selected interface: %s", interface_names[position_interface]);
	if (hardware_logic) {
		/* Open the file representing the hardware decision */
	        freefall_fd = open (FREEFALL_FILE, FREEFALL_FD_FLAGS);
		if (freefall_fd < 0) {
				printlog(stdout,
				        "ERROR: Failed openning the hardware logic file (%s). "
					"It is probably not supported on your system.",
				        strerror(errno));
				return errno;
		}
		else {
			printlog (stdout, "Uses hardware logic from " FREEFALL_FILE);
		}
	}
	if (!poll_sysfs && !hardware_logic) {
		if (position_interface == INTERFACE_HDAPS) {
			hdaps_input_nr = device_find_byphys("hdaps/input1");
			hdaps_input_fd = device_open(hdaps_input_nr);
			if (hdaps_input_fd < 0) {
				printlog(stdout,
				        "WARNING: Could not find hdaps input device (%s). "
				        "You may be using an incompatible version of the hdaps module. "
				        "Falling back to reading the position from sysfs (uses more power).\n"
				        "Use '-y' to silence this warning.",
				        strerror(errno));
				poll_sysfs = 1;
			}
			else {
				printlog(stdout, "Selected HDAPS input device: /dev/input/event%d", hdaps_input_nr);
			}
		} else if (position_interface == INTERFACE_AMS) {
			hdaps_input_nr = device_find_byname("Apple Motion Sensor");
			hdaps_input_fd = device_open(hdaps_input_nr);
			if (hdaps_input_fd < 0) {
				printlog(stdout,
					"WARNING: Could not find AMS input device, do you need to set joystick=1?");
				poll_sysfs = 1;
			}
			else {
				printlog(stdout, "Selected AMS input device /dev/input/event%d", hdaps_input_nr);
			}
		} else if (position_interface == INTERFACE_HP3D) {
			hdaps_input_nr = device_find_byname("ST LIS3LV02DL Accelerometer");
			hdaps_input_fd = device_open(hdaps_input_nr);
			if (hdaps_input_fd < 0) {
				printlog(stdout,
					"WARNING: Could not find HP3D input device");
				poll_sysfs = 1;
			}
			else {
				printlog(stdout, "Selected HP3D input device /dev/input/event%d", hdaps_input_nr);
			}
		} else if (position_interface == INTERFACE_APPLESMC) {
			hdaps_input_nr = device_find_byname("applesmc");
			hdaps_input_fd = device_open(hdaps_input_nr);
			if (hdaps_input_fd < 0) {
				printlog(stdout,
					"WARNING: Could not find APPLESMC input device");
				poll_sysfs = 1;
			}
			else {
				printlog(stdout, "Selected APPLESMC input device /dev/input/event%d", hdaps_input_nr);
			}
		}
	}
	if (position_interface != INTERFACE_HP3D && position_interface != INTERFACE_FREEFALL) {
		/* LEDs are not supported yet on other systems */
		use_leds = 0;
	}
	if (use_leds) {
		fd = open(HP3D_LED_FILE, O_WRONLY);
		if (fd < 0)
			use_leds = 0;
		else
			close(fd);
	}

	if (background) {
		verbose = 0;
		if (pidfile) {
			fd = open (pid_file, O_WRONLY | O_CREAT, 0644);
			if (fd < 0) {
				printlog (stderr, "Could not create pidfile: %s", pid_file);
				return 1;
			}
		}
		daemon(0,0);
		if (pidfile) {
			char buf[BUF_LEN];
			snprintf (buf, sizeof(buf), "%d\n", getpid());
			ret = write (fd, buf, strlen(buf));
			if (ret < 0) {
				printlog (stderr, "Could not write to pidfile %s", pid_file);
				return 1;
			}
			if (close (fd)) {
				printlog (stderr, "Could not close pidfile %s", pid_file);
				return 1;
			}
		}
	}

	mlockall(MCL_FUTURE);

	if (verbose) {
		p = disklist;
		while (p != NULL) {
			printf("disk: %s\n", p->name);
			p = p->next;
		}
		printf("threshold: %i\n", threshold);
		printf("read_method: %s\n", poll_sysfs ? "poll-sysfs" : (hardware_logic ? "hardware-logic" : "input-dev"));
	}

	/* check the protect attribute exists */
	/* wait for it if it's not there (in case the attribute hasn't been created yet) */
	p = disklist;
	while (p != NULL && !dry_run) {
		fd = open (p->protect_file, O_RDWR);
		if (background)
			for (i = 0; fd < 0 && i < 100; ++i) {
				usleep (100000);	/* 10 Hz */
				fd = open (p->protect_file, O_RDWR);
			}
		if (fd < 0) {
			printlog (stderr, "Could not open %s\nDoes your kernel/drive support IDLE_IMMEDIATE with UNLOAD?", p->protect_file);
			free_disk(disklist);
			return 1;
		}
		close (fd);
		p = p->next;
	}

	/* see if we can read the sensor */
	/* wait for it if it's not there (in case the attribute hasn't been created yet) */
	if (!hardware_logic) {
		ret = read_position_from_sysfs (&x, &y, &z);
		if (background)
			for (i = 0; ret && i < 100; ++i) {
				usleep (100000);	/* 10 Hz */
				ret = read_position_from_sysfs (&x, &y, &z);
			}
		if (ret) {
			printlog(stderr, "Could not read position from sysfs.");
			return 1;
		}
	}

	/* adapt to the driver's sampling rate */
	if (position_interface == INTERFACE_HDAPS)
		sampling_rate = read_int(HDAPS_SAMPLING_RATE_FILE);
	else if (position_interface == INTERFACE_HP3D)
		sampling_rate = read_int(HP3D_SAMPLING_RATE_FILE);
	if (sampling_rate <= 0)
		sampling_rate = DEFAULT_SAMPLING_RATE;
	if (verbose)
		printf("sampling_rate: %d\n", sampling_rate);

	signal(SIGUSR1, SIGUSR1_handler);

	signal(SIGTERM, SIGTERM_handler);

	while (running) {
		if (!hardware_logic) { /* The decision is made by the software */
			/* Get statistics and decide what to do */
			if (poll_sysfs) {
				usleep (1000000/sampling_rate);
				ret = read_position_from_sysfs (&x, &y, &z);
				unow = get_utime(); /* microsec */
			} else {
				double oldunow = unow;
				int oldx = x, oldy = y, oldz = z;
				ret = read_position_from_inputdev (&x, &y, &z, &unow);

				/*
				 * The input device issues events only when the position changed.
				 * The analysis state needs to know how long the position remained
				 * unchanged, so send analyze() a fake retroactive update before sending
				 * the new one.
				 */
				if (!ret && oldunow && unow-oldunow > 1.5/sampling_rate)
					analyze(oldx, oldy, unow-1.0/sampling_rate, threshold, adaptive, parked);

			}

			if (ret) {
				if (verbose)
					printf("readout error (%d)\n", ret);
				continue;
			}

			park_now = analyze(x, y, unow, threshold, adaptive, parked);
		}
		else /* if (hardware_logic) */ {
			unsigned char count; /* Number of fall events */
			if (!parked) {
				/* Wait for the hardware to notify a fall */
				ret = read(freefall_fd, &count, sizeof(count));
			}
			else {
				/*
				 * Poll to check if we no longer are falling
				 * (hardware_logic polls only when parked)
				 */
				usleep (1000000/sampling_rate);
				fcntl (freefall_fd, F_SETFL, FREEFALL_FD_FLAGS|O_NONBLOCK);
				ret = read(freefall_fd, &count, sizeof(count));
				fcntl (freefall_fd, F_SETFL, FREEFALL_FD_FLAGS);
				/*
				 * If the error is EAGAIN then it is not a real error but
				 * a sign that the fall has ended
				 */
				if (ret != sizeof(count) && errno == EAGAIN) {
					count = 0; /* set fall events count to 0 */
					ret = sizeof(count); /* Validate count */
				}
			}
			/* handle read errors */
			if (ret != sizeof(count)) {
				if (verbose)
					printf("readout error (%d)\n", ret);
				continue;
			}
			/* Display the read values in verbose mode */
			if (verbose)
				printf ("HW=%u\n", (unsigned) count);
			unow = get_utime(); /* microsec */
			park_now = (count > 0);
		}

		if (park_now && !pause_now) {
			if (!parked || unow>parked_utime+REFREEZE_SECONDS) {
				/* Not frozen or freeze about to expire */
				p = disklist;
				while (p != NULL) {
					write_protect(p->protect_file,
					      (FREEZE_SECONDS+FREEZE_EXTRA_SECONDS) * protect_factor);
					p = p->next;
				}
				/*
				 * Write protect before any output (xterm, or
				 * whatever else is handling our stdout, may be
				 * swapped out).
				 */
				if (!parked) {
				        printlog(stdout, "parking");
					if (use_leds)
						write_int (HP3D_LED_FILE, 1);
				}
				parked = 1;
				parked_utime = unow;
			}
		} else {
			if (parked &&
			    (pause_now || unow>parked_utime+FREEZE_SECONDS)) {
				/* Sanity check */
				p = disklist;
				while (p != NULL) {
					if (!dry_run && !read_int(p->protect_file))
						printlog(stderr, "Error! Not parked when we "
						       "thought we were... (paged out "
					               "and timer expired?)");
					/* Freeze has expired */
					write_protect(p->protect_file, 0); /* unprotect */
					if (use_leds)
						write_int (HP3D_LED_FILE, 0);
					p = p->next;
				}
				parked = 0;
				printlog(stdout, "un-parking");
			}
			while (pause_now) {
				pause_now = 0;
				printlog(stdout, "pausing for %d seconds", SIGUSR1_SLEEP_SEC);
				sleep(SIGUSR1_SLEEP_SEC);
			}
		}

	}

	free_disk(disklist);
	printlog(stdout, "Terminating "PACKAGE_NAME);
	closelog();
	if (pidfile)
		unlink(pid_file);
	munlockall();
	return ret;
}
Ejemplo n.º 24
0
double read_num(unsigned char *buf) {
  unsigned char *limit;
  double i, result, denom;
  switch (buf[0]) {
  case S1_FIXNUM:
    return (double)read_int(buf, 1);
  case S1_SINGLE_FLOAT:
    return (double)read_float(buf, 1);
  case S1_DOUBLE_FLOAT:
    return read_double(buf, 1);
  case S1_NEGATIVE_BIGNUM:
    result = 0;
    buf += 5;
    limit = buf + read_uint(buf, -4);
    for(i=0 ; buf < limit; i++, buf = buf+4) {
      result -= exp2(i*32) * read_uint(buf, 0);
    }
    return result;
  case S1_POSITIVE_BIGNUM:
    result = 0;
    buf += 5;
    limit = buf + read_uint(buf, -4);
    for(i=0 ; buf < limit; i++, buf = buf+4) {
      result += exp2(i*32) * read_uint(buf, 0);
    }
    return result;
  case S1_RATIONAL:
  default:
    switch ((++buf)[0]) {
    case S1_FIXNUM:
      result = (double)read_int(++buf, 0);
      buf += 4;
      break;
    case S1_NEGATIVE_BIGNUM:
      result = 0;
      buf += 5;
      limit = buf + read_uint(buf, -4);
      for(i=0 ; buf < limit; i++, buf = buf+4) {
	result -= exp2(i*32) - read_uint(buf, 0);
      }
      break;
    case S1_POSITIVE_BIGNUM:
    default:
      result = 0;
      buf += 5;
      limit = buf + read_uint(buf, -4);
      for(i=0 ; buf < limit; i++, buf = buf+4) {
	result += exp2(i*32) * read_uint(buf, 0);
      }
      break;
    }
    
    switch (buf[0]) {
    case S1_FIXNUM: 
      return result / read_int(++buf, 0);
    case S1_NEGATIVE_BIGNUM:
      denom = 0;
      buf += 5;
      limit = buf + read_uint(buf, -4);
      for(i=0 ; buf < limit; i++, buf = buf+4) {
	denom -= exp2(i*32) * read_uint(buf, 0);
      }
      return result / denom;
    case S1_POSITIVE_BIGNUM:
    default:
      denom = 0;
      buf += 5;
      limit = buf + read_uint(buf, -4);
      for(i=0 ; buf < limit; i++, buf = buf+4) {
	denom += exp2(i*32) * read_uint(buf, 0);
      }
      return result / denom;
    }    
  }
}
Ejemplo n.º 25
0
void eoRealVectorBounds::readFrom(std::string _value)
{
  // keep track of old size - to adjust in the end
  unsigned oldSize = size();
  // clean-up before filling in
  if (ownedBounds.size()>0)
    for (unsigned i = 0; i < ownedBounds.size(); ++i)
      {
        delete ownedBounds[i];
      }
  ownedBounds.resize(0);
  factor.resize(0);
  resize(0);

  // now read
  std::string delim(",; ");
  while (_value.size()>0)
    {
      if (!remove_leading(_value, delim)) // only delimiters were left
        break;
      // look for opening char
      size_t posDeb = _value.find_first_of("[(");
      if (posDeb >= _value.size())	// nothing left to read (though probably a syntax error there)
        {
          break;
        }
      // ending char
      std::string closeChar = (_value[posDeb] == '(' ? std::string(")") : std::string("]") );

      size_t posFin = _value.find_first_of(std::string(closeChar));
      if (posFin >= _value.size())
        throw std::runtime_error("Syntax error when reading bounds");

  // y a-t-il un nbre devant
      unsigned count = 1;
      if (posDeb > 0)			// something before opening
        {
          std::string sCount = _value.substr(0, posDeb);
          count = read_int(sCount);
          if (count <= 0)
            throw std::runtime_error("Syntax error when reading bounds");
        }

      // the bounds
      std::string sBounds = _value.substr(posDeb+1, posFin-posDeb-1);
      // and remove from original string
      _value = _value.substr(posFin+1);

      remove_leading(sBounds, delim);
      size_t posDelim = sBounds.find_first_of(delim);
      if (posDelim >= sBounds.size())
        throw std::runtime_error("Syntax error when reading bounds");

      bool minBounded=false, maxBounded=false;
      double minBound=0, maxBound=0;

      // min bound
      std::string sMinBounds = sBounds.substr(0,posDelim);
      if (sMinBounds != std::string("-inf"))
        {
          minBounded = true;
          minBound = read_double(sMinBounds);
        }

      // max bound
      size_t posEndDelim = sBounds.find_first_not_of(delim,posDelim);

      std::string sMaxBounds = sBounds.substr(posEndDelim);
      if (sMaxBounds != std::string("+inf"))
        {
          maxBounded = true;
          maxBound = read_double(sMaxBounds);
        }

      // now create the eoRealBounds objects
      eoRealBounds *ptBounds;
      if (minBounded && maxBounded)
        ptBounds = new eoRealInterval(minBound, maxBound);
      else if (!minBounded && !maxBounded)	// no bound at all
        ptBounds = new eoRealNoBounds;
      else if (!minBounded && maxBounded)
        ptBounds = new eoRealAboveBound(maxBound);
      else if (minBounded && !maxBounded)
        ptBounds = new eoRealBelowBound(minBound);
      // store it for memory management
      ownedBounds.push_back(ptBounds);
      // push the count
      factor.push_back(count);
      // and add count of it to the actual bounds
      for (unsigned i=0; i<count; i++)
        push_back(ptBounds);
    }
  // now adjust the size to the initial value
  adjust_size(oldSize);
}
Ejemplo n.º 26
0
/*
 * Read the player inventory
 *
 * Note that the inventory changed in Angband 2.7.4.  Two extra
 * pack slots were added and the equipment was rearranged.  Note
 * that these two features combine when parsing old save-files, in
 * which items from the old "aux" slot are "carried", perhaps into
 * one of the two new "inventory" slots.
 *
 * Note that the inventory is "re-sorted" later by "dungeon()".
 */
static errr rd_inventory(player_type *p_ptr)
{
	int slot = 0;

	object_type forge;

	start_section_read("inventory");

	/* No weight */
	p_ptr->total_weight = 0;

	/* No items */
	p_ptr->inven_cnt = 0;
	p_ptr->equip_cnt = 0;

	/* Read until done */
	while (1)
	{
		u16b n;

		/* Get the next item index */
		n = read_int("inv_entry");

		/* Nope, we reached the end */
		if (n == 0xFFFF) break;

		/* Read the item */
		rd_item(&forge);

		/* Hack -- verify item */
		if (!forge.k_idx) return (53);

		/* Mega-Hack -- Handle artifacts that aren't yet "created" */
		if (artifact_p(&forge))
		{
			/* If this artifact isn't created, mark it as created */
			/* Only if this isn't a "death" restore */
			if (!a_info[forge.name1].cur_num && !p_ptr->death)
				a_info[forge.name1].cur_num = 1;
		}

		/* Wield equipment */
		if (n >= INVEN_WIELD)
		{
			/* Structure copy */
			p_ptr->inventory[n] = forge;

			/* Add the weight */
			p_ptr->total_weight += (forge.number * forge.weight);

			/* One more item */
			p_ptr->equip_cnt++;
		}

		/* Warning -- backpack is full */
		else if (p_ptr->inven_cnt == INVEN_PACK)
		{
			/* Oops */
			/*note("Too many items in the inventory!");*/

			/* Fail */
			return (54);
		}

		/* Carry inventory */
		else
		{
			/* Get a slot */
			n = slot++;

			/* Structure copy */
			p_ptr->inventory[n] = forge;

			/* Add the weight */
			p_ptr->total_weight += (forge.number * forge.weight);

			/* One more item */
			p_ptr->inven_cnt++;
		}
	}

	end_section_read("inventory");

	/* Success */
	return (0);
}
Ejemplo n.º 27
0
static void
check_file (const char* file_name)
{
  FILE *fp;

  int tmp;
  int base;
  int inex_re;
  int inex_im;
  mpc_t expected, got;
  mpc_rnd_t rnd = MPC_RNDNN;
  int inex = 0, expected_inex;
  size_t expected_size, size;
  known_signs_t ks = {1, 1};

  fp = open_data_file (file_name);

  mpc_init2 (expected, 53);
  mpc_init2 (got, 53);

  /* read data file */
  line_number = 1;
  nextchar = getc (fp);
  skip_whitespace_comments (fp);

  while (nextchar != EOF)
    {
      /* 1. read a line of data: expected result, base, rounding mode */
      read_ternary (fp, &inex_re);
      read_ternary (fp, &inex_im);
      read_mpc (fp, expected, &ks);
      if (inex_re == TERNARY_ERROR || inex_im == TERNARY_ERROR)
         expected_inex = -1;
      else
         expected_inex = MPC_INEX (inex_re, inex_im);
      read_int (fp, &tmp, "size");
      expected_size = (size_t)tmp;
      read_int (fp, &base, "base");
      read_mpc_rounding_mode (fp, &rnd);

      /* 2. read string at the same precision as the expected result */
      while (nextchar != '"')
        nextchar = getc (fp);
      mpfr_set_prec (MPC_RE (got), MPC_PREC_RE (expected));
      mpfr_set_prec (MPC_IM (got), MPC_PREC_IM (expected));
      inex = mpc_inp_str (got, fp, &size, base, rnd);

      /* 3. compare this result with the expected one */
      if (inex != expected_inex || !same_mpc_value (got, expected, ks)
          || size != expected_size)
        {
          printf ("mpc_inp_str failed (line %lu) with rounding mode %s\n",
                  line_number, rnd_mode[rnd]);
          if (inex != expected_inex)
            printf("     got inexact value: %d\nexpected inexact value: %d\n",
                   inex, expected_inex);
          if (size !=  expected_size)
            printf ("     got size: %lu\nexpected size: %lu\n     ",
                    (unsigned long int) size, (unsigned long int) expected_size);
          printf ("    ");
          OUT (got);
          OUT (expected);

          exit (1);
        }

      while ((nextchar = getc (fp)) != '"');
      nextchar = getc (fp);

      skip_whitespace_comments (fp);
    }

  mpc_clear (expected);
  mpc_clear (got);
  close_data_file (fp);
}
Ejemplo n.º 28
0
static errr rd_dungeon(bool ext, int Depth)
{
	s32b depth;
	u16b max_y, max_x;

	int y, x;
	cave_type *c_ptr;
	char cave_row[MAX_WID+1];

	start_section_read("dungeon_level");

	/*** Depth info ***/

	/* Level info */
	depth = read_int("depth");
	max_y = read_int("max_height");
	max_x = read_int("max_width");
	if (ext) depth = Depth;

	/* players on this depth */
	players_on_depth[depth] = read_int("players_on_depth");

	/* Hack -- only read in staircase information for non-wilderness
	 * levels
	 */

	if (depth >= 0)
	{

		level_up_y[depth] = read_int("level_up_y");
		level_up_x[depth] = read_int("level_up_x");
		level_down_y[depth] = read_int("level_down_y");
		level_down_x[depth] = read_int("level_down_x");
		level_rand_y[depth] = read_int("level_rand_y");
		level_rand_x[depth] = read_int("level_rand_x");
		
	}
	/* HACK */
	else if (value_exists("level_up_y"))
	{
		skip_value("level_up_y");
		skip_value("level_up_x");
		skip_value("level_down_y");
		skip_value("level_down_x");
		skip_value("level_rand_y");
		skip_value("level_rand_x");	
	}

	/* allocate the memory for the dungoen if it has not already */
	/* been allocated - which it might have been if we are loading */
	/* a special static level file */
	if(!cave[depth])
		alloc_dungeon_level(depth);

	/* Load features */
	start_section_read("features");

		for (y = 0; y < max_y; y++)
		{
			read_binary("row",cave_row,MAX_WID);
			for(x = 0; x < max_x; x++)
			{
				/* Access the cave */
				c_ptr = &cave[depth][y][x];

				/* set the feature */
				c_ptr->feat = cave_row[x];
			}			
		}

	end_section_read("features");

	/* Load info */
	start_section_read("info");

		for (y = 0; y < max_y; y++)
		{
			read_binary("row",cave_row,MAX_WID);
			for(x = 0; x < max_x; x++)
			{
				/* Access the cave */
				c_ptr = &cave[depth][y][x];

				/* set the feature */
				c_ptr->info = cave_row[x];
			}			
		}

	end_section_read("info");

	end_section_read("dungeon_level");
	/* Success */
	return (0);
}
Ejemplo n.º 29
0
void
hcache_readfile(HCACHEFILE *file)
{
	HCACHEDATA	cachedata, *c, *last = 0;
	FILE	*f;
	int		bad_cache = 1, ch;
	const char	*version;
	BUFFER	buff;
	long	buffsize;

/*    if( ! (hcachename = hcache_filename()) )
	return;*/

	if( ! (f = fopen( file->cachefilename, "rb" )) )
		return;

	fseek( f, 0, SEEK_END );
	buffsize = ftell( f );
	fseek( f, 0, SEEK_SET );
	buffer_init( &buff );
	buffer_resize( &buff, buffsize + 1 );
	if ( fread( buffer_ptr( &buff ), buffsize, 1, f ) != 1 )
	{
		fclose( f );
		goto bail;
	}
	buffer_ptr( &buff )[buffsize] = 0;
	fclose( f );

	version = read_string( &buff );
	ch = buffer_getchar( &buff );
	if (!version || strcmp( version, CACHE_FILE_VERSION ) || ch != '\n' ) {
		goto bail;
	}

	for(;;) {
		int i, count, ch;
		LIST *l;

		c = &cachedata;

		c->boundname = read_string( &buff );
		if( !c->boundname ) /* Test for eof */
			break;

		c->time = read_int( &buff );
		c->age = read_int( &buff ) + 1; /* we're getting older... */

#ifdef OPT_BUILTIN_MD5CACHE_EXT
		c->mtime = read_int( &buff );
		read_md5sum( &buff, c->rulemd5sum );
		memcpy( &c->currentrulemd5sum, &c->rulemd5sum, MD5_SUMSIZE );
		read_md5sum( &buff, c->contentmd5sum );
		memcpy( &c->currentcontentmd5sum, &c->contentmd5sum, MD5_SUMSIZE );
#endif

		if( !c->boundname )
			goto bail;

		/* headers */
		count = read_int( &buff );
		for( l = 0, i = 0; i < count; ++i ) {
			const char *s = read_string( &buff );
			if( !s )
				goto bail;
			l = list_append( l, s, 0 );
		}
		c->includes = l;

		/* hdrscan */
		count = read_int( &buff );
		for( l = 0, i = 0; i < count; ++i ) {
			const char *s = read_string( &buff );
			if( !s )
				goto bail;
			l = list_append( l, s, 0 );
		}
		c->hdrscan = l;

		/* Read the newline */
		ch = skip_spaces( &buff );
		if( ch != '!' )
			goto bail;
		ch = skip_spaces( &buff );
		if( ch != '\n' )
			goto bail;

		if( !hashenter( file->hcachehash, (HASHDATA **)&c ) ) {
			printf( "jam: can't insert header cache item, bailing on %s\n",
				file->cachefilename );
			goto bail;
		}

		c->next = 0;
		if( last )
			last->next = c;
		else
			file->hcachelist = c;
		last = c;
	}

	bad_cache = 0;

	if( DEBUG_HEADER )
		printf( "hcache read from file %s\n", file->cachefilename );

bail:
	/* If its bad, no worries, it'll be overwritten in hcache_done() */
	if( bad_cache )
		printf( "jam: warning: the cache was invalid: %s\n", file->cachefilename );
	buffer_free( &buff );
}
Ejemplo n.º 30
0
bool get_int(HSQUIRRELVM vm, const char* name, int& val) {
  if (!has_int(vm, name)) return false;
  val = read_int(vm, name);
  return true;
}