Esempio n. 1
0
	PerlinNoise::PerlinNoise(uint_t seed /* = 0 */) {
		m_holdrand = seed;

		int i, j, k;

		for (i = 0 ; i < B ; i++) {
			p[i] = i;

			g1[i] = (float)((xrand() % (B + B)) - B) / B;

			for (j = 0 ; j < 2 ; j++)
				g2[i][j] = (float)((xrand() % (B + B)) - B) / B;
//			normalize2(g2[i]);

			for (j = 0 ; j < 3 ; j++)
				g3[i][j] = (float)((xrand() % (B + B)) - B) / B;
			normalize3(g3[i]);
		}

		while (--i) {
			k = p[i];
			p[i] = p[j = xrand() % B];
			p[j] = k;
		}

		for (i = 0 ; i < B + 2 ; i++) {
			p[B + i] = p[i];
			g1[B + i] = g1[i];
			for (j = 0 ; j < 2 ; j++)
				g2[B + i][j] = g2[i][j];
			for (j = 0 ; j < 3 ; j++)
				g3[B + i][j] = g3[i][j];
		}
	}
Esempio n. 2
0
// float rand
float MathsVector::grand(float mean, float sdev)
{
float v1, v2, s;

 do
 {
  v1 = xrand(-1.0, 1.0);
  v2 = xrand(-1.0, 1.0);
  s = v1*v1 + v2*v2;
 } while (s >= 1.0);

 return (mean + sdev * v1 * sqrt(-2.0 * log(s) / s));
}
Esempio n. 3
0
void INITIA()
{
    /*   this routine initializes the positions of the molecules along
         a regular cubical lattice, and randomizes the initial velocities of
         the atoms.  The random numbers used in the initialization of velocities
         are read from the file random.in, which must be in the current working
         directory in which the program is run  */

    FILE *random_numbers;       /* points to input file containing
                                   pseudo-random numbers for initializing
                                   velocities */
    double XMAS[4], XT[4], YT[4], Z;
    double SUX, SUY, SUZ, SUMX, SUMY, SUMZ, FAC;
    long mol=0;
    long atom=0;
    long deriv;
#ifdef SIM_SOCLIB
	extern int * SOCLIB_STATIC_MEM;
	double * static_var = (double *) SOCLIB_STATIC_MEM ;
	int32_t retval = 0; 
	printf("address de la variable statique : %x\n",static_var);
	random_numbers = fopen ("/devices/fdaccess", "r+");
	vfs_component . operation . ioctl (fileno(random_numbers), FD_OPEN, "random.in", & retval);
	if (retval < 0) printf ("Error opening the random file.\r\n");
#else
	random_numbers = fopen("random.in","r");
#endif

    if (random_numbers == NULL) {
        fprintf(stderr,"Error in opening file random.in\n");
        fflush(stderr);
        exit(-1);
    }

    XMAS[1]=sqrt(OMAS*HMAS);
    XMAS[0]=HMAS;
    XMAS[2]=HMAS;

    /* .....assign positions */
    {
        double NS = pow((double) NMOL, 1.0/3.0) - 0.00001;
        double XS = BOXL/NS;
        double ZERO = XS * 0.50;
        double WCOS = ROH * cos(ANGLE * 0.5);
        double WSIN = ROH * sin(ANGLE * 0.5);
        long i,j,k;

        printf("\nNS = %.16f\n",NS);
        printf("BOXL = %10f\n",BOXL);
        printf("CUTOFF = %10f\n",CUTOFF);
        printf("XS = %10f\n",XS);
        printf("ZERO = %g\n",ZERO);
        printf("WCOS = %f\n",WCOS);
        printf("WSIN = %f\n",WSIN);
        fflush(stdout);

#ifdef RANDOM
        /* if we want to initialize to a random distribution of displacements
           for the molecules, rather than a distribution along a regular lattice
           spaced according to intermolecular distances in water */
        srand(1023);
        for (i = 0; i < NMOL; i++) {
            VAR[mol].F[DISP][XDIR][O] = xrand(0, BOXL);
            VAR[mol].F[DISP][XDIR][H1] = VAR[mol].F[DISP][XDIR][O] + WCOS;
            VAR[mol].F[DISP][XDIR][H2] = VAR[mol].F[DISP][XDIR][H1];
            VAR[mol].F[DISP][YDIR][O] = xrand(0, BOXL);
            VAR[mol].F[DISP][YDIR][H1] = VAR[mol].F[DISP][YDIR][O] + WSIN;
            VAR[mol].F[DISP][YDIR][H2] = VAR[mol].F[DISP][YDIR][O] - WSIN;
            VAR[mol].F[DISP][ZDIR][O] = xrand(0, BOXL);
            VAR[mol].F[DISP][ZDIR][H1] = VAR[mol].F[DISP][ZDIR][O];
            VAR[mol].F[DISP][ZDIR][H2] = VAR[mol].F[DISP][ZDIR][O];
        }
#else
        /* not random initial placement, but rather along a regular
           lattice.  This is the default and the prefered initialization
           since random does not necessarily make sense from the viewpoint
           of preserving bond distances */

        fprintf(six, "***** NEW RUN STARTING FROM REGULAR LATTICE *****\n");
        fflush(six);
        XT[2] = ZERO;
        mol = 0;
        for (i=0; i < NS; i+=1) {
            XT[1]=XT[2]+WCOS;
            XT[3]=XT[1];
            YT[2]=ZERO;
            for (j=0; j < NS; j+=1) {
                YT[1]=YT[2]+WSIN;
                YT[3]=YT[2]-WSIN;
                Z=ZERO;
                for (k = 0; k < NS; k++) {
                    for (atom = 0; atom < NATOMS; atom +=1) {
                        VAR[mol].F[DISP][XDIR][atom] = XT[atom+1];
                        VAR[mol].F[DISP][YDIR][atom] = YT[atom+1];
                        VAR[mol].F[DISP][ZDIR][atom] = Z;
                    }
                    mol += 1;
                    Z=Z+XS;
                }
                YT[2]=YT[2]+XS;
            }
            XT[2]=XT[2]+XS;
        }

        if (NMOL != mol) {
            printf("Lattice init error: total mol %ld != NMOL %ld\n", mol, NMOL);
            exit(-1);
        }
#endif
    }

    /* ASSIGN RANDOM MOMENTA */
#ifdef SIM_SOCLIB
    fscanf(random_numbers,"%lf",static_var);
	SUX = *static_var;
#else
    fscanf(random_numbers,"%lf",&SUX);
#endif

    SUMX=0.0;
    SUMY=0.0;
    SUMZ=0.0;
    /*   read pseudo-random numbers from input file random.in */
    for (mol = 0; mol < NMOL; mol++) {
        for (atom = 0; atom < NATOMS; atom++) {
#ifndef SIM_SOCLIB
            fscanf(random_numbers,"%lf",&VAR[mol].F[VEL][XDIR][atom]);
            fscanf(random_numbers,"%lf",&VAR[mol].F[VEL][YDIR][atom]);
            fscanf(random_numbers,"%lf",&VAR[mol].F[VEL][ZDIR][atom]);
#else
			fscanf(random_numbers,"%lf",static_var);
			VAR[mol].F[VEL][XDIR][atom] = *static_var;
			fscanf(random_numbers,"%lf",static_var);
			VAR[mol].F[VEL][YDIR][atom] = *static_var;
			fscanf(random_numbers,"%lf",static_var);
			VAR[mol].F[VEL][ZDIR][atom] = *static_var;
#endif
            SUMX = SUMX + VAR[mol].F[VEL][XDIR][atom];
            SUMY = SUMY + VAR[mol].F[VEL][YDIR][atom];
            SUMZ = SUMZ + VAR[mol].F[VEL][ZDIR][atom];
            for (deriv = ACC; deriv < MAXODR; deriv++) {
                VAR[mol].F[deriv][XDIR][atom] = 0.0;
                VAR[mol].F[deriv][YDIR][atom] = 0.0;
                VAR[mol].F[deriv][ZDIR][atom] = 0.0;
            }
        } /* atoms */
    } /* molecules */

    /* find average momenta per atom */
    SUMX=SUMX/(NATOMS*NMOL);
    SUMY=SUMY/(NATOMS*NMOL);
    SUMZ=SUMZ/(NATOMS*NMOL);

    /*  find normalization factor so that <k.e.>=KT/2  */
    SUX=0.0;
    SUY=0.0;
    SUZ=0.0;
    for (mol = 0; mol < NMOL; mol++) {
        SUX = SUX + (pow( (VAR[mol].F[VEL][XDIR][H1] - SUMX),2.0)
                     +pow( (VAR[mol].F[VEL][XDIR][H2] - SUMX),2.0))/HMAS
                         +pow( (VAR[mol].F[VEL][XDIR][O]  - SUMX),2.0)/OMAS;

        SUY = SUY + (pow( (VAR[mol].F[VEL][YDIR][H1] - SUMY),2.0)
                     +pow( (VAR[mol].F[VEL][YDIR][H2] - SUMY),2.0))/HMAS
                         +pow( (VAR[mol].F[VEL][YDIR][O]  - SUMY),2.0)/OMAS;

        SUZ = SUZ + (pow( (VAR[mol].F[VEL][ZDIR][H1] - SUMZ),2.0)
                     +pow( (VAR[mol].F[VEL][ZDIR][H2] - SUMZ),2.0))/HMAS
                         +pow( (VAR[mol].F[VEL][ZDIR][O]  - SUMZ),2.0)/OMAS;
    }
    FAC=BOLTZ*TEMP*NATMO/UNITM * pow((UNITT*TSTEP/UNITL),2.0);
    SUX=sqrt(FAC/SUX);
    SUY=sqrt(FAC/SUY);
    SUZ=sqrt(FAC/SUZ);

    /* normalize individual velocities so that there are no bulk
       momenta  */
    XMAS[1]=OMAS;
    for (mol = 0; mol < NMOL; mol++) {
        for (atom = 0; atom < NATOMS; atom++) {
            VAR[mol].F[VEL][XDIR][atom] = ( VAR[mol].F[VEL][XDIR][atom] -
                                           SUMX) * SUX/XMAS[atom];
            VAR[mol].F[VEL][YDIR][atom] = ( VAR[mol].F[VEL][YDIR][atom] -
                                           SUMY) * SUY/XMAS[atom];
            VAR[mol].F[VEL][ZDIR][atom] = ( VAR[mol].F[VEL][ZDIR][atom] -
                                           SUMZ) * SUZ/XMAS[atom];
        } /* for atom */
    } /* for mol */

#ifdef SIM_SOCLIB
	vfs_component . operation . ioctl (fileno(random_numbers), FD_CLOSE, "random.in", & retval);
	if (retval < 0) printf ("Error closing the video file.\r\n");
    //fclose(random_numbers); avoid a call to an unimplemented function : vfs_lseek
#else
    fclose(random_numbers);
#endif


} /* end of subroutine INITIA */
Esempio n. 4
0
void SCR_CaptureVideo_Ogg_BeginVideo(void)
{
	char vabuf[1024];
	cls.capturevideo.format = CAPTUREVIDEOFORMAT_OGG_VORBIS_THEORA;
	cls.capturevideo.formatextension = "ogv";
	cls.capturevideo.videofile = FS_OpenRealFile(va(vabuf, sizeof(vabuf), "%s.%s", cls.capturevideo.basename, cls.capturevideo.formatextension), "wb", false);
	cls.capturevideo.endvideo = SCR_CaptureVideo_Ogg_EndVideo;
	cls.capturevideo.videoframes = SCR_CaptureVideo_Ogg_VideoFrames;
	cls.capturevideo.soundframe = SCR_CaptureVideo_Ogg_SoundFrame;
	cls.capturevideo.formatspecific = Mem_Alloc(tempmempool, sizeof(capturevideostate_ogg_formatspecific_t));
	{
		LOAD_FORMATSPECIFIC_OGG();
		int num, denom, i;
		ogg_page pg;
		ogg_packet pt, pt2, pt3;
		theora_comment tc;
		vorbis_comment vc;
		theora_info ti;
		int vp3compat;

		format->serial1 = xrand();
		qogg_stream_init(&format->to, format->serial1);

		if(cls.capturevideo.soundrate)
		{
			do
			{
				format->serial2 = xrand();
			}
			while(format->serial1 == format->serial2);
			qogg_stream_init(&format->vo, format->serial2);
		}

		format->videopage.len = format->audiopage.len = 0;

		qtheora_info_init(&ti);
		ti.frame_width = cls.capturevideo.width;
		ti.frame_height = cls.capturevideo.height;
		ti.width = (ti.frame_width + 15) & ~15;
		ti.height = (ti.frame_height + 15) & ~15;
		//ti.offset_x = ((ti.width - ti.frame_width) / 2) & ~1;
		//ti.offset_y = ((ti.height - ti.frame_height) / 2) & ~1;

		for(i = 0; i < 2; ++i)
		{
			format->yuv[i].y_width = ti.width;
			format->yuv[i].y_height = ti.height;
			format->yuv[i].y_stride = ti.width;
			format->yuv[i].uv_width = ti.width / 2;
			format->yuv[i].uv_height = ti.height / 2;
			format->yuv[i].uv_stride = ti.width / 2;
			format->yuv[i].y = (unsigned char *) Mem_Alloc(tempmempool, format->yuv[i].y_stride * format->yuv[i].y_height);
			format->yuv[i].u = (unsigned char *) Mem_Alloc(tempmempool, format->yuv[i].uv_stride * format->yuv[i].uv_height);
			format->yuv[i].v = (unsigned char *) Mem_Alloc(tempmempool, format->yuv[i].uv_stride * format->yuv[i].uv_height);
		}
		format->yuvi = -1; // -1: no frame valid yet, write into 0

		FindFraction(cls.capturevideo.framerate / cls.capturevideo.framestep, &num, &denom, 1001);
		ti.fps_numerator = num;
		ti.fps_denominator = denom;

		FindFraction(1 / vid_pixelheight.value, &num, &denom, 1000);
		ti.aspect_numerator = num;
		ti.aspect_denominator = denom;

		ti.colorspace = OC_CS_UNSPECIFIED;
		ti.pixelformat = OC_PF_420;

		ti.quick_p = true; // http://mlblog.osdir.com/multimedia.ogg.theora.general/2004-07/index.shtml
		ti.dropframes_p = false;

		ti.target_bitrate = cl_capturevideo_ogg_theora_bitrate.integer * 1000;
		ti.quality = cl_capturevideo_ogg_theora_quality.integer;

		if(ti.target_bitrate <= 0)
		{
			ti.target_bitrate = -1;
			ti.keyframe_data_target_bitrate = (unsigned int)-1;
		}
		else
		{
			ti.keyframe_data_target_bitrate = (int) (ti.target_bitrate * max(1, cl_capturevideo_ogg_theora_keyframe_bitrate_multiplier.value));

			if(ti.target_bitrate < 45000 || ti.target_bitrate > 2000000)
				Con_DPrintf("WARNING: requesting an odd bitrate for theora (sensible values range from 45 to 2000 kbps)\n");
		}

		if(ti.quality < 0 || ti.quality > 63)
		{
			ti.quality = 63;
			if(ti.target_bitrate <= 0)
			{
				ti.target_bitrate = 0x7FFFFFFF;
				ti.keyframe_data_target_bitrate = 0x7FFFFFFF;
			}
		}

		// this -1 magic is because ti.keyframe_frequency and ti.keyframe_mindistance use different metrics
		ti.keyframe_frequency = bound(1, cl_capturevideo_ogg_theora_keyframe_maxinterval.integer, 1000);
		ti.keyframe_mindistance = bound(1, cl_capturevideo_ogg_theora_keyframe_mininterval.integer, (int) ti.keyframe_frequency) - 1;
		ti.noise_sensitivity = bound(0, cl_capturevideo_ogg_theora_noise_sensitivity.integer, 6);
		ti.sharpness = bound(0, cl_capturevideo_ogg_theora_sharpness.integer, 2);
		ti.keyframe_auto_threshold = bound(0, cl_capturevideo_ogg_theora_keyframe_auto_threshold.integer, 100);

		ti.keyframe_frequency_force = ti.keyframe_frequency;
		ti.keyframe_auto_p = (ti.keyframe_frequency != ti.keyframe_mindistance + 1);

		qtheora_encode_init(&format->ts, &ti);
		qtheora_info_clear(&ti);

		if(cl_capturevideo_ogg_theora_vp3compat.integer)
		{
			vp3compat = 1;
			qtheora_control(&format->ts, TH_ENCCTL_SET_VP3_COMPATIBLE, &vp3compat, sizeof(vp3compat));
			if(!vp3compat)
				Con_DPrintf("Warning: theora stream is not fully VP3 compatible\n");
		}

		// vorbis?
		if(cls.capturevideo.soundrate)
		{
			qvorbis_info_init(&format->vi);
			qvorbis_encode_init_vbr(&format->vi, cls.capturevideo.soundchannels, cls.capturevideo.soundrate, bound(-1, cl_capturevideo_ogg_vorbis_quality.value, 10) * 0.099);
			qvorbis_comment_init(&vc);
			qvorbis_analysis_init(&format->vd, &format->vi);
			qvorbis_block_init(&format->vd, &format->vb);
		}

		qtheora_comment_init(&tc);

		/* create the remaining theora headers */
		qtheora_encode_header(&format->ts, &pt);
		qogg_stream_packetin(&format->to, &pt);
		if (qogg_stream_pageout (&format->to, &pg) != 1)
			fprintf (stderr, "Internal Ogg library error.\n");
		FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
		FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);

		qtheora_encode_comment(&tc, &pt);
		qogg_stream_packetin(&format->to, &pt);
		qtheora_encode_tables(&format->ts, &pt);
		qogg_stream_packetin (&format->to, &pt);

		qtheora_comment_clear(&tc);

		if(cls.capturevideo.soundrate)
		{
			qvorbis_analysis_headerout(&format->vd, &vc, &pt, &pt2, &pt3);
			qogg_stream_packetin(&format->vo, &pt);
			if (qogg_stream_pageout (&format->vo, &pg) != 1)
				fprintf (stderr, "Internal Ogg library error.\n");
			FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
			FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);

			qogg_stream_packetin(&format->vo, &pt2);
			qogg_stream_packetin(&format->vo, &pt3);

			qvorbis_comment_clear(&vc);
		}

		for(;;)
		{
			int result = qogg_stream_flush (&format->to, &pg);
			if (result < 0)
				fprintf (stderr, "Internal Ogg library error.\n"); // TODO Sys_Error
			if (result <= 0)
				break;
			FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
			FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
		}

		if(cls.capturevideo.soundrate)
		for(;;)
		{
			int result = qogg_stream_flush (&format->vo, &pg);
			if (result < 0)
				fprintf (stderr, "Internal Ogg library error.\n"); // TODO Sys_Error
			if (result <= 0)
				break;
			FS_Write(cls.capturevideo.videofile, pg.header, pg.header_len);
			FS_Write(cls.capturevideo.videofile, pg.body, pg.body_len);
		}
	}
}
Esempio n. 5
0
void INITIA()
{
    /*   this routine initializes the positions of the molecules along
         a regular cubical lattice, and randomizes the initial velocities of
         the atoms.  The random numbers used in the initialization of velocities
         are read from the file random.in, which must be in the current working
         directory in which the program is run  */

    FILE *random_numbers;       /* points to input file containing
                                   pseudo-random numbers for initializing
                                   velocities */
    double XMAS[4];
    double SUX, SUY, SUZ, SUMX, SUMY, SUMZ, FAC;
    long X_INDEX, Y_INDEX, Z_INDEX;
    long atom=0;
    long i, j, k;
    struct link *link_ptr, *curr_ptr, *last_ptr;
#ifdef RANDOM
    long Part_per_box, Unassigned, m, pid;
#else
    long mol = 0, XT[4], YT[4], Z;
#endif

#ifdef SIM_SOCLIB
	extern int * SOCLIB_STATIC_MEM;
	double * static_var = (double *) SOCLIB_STATIC_MEM ;
	int32_t retval = 0; 
	printf("address de la variable statique : %x\n",static_var);
	random_numbers = fopen ("/devices/fdaccess", "r+");
	vfs_component . operation . ioctl (fileno(random_numbers), FD_OPEN, "random.in", & retval);
	if (retval < 0) printf ("Error opening the random file.\r\n");
#else
	random_numbers = fopen("random.in","r");
#endif
    if (random_numbers == NULL) {
        fprintf(stderr,"Error in opening file random.in\n");
        fflush(stderr);
        exit(-1);
    }

    XMAS[1]=sqrt(OMAS*HMAS);
    XMAS[0]=HMAS;
    XMAS[2]=HMAS;

    /* .....assign positions */

    {
        long deriv;

        double NS = pow((double) NMOL, 1.0/3.0) - 0.00000000000001;
        double XS = BOXL/NS;
        double ZERO = XS * 0.50;
        double WCOS = ROH * cos(ANGLE * 0.5);
        double WSIN = ROH * sin(ANGLE * 0.5);

        printf("\nNS = %.16f\n",NS);
        printf("BOXL = %10f\n",BOXL);
        printf("CUTOFF = %10f\n",CUTOFF);
        printf("BOX_LENGTH = %10f\n",BOX_LENGTH);
        printf("BOX_PER_SIDE = %ld\n",BOX_PER_SIDE);
        printf("XS = %10f\n",XS);
        printf("ZERO = %g\n",ZERO);
        printf("WCOS = %f\n",WCOS);
        printf("WSIN = %f\n",WSIN);
        fflush(stdout);

#ifdef RANDOM
        /* if we want to initialize to a random distribution of displacements
           for the molecules, rather than a distribution along a regular lattice
           spaced according to intermolecular distances in water */

        srand(1023);
#ifndef SIM_SOCLIB
    fscanf(random_numbers,"%lf",static_var);
	SUX = *static_var;
#else
    fscanf(random_numbers,"%lf",&SUX);
#endif

        SUMX=0.0;
        SUMY=0.0;
        SUMZ=0.0;

        Part_per_box = NMOL / (BOX_PER_SIDE * BOX_PER_SIDE * BOX_PER_SIDE);
        Unassigned = NMOL - (Part_per_box * BOX_PER_SIDE * BOX_PER_SIDE * BOX_PER_SIDE);
        printf("Part_per_box = %ld, BOX_PER_SIDE = %ld, Unassigned = %ld\n",Part_per_box, BOX_PER_SIDE, Unassigned);
        for (i = 0; i < BOX_PER_SIDE; i++)
            for (j = 0; j < BOX_PER_SIDE; j++)
                for (k = 0; k < BOX_PER_SIDE; k++)
                    for (m = 0; m < Part_per_box; m++) {
                        link_ptr = (struct link *) G_MALLOC(sizeof(link_type));
                        link_ptr->mol.F[DISP][XDIR][O] = xrand(BOX_LENGTH * i, BOX_LENGTH * (i+1));
                        link_ptr->mol.F[DISP][XDIR][H1] = link_ptr->mol.F[DISP][XDIR][O] + WCOS;
                        link_ptr->mol.F[DISP][XDIR][H2] = link_ptr->mol.F[DISP][XDIR][H1];
                        link_ptr->mol.F[DISP][YDIR][O] = xrand(BOX_LENGTH * j, BOX_LENGTH * (j+1));
                        link_ptr->mol.F[DISP][YDIR][H1] = link_ptr->mol.F[DISP][YDIR][O] + WSIN;
                        link_ptr->mol.F[DISP][YDIR][H2] = link_ptr->mol.F[DISP][YDIR][O] - WSIN;
                        link_ptr->mol.F[DISP][ZDIR][O] = xrand(BOX_LENGTH * k, BOX_LENGTH * (k+1));
                        link_ptr->mol.F[DISP][ZDIR][H1] = link_ptr->mol.F[DISP][ZDIR][O];
                        link_ptr->mol.F[DISP][ZDIR][H2] = link_ptr->mol.F[DISP][ZDIR][O];

                        for (atom = 0; atom < NATOMS; atom++) {
                            /* read random velocities from file random.in */
#ifndef SIM_SOCLIB
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][XDIR][atom]);
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][YDIR][atom]);
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][ZDIR][atom]);
#else
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][XDIR][atom] = *static_var;
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][YDIR][atom] = *static_var;
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][ZDIR][atom] = *static_var;
#endif
                            SUMX = SUMX + link_ptr->mol.F[VEL][XDIR][atom];
                            SUMY = SUMY + link_ptr->mol.F[VEL][YDIR][atom];
                            SUMZ = SUMZ + link_ptr->mol.F[VEL][ZDIR][atom];
                            /* set acceleration and all higher-order derivatives to zero */
                            for (deriv = ACC; deriv < MAXODR; deriv++) {
                                link_ptr->mol.F[deriv][XDIR][atom] = 0.0;
                                link_ptr->mol.F[deriv][YDIR][atom] = 0.0;
                                link_ptr->mol.F[deriv][ZDIR][atom] = 0.0;
                            }
                        }

                        link_ptr->next_mol = NULL;        /* Terminating link */

                        /* update box indices in all three dimensions */
                        X_INDEX = (long) (link_ptr->mol.F[DISP][XDIR][O]/BOX_LENGTH);
                        Y_INDEX = (long) (link_ptr->mol.F[DISP][YDIR][O]/BOX_LENGTH);
                        Z_INDEX = (long) (link_ptr->mol.F[DISP][ZDIR][O]/BOX_LENGTH);

                        /* Put X_, Y_, and Z_INDEX back in box */

                        if (X_INDEX >=BOX_PER_SIDE) X_INDEX -= 1;
                        if (Y_INDEX >=BOX_PER_SIDE) Y_INDEX -= 1;
                        if (Z_INDEX >=BOX_PER_SIDE) Z_INDEX -= 1;

                        /* get list ptr */
                        curr_ptr = BOX[X_INDEX][Y_INDEX][Z_INDEX].list;

                        if (curr_ptr == NULL) {             /* No links in box yet */
                            BOX[X_INDEX][Y_INDEX][Z_INDEX].list = link_ptr;
                        } else {
                            while (curr_ptr) {               /* Scan to end of list */
                                last_ptr = curr_ptr;
                                curr_ptr = curr_ptr->next_mol;
                            } /* while curr_ptr */
                            last_ptr->next_mol = link_ptr;    /* Add to end of list */
                        } /* if curr_ptr */
                    }

        /* distribute the unassigned molecules evenly among processors */
        pid = 0;
        for (i = 0; i < Unassigned; i++) {
            link_ptr = (struct link *) G_MALLOC(sizeof(link_type));
            link_ptr->mol.F[DISP][XDIR][O] = xrand(BOX_LENGTH * start_end[pid]->box[XDIR][FIRST], BOX_LENGTH * (start_end[pid]->box[XDIR][LAST] + 1));
            link_ptr->mol.F[DISP][XDIR][H1] = link_ptr->mol.F[DISP][XDIR][O] + WCOS;
            link_ptr->mol.F[DISP][XDIR][H2] = link_ptr->mol.F[DISP][XDIR][H1];
            link_ptr->mol.F[DISP][YDIR][O] = xrand(BOX_LENGTH * start_end[pid]->box[YDIR][FIRST], BOX_LENGTH * (start_end[pid]->box[YDIR][LAST] + 1));
            link_ptr->mol.F[DISP][YDIR][H1] = link_ptr->mol.F[DISP][YDIR][O] + WSIN;
            link_ptr->mol.F[DISP][YDIR][H2] = link_ptr->mol.F[DISP][YDIR][O] - WSIN;
            link_ptr->mol.F[DISP][ZDIR][O] = xrand(BOX_LENGTH * start_end[pid]->box[ZDIR][FIRST], BOX_LENGTH * (start_end[pid]->box[ZDIR][LAST] + 1));
            link_ptr->mol.F[DISP][ZDIR][H1] = link_ptr->mol.F[DISP][ZDIR][O];
            link_ptr->mol.F[DISP][ZDIR][H2] = link_ptr->mol.F[DISP][ZDIR][O];

            pid = (pid + 1) % NumProcs;

            /* read random velocities from file random.in */
            for (atom = 0; atom < NATOMS; atom++) {
#ifndef SIM_SOCLIB
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][XDIR][atom]);
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][YDIR][atom]);
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][ZDIR][atom]);
#else
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][XDIR][atom] = *static_var;
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][YDIR][atom] = *static_var;
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][ZDIR][atom] = *static_var;
#endif
                SUMX = SUMX + link_ptr->mol.F[VEL][XDIR][atom];
                SUMY = SUMY + link_ptr->mol.F[VEL][YDIR][atom];
                SUMZ = SUMZ + link_ptr->mol.F[VEL][ZDIR][atom];
                /* set acceleration and all higher derivatives to zero */
                for (deriv = ACC; deriv < MAXODR; deriv++) {
                    link_ptr->mol.F[deriv][XDIR][atom] = 0.0;
                    link_ptr->mol.F[deriv][YDIR][atom] = 0.0;
                    link_ptr->mol.F[deriv][ZDIR][atom] = 0.0;
                }
            }

            link_ptr->next_mol = NULL;        /* Terminating link */

            /* updated box indices in all dimensions */

            X_INDEX = (long) (link_ptr->mol.F[DISP][XDIR][O]/BOX_LENGTH);
            Y_INDEX = (long) (link_ptr->mol.F[DISP][YDIR][O]/BOX_LENGTH);
            Z_INDEX = (long) (link_ptr->mol.F[DISP][ZDIR][O]/BOX_LENGTH);

            /* Put X_, Y_, and Z_INDEX back in box */

            if (X_INDEX >=BOX_PER_SIDE) X_INDEX -= 1;
            if (Y_INDEX >=BOX_PER_SIDE) Y_INDEX -= 1;
            if (Z_INDEX >=BOX_PER_SIDE) Z_INDEX -= 1;

            /* get list ptr */
            curr_ptr = BOX[X_INDEX][Y_INDEX][Z_INDEX].list;

            if (curr_ptr == NULL) {             /* No links in box yet */
                BOX[X_INDEX][Y_INDEX][Z_INDEX].list = link_ptr;
            } else {
                while (curr_ptr) {               /* Scan to end of list */
                    last_ptr = curr_ptr;
                    curr_ptr = curr_ptr->next_mol;
                } /* while curr_ptr */
                last_ptr->next_mol = link_ptr;    /* Add to end of list */
            } /* if curr_ptr */
        }

#else
        /* not random initial placement, but rather along a regular
           lattice.  This is the default and the prefered initialization
           since random does not necessarily make sense from the viewpoint
           of preserving bond distances */

        fprintf(six, "***** NEW RUN STARTING FROM REGULAR LATTICE *****\n");
        fflush(six);
        XT[2] = ZERO;
        mol = 0;
#ifdef SIM_SOCLIB
    fscanf(random_numbers,"%lf",static_var);
	SUX = *static_var;
#else
    fscanf(random_numbers,"%lf",&SUX);
#endif

        SUMX=0.0;
        SUMY=0.0;
        SUMZ=0.0;

        /* Generate displacements along a regular lattice */

        for (i=0; i < NS; i++) {
            XT[1]=XT[2]+WCOS;
            XT[3]=XT[1];
            YT[2]=ZERO;
            for (j=0; j < NS; j+=1) {
                YT[1]=YT[2]+WSIN;
                YT[3]=YT[2]-WSIN;
                Z=ZERO;
                for (k = 0; k < NS; k++) {
                    link_ptr = (struct link *) G_MALLOC(sizeof(link_type));
                    for (atom = 0; atom < NATOMS; atom++) {

                        /* displacements for atom */
                        link_ptr->mol.F[DISP][XDIR][atom] = XT[atom+1];
                        link_ptr->mol.F[DISP][YDIR][atom] = YT[atom+1];
                        link_ptr->mol.F[DISP][ZDIR][atom] = Z;

#ifndef SIM_SOCLIB
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][XDIR][atom]);
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][YDIR][atom]);
			fscanf(random_numbers,"%lf",&link_ptr->mol.F[VEL][ZDIR][atom]);
#else
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][XDIR][atom] = *static_var;
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][YDIR][atom] = *static_var;
			fscanf(random_numbers,"%lf",static_var);
			link_ptr->mol.F[VEL][ZDIR][atom] = *static_var;
#endif
                        /* read random velocities from file random.in */
                        SUMX = SUMX + link_ptr->mol.F[VEL][XDIR][atom];
                        SUMY = SUMY + link_ptr->mol.F[VEL][YDIR][atom];
                        SUMZ = SUMZ + link_ptr->mol.F[VEL][ZDIR][atom];
                        for (deriv = ACC; deriv < MAXODR; deriv++) {
                            link_ptr->mol.F[deriv][XDIR][atom] = 0.0;
                            link_ptr->mol.F[deriv][YDIR][atom] = 0.0;
                            link_ptr->mol.F[deriv][ZDIR][atom] = 0.0;
                        }
                    }

                    link_ptr->next_mol = NULL;        /* Terminating link */
                    mol++;
                    Z += XS;

                    /* update box numbers in all dimensions */

                    X_INDEX = (long) (link_ptr->mol.F[DISP][XDIR][O]/BOX_LENGTH);
                    Y_INDEX = (long) (link_ptr->mol.F[DISP][YDIR][O]/BOX_LENGTH);
                    Z_INDEX = (long) (link_ptr->mol.F[DISP][ZDIR][O]/BOX_LENGTH);

                    /* Put X_, Y_, and Z_INDEX back in box */

                    if (X_INDEX >=BOX_PER_SIDE) X_INDEX -= 1;
                    if (Y_INDEX >=BOX_PER_SIDE) Y_INDEX -= 1;
                    if (Z_INDEX >=BOX_PER_SIDE) Z_INDEX -= 1;

                    /* get list ptr */
                    curr_ptr = BOX[X_INDEX][Y_INDEX][Z_INDEX].list;

                    if (curr_ptr == NULL) {             /* No links in box yet */
                        BOX[X_INDEX][Y_INDEX][Z_INDEX].list = link_ptr;
                    } else {
                        while (curr_ptr) {               /* Scan to end of list */
                            last_ptr = curr_ptr;
                            curr_ptr = curr_ptr->next_mol;
                        } /* while curr_ptr */
                        last_ptr->next_mol = link_ptr;    /* Add to end of list */
                    } /* if curr_ptr */

                } /* for k */
                YT[2] += XS;
            } /* for j */
            XT[2] += XS;
        } /* for i */

        if (NMOL != mol) {
            printf("Lattice init error: total mol %ld != NMOL %ld\n", mol, NMOL);
            exit(-1);
        }
#endif
    }
    /* assign random momenta */
    /* find average momenta per atom */

    SUMX=SUMX/(NATOMS*NMOL);
    SUMY=SUMY/(NATOMS*NMOL);
    SUMZ=SUMZ/(NATOMS*NMOL);

    /*  find normalization factor so that <k.e.>=KT/2  */

    SUX=0.0;
    SUY=0.0;
    SUZ=0.0;

    for (i=0; i<BOX_PER_SIDE; i++) {
        for (j=0; j<BOX_PER_SIDE; j++) {
            for (k=0; k<BOX_PER_SIDE; k++) {
                curr_ptr = BOX[i][j][k].list;
                while (curr_ptr) {
                    SUX = SUX +
                        (pow( (curr_ptr->mol.F[VEL][XDIR][H1] - SUMX),2.0)
                         +pow( (curr_ptr->mol.F[VEL][XDIR][H2] - SUMX),2.0))/HMAS
                             +pow( (curr_ptr->mol.F[VEL][XDIR][O]  - SUMX),2.0)/OMAS;

                    SUY = SUY +
                        (pow( (curr_ptr->mol.F[VEL][YDIR][H1] - SUMY),2.0)
                         +pow( (curr_ptr->mol.F[VEL][YDIR][H2] - SUMY),2.0))/HMAS
                             +pow( (curr_ptr->mol.F[VEL][YDIR][O]  - SUMY),2.0)/OMAS;

                    SUZ = SUZ +
                        (pow( (curr_ptr->mol.F[VEL][ZDIR][H1] - SUMZ),2.0)
                         + pow( (curr_ptr->mol.F[VEL][ZDIR][H2] - SUMZ),2.0))/HMAS
                             +pow( (curr_ptr->mol.F[VEL][ZDIR][O]  - SUMZ),2.0)/OMAS;

                    curr_ptr = curr_ptr->next_mol;
                } /* while curr_ptr */
            }
        }
    } /* for boxes */

    FAC=BOLTZ*TEMP*NATMO/UNITM * pow((UNITT*TSTEP/UNITL),2.0);
    SUX=sqrt(FAC/SUX);
    SUY=sqrt(FAC/SUY);
    SUZ=sqrt(FAC/SUZ);

    /* normalize individual velocities so that there are no bulk momenta  */

    XMAS[1]=OMAS;
    for (i=0; i<BOX_PER_SIDE; i++) {
        for (j=0; j<BOX_PER_SIDE; j++) {
            for (k=0; k<BOX_PER_SIDE; k++) {
                curr_ptr = BOX[i][j][k].list;
                while (curr_ptr) {
                    for (atom = 0; atom < NATOMS; atom++) {
                        curr_ptr->mol.F[VEL][XDIR][atom] =
                            ( curr_ptr->mol.F[VEL][XDIR][atom] -
                             SUMX) * SUX/XMAS[atom];
                        curr_ptr->mol.F[VEL][YDIR][atom] =
                            ( curr_ptr->mol.F[VEL][YDIR][atom] -
                             SUMY) * SUY/XMAS[atom];
                        curr_ptr->mol.F[VEL][ZDIR][atom] =
                            ( curr_ptr->mol.F[VEL][ZDIR][atom] -
                             SUMZ) * SUZ/XMAS[atom];
                    } /* for atom */
                    curr_ptr = curr_ptr->next_mol;
                } /* while curr_ptr */
            }
        }
    } /* for box */

#ifdef SIM_SOCLIB
	vfs_component . operation . ioctl (fileno(random_numbers), FD_CLOSE, "random.in", & retval);
	if (retval < 0) printf ("Error closing the video file.\r\n");
    //fclose(random_numbers); avoid a call to an unimplemented function : vfs_lseek
#else
    fclose(random_numbers);
#endif
} /* end of subroutine INITIA */
Esempio n. 6
0
void BLAS_ztrmv_c_testgen(int norm, enum blas_order_type order,
			  enum blas_uplo_type uplo,
			  enum blas_trans_type trans,
			  enum blas_diag_type diag, int n, void *alpha,
			  int alpha_flag, void *T, int ldt, void *x,
			  int *seed, double *head_r_true, double *tail_r_true)

/*
 * Purpose
 * =======
 *
 * Generates alpha, T and x, where T is a triangular matrix; and 
 * computes r_true.
 *
 * Arguments
 * =========
 *
 * norm         (input) blas_norm_type 
 *
 * order        (input) blas_order_type
 *              Order of T; row or column major
 *
 * uplo         (input) blas_uplo_type
 *              Whether T is upper or lower
 *
 * trans        (input) blas_trans_type
 *              No trans, trans, conj trans
 *
 * diag         (input) blas_diag_type
 *              non unit, unit
 *
 * n            (input) int
 *              Dimension of AP and the length of vector x
 *
 * alpha        (input/output) void*
 *              If alpha_flag = 1, alpha is input.
 *              If alpha_flag = 0, alpha is output.
 *
 * alpha_flag   (input) int
 *              = 0 : alpha is free, and is output.
 *              = 1 : alpha is fixed on input.
 *              
 * T            (output) void*
 *
 * x            (input/output) void*
 *
 * seed         (input/output) int
 *
 * head_r_true     (output) double*
 *              The leading part of the truth in double-double.
 *
 * tail_r_true     (output) double*
 *              The trailing part of the truth in double-double.
 *
 */
{
  double *x_i = (double *) x;
  float *T_i = (float *) T;
  double *alpha_i = (double *) alpha;
  double *x_vec;
  float *t_vec;
  double beta[2];
  double r[2];
  double head_r_true_elem[2], tail_r_true_elem[2];
  double x_elem[2];
  float t_elem[2];

  int inc_tvec = 1, inc_xvec = 1;
  int xvec_i, tvec_j;
  int xi;
  int ti, tij;
  int inc_ti, inc_tij;
  int inc_xi;
  int i, j;

  r[0] = r[1] = 0.0;
  beta[0] = beta[1] = 0.0;

  inc_tvec *= 2;
  inc_xvec *= 2;

  t_vec = (float *) blas_malloc(n * sizeof(float) * 2);
  if (n > 0 && t_vec == NULL) {
    BLAS_error("blas_malloc", 0, 0, "malloc failed.\n");
  };
  x_vec = (double *) blas_malloc(n * sizeof(double) * 2);
  if (n > 0 && x_vec == NULL) {
    BLAS_error("blas_malloc", 0, 0, "malloc failed.\n");
  };

  if (trans == blas_no_trans) {
    if (uplo == blas_upper) {
      inc_xi = -1;
      if (order == blas_rowmajor) {
	inc_ti = -ldt;
	inc_tij = -1;
      } else {
	inc_ti = -1;
	inc_tij = -ldt;
      }
    } else {
      inc_xi = 1;
      if (order == blas_rowmajor) {
	inc_ti = ldt;
	inc_tij = 1;
      } else {
	inc_ti = 1;
	inc_tij = ldt;
      }
    }
  } else {
    if (uplo == blas_upper) {
      inc_xi = 1;
      if (order == blas_rowmajor) {
	inc_ti = 1;
	inc_tij = ldt;
      } else {
	inc_ti = ldt;
	inc_tij = 1;
      }
    } else {
      inc_xi = -1;
      if (order == blas_rowmajor) {
	inc_ti = -1;
	inc_tij = -ldt;
      } else {
	inc_ti = -ldt;
	inc_tij = -1;
      }
    }
  }

  inc_xi *= 2;

  inc_ti *= 2;
  inc_tij *= 2;

  /* Call dot_testgen n times.  Each call will generate
   * one row of T and one element of x.                   */
  ti = (inc_ti > 0 ? 0 : -(n - 1) * inc_ti);
  xi = (inc_xi > 0 ? 0 : -(n - 1) * inc_xi);
  xvec_i = 0;
  for (i = 0; i < n; i++) {

    /* Generate the i-th element of x_vec and all of t_vec. */
    if (diag == blas_unit_diag) {
      /* Since we need alpha = beta, we fix alpha if alpha_flag = 0. */
      if (i == 0 && alpha_flag == 0) {
	alpha_i[0] = xrand(seed);
	alpha_i[1] = xrand(seed);
      }
      BLAS_zdot_z_c_testgen(i, 0, i, norm, blas_no_conj, alpha_i,
			    1, alpha_i, 1, x_vec, t_vec,
			    seed, r, head_r_true_elem, tail_r_true_elem);

      /* Copy generated t_vec to T. */
      tvec_j = 0;
      tij = (inc_tij > 0 ? ti : ti - (n - 1) * inc_tij);
      for (j = 0; j < i; j++) {
	t_elem[0] = t_vec[tvec_j];
	t_elem[1] = t_vec[tvec_j + 1];

	if (trans == blas_conj_trans) {
	  t_elem[1] = -t_elem[1];
	}
	T_i[tij] = t_elem[0];
	T_i[tij + 1] = t_elem[1];
	tvec_j += inc_tvec;
	tij += inc_tij;
      }

      /* Set the diagonal element to 1. */
      t_elem[0] = 1.0;
      t_elem[1] = 0.0;
      T_i[tij] = t_elem[0];
      T_i[tij + 1] = t_elem[1];

      /* Set x[i] to be r. */
      x_i[xi] = r[0];
      x_i[xi + 1] = r[1];
      x_vec[xvec_i] = r[0];
      x_vec[xvec_i + 1] = r[1];

    } else {
      BLAS_zdot_z_c_testgen(i + 1, 0, i, norm, blas_no_conj, alpha,
			    (i == 0 ? alpha_flag : 1), beta, 1, x_vec, t_vec,
			    seed, r, head_r_true_elem, tail_r_true_elem);

      /* Copy generated t_vec to T. */
      tvec_j = 0;
      tij = (inc_tij > 0 ? ti : ti - (n - 1) * inc_tij);
      for (j = 0; j <= i; j++) {
	t_elem[0] = t_vec[tvec_j];
	t_elem[1] = t_vec[tvec_j + 1];

	if (trans == blas_conj_trans) {
	  t_elem[1] = -t_elem[1];
	}
	T_i[tij] = t_elem[0];
	T_i[tij + 1] = t_elem[1];
	tvec_j += inc_tvec;
	tij += inc_tij;
      }

      /* Copy generated x_vec[i] to appropriate position in x. */
      x_elem[0] = x_vec[xvec_i];
      x_elem[1] = x_vec[xvec_i + 1];
      x_i[xi] = x_elem[0];
      x_i[xi + 1] = x_elem[1];
    }

    /* Copy r_true */
    head_r_true[xi] = head_r_true_elem[0];
    head_r_true[xi + 1] = head_r_true_elem[1];
    tail_r_true[xi] = tail_r_true_elem[0];
    tail_r_true[xi + 1] = tail_r_true_elem[1];

    xvec_i += inc_xvec;
    xi += inc_xi;

    ti += inc_ti;
  }

  blas_free(x_vec);
  blas_free(t_vec);
}
Esempio n. 7
0
static double random_raw(void)
{
	return xrand();
}
Esempio n. 8
0
void Host_Main(void)
{
	double time1 = 0;
	double time2 = 0;
	double time3 = 0;
	double cl_timer = 0, sv_timer = 0;
	double clframetime, deltacleantime, olddirtytime, dirtytime;
	double wait;
	int pass1, pass2, pass3, i;
	char vabuf[1024];
	qboolean playing;

	Host_Init();

	realtime = 0;
	host_dirtytime = Sys_DirtyTime();
	for (;;)
	{
		if (setjmp(host_abortframe))
		{
			SCR_ClearLoadingScreen(false);
			continue;			// something bad happened, or the server disconnected
		}

		olddirtytime = host_dirtytime;
		dirtytime = Sys_DirtyTime();
		deltacleantime = dirtytime - olddirtytime;
		if (deltacleantime < 0)
		{
			// warn if it's significant
			if (deltacleantime < -0.01)
				Con_Printf("Host_Mingled: time stepped backwards (went from %f to %f, difference %f)\n", olddirtytime, dirtytime, deltacleantime);
			deltacleantime = 0;
		}
		else if (deltacleantime >= 1800)
		{
			Con_Printf("Host_Mingled: time stepped forward (went from %f to %f, difference %f)\n", olddirtytime, dirtytime, deltacleantime);
			deltacleantime = 0;
		}
		realtime += deltacleantime;
		host_dirtytime = dirtytime;

		cl_timer += deltacleantime;
		sv_timer += deltacleantime;

		if (!svs.threaded)
		{
			svs.perf_acc_realtime += deltacleantime;

			// Look for clients who have spawned
			playing = false;
			for (i = 0, host_client = svs.clients;i < svs.maxclients;i++, host_client++)
				if(host_client->begun)
					if(host_client->netconnection)
						playing = true;
			if(sv.time < 10)
			{
				// don't accumulate time for the first 10 seconds of a match
				// so things can settle
				svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
			}
			else if(svs.perf_acc_realtime > 5)
			{
				svs.perf_cpuload = 1 - svs.perf_acc_sleeptime / svs.perf_acc_realtime;
				svs.perf_lost = svs.perf_acc_lost / svs.perf_acc_realtime;
				if(svs.perf_acc_offset_samples > 0)
				{
					svs.perf_offset_max = svs.perf_acc_offset_max;
					svs.perf_offset_avg = svs.perf_acc_offset / svs.perf_acc_offset_samples;
					svs.perf_offset_sdev = sqrt(svs.perf_acc_offset_squared / svs.perf_acc_offset_samples - svs.perf_offset_avg * svs.perf_offset_avg);
				}
				if(svs.perf_lost > 0 && developer_extra.integer)
					if(playing) // only complain if anyone is looking
						Con_DPrintf("Server can't keep up: %s\n", Host_TimingReport(vabuf, sizeof(vabuf)));
				svs.perf_acc_realtime = svs.perf_acc_sleeptime = svs.perf_acc_lost = svs.perf_acc_offset = svs.perf_acc_offset_squared = svs.perf_acc_offset_max = svs.perf_acc_offset_samples = 0;
			}
		}

		if (slowmo.value < 0.00001 && slowmo.value != 0)
			Cvar_SetValue("slowmo", 0);
		if (host_framerate.value < 0.00001 && host_framerate.value != 0)
			Cvar_SetValue("host_framerate", 0);

		// keep the random time dependent, but not when playing demos/benchmarking
		if(!*sv_random_seed.string && !cls.demoplayback) {
			xrand();
            rand();
        }

		// get new key events
		Key_EventQueue_Unblock();
		SndSys_SendKeyEvents();
		Sys_SendKeyEvents();

		NetConn_UpdateSockets();

		Log_DestBuffer_Flush();

		// receive packets on each main loop iteration, as the main loop may
		// be undersleeping due to select() detecting a new packet
		if (sv.active && !svs.threaded)
			NetConn_ServerFrame();

		Curl_Run();

		// check for commands typed to the host
		Host_GetConsoleCommands();

		// when a server is running we only execute console commands on server frames
		// (this mainly allows frikbot .way config files to work properly by staying in sync with the server qc)
		// otherwise we execute them on client frames
		if (sv.active ? sv_timer > 0 : cl_timer > 0)
		{
			// process console commands
//			R_TimeReport("preconsole");
			CL_VM_PreventInformationLeaks();
			Cbuf_Frame();
//			R_TimeReport("console");
		}

		//Con_Printf("%6.0f %6.0f\n", cl_timer * 1000000.0, sv_timer * 1000000.0);

		// if the accumulators haven't become positive yet, wait a while
		if (cls.state == ca_dedicated)
			wait = sv_timer * -1000000.0;
		else if (!sv.active || svs.threaded)
			wait = cl_timer * -1000000.0;
		else
			wait = max(cl_timer, sv_timer) * -1000000.0;

		if (!cls.timedemo && wait >= 1)
		{
			double time0, delta;

			if(host_maxwait.value <= 0)
				wait = min(wait, 1000000.0);
			else
				wait = min(wait, host_maxwait.value * 1000.0);
			if(wait < 1)
				wait = 1; // because we cast to int

			time0 = Sys_DirtyTime();
			if (sv_checkforpacketsduringsleep.integer && !sys_usenoclockbutbenchmark.integer && !svs.threaded) {
				NetConn_SleepMicroseconds((int)wait);
				if (cls.state != ca_dedicated)
					NetConn_ClientFrame(); // helps server browser get good ping values
				// TODO can we do the same for ServerFrame? Probably not.
			}
			else
				Sys_Sleep((int)wait);
			delta = Sys_DirtyTime() - time0;
			if (delta < 0 || delta >= 1800) delta = 0;
			if (!svs.threaded)
				svs.perf_acc_sleeptime += delta;
//			R_TimeReport("sleep");
			continue;
		}

		// limit the frametime steps to no more than 100ms each
		if (cl_timer > 0.1)
			cl_timer = 0.1;
		if (sv_timer > 0.1)
		{
			if (!svs.threaded)
				svs.perf_acc_lost += (sv_timer - 0.1);
			sv_timer = 0.1;
		}

		R_TimeReport("---");

	//-------------------
	//
	// server operations
	//
	//-------------------

		// limit the frametime steps to no more than 100ms each
		if (sv.active && sv_timer > 0 && !svs.threaded)
		{
			// execute one or more server frames, with an upper limit on how much
			// execution time to spend on server frames to avoid freezing the game if
			// the server is overloaded, this execution time limit means the game will
			// slow down if the server is taking too long.
			int framecount, framelimit = 1;
			double advancetime, aborttime = 0;
			float offset;
			prvm_prog_t *prog = SVVM_prog;

			// run the world state
			// don't allow simulation to run too fast or too slow or logic glitches can occur

			// stop running server frames if the wall time reaches this value
			if (sys_ticrate.value <= 0)
				advancetime = sv_timer;
			else if (cl.islocalgame && !sv_fixedframeratesingleplayer.integer)
			{
				// synchronize to the client frametime, but no less than 10ms and no more than 100ms
				advancetime = bound(0.01, cl_timer, 0.1);
			}
			else
			{
				advancetime = sys_ticrate.value;
				// listen servers can run multiple server frames per client frame
				framelimit = cl_maxphysicsframesperserverframe.integer;
				aborttime = Sys_DirtyTime() + 0.1;
			}
			if(slowmo.value > 0 && slowmo.value < 1)
				advancetime = min(advancetime, 0.1 / slowmo.value);
			else
				advancetime = min(advancetime, 0.1);

			if(advancetime > 0)
			{
				offset = Sys_DirtyTime() - dirtytime;if (offset < 0 || offset >= 1800) offset = 0;
				offset += sv_timer;
				++svs.perf_acc_offset_samples;
				svs.perf_acc_offset += offset;
				svs.perf_acc_offset_squared += offset * offset;
				if(svs.perf_acc_offset_max < offset)
					svs.perf_acc_offset_max = offset;
			}

			// only advance time if not paused
			// the game also pauses in singleplayer when menu or console is used
			sv.frametime = advancetime * slowmo.value;
			if (host_framerate.value)
				sv.frametime = host_framerate.value;
			if (sv.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
				sv.frametime = 0;

			for (framecount = 0;framecount < framelimit && sv_timer > 0;framecount++)
			{
				sv_timer -= advancetime;

				// move things around and think unless paused
				if (sv.frametime)
					SV_Physics();

				// if this server frame took too long, break out of the loop
				if (framelimit > 1 && Sys_DirtyTime() >= aborttime)
					break;
			}
			R_TimeReport("serverphysics");

			// send all messages to the clients
			SV_SendClientMessages();

			if (sv.paused == 1 && realtime > sv.pausedstart && sv.pausedstart > 0) {
				prog->globals.fp[OFS_PARM0] = realtime - sv.pausedstart;
				PRVM_serverglobalfloat(time) = sv.time;
				prog->ExecuteProgram(prog, PRVM_serverfunction(SV_PausedTic), "QC function SV_PausedTic is missing");
			}

			// send an heartbeat if enough time has passed since the last one
			NetConn_Heartbeat(0);
			R_TimeReport("servernetwork");
		}
		else if (!svs.threaded)
		{
			// don't let r_speeds display jump around
			R_TimeReport("serverphysics");
			R_TimeReport("servernetwork");
		}

	//-------------------
	//
	// client operations
	//
	//-------------------

		if (cls.state != ca_dedicated && (cl_timer > 0 || cls.timedemo || ((vid_activewindow ? cl_maxfps : cl_maxidlefps).value < 1)))
		{
            if(cls.td_frames < -2 || cls.td_frames > 0) {
                TimeDemo_BeginFrame(&tdstats);
            }
			R_TimeReport("---");
			Collision_Cache_NewFrame();
			R_TimeReport("photoncache");
			// decide the simulation time
			if (cls.capturevideo.active)
			{
				//***
				if (cls.capturevideo.realtime)
					clframetime = cl.realframetime = max(cl_timer, 1.0 / cls.capturevideo.framerate);
				else
				{
					clframetime = 1.0 / cls.capturevideo.framerate;
					cl.realframetime = max(cl_timer, clframetime);
				}
			}
			else if (vid_activewindow && cl_maxfps.value >= 1 && !cls.timedemo)
			{
				clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxfps.value);
				// when running slow, we need to sleep to keep input responsive
				wait = bound(0, cl_maxfps_alwayssleep.value * 1000, 100000);
				if (wait > 0)
					Sys_Sleep((int)wait);
			}
			else if (!vid_activewindow && cl_maxidlefps.value >= 1 && !cls.timedemo)
				clframetime = cl.realframetime = max(cl_timer, 1.0 / cl_maxidlefps.value);
			else
				clframetime = cl.realframetime = cl_timer;

			// apply slowmo scaling
			clframetime *= cl.movevars_timescale;
			// scale playback speed of demos by slowmo cvar
			if (cls.demoplayback)
			{
				clframetime *= slowmo.value;
				// if demo playback is paused, don't advance time at all
				if (cls.demopaused)
					clframetime = 0;
			}
			else
			{
				// host_framerate overrides all else
				if (host_framerate.value)
					clframetime = host_framerate.value;

				if (cl.paused || (cl.islocalgame && (key_dest != key_game || key_consoleactive || cl.csqc_paused)))
					clframetime = 0;
			}

			if (cls.timedemo)
				clframetime = cl.realframetime = cl_timer;

			// deduct the frame time from the accumulator
			cl_timer -= cl.realframetime;

			cl.oldtime = cl.time;
			cl.time += clframetime;

			// update video
			if (host_speeds.integer)
				time1 = Sys_DirtyTime();
			R_TimeReport("pre-input");

			// Collect input into cmd
			CL_Input();

			R_TimeReport("input");

			// check for new packets
			NetConn_ClientFrame();

			// read a new frame from a demo if needed
			CL_ReadDemoMessage();
			R_TimeReport("clientnetwork");

			// now that packets have been read, send input to server
			CL_SendMove();
			R_TimeReport("sendmove");

			// update client world (interpolate entities, create trails, etc)
			CL_UpdateWorld();
			R_TimeReport("lerpworld");

			CL_Video_Frame();

			R_TimeReport("client");

			CL_UpdateScreen();
			R_TimeReport("render");

			if (host_speeds.integer)
				time2 = Sys_DirtyTime();

			// update audio
			if(cl.csqc_usecsqclistener)
			{
				S_Update(&cl.csqc_listenermatrix);
				cl.csqc_usecsqclistener = false;
			}
			else
				S_Update(&r_refdef.view.matrix);

#ifdef CONFIG_CD
			CDAudio_Update();
			R_TimeReport("audio");
#endif

			// reset gathering of mouse input
			in_mouse_x = in_mouse_y = 0;

            if(cls.td_frames < -2 || cls.td_frames > 0) {
                TimeDemo_EndFrame(&tdstats);
            }
			if (host_speeds.integer)
			{
				pass1 = (int)((time1 - time3)*1000000);
				time3 = Sys_DirtyTime();
				pass2 = (int)((time2 - time1)*1000000);
				pass3 = (int)((time3 - time2)*1000000);
				Con_Printf("%6ius total %6ius server %6ius gfx %6ius snd\n",
							pass1+pass2+pass3, pass1, pass2, pass3);
			}
		}

#if MEMPARANOIA
		Mem_CheckSentinelsGlobal();
#else
		if (developer_memorydebug.integer)
			Mem_CheckSentinelsGlobal();
#endif

		// if there is some time remaining from this frame, reset the timers
		if (cl_timer >= 0)
			cl_timer = 0;
		if (sv_timer >= 0)
		{
			if (!svs.threaded)
				svs.perf_acc_lost += sv_timer;
			sv_timer = 0;
		}

        IRC_Frame();

		host_framecount++;
	}
}
Esempio n. 9
0
void creatures::animate()
{
	ui::frame* f;
	int ml = get(LastValid);
	unsigned tm = (unsigned)timeticks();
	for(int mid = FirstCreature; mid<=ml; mid++)
	{
		if(creatures::get(mid, AnimationStop)>0)
		{
			creatures::set(mid, AnimationStop, creatures::get(mid, AnimationStop) - 1);
			continue;
		}
		res::token rs = (res::token)creatures::get(mid, Frame);
		int ac = creatures::get(mid, AnimationCicle);
		int fr = creatures::get(mid, AnimationFrame);
		int dr = creatures::get(mid, Direction);
		int fc = res::gframes(rs, ac) / 6;
		int x1 = creatures::get(mid, PositionX);
		int y1 = creatures::get(mid, PositionY);
		int p2, p3, x3, y3;
		switch(creatures::get(mid, Action))
		{
		case ActionWalk:
			if((hot::frame%2)==0)
				break;
		case ActionRun:
			f = ui::gframe(rs, ac, dr*fc + fr);
			x1 += f->mx; y1 += f->my;
			creatures::set(mid, PositionX, x1);
			creatures::set(mid, PositionY, y1);
			p3 = creatures::get(mid, Position);
			x3 = map::h2x(p3);
			y3 = map::h2y(p3);
			p2 = creatures::get(mid, Order);
			if(iabs(x3-x1)<=6 && iabs(y3-y1)<=6)
			{
				if(p2==p3)
				{
					creatures::set(mid, Action, ActionStand);
					creatures::set(mid, Position, p3);
					break;
				}
				else
					creatures::set(mid, Direction, map::d2o(map::direction(p3, p2)));
			}
			creatures::set(mid, AnimationFrame, (++fr)%fc);
			break;
		case ActionStand:
			if((hot::frame%2)==0)
				break;
			if(++fr>=fc)
			{
				creatures::set(mid, AnimationFrame, 0);
				creatures::set(mid, AnimationStop, (1+(xrand()%8))*12);
			}
			else
				creatures::set(mid, AnimationFrame, fr);
			break;
		}
	}
}